PhysRigidBody.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. #include "PhysRigidBody.h"
  2. #include "PhysicsScene.h"
  3. #include "PhysTriangleMesh.h"
  4. #include "IProxy.h"
  5. #ifndef STOP_DEBUG
  6. // определена в PhysicsService.cpp
  7. IProxy * FindProxyObject(NxActor * actor);
  8. #endif
  9. inline PhysRigidBodyActor::PhysRigidBodyActor(float density) :
  10. actor(null),
  11. group(phys_world),
  12. m_density(density)
  13. {
  14. bKinematic = false;
  15. }
  16. inline PhysRigidBodyActor::~PhysRigidBodyActor()
  17. {
  18. Release();
  19. }
  20. inline void PhysRigidBodyActor::Release()
  21. {
  22. if(actor)
  23. {
  24. actor->getScene().releaseActor(*actor);
  25. }
  26. actor = null;
  27. }
  28. inline bool PhysRigidBodyActorCheckDynamic(const NxActor & actor, const char * file, long line)
  29. {
  30. return true;
  31. if (!actor.isDynamic())
  32. {
  33. api->Trace("Physics error: Bad call for static actor, %s, %d", file, line);
  34. }
  35. return true;
  36. }
  37. bool PhysRigidBodyActorCheckMtx(const Matrix & mtx, NxActor * actor, const char * filename, long fileline)
  38. {
  39. bool isScaled = false;
  40. #ifndef _XBOX
  41. const float eps = 1e-3f;
  42. const float ortoEps = 0.999f;
  43. #else
  44. const float eps = 1e-2f;
  45. const float ortoEps = 0.999f;
  46. #endif
  47. bool isNan = false;
  48. for (int i=0; i<16; i++)
  49. if (_isnan(mtx.matrix[i]))
  50. {
  51. isNan = true;
  52. break;
  53. }
  54. if(fabsf(~mtx.vx - 1.0f) > eps) isScaled = true;
  55. if(fabsf(~mtx.vy - 1.0f) > eps) isScaled = true;
  56. if(fabsf(~mtx.vz - 1.0f) > eps) isScaled = true;
  57. float orhto = (!(mtx.vx ^ mtx.vz) | !mtx.vy);
  58. bool isNonOrtho = (orhto >= -ortoEps);
  59. //if (api->DebugKeyState('8') && (rand()%10) == 5) isNonOrtho = true;
  60. if (isScaled || isNonOrtho || isNan)
  61. {
  62. if (isScaled) api->Trace("Matrix have scale factor");
  63. if (isNonOrtho) api->Trace("Matrix non-orthogonal, cos = %.6f, degree = %.2f", orhto, safeACos(orhto));
  64. if (isNan) api->Trace("Matrix have NAN numbers");
  65. api->Trace("vx = (%f, %f, %f; %f); len = %f", mtx.vx.x, mtx.vx.y, mtx.vx.z, mtx.wx, mtx.vx.GetLength());
  66. api->Trace("vy = (%f, %f, %f; %f); len = %f", mtx.vy.x, mtx.vy.y, mtx.vy.z, mtx.wy, mtx.vy.GetLength());
  67. api->Trace("vz = (%f, %f, %f; %f); len = %f", mtx.vz.x, mtx.vz.y, mtx.vz.z, mtx.wz, mtx.vz.GetLength());
  68. api->Trace("pos = (%f, %f, %f; %f)", mtx.pos.x, mtx.pos.y, mtx.pos.z, mtx.w);
  69. api->Trace("file: %s, line: %d", filename, fileline);
  70. #ifndef STOP_DEBUG
  71. if (!actor) return false;
  72. // трейсим несколько последних установок параметров в прокси объекте
  73. // ищем прокси объект
  74. IProxy * proxy = FindProxyObject(actor);
  75. if (proxy)
  76. proxy->OnSyncTrace();
  77. #endif
  78. return false;
  79. }
  80. return true;
  81. }
  82. //array<Matrix> aMats(_FL_);
  83. //Устоновить мировую позицию
  84. inline void PhysRigidBodyActor::SetTransform(const Matrix & mtx)
  85. {
  86. Assert(PhysRigidBodyActorCheckMtx(mtx, null, GetFileName(), GetFileLine()));
  87. NxMat34 m;
  88. GetNxActor().setGlobalPose(Nx(m, mtx));
  89. }
  90. //Получить позицию и ориентацию в мире
  91. inline void PhysRigidBodyActor::GetTransform(Matrix & mtx) const
  92. {
  93. Nx(mtx, GetNxActor().getGlobalPose());
  94. Assert(PhysRigidBodyActorCheckMtx(mtx, actor, GetFileName(), GetFileLine()));
  95. }
  96. // Нормализовать глобальную матрицу чтобы не искажалась
  97. inline int PhysRigidBodyActor::Normalize()
  98. {
  99. if (!actor->isDynamic())
  100. return 0;
  101. Matrix mtx;
  102. GetTransform(mtx);
  103. Vector & x = mtx.vx;
  104. Vector & y = mtx.vy;
  105. Vector & z = mtx.vz;
  106. x = !(y ^ z);
  107. y = !(z ^ x);
  108. z = !z;
  109. SetTransform(mtx);
  110. return 1;
  111. }
  112. //Установить массу
  113. inline void PhysRigidBodyActor::SetMass(float mass)
  114. {
  115. if(!GetNxActor().isDynamic()) return;
  116. GetNxActor().updateMassFromShapes(mass, 0.0f);
  117. }
  118. //Установить массу
  119. float PhysRigidBodyActor::GetMass() const
  120. {
  121. return GetNxActor().getMass();
  122. }
  123. //Установить центр масс
  124. inline void PhysRigidBodyActor::SetCenterMass(const Vector & cm)
  125. {
  126. if(!GetNxActor().isDynamic()) return;
  127. GetNxActor().setCMassOffsetLocalPosition(Nx(cm));
  128. }
  129. //Установить центр масс
  130. inline Vector PhysRigidBodyActor::GetCenterMass() const
  131. {
  132. if(!GetNxActor().isDynamic())
  133. {
  134. return Nx(GetNxActor().getGlobalPosition());
  135. }
  136. return Nx(GetNxActor().getCMassLocalPosition());
  137. }
  138. //Установить группы
  139. inline void PhysRigidBodyActor::SetGroup(PhysicsCollisionGroup group)
  140. {
  141. this->group = group;
  142. if(!GetNxActor().isDynamic())
  143. {
  144. if(GetNxActor().getGroup() == phys_nocollision)
  145. {
  146. return;
  147. }
  148. }
  149. sys_SetGroup(group);
  150. }
  151. inline void PhysRigidBodyActor::sys_SetGroup(PhysicsCollisionGroup group)
  152. {
  153. NxActor & act = GetNxActor();
  154. act.setGroup((NxActorGroup)group);
  155. NxU32 count = act.getNbShapes();
  156. NxShape * const * shapes = act.getShapes();
  157. for(NxU32 i = 0; i < count; i++)
  158. {
  159. shapes[i]->setGroup((NxCollisionGroup)group);
  160. }
  161. if (act.isDynamic())
  162. act.wakeUp();
  163. }
  164. //Получить группы
  165. inline PhysicsCollisionGroup PhysRigidBodyActor::GetGroup() const
  166. {
  167. return (PhysicsCollisionGroup)GetNxActor().getGroup();
  168. }
  169. //Приложить силу к кости в заданной локальной точке
  170. inline void PhysRigidBodyActor::ApplyForce(const Vector & force, const Vector & localPosition)
  171. {
  172. #ifndef STOP_ASSERTS
  173. if (_isnan(force.x) || _isnan(force.y) || _isnan(force.z) || fabsf(force.x) > 100000.0f || fabsf(force.y) > 100000.0f || fabsf(force.z) > 100000.0f)
  174. {
  175. api->Trace("ApplyForce force: %.3f, %.3f, %.3f [%s, %d] ", force.x, force.y, force.z, GetFileName(), GetFileLine());
  176. Assert(false);
  177. }
  178. if (!(GetNxActor().isDynamic() && !bKinematic))
  179. {
  180. api->Trace("ApplyForce actor non dynamic or kinematic [%s, %d]", GetFileName(), GetFileLine());
  181. Assert(false);
  182. }
  183. #endif
  184. GetNxActor().addForceAtLocalPos(Nx(force), Nx(localPosition), NX_FORCE);
  185. }
  186. //Приложить силу к кости в заданной локальной точке
  187. inline void PhysRigidBodyActor::ApplyImpulse(const Vector & force, const Vector & localPosition)
  188. {
  189. #ifndef STOP_ASSERTS
  190. if (_isnan(force.x) || _isnan(force.y) || _isnan(force.z) || fabsf(force.x) > 100000.0f || fabsf(force.y) > 100000.0f || fabsf(force.z) > 100000.0f)
  191. {
  192. api->Trace("ApplyImpulse force: %.3f, %.3f, %.3f [%s, %d] ", force.x, force.y, force.z, GetFileName(), GetFileLine());
  193. Assert(false);
  194. }
  195. if (!(GetNxActor().isDynamic() && !bKinematic))
  196. {
  197. api->Trace("ApplyImpulse actor non dynamic or kinematic [%s, %d], GetFileName(), GetFileLine()");
  198. Assert(false);
  199. }
  200. #endif
  201. float k = GetNxActor().getMass();
  202. k = Clampf(k, 0.01f, 4.0f);
  203. GetNxActor().addForceAtLocalPos(Nx(force*k), Nx(localPosition), NX_IMPULSE);
  204. }
  205. //приложить вращающий момент в СК актера
  206. void PhysRigidBodyActor::ApplyLocalTorque(const Vector & torque)
  207. {
  208. #ifndef STOP_ASSERTS
  209. if (_isnan(torque.x) || _isnan(torque.y) || _isnan(torque.z))
  210. {
  211. api->Trace("ApplyLocalTorque torque: %.3f, %.3f, %.3f [%s, %d] ", torque.x, torque.y, torque.z, GetFileName(), GetFileLine());
  212. Assert(false);
  213. }
  214. if (!(GetNxActor().isDynamic() && !bKinematic))
  215. {
  216. api->Trace("ApplyLocalTorque actor non dynamic or kinematic [%s, %d], GetFileName(), GetFileLine()");
  217. Assert(false);
  218. }
  219. #endif
  220. GetNxActor().addLocalTorque(Nx(torque));
  221. }
  222. // установить затухание движения
  223. void PhysRigidBodyActor::SetMotionDamping ( float fDamping )
  224. {
  225. GetNxActor().setLinearDamping ( fDamping );
  226. GetNxActor().setAngularDamping ( fDamping );
  227. };
  228. void PhysRigidBodyActor::SetMotionDamping( float fLinDamping, float fAngDamping )
  229. {
  230. GetNxActor().setLinearDamping ( fLinDamping );
  231. GetNxActor().setAngularDamping ( fAngDamping );
  232. }
  233. // включить-выключить коллизию
  234. void PhysRigidBodyActor::EnableCollision ( bool bEnable )
  235. {
  236. NxActor & rActor = GetNxActor();
  237. if (bEnable)
  238. rActor.clearActorFlag(NX_AF_DISABLE_COLLISION);
  239. else
  240. rActor.raiseActorFlag(NX_AF_DISABLE_COLLISION);
  241. /*NxU32 iShapesCount = rActor.getNbShapes ();
  242. NxShape * const * pShapes = rActor.getShapes ();
  243. for ( NxU32 i = 0; i < iShapesCount; ++ i )
  244. {
  245. Assert ( pShapes[i] );
  246. pShapes[i]->setFlag ( NX_SF_DISABLE_COLLISION, !bEnable );
  247. };*/
  248. };
  249. // включить-выключить гравитацию
  250. void PhysRigidBodyActor::EnableGravity ( bool bEnable )
  251. {
  252. if (!bEnable)
  253. GetNxActor().raiseBodyFlag(NX_BF_DISABLE_GRAVITY);
  254. else
  255. GetNxActor().clearBodyFlag(NX_BF_DISABLE_GRAVITY);
  256. }
  257. // включить-выключить кинематическое поведение
  258. void PhysRigidBodyActor::EnableKinematic(bool bEnable)
  259. {
  260. bKinematic = bEnable;
  261. if (bEnable)
  262. GetNxActor().raiseBodyFlag(NX_BF_KINEMATIC);
  263. else
  264. GetNxActor().clearBodyFlag(NX_BF_KINEMATIC);
  265. }
  266. //Включить-выключить объект
  267. inline void PhysRigidBodyActor::Activate(bool isActive)
  268. {
  269. NxActor & a = GetNxActor();
  270. if(isActive)
  271. {
  272. if(a.isDynamic())
  273. {
  274. a.clearActorFlag(NX_AF_DISABLE_COLLISION);
  275. a.raiseBodyFlag(NX_BF_VISUALIZATION);
  276. a.clearActorFlag(NX_AF_DISABLE_RESPONSE);
  277. a.clearBodyFlag(NX_BF_FROZEN);
  278. a.wakeUp();
  279. }else{
  280. sys_SetGroup(group);
  281. }
  282. }else{
  283. if(a.isDynamic())
  284. {
  285. a.raiseActorFlag(NX_AF_DISABLE_COLLISION);
  286. a.clearBodyFlag(NX_BF_VISUALIZATION);
  287. a.raiseActorFlag(NX_AF_DISABLE_RESPONSE);
  288. a.raiseBodyFlag(NX_BF_FROZEN);
  289. a.wakeUp();
  290. }else{
  291. sys_SetGroup(phys_nocollision);
  292. }
  293. }
  294. }
  295. void PhysRigidBodyActor::SetFileLine(const char * filename, long fileline)
  296. {
  297. m_fileName = filename;
  298. m_fileLine = fileline;
  299. }
  300. //получить владение
  301. void PhysRigidBodyActor::SetNxActor(const char * filename, long fileline, NxActor* nxActor)
  302. {
  303. SetFileLine(filename, fileline);
  304. Assert(nxActor);
  305. actor = nxActor;
  306. if (actor->isDynamic())
  307. actor->setContactReportThreshold(0.6f);
  308. }
  309. //Получить ссылку на актёра
  310. inline NxActor & PhysRigidBodyActor::GetNxActor() const
  311. {
  312. Assert(actor);
  313. return *actor;
  314. }
  315. // установить материал
  316. void PhysRigidBodyActor::SetPhysMaterial(IPhysMaterial * material)
  317. {
  318. this->material = material;
  319. for (unsigned int i = 0; i < actor->getNbShapes(); ++i)
  320. actor->getShapes()[i]->setMaterial(material->GetIndex());
  321. }
  322. // получить материал
  323. IPhysMaterial * PhysRigidBodyActor::GetPhysMaterial() const
  324. {
  325. return material;
  326. }
  327. // получить линейную составляющую скорости
  328. Vector PhysRigidBodyActor::GetLinearVelocity() const
  329. {
  330. return Nx(actor->getLinearVelocity());
  331. }
  332. PhysPlane::PhysPlane(const char * filename, long fileline, const Vector & n, float d, IPhysicsScene * _scene) :
  333. IPhysPlane(_scene),
  334. rbactor(0.0f)
  335. {
  336. SetFileLine(filename, fileline);
  337. NxPlaneShapeDesc planeDesc;
  338. planeDesc.normal = Nx(n);
  339. planeDesc.d = (NxReal)d;
  340. planeDesc.userData = null;
  341. planeDesc.group = phys_world;
  342. NxActorDesc actorDesc;
  343. actorDesc.shapes.pushBack(&planeDesc);
  344. actorDesc.userData = this;
  345. actorDesc.group = phys_world;
  346. NxActor * nxActor = ((PhysicsScene *)scene)->Scene().createActor(actorDesc);
  347. Assert(nxActor);
  348. rbactor.SetNxActor(GetFileName(), GetFileLine(), nxActor);
  349. }
  350. PhysPlane::~PhysPlane()
  351. {
  352. scene->SceneChanged();
  353. }
  354. //Установить плоскость
  355. void PhysPlane::SetPlane(Plane & p)
  356. {
  357. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  358. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  359. NxPlaneShape * plane = shape->isPlane();
  360. plane->setPlane(Nx(p.n), (NxReal)p.d);
  361. }
  362. //Получить плоскость
  363. Plane PhysPlane::GetPlane()
  364. {
  365. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  366. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  367. NxPlaneShape * plane = shape->isPlane();
  368. NxPlane p = plane->getPlane();
  369. return Nx(p);
  370. }
  371. PhysBox::PhysBox(const char * filename, long fileline, const Vector & size, const Matrix & transform, bool isDynamic, float density, IPhysicsScene * _scene) :
  372. IPhysBox(_scene),
  373. rbactor(density)
  374. {
  375. SetFileLine(filename, fileline);
  376. NxActorDesc actorDesc;
  377. NxBodyDesc bodyDesc;
  378. NxBoxShapeDesc boxDesc;
  379. boxDesc.dimensions.set(size.x*0.5f, size.y*0.5f, size.z*0.5f);
  380. boxDesc.userData = null;
  381. boxDesc.group = phys_world;
  382. actorDesc.shapes.pushBack(&boxDesc);
  383. actorDesc.body = isDynamic ? &bodyDesc : null;
  384. actorDesc.density = density;
  385. Nx(actorDesc.globalPose, transform);
  386. actorDesc.userData = this;
  387. actorDesc.group = phys_world;
  388. //if ( _scene->IsHardware () )
  389. // actorDesc.managedHwSceneIndex = 1;
  390. NxActor * nxActor = ((PhysicsScene *)scene)->Scene().createActor(actorDesc);
  391. if (nxActor == NULL)
  392. {
  393. api->Trace("Error creating physical BOX !!!");
  394. api->Trace("Size: %f, %f, %f", size.x, size.y, size.z);
  395. api->Trace("Dynamic: %d", isDynamic);
  396. api->Trace("%f, %f, %f, %f", transform.m[0][0], transform.m[0][1], transform.m[0][2], transform.m[0][3]);
  397. api->Trace("%f, %f, %f, %f", transform.m[1][0], transform.m[1][1], transform.m[1][2], transform.m[1][3]);
  398. api->Trace("%f, %f, %f, %f", transform.m[2][0], transform.m[2][1], transform.m[2][2], transform.m[2][3]);
  399. api->Trace("%f, %f, %f, %f", transform.m[3][0], transform.m[3][1], transform.m[3][2], transform.m[3][3]);
  400. }
  401. Assert(nxActor);
  402. rbactor.SetNxActor(GetFileName(), GetFileLine(), nxActor);
  403. }
  404. PhysBox::~PhysBox()
  405. {
  406. scene->SceneChanged();
  407. }
  408. //Установить размер ящика
  409. void PhysBox::SetSize(const Vector & size)
  410. {
  411. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  412. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  413. NxBoxShape * box = shape->isBox();
  414. box->setDimensions(Nx(size*0.5f));
  415. }
  416. //Получить размер ящика
  417. Vector PhysBox::GetSize()
  418. {
  419. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  420. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  421. NxBoxShape * box = shape->isBox();
  422. Vector size = Nx(box->getDimensions())*2.0f;
  423. return size;
  424. }
  425. //Сфера
  426. PhysSphere::PhysSphere(const char * filename, long fileline, float radius, const Matrix & transform, bool isDynamic, float density, IPhysicsScene * _scene) :
  427. IPhysSphere(_scene),
  428. rbactor(density)
  429. {
  430. SetFileLine(filename, fileline);
  431. Assert(PhysRigidBodyActorCheckMtx(transform, null, GetFileName(), GetFileLine()));
  432. NxActorDesc actorDesc;
  433. NxBodyDesc bodyDesc;
  434. NxSphereShapeDesc sphereDesc;
  435. sphereDesc.radius = radius;
  436. sphereDesc.userData = null;
  437. sphereDesc.group = phys_world;
  438. actorDesc.shapes.pushBack(&sphereDesc);
  439. actorDesc.body = isDynamic ? &bodyDesc : null;
  440. actorDesc.density = density;
  441. Nx(actorDesc.globalPose, transform);
  442. actorDesc.userData = this;
  443. actorDesc.group = phys_world;
  444. NxActor * nxActor = ((PhysicsScene *)scene)->Scene().createActor(actorDesc);
  445. Assert(nxActor);
  446. rbactor.SetNxActor(GetFileName(), GetFileLine(), nxActor);
  447. }
  448. PhysSphere::~PhysSphere()
  449. {
  450. scene->SceneChanged();
  451. }
  452. //Установить радиус
  453. void PhysSphere::SetRadius(float radius)
  454. {
  455. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  456. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  457. NxSphereShape * sphere = shape->isSphere();
  458. sphere->setRadius(radius);
  459. }
  460. //Получить радиус
  461. float PhysSphere::GetRadius()
  462. {
  463. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  464. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  465. NxSphereShape * sphere = shape->isSphere();
  466. return (float)sphere->getRadius();
  467. }
  468. //Капсула
  469. PhysCapsule::PhysCapsule(const char * filename, long fileline, float radius, float height, const Matrix & transform, bool isDynamic, float density, IPhysicsScene * _scene) :
  470. IPhysCapsule(_scene),
  471. rbactor(density)
  472. {
  473. SetFileLine(filename, fileline);
  474. Assert(PhysRigidBodyActorCheckMtx(transform, null, GetFileName(), GetFileLine()));
  475. NxActorDesc actorDesc;
  476. NxBodyDesc bodyDesc;
  477. NxCapsuleShapeDesc capsuleDesc;
  478. capsuleDesc.radius = radius;
  479. capsuleDesc.height = height;
  480. capsuleDesc.userData = null;
  481. capsuleDesc.group = phys_world;
  482. actorDesc.shapes.pushBack(&capsuleDesc);
  483. actorDesc.body = isDynamic ? &bodyDesc : null;
  484. actorDesc.density = density;
  485. Nx(actorDesc.globalPose, transform);
  486. actorDesc.userData = this;
  487. actorDesc.group = phys_world;
  488. NxActor * nxActor = ((PhysicsScene *)scene)->Scene().createActor(actorDesc);
  489. Assert(nxActor);
  490. rbactor.SetNxActor(GetFileName(), GetFileLine(), nxActor);
  491. }
  492. PhysCapsule::~PhysCapsule()
  493. {
  494. scene->SceneChanged();
  495. }
  496. //Установить радиус
  497. void PhysCapsule::SetRadius(float radius)
  498. {
  499. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  500. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  501. NxCapsuleShape * capsule = shape->isCapsule();
  502. capsule->setRadius(radius);
  503. }
  504. //Получить радиус
  505. float PhysCapsule::GetRadius()
  506. {
  507. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  508. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  509. NxCapsuleShape * capsule = shape->isCapsule();
  510. return (float)capsule->getRadius();
  511. }
  512. //Установить высоту
  513. void PhysCapsule::SetHeight(float height)
  514. {
  515. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  516. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  517. NxCapsuleShape * capsule = shape->isCapsule();
  518. capsule->setHeight(height);
  519. }
  520. //Получить высоту
  521. float PhysCapsule::GetHeight()
  522. {
  523. Assert(rbactor.GetNxActor().getNbShapes() == 1);
  524. NxShape * shape = rbactor.GetNxActor().getShapes()[0];
  525. NxCapsuleShape * capsule = shape->isCapsule();
  526. return (float)capsule->getHeight();
  527. }
  528. //Объект состоящий из сетки треугольников
  529. PhysMesh::PhysMesh(const char * filename, long fileline, const IPhysicsScene::MeshInit * meshes, dword numMeshes, bool isDynamic, float density, IPhysicsScene * _scene) :
  530. IPhysMesh(_scene),
  531. rbactor(density),
  532. refMeshes(_FL_)
  533. {
  534. SetFileLine(filename, fileline);
  535. AssertCoreThread
  536. NxActorDesc actorDesc;
  537. actorDesc.shapes.reserve(numMeshes);
  538. static NxTriangleMeshShapeDesc static_shapeDesc[16];
  539. NxTriangleMeshShapeDesc * descs = static_shapeDesc;
  540. array<NxTriangleMeshShapeDesc> dyn_shapeDesc(_FL_);
  541. if(numMeshes > ARRSIZE(static_shapeDesc))
  542. {
  543. dyn_shapeDesc.AddElements(numMeshes);
  544. descs = dyn_shapeDesc.GetBuffer();
  545. }
  546. for(long i = 0; i < (long)numMeshes; i++)
  547. {
  548. PhysTriangleMesh * physMesh = (PhysTriangleMesh *)meshes[i].mesh;
  549. physMesh->AddRef();
  550. refMeshes.Add(physMesh);
  551. NxTriangleMeshShapeDesc & shapeDesc = descs[i];
  552. Assert(meshes[i].mesh);
  553. shapeDesc.shapeFlags |= NX_SF_FEATURE_INDICES;
  554. shapeDesc.meshData = physMesh->TriangleMesh();
  555. Nx(shapeDesc.localPose, meshes[i].mtx);
  556. shapeDesc.userData = null;
  557. actorDesc.group = phys_world;
  558. actorDesc.shapes.pushBack(&shapeDesc);
  559. }
  560. NxBodyDesc bodyDesc;
  561. actorDesc.body = isDynamic ? &bodyDesc : null;
  562. actorDesc.density = density;
  563. actorDesc.userData = this;
  564. actorDesc.group = phys_world;
  565. rbactor.SetNxActor(GetFileName(), GetFileLine(), ((PhysicsScene *)scene)->Scene().createActor(actorDesc));
  566. if (isDynamic)
  567. EnableKinematic(true);
  568. }
  569. void PhysMesh::EnableCollision(bool bEnable)
  570. {
  571. //Assert(!(bEnable && rbactor.GetNxActor().isDynamic()));
  572. rbactor.EnableCollision(bEnable);
  573. }
  574. PhysMesh::~PhysMesh()
  575. {
  576. rbactor.Release();
  577. for (int i=0; i<refMeshes.Len(); i++)
  578. refMeshes[i]->Release();
  579. refMeshes.DelAll();
  580. scene->SceneChanged();
  581. }
  582. void PhysMesh::EnableKinematic(bool bEnable)
  583. {
  584. if (!bEnable)
  585. api->Trace("PhysMesh Error: Someone tryed to disable kinematic flag for PhysMesh!!");
  586. rbactor.EnableKinematic(true);
  587. }
  588. PhysCombined::ObjectDesc::ObjectDesc() : descs(_FL_)
  589. {
  590. }
  591. PhysCombined::ObjectDesc::~ObjectDesc()
  592. {
  593. for(long i = 0; i < descs; i++)
  594. {
  595. delete descs[i];
  596. }
  597. }
  598. //Комбинированный объект
  599. PhysCombined::PhysCombined(const char * filename, long fileline, const Matrix & transform, bool isDynamic, float density, IPhysicsScene * _scene) :
  600. IPhysCombined(_scene),
  601. rbactor(density)
  602. {
  603. SetFileLine(filename, fileline);
  604. Assert(PhysRigidBodyActorCheckMtx(transform, null, GetFileName(), GetFileLine()));
  605. desc = NEW ObjectDesc();
  606. Nx(desc->actorDesc.globalPose, transform);
  607. desc->actorDesc.body = isDynamic ? &desc->bodyDesc : null;
  608. desc->actorDesc.density = density;
  609. desc->actorDesc.userData = this;
  610. desc->actorDesc.group = phys_world;
  611. }
  612. PhysCombined::~PhysCombined()
  613. {
  614. if(desc)
  615. {
  616. delete desc;
  617. desc = null;
  618. }
  619. scene->SceneChanged();
  620. }
  621. //Добавить ящик
  622. void PhysCombined::AddBox(const Vector & size, const Matrix & transform)
  623. {
  624. Assert(PhysRigidBodyActorCheckMtx(transform, null, GetFileName(), GetFileLine()));
  625. Assert(desc);
  626. NxBoxShapeDesc * boxDesc = NEW NxBoxShapeDesc;
  627. boxDesc->dimensions.set(size.x*0.5f, size.y*0.5f, size.z*0.5f);
  628. Nx(boxDesc->localPose, transform);
  629. boxDesc->userData = null;
  630. boxDesc->group = phys_world;
  631. desc->actorDesc.shapes.pushBack(boxDesc);
  632. desc->descs.Add(boxDesc);
  633. }
  634. //Добавить шар
  635. void PhysCombined::AddSphere(float radius, const Matrix & transform)
  636. {
  637. Assert(PhysRigidBodyActorCheckMtx(transform, null, GetFileName(), GetFileLine()));
  638. Assert(desc);
  639. NxSphereShapeDesc * sphereDesc = NEW NxSphereShapeDesc;
  640. sphereDesc->radius = radius;
  641. Nx(sphereDesc->localPose, transform);
  642. sphereDesc->userData = null;
  643. sphereDesc->group = phys_world;
  644. desc->actorDesc.shapes.pushBack(sphereDesc);
  645. desc->descs.Add(sphereDesc);
  646. }
  647. //Добавить капсулу
  648. void PhysCombined::AddCapsule(float radius, float height, const Matrix & transform)
  649. {
  650. Assert(PhysRigidBodyActorCheckMtx(transform, null, GetFileName(), GetFileLine()));
  651. Assert(desc);
  652. NxCapsuleShapeDesc * capsuleDesc = NEW NxCapsuleShapeDesc;
  653. capsuleDesc->radius = radius;
  654. capsuleDesc->height = height;
  655. Nx(capsuleDesc->localPose, transform);
  656. capsuleDesc->userData = null;
  657. capsuleDesc->group = phys_world;
  658. desc->actorDesc.shapes.pushBack(capsuleDesc);
  659. desc->descs.Add(capsuleDesc);
  660. }
  661. //Установить массу элемента
  662. bool PhysCombined::SetMass(unsigned int index, float mass)
  663. {
  664. Assert(desc);
  665. if ( index >= desc->descs.Size() ) return false;
  666. desc->descs[index]->mass = mass;
  667. return true;
  668. }
  669. //Получить текущее число фигур для билда
  670. unsigned int PhysCombined::GetCountForBuild()
  671. {
  672. Assert(desc);
  673. return desc->descs.Size();
  674. }
  675. //Сконструировать объект
  676. void PhysCombined::Build()
  677. {
  678. Assert(desc);
  679. Assert(desc->descs > 0);
  680. NxActor * nxActor = ((PhysicsScene *)scene)->Scene().createActor(desc->actorDesc);
  681. Assert(nxActor);
  682. rbactor.SetNxActor(GetFileName(), GetFileLine(), nxActor);
  683. delete desc;
  684. desc = null;
  685. }
  686. //Получить количество фигур
  687. long PhysCombined::GetCount()
  688. {
  689. if(desc) return 0;
  690. return (long)rbactor.GetNxActor().getNbShapes();
  691. }
  692. //Получить локальную позицию
  693. bool PhysCombined::SetLocalTransform(long index, const Matrix & transform)
  694. {
  695. if(desc) return false;
  696. if(index < 0 || index >= (long)rbactor.GetNxActor().getNbShapes()) return false;
  697. NxMat34 mtx;
  698. rbactor.GetNxActor().getShapes()[index]->setLocalPose(Nx(mtx, transform));
  699. return true;
  700. }
  701. //Установить локальную позицию
  702. bool PhysCombined::GetLocalTransform(long index, Matrix & transform)
  703. {
  704. if(desc) return false;
  705. if(index < 0 || index >= (long)rbactor.GetNxActor().getNbShapes()) return false;
  706. Nx(transform, rbactor.GetNxActor().getShapes()[index]->getLocalPose());
  707. return true;
  708. }
  709. //Получить тип
  710. IPhysCombined::Type PhysCombined::GetType(long index)
  711. {
  712. if(desc) return t_error;
  713. if(index < 0 || index >= (long)rbactor.GetNxActor().getNbShapes()) return t_error;
  714. NxShape * shp = rbactor.GetNxActor().getShapes()[index];
  715. if(!shp) return t_error;
  716. switch(shp->getType())
  717. {
  718. case NX_SHAPE_SPHERE:
  719. return t_sphere;
  720. case NX_SHAPE_BOX:
  721. return t_box;
  722. case NX_SHAPE_CAPSULE:
  723. return t_capsule;
  724. }
  725. return t_error;
  726. }
  727. //Получить параметры ящика
  728. bool PhysCombined::GetBox(long index, Vector & size)
  729. {
  730. if(desc) return false;
  731. if(index < 0 || index >= (long)rbactor.GetNxActor().getNbShapes()) return false;
  732. NxBoxShape * shp = rbactor.GetNxActor().getShapes()[index]->isBox();
  733. if(!shp) return false;
  734. size = Nx(shp->getDimensions());
  735. return true;
  736. }
  737. //Получить параметры шара
  738. bool PhysCombined::GetSphere(long index, float & radius)
  739. {
  740. if(desc) return false;
  741. if(index < 0 || index >= (long)rbactor.GetNxActor().getNbShapes()) return false;
  742. NxSphereShape * shp = rbactor.GetNxActor().getShapes()[index]->isSphere();
  743. if(!shp) return false;
  744. radius = float(shp->getRadius());
  745. return true;
  746. }
  747. //Получить параметры капсулы
  748. bool PhysCombined::GetCapsule(long index, float & radius, float & height)
  749. {
  750. if(desc) return false;
  751. if(index < 0 || index >= (long)rbactor.GetNxActor().getNbShapes()) return false;
  752. NxCapsuleShape * shp = rbactor.GetNxActor().getShapes()[index]->isCapsule();
  753. if(!shp) return false;
  754. radius = float(shp->getRadius());
  755. height = float(shp->getHeight());
  756. return true;
  757. }
  758. //Установить глобальную позицию
  759. bool PhysCombined::SetGlobalTransform(unsigned int index, const Matrix & transform)
  760. {
  761. if (desc) return false;
  762. if (index >= rbactor.GetNxActor().getNbShapes()) return false;
  763. NxMat34 mtx;
  764. rbactor.GetNxActor().getShapes()[index]->setGlobalPose(Nx(mtx, transform));
  765. return true;
  766. }
  767. //Получить глобальную позицию
  768. bool PhysCombined::GetGlobalTransform(unsigned int index, Matrix & transform)
  769. {
  770. if (desc) return false;
  771. if (index >= rbactor.GetNxActor().getNbShapes()) return false;
  772. Nx(transform, rbactor.GetNxActor().getShapes()[index]->getGlobalPose());
  773. return true;
  774. }
  775. //Включить/выключить коллизии
  776. void PhysCombined::EnableCollision(unsigned int index, bool enable)
  777. {
  778. if (desc)
  779. {
  780. if (index >= desc->descs.Size())
  781. return;
  782. if (enable)
  783. desc->descs[index]->shapeFlags &= ~NX_SF_DISABLE_COLLISION;
  784. else
  785. desc->descs[index]->shapeFlags |= NX_SF_DISABLE_COLLISION;
  786. }
  787. else
  788. {
  789. if (index >= rbactor.GetNxActor().getNbShapes()) return;
  790. rbactor.GetNxActor().getShapes()[index]->setFlag(NX_SF_DISABLE_COLLISION, !enable);
  791. }
  792. }
  793. //Включить/выключить коллизию для актера
  794. void PhysCombined::EnableCollision(bool enable)
  795. {
  796. if (desc)
  797. for (unsigned int i = 0; i < GetCountForBuild(); ++i)
  798. EnableCollision(i, enable);
  799. else
  800. {
  801. if (enable)
  802. rbactor.GetNxActor().clearActorFlag(NX_AF_DISABLE_COLLISION);
  803. else
  804. rbactor.GetNxActor().raiseActorFlag(NX_AF_DISABLE_COLLISION);
  805. }
  806. }
  807. //Включить/выключить реакцию на коллизии
  808. void PhysCombined::EnableResponse(unsigned int index, bool enable)
  809. {
  810. if (desc)
  811. {
  812. if (index >= desc->descs.Size())
  813. return;
  814. if (enable)
  815. desc->descs[index]->shapeFlags &= ~NX_SF_DISABLE_RESPONSE;
  816. else
  817. desc->descs[index]->shapeFlags |= NX_SF_DISABLE_RESPONSE;
  818. }
  819. else
  820. {
  821. if (index >= rbactor.GetNxActor().getNbShapes()) return;
  822. rbactor.GetNxActor().getShapes()[index]->setFlag(NX_SF_DISABLE_RESPONSE, !enable);
  823. }
  824. }
  825. //Включить/выключить рэйкаст
  826. void PhysCombined::EnableRaycast(unsigned int index, bool enable)
  827. {
  828. if (desc)
  829. {
  830. if (index >= desc->descs.Size())
  831. return;
  832. if (enable)
  833. desc->descs[index]->shapeFlags &= ~NX_SF_DISABLE_RAYCASTING;
  834. else
  835. desc->descs[index]->shapeFlags |= NX_SF_DISABLE_RAYCASTING;
  836. }
  837. else
  838. {
  839. if (index >= rbactor.GetNxActor().getNbShapes()) return;
  840. rbactor.GetNxActor().getShapes()[index]->setFlag(NX_SF_DISABLE_RAYCASTING, !enable);
  841. }
  842. }
  843. //Включить/выключить визуализацию
  844. void PhysCombined::EnableVisualization(unsigned int index, bool enable)
  845. {
  846. if (desc)
  847. {
  848. if (index >= desc->descs.Size())
  849. return;
  850. if (enable)
  851. desc->descs[index]->shapeFlags |= NX_SF_VISUALIZATION;
  852. else
  853. desc->descs[index]->shapeFlags &= ~NX_SF_VISUALIZATION;
  854. }
  855. else
  856. {
  857. if (index >= rbactor.GetNxActor().getNbShapes()) return;
  858. rbactor.GetNxActor().getShapes()[index]->setFlag(NX_SF_VISUALIZATION, enable);
  859. }
  860. }
  861. //Включить/выключить визуализацию для актера
  862. void PhysCombined::EnableVisualization(bool enable)
  863. {
  864. if (desc)
  865. for (unsigned int i = 0; i < GetCountForBuild(); ++i)
  866. EnableCollision(i, enable);
  867. else
  868. {
  869. if (enable)
  870. rbactor.GetNxActor().raiseBodyFlag(NX_BF_VISUALIZATION);
  871. else
  872. rbactor.GetNxActor().clearBodyFlag(NX_BF_VISUALIZATION);
  873. }
  874. }
  875. // включить-выключить гравитацию
  876. void PhysCombined::EnableGravity( bool bEnable )
  877. {
  878. if (desc)
  879. {
  880. Assert(!"can't change gravity state - no actor created");
  881. }
  882. else
  883. {
  884. if (bEnable)
  885. rbactor.GetNxActor().clearBodyFlag(NX_BF_DISABLE_GRAVITY);
  886. else
  887. rbactor.GetNxActor().raiseBodyFlag(NX_BF_DISABLE_GRAVITY);
  888. }
  889. }
  890. // включить-выключить кинематическое поведение
  891. void PhysCombined::EnableKinematic(bool bEnable)
  892. {
  893. rbactor.EnableKinematic(bEnable);
  894. }
  895. // установить кол-во итерация солвера для актера
  896. void PhysCombined::SetSolverIterations(unsigned int count)
  897. {
  898. rbactor.GetNxActor().setSolverIterationCount(count);
  899. }
  900. //Протестировать на пересечение с лучом
  901. bool PhysCombined::Raycast(unsigned int index, const Vector& from, const Vector& to, RaycastResult * details)
  902. {
  903. if (desc) return false;
  904. if (index >= rbactor.GetNxActor().getNbShapes()) return false;
  905. NxRay worldRay;
  906. NxReal maxDist;
  907. NxU32 hintFlags = NX_RAYCAST_IMPACT | NX_RAYCAST_NORMAL | NX_RAYCAST_DISTANCE | NX_RAYCAST_MATERIAL;
  908. NxRaycastHit hit;
  909. bool firstHit = details == null;
  910. worldRay.orig = Nx(from);
  911. worldRay.dir = Nx(to-from);
  912. maxDist = worldRay.dir.normalize();
  913. bool result = rbactor.GetNxActor().getShapes()[index]->raycast(worldRay, maxDist, hintFlags, hit, firstHit);
  914. if (details && result)
  915. {
  916. details->distance = hit.distance;
  917. details->mtl = hit.materialIndex;
  918. details->position = Nx(hit.worldImpact);
  919. details->normal = Nx(hit.worldNormal);
  920. }
  921. return result;
  922. }
  923. //Протестировать элемент на пересечение с боксом
  924. bool PhysCombined::OverlapBox(unsigned int index, const Vector& size, const Matrix& transform )
  925. {
  926. if (desc) return false;
  927. if (index >= rbactor.GetNxActor().getNbShapes()) return false;
  928. NxMat33 rot;
  929. NxBox box(Nx(transform.pos), Nx(size*0.5f), Nx(rot, transform));
  930. return rbactor.GetNxActor().getShapes()[index]->checkOverlapOBB(box);
  931. }
  932. //Протестировать элемент на пересечение со сферой
  933. bool PhysCombined::OverlapSphere(unsigned int index, const Vector& center, float radius)
  934. {
  935. if (desc) return false;
  936. if (index >= rbactor.GetNxActor().getNbShapes()) return false;
  937. NxSphere sph(Nx(center), radius);
  938. return rbactor.GetNxActor().getShapes()[index]->checkOverlapSphere(sph);
  939. }
  940. PhysRigidBodyConnector::PhysRigidBodyConnector(const char * filename, long fileline, IPhysicsScene * _scene, IPhysRigidBody * _left, IPhysRigidBody * _right, float brokeForce) :
  941. IPhysRigidBodyConnector(_scene)
  942. {
  943. SetFileLine(filename, fileline);
  944. left = _left;
  945. right = _right;
  946. Assert(left);
  947. Assert(right);
  948. NxFixedJointDesc fixedDesc;
  949. PhysInternal nxFirst;
  950. PhysInternal nxSecond;
  951. _left->GetInternals(nxFirst);
  952. _right->GetInternals(nxSecond);
  953. fixedDesc.actor[0] = nxFirst.actor;
  954. fixedDesc.actor[1] = nxSecond.actor;
  955. joint = (NxFixedJoint *)((PhysicsScene *)scene)->Scene().createJoint(fixedDesc);
  956. Assert(joint);
  957. joint->setBreakable((NxReal)brokeForce, (NxReal)brokeForce*0.105f);
  958. }
  959. PhysRigidBodyConnector::~PhysRigidBodyConnector()
  960. {
  961. ((PhysicsScene *)scene)->Scene().releaseJoint(*joint);
  962. }
  963. //Сломано соединение или нет
  964. bool PhysRigidBodyConnector::IsBroke()
  965. {
  966. return joint->getState() == NX_JS_BROKEN;
  967. }
  968. //Поставить обработчик
  969. void PhysRigidBodyConnector::SetEventHandler(BrokeEvent * event)
  970. {
  971. Assert(false);
  972. }
  973. //Получить первый объект к которому присоеденены
  974. IPhysRigidBody * PhysRigidBodyConnector::GetLeft()
  975. {
  976. return left;
  977. }
  978. //Получить второй объект к которому присоеденены
  979. IPhysRigidBody * PhysRigidBodyConnector::GetRight()
  980. {
  981. return right;
  982. }