NewtonBody* CreateRigidBody(DemoEntityManager* const scene, dFloat mass, NewtonCollision* const deformableCollision) { //create the rigid body NewtonWorld* const world = scene->GetNewton(); dMatrix matrix(GetCurrentMatrix()); //matrix.m_posit.m_y = FindFloor (world, matrix.m_posit.m_x, matrix.m_posit.m_z) + 4.0f; SetMatrix(*scene, dQuaternion(), matrix.m_posit); SetMatrix(*scene, dQuaternion(), matrix.m_posit); NewtonBody* const deformableBody = NewtonCreateDynamicBody(world, deformableCollision, &matrix[0][0]); // set the mass matrix NewtonBodySetMassProperties(deformableBody, mass, deformableCollision); // save the pointer to the graphic object with the body. NewtonBodySetUserData(deformableBody, this); // assign the wood id // NewtonBodySetMaterialGroupID (deformableBody, materialId); // set a destructor for this rigid body NewtonBodySetDestructorCallback(deformableBody, PhysicsBodyDestructor); // set the transform call back function NewtonBodySetTransformCallback(deformableBody, DemoEntity::TransformCallback); // set the force and torque call back function NewtonBodySetForceAndTorqueCallback(deformableBody, PhysicsApplyGravityForce); return deformableBody; }
iPhysicsBody* iPhysics::createBody(iPhysicsCollision* collisionVolume) { con_assert(collisionVolume != nullptr, "zero pointer"); con_assert(collisionVolume->_collision != nullptr, "zero pointer"); iaMatrixf matrix; NewtonWaitForUpdateToFinish(static_cast<const NewtonWorld*>(_defaultWorld)); NewtonBody* newtonBody = NewtonCreateDynamicBody(static_cast<const NewtonWorld*>(_defaultWorld), static_cast<const NewtonCollision*>(collisionVolume->_collision), matrix.getData()); // set callbacks NewtonBodySetDestructorCallback(newtonBody, reinterpret_cast<NewtonBodyDestructor>(PhysicsNodeDestructor)); NewtonBodySetTransformCallback(newtonBody, reinterpret_cast<NewtonSetTransform>(PhysicsNodeSetTransform)); NewtonBodySetForceAndTorqueCallback(newtonBody, reinterpret_cast<NewtonApplyForceAndTorque>(PhysicsApplyForceAndTorque)); NewtonBodySetMassMatrix(newtonBody, 0, 0, 0, 0); NewtonBodySetMatrix(newtonBody, matrix.getData()); start(); iPhysicsBody* result = new iPhysicsBody(newtonBody); _bodyListMutex.lock(); _bodys[result->getID()] = result; _bodyListMutex.unlock(); return result; }
static void CreateScaleStaticMesh (DemoEntity* const entity, NewtonCollision* const collision, DemoEntityManager* const scene, const dMatrix& location, const dVector& scale) { // now make a scale version of the same model // first Get The mesh and make a scale copy DemoMesh* const mesh = (DemoMesh*)entity->GetMesh(); dAssert (mesh->IsType(DemoMesh::GetRttiType())); // since the render does no handle scale, we will made a duplicated mesh with the scale baked in DemoMesh* const scaledMesh = new DemoMesh (*mesh); // now scale the vertex list for (int i = 0 ; i < mesh->m_vertexCount; i ++) { scaledMesh->m_vertex[i * 3 + 0] *= scale.m_x; scaledMesh->m_vertex[i * 3 + 1] *= scale.m_y; scaledMesh->m_vertex[i * 3 + 2] *= scale.m_z; } // re-optimize for render scaledMesh->OptimizeForRender(); DemoEntity* const scaledEntity = new DemoEntity(location, NULL); scene->Append (scaledEntity); scaledEntity->SetMesh(scaledMesh, dGetIdentityMatrix()); scaledMesh->Release(); // now make a body with a scaled collision mesh // note: the collision do not have to be destroyed because we did no create a new collision we are simple using an existing one NewtonBody* const scaledBody = NewtonCreateDynamicBody(scene->GetNewton(), collision, &location[0][0]); NewtonBodySetUserData(scaledBody, scaledEntity); // apply the scale to the new body collision; // // note: scaling a collision mesh does not updates the broadPhase, this function is a until that do update broad phase NewtonBodySetCollisionScale (scaledBody, scale.m_x, scale.m_y, scale.m_z); }
NewtonBody* CreateBodyPart(DemoEntity* const bodyPart) { NewtonWorld* const world = GetWorld(); NewtonCollision* const shape = bodyPart->CreateCollisionFromchildren(world); dAssert(shape); // calculate the bone matrix dMatrix matrix(bodyPart->CalculateGlobalMatrix()); // create the rigid body that will make this bone NewtonBody* const bone = NewtonCreateDynamicBody(world, shape, &matrix[0][0]); // calculate the moment of inertia and the relative center of mass of the solid //NewtonBodySetMassProperties (bone, definition.m_mass, shape); NewtonBodySetMassProperties(bone, 1.0f, shape); // save the user data with the bone body (usually the visual geometry) NewtonBodySetUserData(bone, bodyPart); // assign the material for early collision culling //NewtonBodySetMaterialGroupID(bone, m_material); // set the bod part force and torque call back to the gravity force, skip the transform callback //NewtonBodySetForceAndTorqueCallback (bone, PhysicsApplyGravityForce); NewtonBodySetForceAndTorqueCallback(bone, ClampAngularVelocity); // destroy the collision helper shape NewtonDestroyCollision(shape); return bone; }
OgreNewtonSceneBody::OgreNewtonSceneBody (OgreNewtonWorld* const ogreWorld, dLong collisionMask) :dNewtonDynamicBody (NULL) { Matrix4 matrix (Matrix4::IDENTITY); dNewtonCollisionScene collision (ogreWorld, collisionMask); SetBody (NewtonCreateDynamicBody (ogreWorld->GetNewton (), collision.GetShape(), matrix[0])); }
NewtonBody* CreateBodyPart(DemoEntity* const bodyPart, const dArmRobotConfig& definition) { NewtonCollision* const shape = MakeConvexHull(bodyPart); // calculate the bone matrix dMatrix matrix(bodyPart->CalculateGlobalMatrix()); NewtonWorld* const world = GetWorld(); // create the rigid body that will make this bone NewtonBody* const body = NewtonCreateDynamicBody(world, shape, &matrix[0][0]); // destroy the collision helper shape NewtonDestroyCollision(shape); // get the collision from body NewtonCollision* const collision = NewtonBodyGetCollision(body); // calculate the moment of inertia and the relative center of mass of the solid NewtonBodySetMassProperties(body, definition.m_mass, collision); //NewtonBodySetMassProperties(body, 0.0f, collision); // save the user lifterData with the bone body (usually the visual geometry) NewtonBodySetUserData(body, bodyPart); // assign a body part id //NewtonCollisionSetUserID(collision, definition.m_bodyPartID); // set the bod part force and torque call back to the gravity force, skip the transform callback NewtonBodySetForceAndTorqueCallback(body, PhysicsApplyGravityForce); return body; }
static NewtonBody* CreatePlaneCollision (DemoEntityManager* const scene, const dVector& planeEquation) { NewtonCollision* const planeCollision = CreateInfinitePlane (scene->GetNewton(), planeEquation); // create the the rigid body for dMatrix matrix (dGetIdentityMatrix()); NewtonBody* const body = NewtonCreateDynamicBody(scene->GetNewton(), planeCollision, &matrix[0][0]); // create a visual mesh DemoMesh* const mesh = CreateVisualPlaneMesh (planeEquation, scene); DemoEntity* const entity = new DemoEntity(matrix, NULL); NewtonCollisionGetMatrix(planeCollision, &matrix[0][0]); scene->Append (entity); entity->SetMesh(mesh, matrix); mesh->Release(); // save the pointer to the graphic object with the body. NewtonBodySetUserData (body, entity); // destroy the collision shape NewtonDestroyCollision (planeCollision); return body; }
static void LoadPlayGroundScene(DemoEntityManager* const scene, TriggerManager* const triggerManager) { NewtonWorld* const world = scene->GetNewton(); // CreateLevelMesh (scene, "flatPlane.ngd", true); // return; // make the body with a dummy null collision, so that we can use for attaching world objects dMatrix matrix (dGetIdentityMatrix()); NewtonCollision* const dommyCollision = NewtonCreateNull(world); NewtonBody* const playGroundBody = NewtonCreateDynamicBody (world, dommyCollision, &matrix[0][0]); NewtonDestroyCollision (dommyCollision); // use a multi shape static scene collision NewtonCollision* const sceneCollision = NewtonCreateSceneCollision (world, 0); // start adding shapes to this scene collisions NewtonSceneCollisionBeginAddRemove (sceneCollision); // populate the scene collision { // load a flat floor LoadFloor(scene, sceneCollision); // load a slide platform dMatrix slideMatrix(dGetIdentityMatrix()); slideMatrix.m_posit.m_x += 80.0f; slideMatrix.m_posit.m_z = -20.0f; //LoadSlide(scene, triggerManager, sceneCollision, "slide.ngd", slideMatrix, playGroundBody); LoadFerryBridge(scene, triggerManager, sceneCollision, "platformBridge.ngd", slideMatrix, playGroundBody); // load another hanging bridge dMatrix bridgeMatrix(dGetIdentityMatrix()); bridgeMatrix.m_posit.m_x += 40.0f; LoadHangingBridge(scene, triggerManager, sceneCollision, "hangingBridge.ngd", bridgeMatrix, playGroundBody); // load another ferry bridge bridgeMatrix.m_posit.m_z += 20.0f; LoadFerryBridge(scene, triggerManager, sceneCollision, "platformBridge.ngd", bridgeMatrix, playGroundBody); } // finalize adding shapes to this scene collisions NewtonSceneCollisionEndAddRemove (sceneCollision); // attach this collision to the playground Body NewtonBodySetCollision(playGroundBody, sceneCollision); // set the reference to the visual //NewtonBodySetUserData(level, visualMesh); // do not forget to release the collision NewtonDestroyCollision (sceneCollision); }
NewtonBody* CreateSimpleBody (NewtonWorld* const world, void* const userData, dFloat mass, const dMatrix& matrix, NewtonCollision* const collision, int materialId) { // calculate the moment of inertia and the relative center of mass of the solid // dVector origin; // dVector inertia; // NewtonConvexCollisionCalculateInertialMatrix (collision, &inertia[0], &origin[0]); // dFloat Ixx = mass * inertia[0]; // dFloat Iyy = mass * inertia[1]; // dFloat Izz = mass * inertia[2]; //create the rigid body NewtonBody* const rigidBody = NewtonCreateDynamicBody (world, collision, &matrix[0][0]); // set the correct center of gravity for this body (these function are for legacy) // NewtonBodySetCentreOfMass (rigidBody, &origin[0]); // NewtonBodySetMassMatrix (rigidBody, mass, Ixx, Iyy, Izz); // use a more convenient function for setting mass and inertia matrix NewtonBodySetMassProperties (rigidBody, mass, collision); // save the pointer to the graphic object with the body. NewtonBodySetUserData (rigidBody, userData); // assign the wood id NewtonBodySetMaterialGroupID (rigidBody, materialId); // set continuous collision mode // NewtonBodySetContinuousCollisionMode (rigidBody, continueCollisionMode); // set a destructor for this rigid body NewtonBodySetDestructorCallback (rigidBody, PhysicsBodyDestructor); // set the transform call back function NewtonBodySetTransformCallback (rigidBody, DemoEntity::TransformCallback); // set the force and torque call back function NewtonBodySetForceAndTorqueCallback (rigidBody, PhysicsApplyGravityForce); // set the matrix for both the rigid body and the graphic body //NewtonBodySetMatrix (rigidBody, &matrix[0][0]); //PhysicsSetTransform (rigidBody, &matrix[0][0], 0); //dVector xxx (0, -9.8f * mass, 0.0f, 0.0f); //NewtonBodySetForce (rigidBody, &xxx[0]); // force the body to be active of inactive // NewtonBodySetAutoSleep (rigidBody, sleepMode); return rigidBody; }
static void AddFracturedEntity(DemoEntityManager* const scene, DemoMesh* const visualMesh, NewtonCollision* const collision, const FractureEffect& fractureEffect, const dVector& location) { dQuaternion rotation; SimpleFracturedEffectEntity* const entity = new SimpleFracturedEffectEntity(visualMesh, fractureEffect); entity->SetMatrix(*scene, rotation, location); entity->InterpolateMatrix(*scene, 1.0f); scene->Append(entity); dVector origin(0.0f); dVector inertia(0.0f); NewtonConvexCollisionCalculateInertialMatrix(collision, &inertia[0], &origin[0]); dFloat mass = 10.0f; int materialId = 0; //create the rigid body dMatrix matrix(dGetIdentityMatrix()); matrix.m_posit = location; NewtonWorld* const world = scene->GetNewton(); NewtonBody* const rigidBody = NewtonCreateDynamicBody(world, collision, &matrix[0][0]); entity->m_myBody = rigidBody; entity->m_myMassInverse = 1.0f / mass; // set the correct center of gravity for this body //NewtonBodySetCentreOfMass (rigidBody, &origin[0]); // set the mass matrix NewtonBodySetMassProperties(rigidBody, mass, collision); // save the pointer to the graphic object with the body. NewtonBodySetUserData(rigidBody, entity); // assign the wood id NewtonBodySetMaterialGroupID(rigidBody, materialId); // set continuous collision mode // NewtonBodySetContinuousCollisionMode (rigidBody, continueCollisionMode); // set a destructor for this rigid body NewtonBodySetDestructorCallback(rigidBody, PhysicsBodyDestructor); // set the transform call back function NewtonBodySetTransformCallback(rigidBody, DemoEntity::TransformCallback); // set the force and torque call back function NewtonBodySetForceAndTorqueCallback(rigidBody, PhysicsApplyGravityForce); }
void dVehicleChassis::Init(NewtonCollision* const chassisShape, dFloat mass, const dMatrix& localFrame, NewtonApplyForceAndTorque forceAndTorque, dFloat gravityMag) { dVehicleManager* const manager = (dVehicleManager*)GetManager(); NewtonWorld* const world = manager->GetWorld(); // create a body and call the low level init function dMatrix locationMatrix(dGetIdentityMatrix()); NewtonBody* const body = NewtonCreateDynamicBody(world, chassisShape, &locationMatrix[0][0]); // set vehicle mass, inertia and center of mass NewtonBodySetMassProperties(body, mass, chassisShape); // initialize Init(body, localFrame, forceAndTorque, gravityMag); }
void CustomVehicleController::Init (NewtonCollision* const chassisShape, const dMatrix& vehicleFrame, dFloat mass, const dVector& gravityVector) { CustomVehicleControllerManager* const manager = (CustomVehicleControllerManager*) GetManager(); NewtonWorld* const world = manager->GetWorld(); // create a body and an call the low level init function dMatrix locationMatrix (dGetIdentityMatrix()); NewtonBody* const body = NewtonCreateDynamicBody(world, chassisShape, &locationMatrix[0][0]); // set vehicle mass, inertia and center of mass NewtonBodySetMassProperties (body, mass, chassisShape); // initialize Init (body, vehicleFrame, gravityVector); }
void RigidBodyData::CreateBody(NewtonCollision* const collision, const dVector& veloc, const dVector& omega) { _ASSERTE (!m_body); RigidBodyWorldDesc& me = *(RigidBodyWorldDesc*) RigidBodyWorldDesc::GetDescriptor(); dMatrix matrix (GetIdentityMatrix()); m_body = NewtonCreateDynamicBody(me.m_newton, collision, &matrix[0][0]); //NewtonBodySetMassMatrix(m_body, m_mass, m_mass * m_inertia.m_x, m_mass * m_inertia.m_y, m_mass * m_inertia.m_z); NewtonBodySetMassProperties(m_body, m_mass, collision); NewtonBodySetCentreOfMass(m_body, &m_origin[0]); NewtonBodySetVelocity(m_body, &veloc[0]); NewtonBodySetOmega(m_body, &omega[0]); NewtonBodySetForceAndTorqueCallback(m_body, RigidBodyController::ApplyGravityForce); }
dNewtonDynamicBody::dNewtonDynamicBody(dNewtonWorld* const world, dNewtonCollision* const collision, dMatrix matrix, dFloat mass) :dNewtonBody(matrix) { NewtonWorld* const newton = world->m_world; NewtonWaitForUpdateToFinish(newton); m_body = NewtonCreateDynamicBody(newton, collision->m_shape, &matrix[0][0]); collision->DeleteShape(); collision->SetShape(NewtonBodyGetCollision(m_body)); NewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body)); NewtonBodySetUserData(m_body, this); NewtonBodySetTransformCallback(m_body, OnBodyTransformCallback); NewtonBodySetForceAndTorqueCallback(m_body, OnForceAndTorqueCallback); }
NewtonBody* CreateLevelMeshBody (NewtonWorld* const world, DemoEntity* const ent, bool optimize) { NewtonCollision* const collision = CreateCollisionTree (world, ent, 0, optimize); // Get the root Matrix dMatrix matrix (ent->CalculateGlobalMatrix(NULL)); // create the level rigid body NewtonBody* const level = NewtonCreateDynamicBody(world, collision, &matrix[0][0]); //NewtonCollision* const collision1 = NewtonCreateNull(world); //NewtonBody* const level = NewtonCreateDynamicBody(world, collision1, &matrix[0][0]); //NewtonBodySetCollision(level, collision); //NewtonDestroyCollision (collision1); // save the pointer to the graphic object with the body. NewtonBodySetUserData (level, ent); #if 0 NewtonCollisionInfoRecord collisionInfo; NewtonCollisionGetInfo (collision, &collisionInfo); if (collisionInfo.m_collisionType == SERIALIZE_ID_TREE) { int count; dVector p0(-100, -100, -100); dVector p1(100, 100, 100); const dFloat* vertexArray; int vertexStrideInBytes; int vertexCount; int indexList[256]; int attributeList[256/3]; count = NewtonTreeCollisionGetVertexListTriangleListInAABB (collision, &p0[0], &p1[0], &vertexArray, &vertexCount, &vertexStrideInBytes, indexList, sizeof (indexList)/sizeof (indexList[0]), attributeList); } #endif // set a destructor for this rigid body //NewtonBodySetDestructorCallback (m_level, Destructor); // release the collision tree (this way the application does not have to do book keeping of Newton objects NewtonDestroyCollision (collision); // now we will make a lookup table for quick material index lookup for face to index //CollsionTreeFaceMap faceMap (NewtonBodyGetCollision(level)); return level; }
NzPhysObject::NzPhysObject(NzPhysWorld* world, const NzBaseGeom* geom, const NzMatrix4f& mat) : m_matrix(mat), m_forceAccumulator(NzVector3f::Zero()), m_torqueAccumulator(NzVector3f::Zero()), m_geom(geom), m_world(world), m_ownsGeom(false), m_gravityFactor(1.f), m_mass(0.f) { #if NAZARA_PHYSICS_SAFE if (!world) NazaraError("Invalid physics world"); ///TODO: Unexcepted #endif m_body = NewtonCreateDynamicBody(world->GetHandle(), geom->GetHandle(), mat); NewtonBodySetUserData(m_body, this); }
Error PhysicsWorld::create(AllocAlignedCallback allocCb, void* allocCbData) { Error err = ErrorCode::NONE; m_alloc = HeapAllocator<U8>(allocCb, allocCbData); // Set allocators gAlloc = &m_alloc; NewtonSetMemorySystem(newtonAlloc, newtonFree); // Initialize world m_world = NewtonCreate(); if(!m_world) { ANKI_LOGE("NewtonCreate() failed"); return ErrorCode::FUNCTION_FAILED; } // Set the simplified solver mode (faster but less accurate) NewtonSetSolverModel(m_world, 1); // Create scene collision m_sceneCollision = NewtonCreateSceneCollision(m_world, 0); Mat4 trf = Mat4::getIdentity(); m_sceneBody = NewtonCreateDynamicBody(m_world, m_sceneCollision, &trf[0]); NewtonBodySetMaterialGroupID(m_sceneBody, NewtonMaterialGetDefaultGroupID(m_world)); NewtonDestroyCollision(m_sceneCollision); // destroy old scene m_sceneCollision = NewtonBodyGetCollision(m_sceneBody); // Set the post update listener NewtonWorldAddPostListener(m_world, "world", this, postUpdateCallback, destroyCallback); // Set callbacks NewtonMaterialSetCollisionCallback(m_world, NewtonMaterialGetDefaultGroupID(m_world), NewtonMaterialGetDefaultGroupID(m_world), nullptr, onAabbOverlapCallback, onContactCallback); return err; }
// it fires a box when a key is pressed. static void FireNewtonCcdBox(NewtonWorld* world, const dVector & postion, const dVector & velocity) { NewtonCollision* collision = NewtonCreateBox(world, 1.0f, 1.0f, 1.0f, 0, NULL); dMatrix matrix(dGetIdentityMatrix()); matrix.m_posit = postion; NewtonBody* const body = NewtonCreateDynamicBody(world, collision, &matrix[0][0]); // set the force callback for applying the force and torque NewtonBodySetForceAndTorqueCallback(body, ApplyGravity); // set the mass for this body dFloat mass = 1.0f; NewtonBodySetMassProperties(body, mass, collision); NewtonDestroyCollision(collision); NewtonBodySetVelocity(body, &velocity[0]); NewtonBodySetContinuousCollisionMode(body, 1); }
static void AddSingleCompound(DemoEntityManager* const scene) { NewtonWorld* const world = scene->GetNewton(); NewtonCollision* compoundCollision = NewtonCreateCompoundCollision(world, 0); NewtonCompoundCollisionBeginAddRemove(compoundCollision); NewtonCollision* boxCollision = NewtonCreateBox(world, 50, 50, 50, 0, NULL); NewtonCompoundCollisionAddSubCollision(compoundCollision, boxCollision); NewtonDestroyCollision(boxCollision); dMatrix matrix(dGetIdentityMatrix()); matrix.m_posit.m_y = 10.0f; NewtonCompoundCollisionEndAddRemove(compoundCollision); NewtonBody* compoundBody = NewtonCreateDynamicBody(world, compoundCollision, &matrix[0][0]); NewtonDestroyCollision(compoundCollision); // scale after creating body slows everything down. Without the scale it runs fine even though the body is huge NewtonCollisionSetScale(NewtonBodyGetCollision(compoundBody), 0.05f, 0.05f, 0.05f); // adding some visualization NewtonBodySetMassProperties (compoundBody, 1.0f, NewtonBodyGetCollision(compoundBody)); NewtonBodySetTransformCallback(compoundBody, DemoEntity::TransformCallback); NewtonBodySetForceAndTorqueCallback(compoundBody, PhysicsApplyGravityForce); DemoMesh* mesh = new DemoMesh("geometry", NewtonBodyGetCollision(compoundBody), "smilli.tga", "smilli.tga", "smilli.tga"); DemoEntity* const entity = new DemoEntity(matrix, NULL); entity->SetMesh(mesh, dGetIdentityMatrix()); mesh->Release(); NewtonBodySetUserData(compoundBody, entity); scene->Append(entity); NewtonBodySetSimulationState(compoundBody, 0); NewtonBodySetSimulationState(compoundBody, 1); }
NewtonBody* dRigidbodyNodeInfo::CreateNewtonBody (NewtonWorld* const world, dScene* const scene, dScene::dTreeNode* const myNode) const { // find the collision and crate a rigid body dAssert (IsType (dRigidbodyNodeInfo::GetRttiType())); // attach the parent node as user data dScene::dTreeNode* parentNode = scene->FindParentByType(myNode, dSceneNodeInfo::GetRttiType()); dSceneNodeInfo* sceneInfo = (dSceneNodeInfo*) scene->GetInfoFromNode(parentNode); dScene::dTreeNode* shapeNode = scene->FindChildByType (myNode, dCollisionNodeInfo::GetRttiType()); dAssert (shapeNode); dCollisionNodeInfo* collInfo = (dCollisionNodeInfo*) scene->GetInfoFromNode(shapeNode); dMatrix matrix (sceneInfo->CalculateOrthoMatrix()); NewtonCollision* const collision = collInfo->CreateNewtonCollision (world, scene, shapeNode); NewtonBody* const body = NewtonCreateDynamicBody(world, collision, &matrix[0][0]); NewtonDestroyCollision(collision); // NewtonBodySetMatrix(body, &matrix[0][0]); NewtonBodySetUserData(body, parentNode); NewtonBodySetCentreOfMass(body, &m_centerOfMass[0]); NewtonBodySetMassMatrix(body, m_massMatrix.m_w, m_massMatrix.m_x, m_massMatrix.m_y, m_massMatrix.m_z); NewtonBodySetVelocity(body, &m_velocity[0]); NewtonBodySetOmega(body, &m_omega[0]); //dVector internalDamp(rigidBody->GetI); //NewtonBodySetLinearDamping(body, internalDamp); //dVariable* bodyType = rigidBody->FindVariable("rigidBodyType"); //if (!bodyType || !strcmp (bodyType->GetString(), "default gravity")) { // NewtonBodySetTransformCallback(body, DemoEntity::TransformCallback); //} return body; }
static NewtonBody* CreateBackgroundWallsAndCellingBody(NewtonWorld* world) { // make a flat quad dFloat floor[4][3] = { { -100.0f, 0.0f, 100.0f }, { 100.0f, 0.0f, 100.0f }, { 100.0f, 0.0f, -100.0f }, { -100.0f, 0.0f, -100.0f }, }; dFloat wall_N[4][3] = { { -100.0f, 0.0f, 100.0f }, { -100.0f, 100.0f, 100.0f }, { 100.0f, 100.0f, 100.0f }, { 100.0f, 0.0f, 100.0f }, }; dFloat wall_W[4][3] = { { 100.0f, 0.0f, 100.0f }, { 100.0f, 100.0f, 100.0f }, { 100.0f, 100.0f, -100.0f }, { 100.0f, 0.0f, -100.0f }, }; dFloat wall_S[4][3] = { { 100.0f, 0.0f, -100.0f }, { 100.0f, 100.0f, -100.0f }, { -100.0f, 100.0f, -100.0f }, { -100.0f, 0.0f, -100.0f }, }; dFloat wall_E[4][3] = { { -100.0f, 0.0f, -100.0f }, { -100.0f, 100.0f, -100.0f }, { -100.0f, 100.0f, 100.0f }, { -100.0f, 0.0f, 100.0f }, }; dFloat celling[4][3] = { { -100.0f, 100.0f, -100.0f }, { 100.0f, 100.0f, -100.0f }, { 100.0f, 100.0f, 100.0f }, { -100.0f, 100.0f, 100.0f }, }; // crate a collision tree NewtonCollision* const collision = NewtonCreateTreeCollision(world, 0); // start building the collision mesh NewtonTreeCollisionBeginBuild(collision); // add the face one at a time NewtonTreeCollisionAddFace(collision, 4, &floor[0][0], 3 * sizeof (dFloat), 0); NewtonTreeCollisionAddFace(collision, 4, &wall_N[0][0], 3 * sizeof (dFloat), 0); NewtonTreeCollisionAddFace(collision, 4, &wall_W[0][0], 3 * sizeof (dFloat), 0); NewtonTreeCollisionAddFace(collision, 4, &wall_S[0][0], 3 * sizeof (dFloat), 0); NewtonTreeCollisionAddFace(collision, 4, &wall_E[0][0], 3 * sizeof (dFloat), 0); NewtonTreeCollisionAddFace(collision, 4, &celling[0][0], 3 * sizeof (dFloat), 0); // finish building the collision NewtonTreeCollisionEndBuild(collision, 1); // create a body with a collision and locate at the identity matrix position dMatrix matrix(dGetIdentityMatrix()); NewtonBody* const body = NewtonCreateDynamicBody(world, collision, &matrix[0][0]); // do no forget to destroy the collision after you not longer need it NewtonDestroyCollision(collision); return body; }
void SimulationPostListener(DemoEntityManager* const scene, DemoEntityManager::dListNode* const mynode, dFloat timeStep) { // see if the net force on the body comes fr a high impact collision dFloat breakImpact = 0.0f; for (NewtonJoint* joint = NewtonBodyGetFirstContactJoint(m_myBody); joint; joint = NewtonBodyGetNextContactJoint(m_myBody, joint)) { for (void* contact = NewtonContactJointGetFirstContact(joint); contact; contact = NewtonContactJointGetNextContact(joint, contact)) { dVector contactForce; NewtonMaterial* const material = NewtonContactGetMaterial(contact); dFloat impulseImpact = NewtonMaterialGetContactMaxNormalImpact(material); if (impulseImpact > breakImpact) { breakImpact = impulseImpact; } } } // if the force is bigger than N time Gravities, It is considered a collision force breakImpact *= m_myMassInverse; // breakImpact = 1000.0f; if (breakImpact > BREAK_IMPACT_IN_METERS_PER_SECONDS) { NewtonWorld* const world = NewtonBodyGetWorld(m_myBody); dMatrix bodyMatrix; dVector com(0.0f); dVector veloc(0.0f); dVector omega(0.0f); dFloat Ixx; dFloat Iyy; dFloat Izz; dFloat mass; NewtonBodyGetVelocity(m_myBody, &veloc[0]); NewtonBodyGetOmega(m_myBody, &omega[0]); NewtonBodyGetCentreOfMass(m_myBody, &com[0]); NewtonBodyGetMatrix(m_myBody, &bodyMatrix[0][0]); NewtonBodyGetMass(m_myBody, &mass, &Ixx, &Iyy, &Izz); com = bodyMatrix.TransformVector(com); dMatrix matrix(GetCurrentMatrix()); dQuaternion rotation(matrix); // we need to lock the world before creation a bunch of bodies scene->Lock(m_lock); for (FractureEffect::dListNode* node = m_effect.GetFirst(); node; node = node->GetNext()) { FractureAtom& atom = node->GetInfo(); DemoEntity* const entity = new DemoEntity(dMatrix(rotation, matrix.m_posit), NULL); entity->SetMesh(atom.m_mesh, dGetIdentityMatrix()); scene->Append(entity); int materialId = 0; dFloat debriMass = mass * atom.m_massFraction; //create the rigid body NewtonBody* const rigidBody = NewtonCreateDynamicBody(world, atom.m_collision, &matrix[0][0]); // calculate debris initial velocity dVector center(matrix.TransformVector(atom.m_centerOfMass)); dVector v(veloc + omega.CrossProduct(center - com)); // set initial velocity NewtonBodySetVelocity(rigidBody, &v[0]); NewtonBodySetOmega(rigidBody, &omega[0]); // set the debris mass properties, mass, center of mass, and inertia NewtonBodySetMassProperties(rigidBody, debriMass, atom.m_collision); // save the pointer to the graphic object with the body. NewtonBodySetUserData(rigidBody, entity); // assign the wood id NewtonBodySetMaterialGroupID(rigidBody, materialId); // set continuous collision mode // NewtonBodySetContinuousCollisionMode (rigidBody, continueCollisionMode); // set a destructor for this rigid body NewtonBodySetDestructorCallback(rigidBody, PhysicsBodyDestructor); // set the transform call back function NewtonBodySetTransformCallback(rigidBody, DemoEntity::TransformCallback); // set the force and torque call back function NewtonBodySetForceAndTorqueCallback(rigidBody, PhysicsApplyGravityForce); } NewtonDestroyBody(m_myBody); scene->RemoveEntity(mynode); // unlock the work after done with the effect scene->Unlock(m_lock); } }
void SceneCollision (DemoEntityManager* const scene) { NewtonWorld* world = scene->GetNewton(); // add the Sky scene->CreateSkyBox(); // create a body and with a scene collision NewtonCollision* const sceneCollision = NewtonCreateSceneCollision (scene->GetNewton(), 0); // create a visual scene empty mesh ComplexScene* const visualMesh = new ComplexScene(sceneCollision); scene->Append (visualMesh); // add some shapes visualMesh->AddPrimitives(scene); // this is optional, finish the scene construction, optimize the collision scene dMatrix matrix (dGetIdentityMatrix()); // create the level body and add it to the world NewtonBody* const level = NewtonCreateDynamicBody (world, sceneCollision, &matrix[0][0]); // replace the collision with the newly created one the visualMesh->m_sceneCollision = NewtonBodyGetCollision(level); // set the reference to the visual NewtonBodySetUserData(level, visualMesh); // do not forget to release the collision NewtonDestroyCollision (sceneCollision); // add few objects int defaultMaterialID = NewtonMaterialGetDefaultGroupID (world); NewtonMaterialSetCollisionCallback (world, defaultMaterialID, defaultMaterialID, OnBodyAABBOverlap, OnContactCollision); NewtonMaterialSetCompoundCollisionCallback(world, defaultMaterialID, defaultMaterialID, OnSubShapeAABBOverlapTest); dVector location (0.0f, 0.0f, 0.0f, 0.0f); dVector size (0.5f, 0.5f, 0.5f, 0.0f); dMatrix shapeOffsetMatrix (dGetIdentityMatrix()); int count = 5; AddPrimitiveArray(scene, 10.0f, location, size, count, count, 1.7f, _SPHERE_PRIMITIVE, defaultMaterialID, shapeOffsetMatrix); AddPrimitiveArray(scene, 10.0f, location, size, count, count, 1.7f, _BOX_PRIMITIVE, defaultMaterialID, shapeOffsetMatrix); AddPrimitiveArray(scene, 10.0f, location, size, count, count, 1.7f, _CYLINDER_PRIMITIVE, defaultMaterialID, shapeOffsetMatrix); AddPrimitiveArray(scene, 10.0f, location, size, count, count, 1.7f, _CHAMFER_CYLINDER_PRIMITIVE, defaultMaterialID, shapeOffsetMatrix); AddPrimitiveArray(scene, 10.0f, location, size, count, count, 1.7f, _CONE_PRIMITIVE, defaultMaterialID, shapeOffsetMatrix); AddPrimitiveArray(scene, 10.0f, location, size, count, count, 1.7f, _CAPSULE_PRIMITIVE, defaultMaterialID, shapeOffsetMatrix); AddPrimitiveArray(scene, 10.0f, location, size, count, count, 1.7f, _RANDOM_CONVEX_HULL_PRIMITIVE, defaultMaterialID, shapeOffsetMatrix); AddPrimitiveArray(scene, 10.0f, location, size, count, count, 1.7f, _COMPOUND_CONVEX_CRUZ_PRIMITIVE, defaultMaterialID, shapeOffsetMatrix); dMatrix camMatrix (dRollMatrix(-20.0f * 3.1416f /180.0f) * dYawMatrix(-45.0f * 3.1416f /180.0f)); dQuaternion rot (camMatrix); dVector origin (-15.0f, 5.0f, 0.0f, 0.0f); scene->SetCameraMatrix(rot, origin); }
void CustomVehicleController::Init (NewtonCollision* const chassisShape, const dMatrix& vehicleFrame, dFloat mass, const dVector& gravityVector) { m_finalized = false; m_externalContactStatesCount = 0; m_sleepCounter = VEHICLE_SLEEP_COUNTER; m_freeContactList = m_externalContactStatesPoll.GetFirst(); CustomVehicleControllerManager* const manager = (CustomVehicleControllerManager*) GetManager(); NewtonWorld* const world = manager->GetWorld(); // create a compound collision NewtonCollision* const vehShape = NewtonCreateCompoundCollision(world, 0); NewtonCompoundCollisionBeginAddRemove(vehShape); // if the shape is a compound collision ass all the pieces one at a time int shapeType = NewtonCollisionGetType (chassisShape); if (shapeType == SERIALIZE_ID_COMPOUND) { for (void* node = NewtonCompoundCollisionGetFirstNode(chassisShape); node; node = NewtonCompoundCollisionGetNextNode (chassisShape, node)) { NewtonCollision* const subCollision = NewtonCompoundCollisionGetCollisionFromNode(chassisShape, node); NewtonCompoundCollisionAddSubCollision (vehShape, subCollision); } } else { dAssert ((shapeType == SERIALIZE_ID_CONVEXHULL) || (shapeType == SERIALIZE_ID_BOX)); NewtonCompoundCollisionAddSubCollision (vehShape, chassisShape); } NewtonCompoundCollisionEndAddRemove (vehShape); // create the rigid body for this vehicle dMatrix locationMatrix (dGetIdentityMatrix()); m_body = NewtonCreateDynamicBody(world, vehShape, &locationMatrix[0][0]); // set vehicle mass, inertia and center of mass NewtonBodySetMassProperties (m_body, mass, vehShape); // set linear and angular drag to zero dVector drag(0.0f, 0.0f, 0.0f, 0.0f); NewtonBodySetLinearDamping(m_body, 0); NewtonBodySetAngularDamping(m_body, &drag[0]); // destroy the collision help shape NewtonDestroyCollision (vehShape); // initialize vehicle internal components NewtonBodyGetCentreOfMass (m_body, &m_chassisState.m_com[0]); m_chassisState.m_comOffset = dVector (0.0f, 0.0f, 0.0f, 0.0f); m_chassisState.m_gravity = gravityVector; m_chassisState.m_gravityMag = dSqrt (gravityVector % gravityVector); m_chassisState.Init(this, vehicleFrame); // m_stateList.Append(&m_staticWorld); m_stateList.Append(&m_chassisState); // create the normalized size tire shape m_tireCastShape = NewtonCreateChamferCylinder(world, 0.5f, 1.0f, 0, NULL); // initialize all components to empty m_engine = NULL; m_brakes = NULL; m_steering = NULL; m_handBrakes = NULL; SetDryRollingFrictionTorque (100.0f/4.0f); SetAerodynamicsDownforceCoefficient (0.5f * dSqrt (gravityVector % gravityVector), 60.0f * 0.447f); }
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); }
static NewtonBody* CreateHeightFieldTerrain (DemoEntityManager* const scene, int sizeInPowerOfTwos, dFloat cellSize, dFloat elevationScale, dFloat roughness, dFloat maxElevation, dFloat minElevation) { int size = (1 << sizeInPowerOfTwos) + 1 ; dFloat* const elevation = new dFloat [size * size]; //MakeFractalTerrain (elevation, sizeInPowerOfTwos, elevationScale, roughness, maxElevation, minElevation); MakeFractalTerrain (elevation, sizeInPowerOfTwos, elevationScale, roughness, maxElevation, minElevation); for (int i = 0; i < 4; i ++) { ApplySmoothFilter (elevation, size); } //memset (elevation, 0, size * size * sizeof (dFloat)); //SetBaseHeight (elevation, size); // apply simple calderas // MakeCalderas (elevation, size, maxElevation * 0.7f, maxElevation * 0.1f); // // create the visual mesh DemoMesh* const mesh = new DemoMesh ("terrain", elevation, size, cellSize, 1.0f/4.0f, TILE_SIZE); DemoEntity* const entity = new DemoEntity(dGetIdentityMatrix(), NULL); scene->Append (entity); entity->SetMesh(mesh, dGetIdentityMatrix()); mesh->Release(); // create the height field collision and rigid body // create the attribute map int width = size; int height = size; char* const attibutes = new char [size * size]; memset (attibutes, 0, width * height * sizeof (char)); NewtonCollision* collision = NewtonCreateHeightFieldCollision (scene->GetNewton(), width, height, 1, 0, elevation, attibutes, 1.0f, cellSize, 0); #ifdef USE_STATIC_MESHES_DEBUG_COLLISION NewtonStaticCollisionSetDebugCallback (collision, ShowMeshCollidingFaces); #endif NewtonCollisionInfoRecord collisionInfo; // keep the compiler happy memset (&collisionInfo, 0, sizeof (NewtonCollisionInfoRecord)); NewtonCollisionGetInfo (collision, &collisionInfo); width = collisionInfo.m_heightField.m_width; height = collisionInfo.m_heightField.m_height; //elevations = collisionInfo.m_heightField.m_elevation; dVector boxP0; dVector boxP1; // get the position of the aabb of this geometry dMatrix matrix (entity->GetCurrentMatrix()); NewtonCollisionCalculateAABB (collision, &matrix[0][0], &boxP0.m_x, &boxP1.m_x); matrix.m_posit = (boxP0 + boxP1).Scale (-0.5f); matrix.m_posit.m_w = 1.0f; //SetMatrix (matrix); entity->ResetMatrix (*scene, matrix); // create the terrainBody rigid body NewtonBody* const terrainBody = NewtonCreateDynamicBody(scene->GetNewton(), collision, &matrix[0][0]); // release the collision tree (this way the application does not have to do book keeping of Newton objects NewtonDestroyCollision (collision); // in newton 300 collision are instance, you need to ready it after you create a body, if you want to male call on the instance collision = NewtonBodyGetCollision(terrainBody); #if 0 // uncomment this to test horizontal displacement unsigned short* const horizontalDisplacemnet = new unsigned short[size * size]; for (int i = 0; i < size * size; i++) { horizontalDisplacemnet[i] = dRand(); } NewtonHeightFieldSetHorizontalDisplacement(collision, horizontalDisplacemnet, 0.02f); delete horizontalDisplacemnet; #endif // save the pointer to the graphic object with the body. NewtonBodySetUserData (terrainBody, entity); // set the global position of this body // NewtonBodySetMatrix (m_terrainBody, &matrix[0][0]); // set the destructor for this object //NewtonBodySetDestructorCallback (terrainBody, Destructor); // get the position of the aabb of this geometry //NewtonCollisionCalculateAABB (collision, &matrix[0][0], &boxP0.m_x, &boxP1.m_x); #ifdef USE_TEST_ALL_FACE_USER_RAYCAST_CALLBACK // set a ray cast callback for all face ray cast NewtonTreeCollisionSetUserRayCastCallback (collision, AllRayHitCallback); dVector p0 (0, 100, 0, 0); dVector p1 (0, -100, 0, 0); dVector normal; dLong id; dFloat parameter; parameter = NewtonCollisionRayCast (collision, &p0[0], &p1[0], &normal[0], &id); #endif delete[] attibutes; delete[] elevation; return terrainBody; }