sceneContainer.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  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 "scene/sceneContainer.h"
  24. #include "collision/extrudedPolyList.h"
  25. #include "collision/earlyOutPolyList.h"
  26. #include "scene/sceneObject.h"
  27. #include "platform/profiler.h"
  28. #include "console/engineAPI.h"
  29. #include "math/util/frustum.h"
  30. // [rene, 02-Mar-11]
  31. // - *Loads* of copy&paste sin in this file (among its many other sins); all the findObjectXXX methods
  32. // are trivial permutations of the same snippet of copy&pasted code
  33. // - FindCallback should return a bool so it's possible to use the findObjectXXX methods to look
  34. // for the first object matching a certain criteria
  35. SceneContainer gServerContainer;
  36. SceneContainer gClientContainer;
  37. const U32 SceneContainer::csmNumBins = 16;
  38. const F32 SceneContainer::csmBinSize = 64;
  39. const F32 SceneContainer::csmTotalBinSize = SceneContainer::csmBinSize * SceneContainer::csmNumBins;
  40. const U32 SceneContainer::csmRefPoolBlockSize = 4096;
  41. // Statics used by buildPolyList methods
  42. static AbstractPolyList* sPolyList;
  43. static SphereF sBoundingSphere;
  44. static Box3F sBoundingBox;
  45. //=============================================================================
  46. // SceneContainer::Link.
  47. //=============================================================================
  48. //-----------------------------------------------------------------------------
  49. SceneContainer::Link::Link()
  50. {
  51. next = prev = this;
  52. }
  53. //-----------------------------------------------------------------------------
  54. void SceneContainer::Link::unlink()
  55. {
  56. next->prev = prev;
  57. prev->next = next;
  58. next = prev = this;
  59. }
  60. //-----------------------------------------------------------------------------
  61. void SceneContainer::Link::linkAfter(SceneContainer::Link* ptr)
  62. {
  63. next = ptr->next;
  64. next->prev = this;
  65. prev = ptr;
  66. prev->next = this;
  67. }
  68. //=============================================================================
  69. // SceneContainer.
  70. //=============================================================================
  71. //-----------------------------------------------------------------------------
  72. SceneContainer::SceneContainer()
  73. {
  74. mSearchInProgress = false;
  75. mCurrSeqKey = 0;
  76. mEnd.next = mEnd.prev = &mStart;
  77. mStart.next = mStart.prev = &mEnd;
  78. mBinArray = new SceneObjectRef[csmNumBins * csmNumBins];
  79. for (U32 i = 0; i < csmNumBins; i++)
  80. {
  81. U32 base = i * csmNumBins;
  82. for (U32 j = 0; j < csmNumBins; j++)
  83. {
  84. mBinArray[base + j].object = NULL;
  85. mBinArray[base + j].nextInBin = NULL;
  86. mBinArray[base + j].prevInBin = NULL;
  87. mBinArray[base + j].nextInObj = NULL;
  88. }
  89. }
  90. mOverflowBin.object = NULL;
  91. mOverflowBin.nextInBin = NULL;
  92. mOverflowBin.prevInBin = NULL;
  93. mOverflowBin.nextInObj = NULL;
  94. VECTOR_SET_ASSOCIATION( mRefPoolBlocks );
  95. VECTOR_SET_ASSOCIATION( mSearchList );
  96. VECTOR_SET_ASSOCIATION( mWaterAndZones );
  97. VECTOR_SET_ASSOCIATION( mTerrains );
  98. mFreeRefPool = NULL;
  99. addRefPoolBlock();
  100. cleanupSearchVectors();
  101. }
  102. //-----------------------------------------------------------------------------
  103. SceneContainer::~SceneContainer()
  104. {
  105. delete[] mBinArray;
  106. for (U32 i = 0; i < mRefPoolBlocks.size(); i++)
  107. {
  108. SceneObjectRef* pool = mRefPoolBlocks[i];
  109. for (U32 j = 0; j < csmRefPoolBlockSize; j++)
  110. {
  111. // Depressingly, this can give weird results if its pointing at bad memory...
  112. if(pool[j].object != NULL)
  113. Con::warnf("Error, a %s (%x) isn't properly out of the bins!", pool[j].object->getClassName(), pool[j].object);
  114. // If you're getting this it means that an object created didn't
  115. // remove itself from its container before we destroyed the
  116. // container. Typically you get this behavior from particle
  117. // emitters, as they try to hang around until all their particles
  118. // die. In general it's benign, though if you get it for things
  119. // that aren't particle emitters it can be a bad sign!
  120. }
  121. delete [] pool;
  122. }
  123. mFreeRefPool = NULL;
  124. cleanupSearchVectors();
  125. }
  126. //-----------------------------------------------------------------------------
  127. bool SceneContainer::addObject(SceneObject* obj)
  128. {
  129. AssertFatal(obj->mContainer == NULL, "Adding already added object.");
  130. obj->mContainer = this;
  131. obj->linkAfter(&mStart);
  132. insertIntoBins(obj);
  133. // Also insert water and physical zone types into the special vector.
  134. if ( obj->getTypeMask() & ( WaterObjectType | PhysicalZoneObjectType ) )
  135. mWaterAndZones.push_back(obj);
  136. if( obj->getTypeMask() & TerrainObjectType )
  137. mTerrains.push_back( obj );
  138. return true;
  139. }
  140. //-----------------------------------------------------------------------------
  141. bool SceneContainer::removeObject(SceneObject* obj)
  142. {
  143. AssertFatal(obj->mContainer == this, "Trying to remove from wrong container.");
  144. removeFromBins(obj);
  145. // Remove water and physical zone types from the special vector.
  146. if ( obj->getTypeMask() & ( WaterObjectType | PhysicalZoneObjectType ) )
  147. {
  148. Vector<SceneObject*>::iterator iter = find( mWaterAndZones.begin(), mWaterAndZones.end(), obj );
  149. if( iter != mTerrains.end() )
  150. mWaterAndZones.erase_fast(iter);
  151. }
  152. // Remove terrain objects from special vector.
  153. if( obj->getTypeMask() & TerrainObjectType )
  154. {
  155. Vector< SceneObject* >::iterator iter = find( mTerrains.begin(), mTerrains.end(), obj );
  156. if( iter != mTerrains.end() )
  157. mTerrains.erase_fast(iter);
  158. }
  159. obj->mContainer = 0;
  160. obj->unlink();
  161. return true;
  162. }
  163. //-----------------------------------------------------------------------------
  164. void SceneContainer::addRefPoolBlock()
  165. {
  166. mRefPoolBlocks.push_back(new SceneObjectRef[csmRefPoolBlockSize]);
  167. for (U32 i = 0; i < csmRefPoolBlockSize-1; i++)
  168. {
  169. mRefPoolBlocks.last()[i].object = NULL;
  170. mRefPoolBlocks.last()[i].prevInBin = NULL;
  171. mRefPoolBlocks.last()[i].nextInBin = NULL;
  172. mRefPoolBlocks.last()[i].nextInObj = &(mRefPoolBlocks.last()[i+1]);
  173. }
  174. mRefPoolBlocks.last()[csmRefPoolBlockSize-1].object = NULL;
  175. mRefPoolBlocks.last()[csmRefPoolBlockSize-1].prevInBin = NULL;
  176. mRefPoolBlocks.last()[csmRefPoolBlockSize-1].nextInBin = NULL;
  177. mRefPoolBlocks.last()[csmRefPoolBlockSize-1].nextInObj = mFreeRefPool;
  178. mFreeRefPool = &(mRefPoolBlocks.last()[0]);
  179. }
  180. //-----------------------------------------------------------------------------
  181. void SceneContainer::insertIntoBins(SceneObject* obj)
  182. {
  183. AssertFatal(obj != NULL, "No object?");
  184. AssertFatal(obj->mBinRefHead == NULL, "Error, already have a bin chain!");
  185. // The first thing we do is find which bins are covered in x and y...
  186. const Box3F* pWBox = &obj->getWorldBox();
  187. U32 minX, maxX, minY, maxY;
  188. getBinRange(pWBox->minExtents.x, pWBox->maxExtents.x, minX, maxX);
  189. getBinRange(pWBox->minExtents.y, pWBox->maxExtents.y, minY, maxY);
  190. // Store the current regions for later queries
  191. obj->mBinMinX = minX;
  192. obj->mBinMaxX = maxX;
  193. obj->mBinMinY = minY;
  194. obj->mBinMaxY = maxY;
  195. // For huge objects, dump them into the overflow bin. Otherwise, everything
  196. // goes into the grid...
  197. if (!obj->isGlobalBounds() && ((maxX - minX + 1) < csmNumBins || (maxY - minY + 1) < csmNumBins))
  198. {
  199. SceneObjectRef** pCurrInsert = &obj->mBinRefHead;
  200. for (U32 i = minY; i <= maxY; i++)
  201. {
  202. U32 insertY = i % csmNumBins;
  203. U32 base = insertY * csmNumBins;
  204. for (U32 j = minX; j <= maxX; j++)
  205. {
  206. U32 insertX = j % csmNumBins;
  207. SceneObjectRef* ref = allocateObjectRef();
  208. ref->object = obj;
  209. ref->nextInBin = mBinArray[base + insertX].nextInBin;
  210. ref->prevInBin = &mBinArray[base + insertX];
  211. ref->nextInObj = NULL;
  212. if (mBinArray[base + insertX].nextInBin)
  213. mBinArray[base + insertX].nextInBin->prevInBin = ref;
  214. mBinArray[base + insertX].nextInBin = ref;
  215. *pCurrInsert = ref;
  216. pCurrInsert = &ref->nextInObj;
  217. }
  218. }
  219. }
  220. else
  221. {
  222. SceneObjectRef* ref = allocateObjectRef();
  223. ref->object = obj;
  224. ref->nextInBin = mOverflowBin.nextInBin;
  225. ref->prevInBin = &mOverflowBin;
  226. ref->nextInObj = NULL;
  227. if (mOverflowBin.nextInBin)
  228. mOverflowBin.nextInBin->prevInBin = ref;
  229. mOverflowBin.nextInBin = ref;
  230. obj->mBinRefHead = ref;
  231. }
  232. }
  233. //-----------------------------------------------------------------------------
  234. void SceneContainer::insertIntoBins(SceneObject* obj,
  235. U32 minX, U32 maxX,
  236. U32 minY, U32 maxY)
  237. {
  238. PROFILE_START(InsertBins);
  239. AssertFatal(obj != NULL, "No object?");
  240. AssertFatal(obj->mBinRefHead == NULL, "Error, already have a bin chain!");
  241. // Store the current regions for later queries
  242. obj->mBinMinX = minX;
  243. obj->mBinMaxX = maxX;
  244. obj->mBinMinY = minY;
  245. obj->mBinMaxY = maxY;
  246. // For huge objects, dump them into the overflow bin. Otherwise, everything
  247. // goes into the grid...
  248. //
  249. if ((maxX - minX + 1) < csmNumBins || (maxY - minY + 1) < csmNumBins && !obj->isGlobalBounds())
  250. {
  251. SceneObjectRef** pCurrInsert = &obj->mBinRefHead;
  252. for (U32 i = minY; i <= maxY; i++)
  253. {
  254. U32 insertY = i % csmNumBins;
  255. U32 base = insertY * csmNumBins;
  256. for (U32 j = minX; j <= maxX; j++)
  257. {
  258. U32 insertX = j % csmNumBins;
  259. SceneObjectRef* ref = allocateObjectRef();
  260. ref->object = obj;
  261. ref->nextInBin = mBinArray[base + insertX].nextInBin;
  262. ref->prevInBin = &mBinArray[base + insertX];
  263. ref->nextInObj = NULL;
  264. if (mBinArray[base + insertX].nextInBin)
  265. mBinArray[base + insertX].nextInBin->prevInBin = ref;
  266. mBinArray[base + insertX].nextInBin = ref;
  267. *pCurrInsert = ref;
  268. pCurrInsert = &ref->nextInObj;
  269. }
  270. }
  271. }
  272. else
  273. {
  274. SceneObjectRef* ref = allocateObjectRef();
  275. ref->object = obj;
  276. ref->nextInBin = mOverflowBin.nextInBin;
  277. ref->prevInBin = &mOverflowBin;
  278. ref->nextInObj = NULL;
  279. if (mOverflowBin.nextInBin)
  280. mOverflowBin.nextInBin->prevInBin = ref;
  281. mOverflowBin.nextInBin = ref;
  282. obj->mBinRefHead = ref;
  283. }
  284. PROFILE_END();
  285. }
  286. //-----------------------------------------------------------------------------
  287. void SceneContainer::removeFromBins(SceneObject* obj)
  288. {
  289. PROFILE_START(RemoveFromBins);
  290. AssertFatal(obj != NULL, "No object?");
  291. SceneObjectRef* chain = obj->mBinRefHead;
  292. obj->mBinRefHead = NULL;
  293. while (chain)
  294. {
  295. SceneObjectRef* trash = chain;
  296. chain = chain->nextInObj;
  297. AssertFatal(trash->prevInBin != NULL, "Error, must have a previous entry in the bin!");
  298. if (trash->nextInBin)
  299. trash->nextInBin->prevInBin = trash->prevInBin;
  300. trash->prevInBin->nextInBin = trash->nextInBin;
  301. freeObjectRef(trash);
  302. }
  303. PROFILE_END();
  304. }
  305. //-----------------------------------------------------------------------------
  306. void SceneContainer::checkBins(SceneObject* obj)
  307. {
  308. AssertFatal(obj != NULL, "No object?");
  309. PROFILE_START(CheckBins);
  310. if (obj->mBinRefHead == NULL)
  311. {
  312. insertIntoBins(obj);
  313. PROFILE_END();
  314. return;
  315. }
  316. // Otherwise, the object is already in the bins. Let's see if it has strayed out of
  317. // the bins that it's currently in...
  318. const Box3F* pWBox = &obj->getWorldBox();
  319. U32 minX, maxX, minY, maxY;
  320. getBinRange(pWBox->minExtents.x, pWBox->maxExtents.x, minX, maxX);
  321. getBinRange(pWBox->minExtents.y, pWBox->maxExtents.y, minY, maxY);
  322. if (obj->mBinMinX != minX || obj->mBinMaxX != maxX ||
  323. obj->mBinMinY != minY || obj->mBinMaxY != maxY)
  324. {
  325. // We have to rebin the object
  326. removeFromBins(obj);
  327. insertIntoBins(obj, minX, maxX, minY, maxY);
  328. }
  329. PROFILE_END();
  330. }
  331. //-----------------------------------------------------------------------------
  332. void SceneContainer::findObjects(const Box3F& box, U32 mask, FindCallback callback, void *key)
  333. {
  334. PROFILE_SCOPE(ContainerFindObjects_Box);
  335. // If we're searching for just water, just physical zones, or
  336. // just water and physical zones then use the optimized path.
  337. if ( mask == WaterObjectType ||
  338. mask == PhysicalZoneObjectType ||
  339. mask == (WaterObjectType|PhysicalZoneObjectType) )
  340. {
  341. _findSpecialObjects( mWaterAndZones, box, mask, callback, key );
  342. return;
  343. }
  344. else if( mask == TerrainObjectType )
  345. {
  346. _findSpecialObjects( mTerrains, box, mask, callback, key );
  347. return;
  348. }
  349. AssertFatal( !mSearchInProgress, "SceneContainer::findObjects - Container queries are not re-entrant" );
  350. mSearchInProgress = true;
  351. U32 minX, maxX, minY, maxY;
  352. getBinRange(box.minExtents.x, box.maxExtents.x, minX, maxX);
  353. getBinRange(box.minExtents.y, box.maxExtents.y, minY, maxY);
  354. mCurrSeqKey++;
  355. for (U32 i = minY; i <= maxY; i++)
  356. {
  357. U32 insertY = i % csmNumBins;
  358. U32 base = insertY * csmNumBins;
  359. for (U32 j = minX; j <= maxX; j++)
  360. {
  361. U32 insertX = j % csmNumBins;
  362. SceneObjectRef* chain = mBinArray[base + insertX].nextInBin;
  363. while (chain)
  364. {
  365. if (chain->object->getContainerSeqKey() != mCurrSeqKey)
  366. {
  367. chain->object->setContainerSeqKey(mCurrSeqKey);
  368. if ((chain->object->getTypeMask() & mask) != 0 &&
  369. chain->object->isCollisionEnabled())
  370. {
  371. if (chain->object->getWorldBox().isOverlapped(box) || chain->object->isGlobalBounds())
  372. {
  373. (*callback)(chain->object,key);
  374. }
  375. }
  376. }
  377. chain = chain->nextInBin;
  378. }
  379. }
  380. }
  381. SceneObjectRef* chain = mOverflowBin.nextInBin;
  382. while (chain)
  383. {
  384. if (chain->object->getContainerSeqKey() != mCurrSeqKey)
  385. {
  386. chain->object->setContainerSeqKey(mCurrSeqKey);
  387. if ((chain->object->getTypeMask() & mask) != 0 &&
  388. chain->object->isCollisionEnabled())
  389. {
  390. if (chain->object->getWorldBox().isOverlapped(box) || chain->object->isGlobalBounds())
  391. {
  392. (*callback)(chain->object,key);
  393. }
  394. }
  395. }
  396. chain = chain->nextInBin;
  397. }
  398. mSearchInProgress = false;
  399. }
  400. //-----------------------------------------------------------------------------
  401. void SceneContainer::findObjects( const Frustum &frustum, U32 mask, FindCallback callback, void *key )
  402. {
  403. PROFILE_SCOPE(ContainerFindObjects_Frustum);
  404. Box3F searchBox = frustum.getBounds();
  405. if ( mask == WaterObjectType ||
  406. mask == PhysicalZoneObjectType ||
  407. mask == (WaterObjectType|PhysicalZoneObjectType) )
  408. {
  409. _findSpecialObjects( mWaterAndZones, searchBox, mask, callback, key );
  410. return;
  411. }
  412. else if( mask == TerrainObjectType )
  413. {
  414. _findSpecialObjects( mTerrains, searchBox, mask, callback, key );
  415. return;
  416. }
  417. AssertFatal( !mSearchInProgress, "SceneContainer::findObjects - Container queries are not re-entrant" );
  418. mSearchInProgress = true;
  419. U32 minX, maxX, minY, maxY;
  420. getBinRange(searchBox.minExtents.x, searchBox.maxExtents.x, minX, maxX);
  421. getBinRange(searchBox.minExtents.y, searchBox.maxExtents.y, minY, maxY);
  422. mCurrSeqKey++;
  423. for (U32 i = minY; i <= maxY; i++)
  424. {
  425. U32 insertY = i % csmNumBins;
  426. U32 base = insertY * csmNumBins;
  427. for (U32 j = minX; j <= maxX; j++)
  428. {
  429. U32 insertX = j % csmNumBins;
  430. SceneObjectRef* chain = mBinArray[base + insertX].nextInBin;
  431. while (chain)
  432. {
  433. SceneObject *object = chain->object;
  434. if (object->getContainerSeqKey() != mCurrSeqKey)
  435. {
  436. object->setContainerSeqKey(mCurrSeqKey);
  437. if ((object->getTypeMask() & mask) != 0 &&
  438. object->isCollisionEnabled())
  439. {
  440. const Box3F &worldBox = object->getWorldBox();
  441. if ( object->isGlobalBounds() || worldBox.isOverlapped(searchBox) )
  442. {
  443. if ( !frustum.isCulled( worldBox ) )
  444. (*callback)(chain->object,key);
  445. }
  446. }
  447. }
  448. chain = chain->nextInBin;
  449. }
  450. }
  451. }
  452. SceneObjectRef* chain = mOverflowBin.nextInBin;
  453. while (chain)
  454. {
  455. SceneObject *object = chain->object;
  456. if (object->getContainerSeqKey() != mCurrSeqKey)
  457. {
  458. object->setContainerSeqKey(mCurrSeqKey);
  459. if ((object->getTypeMask() & mask) != 0 &&
  460. object->isCollisionEnabled())
  461. {
  462. const Box3F &worldBox = object->getWorldBox();
  463. if ( object->isGlobalBounds() || worldBox.isOverlapped(searchBox) )
  464. {
  465. if ( !frustum.isCulled( worldBox ) )
  466. (*callback)(object,key);
  467. }
  468. }
  469. }
  470. chain = chain->nextInBin;
  471. }
  472. mSearchInProgress = false;
  473. }
  474. //-----------------------------------------------------------------------------
  475. void SceneContainer::polyhedronFindObjects(const Polyhedron& polyhedron, U32 mask, FindCallback callback, void *key)
  476. {
  477. PROFILE_SCOPE(ContainerFindObjects_polyhedron);
  478. U32 i;
  479. Box3F box;
  480. box.minExtents.set(1e9, 1e9, 1e9);
  481. box.maxExtents.set(-1e9, -1e9, -1e9);
  482. for (i = 0; i < polyhedron.pointList.size(); i++)
  483. {
  484. box.minExtents.setMin(polyhedron.pointList[i]);
  485. box.maxExtents.setMax(polyhedron.pointList[i]);
  486. }
  487. if ( mask == WaterObjectType ||
  488. mask == PhysicalZoneObjectType ||
  489. mask == (WaterObjectType|PhysicalZoneObjectType) )
  490. {
  491. _findSpecialObjects( mWaterAndZones, box, mask, callback, key );
  492. return;
  493. }
  494. else if( mask == TerrainObjectType )
  495. {
  496. _findSpecialObjects( mTerrains, mask, callback, key );
  497. return;
  498. }
  499. AssertFatal( !mSearchInProgress, "SceneContainer::polyhedronFindObjects - Container queries are not re-entrant" );
  500. mSearchInProgress = true;
  501. U32 minX, maxX, minY, maxY;
  502. getBinRange(box.minExtents.x, box.maxExtents.x, minX, maxX);
  503. getBinRange(box.minExtents.y, box.maxExtents.y, minY, maxY);
  504. mCurrSeqKey++;
  505. for (i = minY; i <= maxY; i++)
  506. {
  507. U32 insertY = i % csmNumBins;
  508. U32 base = insertY * csmNumBins;
  509. for (U32 j = minX; j <= maxX; j++)
  510. {
  511. U32 insertX = j % csmNumBins;
  512. SceneObjectRef* chain = mBinArray[base + insertX].nextInBin;
  513. while (chain)
  514. {
  515. if (chain->object->getContainerSeqKey() != mCurrSeqKey)
  516. {
  517. chain->object->setContainerSeqKey(mCurrSeqKey);
  518. if ((chain->object->getTypeMask() & mask) != 0 &&
  519. chain->object->isCollisionEnabled())
  520. {
  521. if (chain->object->getWorldBox().isOverlapped(box) || chain->object->isGlobalBounds())
  522. {
  523. (*callback)(chain->object,key);
  524. }
  525. }
  526. }
  527. chain = chain->nextInBin;
  528. }
  529. }
  530. }
  531. SceneObjectRef* chain = mOverflowBin.nextInBin;
  532. while (chain)
  533. {
  534. if (chain->object->getContainerSeqKey() != mCurrSeqKey)
  535. {
  536. chain->object->setContainerSeqKey(mCurrSeqKey);
  537. if ((chain->object->getTypeMask() & mask) != 0 &&
  538. chain->object->isCollisionEnabled())
  539. {
  540. if (chain->object->getWorldBox().isOverlapped(box) || chain->object->isGlobalBounds())
  541. {
  542. (*callback)(chain->object,key);
  543. }
  544. }
  545. }
  546. chain = chain->nextInBin;
  547. }
  548. mSearchInProgress = false;
  549. }
  550. //-----------------------------------------------------------------------------
  551. void SceneContainer::findObjectList( const Box3F& searchBox, U32 mask, Vector<SceneObject*> *outFound )
  552. {
  553. PROFILE_SCOPE( Container_FindObjectList_Box );
  554. AssertFatal( !mSearchInProgress, "SceneContainer::findObjectList - Container queries are not re-entrant" );
  555. mSearchInProgress = true;
  556. // TODO: Optimize for water and zones?
  557. U32 minX, maxX, minY, maxY;
  558. getBinRange(searchBox.minExtents.x, searchBox.maxExtents.x, minX, maxX);
  559. getBinRange(searchBox.minExtents.y, searchBox.maxExtents.y, minY, maxY);
  560. mCurrSeqKey++;
  561. for (U32 i = minY; i <= maxY; i++)
  562. {
  563. U32 insertY = i % csmNumBins;
  564. U32 base = insertY * csmNumBins;
  565. for (U32 j = minX; j <= maxX; j++)
  566. {
  567. U32 insertX = j % csmNumBins;
  568. SceneObjectRef* chain = mBinArray[base + insertX].nextInBin;
  569. while (chain)
  570. {
  571. SceneObject *object = chain->object;
  572. if (object->getContainerSeqKey() != mCurrSeqKey)
  573. {
  574. object->setContainerSeqKey(mCurrSeqKey);
  575. if ((object->getTypeMask() & mask) != 0 &&
  576. object->isCollisionEnabled())
  577. {
  578. const Box3F &worldBox = object->getWorldBox();
  579. if ( object->isGlobalBounds() || worldBox.isOverlapped( searchBox ) )
  580. {
  581. outFound->push_back( object );
  582. }
  583. }
  584. }
  585. chain = chain->nextInBin;
  586. }
  587. }
  588. }
  589. SceneObjectRef* chain = mOverflowBin.nextInBin;
  590. while (chain)
  591. {
  592. SceneObject *object = chain->object;
  593. if (object->getContainerSeqKey() != mCurrSeqKey)
  594. {
  595. object->setContainerSeqKey(mCurrSeqKey);
  596. if ((object->getTypeMask() & mask) != 0 &&
  597. object->isCollisionEnabled())
  598. {
  599. const Box3F &worldBox = object->getWorldBox();
  600. if ( object->isGlobalBounds() || worldBox.isOverlapped( searchBox ) )
  601. {
  602. outFound->push_back( object );
  603. }
  604. }
  605. }
  606. chain = chain->nextInBin;
  607. }
  608. mSearchInProgress = false;
  609. }
  610. //-----------------------------------------------------------------------------
  611. void SceneContainer::findObjectList( const Frustum &frustum, U32 mask, Vector<SceneObject*> *outFound )
  612. {
  613. PROFILE_SCOPE( Container_FindObjectList_Frustum );
  614. // Do a box find first.
  615. findObjectList( frustum.getBounds(), mask, outFound );
  616. // Now do the frustum testing.
  617. for ( U32 i=0; i < outFound->size(); )
  618. {
  619. const Box3F &worldBox = (*outFound)[i]->getWorldBox();
  620. if ( frustum.isCulled( worldBox ) )
  621. outFound->erase_fast( i );
  622. else
  623. i++;
  624. }
  625. }
  626. //-----------------------------------------------------------------------------
  627. void SceneContainer::findObjectList( U32 mask, Vector<SceneObject*> *outFound )
  628. {
  629. for ( Link* itr = mStart.next; itr != &mEnd; itr = itr->next )
  630. {
  631. SceneObject* ptr = static_cast<SceneObject*>( itr );
  632. if ( ( ptr->getTypeMask() & mask ) != 0 )
  633. outFound->push_back( ptr );
  634. }
  635. }
  636. //-----------------------------------------------------------------------------
  637. void SceneContainer::findObjects( U32 mask, FindCallback callback, void *key )
  638. {
  639. for (Link* itr = mStart.next; itr != &mEnd; itr = itr->next) {
  640. SceneObject* ptr = static_cast<SceneObject*>(itr);
  641. if ((ptr->getTypeMask() & mask) != 0 && !ptr->mCollisionCount)
  642. (*callback)(ptr,key);
  643. }
  644. }
  645. //-----------------------------------------------------------------------------
  646. void SceneContainer::_findSpecialObjects( const Vector< SceneObject* >& vector, U32 mask, FindCallback callback, void *key )
  647. {
  648. PROFILE_SCOPE( Container_findSpecialObjects );
  649. Vector<SceneObject*>::const_iterator iter = vector.begin();
  650. for ( ; iter != vector.end(); iter++ )
  651. {
  652. if ( (*iter)->getTypeMask() & mask )
  653. callback( *iter, key );
  654. }
  655. }
  656. //-----------------------------------------------------------------------------
  657. void SceneContainer::_findSpecialObjects( const Vector< SceneObject* >& vector, const Box3F &box, U32 mask, FindCallback callback, void *key )
  658. {
  659. PROFILE_SCOPE( Container_findSpecialObjects_Box );
  660. Vector<SceneObject*>::const_iterator iter = vector.begin();
  661. for ( ; iter != vector.end(); iter++ )
  662. {
  663. SceneObject *pObj = *iter;
  664. if ( pObj->getTypeMask() & mask &&
  665. ( pObj->isGlobalBounds() || pObj->getWorldBox().isOverlapped(box) ) )
  666. {
  667. callback( pObj, key );
  668. }
  669. }
  670. }
  671. //-----------------------------------------------------------------------------
  672. bool SceneContainer::castRay( const Point3F& start, const Point3F& end, U32 mask, RayInfo* info, CastRayCallback callback )
  673. {
  674. AssertFatal( info->userData == NULL, "SceneContainer::castRay - RayInfo->userData cannot be used here!" );
  675. PROFILE_START( SceneContainer_CastRay );
  676. bool result = _castRay( CollisionGeometry, start, end, mask, info, callback );
  677. PROFILE_END();
  678. return result;
  679. }
  680. //-----------------------------------------------------------------------------
  681. bool SceneContainer::castRayRendered( const Point3F& start, const Point3F& end, U32 mask, RayInfo* info, CastRayCallback callback )
  682. {
  683. AssertFatal( info->userData == NULL, "SceneContainer::castRayRendered - RayInfo->userData cannot be used here!" );
  684. PROFILE_START( SceneContainer_CastRayRendered );
  685. bool result = _castRay( RenderedGeometry, start, end, mask, info, callback );
  686. PROFILE_END();
  687. return result;
  688. }
  689. //-----------------------------------------------------------------------------
  690. // DMMNOTE: There are still some optimizations to be done here. In particular:
  691. // - After checking the overflow bin, we can potentially shorten the line
  692. // that we rasterize against the grid if there is a collision with say,
  693. // the terrain.
  694. // - The optimal grid size isn't necessarily what we have set here. possibly
  695. // a resolution of 16 meters would give better results
  696. // - The line rasterizer is pretty lame. Unfortunately we can't use a
  697. // simple bres. here, since we need to check every grid element that the line
  698. // passes through, which bres does _not_ do for us. Possibly there's a
  699. // rasterizer for anti-aliased lines that will serve better than what
  700. // we have below.
  701. bool SceneContainer::_castRay( U32 type, const Point3F& start, const Point3F& end, U32 mask, RayInfo* info, CastRayCallback callback )
  702. {
  703. AssertFatal( !mSearchInProgress, "SceneContainer::_castRay - Container queries are not re-entrant" );
  704. mSearchInProgress = true;
  705. F32 currentT = 2.0;
  706. mCurrSeqKey++;
  707. SceneObjectRef* chain = mOverflowBin.nextInBin;
  708. while (chain)
  709. {
  710. SceneObject* ptr = chain->object;
  711. if (ptr->getContainerSeqKey() != mCurrSeqKey)
  712. {
  713. ptr->setContainerSeqKey(mCurrSeqKey);
  714. // In the overflow bin, the world box is always going to intersect the line,
  715. // so we can omit that test...
  716. if ((ptr->getTypeMask() & mask) != 0 &&
  717. ptr->isCollisionEnabled() == true)
  718. {
  719. Point3F xformedStart, xformedEnd;
  720. ptr->mWorldToObj.mulP(start, &xformedStart);
  721. ptr->mWorldToObj.mulP(end, &xformedEnd);
  722. xformedStart.convolveInverse(ptr->mObjScale);
  723. xformedEnd.convolveInverse(ptr->mObjScale);
  724. RayInfo ri;
  725. ri.generateTexCoord = info->generateTexCoord;
  726. bool result = false;
  727. if (type == CollisionGeometry)
  728. result = ptr->castRay(xformedStart, xformedEnd, &ri);
  729. else if (type == RenderedGeometry)
  730. result = ptr->castRayRendered(xformedStart, xformedEnd, &ri);
  731. if (result)
  732. {
  733. if( ri.t < currentT && ( !callback || callback( &ri ) ) )
  734. {
  735. *info = ri;
  736. info->point.interpolate(start, end, info->t);
  737. currentT = ri.t;
  738. info->distance = (start - info->point).len();
  739. }
  740. }
  741. }
  742. }
  743. chain = chain->nextInBin;
  744. }
  745. // These are just for rasterizing the line against the grid. We want the x coord
  746. // of the start to be <= the x coord of the end
  747. Point3F normalStart, normalEnd;
  748. if (start.x <= end.x)
  749. {
  750. normalStart = start;
  751. normalEnd = end;
  752. }
  753. else
  754. {
  755. normalStart = end;
  756. normalEnd = start;
  757. }
  758. // Ok, let's scan the grids. The simplest way to do this will be to scan across in
  759. // x, finding the y range for each affected bin...
  760. U32 minX, maxX;
  761. U32 minY, maxY;
  762. //if (normalStart.x == normalEnd.x)
  763. // Con::printf("X start = %g, end = %g", normalStart.x, normalEnd.x);
  764. getBinRange(normalStart.x, normalEnd.x, minX, maxX);
  765. getBinRange(getMin(normalStart.y, normalEnd.y),
  766. getMax(normalStart.y, normalEnd.y), minY, maxY);
  767. //if (normalStart.x == normalEnd.x && minX != maxX)
  768. // Con::printf("X min = %d, max = %d", minX, maxX);
  769. //if (normalStart.y == normalEnd.y && minY != maxY)
  770. // Con::printf("Y min = %d, max = %d", minY, maxY);
  771. // We'll optimize the case that the line is contained in one bin row or column, which
  772. // will be quite a few lines. No sense doing more work than we have to...
  773. //
  774. if ((mFabs(normalStart.x - normalEnd.x) < csmTotalBinSize && minX == maxX) ||
  775. (mFabs(normalStart.y - normalEnd.y) < csmTotalBinSize && minY == maxY))
  776. {
  777. U32 count;
  778. U32 incX, incY;
  779. if (minX == maxX)
  780. {
  781. count = maxY - minY + 1;
  782. incX = 0;
  783. incY = 1;
  784. }
  785. else
  786. {
  787. count = maxX - minX + 1;
  788. incX = 1;
  789. incY = 0;
  790. }
  791. U32 x = minX;
  792. U32 y = minY;
  793. for (U32 i = 0; i < count; i++)
  794. {
  795. U32 checkX = x % csmNumBins;
  796. U32 checkY = y % csmNumBins;
  797. SceneObjectRef* chain = mBinArray[(checkY * csmNumBins) + checkX].nextInBin;
  798. while (chain)
  799. {
  800. SceneObject* ptr = chain->object;
  801. if (ptr->getContainerSeqKey() != mCurrSeqKey)
  802. {
  803. ptr->setContainerSeqKey(mCurrSeqKey);
  804. if ((ptr->getTypeMask() & mask) != 0 &&
  805. ptr->isCollisionEnabled() == true)
  806. {
  807. if (ptr->getWorldBox().collideLine(start, end) || chain->object->isGlobalBounds())
  808. {
  809. Point3F xformedStart, xformedEnd;
  810. ptr->mWorldToObj.mulP(start, &xformedStart);
  811. ptr->mWorldToObj.mulP(end, &xformedEnd);
  812. xformedStart.convolveInverse(ptr->mObjScale);
  813. xformedEnd.convolveInverse(ptr->mObjScale);
  814. RayInfo ri;
  815. ri.generateTexCoord = info->generateTexCoord;
  816. bool result = false;
  817. if (type == CollisionGeometry)
  818. result = ptr->castRay(xformedStart, xformedEnd, &ri);
  819. else if (type == RenderedGeometry)
  820. result = ptr->castRayRendered(xformedStart, xformedEnd, &ri);
  821. if (result)
  822. {
  823. if( ri.t < currentT && ( !callback || callback( &ri ) ) )
  824. {
  825. *info = ri;
  826. info->point.interpolate(start, end, info->t);
  827. currentT = ri.t;
  828. info->distance = (start - info->point).len();
  829. }
  830. }
  831. }
  832. }
  833. }
  834. chain = chain->nextInBin;
  835. }
  836. x += incX;
  837. y += incY;
  838. }
  839. }
  840. else
  841. {
  842. // Oh well, let's earn our keep. We know that after the above conditional, we're
  843. // going to cross at least one boundary, so that simplifies our job...
  844. F32 currStartX = normalStart.x;
  845. AssertFatal(currStartX != normalEnd.x, "This is going to cause problems in SceneContainer::castRay");
  846. while (currStartX != normalEnd.x)
  847. {
  848. F32 currEndX = getMin(currStartX + csmTotalBinSize, normalEnd.x);
  849. F32 currStartT = (currStartX - normalStart.x) / (normalEnd.x - normalStart.x);
  850. F32 currEndT = (currEndX - normalStart.x) / (normalEnd.x - normalStart.x);
  851. F32 y1 = normalStart.y + (normalEnd.y - normalStart.y) * currStartT;
  852. F32 y2 = normalStart.y + (normalEnd.y - normalStart.y) * currEndT;
  853. U32 subMinX, subMaxX;
  854. getBinRange(currStartX, currEndX, subMinX, subMaxX);
  855. F32 subStartX = currStartX;
  856. F32 subEndX = currStartX;
  857. if (currStartX < 0.0f)
  858. subEndX -= mFmod(subEndX, csmBinSize);
  859. else
  860. subEndX += (csmBinSize - mFmod(subEndX, csmBinSize));
  861. for (U32 currXBin = subMinX; currXBin <= subMaxX; currXBin++)
  862. {
  863. U32 checkX = currXBin % csmNumBins;
  864. F32 subStartT = (subStartX - currStartX) / (currEndX - currStartX);
  865. F32 subEndT = getMin(F32((subEndX - currStartX) / (currEndX - currStartX)), 1.f);
  866. F32 subY1 = y1 + (y2 - y1) * subStartT;
  867. F32 subY2 = y1 + (y2 - y1) * subEndT;
  868. U32 newMinY, newMaxY;
  869. getBinRange(getMin(subY1, subY2), getMax(subY1, subY2), newMinY, newMaxY);
  870. for (U32 i = newMinY; i <= newMaxY; i++)
  871. {
  872. U32 checkY = i % csmNumBins;
  873. SceneObjectRef* chain = mBinArray[(checkY * csmNumBins) + checkX].nextInBin;
  874. while (chain)
  875. {
  876. SceneObject* ptr = chain->object;
  877. if (ptr->getContainerSeqKey() != mCurrSeqKey)
  878. {
  879. ptr->setContainerSeqKey(mCurrSeqKey);
  880. if ((ptr->getTypeMask() & mask) != 0 &&
  881. ptr->isCollisionEnabled() == true)
  882. {
  883. if (ptr->getWorldBox().collideLine(start, end))
  884. {
  885. Point3F xformedStart, xformedEnd;
  886. ptr->mWorldToObj.mulP(start, &xformedStart);
  887. ptr->mWorldToObj.mulP(end, &xformedEnd);
  888. xformedStart.convolveInverse(ptr->mObjScale);
  889. xformedEnd.convolveInverse(ptr->mObjScale);
  890. RayInfo ri;
  891. ri.generateTexCoord = info->generateTexCoord;
  892. bool result = false;
  893. if (type == CollisionGeometry)
  894. result = ptr->castRay(xformedStart, xformedEnd, &ri);
  895. else if (type == RenderedGeometry)
  896. result = ptr->castRayRendered(xformedStart, xformedEnd, &ri);
  897. if (result)
  898. {
  899. if( ri.t < currentT && ( !callback || callback( &ri ) ) )
  900. {
  901. *info = ri;
  902. info->point.interpolate(start, end, info->t);
  903. currentT = ri.t;
  904. info->distance = (start - info->point).len();
  905. }
  906. }
  907. }
  908. }
  909. }
  910. chain = chain->nextInBin;
  911. }
  912. }
  913. subStartX = subEndX;
  914. subEndX = getMin(subEndX + csmBinSize, currEndX);
  915. }
  916. currStartX = currEndX;
  917. }
  918. }
  919. mSearchInProgress = false;
  920. // Bump the normal into worldspace if appropriate.
  921. if(currentT != 2)
  922. {
  923. PlaneF fakePlane;
  924. fakePlane.x = info->normal.x;
  925. fakePlane.y = info->normal.y;
  926. fakePlane.z = info->normal.z;
  927. fakePlane.d = 0;
  928. PlaneF result;
  929. mTransformPlane(info->object->getTransform(), info->object->getScale(), fakePlane, &result);
  930. info->normal = result;
  931. return true;
  932. }
  933. else
  934. {
  935. // Do nothing and exit...
  936. return false;
  937. }
  938. }
  939. //-----------------------------------------------------------------------------
  940. // collide with the objects projected object box
  941. bool SceneContainer::collideBox(const Point3F &start, const Point3F &end, U32 mask, RayInfo * info)
  942. {
  943. AssertFatal( info->userData == NULL, "SceneContainer::collideBox - RayInfo->userData cannot be used here!" );
  944. F32 currentT = 2;
  945. for (Link* itr = mStart.next; itr != &mEnd; itr = itr->next)
  946. {
  947. SceneObject* ptr = static_cast<SceneObject*>(itr);
  948. if (ptr->getTypeMask() & mask && !ptr->mCollisionCount)
  949. {
  950. Point3F xformedStart, xformedEnd;
  951. ptr->mWorldToObj.mulP(start, &xformedStart);
  952. ptr->mWorldToObj.mulP(end, &xformedEnd);
  953. xformedStart.convolveInverse(ptr->mObjScale);
  954. xformedEnd.convolveInverse(ptr->mObjScale);
  955. RayInfo ri;
  956. if(ptr->collideBox(xformedStart, xformedEnd, &ri))
  957. {
  958. if(ri.t < currentT)
  959. {
  960. *info = ri;
  961. info->point.interpolate(start, end, info->t);
  962. currentT = ri.t;
  963. }
  964. }
  965. }
  966. }
  967. return currentT != 2;
  968. }
  969. //-----------------------------------------------------------------------------
  970. static void buildCallback(SceneObject* object,void *key)
  971. {
  972. SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
  973. object->buildPolyList(info->context,info->polyList,info->boundingBox,info->boundingSphere);
  974. }
  975. bool SceneContainer::buildPolyList(PolyListContext context, const Box3F &box, U32 mask, AbstractPolyList *polyList)
  976. {
  977. CallbackInfo info;
  978. info.context = context;
  979. info.boundingBox = box;
  980. info.polyList = polyList;
  981. // Build bounding sphere
  982. info.boundingSphere.center = (info.boundingBox.minExtents + info.boundingBox.maxExtents) * 0.5;
  983. VectorF bv = box.maxExtents - info.boundingSphere.center;
  984. info.boundingSphere.radius = bv.len();
  985. sPolyList = polyList;
  986. findObjects(box,mask,buildCallback,&info);
  987. return !polyList->isEmpty();
  988. }
  989. //-----------------------------------------------------------------------------
  990. void SceneContainer::cleanupSearchVectors()
  991. {
  992. for (U32 i = 0; i < mSearchList.size(); i++)
  993. delete mSearchList[i];
  994. mSearchList.clear();
  995. mCurrSearchPos = -1;
  996. }
  997. //-----------------------------------------------------------------------------
  998. static Point3F sgSortReferencePoint;
  999. static S32 QSORT_CALLBACK cmpSearchPointers(const void* inP1, const void* inP2)
  1000. {
  1001. SimObjectPtr<SceneObject>** p1 = (SimObjectPtr<SceneObject>**)inP1;
  1002. SimObjectPtr<SceneObject>** p2 = (SimObjectPtr<SceneObject>**)inP2;
  1003. Point3F temp;
  1004. F32 d1, d2;
  1005. if (bool(**p1))
  1006. {
  1007. (**p1)->getWorldBox().getCenter(&temp);
  1008. d1 = (temp - sgSortReferencePoint).len();
  1009. }
  1010. else
  1011. {
  1012. d1 = 0;
  1013. }
  1014. if (bool(**p2))
  1015. {
  1016. (**p2)->getWorldBox().getCenter(&temp);
  1017. d2 = (temp - sgSortReferencePoint).len();
  1018. }
  1019. else
  1020. {
  1021. d2 = 0;
  1022. }
  1023. if (d1 > d2)
  1024. return 1;
  1025. else if (d1 < d2)
  1026. return -1;
  1027. else
  1028. return 0;
  1029. }
  1030. void SceneContainer::initRadiusSearch(const Point3F& searchPoint,
  1031. const F32 searchRadius,
  1032. const U32 searchMask)
  1033. {
  1034. cleanupSearchVectors();
  1035. mSearchReferencePoint = searchPoint;
  1036. Box3F queryBox(searchPoint, searchPoint);
  1037. queryBox.minExtents -= Point3F(searchRadius, searchRadius, searchRadius);
  1038. queryBox.maxExtents += Point3F(searchRadius, searchRadius, searchRadius);
  1039. SimpleQueryList queryList;
  1040. findObjects(queryBox, searchMask, SimpleQueryList::insertionCallback, &queryList);
  1041. F32 radiusSquared = searchRadius * searchRadius;
  1042. const F32* pPoint = &searchPoint.x;
  1043. for (U32 i = 0; i < queryList.mList.size(); i++)
  1044. {
  1045. const F32* bMins;
  1046. const F32* bMaxs;
  1047. bMins = &queryList.mList[i]->getWorldBox().minExtents.x;
  1048. bMaxs = &queryList.mList[i]->getWorldBox().maxExtents.x;
  1049. F32 sum = 0;
  1050. for (U32 j = 0; j < 3; j++)
  1051. {
  1052. if (pPoint[j] < bMins[j])
  1053. sum += (pPoint[j] - bMins[j])*(pPoint[j] - bMins[j]);
  1054. else if (pPoint[j] > bMaxs[j])
  1055. sum += (pPoint[j] - bMaxs[j])*(pPoint[j] - bMaxs[j]);
  1056. }
  1057. if (sum < radiusSquared || queryList.mList[i]->isGlobalBounds())
  1058. {
  1059. mSearchList.push_back(new SimObjectPtr<SceneObject>);
  1060. *(mSearchList.last()) = queryList.mList[i];
  1061. }
  1062. }
  1063. if (mSearchList.size() != 0)
  1064. {
  1065. sgSortReferencePoint = mSearchReferencePoint;
  1066. dQsort(mSearchList.address(), mSearchList.size(),
  1067. sizeof(SimObjectPtr<SceneObject>*), cmpSearchPointers);
  1068. }
  1069. }
  1070. //-----------------------------------------------------------------------------
  1071. void SceneContainer::initTypeSearch(const U32 searchMask)
  1072. {
  1073. cleanupSearchVectors();
  1074. SimpleQueryList queryList;
  1075. findObjects(searchMask, SimpleQueryList::insertionCallback, &queryList);
  1076. for (U32 i = 0; i < queryList.mList.size(); i++)
  1077. {
  1078. mSearchList.push_back(new SimObjectPtr<SceneObject>);
  1079. *(mSearchList.last()) = queryList.mList[i];
  1080. }
  1081. if (mSearchList.size() != 0)
  1082. {
  1083. sgSortReferencePoint = mSearchReferencePoint;
  1084. dQsort(mSearchList.address(), mSearchList.size(),
  1085. sizeof(SimObjectPtr<SceneObject>*), cmpSearchPointers);
  1086. }
  1087. }
  1088. //-----------------------------------------------------------------------------
  1089. SceneObject* SceneContainer::containerSearchNextObject()
  1090. {
  1091. if (mCurrSearchPos >= mSearchList.size())
  1092. return NULL;
  1093. mCurrSearchPos++;
  1094. while (mCurrSearchPos < mSearchList.size() && bool(*mSearchList[mCurrSearchPos]) == false)
  1095. mCurrSearchPos++;
  1096. if (mCurrSearchPos == mSearchList.size())
  1097. return NULL;
  1098. return (*mSearchList[mCurrSearchPos]);
  1099. }
  1100. //-----------------------------------------------------------------------------
  1101. U32 SceneContainer::containerSearchNext()
  1102. {
  1103. SceneObject* object = containerSearchNextObject();
  1104. if( !object )
  1105. return 0;
  1106. return object->getId();
  1107. }
  1108. //-----------------------------------------------------------------------------
  1109. F32 SceneContainer::containerSearchCurrDist()
  1110. {
  1111. AssertFatal(mCurrSearchPos != -1, "Error, must call containerSearchNext before containerSearchCurrDist");
  1112. if (mCurrSearchPos == -1 || mCurrSearchPos >= mSearchList.size() ||
  1113. bool(*mSearchList[mCurrSearchPos]) == false)
  1114. return 0.0;
  1115. Point3F pos;
  1116. (*mSearchList[mCurrSearchPos])->getWorldBox().getCenter(&pos);
  1117. return (pos - mSearchReferencePoint).len();
  1118. }
  1119. //-----------------------------------------------------------------------------
  1120. F32 SceneContainer::containerSearchCurrRadiusDist()
  1121. {
  1122. AssertFatal(mCurrSearchPos != -1, "Error, must call containerSearchNext before containerSearchCurrDist");
  1123. if (mCurrSearchPos == -1 || mCurrSearchPos >= mSearchList.size() ||
  1124. bool(*mSearchList[mCurrSearchPos]) == false)
  1125. return 0.0;
  1126. Point3F pos;
  1127. Box3F worldBox = (*mSearchList[mCurrSearchPos])->getWorldBox();
  1128. worldBox.getCenter(&pos);
  1129. F32 dist = (pos - mSearchReferencePoint).len();
  1130. F32 min = worldBox.len_x();
  1131. if (worldBox.len_y() < min)
  1132. min = worldBox.len_y();
  1133. if (worldBox.len_z() < min)
  1134. min = worldBox.len_z();
  1135. dist -= min;
  1136. if (dist < 0)
  1137. dist = 0;
  1138. return dist;
  1139. }
  1140. //-----------------------------------------------------------------------------
  1141. void SceneContainer::getBinRange( const F32 min, const F32 max, U32& minBin, U32& maxBin )
  1142. {
  1143. AssertFatal(max >= min, avar("Error, bad range in getBinRange. min: %f, max: %f", min, max));
  1144. if ((max - min) >= (SceneContainer::csmTotalBinSize - SceneContainer::csmBinSize))
  1145. {
  1146. F32 minCoord = mFmod(min, SceneContainer::csmTotalBinSize);
  1147. if (minCoord < 0.0f)
  1148. {
  1149. minCoord += SceneContainer::csmTotalBinSize;
  1150. // This is truly lame, but it can happen. There must be a better way to
  1151. // deal with this.
  1152. if (minCoord == SceneContainer::csmTotalBinSize)
  1153. minCoord = SceneContainer::csmTotalBinSize - 0.01;
  1154. }
  1155. AssertFatal(minCoord >= 0.0 && minCoord < SceneContainer::csmTotalBinSize, "Bad minCoord");
  1156. minBin = U32(minCoord / SceneContainer::csmBinSize);
  1157. AssertFatal(minBin < SceneContainer::csmNumBins, avar("Error, bad clipping! (%g, %d)", minCoord, minBin));
  1158. maxBin = minBin + (SceneContainer::csmNumBins - 1);
  1159. return;
  1160. }
  1161. else
  1162. {
  1163. F32 minCoord = mFmod(min, SceneContainer::csmTotalBinSize);
  1164. if (minCoord < 0.0f)
  1165. {
  1166. minCoord += SceneContainer::csmTotalBinSize;
  1167. // This is truly lame, but it can happen. There must be a better way to
  1168. // deal with this.
  1169. if (minCoord == SceneContainer::csmTotalBinSize)
  1170. minCoord = SceneContainer::csmTotalBinSize - 0.01;
  1171. }
  1172. AssertFatal(minCoord >= 0.0 && minCoord < SceneContainer::csmTotalBinSize, "Bad minCoord");
  1173. F32 maxCoord = mFmod(max, SceneContainer::csmTotalBinSize);
  1174. if (maxCoord < 0.0f) {
  1175. maxCoord += SceneContainer::csmTotalBinSize;
  1176. // This is truly lame, but it can happen. There must be a better way to
  1177. // deal with this.
  1178. if (maxCoord == SceneContainer::csmTotalBinSize)
  1179. maxCoord = SceneContainer::csmTotalBinSize - 0.01;
  1180. }
  1181. AssertFatal(maxCoord >= 0.0 && maxCoord < SceneContainer::csmTotalBinSize, "Bad maxCoord");
  1182. minBin = U32(minCoord / SceneContainer::csmBinSize);
  1183. maxBin = U32(maxCoord / SceneContainer::csmBinSize);
  1184. AssertFatal(minBin < SceneContainer::csmNumBins, avar("Error, bad clipping(min)! (%g, %d)", maxCoord, minBin));
  1185. AssertFatal(minBin < SceneContainer::csmNumBins, avar("Error, bad clipping(max)! (%g, %d)", maxCoord, maxBin));
  1186. // MSVC6 seems to be generating some bad floating point code around
  1187. // here when full optimizations are on. The min != max test should
  1188. // not be needed, but it clears up the VC issue.
  1189. if (min != max && minCoord > maxCoord)
  1190. maxBin += SceneContainer::csmNumBins;
  1191. AssertFatal(maxBin >= minBin, "Error, min should always be less than max!");
  1192. }
  1193. }
  1194. //=============================================================================
  1195. // Console API.
  1196. //=============================================================================
  1197. // MARK: ---- Console API ----
  1198. ConsoleFunctionGroupBegin( Containers, "Functions for ray casting and spatial queries.\n\n");
  1199. //-----------------------------------------------------------------------------
  1200. DefineEngineFunction( containerBoxEmpty, bool,
  1201. ( U32 mask, Point3F center, F32 xRadius, F32 yRadius, F32 zRadius, bool useClientContainer ), ( -1, -1, false ),
  1202. "@brief See if any objects of the given types are present in box of given extent.\n\n"
  1203. "@note Extent parameter is last since only one radius is often needed. If "
  1204. "one radius is provided, the yRadius and zRadius are assumed to be the same. Unfortunately, "
  1205. "if you need to use the client container, you'll need to set all of the radius parameters. "
  1206. "Fortunately, this function is mostly used on the server.\n"
  1207. "@param mask Indicates the type of objects we are checking against.\n"
  1208. "@param center Center of box.\n"
  1209. "@param xRadius Search radius in the x-axis. See note above.\n"
  1210. "@param yRadius Search radius in the y-axis. See note above.\n"
  1211. "@param zRadius Search radius in the z-axis. See note above.\n"
  1212. "@param useClientContainer Optionally indicates the search should be within the "
  1213. "client container.\n"
  1214. "@return true if the box is empty, false if any object is found.\n"
  1215. "@ingroup Game")
  1216. {
  1217. Point3F extent( xRadius, yRadius, zRadius );
  1218. extent.y = extent.y >= 0 ? extent.y : extent.x;
  1219. extent.z = extent.z >= 0 ? extent.z : extent.x;
  1220. Box3F B(center - extent, center + extent, true);
  1221. EarlyOutPolyList polyList;
  1222. polyList.mPlaneList.clear();
  1223. polyList.mNormal.set(0,0,0);
  1224. polyList.mPlaneList.setSize(6);
  1225. polyList.mPlaneList[0].set(B.minExtents, VectorF(-1,0,0));
  1226. polyList.mPlaneList[1].set(B.maxExtents, VectorF(0,1,0));
  1227. polyList.mPlaneList[2].set(B.maxExtents, VectorF(1,0,0));
  1228. polyList.mPlaneList[3].set(B.minExtents, VectorF(0,-1,0));
  1229. polyList.mPlaneList[4].set(B.minExtents, VectorF(0,0,-1));
  1230. polyList.mPlaneList[5].set(B.maxExtents, VectorF(0,0,1));
  1231. SceneContainer* pContainer = useClientContainer ? &gClientContainer : &gServerContainer;
  1232. return ! pContainer->buildPolyList(PLC_Collision, B, mask, &polyList);
  1233. }
  1234. //-----------------------------------------------------------------------------
  1235. DefineEngineFunction( initContainerRadiusSearch, void, ( Point3F pos, F32 radius, U32 mask, bool useClientContainer ), ( false ),
  1236. "@brief Start a search for items at the given position and within the given radius, filtering by mask.\n\n"
  1237. "@param pos Center position for the search\n"
  1238. "@param radius Search radius\n"
  1239. "@param mask Bitmask of object types to include in the search\n"
  1240. "@param useClientContainer Optionally indicates the search should be within the "
  1241. "client container.\n"
  1242. "@see containerSearchNext\n"
  1243. "@ingroup Game")
  1244. {
  1245. SceneContainer* pContainer = useClientContainer ? &gClientContainer : &gServerContainer;
  1246. pContainer->initRadiusSearch( pos, radius, mask );
  1247. }
  1248. //-----------------------------------------------------------------------------
  1249. DefineEngineFunction( initContainerTypeSearch, void, ( U32 mask, bool useClientContainer ), ( false ),
  1250. "@brief Start a search for all items of the types specified by the bitset mask.\n\n"
  1251. "@param mask Bitmask of object types to include in the search\n"
  1252. "@param useClientContainer Optionally indicates the search should be within the "
  1253. "client container.\n"
  1254. "@see containerSearchNext\n"
  1255. "@ingroup Game")
  1256. {
  1257. SceneContainer* pContainer = useClientContainer ? &gClientContainer : &gServerContainer;
  1258. pContainer->initTypeSearch( mask );
  1259. }
  1260. //-----------------------------------------------------------------------------
  1261. DefineEngineFunction( containerSearchNext, SceneObject*, ( bool useClientContainer ), ( false ),
  1262. "@brief Get next item from a search started with initContainerRadiusSearch() or "
  1263. "initContainerTypeSearch().\n\n"
  1264. "@param useClientContainer Optionally indicates the search should be within the "
  1265. "client container.\n"
  1266. "@return the next object found in the search, or null if no more\n"
  1267. "@tsexample\n"
  1268. "// print the names of all nearby ShapeBase derived objects\n"
  1269. "%position = %obj.getPosition;\n"
  1270. "%radius = 20;\n"
  1271. "%mask = $TypeMasks::ShapeBaseObjectType;\n"
  1272. "initContainerRadiusSearch( %position, %radius, %mask );\n"
  1273. "while ( (%targetObject = containerSearchNext()) != 0 )\n"
  1274. "{\n"
  1275. " echo( \"Found: \" @ %targetObject.getName() );\n"
  1276. "}\n"
  1277. "@endtsexample\n"
  1278. "@see initContainerRadiusSearch()\n"
  1279. "@see initContainerTypeSearch()\n"
  1280. "@ingroup Game")
  1281. {
  1282. SceneContainer* pContainer = useClientContainer ? &gClientContainer : &gServerContainer;
  1283. return pContainer->containerSearchNextObject();
  1284. }
  1285. //-----------------------------------------------------------------------------
  1286. DefineEngineFunction( containerSearchCurrDist, F32, ( bool useClientContainer ), ( false ),
  1287. "@brief Get distance of the center of the current item from the center of the "
  1288. "current initContainerRadiusSearch.\n\n"
  1289. "@param useClientContainer Optionally indicates the search should be within the "
  1290. "client container.\n"
  1291. "@return distance from the center of the current object to the center of "
  1292. "the search\n"
  1293. "@see containerSearchNext\n"
  1294. "@ingroup Game")
  1295. {
  1296. SceneContainer* pContainer = useClientContainer ? &gClientContainer : &gServerContainer;
  1297. return pContainer->containerSearchCurrDist();
  1298. }
  1299. //-----------------------------------------------------------------------------
  1300. DefineEngineFunction( containerSearchCurrRadiusDist, F32, ( bool useClientContainer ), ( false ),
  1301. "@brief Get the distance of the closest point of the current item from the center "
  1302. "of the current initContainerRadiusSearch.\n\n"
  1303. "@param useClientContainer Optionally indicates the search should be within the "
  1304. "client container.\n"
  1305. "@return distance from the closest point of the current object to the "
  1306. "center of the search\n"
  1307. "@see containerSearchNext\n"
  1308. "@ingroup Game")
  1309. {
  1310. SceneContainer* pContainer = useClientContainer ? &gClientContainer : &gServerContainer;
  1311. return pContainer->containerSearchCurrRadiusDist();
  1312. }
  1313. //-----------------------------------------------------------------------------
  1314. //TODO: make RayInfo an API type
  1315. DefineEngineFunction( containerRayCast, const char*,
  1316. ( Point3F start, Point3F end, U32 mask, SceneObject *pExempt, bool useClientContainer ), ( NULL, false ),
  1317. "@brief Cast a ray from start to end, checking for collision against items matching mask.\n\n"
  1318. "If pExempt is specified, then it is temporarily excluded from collision checks (For "
  1319. "instance, you might want to exclude the player if said player was firing a weapon.)\n"
  1320. "@param start An XYZ vector containing the tail position of the ray.\n"
  1321. "@param end An XYZ vector containing the head position of the ray\n"
  1322. "@param mask A bitmask corresponding to the type of objects to check for\n"
  1323. "@param pExempt An optional ID for a single object that ignored for this raycast\n"
  1324. "@param useClientContainer Optionally indicates the search should be within the "
  1325. "client container.\n"
  1326. "@returns A string containing either null, if nothing was struck, or these fields:\n"
  1327. "<ul><li>The ID of the object that was struck.</li>"
  1328. "<li>The x, y, z position that it was struck.</li>"
  1329. "<li>The x, y, z of the normal of the face that was struck.</li>"
  1330. "<li>The distance between the start point and the position we hit.</li></ul>"
  1331. "@ingroup Game")
  1332. {
  1333. if (pExempt)
  1334. pExempt->disableCollision();
  1335. SceneContainer* pContainer = useClientContainer ? &gClientContainer : &gServerContainer;
  1336. RayInfo rinfo;
  1337. S32 ret = 0;
  1338. if (pContainer->castRay(start, end, mask, &rinfo) == true)
  1339. ret = rinfo.object->getId();
  1340. if (pExempt)
  1341. pExempt->enableCollision();
  1342. // add the hit position and normal?
  1343. static const U32 bufSize = 256;
  1344. char *returnBuffer = Con::getReturnBuffer(bufSize);
  1345. if(ret)
  1346. {
  1347. dSprintf(returnBuffer, bufSize, "%d %g %g %g %g %g %g %g",
  1348. ret, rinfo.point.x, rinfo.point.y, rinfo.point.z,
  1349. rinfo.normal.x, rinfo.normal.y, rinfo.normal.z, rinfo.distance);
  1350. }
  1351. else
  1352. {
  1353. returnBuffer[0] = '0';
  1354. returnBuffer[1] = '\0';
  1355. }
  1356. return(returnBuffer);
  1357. }
  1358. ConsoleFunctionGroupEnd( Containers );