NewtonMesh* MakeViualMesh::CreateVisualMesh (NewtonBody* const body, char* const name, int maxNameSize) const
{
	// here the use should take the user data from the body create newtonMesh form it and return that back
	NewtonCollision* const collision = NewtonBodyGetCollision(body);
	NewtonMesh* const mesh = NewtonMeshCreateFromCollision(collision);
	sprintf (name, "visual Mesh");
	return mesh;
}
dPluginScene* dMeshBoxPrimitive::Create (dPluginInterface* const interface)
{
	dPluginScene* const scene = interface->GetScene();
	NewtonWorld* const world = scene->GetNewtonWorld();
	wxFrame* const mainWindow = (wxFrame*) NewtonWorldGetUserData(world);
	dBoxPrimitiveUI modaldialog(mainWindow);

	dPluginScene* asset = NULL;

//	if (modaldialog.execute(PLACEMENT_OWNER)) {
	if (1) {
		// for now asset manage does not have undo/redo
		//interface->Push (new dUndoCurrentAsset(scene));

		asset = new dPluginScene(world);
		//double x = atof (modaldialog.m_x->getText().text());
		//double y = atof (modaldialog.m_y->getText().text());
		//double z = atof (modaldialog.m_z->getText().text());

		double x = modaldialog.m_sizeX;
		double y = modaldialog.m_sizeY;
		double z = modaldialog.m_sizeZ;

//		dPluginScene::dTreeNode* const root = asset->GetRoot();
//		dNodeInfo* const rootInfo = asset->GetInfoFromNode(root);
//		rootInfo->SetName(modaldialog.m_name.c_str());		

		dPluginScene::dTreeNode* const sceneNode = asset->CreateSceneNode(asset->GetRoot());
		dSceneModelInfo* const sceneNodeInfo = (dSceneModelInfo*) asset->GetInfoFromNode(sceneNode);
		sceneNodeInfo->SetName("box_node");

		dPluginScene::dTreeNode* const boxMesh = asset->CreateMeshNode(sceneNode);
		dMeshNodeInfo* const instance = (dMeshNodeInfo*) asset->GetInfoFromNode(boxMesh);
		instance->SetName("box");

		NewtonCollision* const boxCollision = NewtonCreateBox (world, float (x), float (y), float (z), 0, NULL); 
		NewtonMesh* const mesh = NewtonMeshCreateFromCollision(boxCollision);
		NewtonDestroyCollision(boxCollision);
		instance->ReplaceMesh (mesh);

//		char name[256];
//		sprintf (name, "%s_mesh", parent->GetName());
//		instance->SetName(name);
	}

	return asset;
}
	static void AddFracturedPrimitive(DemoEntityManager* const scene, dFloat mass, const dVector& origin, const dVector& size, int xCount, int zCount, dFloat spacing, PrimitiveType type, int materialID, const dMatrix& shapeOffsetMatrix)
	{
		// create the shape and visual mesh as a common data to be re used
		NewtonWorld* const world = scene->GetNewton();
		NewtonCollision* const collision = CreateConvexCollision(world, shapeOffsetMatrix, size, type, materialID);

		// create a newton mesh from the collision primitive
		NewtonMesh* const mesh = NewtonMeshCreateFromCollision(collision);

		// apply a material map
		int externalMaterial = LoadTexture("reljef.tga");
		//int internalMaterial = LoadTexture("KAMEN-stup.tga");
		int internalMaterial = LoadTexture("concreteBrick.tga");

		dMatrix aligmentUV(dGetIdentityMatrix());
		NewtonMeshApplyBoxMapping(mesh, externalMaterial, externalMaterial, externalMaterial, &aligmentUV[0][0]);

		// create a newton mesh from the collision primitive
		VoronoidEffect fracture(world, mesh, internalMaterial);

		DemoMesh* const visualMesh = new DemoMesh(mesh);

		dFloat startElevation = 100.0f;
		dMatrix matrix(dGetIdentityMatrix());
		for (int i = 0; i < xCount; i++) {
			dFloat x = origin.m_x + (i - xCount / 2) * spacing;
			for (int j = 0; j < zCount; j++) {
				dFloat z = origin.m_z + (j - zCount / 2) * spacing;

				matrix.m_posit.m_x = x;
				matrix.m_posit.m_z = z;
				dVector floor(FindFloor(world, dVector(matrix.m_posit.m_x, startElevation, matrix.m_posit.m_z, 0.0f), 2.0f * startElevation));
				matrix.m_posit.m_y = floor.m_y + 1.0f;
				SimpleFracturedEffectEntity::AddFracturedEntity(scene, visualMesh, collision, fracture, matrix.m_posit);
			}
		}

		// do not forget to release the assets	
		NewtonMeshDestroy(mesh);
		visualMesh->Release();
		NewtonDestroyCollision(collision);
	}
