tsShape.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499
  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/tsShape.h"
  24. #include "ts/tsLastDetail.h"
  25. #include "ts/tsMaterialList.h"
  26. #include "core/stringTable.h"
  27. #include "console/console.h"
  28. #include "ts/tsShapeInstance.h"
  29. #include "collision/convex.h"
  30. #include "materials/matInstance.h"
  31. #include "materials/materialManager.h"
  32. #include "math/mathIO.h"
  33. #include "core/util/endian.h"
  34. #include "core/stream/fileStream.h"
  35. #include "console/compiler.h"
  36. #include "core/fileObject.h"
  37. #ifdef TORQUE_COLLADA
  38. extern TSShape* loadColladaShape(const Torque::Path &path);
  39. #endif
  40. #ifdef TORQUE_ASSIMP
  41. extern TSShape* assimpLoadShape(const Torque::Path &path);
  42. #endif
  43. /// most recent version -- this is the version we write
  44. S32 TSShape::smVersion = 28;
  45. /// the version currently being read...valid only during a read
  46. S32 TSShape::smReadVersion = -1;
  47. const U32 TSShape::smMostRecentExporterVersion = DTS_EXPORTER_CURRENT_VERSION;
  48. F32 TSShape::smAlphaOutLastDetail = -1.0f;
  49. F32 TSShape::smAlphaInBillboard = 0.15f;
  50. F32 TSShape::smAlphaOutBillboard = 0.15f;
  51. F32 TSShape::smAlphaInDefault = -1.0f;
  52. F32 TSShape::smAlphaOutDefault = -1.0f;
  53. // don't bother even loading this many of the highest detail levels (but
  54. // always load last renderable detail)
  55. S32 TSShape::smNumSkipLoadDetails = 0;
  56. bool TSShape::smInitOnRead = true;
  57. bool TSShape::smUseHardwareSkinning = true;
  58. U32 TSShape::smMaxSkinBones = 70;
  59. TSShape::TSShape()
  60. {
  61. mExporterVersion = 124;
  62. mSmallestVisibleSize = 2;
  63. mSmallestVisibleDL = 0;
  64. mRadius = 0;
  65. mFlags = 0;
  66. tubeRadius = 0;
  67. data = 0;
  68. materialList = NULL;
  69. mReadVersion = -1; // -1 means constructed from scratch (e.g., in exporter or no read yet)
  70. mSequencesConstructed = false;
  71. mShapeData = NULL;
  72. mShapeDataSize = 0;
  73. mVertexSize = 0;
  74. mUseDetailFromScreenError = false;
  75. mNeedReinit = false;
  76. mDetailLevelLookup.setSize( 1 );
  77. mDetailLevelLookup[0].set( -1, 0 );
  78. VECTOR_SET_ASSOCIATION(sequences);
  79. VECTOR_SET_ASSOCIATION(nodeRotations);
  80. VECTOR_SET_ASSOCIATION(nodeTranslations);
  81. VECTOR_SET_ASSOCIATION(nodeUniformScales);
  82. VECTOR_SET_ASSOCIATION(nodeAlignedScales);
  83. VECTOR_SET_ASSOCIATION(nodeArbitraryScaleRots);
  84. VECTOR_SET_ASSOCIATION(nodeArbitraryScaleFactors);
  85. VECTOR_SET_ASSOCIATION(groundRotations);
  86. VECTOR_SET_ASSOCIATION(groundTranslations);
  87. VECTOR_SET_ASSOCIATION(triggers);
  88. VECTOR_SET_ASSOCIATION(billboardDetails);
  89. VECTOR_SET_ASSOCIATION(detailCollisionAccelerators);
  90. VECTOR_SET_ASSOCIATION(names);
  91. VECTOR_SET_ASSOCIATION( nodes );
  92. VECTOR_SET_ASSOCIATION( objects );
  93. VECTOR_SET_ASSOCIATION( objectStates );
  94. VECTOR_SET_ASSOCIATION( subShapeFirstNode );
  95. VECTOR_SET_ASSOCIATION( subShapeFirstObject );
  96. VECTOR_SET_ASSOCIATION( detailFirstSkin );
  97. VECTOR_SET_ASSOCIATION( subShapeNumNodes );
  98. VECTOR_SET_ASSOCIATION( subShapeNumObjects );
  99. VECTOR_SET_ASSOCIATION( details );
  100. VECTOR_SET_ASSOCIATION( defaultRotations );
  101. VECTOR_SET_ASSOCIATION( defaultTranslations );
  102. VECTOR_SET_ASSOCIATION( subShapeFirstTranslucentObject );
  103. VECTOR_SET_ASSOCIATION( meshes );
  104. VECTOR_SET_ASSOCIATION( alphaIn );
  105. VECTOR_SET_ASSOCIATION( alphaOut );
  106. }
  107. TSShape::~TSShape()
  108. {
  109. delete materialList;
  110. S32 i;
  111. // everything left over here is a legit mesh
  112. for (i=0; i<meshes.size(); i++)
  113. {
  114. if (!meshes[i])
  115. continue;
  116. // Handle meshes that were either assembled with the shape or added later
  117. if (((S8*)meshes[i] >= mShapeData) && ((S8*)meshes[i] < (mShapeData + mShapeDataSize)))
  118. destructInPlace(meshes[i]);
  119. else
  120. delete meshes[i];
  121. }
  122. for (i=0; i<billboardDetails.size(); i++)
  123. {
  124. delete billboardDetails[i];
  125. billboardDetails[i] = NULL;
  126. }
  127. billboardDetails.clear();
  128. // Delete any generated accelerators
  129. S32 dca;
  130. for (dca = 0; dca < detailCollisionAccelerators.size(); dca++)
  131. {
  132. ConvexHullAccelerator* accel = detailCollisionAccelerators[dca];
  133. if (accel != NULL) {
  134. delete [] accel->vertexList;
  135. delete [] accel->normalList;
  136. for (S32 j = 0; j < accel->numVerts; j++)
  137. delete [] accel->emitStrings[j];
  138. delete [] accel->emitStrings;
  139. delete accel;
  140. }
  141. }
  142. for (dca = 0; dca < detailCollisionAccelerators.size(); dca++)
  143. detailCollisionAccelerators[dca] = NULL;
  144. if( mShapeData )
  145. delete[] mShapeData;
  146. }
  147. const String& TSShape::getName( S32 nameIndex ) const
  148. {
  149. AssertFatal(nameIndex>=0 && nameIndex<names.size(),"TSShape::getName");
  150. return names[nameIndex];
  151. }
  152. const String& TSShape::getMeshName( S32 meshIndex ) const
  153. {
  154. S32 nameIndex = objects[meshIndex].nameIndex;
  155. if ( nameIndex < 0 )
  156. return String::EmptyString;
  157. return names[nameIndex];
  158. }
  159. const String& TSShape::getNodeName( S32 nodeIndex ) const
  160. {
  161. S32 nameIdx = nodes[nodeIndex].nameIndex;
  162. if ( nameIdx < 0 )
  163. return String::EmptyString;
  164. return names[nameIdx];
  165. }
  166. const String& TSShape::getSequenceName( S32 seqIndex ) const
  167. {
  168. AssertFatal(seqIndex >= 0 && seqIndex<sequences.size(),"TSShape::getSequenceName index beyond range");
  169. S32 nameIdx = sequences[seqIndex].nameIndex;
  170. if ( nameIdx < 0 )
  171. return String::EmptyString;
  172. return names[nameIdx];
  173. }
  174. S32 TSShape::findName(const String &name) const
  175. {
  176. for (S32 i=0; i<names.size(); i++)
  177. {
  178. if (names[i].equal( name, String::NoCase ))
  179. return i;
  180. }
  181. return -1;
  182. }
  183. const String& TSShape::getTargetName( S32 mapToNameIndex ) const
  184. {
  185. S32 targetCount = materialList->getMaterialNameList().size();
  186. if(mapToNameIndex < 0 || mapToNameIndex >= targetCount)
  187. return String::EmptyString;
  188. return materialList->getMaterialNameList()[mapToNameIndex];
  189. }
  190. S32 TSShape::getTargetCount() const
  191. {
  192. return materialList->getMaterialNameList().size();
  193. }
  194. S32 TSShape::findNode(S32 nameIndex) const
  195. {
  196. for (S32 i=0; i<nodes.size(); i++)
  197. if (nodes[i].nameIndex==nameIndex)
  198. return i;
  199. return -1;
  200. }
  201. S32 TSShape::findObject(S32 nameIndex) const
  202. {
  203. for (S32 i=0; i<objects.size(); i++)
  204. if (objects[i].nameIndex==nameIndex)
  205. return i;
  206. return -1;
  207. }
  208. S32 TSShape::findDetail(S32 nameIndex) const
  209. {
  210. for (S32 i=0; i<details.size(); i++)
  211. if (details[i].nameIndex==nameIndex)
  212. return i;
  213. return -1;
  214. }
  215. S32 TSShape::findDetailBySize(S32 size) const
  216. {
  217. for (S32 i=0; i<details.size(); i++)
  218. if (details[i].size==size)
  219. return i;
  220. return -1;
  221. }
  222. S32 TSShape::findSequence(S32 nameIndex) const
  223. {
  224. for (S32 i=0; i<sequences.size(); i++)
  225. if (sequences[i].nameIndex==nameIndex)
  226. return i;
  227. return -1;
  228. }
  229. bool TSShape::findMeshIndex(const String& meshName, S32& objIndex, S32& meshIndex)
  230. {
  231. // Determine the object name and detail size from the mesh name
  232. S32 detailSize = 999;
  233. objIndex = findObject(String::GetTrailingNumber(meshName, detailSize));
  234. if (objIndex < 0)
  235. return false;
  236. // Determine the subshape this object belongs to
  237. S32 subShapeIndex = getSubShapeForObject(objIndex);
  238. AssertFatal(subShapeIndex < subShapeFirstObject.size(), "Could not find subshape for object!");
  239. // Get the detail levels for the subshape
  240. Vector<S32> validDetails;
  241. getSubShapeDetails(subShapeIndex, validDetails);
  242. // Find the detail with the correct size
  243. for (meshIndex = 0; meshIndex < validDetails.size(); meshIndex++)
  244. {
  245. const TSShape::Detail& det = details[validDetails[meshIndex]];
  246. if (detailSize == det.size)
  247. return true;
  248. }
  249. return false;
  250. }
  251. bool TSShape::needsBufferUpdate()
  252. {
  253. // No buffer? definitely need an update!
  254. if (mVertexSize == 0 || mShapeVertexData.size == 0)
  255. return true;
  256. // Check if we have modified vertex data
  257. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  258. {
  259. TSMesh *mesh = *iter;
  260. if (!mesh ||
  261. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  262. mesh->getMeshType() != TSMesh::SkinMeshType))
  263. continue;
  264. // NOTE: cant use mVertexData.isReady since that might not be init'd at this stage
  265. if (mesh->mVertSize == 0)
  266. return true;
  267. }
  268. return false;
  269. }
  270. TSMesh* TSShape::findMesh(const String& meshName)
  271. {
  272. S32 objIndex, meshIndex;
  273. if (!findMeshIndex(meshName, objIndex, meshIndex))
  274. return 0;
  275. return meshes[objects[objIndex].startMeshIndex + meshIndex];
  276. }
  277. S32 TSShape::getSubShapeForNode(S32 nodeIndex)
  278. {
  279. for (S32 i = 0; i < subShapeFirstNode.size(); i++)
  280. {
  281. S32 start = subShapeFirstNode[i];
  282. S32 end = start + subShapeNumNodes[i];
  283. if ((nodeIndex >= start) && (nodeIndex < end))
  284. return i;;
  285. }
  286. return -1;
  287. }
  288. S32 TSShape::getSubShapeForObject(S32 objIndex)
  289. {
  290. for (S32 i = 0; i < subShapeFirstObject.size(); i++)
  291. {
  292. S32 start = subShapeFirstObject[i];
  293. S32 end = start + subShapeNumObjects[i];
  294. if ((objIndex >= start) && (objIndex < end))
  295. return i;
  296. }
  297. return -1;
  298. }
  299. void TSShape::getSubShapeDetails(S32 subShapeIndex, Vector<S32>& validDetails)
  300. {
  301. validDetails.clear();
  302. for (S32 i = 0; i < details.size(); i++)
  303. {
  304. if ((details[i].subShapeNum == subShapeIndex) ||
  305. (details[i].subShapeNum < 0))
  306. validDetails.push_back(i);
  307. }
  308. }
  309. void TSShape::getNodeWorldTransform(S32 nodeIndex, MatrixF* mat) const
  310. {
  311. if ( nodeIndex == -1 )
  312. {
  313. mat->identity();
  314. }
  315. else
  316. {
  317. // Calculate the world transform of the given node
  318. defaultRotations[nodeIndex].getQuatF().setMatrix(mat);
  319. mat->setPosition(defaultTranslations[nodeIndex]);
  320. S32 parentIndex = nodes[nodeIndex].parentIndex;
  321. while (parentIndex != -1)
  322. {
  323. MatrixF mat2(*mat);
  324. defaultRotations[parentIndex].getQuatF().setMatrix(mat);
  325. mat->setPosition(defaultTranslations[parentIndex]);
  326. mat->mul(mat2);
  327. parentIndex = nodes[parentIndex].parentIndex;
  328. }
  329. }
  330. }
  331. void TSShape::getNodeObjects(S32 nodeIndex, Vector<S32>& nodeObjects)
  332. {
  333. for (S32 i = 0; i < objects.size(); i++)
  334. {
  335. if ((nodeIndex == -1) || (objects[i].nodeIndex == nodeIndex))
  336. nodeObjects.push_back(i);
  337. }
  338. }
  339. void TSShape::getNodeChildren(S32 nodeIndex, Vector<S32>& nodeChildren)
  340. {
  341. for (S32 i = 0; i < nodes.size(); i++)
  342. {
  343. if (nodes[i].parentIndex == nodeIndex)
  344. nodeChildren.push_back(i);
  345. }
  346. }
  347. void TSShape::getObjectDetails(S32 objIndex, Vector<S32>& objDetails)
  348. {
  349. // Get the detail levels for this subshape
  350. Vector<S32> validDetails;
  351. getSubShapeDetails(getSubShapeForObject(objIndex), validDetails);
  352. // Get the non-null details for this object
  353. const TSShape::Object& obj = objects[objIndex];
  354. for (S32 i = 0; i < obj.numMeshes; i++)
  355. {
  356. if (meshes[obj.startMeshIndex + i])
  357. objDetails.push_back(validDetails[i]);
  358. }
  359. }
  360. void TSShape::init()
  361. {
  362. initObjects();
  363. initVertexFeatures();
  364. initMaterialList();
  365. mNeedReinit = false;
  366. }
  367. void TSShape::initObjects()
  368. {
  369. S32 numSubShapes = subShapeFirstNode.size();
  370. AssertFatal(numSubShapes == subShapeFirstObject.size(), "TSShape::initObjects");
  371. S32 i, j;
  372. // set up parent/child relationships on nodes and objects
  373. for (i = 0; i<nodes.size(); i++)
  374. nodes[i].firstObject = nodes[i].firstChild = nodes[i].nextSibling = -1;
  375. for (i = 0; i<nodes.size(); i++)
  376. {
  377. S32 parentIndex = nodes[i].parentIndex;
  378. if (parentIndex >= 0)
  379. {
  380. if (nodes[parentIndex].firstChild<0)
  381. nodes[parentIndex].firstChild = i;
  382. else
  383. {
  384. S32 child = nodes[parentIndex].firstChild;
  385. while (nodes[child].nextSibling >= 0)
  386. child = nodes[child].nextSibling;
  387. nodes[child].nextSibling = i;
  388. }
  389. }
  390. }
  391. for (i = 0; i<objects.size(); i++)
  392. {
  393. objects[i].nextSibling = -1;
  394. S32 nodeIndex = objects[i].nodeIndex;
  395. if (nodeIndex >= 0)
  396. {
  397. if (nodes[nodeIndex].firstObject<0)
  398. nodes[nodeIndex].firstObject = i;
  399. else
  400. {
  401. S32 objectIndex = nodes[nodeIndex].firstObject;
  402. while (objects[objectIndex].nextSibling >= 0)
  403. objectIndex = objects[objectIndex].nextSibling;
  404. objects[objectIndex].nextSibling = i;
  405. }
  406. }
  407. }
  408. mFlags = 0;
  409. for (i = 0; i<sequences.size(); i++)
  410. {
  411. if (!sequences[i].animatesScale())
  412. continue;
  413. U32 curVal = mFlags & AnyScale;
  414. U32 newVal = sequences[i].flags & AnyScale;
  415. mFlags &= ~(AnyScale);
  416. mFlags |= getMax(curVal, newVal); // take the larger value (can only convert upwards)
  417. }
  418. // set up alphaIn and alphaOut vectors...
  419. alphaIn.setSize(details.size());
  420. alphaOut.setSize(details.size());
  421. for (i = 0; i<details.size(); i++)
  422. {
  423. if (details[i].size<0)
  424. {
  425. // we don't care...
  426. alphaIn[i] = 0.0f;
  427. alphaOut[i] = 0.0f;
  428. }
  429. else if (i + 1 == details.size() || details[i + 1].size<0)
  430. {
  431. alphaIn[i] = 0.0f;
  432. alphaOut[i] = smAlphaOutLastDetail;
  433. }
  434. else
  435. {
  436. if (details[i + 1].subShapeNum<0)
  437. {
  438. // following detail is a billboard detail...treat special...
  439. alphaIn[i] = smAlphaInBillboard;
  440. alphaOut[i] = smAlphaOutBillboard;
  441. }
  442. else
  443. {
  444. // next detail is normal detail
  445. alphaIn[i] = smAlphaInDefault;
  446. alphaOut[i] = smAlphaOutDefault;
  447. }
  448. }
  449. }
  450. for (i = mSmallestVisibleDL - 1; i >= 0; i--)
  451. {
  452. if (i<smNumSkipLoadDetails)
  453. {
  454. // this detail level renders when pixel size
  455. // is larger than our cap...zap all the meshes and decals
  456. // associated with it and use the next detail level
  457. // instead...
  458. S32 ss = details[i].subShapeNum;
  459. S32 od = details[i].objectDetailNum;
  460. if (ss == details[i + 1].subShapeNum && od == details[i + 1].objectDetailNum)
  461. // doh! already done this one (init can be called multiple times on same shape due
  462. // to sequence importing).
  463. continue;
  464. details[i].subShapeNum = details[i + 1].subShapeNum;
  465. details[i].objectDetailNum = details[i + 1].objectDetailNum;
  466. }
  467. }
  468. for (i = 0; i<details.size(); i++)
  469. {
  470. S32 count = 0;
  471. S32 ss = details[i].subShapeNum;
  472. S32 od = details[i].objectDetailNum;
  473. if (ss<0)
  474. {
  475. // billboard detail...
  476. details[i].polyCount = 2;
  477. continue;
  478. }
  479. S32 start = subShapeFirstObject[ss];
  480. S32 end = start + subShapeNumObjects[ss];
  481. for (j = start; j<end; j++)
  482. {
  483. Object & obj = objects[j];
  484. if (od<obj.numMeshes)
  485. {
  486. TSMesh * mesh = meshes[obj.startMeshIndex + od];
  487. count += mesh ? mesh->getNumPolys() : 0;
  488. }
  489. }
  490. details[i].polyCount = count;
  491. }
  492. // Init the collision accelerator array. Note that we don't compute the
  493. // accelerators until the app requests them
  494. {
  495. S32 dca;
  496. for (dca = 0; dca < detailCollisionAccelerators.size(); dca++)
  497. {
  498. ConvexHullAccelerator* accel = detailCollisionAccelerators[dca];
  499. if (accel != NULL) {
  500. delete[] accel->vertexList;
  501. delete[] accel->normalList;
  502. for (S32 vertID = 0; vertID < accel->numVerts; vertID++)
  503. delete[] accel->emitStrings[vertID];
  504. delete[] accel->emitStrings;
  505. delete accel;
  506. }
  507. }
  508. detailCollisionAccelerators.setSize(details.size());
  509. for (dca = 0; dca < detailCollisionAccelerators.size(); dca++)
  510. detailCollisionAccelerators[dca] = NULL;
  511. }
  512. // Assign mesh parents & format
  513. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  514. {
  515. TSMesh *mesh = *iter;
  516. if (!mesh)
  517. continue;
  518. if (mesh->mParentMesh >= meshes.size())
  519. {
  520. Con::warnf("Mesh %i has a bad parentMeshObject (%i)", iter - meshes.begin(), mesh->mParentMesh);
  521. }
  522. if (mesh->mParentMesh >= 0 && mesh->mParentMesh < meshes.size())
  523. {
  524. mesh->mParentMeshObject = meshes[mesh->mParentMesh];
  525. }
  526. else
  527. {
  528. mesh->mParentMeshObject = NULL;
  529. }
  530. mesh->mVertexFormat = &mVertexFormat;
  531. }
  532. }
  533. void TSShape::initVertexBuffers()
  534. {
  535. // Assumes mVertexData is valid
  536. if (!mShapeVertexData.vertexDataReady)
  537. {
  538. AssertFatal(false, "WTF");
  539. }
  540. U32 destIndices = 0;
  541. U32 destPrims = 0;
  542. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  543. {
  544. TSMesh *mesh = *iter;
  545. if (!mesh ||
  546. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  547. mesh->getMeshType() != TSMesh::SkinMeshType))
  548. continue;
  549. destIndices += mesh->mIndices.size();
  550. destPrims += mesh->mPrimitives.size();
  551. }
  552. // For HW skinning we can just use the static buffer
  553. if (TSShape::smUseHardwareSkinning)
  554. {
  555. getVertexBuffer(mShapeVertexBuffer, GFXBufferTypeStatic);
  556. }
  557. // Also the IBO
  558. mShapeVertexIndices.set(GFX, destIndices, destPrims, GFXBufferTypeStatic);
  559. U16 *indicesStart = NULL;
  560. mShapeVertexIndices.lock(&indicesStart, NULL);
  561. U16 *ibIndices = indicesStart;
  562. GFXPrimitive *piInput = mShapeVertexIndices->mPrimitiveArray;
  563. U32 vertStart = 0;
  564. U32 primStart = 0;
  565. U32 indStart = 0;
  566. // Create VBO
  567. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  568. {
  569. TSMesh *mesh = *iter;
  570. if (!mesh ||
  571. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  572. mesh->getMeshType() != TSMesh::SkinMeshType))
  573. continue;
  574. // Make the offset vbo
  575. mesh->mPrimBufferOffset = primStart;
  576. // Dump primitives to locked buffer
  577. mesh->dumpPrimitives(vertStart, indStart, piInput, ibIndices);
  578. AssertFatal(mesh->mVertOffset / mVertexSize == vertStart, "offset mismatch");
  579. vertStart += mesh->mNumVerts;
  580. primStart += mesh->mPrimitives.size();
  581. indStart += mesh->mIndices.size();
  582. mesh->mVB = mShapeVertexBuffer;
  583. mesh->mPB = mShapeVertexIndices;
  584. // Advance
  585. piInput += mesh->mPrimitives.size();
  586. ibIndices += mesh->mIndices.size();
  587. if (TSSkinMesh::smDebugSkinVerts && mesh->getMeshType() == TSMesh::SkinMeshType)
  588. {
  589. static_cast<TSSkinMesh*>(mesh)->printVerts();
  590. }
  591. }
  592. #ifdef TORQUE_DEBUG
  593. // Verify prims
  594. if (TSSkinMesh::smDebugSkinVerts)
  595. {
  596. U32 vertsInBuffer = mShapeVertexData.size / mVertexSize;
  597. U32 indsInBuffer = ibIndices - indicesStart;
  598. for (U32 primID = 0; primID < primStart; primID++)
  599. {
  600. GFXPrimitive &prim = mShapeVertexIndices->mPrimitiveArray[primID];
  601. if (prim.type != GFXTriangleList && prim.type != GFXTriangleStrip)
  602. {
  603. AssertFatal(false, "Unexpected triangle list");
  604. }
  605. if (prim.type == GFXTriangleStrip)
  606. continue;
  607. AssertFatal(prim.startVertex < vertsInBuffer, "wrong start vertex");
  608. AssertFatal((prim.startVertex + prim.numVertices) <= vertsInBuffer, "too many verts");
  609. AssertFatal(prim.startIndex + (prim.numPrimitives * 3) <= indsInBuffer, "too many inds");
  610. for (U32 i = prim.startIndex; i < prim.startIndex + (prim.numPrimitives * 3); i++)
  611. {
  612. if (indicesStart[i] >= vertsInBuffer)
  613. {
  614. AssertFatal(false, "vert not in buffer");
  615. }
  616. U16 idx = indicesStart[i];
  617. if (idx < prim.minIndex)
  618. {
  619. AssertFatal(false, "index out of minIndex range");
  620. }
  621. }
  622. }
  623. }
  624. #endif
  625. mShapeVertexIndices.unlock();
  626. }
  627. void TSShape::getVertexBuffer(TSVertexBufferHandle &vb, GFXBufferType bufferType)
  628. {
  629. vb.set(GFX, mVertexSize, &mVertexFormat, mShapeVertexData.size / mVertexSize, bufferType);
  630. U8 *vertPtr = vb.lock();
  631. dMemcpy(vertPtr, mShapeVertexData.base, mShapeVertexData.size);
  632. vb.unlock();
  633. }
  634. void TSShape::initVertexBufferPointers()
  635. {
  636. if (mBasicVertexFormat.vertexSize == -1)
  637. return;
  638. AssertFatal(mVertexSize == mBasicVertexFormat.vertexSize, "vertex size mismatch");
  639. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  640. {
  641. TSMesh *mesh = *iter;
  642. if (mesh &&
  643. (mesh->getMeshType() == TSMesh::StandardMeshType ||
  644. mesh->getMeshType() == TSMesh::SkinMeshType))
  645. {
  646. // Set buffer
  647. AssertFatal(mesh->mNumVerts == 0 || mesh->mNumVerts >= mesh->vertsPerFrame, "invalid verts per frame");
  648. if (mesh->mVertSize > 0 && !mesh->mVertexData.isReady())
  649. {
  650. U32 boneOffset = 0;
  651. U32 texCoordOffset = 0;
  652. AssertFatal(mesh->mVertSize == mVertexFormat.getSizeInBytes(), "mismatch in format size");
  653. if (mBasicVertexFormat.boneOffset >= 0)
  654. {
  655. boneOffset = mBasicVertexFormat.boneOffset;
  656. }
  657. if (mBasicVertexFormat.texCoordOffset >= 0)
  658. {
  659. texCoordOffset = mBasicVertexFormat.texCoordOffset;
  660. }
  661. // Initialize the vertex data
  662. mesh->mVertexData.set(mShapeVertexData.base + mesh->mVertOffset, mesh->mVertSize, mesh->mNumVerts, texCoordOffset, boneOffset, false);
  663. mesh->mVertexData.setReady(true);
  664. }
  665. }
  666. }
  667. }
  668. void TSShape::initVertexFeatures()
  669. {
  670. if (!needsBufferUpdate())
  671. {
  672. // Init format from basic format
  673. mVertexFormat.clear();
  674. mBasicVertexFormat.getFormat(mVertexFormat);
  675. mVertexSize = mVertexFormat.getSizeInBytes();
  676. initVertexBufferPointers();
  677. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  678. {
  679. TSMesh *mesh = *iter;
  680. if (mesh &&
  681. (mesh->getMeshType() == TSMesh::SkinMeshType))
  682. {
  683. static_cast<TSSkinMesh*>(mesh)->createSkinBatchData();
  684. }
  685. }
  686. // Make sure VBO is init'd
  687. initVertexBuffers();
  688. return;
  689. }
  690. // Cleanout VBO
  691. mShapeVertexBuffer = NULL;
  692. // Make sure mesh has verts stored in mesh data, we're recreating the buffer
  693. TSBasicVertexFormat basicFormat;
  694. initVertexBufferPointers();
  695. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  696. {
  697. TSMesh *mesh = *iter;
  698. if (mesh &&
  699. (mesh->getMeshType() == TSMesh::StandardMeshType ||
  700. mesh->getMeshType() == TSMesh::SkinMeshType))
  701. {
  702. // Make sure we have everything in the vert lists
  703. mesh->makeEditable();
  704. // We need the skin batching data here to determine bone counts
  705. if (mesh->getMeshType() == TSMesh::SkinMeshType)
  706. {
  707. static_cast<TSSkinMesh*>(mesh)->createSkinBatchData();
  708. }
  709. basicFormat.addMeshRequirements(mesh);
  710. }
  711. }
  712. mVertexFormat.clear();
  713. mBasicVertexFormat = basicFormat;
  714. mBasicVertexFormat.getFormat(mVertexFormat);
  715. mBasicVertexFormat.vertexSize = mVertexFormat.getSizeInBytes();
  716. mVertexSize = mBasicVertexFormat.vertexSize;
  717. U32 destVertex = 0;
  718. U32 destIndices = 0;
  719. // Go fix up meshes to include defaults for optional features
  720. // and initialize them if they're not a skin mesh.
  721. U32 count = 0;
  722. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  723. {
  724. TSMesh *mesh = *iter;
  725. if (!mesh ||
  726. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  727. mesh->getMeshType() != TSMesh::SkinMeshType))
  728. continue;
  729. mesh->mVertSize = mVertexSize;
  730. mesh->mVertOffset = destVertex;
  731. destVertex += mesh->mVertSize * mesh->getNumVerts();
  732. destIndices += mesh->mIndices.size();
  733. count += 1;
  734. }
  735. // Don't set up if we have no meshes
  736. if (count == 0)
  737. {
  738. mShapeVertexData.set(NULL, 0);
  739. mShapeVertexData.vertexDataReady = false;
  740. return;
  741. }
  742. // Now we can create the VBO
  743. mShapeVertexData.set(NULL, 0);
  744. U8 *vertexData = (U8*)dMalloc_aligned(destVertex, 16);
  745. U8 *vertexDataPtr = vertexData;
  746. mShapeVertexData.set(vertexData, destVertex);
  747. // Create VBO
  748. for (Vector<TSMesh*>::iterator iter = meshes.begin(); iter != meshes.end(); iter++)
  749. {
  750. TSMesh *mesh = *iter;
  751. if (!mesh ||
  752. (mesh->getMeshType() != TSMesh::StandardMeshType &&
  753. mesh->getMeshType() != TSMesh::SkinMeshType))
  754. continue;
  755. U32 boneOffset = 0;
  756. U32 texCoordOffset = 0;
  757. AssertFatal(mesh->mVertSize == mVertexFormat.getSizeInBytes(), "mismatch in format size");
  758. if (mBasicVertexFormat.boneOffset >= 0)
  759. {
  760. boneOffset = mBasicVertexFormat.boneOffset;
  761. }
  762. if (mBasicVertexFormat.texCoordOffset >= 0)
  763. {
  764. texCoordOffset = mBasicVertexFormat.texCoordOffset;
  765. }
  766. // Dump everything
  767. mesh->mVertexData.setReady(false);
  768. mesh->mVertSize = mVertexSize;
  769. AssertFatal(mesh->mVertOffset == vertexDataPtr - vertexData, "vertex offset mismatch");
  770. mesh->mNumVerts = mesh->getNumVerts();
  771. // Correct bad meshes
  772. if (mesh->mNumVerts != 0 && mesh->vertsPerFrame > mesh->mNumVerts)
  773. {
  774. Con::warnf("Shape mesh has bad vertsPerFrame (%i, should be <= %i)", mesh->vertsPerFrame, mesh->mNumVerts);
  775. mesh->vertsPerFrame = mesh->mNumVerts;
  776. }
  777. mesh->mVertexData.set(mShapeVertexData.base + mesh->mVertOffset, mesh->mVertSize, mesh->mNumVerts, texCoordOffset, boneOffset, false);
  778. mesh->convertToVertexData();
  779. mesh->mVertexData.setReady(true);
  780. #ifdef TORQUE_DEBUG
  781. AssertFatal(mesh->mNumVerts == mesh->mVerts.size(), "vert mismatch");
  782. for (U32 i = 0; i < mesh->mNumVerts; i++)
  783. {
  784. Point3F v1 = mesh->mVerts[i];
  785. Point3F v2 = mesh->mVertexData.getBase(i).vert();
  786. AssertFatal(mesh->mVerts[i] == mesh->mVertexData.getBase(i).vert(), "vert data mismatch");
  787. }
  788. if (mesh->getMeshType() == TSMesh::SkinMeshType)
  789. {
  790. AssertFatal(mesh->getMaxBonesPerVert() != 0, "Skin mesh has no bones used, very strange!");
  791. }
  792. #endif
  793. // Advance
  794. vertexDataPtr += mesh->mVertSize * mesh->mNumVerts;
  795. AssertFatal(vertexDataPtr - vertexData <= destVertex, "Vertex data overflow");
  796. }
  797. mShapeVertexData.vertexDataReady = true;
  798. initVertexBuffers();
  799. }
  800. void TSShape::setupBillboardDetails( const String &cachePath )
  801. {
  802. // set up billboard details -- only do this once, meaning that
  803. // if we add a sequence to the shape we don't redo the billboard
  804. // details...
  805. if ( !billboardDetails.empty() )
  806. return;
  807. for ( U32 i=0; i < details.size(); i++ )
  808. {
  809. const Detail &det = details[i];
  810. if ( det.subShapeNum >= 0 )
  811. continue; // not a billboard detail
  812. while (billboardDetails.size() <= i )
  813. billboardDetails.push_back(NULL);
  814. billboardDetails[i] = new TSLastDetail( this,
  815. cachePath,
  816. det.bbEquatorSteps,
  817. det.bbPolarSteps,
  818. det.bbPolarAngle,
  819. det.bbIncludePoles,
  820. det.bbDetailLevel,
  821. det.bbDimension );
  822. billboardDetails[i]->update();
  823. }
  824. }
  825. void TSShape::setupBillboardDetails(const String& cachePath, const String& diffsePath, const String& normalPath)
  826. {
  827. // set up billboard details -- only do this once, meaning that
  828. // if we add a sequence to the shape we don't redo the billboard
  829. // details...
  830. if (!billboardDetails.empty())
  831. return;
  832. for (U32 i = 0; i < details.size(); i++)
  833. {
  834. const Detail& det = details[i];
  835. if (det.subShapeNum >= 0)
  836. continue; // not a billboard detail
  837. while (billboardDetails.size() <= i)
  838. billboardDetails.push_back(NULL);
  839. billboardDetails[i] = new TSLastDetail(this,
  840. cachePath,
  841. diffsePath,
  842. normalPath,
  843. det.bbEquatorSteps,
  844. det.bbPolarSteps,
  845. det.bbPolarAngle,
  846. det.bbIncludePoles,
  847. det.bbDetailLevel,
  848. det.bbDimension);
  849. billboardDetails[i]->update();
  850. }
  851. }
  852. void TSShape::initMaterialList()
  853. {
  854. S32 numSubShapes = subShapeFirstObject.size();
  855. #if defined(TORQUE_MAX_LIB)
  856. subShapeFirstTranslucentObject.setSize(numSubShapes);
  857. #endif
  858. S32 i,j,k;
  859. // for each subshape, find the first translucent object
  860. // also, while we're at it, set mHasTranslucency
  861. for (S32 ss = 0; ss<numSubShapes; ss++)
  862. {
  863. S32 start = subShapeFirstObject[ss];
  864. S32 end = subShapeNumObjects[ss];
  865. subShapeFirstTranslucentObject[ss] = end;
  866. for (i=start; i<end; i++)
  867. {
  868. // check to see if this object has translucency
  869. Object & obj = objects[i];
  870. for (j=0; j<obj.numMeshes; j++)
  871. {
  872. TSMesh * mesh = meshes[obj.startMeshIndex+j];
  873. if (!mesh)
  874. continue;
  875. for (k=0; k<mesh->mPrimitives.size(); k++)
  876. {
  877. if (mesh->mPrimitives[k].matIndex & TSDrawPrimitive::NoMaterial)
  878. continue;
  879. S32 flags = materialList->getFlags(mesh->mPrimitives[k].matIndex & TSDrawPrimitive::MaterialMask);
  880. if (flags & TSMaterialList::AuxiliaryMap)
  881. continue;
  882. if (flags & TSMaterialList::Translucent)
  883. {
  884. mFlags |= HasTranslucency;
  885. subShapeFirstTranslucentObject[ss] = i;
  886. break;
  887. }
  888. }
  889. if (k!=mesh->mPrimitives.size())
  890. break;
  891. }
  892. if (j!=obj.numMeshes)
  893. break;
  894. }
  895. if (i!=end)
  896. break;
  897. }
  898. }
  899. bool TSShape::preloadMaterialList(const Torque::Path &path)
  900. {
  901. if (materialList)
  902. materialList->setTextureLookupPath(path.getPath());
  903. return true;
  904. }
  905. bool TSShape::buildConvexHull(S32 dl) const
  906. {
  907. AssertFatal(dl>=0 && dl<details.size(),"TSShape::buildConvexHull: detail out of range");
  908. bool ok = true;
  909. const Detail & detail = details[dl];
  910. S32 ss = detail.subShapeNum;
  911. S32 od = detail.objectDetailNum;
  912. S32 start = subShapeFirstObject[ss];
  913. S32 end = subShapeNumObjects[ss];
  914. for (S32 i=start; i<end; i++)
  915. {
  916. TSMesh * mesh = meshes[objects[i].startMeshIndex+od];
  917. if (!mesh)
  918. continue;
  919. ok &= mesh->buildConvexHull();
  920. }
  921. return ok;
  922. }
  923. Vector<MatrixF> gTempNodeTransforms(__FILE__, __LINE__);
  924. void TSShape::computeBounds(S32 dl, Box3F & bounds) const
  925. {
  926. // if dl==-1, nothing to do
  927. if (dl==-1)
  928. return;
  929. AssertFatal(dl>=0 && dl<details.size(),"TSShapeInstance::computeBounds");
  930. // get subshape and object detail
  931. const TSDetail * detail = &details[dl];
  932. S32 ss = detail->subShapeNum;
  933. S32 od = detail->objectDetailNum;
  934. // If we have no subshapes then there is
  935. // no valid bounds for this detail level.
  936. if ( ss < 0 )
  937. return;
  938. // set up temporary storage for non-local transforms...
  939. S32 i;
  940. S32 start = subShapeFirstNode[ss];
  941. S32 end = subShapeNumNodes[ss] + start;
  942. gTempNodeTransforms.setSize(end-start);
  943. for (i=start; i<end; i++)
  944. {
  945. MatrixF mat;
  946. QuatF q;
  947. TSTransform::setMatrix(defaultRotations[i].getQuatF(&q),defaultTranslations[i],&mat);
  948. if (nodes[i].parentIndex>=0)
  949. gTempNodeTransforms[i-start].mul(gTempNodeTransforms[nodes[i].parentIndex-start],mat);
  950. else
  951. gTempNodeTransforms[i-start] = mat;
  952. }
  953. // run through objects and updating bounds as we go
  954. bounds.minExtents.set( 10E30f, 10E30f, 10E30f);
  955. bounds.maxExtents.set(-10E30f,-10E30f,-10E30f);
  956. Box3F box;
  957. start = subShapeFirstObject[ss];
  958. end = subShapeNumObjects[ss] + start;
  959. for (i=start; i<end; i++)
  960. {
  961. const Object * object = &objects[i];
  962. TSMesh * mesh = od<object->numMeshes ? meshes[object->startMeshIndex+od] : NULL;
  963. if (mesh)
  964. {
  965. static MatrixF idMat(true);
  966. if (object->nodeIndex<0)
  967. mesh->computeBounds(idMat,box);
  968. else
  969. mesh->computeBounds(gTempNodeTransforms[object->nodeIndex-start],box);
  970. bounds.minExtents.setMin(box.minExtents);
  971. bounds.maxExtents.setMax(box.maxExtents);
  972. }
  973. }
  974. }
  975. TSShapeAlloc TSShape::smTSAlloc;
  976. #define tsalloc TSShape::smTSAlloc
  977. // messy stuff: check to see if we should "skip" meshNum
  978. // this assumes that meshes for a given object are in a row
  979. // skipDL is the lowest detail number we keep (i.e., the # of details we skip)
  980. bool TSShape::checkSkip(S32 meshNum, S32 & curObject, S32 skipDL)
  981. {
  982. if (skipDL==0)
  983. // easy out...
  984. return false;
  985. // skip detail level exists on this subShape
  986. S32 skipSS = details[skipDL].subShapeNum;
  987. if (curObject<objects.size())
  988. {
  989. S32 start = objects[curObject].startMeshIndex;
  990. if (meshNum>=start)
  991. {
  992. // we are either from this object, the next object, or a decal
  993. if (meshNum < start + objects[curObject].numMeshes)
  994. {
  995. // this object...
  996. if (subShapeFirstObject[skipSS]>curObject)
  997. // haven't reached this subshape yet
  998. return true;
  999. if (skipSS+1==subShapeFirstObject.size() || curObject<subShapeFirstObject[skipSS+1])
  1000. // curObject is on subshape of skip detail...make sure it's after skipDL
  1001. return (meshNum-start<details[skipDL].objectDetailNum);
  1002. // if we get here, then curObject occurs on subShape after skip detail (so keep it)
  1003. return false;
  1004. }
  1005. else
  1006. // advance object, try again
  1007. return checkSkip(meshNum,++curObject,skipDL);
  1008. }
  1009. }
  1010. AssertFatal(0,"TSShape::checkSkip: assertion failed");
  1011. return false;
  1012. }
  1013. void TSShape::assembleShape()
  1014. {
  1015. S32 i,j;
  1016. // get counts...
  1017. S32 numNodes = tsalloc.get32();
  1018. S32 numObjects = tsalloc.get32();
  1019. S32 numDecals = tsalloc.get32();
  1020. S32 numSubShapes = tsalloc.get32();
  1021. S32 numIflMaterials = tsalloc.get32();
  1022. S32 numNodeRots;
  1023. S32 numNodeTrans;
  1024. S32 numNodeUniformScales;
  1025. S32 numNodeAlignedScales;
  1026. S32 numNodeArbitraryScales;
  1027. if (smReadVersion<22)
  1028. {
  1029. numNodeRots = numNodeTrans = tsalloc.get32() - numNodes;
  1030. numNodeUniformScales = numNodeAlignedScales = numNodeArbitraryScales = 0;
  1031. }
  1032. else
  1033. {
  1034. numNodeRots = tsalloc.get32();
  1035. numNodeTrans = tsalloc.get32();
  1036. numNodeUniformScales = tsalloc.get32();
  1037. numNodeAlignedScales = tsalloc.get32();
  1038. numNodeArbitraryScales = tsalloc.get32();
  1039. }
  1040. S32 numGroundFrames = 0;
  1041. if (smReadVersion>23)
  1042. numGroundFrames = tsalloc.get32();
  1043. S32 numObjectStates = tsalloc.get32();
  1044. S32 numDecalStates = tsalloc.get32();
  1045. S32 numTriggers = tsalloc.get32();
  1046. S32 numDetails = tsalloc.get32();
  1047. S32 numMeshes = tsalloc.get32();
  1048. S32 numSkins = 0;
  1049. if (smReadVersion<23)
  1050. // in later versions, skins are kept with other meshes
  1051. numSkins = tsalloc.get32();
  1052. S32 numNames = tsalloc.get32();
  1053. // Note that we are recalculating these values later on for safety.
  1054. mSmallestVisibleSize = (F32)tsalloc.get32();
  1055. mSmallestVisibleDL = tsalloc.get32();
  1056. tsalloc.checkGuard();
  1057. // get bounds...
  1058. tsalloc.get32((S32*)&mRadius,1);
  1059. tsalloc.get32((S32*)&tubeRadius,1);
  1060. tsalloc.get32((S32*)&center,3);
  1061. tsalloc.get32((S32*)&mBounds,6);
  1062. tsalloc.checkGuard();
  1063. // copy various vectors...
  1064. S32 * ptr32 = tsalloc.copyToShape32(numNodes*5);
  1065. nodes.set(ptr32,numNodes);
  1066. tsalloc.checkGuard();
  1067. ptr32 = tsalloc.copyToShape32(numObjects*6,true);
  1068. if (!ptr32)
  1069. ptr32 = tsalloc.allocShape32(numSkins*6); // pre v23 shapes store skins and meshes separately...no longer
  1070. else
  1071. tsalloc.allocShape32(numSkins*6);
  1072. objects.set(ptr32,numObjects);
  1073. tsalloc.checkGuard();
  1074. // DEPRECATED decals
  1075. ptr32 = tsalloc.getPointer32(numDecals*5);
  1076. tsalloc.checkGuard();
  1077. // DEPRECATED ifl materials
  1078. ptr32 = tsalloc.copyToShape32(numIflMaterials*5);
  1079. tsalloc.checkGuard();
  1080. ptr32 = tsalloc.copyToShape32(numSubShapes,true);
  1081. subShapeFirstNode.set(ptr32,numSubShapes);
  1082. ptr32 = tsalloc.copyToShape32(numSubShapes,true);
  1083. subShapeFirstObject.set(ptr32,numSubShapes);
  1084. // DEPRECATED subShapeFirstDecal
  1085. ptr32 = tsalloc.getPointer32(numSubShapes);
  1086. tsalloc.checkGuard();
  1087. ptr32 = tsalloc.copyToShape32(numSubShapes);
  1088. subShapeNumNodes.set(ptr32,numSubShapes);
  1089. ptr32 = tsalloc.copyToShape32(numSubShapes);
  1090. subShapeNumObjects.set(ptr32,numSubShapes);
  1091. // DEPRECATED subShapeNumDecals
  1092. ptr32 = tsalloc.getPointer32(numSubShapes);
  1093. tsalloc.checkGuard();
  1094. ptr32 = tsalloc.allocShape32(numSubShapes);
  1095. subShapeFirstTranslucentObject.set(ptr32,numSubShapes);
  1096. // get default translation and rotation
  1097. S16 * ptr16 = tsalloc.allocShape16(0);
  1098. for (i=0;i<numNodes;i++)
  1099. tsalloc.copyToShape16(4);
  1100. defaultRotations.set(ptr16,numNodes);
  1101. tsalloc.align32();
  1102. ptr32 = tsalloc.allocShape32(0);
  1103. for (i=0;i<numNodes;i++)
  1104. {
  1105. tsalloc.copyToShape32(3);
  1106. tsalloc.copyToShape32(sizeof(Point3F)-12); // handle alignment issues w/ point3f
  1107. }
  1108. defaultTranslations.set(ptr32,numNodes);
  1109. // get any node sequence data stored in shape
  1110. nodeTranslations.setSize(numNodeTrans);
  1111. for (i=0;i<numNodeTrans;i++)
  1112. tsalloc.get32((S32*)&nodeTranslations[i],3);
  1113. nodeRotations.setSize(numNodeRots);
  1114. for (i=0;i<numNodeRots;i++)
  1115. tsalloc.get16((S16*)&nodeRotations[i],4);
  1116. tsalloc.align32();
  1117. tsalloc.checkGuard();
  1118. if (smReadVersion>21)
  1119. {
  1120. // more node sequence data...scale
  1121. nodeUniformScales.setSize(numNodeUniformScales);
  1122. for (i=0;i<numNodeUniformScales;i++)
  1123. tsalloc.get32((S32*)&nodeUniformScales[i],1);
  1124. nodeAlignedScales.setSize(numNodeAlignedScales);
  1125. for (i=0;i<numNodeAlignedScales;i++)
  1126. tsalloc.get32((S32*)&nodeAlignedScales[i],3);
  1127. nodeArbitraryScaleFactors.setSize(numNodeArbitraryScales);
  1128. for (i=0;i<numNodeArbitraryScales;i++)
  1129. tsalloc.get32((S32*)&nodeArbitraryScaleFactors[i],3);
  1130. nodeArbitraryScaleRots.setSize(numNodeArbitraryScales);
  1131. for (i=0;i<numNodeArbitraryScales;i++)
  1132. tsalloc.get16((S16*)&nodeArbitraryScaleRots[i],4);
  1133. tsalloc.align32();
  1134. tsalloc.checkGuard();
  1135. }
  1136. // old shapes need ground transforms moved to ground arrays...but only do it once
  1137. if (smReadVersion<22 && tsalloc.allocShape32(0))
  1138. {
  1139. for (i=0; i<sequences.size(); i++)
  1140. {
  1141. // move ground transform data to ground vectors
  1142. Sequence & seq = sequences[i];
  1143. S32 oldSz = groundTranslations.size();
  1144. groundTranslations.setSize(oldSz+seq.numGroundFrames);
  1145. groundRotations.setSize(oldSz+seq.numGroundFrames);
  1146. for (S32 groundFrm =0; groundFrm<seq.numGroundFrames; groundFrm++)
  1147. {
  1148. groundTranslations[groundFrm +oldSz] = nodeTranslations[seq.firstGroundFrame+ groundFrm -numNodes];
  1149. groundRotations[groundFrm +oldSz] = nodeRotations[seq.firstGroundFrame+ groundFrm -numNodes];
  1150. }
  1151. seq.firstGroundFrame = oldSz;
  1152. seq.baseTranslation -= numNodes;
  1153. seq.baseRotation -= numNodes;
  1154. seq.baseScale = 0; // not used on older shapes...but keep it clean
  1155. }
  1156. }
  1157. // version 22 & 23 shapes accidentally had no ground transforms, and ground for
  1158. // earlier shapes is handled just above, so...
  1159. if (smReadVersion>23)
  1160. {
  1161. groundTranslations.setSize(numGroundFrames);
  1162. for (i=0;i<numGroundFrames;i++)
  1163. tsalloc.get32((S32*)&groundTranslations[i],3);
  1164. groundRotations.setSize(numGroundFrames);
  1165. for (i=0;i<numGroundFrames;i++)
  1166. tsalloc.get16((S16*)&groundRotations[i],4);
  1167. tsalloc.align32();
  1168. tsalloc.checkGuard();
  1169. }
  1170. // object states
  1171. ptr32 = tsalloc.copyToShape32(numObjectStates*3);
  1172. objectStates.set(ptr32,numObjectStates);
  1173. tsalloc.allocShape32(numSkins*3); // provide buffer after objectStates for older shapes
  1174. tsalloc.checkGuard();
  1175. // DEPRECATED decal states
  1176. ptr32 = tsalloc.getPointer32(numDecalStates);
  1177. tsalloc.checkGuard();
  1178. // frame triggers
  1179. ptr32 = tsalloc.getPointer32(numTriggers*2);
  1180. triggers.setSize(numTriggers);
  1181. dMemcpy(triggers.address(),ptr32,sizeof(S32)*numTriggers*2);
  1182. tsalloc.checkGuard();
  1183. // details
  1184. if ( smReadVersion >= 26 )
  1185. {
  1186. U32 alignedSize32 = sizeof( Detail ) / 4;
  1187. ptr32 = tsalloc.copyToShape32( numDetails * alignedSize32, true );
  1188. details.set( ptr32, numDetails );
  1189. }
  1190. else
  1191. {
  1192. // Previous to version 26 the Detail structure
  1193. // only contained the first 7 values...
  1194. //
  1195. // struct Detail
  1196. // {
  1197. // S32 nameIndex;
  1198. // S32 subShapeNum;
  1199. // S32 objectDetailNum;
  1200. // F32 size;
  1201. // F32 averageError;
  1202. // F32 maxError;
  1203. // S32 polyCount;
  1204. // };
  1205. //
  1206. // In the code below we're reading just these 7 values and
  1207. // copying them to the new larger structure.
  1208. ptr32 = tsalloc.copyToShape32( numDetails * 7, true );
  1209. details.setSize( numDetails );
  1210. for ( U32 detID = 0; detID < details.size(); detID++, ptr32 += 7 )
  1211. {
  1212. Detail *det = &(details[detID]);
  1213. // Clear the struct... we don't want to leave
  1214. // garbage in the parts that are unfilled.
  1215. U32 alignedSize32 = sizeof( Detail );
  1216. dMemset( det, 0, alignedSize32 );
  1217. // Copy the old struct values over.
  1218. dMemcpy( det, ptr32, 7 * 4 );
  1219. // If this is an autobillboard then we need to
  1220. // fill in the new part of the struct.
  1221. if ( det->subShapeNum >= 0 )
  1222. continue;
  1223. S32 lastDetailOpts = det->objectDetailNum;
  1224. det->bbEquatorSteps = lastDetailOpts & 0x7F; // bits 0..6
  1225. det->bbPolarSteps = (lastDetailOpts >> 7) & 0x3F; // bits 7..12
  1226. det->bbPolarAngle = 0.5f * M_PI_F * (1.0f/64.0f) * (F32) (( lastDetailOpts >>13 ) & 0x3F); // bits 13..18
  1227. det->bbDetailLevel = (lastDetailOpts >> 19) & 0x0F; // 19..22
  1228. det->bbDimension = (lastDetailOpts >> 23) & 0xFF; // 23..30
  1229. det->bbIncludePoles = (lastDetailOpts & 0x80000000)!=0; // bit 31
  1230. }
  1231. }
  1232. // Some DTS exporters (MAX - I'm looking at you!) write garbage into the
  1233. // averageError and maxError values which stops LOD from working correctly.
  1234. // Try to detect and fix it
  1235. for ( U32 erID = 0; erID < details.size(); erID++ )
  1236. {
  1237. if ( ( details[erID].averageError == 0 ) || ( details[erID].averageError > 10000 ) ||
  1238. ( details[erID].maxError == 0 ) || ( details[erID].maxError > 10000 ) )
  1239. {
  1240. details[erID].averageError = details[erID].maxError = -1.0f;
  1241. }
  1242. }
  1243. // We don't trust the value of mSmallestVisibleDL loaded from the dts
  1244. // since some legacy meshes seem to have the wrong value. Recalculate it
  1245. // now that we have the details loaded.
  1246. updateSmallestVisibleDL();
  1247. S32 skipDL = getMin(mSmallestVisibleDL,smNumSkipLoadDetails);
  1248. if (skipDL < 0)
  1249. skipDL = 0;
  1250. tsalloc.checkGuard();
  1251. if (TSShape::smReadVersion >= 27)
  1252. {
  1253. // Vertex format is set here
  1254. S8 *vboData = NULL;
  1255. S32 vboSize = 0;
  1256. mBasicVertexFormat.readAlloc(&tsalloc);
  1257. mVertexFormat.clear();
  1258. mBasicVertexFormat.getFormat(mVertexFormat);
  1259. mVertexSize = mVertexFormat.getSizeInBytes();
  1260. AssertFatal(mVertexSize == mBasicVertexFormat.vertexSize, "vertex size mismatch");
  1261. vboSize = tsalloc.get32();
  1262. vboData = tsalloc.getPointer8(vboSize);
  1263. if (tsalloc.getBuffer() && vboSize > 0)
  1264. {
  1265. U8 *vertexData = (U8*)dMalloc_aligned(vboSize, 16);
  1266. dMemcpy(vertexData, vboData, vboSize);
  1267. mShapeVertexData.set(vertexData, vboSize);
  1268. mShapeVertexData.vertexDataReady = true;
  1269. }
  1270. else
  1271. {
  1272. mShapeVertexData.set(NULL, 0);
  1273. }
  1274. }
  1275. else
  1276. {
  1277. mShapeVertexData.set(NULL, 0);
  1278. }
  1279. // about to read in the meshes...first must allocate some scratch space
  1280. S32 scratchSize = getMax(numSkins,numMeshes);
  1281. TSMesh::smVertsList.setSize(scratchSize);
  1282. TSMesh::smTVertsList.setSize(scratchSize);
  1283. if ( smReadVersion >= 26 )
  1284. {
  1285. TSMesh::smTVerts2List.setSize(scratchSize);
  1286. TSMesh::smColorsList.setSize(scratchSize);
  1287. }
  1288. TSMesh::smNormsList.setSize(scratchSize);
  1289. TSMesh::smEncodedNormsList.setSize(scratchSize);
  1290. TSMesh::smDataCopied.setSize(scratchSize);
  1291. TSSkinMesh::smInitTransformList.setSize(scratchSize);
  1292. TSSkinMesh::smVertexIndexList.setSize(scratchSize);
  1293. TSSkinMesh::smBoneIndexList.setSize(scratchSize);
  1294. TSSkinMesh::smWeightList.setSize(scratchSize);
  1295. TSSkinMesh::smNodeIndexList.setSize(scratchSize);
  1296. for (i=0; i<numMeshes; i++)
  1297. {
  1298. TSMesh::smVertsList[i]=NULL;
  1299. TSMesh::smTVertsList[i]=NULL;
  1300. if ( smReadVersion >= 26 )
  1301. {
  1302. TSMesh::smTVerts2List[i] = NULL;
  1303. TSMesh::smColorsList[i] = NULL;
  1304. }
  1305. TSMesh::smNormsList[i]=NULL;
  1306. TSMesh::smEncodedNormsList[i]=NULL;
  1307. TSMesh::smDataCopied[i]=false;
  1308. TSSkinMesh::smInitTransformList[i] = NULL;
  1309. TSSkinMesh::smVertexIndexList[i] = NULL;
  1310. TSSkinMesh::smBoneIndexList[i] = NULL;
  1311. TSSkinMesh::smWeightList[i] = NULL;
  1312. TSSkinMesh::smNodeIndexList[i] = NULL;
  1313. }
  1314. // read in the meshes (sans skins)...straightforward read one at a time
  1315. TSMesh **ptrmesh = (TSMesh**)tsalloc.allocShape32((numMeshes + numSkins*numDetails) * (sizeof(TSMesh*) / 4));
  1316. S32 curObject = 0; // for tracking skipped meshes
  1317. for (i=0; i<numMeshes; i++)
  1318. {
  1319. bool skip = checkSkip(i,curObject,skipDL); // skip this mesh?
  1320. S32 meshType = tsalloc.get32();
  1321. if (meshType == TSMesh::DecalMeshType)
  1322. // decal mesh deprecated
  1323. skip = true;
  1324. TSMesh * mesh = TSMesh::assembleMesh(meshType,skip);
  1325. if (ptrmesh)
  1326. {
  1327. ptrmesh[i] = skip ? 0 : mesh;
  1328. }
  1329. // fill in location of verts, tverts, and normals for detail levels
  1330. if (mesh && meshType!=TSMesh::DecalMeshType)
  1331. {
  1332. TSMesh::smVertsList[i] = mesh->mVerts.address();
  1333. TSMesh::smTVertsList[i] = mesh->mTverts.address();
  1334. if (smReadVersion >= 26)
  1335. {
  1336. TSMesh::smTVerts2List[i] = mesh->mTverts2.address();
  1337. TSMesh::smColorsList[i] = mesh->mColors.address();
  1338. }
  1339. TSMesh::smNormsList[i] = mesh->mNorms.address();
  1340. TSMesh::smEncodedNormsList[i] = mesh->mEncodedNorms.address();
  1341. TSMesh::smDataCopied[i] = !skip; // as long as we didn't skip this mesh, the data should be in shape now
  1342. if (meshType==TSMesh::SkinMeshType)
  1343. {
  1344. TSSkinMesh * skin = (TSSkinMesh*)mesh;
  1345. TSMesh::smVertsList[i] = skin->batchData.initialVerts.address();
  1346. TSMesh::smNormsList[i] = skin->batchData.initialNorms.address();
  1347. TSSkinMesh::smInitTransformList[i] = skin->batchData.initialTransforms.address();
  1348. TSSkinMesh::smVertexIndexList[i] = skin->vertexIndex.address();
  1349. TSSkinMesh::smBoneIndexList[i] = skin->boneIndex.address();
  1350. TSSkinMesh::smWeightList[i] = skin->weight.address();
  1351. TSSkinMesh::smNodeIndexList[i] = skin->batchData.nodeIndex.address();
  1352. }
  1353. }
  1354. }
  1355. meshes.set(ptrmesh, numMeshes);
  1356. tsalloc.checkGuard();
  1357. // names
  1358. char * nameBufferStart = (char*)tsalloc.getPointer8(0);
  1359. char * name = nameBufferStart;
  1360. S32 nameBufferSize = 0;
  1361. names.setSize(numNames);
  1362. for (i=0; i<numNames; i++)
  1363. {
  1364. for (j=0; name[j]; j++)
  1365. ;
  1366. names[i] = name;
  1367. nameBufferSize += j + 1;
  1368. name += j + 1;
  1369. }
  1370. tsalloc.getPointer8(nameBufferSize);
  1371. tsalloc.align32();
  1372. tsalloc.checkGuard();
  1373. if (smReadVersion<23)
  1374. {
  1375. // get detail information about skins...
  1376. S32 * detFirstSkin = tsalloc.getPointer32(numDetails);
  1377. S32 * detailNumSkins = tsalloc.getPointer32(numDetails);
  1378. tsalloc.checkGuard();
  1379. // about to read in skins...clear out scratch space...
  1380. if (numSkins)
  1381. {
  1382. TSSkinMesh::smInitTransformList.setSize(numSkins);
  1383. TSSkinMesh::smVertexIndexList.setSize(numSkins);
  1384. TSSkinMesh::smBoneIndexList.setSize(numSkins);
  1385. TSSkinMesh::smWeightList.setSize(numSkins);
  1386. TSSkinMesh::smNodeIndexList.setSize(numSkins);
  1387. }
  1388. for (i=0; i<numSkins; i++)
  1389. {
  1390. TSMesh::smVertsList[i]=NULL;
  1391. TSMesh::smTVertsList[i]=NULL;
  1392. TSMesh::smNormsList[i]=NULL;
  1393. TSMesh::smEncodedNormsList[i]=NULL;
  1394. TSMesh::smDataCopied[i]=false;
  1395. TSSkinMesh::smInitTransformList[i] = NULL;
  1396. TSSkinMesh::smVertexIndexList[i] = NULL;
  1397. TSSkinMesh::smBoneIndexList[i] = NULL;
  1398. TSSkinMesh::smWeightList[i] = NULL;
  1399. TSSkinMesh::smNodeIndexList[i] = NULL;
  1400. }
  1401. // skins
  1402. ptr32 = tsalloc.allocShape32(numSkins);
  1403. for (i=0; i<numSkins; i++)
  1404. {
  1405. bool skip = i<detFirstSkin[skipDL];
  1406. TSSkinMesh * skin = (TSSkinMesh*)TSMesh::assembleMesh(TSMesh::SkinMeshType,skip);
  1407. if (meshes.address())
  1408. {
  1409. // add pointer to skin in shapes list of meshes
  1410. // we reserved room for this above...
  1411. meshes.set(meshes.address(),meshes.size()+1);
  1412. meshes[meshes.size()-1] = skip ? NULL : skin;
  1413. }
  1414. // fill in location of verts, tverts, and normals for shared detail levels
  1415. if (skin)
  1416. {
  1417. TSMesh::smVertsList[i] = skin->batchData.initialVerts.address();
  1418. TSMesh::smTVertsList[i] = skin->mTverts.address();
  1419. TSMesh::smNormsList[i] = skin->batchData.initialNorms.address();
  1420. TSMesh::smEncodedNormsList[i] = skin->mEncodedNorms.address();
  1421. TSMesh::smDataCopied[i] = !skip; // as long as we didn't skip this mesh, the data should be in shape now
  1422. TSSkinMesh::smInitTransformList[i] = skin->batchData.initialTransforms.address();
  1423. TSSkinMesh::smVertexIndexList[i] = skin->vertexIndex.address();
  1424. TSSkinMesh::smBoneIndexList[i] = skin->boneIndex.address();
  1425. TSSkinMesh::smWeightList[i] = skin->weight.address();
  1426. TSSkinMesh::smNodeIndexList[i] = skin->batchData.nodeIndex.address();
  1427. }
  1428. }
  1429. tsalloc.checkGuard();
  1430. // we now have skins in mesh list...add skin objects to object list and patch things up
  1431. fixupOldSkins(numMeshes,numSkins,numDetails,detFirstSkin,detailNumSkins);
  1432. }
  1433. // allocate storage space for some arrays (filled in during Shape::init)...
  1434. ptr32 = tsalloc.allocShape32(numDetails);
  1435. alphaIn.set(ptr32,numDetails);
  1436. ptr32 = tsalloc.allocShape32(numDetails);
  1437. alphaOut.set(ptr32,numDetails);
  1438. }
  1439. void TSShape::disassembleShape()
  1440. {
  1441. S32 i;
  1442. // set counts...
  1443. S32 numNodes = tsalloc.set32(nodes.size());
  1444. S32 numObjects = tsalloc.set32(objects.size());
  1445. tsalloc.set32(0); // DEPRECATED decals
  1446. S32 numSubShapes = tsalloc.set32(subShapeFirstNode.size());
  1447. tsalloc.set32(0); // DEPRECATED ifl materials
  1448. S32 numNodeRotations = tsalloc.set32(nodeRotations.size());
  1449. S32 numNodeTranslations = tsalloc.set32(nodeTranslations.size());
  1450. S32 numNodeUniformScales = tsalloc.set32(nodeUniformScales.size());
  1451. S32 numNodeAlignedScales = tsalloc.set32(nodeAlignedScales.size());
  1452. S32 numNodeArbitraryScales = tsalloc.set32(nodeArbitraryScaleFactors.size());
  1453. S32 numGroundFrames = tsalloc.set32(groundTranslations.size());
  1454. S32 numObjectStates = tsalloc.set32(objectStates.size());
  1455. tsalloc.set32(0); // DEPRECATED decals
  1456. S32 numTriggers = tsalloc.set32(triggers.size());
  1457. S32 numDetails = tsalloc.set32(details.size());
  1458. S32 numMeshes = tsalloc.set32(meshes.size());
  1459. S32 numNames = tsalloc.set32(names.size());
  1460. tsalloc.set32((S32)mSmallestVisibleSize);
  1461. tsalloc.set32(mSmallestVisibleDL);
  1462. tsalloc.setGuard();
  1463. // get bounds...
  1464. tsalloc.copyToBuffer32((S32*)&mRadius,1);
  1465. tsalloc.copyToBuffer32((S32*)&tubeRadius,1);
  1466. tsalloc.copyToBuffer32((S32*)&center,3);
  1467. tsalloc.copyToBuffer32((S32*)&mBounds,6);
  1468. tsalloc.setGuard();
  1469. // copy various vectors...
  1470. tsalloc.copyToBuffer32((S32*)nodes.address(),numNodes*5);
  1471. tsalloc.setGuard();
  1472. tsalloc.copyToBuffer32((S32*)objects.address(),numObjects*6);
  1473. tsalloc.setGuard();
  1474. // DEPRECATED: no copy decals
  1475. tsalloc.setGuard();
  1476. tsalloc.copyToBuffer32(0,0); // DEPRECATED: ifl materials!
  1477. tsalloc.setGuard();
  1478. tsalloc.copyToBuffer32((S32*)subShapeFirstNode.address(),numSubShapes);
  1479. tsalloc.copyToBuffer32((S32*)subShapeFirstObject.address(),numSubShapes);
  1480. tsalloc.copyToBuffer32(0, numSubShapes); // DEPRECATED: no copy subShapeFirstDecal
  1481. tsalloc.setGuard();
  1482. tsalloc.copyToBuffer32((S32*)subShapeNumNodes.address(),numSubShapes);
  1483. tsalloc.copyToBuffer32((S32*)subShapeNumObjects.address(),numSubShapes);
  1484. tsalloc.copyToBuffer32(0, numSubShapes); // DEPRECATED: no copy subShapeNumDecals
  1485. tsalloc.setGuard();
  1486. // default transforms...
  1487. tsalloc.copyToBuffer16((S16*)defaultRotations.address(),numNodes*4);
  1488. tsalloc.copyToBuffer32((S32*)defaultTranslations.address(),numNodes*3);
  1489. // animated transforms...
  1490. tsalloc.copyToBuffer16((S16*)nodeRotations.address(),numNodeRotations*4);
  1491. tsalloc.copyToBuffer32((S32*)nodeTranslations.address(),numNodeTranslations*3);
  1492. tsalloc.setGuard();
  1493. // ...with scale
  1494. tsalloc.copyToBuffer32((S32*)nodeUniformScales.address(),numNodeUniformScales);
  1495. tsalloc.copyToBuffer32((S32*)nodeAlignedScales.address(),numNodeAlignedScales*3);
  1496. tsalloc.copyToBuffer32((S32*)nodeArbitraryScaleFactors.address(),numNodeArbitraryScales*3);
  1497. tsalloc.copyToBuffer16((S16*)nodeArbitraryScaleRots.address(),numNodeArbitraryScales*4);
  1498. tsalloc.setGuard();
  1499. tsalloc.copyToBuffer32((S32*)groundTranslations.address(),3*numGroundFrames);
  1500. tsalloc.copyToBuffer16((S16*)groundRotations.address(),4*numGroundFrames);
  1501. tsalloc.setGuard();
  1502. // object states..
  1503. tsalloc.copyToBuffer32((S32*)objectStates.address(),numObjectStates*3);
  1504. tsalloc.setGuard();
  1505. // decal states...
  1506. // DEPRECATED (numDecalStates = 0)
  1507. tsalloc.setGuard();
  1508. // frame triggers
  1509. tsalloc.copyToBuffer32((S32*)triggers.address(),numTriggers*2);
  1510. tsalloc.setGuard();
  1511. // details
  1512. if (TSShape::smVersion > 25)
  1513. {
  1514. U32 alignedSize32 = sizeof( Detail ) / 4;
  1515. tsalloc.copyToBuffer32((S32*)details.address(),numDetails * alignedSize32 );
  1516. }
  1517. else
  1518. {
  1519. // Legacy details => no explicit autobillboard parameters
  1520. U32 legacyDetailSize32 = 7; // only store the first 7 4-byte values of each detail
  1521. for ( S32 bbID = 0; bbID < details.size(); bbID++ )
  1522. tsalloc.copyToBuffer32( (S32*)&details[bbID], legacyDetailSize32 );
  1523. }
  1524. tsalloc.setGuard();
  1525. if (TSShape::smVersion >= 27)
  1526. {
  1527. // Vertex format now included with mesh data. Note this doesn't include index data which
  1528. // is constructed directly in the buffer from the meshes
  1529. mBasicVertexFormat.writeAlloc(&tsalloc);
  1530. tsalloc.set32(mShapeVertexData.size);
  1531. tsalloc.copyToBuffer8((S8*)mShapeVertexData.base, mShapeVertexData.size);
  1532. }
  1533. // read in the meshes (sans skins)...
  1534. bool * isMesh = new bool[numMeshes]; // funny business because decals are pretend meshes (legacy issue)
  1535. for (i=0;i<numMeshes;i++)
  1536. isMesh[i]=false;
  1537. for (i=0; i<objects.size(); i++)
  1538. {
  1539. for (S32 j=0; j<objects[i].numMeshes; j++)
  1540. // even if an empty mesh, it's a mesh...
  1541. isMesh[objects[i].startMeshIndex+j]=true;
  1542. }
  1543. for (i=0; i<numMeshes; i++)
  1544. {
  1545. TSMesh * mesh = NULL;
  1546. // decal mesh deprecated
  1547. if (isMesh[i])
  1548. mesh = meshes[i];
  1549. tsalloc.set32( (mesh && mesh->getMeshType() != TSMesh::DecalMeshType) ? mesh->getMeshType() : TSMesh::NullMeshType);
  1550. if (mesh)
  1551. mesh->disassemble();
  1552. }
  1553. delete [] isMesh;
  1554. tsalloc.setGuard();
  1555. // names
  1556. for (i=0; i<numNames; i++)
  1557. tsalloc.copyToBuffer8((S8 *)(names[i].c_str()),names[i].length()+1);
  1558. tsalloc.setGuard();
  1559. }
  1560. //-------------------------------------------------
  1561. // write whole shape
  1562. //-------------------------------------------------
  1563. /** Determine whether we can write this shape in TSTPRO compatible format */
  1564. bool TSShape::canWriteOldFormat() const
  1565. {
  1566. // Cannot use old format if using autobillboard details
  1567. for (S32 i = 0; i < details.size(); i++)
  1568. {
  1569. if (details[i].subShapeNum < 0)
  1570. return false;
  1571. }
  1572. for (S32 i = 0; i < meshes.size(); i++)
  1573. {
  1574. if (!meshes[i])
  1575. continue;
  1576. // Cannot use old format if using the new functionality (COLORs, 2nd UV set)
  1577. if (meshes[i]->mTverts2.size() || meshes[i]->mColors.size())
  1578. return false;
  1579. // Cannot use old format if any primitive has too many triangles
  1580. // (ie. cannot fit in a S16)
  1581. for (S32 j = 0; j < meshes[i]->mPrimitives.size(); j++)
  1582. {
  1583. if ((meshes[i]->mPrimitives[j].start +
  1584. meshes[i]->mPrimitives[j].numElements) >= (1 << 15))
  1585. {
  1586. return false;
  1587. }
  1588. }
  1589. }
  1590. return true;
  1591. }
  1592. void TSShape::write(Stream * s, bool saveOldFormat)
  1593. {
  1594. S32 currentVersion = smVersion;
  1595. if (saveOldFormat)
  1596. smVersion = 24;
  1597. // write version
  1598. s->write(smVersion | (mExporterVersion<<16));
  1599. tsalloc.setWrite();
  1600. disassembleShape();
  1601. S32 * buffer32 = tsalloc.getBuffer32();
  1602. S16 * buffer16 = tsalloc.getBuffer16();
  1603. S8 * buffer8 = tsalloc.getBuffer8();
  1604. S32 size32 = tsalloc.getBufferSize32();
  1605. S32 size16 = tsalloc.getBufferSize16();
  1606. S32 size8 = tsalloc.getBufferSize8();
  1607. // convert sizes to dwords...
  1608. if (size16 & 1)
  1609. size16 += 2;
  1610. size16 >>= 1;
  1611. if (size8 & 3)
  1612. size8 += 4;
  1613. size8 >>= 2;
  1614. S32 sizeMemBuffer, start16, start8;
  1615. sizeMemBuffer = size32 + size16 + size8;
  1616. start16 = size32;
  1617. start8 = start16+size16;
  1618. // in dwords -- write will properly endian-flip.
  1619. s->write(sizeMemBuffer);
  1620. s->write(start16);
  1621. s->write(start8);
  1622. // endian-flip the entire write buffers.
  1623. fixEndian(buffer32,buffer16,buffer8,size32,size16,size8);
  1624. // now write buffers
  1625. s->write(size32*4,buffer32);
  1626. s->write(size16*4,buffer16);
  1627. s->write(size8 *4,buffer8);
  1628. // write sequences - write will properly endian-flip.
  1629. s->write(sequences.size());
  1630. for (S32 i=0; i<sequences.size(); i++)
  1631. sequences[i].write(s);
  1632. // write material list - write will properly endian-flip.
  1633. materialList->write(*s);
  1634. delete [] buffer32;
  1635. delete [] buffer16;
  1636. delete [] buffer8;
  1637. smVersion = currentVersion;
  1638. }
  1639. //-------------------------------------------------
  1640. // read whole shape
  1641. //-------------------------------------------------
  1642. bool TSShape::read(Stream * s)
  1643. {
  1644. // read version - read handles endian-flip
  1645. s->read(&smReadVersion);
  1646. mExporterVersion = smReadVersion >> 16;
  1647. smReadVersion &= 0xFF;
  1648. if (smReadVersion>smVersion)
  1649. {
  1650. // error -- don't support future versions yet :>
  1651. Con::errorf(ConsoleLogEntry::General,
  1652. "Error: attempt to load a version %i dts-shape, can currently only load version %i and before.",
  1653. smReadVersion,smVersion);
  1654. return false;
  1655. }
  1656. mReadVersion = smReadVersion;
  1657. S32 * memBuffer32;
  1658. S16 * memBuffer16;
  1659. S8 * memBuffer8;
  1660. S32 count32, count16, count8;
  1661. if (mReadVersion<19)
  1662. {
  1663. Con::errorf("... Shape with old version.");
  1664. return false;
  1665. }
  1666. else
  1667. {
  1668. S32 i;
  1669. U32 sizeMemBuffer, startU16, startU8;
  1670. // in dwords. - read handles endian-flip
  1671. s->read(&sizeMemBuffer);
  1672. s->read(&startU16);
  1673. s->read(&startU8);
  1674. if (s->getStatus()!=Stream::Ok)
  1675. {
  1676. Con::errorf(ConsoleLogEntry::General, "Error: bad shape file.");
  1677. return false;
  1678. }
  1679. S32 * tmp = new S32[sizeMemBuffer];
  1680. s->read(sizeof(S32)*sizeMemBuffer,(U8*)tmp);
  1681. memBuffer32 = tmp;
  1682. memBuffer16 = (S16*)(tmp+startU16);
  1683. memBuffer8 = (S8*)(tmp+startU8);
  1684. count32 = startU16;
  1685. count16 = startU8-startU16;
  1686. count8 = sizeMemBuffer-startU8;
  1687. // read sequences
  1688. S32 numSequences;
  1689. s->read(&numSequences);
  1690. sequences.setSize(numSequences);
  1691. for (i=0; i<numSequences; i++)
  1692. {
  1693. sequences[i].read(s);
  1694. // Store initial (empty) source data
  1695. sequences[i].sourceData.total = sequences[i].numKeyframes;
  1696. sequences[i].sourceData.end = sequences[i].sourceData.total - 1;
  1697. }
  1698. // read material list
  1699. delete materialList; // just in case...
  1700. materialList = new TSMaterialList;
  1701. materialList->read(*s);
  1702. }
  1703. // since we read in the buffers, we need to endian-flip their entire contents...
  1704. fixEndian(memBuffer32,memBuffer16,memBuffer8,count32,count16,count8);
  1705. tsalloc.setRead(memBuffer32,memBuffer16,memBuffer8,true);
  1706. assembleShape(); // determine size of buffer needed
  1707. mShapeDataSize = tsalloc.getSize();
  1708. tsalloc.doAlloc();
  1709. mShapeData = tsalloc.getBuffer();
  1710. tsalloc.setRead(memBuffer32,memBuffer16,memBuffer8,false);
  1711. assembleShape(); // copy to buffer
  1712. AssertFatal(tsalloc.getSize()==mShapeDataSize,"TSShape::read: shape data buffer size mis-calculated");
  1713. delete [] memBuffer32;
  1714. if (smInitOnRead)
  1715. {
  1716. init();
  1717. }
  1718. return true;
  1719. }
  1720. void TSShape::createEmptyShape()
  1721. {
  1722. nodes.set(dMalloc(1 * sizeof(Node)), 1);
  1723. nodes[0].nameIndex = 1;
  1724. nodes[0].parentIndex = -1;
  1725. nodes[0].firstObject = 0;
  1726. nodes[0].firstChild = -1;
  1727. nodes[0].nextSibling = -1;
  1728. objects.set(dMalloc(1 * sizeof(Object)), 1);
  1729. objects[0].nameIndex = 2;
  1730. objects[0].numMeshes = 1;
  1731. objects[0].startMeshIndex = 0;
  1732. objects[0].nodeIndex = 0;
  1733. objects[0].nextSibling = -1;
  1734. objects[0].firstDecal = -1;
  1735. objectStates.set(dMalloc(1 * sizeof(ObjectState)), 1);
  1736. objectStates[0].vis = 1;
  1737. objectStates[0].frameIndex = 0;
  1738. objectStates[0].matFrameIndex = 0;
  1739. subShapeFirstNode.set(dMalloc(1 * sizeof(S32)), 1);
  1740. subShapeFirstNode[0] = 0;
  1741. subShapeFirstObject.set(dMalloc(1 * sizeof(S32)), 1);
  1742. subShapeFirstObject[0] = 0;
  1743. detailFirstSkin.set(NULL, 0);
  1744. subShapeNumNodes.set(dMalloc(1 * sizeof(S32)), 1);
  1745. subShapeNumNodes[0] = 1;
  1746. subShapeNumObjects.set(dMalloc(1 * sizeof(S32)), 1);
  1747. subShapeNumObjects[0] = 1;
  1748. details.set(dMalloc(1 * sizeof(Detail)), 1);
  1749. details[0].nameIndex = 0;
  1750. details[0].subShapeNum = 0;
  1751. details[0].objectDetailNum = 0;
  1752. details[0].size = 2.0f;
  1753. details[0].averageError = -1.0f;
  1754. details[0].maxError = -1.0f;
  1755. details[0].polyCount = 0;
  1756. defaultRotations.set(dMalloc(1 * sizeof(Quat16)), 1);
  1757. defaultRotations[0].x = 0.0f;
  1758. defaultRotations[0].y = 0.0f;
  1759. defaultRotations[0].z = 0.0f;
  1760. defaultRotations[0].w = 0.0f;
  1761. defaultTranslations.set(dMalloc(1 * sizeof(Point3F)), 1);
  1762. defaultTranslations[0].set(0.0f, 0.0f, 0.0f);
  1763. subShapeFirstTranslucentObject.set(dMalloc(1 * sizeof(S32)), 1);
  1764. subShapeFirstTranslucentObject[0] = 1;
  1765. alphaIn.set(dMalloc(1 * sizeof(F32)), 1);
  1766. alphaIn[0] = 0;
  1767. alphaOut.set(dMalloc(1 * sizeof(F32)), 1);
  1768. alphaOut[0] = -1;
  1769. sequences.set(NULL, 0);
  1770. nodeRotations.set(NULL, 0);
  1771. nodeTranslations.set(NULL, 0);
  1772. nodeUniformScales.set(NULL, 0);
  1773. nodeAlignedScales.set(NULL, 0);
  1774. nodeArbitraryScaleRots.set(NULL, 0);
  1775. nodeArbitraryScaleFactors.set(NULL, 0);
  1776. groundRotations.set(NULL, 0);
  1777. groundTranslations.set(NULL, 0);
  1778. triggers.set(NULL, 0);
  1779. billboardDetails.set(NULL, 0);
  1780. names.setSize(3);
  1781. names[0] = StringTable->insert("Detail2");
  1782. names[1] = StringTable->insert("Mesh2");
  1783. names[2] = StringTable->insert("Mesh");
  1784. mRadius = 0.866025f;
  1785. tubeRadius = 0.707107f;
  1786. center.set(0.0f, 0.5f, 0.0f);
  1787. mBounds.minExtents.set(-0.5f, 0.0f, -0.5f);
  1788. mBounds.maxExtents.set(0.5f, 1.0f, 0.5f);
  1789. mExporterVersion = 124;
  1790. mSmallestVisibleSize = 2;
  1791. mSmallestVisibleDL = 0;
  1792. mReadVersion = 24;
  1793. mFlags = 0;
  1794. mSequencesConstructed = 0;
  1795. mUseDetailFromScreenError = false;
  1796. mDetailLevelLookup.setSize( 1 );
  1797. mDetailLevelLookup[0].set( -1, 0 );
  1798. // Init the collision accelerator array. Note that we don't compute the
  1799. // accelerators until the app requests them
  1800. detailCollisionAccelerators.setSize(details.size());
  1801. for (U32 i = 0; i < detailCollisionAccelerators.size(); i++)
  1802. detailCollisionAccelerators[i] = NULL;
  1803. }
  1804. void TSShape::fixEndian(S32 * buff32, S16 * buff16, S8 *, S32 count32, S32 count16, S32)
  1805. {
  1806. // if endian-ness isn't the same, need to flip the buffer contents.
  1807. if (0x12345678!=convertLEndianToHost(0x12345678))
  1808. {
  1809. for (S32 i=0; i<count32; i++)
  1810. buff32[i]=convertLEndianToHost(buff32[i]);
  1811. for (S32 i=0; i<count16*2; i++)
  1812. buff16[i]=convertLEndianToHost(buff16[i]);
  1813. }
  1814. }
  1815. template<> void *Resource<TSShape>::create(const Torque::Path &path)
  1816. {
  1817. // Execute the shape script if it exists
  1818. Torque::Path scriptPath(path);
  1819. scriptPath.setExtension(TORQUE_SCRIPT_EXTENSION);
  1820. // Don't execute the script if we're already doing so!
  1821. StringTableEntry currentScript = Platform::stripBasePath(CodeBlock::getCurrentCodeBlockFullPath());
  1822. if (!scriptPath.getFullPath().equal(currentScript))
  1823. {
  1824. Torque::Path scriptPathDSO(scriptPath);
  1825. scriptPathDSO.setExtension(TORQUE_SCRIPT_EXTENSION ".dso");
  1826. if (Torque::FS::IsFile(scriptPathDSO) || Torque::FS::IsFile(scriptPath))
  1827. {
  1828. String evalCmd = "exec(\"" + scriptPath + "\");";
  1829. String instantGroup = Con::getVariable("InstantGroup");
  1830. Con::setIntVariable("InstantGroup", RootGroupId);
  1831. Con::evaluate((const char*)evalCmd.c_str(), false, scriptPath.getFullPath());
  1832. Con::setVariable("InstantGroup", instantGroup.c_str());
  1833. }
  1834. }
  1835. // Attempt to load the shape
  1836. TSShape * ret = 0;
  1837. bool readSuccess = false;
  1838. const String extension = path.getExtension();
  1839. if ( extension.equal( "dts", String::NoCase ) )
  1840. {
  1841. FileStream stream;
  1842. stream.open( path.getFullPath(), Torque::FS::File::Read );
  1843. if ( stream.getStatus() != Stream::Ok )
  1844. {
  1845. Con::errorf( "Resource<TSShape>::create - Could not open '%s'", path.getFullPath().c_str() );
  1846. return NULL;
  1847. }
  1848. ret = new TSShape;
  1849. readSuccess = ret->read(&stream);
  1850. }
  1851. else if ( extension.equal( "dae", String::NoCase ) || extension.equal( "kmz", String::NoCase ) )
  1852. {
  1853. #ifdef TORQUE_COLLADA
  1854. // Attempt to load the DAE file
  1855. ret = loadColladaShape(path);
  1856. readSuccess = (ret != NULL);
  1857. #else
  1858. // No COLLADA support => attempt to load the cached DTS file instead
  1859. Torque::Path cachedPath = path;
  1860. cachedPath.setExtension("cached.dts");
  1861. FileStream stream;
  1862. stream.open( cachedPath.getFullPath(), Torque::FS::File::Read );
  1863. if ( stream.getStatus() != Stream::Ok )
  1864. {
  1865. Con::errorf( "Resource<TSShape>::create - Could not open '%s'", cachedPath.getFullPath().c_str() );
  1866. return NULL;
  1867. }
  1868. ret = new TSShape;
  1869. readSuccess = ret->read(&stream);
  1870. #endif
  1871. }
  1872. else
  1873. {
  1874. //Con::errorf( "Resource<TSShape>::create - '%s' has an unknown file format", path.getFullPath().c_str() );
  1875. //delete ret;
  1876. //return NULL;
  1877. // andrewmac: Open Asset Import Library
  1878. #ifdef TORQUE_ASSIMP
  1879. ret = assimpLoadShape(path);
  1880. readSuccess = (ret != NULL);
  1881. #endif
  1882. // andrewmac : I could have used another conditional macro but I think this is suffice:
  1883. if (!readSuccess)
  1884. {
  1885. Con::errorf("Resource<TSShape>::create - '%s' has an unknown file format", path.getFullPath().c_str());
  1886. delete ret;
  1887. return NULL;
  1888. }
  1889. }
  1890. if( !readSuccess )
  1891. {
  1892. Con::errorf( "Resource<TSShape>::create - Error reading '%s'", path.getFullPath().c_str() );
  1893. delete ret;
  1894. ret = NULL;
  1895. }
  1896. return ret;
  1897. }
  1898. template<> ResourceBase::Signature Resource<TSShape>::signature()
  1899. {
  1900. return MakeFourCC('t','s','s','h');
  1901. }
  1902. TSShape::ConvexHullAccelerator* TSShape::getAccelerator(S32 dl)
  1903. {
  1904. AssertFatal(dl < details.size(), "Error, bad detail level!");
  1905. if (dl == -1)
  1906. return NULL;
  1907. AssertFatal( detailCollisionAccelerators.size() == details.size(),
  1908. "TSShape::getAccelerator() - mismatched array sizes!" );
  1909. if (detailCollisionAccelerators[dl] == NULL)
  1910. computeAccelerator(dl);
  1911. AssertFatal(detailCollisionAccelerators[dl] != NULL, "This should be non-null after computing it!");
  1912. return detailCollisionAccelerators[dl];
  1913. }
  1914. void TSShape::computeAccelerator(S32 dl)
  1915. {
  1916. AssertFatal(dl < details.size(), "Error, bad detail level!");
  1917. // Have we already computed this?
  1918. if (detailCollisionAccelerators[dl] != NULL)
  1919. return;
  1920. // Create a bogus features list...
  1921. ConvexFeature cf;
  1922. MatrixF mat(true);
  1923. Point3F n(0, 0, 1);
  1924. const TSDetail* detail = &details[dl];
  1925. S32 ss = detail->subShapeNum;
  1926. S32 od = detail->objectDetailNum;
  1927. S32 start = subShapeFirstObject[ss];
  1928. S32 end = subShapeNumObjects[ss] + start;
  1929. if (start < end)
  1930. {
  1931. // run through objects and collide
  1932. // DMMNOTE: This assumes that the transform of the collision hulls is
  1933. // identity...
  1934. U32 surfaceKey = 0;
  1935. for (S32 i = start; i < end; i++)
  1936. {
  1937. const TSObject* obj = &objects[i];
  1938. if (obj->numMeshes && od < obj->numMeshes) {
  1939. TSMesh* mesh = meshes[obj->startMeshIndex + od];
  1940. if (mesh)
  1941. mesh->getFeatures(0, mat, n, &cf, surfaceKey);
  1942. }
  1943. }
  1944. }
  1945. Vector<Point3F> fixedVerts;
  1946. VECTOR_SET_ASSOCIATION(fixedVerts);
  1947. S32 i;
  1948. for (i = 0; i < cf.mVertexList.size(); i++) {
  1949. S32 j;
  1950. bool found = false;
  1951. for (j = 0; j < cf.mFaceList.size(); j++) {
  1952. if (cf.mFaceList[j].vertex[0] == i ||
  1953. cf.mFaceList[j].vertex[1] == i ||
  1954. cf.mFaceList[j].vertex[2] == i) {
  1955. found = true;
  1956. break;
  1957. }
  1958. }
  1959. if (!found)
  1960. continue;
  1961. found = false;
  1962. for (j = 0; j < fixedVerts.size(); j++) {
  1963. if (fixedVerts[j] == cf.mVertexList[i]) {
  1964. found = true;
  1965. break;
  1966. }
  1967. }
  1968. if (found == true) {
  1969. // Ok, need to replace any references to vertex i in the facelists with
  1970. // a reference to vertex j in the fixed list
  1971. for (S32 k = 0; k < cf.mFaceList.size(); k++) {
  1972. for (S32 l = 0; l < 3; l++) {
  1973. if (cf.mFaceList[k].vertex[l] == i)
  1974. cf.mFaceList[k].vertex[l] = j;
  1975. }
  1976. }
  1977. } else {
  1978. for (S32 k = 0; k < cf.mFaceList.size(); k++) {
  1979. for (S32 l = 0; l < 3; l++) {
  1980. if (cf.mFaceList[k].vertex[l] == i)
  1981. cf.mFaceList[k].vertex[l] = fixedVerts.size();
  1982. }
  1983. }
  1984. fixedVerts.push_back(cf.mVertexList[i]);
  1985. }
  1986. }
  1987. cf.mVertexList.setSize(0);
  1988. cf.mVertexList = fixedVerts;
  1989. // Ok, so now we have a vertex list. Lets copy that out...
  1990. ConvexHullAccelerator* accel = new ConvexHullAccelerator;
  1991. detailCollisionAccelerators[dl] = accel;
  1992. accel->numVerts = cf.mVertexList.size();
  1993. accel->vertexList = new Point3F[accel->numVerts];
  1994. dMemcpy(accel->vertexList, cf.mVertexList.address(), sizeof(Point3F) * accel->numVerts);
  1995. accel->normalList = new Point3F[cf.mFaceList.size()];
  1996. for (i = 0; i < cf.mFaceList.size(); i++)
  1997. accel->normalList[i] = cf.mFaceList[i].normal;
  1998. accel->emitStrings = new U8*[accel->numVerts];
  1999. dMemset(accel->emitStrings, 0, sizeof(U8*) * accel->numVerts);
  2000. for (i = 0; i < accel->numVerts; i++) {
  2001. S32 j;
  2002. Vector<U32> faces;
  2003. VECTOR_SET_ASSOCIATION(faces);
  2004. for (j = 0; j < cf.mFaceList.size(); j++) {
  2005. if (cf.mFaceList[j].vertex[0] == i ||
  2006. cf.mFaceList[j].vertex[1] == i ||
  2007. cf.mFaceList[j].vertex[2] == i) {
  2008. faces.push_back(j);
  2009. }
  2010. }
  2011. AssertFatal(faces.size() != 0, "Huh? Vertex unreferenced by any faces");
  2012. // Insert all faces that didn't make the first cut, but share a plane with
  2013. // a face that's on the short list.
  2014. for (j = 0; j < cf.mFaceList.size(); j++) {
  2015. bool found = false;
  2016. S32 k;
  2017. for (k = 0; k < faces.size(); k++) {
  2018. if (faces[k] == j)
  2019. found = true;
  2020. }
  2021. if (found)
  2022. continue;
  2023. found = false;
  2024. for (k = 0; k < faces.size(); k++) {
  2025. if (mDot(accel->normalList[faces[k]], accel->normalList[j]) > 0.999) {
  2026. found = true;
  2027. break;
  2028. }
  2029. }
  2030. if (found)
  2031. faces.push_back(j);
  2032. }
  2033. Vector<U32> vertRemaps;
  2034. VECTOR_SET_ASSOCIATION(vertRemaps);
  2035. for (j = 0; j < faces.size(); j++) {
  2036. for (U32 k = 0; k < 3; k++) {
  2037. U32 insert = cf.mFaceList[faces[j]].vertex[k];
  2038. bool found = false;
  2039. for (S32 l = 0; l < vertRemaps.size(); l++) {
  2040. if (insert == vertRemaps[l]) {
  2041. found = true;
  2042. break;
  2043. }
  2044. }
  2045. if (!found)
  2046. vertRemaps.push_back(insert);
  2047. }
  2048. }
  2049. Vector<Point2I> edges;
  2050. VECTOR_SET_ASSOCIATION(edges);
  2051. for (j = 0; j < faces.size(); j++) {
  2052. for (U32 k = 0; k < 3; k++) {
  2053. U32 edgeStart = cf.mFaceList[faces[j]].vertex[(k + 0) % 3];
  2054. U32 edgeEnd = cf.mFaceList[faces[j]].vertex[(k + 1) % 3];
  2055. U32 e0 = getMin(edgeStart, edgeEnd);
  2056. U32 e1 = getMax(edgeStart, edgeEnd);
  2057. bool found = false;
  2058. for (S32 l = 0; l < edges.size(); l++) {
  2059. if (edges[l].x == e0 && edges[l].y == e1) {
  2060. found = true;
  2061. break;
  2062. }
  2063. }
  2064. if (!found)
  2065. edges.push_back(Point2I(e0, e1));
  2066. }
  2067. }
  2068. //AssertFatal(vertRemaps.size() < 256 && faces.size() < 256 && edges.size() < 256,
  2069. // "Error, ran over the shapebase assumptions about convex hulls.");
  2070. U32 emitStringLen = 1 + vertRemaps.size() +
  2071. 1 + (edges.size() * 2) +
  2072. 1 + (faces.size() * 4);
  2073. accel->emitStrings[i] = new U8[emitStringLen];
  2074. U32 currPos = 0;
  2075. accel->emitStrings[i][currPos++] = vertRemaps.size();
  2076. for (j = 0; j < vertRemaps.size(); j++)
  2077. accel->emitStrings[i][currPos++] = vertRemaps[j];
  2078. accel->emitStrings[i][currPos++] = edges.size();
  2079. for (j = 0; j < edges.size(); j++) {
  2080. S32 l;
  2081. U32 old = edges[j].x;
  2082. bool found = false;
  2083. for (l = 0; l < vertRemaps.size(); l++) {
  2084. if (vertRemaps[l] == old) {
  2085. found = true;
  2086. accel->emitStrings[i][currPos++] = l;
  2087. break;
  2088. }
  2089. }
  2090. AssertFatal(found, "Error, couldn't find the remap!");
  2091. old = edges[j].y;
  2092. found = false;
  2093. for (l = 0; l < vertRemaps.size(); l++) {
  2094. if (vertRemaps[l] == old) {
  2095. found = true;
  2096. accel->emitStrings[i][currPos++] = l;
  2097. break;
  2098. }
  2099. }
  2100. AssertFatal(found, "Error, couldn't find the remap!");
  2101. }
  2102. accel->emitStrings[i][currPos++] = faces.size();
  2103. for (j = 0; j < faces.size(); j++) {
  2104. accel->emitStrings[i][currPos++] = faces[j];
  2105. for (U32 k = 0; k < 3; k++) {
  2106. U32 old = cf.mFaceList[faces[j]].vertex[k];
  2107. bool found = false;
  2108. for (S32 l = 0; l < vertRemaps.size(); l++) {
  2109. if (vertRemaps[l] == old) {
  2110. found = true;
  2111. accel->emitStrings[i][currPos++] = l;
  2112. break;
  2113. }
  2114. }
  2115. AssertFatal(found, "Error, couldn't find the remap!");
  2116. }
  2117. }
  2118. AssertFatal(currPos == emitStringLen, "Error, over/underflowed the emission string!");
  2119. }
  2120. }
  2121. void TSShape::finalizeEditable()
  2122. {
  2123. for (U32 i = 0; i < meshes.size(); i++)
  2124. {
  2125. if (meshes[i])
  2126. {
  2127. meshes[i]->clearEditable();
  2128. }
  2129. }
  2130. }