tsCollision.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "ts/tsShapeInstance.h"
  24. #include "ts/tsMaterialList.h"
  25. #include "scene/sceneObject.h"
  26. #include "collision/convex.h"
  27. #include "collision/collision.h"
  28. #include "T3D/tsStatic.h" // TODO: We shouldn't have this dependancy!
  29. #include "T3D/physics/physicsPlugin.h"
  30. #include "T3D/physics/physicsCollision.h"
  31. #include "collision/concretePolyList.h"
  32. #include "collision/vertexPolyList.h"
  33. #include "platform/profiler.h"
  34. #include "opcode/Opcode.h"
  35. #include "opcode/Ice/IceAABB.h"
  36. #include "opcode/Ice/IcePoint.h"
  37. #include "opcode/OPC_AABBTree.h"
  38. #include "opcode/OPC_AABBCollider.h"
  39. static bool gOpcodeInitialized = false;
  40. //-------------------------------------------------------------------------------------
  41. // Collision methods
  42. //-------------------------------------------------------------------------------------
  43. bool TSShapeInstance::buildPolyList(AbstractPolyList * polyList, S32 dl)
  44. {
  45. // if dl==-1, nothing to do
  46. if (dl==-1)
  47. return false;
  48. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::buildPolyList");
  49. // get subshape and object detail
  50. const TSDetail * detail = &mShape->details[dl];
  51. S32 ss = detail->subShapeNum;
  52. S32 od = detail->objectDetailNum;
  53. // This detail does not have any geometry.
  54. if ( ss < 0 )
  55. return false;
  56. // nothing emitted yet...
  57. bool emitted = false;
  58. U32 surfaceKey = 0;
  59. S32 start = mShape->subShapeFirstObject[ss];
  60. S32 end = mShape->subShapeNumObjects[ss] + start;
  61. if (start<end)
  62. {
  63. MatrixF initialMat;
  64. Point3F initialScale;
  65. polyList->getTransform(&initialMat,&initialScale);
  66. // set up for first object's node
  67. MatrixF mat;
  68. MatrixF scaleMat(true);
  69. F32* p = scaleMat;
  70. p[0] = initialScale.x;
  71. p[5] = initialScale.y;
  72. p[10] = initialScale.z;
  73. const MatrixF *previousMat = &mMeshObjects[start].getTransform();
  74. mat.mul(initialMat,scaleMat);
  75. mat.mul(*previousMat);
  76. polyList->setTransform(&mat,Point3F(1, 1, 1));
  77. // run through objects and collide
  78. for (S32 i=start; i<end; i++)
  79. {
  80. MeshObjectInstance * mesh = &mMeshObjects[i];
  81. if (od >= mesh->object->numMeshes)
  82. continue;
  83. if (&mesh->getTransform() != previousMat)
  84. {
  85. // different node from before, set up for this node
  86. previousMat = &mesh->getTransform();
  87. if (previousMat != NULL)
  88. {
  89. mat.mul(initialMat,scaleMat);
  90. mat.mul(*previousMat);
  91. polyList->setTransform(&mat,Point3F(1, 1, 1));
  92. }
  93. }
  94. // collide...
  95. emitted |= mesh->buildPolyList(od,polyList,surfaceKey,mMaterialList);
  96. }
  97. // restore original transform...
  98. polyList->setTransform(&initialMat,initialScale);
  99. }
  100. return emitted;
  101. }
  102. bool TSShapeInstance::getFeatures(const MatrixF& mat, const Point3F& n, ConvexFeature* cf, S32 dl)
  103. {
  104. // if dl==-1, nothing to do
  105. if (dl==-1)
  106. return false;
  107. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::buildPolyList");
  108. // get subshape and object detail
  109. const TSDetail * detail = &mShape->details[dl];
  110. S32 ss = detail->subShapeNum;
  111. S32 od = detail->objectDetailNum;
  112. // nothing emitted yet...
  113. bool emitted = false;
  114. U32 surfaceKey = 0;
  115. S32 start = mShape->subShapeFirstObject[ss];
  116. S32 end = mShape->subShapeNumObjects[ss] + start;
  117. if (start<end)
  118. {
  119. MatrixF final;
  120. const MatrixF* previousMat = &mMeshObjects[start].getTransform();
  121. final.mul(mat, *previousMat);
  122. // run through objects and collide
  123. for (S32 i=start; i<end; i++)
  124. {
  125. MeshObjectInstance * mesh = &mMeshObjects[i];
  126. if (od >= mesh->object->numMeshes)
  127. continue;
  128. if (&mesh->getTransform() != previousMat)
  129. {
  130. previousMat = &mesh->getTransform();
  131. final.mul(mat, *previousMat);
  132. }
  133. emitted |= mesh->getFeatures(od, final, n, cf, surfaceKey);
  134. }
  135. }
  136. return emitted;
  137. }
  138. bool TSShapeInstance::castRay(const Point3F & a, const Point3F & b, RayInfo * rayInfo, S32 dl)
  139. {
  140. // if dl==-1, nothing to do
  141. if (dl==-1)
  142. return false;
  143. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::castRay");
  144. // get subshape and object detail
  145. const TSDetail * detail = &mShape->details[dl];
  146. S32 ss = detail->subShapeNum;
  147. S32 od = detail->objectDetailNum;
  148. // This detail has no geometry to hit.
  149. if ( ss < 0 )
  150. return false;
  151. S32 start = mShape->subShapeFirstObject[ss];
  152. S32 end = mShape->subShapeNumObjects[ss] + start;
  153. RayInfo saveRay;
  154. saveRay.t = 1.0f;
  155. const MatrixF * saveMat = NULL;
  156. bool found = false;
  157. if (start<end)
  158. {
  159. Point3F ta, tb;
  160. // set up for first object's node
  161. MatrixF mat;
  162. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  163. mat = *previousMat;
  164. mat.inverse();
  165. mat.mulP(a,&ta);
  166. mat.mulP(b,&tb);
  167. // run through objects and collide
  168. for (S32 i=start; i<end; i++)
  169. {
  170. MeshObjectInstance * mesh = &mMeshObjects[i];
  171. if (od >= mesh->object->numMeshes)
  172. continue;
  173. if (&mesh->getTransform() != previousMat)
  174. {
  175. // different node from before, set up for this node
  176. previousMat = &mesh->getTransform();
  177. if (previousMat != NULL)
  178. {
  179. mat = *previousMat;
  180. mat.inverse();
  181. mat.mulP(a,&ta);
  182. mat.mulP(b,&tb);
  183. }
  184. }
  185. // collide...
  186. if (mesh->castRay(od,ta,tb,rayInfo, mMaterialList))
  187. {
  188. if (!rayInfo)
  189. return true;
  190. if (rayInfo->t <= saveRay.t)
  191. {
  192. saveRay = *rayInfo;
  193. saveMat = previousMat;
  194. }
  195. found = true;
  196. }
  197. }
  198. }
  199. // collide with any skins for this detail level...
  200. // TODO: if ever...
  201. // finalize the deal...
  202. if (found)
  203. {
  204. *rayInfo = saveRay;
  205. saveMat->mulV(rayInfo->normal);
  206. rayInfo->point = b-a;
  207. rayInfo->point *= rayInfo->t;
  208. rayInfo->point += a;
  209. }
  210. return found;
  211. }
  212. bool TSShapeInstance::castRayRendered(const Point3F & a, const Point3F & b, RayInfo * rayInfo, S32 dl)
  213. {
  214. // if dl==-1, nothing to do
  215. if (dl==-1)
  216. return false;
  217. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::castRayRendered");
  218. // get subshape and object detail
  219. const TSDetail * detail = &mShape->details[dl];
  220. S32 ss = detail->subShapeNum;
  221. S32 od = detail->objectDetailNum;
  222. if ( ss == -1 )
  223. return false;
  224. S32 start = mShape->subShapeFirstObject[ss];
  225. S32 end = mShape->subShapeNumObjects[ss] + start;
  226. RayInfo saveRay;
  227. saveRay.t = 1.0f;
  228. const MatrixF * saveMat = NULL;
  229. bool found = false;
  230. if (start<end)
  231. {
  232. Point3F ta, tb;
  233. // set up for first object's node
  234. MatrixF mat;
  235. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  236. mat = *previousMat;
  237. mat.inverse();
  238. mat.mulP(a,&ta);
  239. mat.mulP(b,&tb);
  240. // run through objects and collide
  241. for (S32 i=start; i<end; i++)
  242. {
  243. MeshObjectInstance * mesh = &mMeshObjects[i];
  244. if (od >= mesh->object->numMeshes)
  245. continue;
  246. if (&mesh->getTransform() != previousMat)
  247. {
  248. // different node from before, set up for this node
  249. previousMat = &mesh->getTransform();
  250. if (previousMat != NULL)
  251. {
  252. mat = *previousMat;
  253. mat.inverse();
  254. mat.mulP(a,&ta);
  255. mat.mulP(b,&tb);
  256. }
  257. }
  258. // collide...
  259. if (mesh->castRayRendered(od,ta,tb,rayInfo, mMaterialList))
  260. {
  261. if (!rayInfo)
  262. return true;
  263. if (rayInfo->t <= saveRay.t)
  264. {
  265. saveRay = *rayInfo;
  266. saveMat = previousMat;
  267. }
  268. found = true;
  269. }
  270. }
  271. }
  272. // collide with any skins for this detail level...
  273. // TODO: if ever...
  274. // finalize the deal...
  275. if (found)
  276. {
  277. *rayInfo = saveRay;
  278. saveMat->mulV(rayInfo->normal);
  279. rayInfo->point = b-a;
  280. rayInfo->point *= rayInfo->t;
  281. rayInfo->point += a;
  282. }
  283. return found;
  284. }
  285. Point3F TSShapeInstance::support(const Point3F & v, S32 dl)
  286. {
  287. // if dl==-1, nothing to do
  288. AssertFatal(dl != -1, "Error, should never try to collide with a non-existant detail level!");
  289. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::support");
  290. // get subshape and object detail
  291. const TSDetail * detail = &mShape->details[dl];
  292. S32 ss = detail->subShapeNum;
  293. S32 od = detail->objectDetailNum;
  294. S32 start = mShape->subShapeFirstObject[ss];
  295. S32 end = mShape->subShapeNumObjects[ss] + start;
  296. F32 currMaxDP = -1e9f;
  297. Point3F currSupport = Point3F(0, 0, 0);
  298. const MatrixF * previousMat = NULL;
  299. MatrixF mat;
  300. if (start<end)
  301. {
  302. Point3F va;
  303. // set up for first object's node
  304. previousMat = &mMeshObjects[start].getTransform();
  305. mat = *previousMat;
  306. mat.inverse();
  307. // run through objects and collide
  308. for (S32 i=start; i<end; i++)
  309. {
  310. MeshObjectInstance * mesh = &mMeshObjects[i];
  311. if (od >= mesh->object->numMeshes)
  312. continue;
  313. TSMesh* physMesh = mesh->getMesh(od);
  314. if (physMesh && !mesh->forceHidden && mesh->visible > 0.01f)
  315. {
  316. // collide...
  317. if (&mesh->getTransform() != previousMat)
  318. {
  319. // different node from before, set up for this node
  320. previousMat = &mesh->getTransform();
  321. mat = *previousMat;
  322. mat.inverse();
  323. }
  324. mat.mulV(v, &va);
  325. physMesh->support(mesh->frame, va, &currMaxDP, &currSupport);
  326. }
  327. }
  328. }
  329. if (currMaxDP != -1e9f)
  330. {
  331. previousMat->mulP(currSupport);
  332. return currSupport;
  333. }
  334. else
  335. {
  336. return Point3F(0, 0, 0);
  337. }
  338. }
  339. void TSShapeInstance::computeBounds(S32 dl, Box3F & bounds)
  340. {
  341. // if dl==-1, nothing to do
  342. if (dl==-1)
  343. return;
  344. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::computeBounds");
  345. // get subshape and object detail
  346. const TSDetail * detail = &mShape->details[dl];
  347. S32 ss = detail->subShapeNum;
  348. S32 od = detail->objectDetailNum;
  349. // use shape bounds for imposter details
  350. if (ss < 0)
  351. {
  352. bounds = mShape->mBounds;
  353. return;
  354. }
  355. S32 start = mShape->subShapeFirstObject[ss];
  356. S32 end = mShape->subShapeNumObjects[ss] + start;
  357. // run through objects and updating bounds as we go
  358. bounds.minExtents.set( 10E30f, 10E30f, 10E30f);
  359. bounds.maxExtents.set(-10E30f,-10E30f,-10E30f);
  360. Box3F box;
  361. for (S32 i=start; i<end; i++)
  362. {
  363. MeshObjectInstance * mesh = &mMeshObjects[i];
  364. if (od >= mesh->object->numMeshes)
  365. continue;
  366. if (mesh->getMesh(od))
  367. {
  368. mesh->getMesh(od)->computeBounds(mesh->getTransform(),box, 0); // use frame 0 so TSSkinMesh uses skinned verts to compute bounds
  369. bounds.minExtents.setMin(box.minExtents);
  370. bounds.maxExtents.setMax(box.maxExtents);
  371. }
  372. }
  373. }
  374. //-------------------------------------------------------------------------------------
  375. // Object (MeshObjectInstance & PluginObjectInstance) collision methods
  376. //-------------------------------------------------------------------------------------
  377. bool TSShapeInstance::ObjectInstance::buildPolyList(S32 objectDetail, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  378. {
  379. TORQUE_UNUSED( objectDetail );
  380. TORQUE_UNUSED( polyList );
  381. TORQUE_UNUSED( surfaceKey );
  382. TORQUE_UNUSED( materials );
  383. AssertFatal(0,"TSShapeInstance::ObjectInstance::buildPolyList: no default method.");
  384. return false;
  385. }
  386. bool TSShapeInstance::ObjectInstance::getFeatures(S32 objectDetail, const MatrixF& mat, const Point3F& n, ConvexFeature* cf, U32& surfaceKey)
  387. {
  388. TORQUE_UNUSED( objectDetail );
  389. TORQUE_UNUSED( mat );
  390. TORQUE_UNUSED( n );
  391. TORQUE_UNUSED( cf );
  392. TORQUE_UNUSED( surfaceKey );
  393. AssertFatal(0,"TSShapeInstance::ObjectInstance::buildPolyList: no default method.");
  394. return false;
  395. }
  396. void TSShapeInstance::ObjectInstance::support(S32, const Point3F&, F32*, Point3F*)
  397. {
  398. AssertFatal(0,"TSShapeInstance::ObjectInstance::supprt: no default method.");
  399. }
  400. bool TSShapeInstance::ObjectInstance::castRay( S32 objectDetail, const Point3F &start, const Point3F &end, RayInfo *rayInfo, TSMaterialList *materials )
  401. {
  402. TORQUE_UNUSED( objectDetail );
  403. TORQUE_UNUSED( start );
  404. TORQUE_UNUSED( end );
  405. TORQUE_UNUSED( rayInfo );
  406. AssertFatal(0,"TSShapeInstance::ObjectInstance::castRay: no default method.");
  407. return false;
  408. }
  409. bool TSShapeInstance::MeshObjectInstance::buildPolyList( S32 objectDetail, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  410. {
  411. TSMesh * mesh = getMesh(objectDetail);
  412. if (mesh && !forceHidden && visible>0.01f)
  413. return mesh->buildPolyList(frame,polyList,surfaceKey,materials);
  414. return false;
  415. }
  416. bool TSShapeInstance::MeshObjectInstance::getFeatures(S32 objectDetail, const MatrixF& mat, const Point3F& n, ConvexFeature* cf, U32& surfaceKey)
  417. {
  418. TSMesh* mesh = getMesh(objectDetail);
  419. if (mesh && !forceHidden && visible > 0.01f)
  420. return mesh->getFeatures(frame, mat, n, cf, surfaceKey);
  421. return false;
  422. }
  423. void TSShapeInstance::MeshObjectInstance::support(S32 objectDetail, const Point3F& v, F32* currMaxDP, Point3F* currSupport)
  424. {
  425. TSMesh* mesh = getMesh(objectDetail);
  426. if (mesh && !forceHidden && visible > 0.01f)
  427. mesh->support(frame, v, currMaxDP, currSupport);
  428. }
  429. bool TSShapeInstance::MeshObjectInstance::castRay( S32 objectDetail, const Point3F & start, const Point3F & end, RayInfo * rayInfo, TSMaterialList* materials )
  430. {
  431. TSMesh* mesh = getMesh( objectDetail );
  432. if( mesh && !forceHidden && visible > 0.01f )
  433. return mesh->castRay( frame, start, end, rayInfo, materials );
  434. return false;
  435. }
  436. bool TSShapeInstance::MeshObjectInstance::castRayRendered( S32 objectDetail, const Point3F & start, const Point3F & end, RayInfo * rayInfo, TSMaterialList* materials )
  437. {
  438. TSMesh* mesh = getMesh( objectDetail );
  439. if( mesh && !forceHidden && visible > 0.01f )
  440. return mesh->castRayRendered( frame, start, end, rayInfo, materials );
  441. return false;
  442. }
  443. bool TSShapeInstance::ObjectInstance::castRayOpcode( S32 objectDetail, const Point3F & start, const Point3F & end, RayInfo *rayInfo, TSMaterialList* materials )
  444. {
  445. TORQUE_UNUSED( objectDetail );
  446. TORQUE_UNUSED( start );
  447. TORQUE_UNUSED( end );
  448. TORQUE_UNUSED( rayInfo );
  449. TORQUE_UNUSED( materials );
  450. return false;
  451. }
  452. bool TSShapeInstance::ObjectInstance::buildPolyListOpcode( S32 objectDetail, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  453. {
  454. TORQUE_UNUSED( objectDetail );
  455. TORQUE_UNUSED( polyList );
  456. TORQUE_UNUSED( surfaceKey );
  457. TORQUE_UNUSED( materials );
  458. return false;
  459. }
  460. bool TSShapeInstance::ObjectInstance::buildConvexOpcode( const MatrixF &mat, S32 objectDetail, const Box3F &bounds, Convex *c, Convex *list )
  461. {
  462. TORQUE_UNUSED( mat );
  463. TORQUE_UNUSED( objectDetail );
  464. TORQUE_UNUSED( bounds );
  465. TORQUE_UNUSED( c );
  466. TORQUE_UNUSED( list );
  467. return false;
  468. }
  469. bool TSShapeInstance::MeshObjectInstance::castRayOpcode( S32 objectDetail, const Point3F & start, const Point3F & end, RayInfo *info, TSMaterialList* materials )
  470. {
  471. TSMesh * mesh = getMesh(objectDetail);
  472. if (mesh && !forceHidden && visible>0.01f)
  473. return mesh->castRayOpcode(start, end, info, materials);
  474. return false;
  475. }
  476. bool TSShapeInstance::MeshObjectInstance::buildPolyListOpcode( S32 objectDetail, AbstractPolyList *polyList, const Box3F &box, TSMaterialList *materials )
  477. {
  478. TSMesh * mesh = getMesh(objectDetail);
  479. if ( mesh && !forceHidden && visible > 0.01f && box.isOverlapped( mesh->getBounds() ) )
  480. return mesh->buildPolyListOpcode(frame,polyList,box,materials);
  481. return false;
  482. }
  483. bool TSShapeInstance::MeshObjectInstance::buildConvexOpcode( const MatrixF &mat, S32 objectDetail, const Box3F &bounds, Convex *c, Convex *list)
  484. {
  485. TSMesh * mesh = getMesh(objectDetail);
  486. if ( mesh && !forceHidden && visible > 0.01f && bounds.isOverlapped( mesh->getBounds() ) )
  487. return mesh->buildConvexOpcode(mat, bounds, c, list);
  488. return false;
  489. }
  490. bool TSShapeInstance::buildPolyListOpcode( S32 dl, AbstractPolyList *polyList, const Box3F &box )
  491. {
  492. PROFILE_SCOPE( TSShapeInstance_buildPolyListOpcode_MeshObjInst );
  493. if (dl==-1)
  494. return false;
  495. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::buildPolyListOpcode");
  496. // get subshape and object detail
  497. const TSDetail * detail = &mShape->details[dl];
  498. S32 ss = detail->subShapeNum;
  499. if ( ss < 0 )
  500. return false;
  501. S32 od = detail->objectDetailNum;
  502. // nothing emitted yet...
  503. bool emitted = false;
  504. S32 start = mShape->subShapeFirstObject[ss];
  505. S32 end = mShape->subShapeNumObjects[ss] + start;
  506. if (start<end)
  507. {
  508. MatrixF initialMat;
  509. Point3F initialScale;
  510. polyList->getTransform(&initialMat,&initialScale);
  511. // set up for first object's node
  512. MatrixF mat;
  513. MatrixF scaleMat(true);
  514. F32* p = scaleMat;
  515. p[0] = initialScale.x;
  516. p[5] = initialScale.y;
  517. p[10] = initialScale.z;
  518. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  519. mat.mul(initialMat,scaleMat);
  520. mat.mul(*previousMat);
  521. polyList->setTransform(&mat,Point3F(1, 1, 1));
  522. // Update our bounding box...
  523. Box3F localBox = box;
  524. MatrixF otherMat = mat;
  525. otherMat.inverse();
  526. otherMat.mul(localBox);
  527. // run through objects and collide
  528. for (S32 i=start; i<end; i++)
  529. {
  530. MeshObjectInstance * mesh = &mMeshObjects[i];
  531. if (od >= mesh->object->numMeshes)
  532. continue;
  533. if (&mesh->getTransform() != previousMat)
  534. {
  535. // different node from before, set up for this node
  536. previousMat = &mesh->getTransform();
  537. if (previousMat != NULL)
  538. {
  539. mat.mul(initialMat,scaleMat);
  540. mat.mul(*previousMat);
  541. polyList->setTransform(&mat,Point3F(1, 1, 1));
  542. // Update our bounding box...
  543. otherMat = mat;
  544. otherMat.inverse();
  545. localBox = box;
  546. otherMat.mul(localBox);
  547. }
  548. }
  549. // collide...
  550. emitted |= mesh->buildPolyListOpcode(od,polyList,localBox,mMaterialList);
  551. }
  552. // restore original transform...
  553. polyList->setTransform(&initialMat,initialScale);
  554. }
  555. return emitted;
  556. }
  557. bool TSShapeInstance::castRayOpcode( S32 dl, const Point3F & startPos, const Point3F & endPos, RayInfo *info)
  558. {
  559. // if dl==-1, nothing to do
  560. if (dl==-1)
  561. return false;
  562. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::castRayOpcode");
  563. info->t = 100.f;
  564. // get subshape and object detail
  565. const TSDetail * detail = &mShape->details[dl];
  566. S32 ss = detail->subShapeNum;
  567. if ( ss < 0 )
  568. return false;
  569. S32 od = detail->objectDetailNum;
  570. // nothing emitted yet...
  571. bool emitted = false;
  572. const MatrixF* saveMat = NULL;
  573. S32 start = mShape->subShapeFirstObject[ss];
  574. S32 end = mShape->subShapeNumObjects[ss] + start;
  575. if (start<end)
  576. {
  577. MatrixF mat;
  578. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  579. mat = *previousMat;
  580. mat.inverse();
  581. Point3F localStart, localEnd;
  582. mat.mulP(startPos, &localStart);
  583. mat.mulP(endPos, &localEnd);
  584. // run through objects and collide
  585. for (S32 i=start; i<end; i++)
  586. {
  587. MeshObjectInstance * mesh = &mMeshObjects[i];
  588. if (od >= mesh->object->numMeshes)
  589. continue;
  590. if (&mesh->getTransform() != previousMat)
  591. {
  592. // different node from before, set up for this node
  593. previousMat = &mesh->getTransform();
  594. if (previousMat != NULL)
  595. {
  596. mat = *previousMat;
  597. mat.inverse();
  598. mat.mulP(startPos, &localStart);
  599. mat.mulP(endPos, &localEnd);
  600. }
  601. }
  602. // collide...
  603. if ( mesh->castRayOpcode(od,localStart, localEnd, info, mMaterialList) )
  604. {
  605. saveMat = previousMat;
  606. emitted = true;
  607. }
  608. }
  609. }
  610. if ( emitted )
  611. {
  612. saveMat->mulV(info->normal);
  613. info->point = endPos - startPos;
  614. info->point *= info->t;
  615. info->point += startPos;
  616. }
  617. return emitted;
  618. }
  619. bool TSShapeInstance::buildConvexOpcode( const MatrixF &objMat, const Point3F &objScale, S32 dl, const Box3F &bounds, Convex *c, Convex *list )
  620. {
  621. AssertFatal(dl>=0 && dl<mShape->details.size(),"TSShapeInstance::buildConvexOpcode");
  622. // get subshape and object detail
  623. const TSDetail * detail = &mShape->details[dl];
  624. S32 ss = detail->subShapeNum;
  625. S32 od = detail->objectDetailNum;
  626. // nothing emitted yet...
  627. bool emitted = false;
  628. S32 start = mShape->subShapeFirstObject[ss];
  629. S32 end = mShape->subShapeNumObjects[ss] + start;
  630. if (start<end)
  631. {
  632. MatrixF initialMat = objMat;
  633. Point3F initialScale = objScale;
  634. // set up for first object's node
  635. MatrixF mat;
  636. MatrixF scaleMat(true);
  637. F32* p = scaleMat;
  638. p[0] = initialScale.x;
  639. p[5] = initialScale.y;
  640. p[10] = initialScale.z;
  641. const MatrixF * previousMat = &mMeshObjects[start].getTransform();
  642. mat.mul(initialMat,scaleMat);
  643. mat.mul(*previousMat);
  644. // Update our bounding box...
  645. Box3F localBox = bounds;
  646. MatrixF otherMat = mat;
  647. otherMat.inverse();
  648. otherMat.mul(localBox);
  649. // run through objects and collide
  650. for (S32 i=start; i<end; i++)
  651. {
  652. MeshObjectInstance * mesh = &mMeshObjects[i];
  653. if (od >= mesh->object->numMeshes)
  654. continue;
  655. if (&mesh->getTransform() != previousMat)
  656. {
  657. // different node from before, set up for this node
  658. previousMat = &mesh->getTransform();
  659. if (previousMat != NULL)
  660. {
  661. mat.mul(initialMat,scaleMat);
  662. mat.mul(*previousMat);
  663. // Update our bounding box...
  664. otherMat = mat;
  665. otherMat.inverse();
  666. localBox = bounds;
  667. otherMat.mul(localBox);
  668. }
  669. }
  670. // collide... note we pass the original mech transform
  671. // here so that the convex data returned is in mesh space.
  672. emitted |= mesh->buildConvexOpcode(*previousMat,od,localBox,c, list);
  673. }
  674. }
  675. return emitted;
  676. }
  677. void TSShape::findColDetails( bool useVisibleMesh, Vector<S32> *outDetails, Vector<S32> *outLOSDetails ) const
  678. {
  679. PROFILE_SCOPE( TSShape_findColDetails );
  680. if ( useVisibleMesh )
  681. {
  682. // If we're using the visible mesh for collision then
  683. // find the highest detail and use that.
  684. U32 highestDetail = -1;
  685. F32 highestSize = -F32_MAX;
  686. for ( U32 i = 0; i < details.size(); i++ )
  687. {
  688. // Make sure we skip any details that shouldn't be rendered
  689. if ( details[i].size < 0 )
  690. continue;
  691. /*
  692. // Also make sure we skip any collision details with a size.
  693. const String &name = names[details[i].nameIndex];
  694. if ( dStrStartsWith( name, "Collision" ) ||
  695. dStrStartsWith( name, "LOS" ) )
  696. continue;
  697. */
  698. // Otherwise test against the current highest size
  699. if ( details[i].size > highestSize )
  700. {
  701. highestDetail = i;
  702. highestSize = details[i].size;
  703. }
  704. }
  705. // We use the same detail for both raycast and collisions.
  706. if ( highestDetail != -1 )
  707. {
  708. outDetails->push_back( highestDetail );
  709. if ( outLOSDetails )
  710. outLOSDetails->push_back( highestDetail );
  711. }
  712. return;
  713. }
  714. // Detail meshes starting with COL or LOS is considered
  715. // to be a collision mesh.
  716. //
  717. // The LOS (light of sight) details are used for raycasts.
  718. for ( U32 i = 0; i < details.size(); i++ )
  719. {
  720. const String &name = names[ details[i].nameIndex ];
  721. if ( !dStrStartsWith( name, "Collision" ) )
  722. continue;
  723. outDetails->push_back(i);
  724. // If we're not returning LOS details then skip out.
  725. if ( !outLOSDetails )
  726. continue;
  727. // The way LOS works is that it will check to see if there is a LOS detail that matches
  728. // the the collision detail + 1 + MaxCollisionShapes (this variable name should change in
  729. // the future). If it can't find a matching LOS it will simply use the collision instead.
  730. // We check for any "unmatched" LOS's further down.
  731. // Extract the detail number from the name.
  732. S32 number = 0;
  733. String::GetTrailingNumber( name, number );
  734. // Look for a matching LOS collision detail.
  735. //
  736. // TODO: Fix the old 9 detail offset which is there
  737. // because you cannot have two detail markers with
  738. // the same detail number.
  739. //
  740. const S32 LOSOverrideOffset = 9;
  741. String buff = String::ToString( "LOS-%d", mAbs( number ) + LOSOverrideOffset );
  742. S32 los = findDetail( buff );
  743. // If we didn't find the lod detail then use the
  744. // normal collision detail for LOS tests.
  745. if ( los == -1 )
  746. los = i;
  747. outLOSDetails->push_back( los );
  748. }
  749. // If we're not returning LOS details then skip out.
  750. if ( !outLOSDetails )
  751. return;
  752. // Snag any "unmatched" LOS details and put
  753. // them at the end of the list.
  754. for ( U32 i = 0; i < details.size(); i++ )
  755. {
  756. const String &name = names[ details[i].nameIndex ];
  757. if ( !dStrStartsWith( name, "LOS" ) )
  758. continue;
  759. // See if we already have this LOS
  760. bool found = false;
  761. for (U32 j = 0; j < outLOSDetails->size(); j++)
  762. {
  763. if ( (*outLOSDetails)[j] == i )
  764. {
  765. found = true;
  766. break;
  767. }
  768. }
  769. if ( !found )
  770. outLOSDetails->push_back(i);
  771. }
  772. }
  773. PhysicsCollision* TSShape::buildColShape( bool useVisibleMesh, const Point3F &scale )
  774. {
  775. return _buildColShapes( useVisibleMesh, scale, NULL, false );
  776. }
  777. void TSShape::buildColShapes( bool useVisibleMesh, const Point3F &scale, Vector< CollisionShapeInfo > *list )
  778. {
  779. _buildColShapes( useVisibleMesh, scale, list, true );
  780. }
  781. PhysicsCollision* TSShape::_buildColShapes( bool useVisibleMesh, const Point3F &scale, Vector< CollisionShapeInfo > *list, bool perMesh )
  782. {
  783. PROFILE_SCOPE( TSShape_buildColShapes );
  784. if ( !PHYSICSMGR )
  785. return NULL;
  786. PhysicsCollision *colShape = NULL;
  787. U32 surfaceKey = 0;
  788. if ( useVisibleMesh )
  789. {
  790. // Here we build triangle collision meshes from the
  791. // visible detail levels.
  792. // A negative subshape on the detail means we don't have geometry.
  793. const TSShape::Detail &detail = details[0];
  794. if ( detail.subShapeNum < 0 )
  795. return NULL;
  796. // We don't try to optimize the triangles we're given
  797. // and assume the art was created properly for collision.
  798. ConcretePolyList polyList;
  799. polyList.setTransform( &MatrixF::Identity, scale );
  800. // Create the collision meshes.
  801. S32 start = subShapeFirstObject[ detail.subShapeNum ];
  802. S32 end = start + subShapeNumObjects[ detail.subShapeNum ];
  803. for ( S32 o=start; o < end; o++ )
  804. {
  805. const TSShape::Object &object = objects[o];
  806. if ( detail.objectDetailNum >= object.numMeshes )
  807. continue;
  808. // No mesh or no verts.... nothing to do.
  809. TSMesh *mesh = meshes[ object.startMeshIndex + detail.objectDetailNum ];
  810. if ( !mesh || mesh->mNumVerts == 0 )
  811. continue;
  812. // Gather the mesh triangles.
  813. polyList.clear();
  814. mesh->buildPolyList( 0, &polyList, surfaceKey, NULL );
  815. // Create the collision shape if we haven't already.
  816. if ( !colShape )
  817. colShape = PHYSICSMGR->createCollision();
  818. // Get the object space mesh transform.
  819. MatrixF localXfm;
  820. getNodeWorldTransform( object.nodeIndex, &localXfm );
  821. colShape->addTriangleMesh( polyList.mVertexList.address(),
  822. polyList.mVertexList.size(),
  823. polyList.mIndexList.address(),
  824. polyList.mIndexList.size() / 3,
  825. localXfm );
  826. if ( perMesh )
  827. {
  828. list->increment();
  829. list->last().colNode = -1;
  830. list->last().colShape = colShape;
  831. colShape = NULL;
  832. }
  833. }
  834. // Return what we built... if anything.
  835. return colShape;
  836. }
  837. // Scan out the collision hulls...
  838. //
  839. // TODO: We need to support LOS collision for physics.
  840. //
  841. for ( U32 i = 0; i < details.size(); i++ )
  842. {
  843. const TSShape::Detail &detail = details[i];
  844. const String &name = names[detail.nameIndex];
  845. // Is this a valid collision detail.
  846. if ( !dStrStartsWith( name, "Collision" ) || detail.subShapeNum < 0 )
  847. continue;
  848. // Now go thru the meshes for this detail.
  849. S32 start = subShapeFirstObject[ detail.subShapeNum ];
  850. S32 end = start + subShapeNumObjects[ detail.subShapeNum ];
  851. if ( start >= end )
  852. continue;
  853. for ( S32 o=start; o < end; o++ )
  854. {
  855. const TSShape::Object &object = objects[o];
  856. const String &meshName = names[ object.nameIndex ];
  857. if ( object.numMeshes <= detail.objectDetailNum )
  858. continue;
  859. // No mesh, a flat bounds, or no verts.... nothing to do.
  860. TSMesh *mesh = meshes[ object.startMeshIndex + detail.objectDetailNum ];
  861. if ( !mesh || mesh->getBounds().isEmpty() || mesh->mNumVerts == 0 )
  862. continue;
  863. // We need the default mesh transform.
  864. MatrixF localXfm;
  865. getNodeWorldTransform( object.nodeIndex, &localXfm );
  866. Point3F nodeWorldPosition = localXfm.getPosition();
  867. nodeWorldPosition.convolve(scale);
  868. localXfm.setPosition(nodeWorldPosition);
  869. // We have some sort of collision shape... so allocate it.
  870. if ( !colShape )
  871. colShape = PHYSICSMGR->createCollision();
  872. // We have geometry... what is it?
  873. if ( dStrStartsWith( meshName, "Colbox" ) )
  874. {
  875. // The bounds define the box extents directly.
  876. Point3F halfWidth = mesh->getBounds().getExtents() * scale * 0.5f;
  877. // Add the offset to the center of the bounds
  878. // into the local space transform.
  879. MatrixF centerXfm( true );
  880. Point3F meshBoundsCenter = mesh->getBounds().getCenter();
  881. meshBoundsCenter.convolve(scale);
  882. centerXfm.setPosition(meshBoundsCenter);
  883. localXfm.mul( centerXfm );
  884. colShape->addBox( halfWidth, localXfm );
  885. }
  886. else if ( dStrStartsWith( meshName, "Colsphere" ) )
  887. {
  888. // Get a sphere inscribed to the bounds.
  889. Point3F extents = mesh->getBounds().getExtents() * scale;
  890. F32 radius = extents.least() * 0.5f;
  891. // Add the offset to the center of the bounds
  892. // into the local space transform.
  893. MatrixF primXfm( true );
  894. Point3F meshBoundsCenter = mesh->getBounds().getCenter();
  895. meshBoundsCenter.convolve(scale);
  896. primXfm.setPosition(meshBoundsCenter);
  897. localXfm.mul( primXfm );
  898. colShape->addSphere( radius, localXfm );
  899. }
  900. else if ( dStrStartsWith( meshName, "Colcapsule" ) )
  901. {
  902. // Use the smallest extent as the radius for the capsule.
  903. Point3F extents = mesh->getBounds().getExtents() * scale;
  904. F32 radius = extents.least() * 0.5f;
  905. // We need to center the capsule and align it to the Y axis.
  906. MatrixF primXfm( true );
  907. Point3F meshBoundsCenter = mesh->getBounds().getCenter();
  908. meshBoundsCenter.convolve(scale);
  909. primXfm.setPosition(meshBoundsCenter);
  910. // Use the longest axis as the capsule height.
  911. F32 height = -radius * 2.0f;
  912. if ( extents.x > extents.y && extents.x > extents.z )
  913. {
  914. primXfm.setColumn( 0, Point3F( 0, 0, 1 ) );
  915. primXfm.setColumn( 1, Point3F( 1, 0, 0 ) );
  916. primXfm.setColumn( 2, Point3F( 0, 1, 0 ) );
  917. height += extents.x;
  918. }
  919. else if ( extents.z > extents.x && extents.z > extents.y )
  920. {
  921. primXfm.setColumn( 0, Point3F( 0, 1, 0 ) );
  922. primXfm.setColumn( 1, Point3F( 0, 0, 1 ) );
  923. primXfm.setColumn( 2, Point3F( 1, 0, 0 ) );
  924. height += extents.z;
  925. }
  926. else
  927. height += extents.y;
  928. // Add the primitive transform into the local transform.
  929. localXfm.mul( primXfm );
  930. // If we didn't find a positive height then fallback to
  931. // creating a sphere which is better than nothing.
  932. if ( height > 0.0f )
  933. colShape->addCapsule( radius, height, localXfm );
  934. else
  935. colShape->addSphere( radius, localXfm );
  936. }
  937. else if ( dStrStartsWith( meshName, "Colmesh" ) )
  938. {
  939. // For a triangle mesh we gather the triangles raw from the
  940. // mesh and don't do any optimizations or cleanup.
  941. ConcretePolyList polyList;
  942. polyList.setTransform( &MatrixF::Identity, scale );
  943. mesh->buildPolyList( 0, &polyList, surfaceKey, NULL );
  944. colShape->addTriangleMesh( polyList.mVertexList.address(),
  945. polyList.mVertexList.size(),
  946. polyList.mIndexList.address(),
  947. polyList.mIndexList.size() / 3,
  948. localXfm );
  949. }
  950. else
  951. {
  952. // Any other mesh name we assume as a generic convex hull.
  953. //
  954. // Collect the verts using the vertex polylist which will
  955. // filter out duplicates. This is importaint as the convex
  956. // generators can sometimes fail with duplicate verts.
  957. //
  958. VertexPolyList polyList;
  959. MatrixF meshMat( localXfm );
  960. polyList.setTransform( &MatrixF::Identity, scale );
  961. mesh->buildPolyList( 0, &polyList, surfaceKey, NULL );
  962. colShape->addConvex( polyList.getVertexList().address(),
  963. polyList.getVertexList().size(),
  964. meshMat );
  965. }
  966. if ( perMesh )
  967. {
  968. list->increment();
  969. S32 detailNum;
  970. String::GetTrailingNumber( name, detailNum );
  971. String str = String::ToString( "%s%i", meshName.c_str(), detailNum );
  972. S32 found = findNode( str );
  973. if ( found == -1 )
  974. {
  975. str = str.replace('-','_');
  976. found = findNode( str );
  977. }
  978. list->last().colNode = found;
  979. list->last().colShape = colShape;
  980. colShape = NULL;
  981. }
  982. } // objects
  983. } // details
  984. return colShape;
  985. }
  986. bool TSMesh::buildPolyListOpcode( const S32 od, AbstractPolyList *polyList, const Box3F &nodeBox, TSMaterialList *materials )
  987. {
  988. PROFILE_SCOPE( TSMesh_buildPolyListOpcode );
  989. // This is small... there is no win for preallocating it.
  990. Opcode::AABBCollider opCollider;
  991. opCollider.SetPrimitiveTests( true );
  992. // This isn't really needed within the AABBCollider as
  993. // we don't use temporal coherance... use a static to
  994. // remove the allocation overhead.
  995. static Opcode::AABBCache opCache;
  996. IceMaths::AABB opBox;
  997. opBox.SetMinMax( Point( nodeBox.minExtents.x, nodeBox.minExtents.y, nodeBox.minExtents.z ),
  998. Point( nodeBox.maxExtents.x, nodeBox.maxExtents.y, nodeBox.maxExtents.z ) );
  999. Opcode::CollisionAABB opCBox(opBox);
  1000. if ( !opCollider.Collide( opCache, opCBox, *mOptTree ) )
  1001. return false;
  1002. U32 count = opCollider.GetNbTouchedPrimitives();
  1003. const udword *idx = opCollider.GetTouchedPrimitives();
  1004. Opcode::VertexPointers vp;
  1005. U32 plIdx[3];
  1006. S32 j;
  1007. Point3F tmp;
  1008. const IceMaths::Point **verts;
  1009. const Opcode::MeshInterface *mi = mOptTree->GetMeshInterface();
  1010. for ( S32 i=0; i < count; i++ )
  1011. {
  1012. // Get the triangle...
  1013. mi->GetTriangle( vp, idx[i] );
  1014. verts = vp.Vertex;
  1015. // And register it in the polylist...
  1016. polyList->begin( NULL, i );
  1017. for( j = 2; j > -1; j-- )
  1018. {
  1019. tmp.set( verts[j]->x, verts[j]->y, verts[j]->z );
  1020. plIdx[j] = polyList->addPoint( tmp );
  1021. polyList->vertex( plIdx[j] );
  1022. }
  1023. polyList->plane( plIdx[0], plIdx[2], plIdx[1] );
  1024. polyList->end();
  1025. }
  1026. // TODO: Add a polyList->getCount() so we can see if we
  1027. // got clipped polys and didn't really emit anything.
  1028. return count > 0;
  1029. }
  1030. bool TSMesh::buildConvexOpcode( const MatrixF &meshToObjectMat, const Box3F &nodeBox, Convex *convex, Convex *list )
  1031. {
  1032. PROFILE_SCOPE( TSMesh_buildConvexOpcode );
  1033. // This is small... there is no win for preallocating it.
  1034. Opcode::AABBCollider opCollider;
  1035. opCollider.SetPrimitiveTests( true );
  1036. // This isn't really needed within the AABBCollider as
  1037. // we don't use temporal coherance... use a static to
  1038. // remove the allocation overhead.
  1039. static Opcode::AABBCache opCache;
  1040. IceMaths::AABB opBox;
  1041. opBox.SetMinMax( Point( nodeBox.minExtents.x, nodeBox.minExtents.y, nodeBox.minExtents.z ),
  1042. Point( nodeBox.maxExtents.x, nodeBox.maxExtents.y, nodeBox.maxExtents.z ) );
  1043. Opcode::CollisionAABB opCBox(opBox);
  1044. if( !opCollider.Collide( opCache, opCBox, *mOptTree ) )
  1045. return false;
  1046. U32 cnt = opCollider.GetNbTouchedPrimitives();
  1047. const udword *idx = opCollider.GetTouchedPrimitives();
  1048. Opcode::VertexPointers vp;
  1049. for ( S32 i = 0; i < cnt; i++ )
  1050. {
  1051. // First, check our active convexes for a potential match (and clean things
  1052. // up, too.)
  1053. const U32 curIdx = idx[i];
  1054. // See if the square already exists as part of the working set.
  1055. bool gotMatch = false;
  1056. CollisionWorkingList& wl = convex->getWorkingList();
  1057. for ( CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext )
  1058. {
  1059. if( itr->mConvex->getType() != TSPolysoupConvexType )
  1060. continue;
  1061. const TSStaticPolysoupConvex *chunkc = static_cast<TSStaticPolysoupConvex*>( itr->mConvex );
  1062. if( chunkc->getObject() != TSStaticPolysoupConvex::smCurObject )
  1063. continue;
  1064. if( chunkc->mesh != this )
  1065. continue;
  1066. if( chunkc->idx != curIdx )
  1067. continue;
  1068. // A match! Don't need to add it.
  1069. gotMatch = true;
  1070. break;
  1071. }
  1072. if( gotMatch )
  1073. continue;
  1074. // Get the triangle...
  1075. mOptTree->GetMeshInterface()->GetTriangle( vp, idx[i] );
  1076. Point3F a( vp.Vertex[0]->x, vp.Vertex[0]->y, vp.Vertex[0]->z );
  1077. Point3F b( vp.Vertex[1]->x, vp.Vertex[1]->y, vp.Vertex[1]->z );
  1078. Point3F c( vp.Vertex[2]->x, vp.Vertex[2]->y, vp.Vertex[2]->z );
  1079. // Transform the result into object space!
  1080. meshToObjectMat.mulP( a );
  1081. meshToObjectMat.mulP( b );
  1082. meshToObjectMat.mulP( c );
  1083. PlaneF p( c, b, a );
  1084. Point3F peak = ((a + b + c) / 3.0f) - (p * 0.15f);
  1085. // Set up the convex...
  1086. TSStaticPolysoupConvex *cp = new TSStaticPolysoupConvex();
  1087. list->registerObject( cp );
  1088. convex->addToWorkingList( cp );
  1089. cp->mesh = this;
  1090. cp->idx = curIdx;
  1091. cp->mObject = TSStaticPolysoupConvex::smCurObject;
  1092. cp->normal = p;
  1093. cp->verts[0] = a;
  1094. cp->verts[1] = b;
  1095. cp->verts[2] = c;
  1096. cp->verts[3] = peak;
  1097. // Update the bounding box.
  1098. Box3F &bounds = cp->box;
  1099. bounds.minExtents.set( F32_MAX, F32_MAX, F32_MAX );
  1100. bounds.maxExtents.set( -F32_MAX, -F32_MAX, -F32_MAX );
  1101. bounds.minExtents.setMin( a );
  1102. bounds.minExtents.setMin( b );
  1103. bounds.minExtents.setMin( c );
  1104. bounds.minExtents.setMin( peak );
  1105. bounds.maxExtents.setMax( a );
  1106. bounds.maxExtents.setMax( b );
  1107. bounds.maxExtents.setMax( c );
  1108. bounds.maxExtents.setMax( peak );
  1109. }
  1110. return true;
  1111. }
  1112. void TSMesh::prepOpcodeCollision()
  1113. {
  1114. // Make sure opcode is loaded!
  1115. if( !gOpcodeInitialized )
  1116. {
  1117. Opcode::InitOpcode();
  1118. gOpcodeInitialized = true;
  1119. }
  1120. // Don't re init if we already have something...
  1121. if ( mOptTree )
  1122. return;
  1123. // Ok, first set up a MeshInterface
  1124. Opcode::MeshInterface *mi = new Opcode::MeshInterface();
  1125. mOpMeshInterface = mi;
  1126. // Figure out how many triangles we have...
  1127. U32 triCount = 0;
  1128. const U32 base = 0;
  1129. for ( U32 i = 0; i < mPrimitives.size(); i++ )
  1130. {
  1131. TSDrawPrimitive & draw = mPrimitives[i];
  1132. const U32 start = draw.start;
  1133. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildPolyList (1)" );
  1134. // gonna depend on what kind of primitive it is...
  1135. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  1136. triCount += draw.numElements / 3;
  1137. else
  1138. {
  1139. // Have to walk the tristrip to get a count... may have degenerates
  1140. U32 idx0 = base + mIndices[start + 0];
  1141. U32 idx1;
  1142. U32 idx2 = base + mIndices[start + 1];
  1143. U32 * nextIdx = &idx1;
  1144. for ( S32 j = 2; j < draw.numElements; j++ )
  1145. {
  1146. *nextIdx = idx2;
  1147. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  1148. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  1149. idx2 = base + mIndices[start + j];
  1150. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  1151. continue;
  1152. triCount++;
  1153. }
  1154. }
  1155. }
  1156. // Just do the first trilist for now.
  1157. mi->SetNbVertices( mVertexData.isReady() ? mNumVerts : mVerts.size() );
  1158. mi->SetNbTriangles( triCount );
  1159. // Stuff everything into appropriate arrays.
  1160. IceMaths::IndexedTriangle *its = new IceMaths::IndexedTriangle[ mi->GetNbTriangles() ], *curIts = its;
  1161. IceMaths::Point *pts = new IceMaths::Point[ mi->GetNbVertices() ];
  1162. mOpTris = its;
  1163. mOpPoints = pts;
  1164. // add the polys...
  1165. for ( U32 i = 0; i < mPrimitives.size(); i++ )
  1166. {
  1167. TSDrawPrimitive & draw = mPrimitives[i];
  1168. const U32 start = draw.start;
  1169. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildPolyList (1)" );
  1170. const U32 matIndex = draw.matIndex & TSDrawPrimitive::MaterialMask;
  1171. // gonna depend on what kind of primitive it is...
  1172. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  1173. {
  1174. for ( S32 j = 0; j < draw.numElements; )
  1175. {
  1176. curIts->mVRef[2] = base + mIndices[start + j + 0];
  1177. curIts->mVRef[1] = base + mIndices[start + j + 1];
  1178. curIts->mVRef[0] = base + mIndices[start + j + 2];
  1179. curIts->mMatIdx = matIndex;
  1180. curIts++;
  1181. j += 3;
  1182. }
  1183. }
  1184. else
  1185. {
  1186. AssertFatal( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Strip,"TSMesh::buildPolyList (2)" );
  1187. U32 idx0 = base + mIndices[start + 0];
  1188. U32 idx1;
  1189. U32 idx2 = base + mIndices[start + 1];
  1190. U32 * nextIdx = &idx1;
  1191. for ( S32 j = 2; j < draw.numElements; j++ )
  1192. {
  1193. *nextIdx = idx2;
  1194. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  1195. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  1196. idx2 = base + mIndices[start + j];
  1197. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  1198. continue;
  1199. curIts->mVRef[2] = idx0;
  1200. curIts->mVRef[1] = idx1;
  1201. curIts->mVRef[0] = idx2;
  1202. curIts->mMatIdx = matIndex;
  1203. curIts++;
  1204. }
  1205. }
  1206. }
  1207. AssertFatal( (curIts - its) == mi->GetNbTriangles(), "Triangle count mismatch!" );
  1208. for( S32 i = 0; i < mi->GetNbVertices(); i++ )
  1209. {
  1210. if( mVertexData.isReady() )
  1211. {
  1212. const __TSMeshVertexBase &vertData = mVertexData.getBase(i);
  1213. pts[i].Set( vertData.vert().x, vertData.vert().y, vertData.vert().z );
  1214. }
  1215. else
  1216. {
  1217. pts[i].Set( mVerts[i].x, mVerts[i].y, mVerts[i].z );
  1218. }
  1219. }
  1220. mi->SetPointers( its, pts );
  1221. // Ok, we've got a mesh interface populated, now let's build a thingy to collide against.
  1222. mOptTree = new Opcode::Model();
  1223. Opcode::OPCODECREATE opcc;
  1224. opcc.mCanRemap = true;
  1225. opcc.mIMesh = mi;
  1226. opcc.mKeepOriginal = false;
  1227. opcc.mNoLeaf = false;
  1228. opcc.mQuantized = false;
  1229. opcc.mSettings.mLimit = 1;
  1230. mOptTree->Build( opcc );
  1231. }
  1232. static Point3F texGenAxis[18] =
  1233. {
  1234. Point3F(0,0,1), Point3F(1,0,0), Point3F(0,-1,0),
  1235. Point3F(0,0,-1), Point3F(1,0,0), Point3F(0,1,0),
  1236. Point3F(1,0,0), Point3F(0,1,0), Point3F(0,0,1),
  1237. Point3F(-1,0,0), Point3F(0,1,0), Point3F(0,0,-1),
  1238. Point3F(0,1,0), Point3F(1,0,0), Point3F(0,0,1),
  1239. Point3F(0,-1,0), Point3F(-1,0,0), Point3F(0,0,-1)
  1240. };
  1241. bool TSMesh::castRayOpcode( const Point3F &start, const Point3F &end, RayInfo *info, TSMaterialList *materials )
  1242. {
  1243. Opcode::RayCollider ray;
  1244. Opcode::CollisionFaces cfs;
  1245. IceMaths::Point dir(end.x - start.x, end.y - start.y, end.z - start.z );
  1246. const F32 rayLen = dir.Magnitude();
  1247. IceMaths::Ray vec( Point(start.x, start.y, start.z), dir.Normalize() );
  1248. ray.SetDestination( &cfs);
  1249. ray.SetFirstContact( false );
  1250. ray.SetClosestHit( true );
  1251. ray.SetPrimitiveTests( true );
  1252. ray.SetCulling( true );
  1253. ray.SetMaxDist( rayLen );
  1254. AssertFatal( ray.ValidateSettings() == NULL, "invalid ray settings" );
  1255. // Do collision.
  1256. bool safety = ray.Collide( vec, *mOptTree );
  1257. AssertFatal( safety, "TSMesh::castRayOpcode - no good ray collide!" );
  1258. // If no hit, just skip out.
  1259. if( cfs.GetNbFaces() == 0 )
  1260. return false;
  1261. // Got a hit!
  1262. AssertFatal( cfs.GetNbFaces() == 1, "bad" );
  1263. const Opcode::CollisionFace &face = cfs.GetFaces()[0];
  1264. // If the cast was successful let's check if the t value is less than what we had
  1265. // and toggle the collision boolean
  1266. // Stupid t... i prefer coffee
  1267. const F32 t = face.mDistance / rayLen;
  1268. if( t < 0.0f || t > 1.0f )
  1269. return false;
  1270. if( t <= info->t )
  1271. {
  1272. info->t = t;
  1273. // Calculate the normal.
  1274. Opcode::VertexPointers vp;
  1275. mOptTree->GetMeshInterface()->GetTriangle( vp, face.mFaceID );
  1276. if ( materials && vp.MatIdx >= 0 && vp.MatIdx < materials->size() )
  1277. info->material = materials->getMaterialInst( vp.MatIdx );
  1278. // Get the two edges.
  1279. IceMaths::Point baseVert = *vp.Vertex[0];
  1280. IceMaths::Point a = *vp.Vertex[1] - baseVert;
  1281. IceMaths::Point b = *vp.Vertex[2] - baseVert;
  1282. IceMaths::Point n;
  1283. n.Cross( a, b );
  1284. n.Normalize();
  1285. info->normal.set( n.x, n.y, n.z );
  1286. // generate UV coordinate across mesh based on
  1287. // matching normals, this isn't done by default and is
  1288. // primarily of interest in matching a collision point to
  1289. // either a GUI control coordinate or finding a hit pixel in texture space
  1290. if (info->generateTexCoord)
  1291. {
  1292. baseVert = *vp.Vertex[0];
  1293. a = *vp.Vertex[1];
  1294. b = *vp.Vertex[2];
  1295. Point3F facePoint = (1.0f - face.mU - face.mV) * Point3F(baseVert.x, baseVert.y, baseVert.z)
  1296. + face.mU * Point3F(a.x, a.y, a.z) + face.mV * Point3F(b.x, b.y, b.z);
  1297. U32 faces[1024];
  1298. U32 numFaces = 0;
  1299. for (U32 i = 0; i < mOptTree->GetMeshInterface()->GetNbTriangles(); i++)
  1300. {
  1301. if ( i == face.mFaceID )
  1302. {
  1303. faces[numFaces++] = i;
  1304. }
  1305. else
  1306. {
  1307. IceMaths::Point n2;
  1308. mOptTree->GetMeshInterface()->GetTriangle( vp, i );
  1309. baseVert = *vp.Vertex[0];
  1310. a = *vp.Vertex[1] - baseVert;
  1311. b = *vp.Vertex[2] - baseVert;
  1312. n2.Cross( a, b );
  1313. n2.Normalize();
  1314. F32 eps = .01f;
  1315. if ( mFabs(n.x - n2.x) < eps && mFabs(n.y - n2.y) < eps && mFabs(n.z - n2.z) < eps)
  1316. {
  1317. faces[numFaces++] = i;
  1318. }
  1319. }
  1320. if (numFaces == 1024)
  1321. {
  1322. // too many faces in this collision mesh for UV generation
  1323. return true;
  1324. }
  1325. }
  1326. Point3F min(F32_MAX, F32_MAX, F32_MAX);
  1327. Point3F max(-F32_MAX, -F32_MAX, -F32_MAX);
  1328. for (U32 i = 0; i < numFaces; i++)
  1329. {
  1330. mOptTree->GetMeshInterface()->GetTriangle( vp, faces[i] );
  1331. for ( U32 j =0; j < 3; j++)
  1332. {
  1333. a = *vp.Vertex[j];
  1334. if (a.x < min.x)
  1335. min.x = a.x;
  1336. if (a.y < min.y)
  1337. min.y = a.y;
  1338. if (a.z < min.z)
  1339. min.z = a.z;
  1340. if (a.x > max.x)
  1341. max.x = a.x;
  1342. if (a.y > max.y)
  1343. max.y = a.y;
  1344. if (a.z > max.z)
  1345. max.z = a.z;
  1346. }
  1347. }
  1348. // slerp
  1349. Point3F divSafe = (max - min);
  1350. if (divSafe.x == 0.0f) divSafe.x = POINT_EPSILON;
  1351. if (divSafe.y == 0.0f) divSafe.y = POINT_EPSILON;
  1352. if (divSafe.z == 0.0f) divSafe.z = POINT_EPSILON;
  1353. Point3F s = ( (max - min) - (facePoint - min) ) / divSafe;
  1354. // compute axis
  1355. S32 bestAxis = 0;
  1356. F32 best = 0.f;
  1357. for (U32 i = 0 ; i < 6 ; i++)
  1358. {
  1359. F32 dot = mDot (info->normal, texGenAxis[i*3]);
  1360. if (dot > best)
  1361. {
  1362. best = dot;
  1363. bestAxis = i;
  1364. }
  1365. }
  1366. Point3F xv = texGenAxis[bestAxis*3+1];
  1367. Point3F yv = texGenAxis[bestAxis*3+2];
  1368. S32 sv, tv;
  1369. if (xv.x)
  1370. sv = 0;
  1371. else if (xv.y)
  1372. sv = 1;
  1373. else
  1374. sv = 2;
  1375. if (yv.x)
  1376. tv = 0;
  1377. else if (yv.y)
  1378. tv = 1;
  1379. else
  1380. tv = 2;
  1381. // handle coord translation
  1382. if (bestAxis == 2 || bestAxis == 3)
  1383. {
  1384. S32 x = sv;
  1385. sv = tv;
  1386. tv = x;
  1387. if (yv.z < 0)
  1388. s[sv] = 1.f - s[sv];
  1389. }
  1390. if (bestAxis < 2)
  1391. {
  1392. if (yv.y < 0)
  1393. s[sv] = 1.f - s[sv];
  1394. }
  1395. if (bestAxis > 3)
  1396. {
  1397. s[sv] = 1.f - s[sv];
  1398. if (yv.z > 0)
  1399. s[tv] = 1.f - s[tv];
  1400. }
  1401. // done!
  1402. info->texCoord.set(s[sv], s[tv]);
  1403. }
  1404. return true;
  1405. }
  1406. return false;
  1407. }