static void AddShatterPrimitive (DemoEntityManager* const scene, dFloat mass, const dVector& origin, const dVector& size, int xCount, int zCount, dFloat spacing, PrimitiveType type, int materialID)
{
	dMatrix matrix (GetIdentityMatrix());

	// create the shape and visual mesh as a common data to be re used
	NewtonWorld* const world = scene->GetNewton();
	NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, type, materialID);


	// create a newton mesh from the collision primitive
	NewtonMesh* const mesh = NewtonMeshCreateFromCollision(collision);

	// apply a material map
	int externalMaterial = LoadTexture("reljef.tga");
	int internalMaterial = LoadTexture("KAMEN-stup.tga");
	NewtonMeshApplyBoxMapping(mesh, externalMaterial, externalMaterial, externalMaterial);

	// create a newton mesh from the collision primitive
	ShatterEffect shatter (world, mesh, internalMaterial);

	DemoMesh* const visualMesh = new DemoMesh(mesh);

	for (int i = 0; i < xCount; i ++) {
		dFloat x = origin.m_x + (i - xCount / 2) * spacing;
		for (int j = 0; j < zCount; j ++) {
			dFloat z = origin.m_z + (j - zCount / 2) * spacing;

			matrix.m_posit.m_x = x;
			matrix.m_posit.m_z = z;
			matrix.m_posit.m_y = FindFloor (world, x, z) + 4.0f;
			AddShatterEntity (scene, visualMesh, collision, shatter, matrix.m_posit);
		}
	}


	// do not forget to release the assets	
	NewtonMeshDestroy (mesh);
	visualMesh->Release(); 
	NewtonReleaseCollision(world, collision);

}
	void CreateTetrahedraPrimitive(DemoEntityManager* const scene, int materialID)
	{
		dFloat mass = 5.0f;
		dVector size (1.0f);

		NewtonWorld* const world = scene->GetNewton();
		NewtonCollision* const primitiveShape = CreateConvexCollision (world, dGetIdentityMatrix(), size, _SPHERE_PRIMITIVE, materialID);
		//NewtonCollision* const primitiveShape = CreateConvexCollision (world, dGetIdentityMatrix(), size, _BOX_PRIMITIVE, materialID);
		NewtonMesh* const skinMesh = NewtonMeshCreateFromCollision(primitiveShape);

		dMatrix aligmentUV(dGetIdentityMatrix());
		int material = LoadTexture("smilli.tga");
		NewtonMeshApplySphericalMapping(skinMesh, material, &aligmentUV[0][0]);

		// now now make an tetrahedra iso surface approximation of this mesh
		NewtonMesh* const tetraIsoSurface = NewtonMeshCreateTetrahedraIsoSurface(skinMesh);

		// calculate the linear blend weight for the tetrahedra mesh
		NewtonCreateTetrahedraLinearBlendSkinWeightsChannel (tetraIsoSurface, skinMesh);
		NewtonDestroyCollision(primitiveShape);

		// make a deformable collision mesh
		NewtonCollision* const deformableCollision = NewtonCreateDeformableSolid(world, tetraIsoSurface, materialID);

		//create a rigid body with a deformable mesh
		m_body = CreateRigidBody(scene, mass, deformableCollision);

		// create the soft body mesh
		//DemoMesh* const mesh = new TetrahedraSoftMesh(tetraIsoSurface, m_body);
		DemoMesh* const mesh = new LinearBlendMeshTetra(scene, skinMesh, m_body);
		SetMesh(mesh, dGetIdentityMatrix());
		
		// do not forget to destroy this objects, else you get bad memory leaks.
		mesh->Release ();
		NewtonMeshDestroy(skinMesh);
		NewtonDestroyCollision(deformableCollision);
		NewtonMeshDestroy(tetraIsoSurface);
	}
void NewtonImport::BodyDeserialization (NewtonBody* const body, NewtonDeserializeCallback deserializecallback, void* const serializeHandle)
{
#if 0
	//for nwo do not do anything at all;
/*
	int size;
	char bodyIndentification[256];

	deserializecallback (serializeHandle, &size, sizeof (size));
	deserializecallback (serializeHandle, bodyIndentification, size);

	// get the world and the scene form the world user data
	NewtonWorld* const world = NewtonBodyGetWorld(body);

	dScene* const scene = (dScene*)NewtonWorldGetUserData(world);

	// crate a scene node for this body
	dScene::dTreeNode* const scene = scene->CreateSceneNode(scene->GetRootNode());

	// here we attach a visual object to the entity, 
	dMatrix matrix;
	NewtonBodyGetMatrix(body, &matrix[0][0]);

	DemoEntity* const entity = new DemoEntity(matrix, NULL);
	scene->Append (entity);

	NewtonBodySetUserData (body, entity);
	NewtonBodySetTransformCallback(body, DemoEntity::TransformCallback);
	NewtonBodySetForceAndTorqueCallback(body, PhysicsApplyGravityForce);


	//for visual mesh we will collision mesh and convert it to a visual mesh using NewtonMesh 
	NewtonCollision* const collision = NewtonBodyGetCollision(body);
	int collisionID = NewtonCollisionGetType(collision) ;

	DemoMesh* mesh = NULL;
	switch (collisionID) 
	{
	case SERIALIZE_ID_HEIGHTFIELD:
		{
			NewtonCollisionInfoRecord info;
			NewtonCollisionGetInfo(collision, &info);

			const NewtonHeightFieldCollisionParam& heighfield = info.m_heightField;
			mesh = new DemoMesh ("terrain", heighfield.m_elevation, heighfield.m_width, heighfield.m_horizonalScale, 1.0f/16.0f, 128); 
			break;
		}

	default:
		mesh = new DemoMesh("cylinder_1", collision, NULL, NULL, NULL);
		break;
	}

	entity->SetMesh(mesh);
	mesh->Release();
*/


	// search for all collision mesh and create make a dictionary
//	dTree<dSceneNodeCollisionPair, NewtonCollision*> dictionary;

//	int count = 0;
//	dScene::dTreeNode* const materialNode = CreateMaterialNode (GetRootNode(), 0);
//	for (NewtonBody* body = NewtonWorldGetFirstBody(world); body; body = NewtonWorldGetNextBody(world, body)) {
	NewtonCollision* const collision = NewtonBodyGetCollision(body);

//		dTree<dSceneNodeCollisionPair, NewtonCollision*>::dTreeNode* node = dictionary.Find(collision);
//		if (!node) {
//		char meshName[256];
//		sprintf (meshName, "mesh_%d", count);
//		count ++;
//		NewtonMesh* const mesh = visualContext->CreateVisualMesh(body, meshName, sizeof (meshName));
	NewtonMesh* const mesh = NewtonMeshCreateFromCollision(collision);
	dScene::dTreeNode* const meshNode = scene->CreateMeshNode(scene->GetRootNode());
/*
			AddReference(meshNode, materialNode);

			dMeshNodeInfo* const info = (dMeshNodeInfo*)GetInfoFromNode(meshNode);
			info->ReplaceMesh (mesh);
			info->SetName(meshName);

			NewtonCollisionInfoRecord collsionRecord;
			NewtonCollisionGetInfo(collision, &collsionRecord);

			// extract the offset matrix form the collision
			dMatrix& offsetMatrix = *((dMatrix*)&collsionRecord.m_offsetMatrix[0][0]);
			info->BakeTransform (offsetMatrix.Inverse());
			info->SetPivotMatrix(offsetMatrix * info->GetPivotMatrix());

			dScene::dTreeNode* const collisionNode = CreateCollisionFromNewtonCollision(GetRootNode(), collision);

			dSceneNodeCollisionPair pair;
			pair.m_mesh = meshNode;
			pair.m_collision = collisionNode;

			node = dictionary.Insert(pair, collision);
		} 

		// add a visual mesh
		dSceneNodeCollisionPair& info = node->GetInfo();
		dScene::dTreeNode* const sceneNode = CreateSceneNode(GetRootNode());
		dSceneNodeInfo* const sceneInfo = (dSceneNodeInfo*) GetInfoFromNode(sceneNode);
		dMatrix matrix;
		NewtonBodyGetMatrix(body, &matrix[0][0]);
		sceneInfo->SetTransform(matrix);
		AddReference(sceneNode, info.m_mesh);


		// add a rigid body
		dScene::dTreeNode* const sceneBody = CreateRigidbodyNode(sceneNode);
		AddReference(sceneBody, info.m_collision);

		dRigidbodyNodeInfo* const bodyInfo = (dRigidbodyNodeInfo*) GetInfoFromNode(sceneBody);

		dVector com;
		NewtonBodyGetCentreOfMass(body, &com[0]);
		bodyInfo->SetCenterOfMass(com);

		dVector massMatrix;
		NewtonBodyGetMassMatrix(body, &massMatrix.m_w, &massMatrix.m_x, &massMatrix.m_y, &massMatrix.m_z);
		bodyInfo->SetMassMatrix(massMatrix);

		dVector veloc;
		NewtonBodyGetVelocity(body, &veloc[0]);
		bodyInfo->SetVelocity(veloc);

		dVector omega;
		NewtonBodyGetOmega(body, &omega[0]);
		bodyInfo->SetOmega(omega);

		dVariable* var = bodyInfo->CreateVariable ("rigidBodyType");
		var->SetValue("default gravity");
*/
//	}

//	void* nextPtr = NULL;
//	for (void* ptr = GetFirstChild (GetRootNode()); ptr; ptr = nextPtr) {
//		nextPtr = GetNextChild(GetRootNode(), ptr);
//		dScene::dTreeNode* const node = GetNodeFromLink(ptr);
//		dNodeInfo* const info = GetInfoFromNode(node);
//		if ((info->IsType(dMeshNodeInfo::GetRttiType())) || (info->IsType(dCollisionNodeInfo::GetRttiType()))) {
//			RemoveReference(node, GetRootNode());	
//		}
//	}
//	RemoveReference(materialNode, GetRootNode());	
#endif
}
static void CreateSimpleVoronoiShatter (DemoEntityManager* const scene)
{
	// create a collision primitive
//	dVector size (2.0f, 2.0f, 2.0f);
//	dVector size = dVector (10.0f, 0.5f, 10.0f, 0.0f);
	dVector size = dVector (5.0f, 5.0f, 5.0f, 0.0f);
	NewtonWorld* const world = scene->GetNewton();

//	NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _BOX_PRIMITIVE, 0);
	NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _CAPSULE_PRIMITIVE, 0);
//	NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _SPHERE_PRIMITIVE, 0);
//	NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _REGULAR_CONVEX_HULL_PRIMITIVE, 0);
//	NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, _RANDOM_CONVEX_HULL_PRIMITIVE, 0);
	
	

	// create a newton mesh from the collision primitive
	NewtonMesh* const mesh = NewtonMeshCreateFromCollision(collision);

	// apply a simple Box Mapping
	int tex0 = LoadTexture("reljef.tga");
	NewtonMeshApplyBoxMapping(mesh, tex0, tex0, tex0);

	// pepper the bing box of the mesh with random points
	dVector points[NUMBER_OF_ITERNAL_PARTS + 100];
	int count = 0;

	while (count < NUMBER_OF_ITERNAL_PARTS) {
		dFloat x = RandomVariable(size.m_x);
		dFloat y = RandomVariable(size.m_y);
		dFloat z = RandomVariable(size.m_z);
		if ((x <= size.m_x) && (x >= -size.m_x) && (y <= size.m_y) && (y >= -size.m_y) && (z <= size.m_z) && (z >= -size.m_z)){
			points[count] = dVector (x, y, z);
			count ++;
		}
	} 

count = 4;

	// Create the array of convex pieces from the mesh
	int interior = LoadTexture("KAMEN-stup.tga");
//	int interior = LoadTexture("camo.tga");
	dMatrix textureMatrix (GetIdentityMatrix());
	textureMatrix[0][0] = 1.0f / size.m_x;
	textureMatrix[1][1] = 1.0f / size.m_y;
	NewtonMesh* const convexParts = NewtonMeshVoronoiDecomposition (mesh, count, sizeof (dVector), &points[0].m_x, interior, &textureMatrix[0][0]);
//	NewtonMesh* const convexParts = NewtonMeshConvexDecomposition (mesh, 1000000);

#if 1
dScene xxxx(world);
dScene::dTreeNode* const modelNode = xxxx.CreateSceneNode(xxxx.GetRootNode());
dScene::dTreeNode* const meshNode = xxxx.CreateMeshNode(modelNode);
dMeshNodeInfo* const modelMesh = (dMeshNodeInfo*)xxxx.GetInfoFromNode(meshNode);
modelMesh->ReplaceMesh (convexParts);
xxxx.Serialize("../../../media/xxx.ngd");
#endif

	DemoEntity* const entity = new DemoEntity(NULL);
	entity->SetMatrix(*scene, dQuaternion(), dVector (0, 10, 0, 0));
	entity->InterpolateMatrix (*scene, 1.0f);
	
	
	scene->Append (entity);
	DemoMesh* const mesh1 = new DemoMesh(convexParts);
	entity->SetMesh(mesh1);
	mesh1->Release();

/*
DemoEntity* const entity2 = new DemoEntity(NULL);
entity2->SetMatrix(*scene, dQuaternion(), dVector (0, 10, 0, 0));
entity2->InterpolateMatrix (*scene, 1.0f);

scene->Append (entity2);
DemoMesh* const mesh2 = new DemoMesh(mesh);
entity2->SetMesh(mesh2);
mesh2->Release();
*/

	// make sure the assets are released before leaving the function
	if (convexParts) {
		NewtonMeshDestroy (convexParts);
	}
	NewtonMeshDestroy (mesh);
	NewtonReleaseCollision(world, collision);
}
static void AddStructuredFractured (DemoEntityManager* const scene, const dVector& origin, int materialID, const char* const assetName)
{
	// create the shape and visual mesh as a common data to be re used
	NewtonWorld* const world = scene->GetNewton();


#if 0
	// load the mesh asset
	DemoEntity entity(GetIdentityMatrix(), NULL);	
	entity.LoadNGD_mesh (assetName, world);
	DemoMesh____* const mesh = entity.GetMesh();
	dAssert (mesh);

	// convert the mesh to a newtonMesh
	NewtonMesh* const solidMesh = mesh->CreateNewtonMesh (world, entity.GetMeshMatrix() * entity.GetCurrentMatrix());
#else
	int externalMaterial = LoadTexture("wood_0.tga");
	NewtonCollision* const collision = CreateConvexCollision (world, dGetIdentityMatrix(), dVector (3.0f, 3.0f, 3.0f, 0.0), _BOX_PRIMITIVE, 0);
	NewtonMesh* const solidMesh = NewtonMeshCreateFromCollision(collision);
	NewtonDestroyCollision(collision);
	//NewtonMeshTriangulate(solidMesh);
	NewtonMeshApplyBoxMapping (solidMesh, externalMaterial, externalMaterial, externalMaterial);
#endif


	// create a random point cloud
	dVector points[MAX_POINT_CLOUD_SIZE];
	int pointCount = MakeRandomPoisonPointCloud (solidMesh, points);
//	int pointCount = MakeRandomGuassianPointCloud (solidMesh, points, MAX_POINT_CLOUD_SIZE);

	// create and interiors material for texturing the fractured pieces
	//int internalMaterial = LoadTexture("KAMEN-stup.tga");
	int internalMaterial = LoadTexture("concreteBrick.tga");

	// crate a texture matrix for uv mapping of fractured pieces
	dMatrix textureMatrix (dGetIdentityMatrix());
	textureMatrix[0][0] = 1.0f / 2.0f;
	textureMatrix[1][1] = 1.0f / 2.0f;

	/// create the fractured collision and mesh
	int debreePhysMaterial = NewtonMaterialGetDefaultGroupID(world);
	NewtonCollision* structuredFracturedCollision = NewtonCreateFracturedCompoundCollision (world, solidMesh, 0, debreePhysMaterial, pointCount, &points[0][0], sizeof (dVector), internalMaterial, &textureMatrix[0][0],
																							OnReconstructMainMeshCallBack, OnEmitFracturedCompound, OnEmitFracturedChunk);

// uncomment this to test serialization
#if 0
	FILE* file = fopen ("serialize.bin", "wb");
	NewtonCollisionSerialize (world, structuredFracturedCollision, DemoEntityManager::SerializeFile, file);
	NewtonDestroyCollision (structuredFracturedCollision);
	fclose (file);

	file = fopen ("serialize.bin", "rb");
	structuredFracturedCollision = NewtonCreateCollisionFromSerialization (world, DemoEntityManager::DeserializeFile, file);
	NewtonFracturedCompoundSetCallbacks (structuredFracturedCollision, OnReconstructMainMeshCallBack, OnEmitFracturedCompound, OnEmitFracturedChunk);
	fclose (file);
#endif	

#if 0
	// test the interface
	dTree<void*, void*> detachableNodes;
	NewtonCompoundCollisionBeginAddRemove(structuredFracturedCollision);	

	// remove all chunk that can be detached for the first layer
	for (void* node = NewtonCompoundCollisionGetFirstNode(structuredFracturedCollision); node; node = NewtonCompoundCollisionGetNextNode(structuredFracturedCollision, node)) { 
		if (NewtonFracturedCompoundIsNodeFreeToDetach (structuredFracturedCollision, node)) {
			detachableNodes.Insert(node, node);
		}

		// remove any node that can be deched fro the secund layer, this codul; be reusive
		void* neighbors[32];
		int count = NewtonFracturedCompoundNeighborNodeList (structuredFracturedCollision, node, neighbors, sizeof (neighbors) / sizeof (neighbors[0]));
		for (int i = 0; i < count; i ++ ) {
			if (NewtonFracturedCompoundIsNodeFreeToDetach (structuredFracturedCollision, neighbors[i])) {
				detachableNodes.Insert(node, node);
			}
		}
	}

	// now delete the actual nodes
	dTree<void*, void*>::Iterator iter (detachableNodes) ;
	for (iter.Begin(); iter; iter ++) { 
		void* const node = iter.GetNode()->GetInfo(); 
		NewtonCompoundCollisionRemoveSubCollision (structuredFracturedCollision, node);
	}
	NewtonCompoundCollisionEndAddRemove(structuredFracturedCollision);	
#endif
	
#if 1
	dVector plane (0.0f, 1.0f, 0.0f, 0.0f);
	NewtonCollision* const crack = NewtonFracturedCompoundPlaneClip (structuredFracturedCollision, &plane[0]);
	if (crack) {
		NewtonDestroyCollision (structuredFracturedCollision);
	}
#endif




    dVector com(0.0f);
    dVector inertia(0.0f);
    NewtonConvexCollisionCalculateInertialMatrix (structuredFracturedCollision, &inertia[0], &com[0]);	

    //dFloat mass = 10.0f;
    //int materialId = 0;
    //create the rigid body
	dMatrix matrix (dGetIdentityMatrix());
	matrix.m_posit = origin;
	matrix.m_posit.m_y = 20.0;
	matrix.m_posit.m_w = 1.0f;
    NewtonBody* const rigidBody = NewtonCreateDynamicBody (world, structuredFracturedCollision, &matrix[0][0]);

	// set the mass and center of mass
	dFloat density = 1.0f;
	dFloat mass = density * NewtonConvexCollisionCalculateVolume (structuredFracturedCollision);
	NewtonBodySetMassProperties (rigidBody, mass, structuredFracturedCollision);


	// set the transform call back function
	NewtonBodySetTransformCallback (rigidBody, DemoEntity::TransformCallback);

	// set the force and torque call back function
	NewtonBodySetForceAndTorqueCallback (rigidBody, PhysicsApplyGravityForce);

	// create the entity and visual mesh and attach to the body as user data
	CreateVisualEntity (scene, rigidBody);

    // assign the wood id
//    NewtonBodySetMaterialGroupID (rigidBody, materialId);

    // set a destructor for this rigid body
//    NewtonBodySetDestructorCallback (rigidBody, PhysicsBodyDestructor);

	// release the interior texture
//	ReleaseTexture (internalMaterial);

	// delete the solid mesh since it no longed needed
	NewtonMeshDestroy (solidMesh);

	// destroy the fracture collision
	NewtonDestroyCollision (structuredFracturedCollision);
}
Beispiel #9
0
 mesh::mesh(const NewtonCollision *col): _mesh(NULL) {
     _mesh = NewtonMeshCreateFromCollision(col);
 }
DemoMesh::DemoMesh(const char* const name, const NewtonCollision* const collision, const char* const texture0, const char* const texture1, const char* const texture2, dFloat opacity, const dMatrix& uvMatrix)
	:DemoMeshInterface()
	,dList<DemoSubMesh>()
	,m_uv(NULL)
	,m_vertex(NULL)
	,m_normal(NULL)
	,m_optimizedOpaqueDiplayList(0)		
	,m_optimizedTransparentDiplayList(0)
{
	// create a helper mesh from the collision collision
	NewtonMesh* const mesh = NewtonMeshCreateFromCollision(collision);

	// apply the vertex normals
	NewtonMeshCalculateVertexNormals(mesh, 30.0f * dDegreeToRad);

	dMatrix aligmentUV(uvMatrix);
//	NewtonCollisionGetMatrix(collision, &aligmentUV[0][0]);
	aligmentUV = aligmentUV.Inverse();

	// apply uv projections
	NewtonCollisionInfoRecord info;
	NewtonCollisionGetInfo (collision, &info);
	switch (info.m_collisionType) 
	{
		case SERIALIZE_ID_SPHERE:
		{
			NewtonMeshApplySphericalMapping(mesh, LoadTexture (texture0), &aligmentUV[0][0]);
			break;
		}

		case SERIALIZE_ID_CONE:
		case SERIALIZE_ID_CAPSULE:
		case SERIALIZE_ID_CYLINDER:
		case SERIALIZE_ID_CHAMFERCYLINDER:
		{
			//NewtonMeshApplySphericalMapping(mesh, LoadTexture(texture0));
			NewtonMeshApplyCylindricalMapping(mesh, LoadTexture(texture0), LoadTexture(texture1), &aligmentUV[0][0]);
			break;
		}

		default:
		{
			int tex0 = LoadTexture(texture0);
			int tex1 = LoadTexture(texture1);
			int tex2 = LoadTexture(texture2);
			NewtonMeshApplyBoxMapping(mesh, tex0, tex1, tex2, &aligmentUV[0][0]);
			break;
		}
	}

	// extract vertex data  from the newton mesh		
	int vertexCount = NewtonMeshGetPointCount (mesh); 
	AllocVertexData(vertexCount);
	NewtonMeshGetVertexChannel(mesh, 3 * sizeof (dFloat), (dFloat*)m_vertex);
	NewtonMeshGetNormalChannel(mesh, 3 * sizeof (dFloat), (dFloat*)m_normal);
	NewtonMeshGetUV0Channel(mesh, 2 * sizeof (dFloat), (dFloat*)m_uv);

	// extract the materials index array for mesh
	void* const geometryHandle = NewtonMeshBeginHandle (mesh); 
	for (int handle = NewtonMeshFirstMaterial (mesh, geometryHandle); handle != -1; handle = NewtonMeshNextMaterial (mesh, geometryHandle, handle)) {
		int material = NewtonMeshMaterialGetMaterial (mesh, geometryHandle, handle); 
		int indexCount = NewtonMeshMaterialGetIndexCount (mesh, geometryHandle, handle); 

		DemoSubMesh* const segment = AddSubMesh();

		segment->m_textureHandle = (GLuint)material;
		segment->SetOpacity(opacity);

		segment->AllocIndexData (indexCount);
		NewtonMeshMaterialGetIndexStream (mesh, geometryHandle, handle, (int*)segment->m_indexes); 
	}
	NewtonMeshEndHandle (mesh, geometryHandle); 

	// destroy helper mesh
	NewtonMeshDestroy(mesh);

	// optimize this mesh for hardware buffers if possible
	OptimizeForRender ();
}