tsShapeEdit.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  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 "console/consoleTypes.h"
  24. #include "core/resourceManager.h"
  25. #include "ts/tsShape.h"
  26. #include "ts/tsShapeInstance.h"
  27. #include "ts/tsLastDetail.h"
  28. #include "ts/tsMaterialList.h"
  29. #include "core/stream/fileStream.h"
  30. #include "core/volume.h"
  31. #include "assets/assetManager.h"
  32. //-----------------------------------------------------------------------------
  33. S32 TSShape::addName(const String& name)
  34. {
  35. // Check for empty names
  36. if (name.isEmpty())
  37. return -1;
  38. // Return the index of the new name (add if it is unique)
  39. S32 index = findName(name);
  40. if (index >= 0)
  41. return index;
  42. names.push_back(StringTable->insert(name));
  43. return names.size()-1;
  44. }
  45. void TSShape::updateSmallestVisibleDL()
  46. {
  47. // Update smallest visible detail
  48. mSmallestVisibleDL = -1;
  49. mSmallestVisibleSize = F32_MAX;
  50. F32 maxSize = 0.0f;
  51. for (S32 i = 0; i < details.size(); i++)
  52. {
  53. maxSize = getMax( maxSize, details[i].size );
  54. if ((details[i].size >= 0) && (details[i].size < mSmallestVisibleSize))
  55. {
  56. mSmallestVisibleDL = i;
  57. mSmallestVisibleSize = details[i].size;
  58. }
  59. }
  60. // Initialize the detail level lod lookup table.
  61. mDetailLevelLookup.setSize( (U32)( maxSize * 2.0f ) + 2 );
  62. for ( U32 l=0; l < mDetailLevelLookup.size(); l++ )
  63. {
  64. F32 pixelSize = (F32)l;
  65. S32 dl = -1;
  66. for ( U32 d=0; d < details.size(); d++ )
  67. {
  68. // Break when we get to hidden detail
  69. // levels like collision shapes.
  70. if ( details[d].size < 0 )
  71. break;
  72. if ( pixelSize > details[d].size )
  73. {
  74. dl = d;
  75. break;
  76. }
  77. if ( d + 1 >= details.size() || details[d+1].size < 0 )
  78. {
  79. // We've run out of details and haven't found anything?
  80. // Let's just grab this one.
  81. dl = d;
  82. break;
  83. }
  84. }
  85. // Calculate the intra detail level.
  86. F32 intraDL = 0;
  87. if ( dl > -1 )
  88. {
  89. F32 curSize = details[dl].size;
  90. F32 nextSize = dl == 0 ? 2.0f * curSize : details[dl - 1].size;
  91. intraDL = mClampF( nextSize - curSize > 0.01f ? (pixelSize - curSize) / (nextSize - curSize) : 1.0f, 0, 1 );
  92. }
  93. mDetailLevelLookup[l].set( dl, intraDL );
  94. }
  95. // Test for using the legacy screen error
  96. // lod method here instead of runtime.
  97. //
  98. // See setDetailFromDistance().
  99. //
  100. mUseDetailFromScreenError = mSmallestVisibleDL >= 0 &&
  101. details.first().maxError >= 0;
  102. }
  103. S32 TSShape::addDetail(const String& dname, S32 size, S32 subShapeNum)
  104. {
  105. S32 nameIndex = addName(avar("%s%d", dname.c_str(), size));
  106. // Check if this detail size has already been added
  107. S32 index;
  108. for (index = 0; index < details.size(); index++)
  109. {
  110. if ((details[index].size == size) &&
  111. (details[index].subShapeNum == subShapeNum) &&
  112. (details[index].nameIndex == nameIndex))
  113. return index;
  114. if (details[index].size < size)
  115. break;
  116. }
  117. // Create a new detail level at the right index, so array
  118. // remains sorted by detail size (from largest to smallest)
  119. details.insert(index);
  120. TSShape::Detail &detail = details[index];
  121. // Clear the detail to ensure no garbage values
  122. // are left in any vars we don't set.
  123. dMemset( &detail, 0, sizeof( Detail ) );
  124. // Setup the detail.
  125. detail.nameIndex = nameIndex;
  126. detail.size = size;
  127. detail.subShapeNum = subShapeNum;
  128. detail.objectDetailNum = 0;
  129. detail.averageError = -1;
  130. detail.maxError = -1;
  131. detail.polyCount = 0;
  132. // Resize alpha vectors
  133. alphaIn.increment();
  134. alphaOut.increment();
  135. // Fixup objectDetailNum in other detail levels
  136. for (S32 i = index+1; i < details.size(); i++)
  137. {
  138. if ((details[i].subShapeNum >= 0) &&
  139. ((subShapeNum == -1) || (details[i].subShapeNum == subShapeNum)))
  140. details[i].objectDetailNum++;
  141. }
  142. // Update smallest visible detail
  143. updateSmallestVisibleDL();
  144. return index;
  145. }
  146. S32 TSShape::addImposter(const String& cachePath, S32 size, S32 numEquatorSteps,
  147. S32 numPolarSteps, S32 dl, S32 dim, bool includePoles, F32 polarAngle)
  148. {
  149. // Check if the desired size is already in use
  150. bool isNewDetail = false;
  151. S32 detIndex = findDetailBySize( size );
  152. if ( detIndex >= 0 )
  153. {
  154. // Size is in use. If the detail is already an imposter, we can just change
  155. // the settings, otherwise quit
  156. if ( details[detIndex].subShapeNum >= 0 )
  157. {
  158. Con::errorf( "TSShape::addImposter: A non-billboard detail already "
  159. "exists at size %d", size );
  160. return -1;
  161. }
  162. }
  163. else
  164. {
  165. // Size is not in use. If an imposter already exists, change its size, otherwise
  166. // create a new detail
  167. for ( detIndex = 0; detIndex < details.size(); ++detIndex )
  168. {
  169. if ( details[detIndex].subShapeNum < 0 )
  170. {
  171. // Change the imposter detail size
  172. setDetailSize( details[detIndex].size, size );
  173. break;
  174. }
  175. }
  176. if ( detIndex == details.size() )
  177. {
  178. isNewDetail = true;
  179. detIndex = addDetail( "bbDetail", size, -1 );
  180. }
  181. }
  182. // Now set the billboard properties.
  183. Detail &detail = details[detIndex];
  184. // In prior to DTS version 26 we would pack the autobillboard
  185. // into this single 32bit value. This was prone to overflows
  186. // of parameters caused random bugs.
  187. //
  188. // Set the old autobillboard properties var to zero.
  189. detail.objectDetailNum = 0;
  190. // We now use the new vars.
  191. detail.bbEquatorSteps = numEquatorSteps;
  192. detail.bbPolarSteps = numPolarSteps;
  193. detail.bbPolarAngle = polarAngle;
  194. detail.bbDetailLevel = dl;
  195. detail.bbDimension = dim;
  196. detail.bbIncludePoles = includePoles;
  197. // Rebuild billboard details or force an update of the modified detail
  198. if ( isNewDetail )
  199. {
  200. // Add NULL meshes for this detail
  201. for ( S32 iObj = 0; iObj < objects.size(); ++iObj )
  202. {
  203. if ( detIndex < objects[iObj].numMeshes )
  204. {
  205. objects[iObj].numMeshes++;
  206. meshes.insert( objects[iObj].startMeshIndex + detIndex, NULL );
  207. for (S32 j = iObj + 1; j < objects.size(); ++j )
  208. objects[j].startMeshIndex++;
  209. }
  210. }
  211. // Could be dedicated server.
  212. if ( GFXDevice::devicePresent() )
  213. setupBillboardDetails( cachePath );
  214. while ( detailCollisionAccelerators.size() < details.size() )
  215. detailCollisionAccelerators.push_back( NULL );
  216. }
  217. else
  218. {
  219. if ( billboardDetails.size() && GFXDevice::devicePresent() )
  220. {
  221. delete billboardDetails[detIndex];
  222. billboardDetails[detIndex] = new TSLastDetail(
  223. this,
  224. cachePath,
  225. detail.bbEquatorSteps,
  226. detail.bbPolarSteps,
  227. detail.bbPolarAngle,
  228. detail.bbIncludePoles,
  229. detail.bbDetailLevel,
  230. detail.bbDimension );
  231. billboardDetails[detIndex]->update( true );
  232. }
  233. }
  234. return detIndex;
  235. }
  236. bool TSShape::removeImposter()
  237. {
  238. // Find the imposter detail level
  239. S32 detIndex;
  240. for ( detIndex = 0; detIndex < details.size(); ++detIndex )
  241. {
  242. if ( details[detIndex].subShapeNum < 0 )
  243. break;
  244. }
  245. if ( detIndex == details.size() )
  246. {
  247. Con::errorf( "TSShape::removeImposter: No imposter detail level found in shape" );
  248. return false;
  249. }
  250. // Remove the detail level
  251. details.erase( detIndex );
  252. if ( detIndex < billboardDetails.size() )
  253. {
  254. // Delete old textures
  255. TSLastDetail* bb = billboardDetails[detIndex];
  256. bb->deleteImposterCacheTextures();
  257. delete billboardDetails[detIndex];
  258. }
  259. billboardDetails.clear();
  260. detailCollisionAccelerators.erase( detIndex );
  261. // Remove the (NULL) meshes from each object
  262. for ( S32 iObj = 0; iObj < objects.size(); ++iObj )
  263. {
  264. if ( detIndex < objects[iObj].numMeshes )
  265. {
  266. objects[iObj].numMeshes--;
  267. meshes.erase( objects[iObj].startMeshIndex + detIndex );
  268. for (S32 j = iObj + 1; j < objects.size(); ++j )
  269. objects[j].startMeshIndex--;
  270. }
  271. }
  272. // Update smallest visible size
  273. updateSmallestVisibleDL();
  274. return true;
  275. }
  276. //-----------------------------------------------------------------------------
  277. /// Get the index of the element in the group with a given name
  278. template<class T> S32 findByName(Vector<T>& group, S32 nameIndex)
  279. {
  280. for (S32 i = 0; i < group.size(); i++)
  281. if (group[i].nameIndex == nameIndex)
  282. return i;
  283. return -1;
  284. }
  285. /// Adjust the nameIndex for elements in the group
  286. template<class T> void adjustForNameRemoval(Vector<T>& group, S32 nameIndex)
  287. {
  288. for (S32 i = 0; i < group.size(); i++)
  289. if (group[i].nameIndex > nameIndex)
  290. group[i].nameIndex--;
  291. }
  292. bool TSShape::removeName(const String& name)
  293. {
  294. // Check if the name is still in use
  295. S32 nameIndex = findName(name);
  296. if ((findByName(nodes, nameIndex) >= 0) ||
  297. (findByName(objects, nameIndex) >= 0) ||
  298. (findByName(sequences, nameIndex) >= 0) ||
  299. (findByName(details, nameIndex) >= 0))
  300. return false;
  301. // Remove the name, then update nameIndex for affected elements
  302. names.erase(nameIndex);
  303. adjustForNameRemoval(nodes, nameIndex);
  304. adjustForNameRemoval(objects, nameIndex);
  305. adjustForNameRemoval(sequences, nameIndex);
  306. adjustForNameRemoval(details, nameIndex);
  307. return true;
  308. }
  309. //-----------------------------------------------------------------------------
  310. template<class T> bool doRename(TSShape* shape, Vector<T>& group, const String& oldName, const String& newName)
  311. {
  312. // Find the element in the group with the oldName
  313. S32 index = findByName(group, shape->findName(oldName));
  314. if (index < 0)
  315. {
  316. Con::errorf("TSShape::rename: Could not find '%s'", oldName.c_str());
  317. return false;
  318. }
  319. // Ignore trivial renames
  320. if (oldName.equal(newName, String::NoCase))
  321. return true;
  322. // Check that this name is not already in use
  323. if (findByName(group, shape->findName(newName)) >= 0)
  324. {
  325. Con::errorf("TSShape::rename: '%s' is already in use", newName.c_str());
  326. return false;
  327. }
  328. // Do the rename (the old name will be removed if it is no longer in use)
  329. group[index].nameIndex = shape->addName(newName);
  330. shape->removeName(oldName);
  331. return true;
  332. }
  333. bool TSShape::renameNode(const String& oldName, const String& newName)
  334. {
  335. return doRename(this, nodes, oldName, newName);
  336. }
  337. bool TSShape::renameObject(const String& oldName, const String& newName)
  338. {
  339. return doRename(this, objects, oldName, newName);
  340. }
  341. bool TSShape::renameDetail(const String& oldName, const String& newName)
  342. {
  343. return doRename(this, details, oldName, newName);
  344. }
  345. bool TSShape::renameSequence(const String& oldName, const String& newName)
  346. {
  347. return doRename(this, sequences, oldName, newName);
  348. }
  349. //-----------------------------------------------------------------------------
  350. bool TSShape::addNode(const String& name, const String& parentName, const Point3F& pos, const QuatF& rot)
  351. {
  352. // Check that adding this node would not exceed the maximum count
  353. if (nodes.size() >= MAX_TS_SET_SIZE)
  354. {
  355. Con::errorf("TSShape::addNode: Cannot add node, shape already has maximum (%d) nodes", MAX_TS_SET_SIZE);
  356. return false;
  357. }
  358. // Check that there is not already a node with this name
  359. if (findNode(name) >= 0)
  360. {
  361. Con::errorf("TSShape::addNode: %s already exists!", name.c_str());
  362. return false;
  363. }
  364. // Find the parent node (OK for name to be empty => node is at root level)
  365. S32 parentIndex = -1;
  366. if (String::compare(parentName, ""))
  367. {
  368. parentIndex = findNode(parentName);
  369. if (parentIndex < 0)
  370. {
  371. Con::errorf("TSShape::addNode: Could not find parent node '%s'", parentName.c_str());
  372. return false;
  373. }
  374. }
  375. // Need to make everything editable since node indexes etc will change
  376. makeEditable();
  377. // Insert node at the end of the subshape
  378. S32 subShapeIndex = (parentIndex >= 0) ? getSubShapeForNode(parentIndex) : 0;
  379. S32 nodeIndex = subShapeNumNodes[subShapeIndex];
  380. // Adjust subshape node indices
  381. subShapeNumNodes[subShapeIndex]++;
  382. for (S32 i = subShapeIndex + 1; i < subShapeFirstNode.size(); i++)
  383. subShapeFirstNode[i]++;
  384. // Update animation sequences
  385. for (S32 iSeq = 0; iSeq < sequences.size(); iSeq++)
  386. {
  387. // Update animation matters arrays (new node is not animated)
  388. TSShape::Sequence& seq = sequences[iSeq];
  389. seq.translationMatters.insert(nodeIndex, false);
  390. seq.rotationMatters.insert(nodeIndex, false);
  391. seq.scaleMatters.insert(nodeIndex, false);
  392. }
  393. // Insert the new node
  394. TSShape::Node node;
  395. node.nameIndex = addName(name);
  396. node.parentIndex = parentIndex;
  397. node.firstChild = -1;
  398. node.firstObject = -1;
  399. node.nextSibling = -1;
  400. nodes.insert(nodeIndex, node);
  401. // Insert node default translation and rotation
  402. Quat16 rot16;
  403. rot16.set(rot);
  404. defaultTranslations.insert(nodeIndex, pos);
  405. defaultRotations.insert(nodeIndex, rot16);
  406. // Fixup node indices
  407. for (S32 i = 0; i < nodes.size(); i++)
  408. {
  409. if (nodes[i].parentIndex >= nodeIndex)
  410. nodes[i].parentIndex++;
  411. }
  412. for (S32 i = 0; i < objects.size(); i++)
  413. {
  414. if (objects[i].nodeIndex >= nodeIndex)
  415. objects[i].nodeIndex++;
  416. }
  417. for (S32 i = 0; i < meshes.size(); i++)
  418. {
  419. if (meshes[i] && (meshes[i]->getMeshType() == TSMesh::SkinMeshType))
  420. {
  421. TSSkinMesh* skin = dynamic_cast<TSSkinMesh*>(meshes[i]);
  422. for (S32 j = 0; j < skin->batchData.nodeIndex.size(); j++)
  423. {
  424. if (skin->batchData.nodeIndex[j] >= nodeIndex)
  425. skin->batchData.nodeIndex[j]++;
  426. }
  427. }
  428. }
  429. initObjects();
  430. return true;
  431. }
  432. /// Erase animation keyframes (translation, rotation etc)
  433. template<class T> S32 eraseStates(Vector<T>& vec, const TSIntegerSet& matters, S32 base, S32 numKeyframes, S32 index=-1)
  434. {
  435. S32 dest, count;
  436. if (index == -1)
  437. {
  438. // Erase for all nodes/objects
  439. dest = base;
  440. count = numKeyframes * matters.count();
  441. }
  442. else
  443. {
  444. // Erase for the indexed node/object only
  445. dest = base + matters.count(index)*numKeyframes;
  446. count = numKeyframes;
  447. }
  448. // Erase the values
  449. if (count)
  450. {
  451. if ((dest + count) < vec.size())
  452. dCopyArray(&vec[dest], &vec[dest + count], vec.size() - (dest + count));
  453. vec.decrement(count);
  454. }
  455. return count;
  456. }
  457. bool TSShape::removeNode(const String& name)
  458. {
  459. // Find the node to be removed
  460. S32 nodeIndex = findNode(name);
  461. if (nodeIndex < 0)
  462. {
  463. Con::errorf("TSShape::removeNode: Could not find node '%s'", name.c_str());
  464. return false;
  465. }
  466. S32 nodeParentIndex = nodes[nodeIndex].parentIndex;
  467. // Warn if there are objects attached to this node
  468. Vector<S32> nodeObjects;
  469. getNodeObjects(nodeIndex, nodeObjects);
  470. if (nodeObjects.size())
  471. {
  472. Con::warnf("TSShape::removeNode: Node '%s' has %d objects attached, these "
  473. "will be reassigned to the node's parent ('%s')", name.c_str(), nodeObjects.size(),
  474. ((nodeParentIndex >= 0) ? getName(nodes[nodeParentIndex].nameIndex).c_str() : "null"));
  475. }
  476. // Need to make everything editable since node indexes etc will change
  477. makeEditable();
  478. // Update animation sequences
  479. for (S32 iSeq = 0; iSeq < sequences.size(); iSeq++)
  480. {
  481. TSShape::Sequence& seq = sequences[iSeq];
  482. // Remove animated node transforms
  483. if (seq.translationMatters.test(nodeIndex))
  484. eraseStates(nodeTranslations, seq.translationMatters, seq.baseTranslation, seq.numKeyframes, nodeIndex);
  485. if (seq.rotationMatters.test(nodeIndex))
  486. eraseStates(nodeRotations, seq.rotationMatters, seq.baseRotation, seq.numKeyframes, nodeIndex);
  487. if (seq.scaleMatters.test(nodeIndex))
  488. {
  489. if (seq.flags & TSShape::ArbitraryScale)
  490. {
  491. eraseStates(nodeArbitraryScaleRots, seq.scaleMatters, seq.baseScale, seq.numKeyframes, nodeIndex);
  492. eraseStates(nodeArbitraryScaleFactors, seq.scaleMatters, seq.baseScale, seq.numKeyframes, nodeIndex);
  493. }
  494. else if (seq.flags & TSShape::AlignedScale)
  495. eraseStates(nodeAlignedScales, seq.scaleMatters, seq.baseScale, seq.numKeyframes, nodeIndex);
  496. else
  497. eraseStates(nodeUniformScales, seq.scaleMatters, seq.baseScale, seq.numKeyframes, nodeIndex);
  498. }
  499. seq.translationMatters.erase(nodeIndex);
  500. seq.rotationMatters.erase(nodeIndex);
  501. seq.scaleMatters.erase(nodeIndex);
  502. }
  503. // Remove the node
  504. nodes.erase(nodeIndex);
  505. defaultTranslations.erase(nodeIndex);
  506. defaultRotations.erase(nodeIndex);
  507. // Adjust subshape node indices
  508. S32 subShapeIndex = getSubShapeForNode(nodeIndex);
  509. subShapeNumNodes[subShapeIndex]--;
  510. for (S32 i = subShapeIndex + 1; i < subShapeFirstNode.size(); i++)
  511. subShapeFirstNode[i]--;
  512. // Fixup node parent indices
  513. for (S32 i = 0; i < nodes.size(); i++)
  514. {
  515. if (nodes[i].parentIndex == nodeIndex)
  516. nodes[i].parentIndex = -1;
  517. else if (nodes[i].parentIndex > nodeIndex)
  518. nodes[i].parentIndex--;
  519. }
  520. if (nodeParentIndex > nodeIndex)
  521. nodeParentIndex--;
  522. // Fixup object node indices, and re-assign attached objects to node's parent
  523. for (S32 i = 0; i < objects.size(); i++)
  524. {
  525. if (objects[i].nodeIndex == nodeIndex)
  526. objects[i].nodeIndex = nodeParentIndex;
  527. if (objects[i].nodeIndex > nodeIndex)
  528. objects[i].nodeIndex--;
  529. }
  530. // Fixup skin weight node indices, and re-assign weights for deleted node to its parent
  531. for (S32 i = 0; i < meshes.size(); i++)
  532. {
  533. if (meshes[i] && (meshes[i]->getMeshType() == TSMesh::SkinMeshType))
  534. {
  535. TSSkinMesh* skin = dynamic_cast<TSSkinMesh*>(meshes[i]);
  536. for (S32 j = 0; j < skin->batchData.nodeIndex.size(); j++)
  537. {
  538. if (skin->batchData.nodeIndex[j] == nodeIndex)
  539. skin->batchData.nodeIndex[j] = nodeParentIndex;
  540. if (skin->batchData.nodeIndex[j] > nodeIndex)
  541. skin->batchData.nodeIndex[j]--;
  542. }
  543. }
  544. }
  545. // Remove the sequence name if it is no longer in use
  546. removeName(name);
  547. initObjects();
  548. return true;
  549. }
  550. //-----------------------------------------------------------------------------
  551. bool TSShape::setNodeTransform(const String& name, const Point3F& pos, const QuatF& rot)
  552. {
  553. // Find the node to be transformed
  554. S32 nodeIndex = findNode(name);
  555. if (nodeIndex < 0)
  556. {
  557. Con::errorf("TSShape::setNodeTransform: Could not find node '%s'", name.c_str());
  558. return false;
  559. }
  560. // Update initial node position and rotation
  561. defaultTranslations[nodeIndex] = pos;
  562. defaultRotations[nodeIndex].set(rot);
  563. return true;
  564. }
  565. //-----------------------------------------------------------------------------
  566. S32 TSShape::addObject(const String& objName, S32 subShapeIndex)
  567. {
  568. S32 objIndex = subShapeNumObjects[subShapeIndex];
  569. // Add object to subshape
  570. subShapeNumObjects[subShapeIndex]++;
  571. for (S32 i = subShapeIndex + 1; i < subShapeFirstObject.size(); i++)
  572. subShapeFirstObject[i]++;
  573. TSShape::Object obj;
  574. obj.nameIndex = addName(objName);
  575. obj.nodeIndex = 0;
  576. obj.numMeshes = 0;
  577. obj.startMeshIndex = (objIndex == 0) ? 0 : objects[objIndex-1].startMeshIndex + objects[objIndex-1].numMeshes;
  578. obj.firstDecal = 0;
  579. obj.nextSibling = 0;
  580. objects.insert(objIndex, obj);
  581. // Add default object state
  582. TSShape::ObjectState state;
  583. state.frameIndex = 0;
  584. state.matFrameIndex = 0;
  585. state.vis = 1.0f;
  586. objectStates.insert(objIndex, state);
  587. // Fixup sequences
  588. for (S32 i = 0; i < sequences.size(); i++)
  589. sequences[i].baseObjectState++;
  590. return objIndex;
  591. }
  592. void TSShape::addMeshToObject(S32 objIndex, S32 meshIndex, TSMesh* mesh)
  593. {
  594. TSShape::Object& obj = objects[objIndex];
  595. // Pad with NULLs if required
  596. S32 oldNumMeshes = obj.numMeshes;
  597. if (mesh)
  598. {
  599. for (S32 i = obj.numMeshes; i < meshIndex; i++)
  600. {
  601. meshes.insert(obj.startMeshIndex + i, NULL);
  602. obj.numMeshes++;
  603. }
  604. }
  605. // Insert the new mesh
  606. meshes.insert(obj.startMeshIndex + meshIndex, mesh);
  607. obj.numMeshes++;
  608. // Skinned meshes are not attached to any node
  609. if (mesh && (mesh->getMeshType() == TSMesh::SkinMeshType))
  610. obj.nodeIndex = -1;
  611. // Fixup mesh indices for other objects
  612. for (S32 i = 0; i < objects.size(); i++)
  613. {
  614. if ((i != objIndex) && (objects[i].startMeshIndex >= obj.startMeshIndex))
  615. objects[i].startMeshIndex += (obj.numMeshes - oldNumMeshes);
  616. }
  617. }
  618. void TSShape::removeMeshFromObject(S32 objIndex, S32 meshIndex)
  619. {
  620. TSShape::Object& obj = objects[objIndex];
  621. // Remove the mesh, but do not destroy it (this must be done by the caller)
  622. meshes[obj.startMeshIndex + meshIndex] = NULL;
  623. // Check if there are any objects remaining that have a valid mesh at this
  624. // detail size
  625. bool removeDetail = true;
  626. for (S32 i = 0; i < objects.size(); i++)
  627. {
  628. if ((meshIndex < objects[i].numMeshes) && meshes[objects[i].startMeshIndex + meshIndex])
  629. {
  630. removeDetail = false;
  631. break;
  632. }
  633. }
  634. // Remove detail level if possible
  635. if (removeDetail)
  636. {
  637. for (S32 i = 0; i < objects.size(); i++)
  638. {
  639. if (meshIndex < objects[i].numMeshes)
  640. {
  641. U32 idxToRemove = objects[i].startMeshIndex + meshIndex;
  642. meshes.erase(idxToRemove);
  643. objects[i].numMeshes--;
  644. // Clear invalid parent
  645. for (U32 k = 0; k < meshes.size(); k++)
  646. {
  647. if (meshes[k] == NULL)
  648. continue;
  649. if (meshes[k]->mParentMesh == idxToRemove)
  650. {
  651. meshes[k]->mParentMesh = -1;
  652. }
  653. else if (meshes[k]->mParentMesh > idxToRemove)
  654. {
  655. meshes[k]->mParentMesh--;
  656. }
  657. }
  658. for (S32 j = 0; j < objects.size(); j++)
  659. {
  660. if (objects[j].startMeshIndex > objects[i].startMeshIndex)
  661. objects[j].startMeshIndex--;
  662. }
  663. }
  664. }
  665. Vector<S32> validDetails;
  666. getSubShapeDetails(getSubShapeForObject(objIndex), validDetails);
  667. for (S32 i = 0; i < validDetails.size(); i++)
  668. {
  669. TSShape::Detail& detail = details[validDetails[i]];
  670. if (detail.objectDetailNum > meshIndex)
  671. detail.objectDetailNum--;
  672. }
  673. details.erase(validDetails[meshIndex]);
  674. }
  675. // Remove trailing NULL meshes from the object
  676. S32 oldNumMeshes = obj.numMeshes;
  677. while (obj.numMeshes && !meshes[obj.startMeshIndex + obj.numMeshes - 1])
  678. {
  679. U32 idxToRemove = obj.startMeshIndex + obj.numMeshes - 1;
  680. meshes.erase(idxToRemove);
  681. // Clear invalid parent
  682. for (U32 k = 0; k < meshes.size(); k++)
  683. {
  684. if (meshes[k] == NULL)
  685. continue;
  686. if (meshes[k]->mParentMesh == idxToRemove)
  687. {
  688. meshes[k]->mParentMesh = -1;
  689. }
  690. else if (meshes[k]->mParentMesh > idxToRemove)
  691. {
  692. meshes[k]->mParentMesh--;
  693. }
  694. }
  695. obj.numMeshes--;
  696. }
  697. // Fixup mesh indices for other objects
  698. for (S32 i = 0; i < objects.size(); i++)
  699. {
  700. if (objects[i].startMeshIndex > obj.startMeshIndex)
  701. objects[i].startMeshIndex -= (oldNumMeshes - obj.numMeshes);
  702. }
  703. }
  704. bool TSShape::setObjectNode(const String& objName, const String& nodeName)
  705. {
  706. // Find the object and node
  707. S32 objIndex = findObject(objName);
  708. if (objIndex < 0)
  709. {
  710. Con::errorf("TSShape::setObjectNode: Could not find object '%s'", objName.c_str());
  711. return false;
  712. }
  713. S32 nodeIndex;
  714. if (nodeName.isEmpty())
  715. nodeIndex = -1;
  716. else
  717. {
  718. nodeIndex = findNode(nodeName);
  719. if (nodeIndex < 0)
  720. {
  721. Con::errorf("TSShape::setObjectNode: Could not find node '%s'", nodeName.c_str());
  722. return false;
  723. }
  724. }
  725. objects[objIndex].nodeIndex = nodeIndex;
  726. return true;
  727. }
  728. bool TSShape::removeObject(const String& name)
  729. {
  730. // Find the object
  731. S32 objIndex = findObject(name);
  732. if (objIndex < 0)
  733. {
  734. Con::errorf("TSShape::removeObject: Could not find object '%s'", name.c_str());
  735. return false;
  736. }
  737. // Need to make everything editable since node indexes etc will change
  738. makeEditable();
  739. // Destroy all meshes in the object
  740. TSShape::Object& obj = objects[objIndex];
  741. while ( obj.numMeshes )
  742. {
  743. destructInPlace(meshes[obj.startMeshIndex + obj.numMeshes - 1]);
  744. removeMeshFromObject(objIndex, obj.numMeshes - 1);
  745. }
  746. // Remove the object from the shape
  747. objects.erase(objIndex);
  748. S32 subShapeIndex = getSubShapeForObject(objIndex);
  749. subShapeNumObjects[subShapeIndex]--;
  750. for (S32 i = subShapeIndex + 1; i < subShapeFirstObject.size(); i++)
  751. subShapeFirstObject[i]--;
  752. // Remove the object from all sequences
  753. for (S32 i = 0; i < sequences.size(); i++)
  754. {
  755. TSShape::Sequence& seq = sequences[i];
  756. TSIntegerSet objMatters(seq.frameMatters);
  757. objMatters.overlap(seq.matFrameMatters);
  758. objMatters.overlap(seq.visMatters);
  759. if (objMatters.test(objIndex))
  760. eraseStates(objectStates, objMatters, seq.baseObjectState, seq.numKeyframes, objIndex);
  761. seq.frameMatters.erase(objIndex);
  762. seq.matFrameMatters.erase(objIndex);
  763. seq.visMatters.erase(objIndex);
  764. }
  765. // Remove the object name if it is no longer in use
  766. removeName(name);
  767. // Update smallest visible detail
  768. updateSmallestVisibleDL();
  769. initObjects();
  770. return true;
  771. }
  772. //-----------------------------------------------------------------------------
  773. // Helper to copy a TSMesh ready for adding to this TSShape (with the right vertex format etc)
  774. TSMesh* TSShape::copyMesh( const TSMesh* srcMesh ) const
  775. {
  776. TSMesh * mesh = 0;
  777. if ( srcMesh && ( srcMesh->getMeshType() == TSMesh::SkinMeshType ) )
  778. {
  779. TSSkinMesh* skin = new TSSkinMesh;
  780. // Copy skin elements
  781. const TSSkinMesh *srcSkin = dynamic_cast<const TSSkinMesh*>(srcMesh);
  782. skin->weight = srcSkin->weight;
  783. skin->vertexIndex = srcSkin->vertexIndex;
  784. skin->boneIndex = srcSkin->boneIndex;
  785. skin->batchData.nodeIndex = srcSkin->batchData.nodeIndex;
  786. skin->batchData.initialTransforms = srcSkin->batchData.initialTransforms;
  787. skin->batchData.initialVerts = srcSkin->batchData.initialVerts;
  788. skin->batchData.initialNorms = srcSkin->batchData.initialNorms;
  789. mesh = static_cast<TSMesh*>(skin);
  790. }
  791. else
  792. {
  793. mesh = new TSMesh;
  794. }
  795. if ( !srcMesh )
  796. return mesh; // return an empty mesh
  797. // Copy mesh elements
  798. mesh->mIndices = srcMesh->mIndices;
  799. mesh->mPrimitives = srcMesh->mPrimitives;
  800. mesh->numFrames = srcMesh->numFrames;
  801. mesh->numMatFrames = srcMesh->numMatFrames;
  802. mesh->vertsPerFrame = srcMesh->vertsPerFrame;
  803. mesh->setFlags(srcMesh->getFlags());
  804. mesh->mNumVerts = srcMesh->mNumVerts;
  805. // Copy vertex data in an *unpacked* form
  806. mesh->copySourceVertexDataFrom(srcMesh);
  807. mesh->createTangents(mesh->mVerts, mesh->mNorms);
  808. mesh->mEncodedNorms.set(NULL, 0);
  809. mesh->computeBounds();
  810. return mesh;
  811. }
  812. bool TSShape::addMesh(TSMesh* mesh, const String& meshName)
  813. {
  814. // Ensure mesh is in editable state
  815. mesh->makeEditable();
  816. // Need to make everything editable since node indexes etc will change
  817. makeEditable();
  818. // Determine the object name and detail size from the mesh name
  819. S32 detailSize = 999;
  820. String objName(String::GetTrailingNumber(meshName, detailSize));
  821. // Find the destination object (create one if it does not exist)
  822. S32 objIndex = findObject(objName);
  823. if (objIndex < 0)
  824. objIndex = addObject(objName, 0);
  825. AssertFatal(objIndex >= 0 && objIndex < objects.size(), "Invalid object index!");
  826. // Determine the subshape this object belongs to
  827. S32 subShapeIndex = getSubShapeForObject(objIndex);
  828. AssertFatal(subShapeIndex < subShapeFirstObject.size(), "Could not find subshape for object!");
  829. // Get the existing detail levels for the subshape
  830. Vector<S32> validDetails;
  831. getSubShapeDetails(subShapeIndex, validDetails);
  832. // Determine where to add the new mesh, and whether this is a new detail
  833. S32 detIndex;
  834. bool newDetail = true;
  835. for (detIndex = 0; detIndex < validDetails.size(); detIndex++)
  836. {
  837. const TSShape::Detail& det = details[validDetails[detIndex]];
  838. if (detailSize >= det.size)
  839. {
  840. newDetail = (det.size != detailSize);
  841. break;
  842. }
  843. }
  844. // Insert the new detail level if required
  845. if (newDetail)
  846. {
  847. // Determine a name for the detail level
  848. const char* detailName;
  849. if (dStrStartsWith(objName, "Col"))
  850. detailName = "collision";
  851. else if (dStrStartsWith(objName, "loscol"))
  852. detailName = "los";
  853. else
  854. detailName = "detail";
  855. S32 index = addDetail(detailName, detailSize, subShapeIndex);
  856. details[index].objectDetailNum = detIndex;
  857. }
  858. // Adding a new mesh or detail level is a bit tricky, since each
  859. // object potentially stores a different number of meshes, including
  860. // NULL meshes for higher detail levels where required.
  861. // For example, the following table shows 3 objects. Note how NULLs
  862. // must be inserted for detail levels higher than the first valid
  863. // mesh, but details after the the last valid mesh are left empty.
  864. //
  865. // Detail | Object1 | Object2 | Object3
  866. // ---------+-----------+-----------+---------
  867. // 128 | 128 | NULL | NULL
  868. // 64 | | NULL | 64
  869. // 32 | | 32 | NULL
  870. // 2 | | | 2
  871. // Add meshes as required for each object
  872. for (S32 i = 0; i < subShapeNumObjects[subShapeIndex]; i++)
  873. {
  874. S32 index = subShapeFirstObject[subShapeIndex] + i;
  875. const TSShape::Object& obj = objects[index];
  876. if (index == objIndex)
  877. {
  878. // The target object: replace the existing mesh (if any) or add a new one
  879. // if required.
  880. if (!newDetail && (detIndex < obj.numMeshes))
  881. {
  882. if ( meshes[obj.startMeshIndex + detIndex] )
  883. destructInPlace(meshes[obj.startMeshIndex + detIndex]);
  884. meshes[obj.startMeshIndex + detIndex] = mesh;
  885. }
  886. else
  887. addMeshToObject(index, detIndex, mesh);
  888. }
  889. else
  890. {
  891. // Other objects: add a NULL mesh only if inserting before a valid mesh
  892. if (newDetail && (detIndex < obj.numMeshes))
  893. addMeshToObject(index, detIndex, NULL);
  894. }
  895. }
  896. initObjects();
  897. return true;
  898. }
  899. bool TSShape::addMesh(TSShape* srcShape, const String& srcMeshName, const String& meshName)
  900. {
  901. // Find the mesh in the source shape
  902. TSMesh* srcMesh = srcShape->findMesh(srcMeshName);
  903. if (!srcMesh)
  904. {
  905. Con::errorf("TSShape::addMesh: Could not find mesh '%s' in shape", srcMeshName.c_str());
  906. return false;
  907. }
  908. // Copy the source mesh
  909. TSMesh *mesh = copyMesh( srcMesh );
  910. if (srcMesh->getMeshType() == TSMesh::SkinMeshType)
  911. {
  912. TSSkinMesh *srcSkin = dynamic_cast<TSSkinMesh*>(srcMesh);
  913. // Check that the source skin is compatible with our skeleton
  914. Vector<S32> nodeMap(srcShape->nodes.size());
  915. for (S32 i = 0; i < srcShape->nodes.size(); i++)
  916. nodeMap.push_back( findNode( srcShape->getName(srcShape->nodes[i].nameIndex) ) );
  917. for (S32 i = 0; i < srcSkin->boneIndex.size(); i++)
  918. {
  919. S32 srcNode = srcSkin->boneIndex[i];
  920. if (nodeMap[srcNode] == -1)
  921. {
  922. const char* name = srcShape->getName(srcShape->nodes[srcNode].nameIndex).c_str();
  923. Con::errorf("TSShape::addMesh: Skin is weighted to node (%s) that "
  924. "does not exist in this shape", name);
  925. return false;
  926. }
  927. }
  928. TSSkinMesh *skin = dynamic_cast<TSSkinMesh*>(mesh);
  929. // Remap node indices
  930. skin->batchData.nodeIndex = srcSkin->batchData.nodeIndex;
  931. for (S32 i = 0; i < skin->batchData.nodeIndex.size(); i++)
  932. skin->batchData.nodeIndex[i] = nodeMap[skin->batchData.nodeIndex[i]];
  933. }
  934. // Add the copied mesh to the shape
  935. if (!addMesh(mesh, meshName))
  936. {
  937. delete mesh;
  938. return false;
  939. }
  940. // Copy materials used by the source mesh (only if from a different shape)
  941. if (srcShape != this)
  942. {
  943. for (S32 i = 0; i < mesh->mPrimitives.size(); i++)
  944. {
  945. if (!(mesh->mPrimitives[i].matIndex & TSDrawPrimitive::NoMaterial))
  946. {
  947. S32 drawType = (mesh->mPrimitives[i].matIndex & (~TSDrawPrimitive::MaterialMask));
  948. S32 srcMatIndex = mesh->mPrimitives[i].matIndex & TSDrawPrimitive::MaterialMask;
  949. const String& matName = srcShape->materialList->getMaterialName(srcMatIndex);
  950. // Add the material if it does not already exist
  951. S32 destMatIndex = materialList->getMaterialNameList().find_next(matName);
  952. if (destMatIndex < 0)
  953. {
  954. destMatIndex = materialList->size();
  955. materialList->push_back(matName, srcShape->materialList->getFlags(srcMatIndex));
  956. }
  957. mesh->mPrimitives[i].matIndex = drawType | destMatIndex;
  958. }
  959. }
  960. }
  961. return true;
  962. }
  963. bool TSShape::setMeshSize(const String& meshName, S32 size)
  964. {
  965. S32 objIndex, meshIndex;
  966. if (!findMeshIndex(meshName, objIndex, meshIndex) ||
  967. !meshes[objects[objIndex].startMeshIndex + meshIndex])
  968. {
  969. Con::errorf("TSShape::setMeshSize: Could not find mesh '%s'", meshName.c_str());
  970. return false;
  971. }
  972. // Need to make everything editable since node indexes etc will change
  973. makeEditable();
  974. // Remove the mesh from the object, but don't destroy it
  975. TSShape::Object& obj = objects[objIndex];
  976. TSMesh* mesh = meshes[obj.startMeshIndex + meshIndex];
  977. removeMeshFromObject(objIndex, meshIndex);
  978. // Add the mesh back at the new position
  979. addMesh(mesh, avar("%s %d", getName(obj.nameIndex).c_str(), size));
  980. // Update smallest visible detail
  981. updateSmallestVisibleDL();
  982. initObjects();
  983. return true;
  984. }
  985. bool TSShape::removeMesh(const String& meshName)
  986. {
  987. S32 objIndex, meshIndex;
  988. if (!findMeshIndex(meshName, objIndex, meshIndex) ||
  989. !meshes[objects[objIndex].startMeshIndex + meshIndex])
  990. {
  991. Con::errorf("TSShape::removeMesh: Could not find mesh '%s'", meshName.c_str());
  992. return false;
  993. }
  994. // Need to make everything editable since node indexes etc will change
  995. makeEditable();
  996. // Destroy and remove the mesh
  997. TSShape::Object& obj = objects[objIndex];
  998. destructInPlace(meshes[obj.startMeshIndex + meshIndex]);
  999. removeMeshFromObject(objIndex, meshIndex);
  1000. // Remove the object if there are no meshes left
  1001. if (!obj.numMeshes)
  1002. removeObject(getName(obj.nameIndex));
  1003. // Update smallest visible detail
  1004. updateSmallestVisibleDL();
  1005. initObjects();
  1006. return true;
  1007. }
  1008. //-----------------------------------------------------------------------------
  1009. // Helper function for dealing with some of the Vectors used in a TSShape. 'meshes'
  1010. // for example contains a TSMesh* per-object, per-detail-level, with NULLs for
  1011. // undefined details for each object. Trailing NULLs are not added to the Vector,
  1012. // so you end up with a different number of pointers for each object, depending
  1013. // on which detail levels it defines. This makes it tricky to move meshes around
  1014. // since you have to know how many elements belong to each object.
  1015. // To simplify things, this function pads the Vector up to a certain length (so
  1016. // all objects can appear to have the same number of meshes), the moves a single
  1017. // element to a new index, then trims trailing NULLs again.
  1018. template<class T>
  1019. static void _PadMoveAndTrim(Vector<T*>& vec, S32 offset, S32 count,
  1020. S32 padLength, S32 oldIndex, S32 newIndex)
  1021. {
  1022. // Pad the array with NULLs
  1023. for ( S32 i = count; i < padLength; ++i )
  1024. vec.insert( offset + count, NULL );
  1025. // Move the element from the old to the new index
  1026. T* tmp = vec[offset + oldIndex];
  1027. vec.erase( offset + oldIndex );
  1028. vec.insert( offset + newIndex, tmp );
  1029. // Trim trailing NULLs from the vector
  1030. for ( S32 i = padLength - 1; i >= 0; --i )
  1031. {
  1032. if ( vec[offset + i] )
  1033. break;
  1034. else
  1035. vec.erase( offset + i );
  1036. }
  1037. }
  1038. S32 TSShape::setDetailSize(S32 oldSize, S32 newSize)
  1039. {
  1040. S32 oldIndex = findDetailBySize( oldSize );
  1041. if ( oldIndex < 0 )
  1042. {
  1043. Con::errorf( "TSShape::setDetailSize: Cannot find detail with size %d", oldSize );
  1044. return -1;
  1045. }
  1046. // Remove this detail from the list
  1047. TSShape::Detail tmpDetail = details[oldIndex];
  1048. tmpDetail.size = newSize;
  1049. details.erase(oldIndex);
  1050. // Determine the new position for the detail (details are sorted by size)
  1051. S32 newIndex = 0;
  1052. for ( newIndex = 0; newIndex < details.size(); ++newIndex )
  1053. {
  1054. if ( newSize > details[newIndex].size )
  1055. break;
  1056. }
  1057. // Add the detail at its new position
  1058. details.insert( newIndex, tmpDetail );
  1059. // Rename the detail so its trailing size value is correct
  1060. {
  1061. S32 tmp;
  1062. String oldName( getName( tmpDetail.nameIndex ) );
  1063. String newName( String::GetTrailingNumber( oldName, tmp ) );
  1064. newName += String::ToString( "%d", newSize );
  1065. renameDetail(oldName, newName);
  1066. }
  1067. if ( newIndex != oldIndex )
  1068. {
  1069. // Fixup details
  1070. for ( S32 iDet = 0; iDet < details.size(); iDet++ )
  1071. {
  1072. if ( details[iDet].subShapeNum < 0 )
  1073. {
  1074. if ( details[iDet].bbDetailLevel == oldIndex )
  1075. details[iDet].bbDetailLevel = newIndex;
  1076. }
  1077. else
  1078. {
  1079. details[iDet].objectDetailNum = iDet;
  1080. }
  1081. }
  1082. // Fixup Billboard details
  1083. _PadMoveAndTrim( billboardDetails, 0, billboardDetails.size(),
  1084. details.size(), oldIndex, newIndex );
  1085. // Now move the mesh for each object in the subshape (adding and removing
  1086. // NULLs as appropriate)
  1087. for ( S32 iObj = 0; iObj < objects.size(); ++iObj )
  1088. {
  1089. TSShape::Object& obj = objects[iObj];
  1090. S32 oldMeshCount = meshes.size();
  1091. _PadMoveAndTrim( meshes, obj.startMeshIndex, obj.numMeshes,
  1092. details.size(), oldIndex, newIndex );
  1093. obj.numMeshes += ( meshes.size() - oldMeshCount );
  1094. // Fixup startMeshIndex for remaining objects
  1095. for ( S32 j = iObj + 1; j < objects.size(); ++j )
  1096. objects[j].startMeshIndex += ( meshes.size() - oldMeshCount );
  1097. }
  1098. }
  1099. // Update smallest visible detail
  1100. updateSmallestVisibleDL();
  1101. // Nothing major, just reint object lists
  1102. initObjects();
  1103. return newIndex;
  1104. }
  1105. bool TSShape::removeDetail( S32 size )
  1106. {
  1107. S32 dl = findDetailBySize( size );
  1108. if ( ( dl < 0 ) || ( dl >= details.size() ) )
  1109. {
  1110. Con::errorf( "TSShape::removeDetail: Invalid detail index (%d)", dl );
  1111. return false;
  1112. }
  1113. // Need to make everything editable since node indexes etc will change
  1114. makeEditable();
  1115. // Destroy and remove each mesh in the detail level
  1116. for ( S32 objIndex = objects.size()-1; objIndex >= 0; objIndex-- )
  1117. {
  1118. TSShape::Object& obj = objects[objIndex];
  1119. if ( dl < obj.numMeshes )
  1120. {
  1121. if ( meshes[obj.startMeshIndex + dl] )
  1122. destructInPlace( meshes[obj.startMeshIndex + dl] );
  1123. removeMeshFromObject(objIndex, dl);
  1124. // Remove the object if there are no meshes left
  1125. if (!obj.numMeshes)
  1126. removeObject( getName( obj.nameIndex ) );
  1127. }
  1128. }
  1129. // Destroy billboard detail level
  1130. if ( dl < billboardDetails.size() )
  1131. {
  1132. if ( billboardDetails[dl] )
  1133. {
  1134. // Delete old textures
  1135. billboardDetails[dl]->deleteImposterCacheTextures();
  1136. delete billboardDetails[dl];
  1137. }
  1138. billboardDetails.erase( dl );
  1139. }
  1140. // Update smallest visible detail
  1141. updateSmallestVisibleDL();
  1142. initObjects();
  1143. return true;
  1144. }
  1145. bool TSShape::isShapeFileType(Torque::Path filePath)
  1146. {
  1147. String fileExt = filePath.getExtension();
  1148. if (
  1149. fileExt.equal("dts", String::NoCase) ||
  1150. fileExt.equal("dsq", String::NoCase) ||
  1151. fileExt.equal("dae", String::NoCase) ||
  1152. fileExt.equal("fbx", String::NoCase) ||
  1153. fileExt.equal("blend", String::NoCase) ||
  1154. fileExt.equal("obj", String::NoCase) ||
  1155. fileExt.equal("gltf", String::NoCase) ||
  1156. fileExt.equal("glb", String::NoCase)
  1157. )
  1158. return true;
  1159. return false;
  1160. }
  1161. //-----------------------------------------------------------------------------
  1162. bool TSShape::addSequence(const Torque::Path& path, const String& assetId, const String& fromSeq,
  1163. const String& name, S32 startFrame, S32 endFrame,
  1164. bool padRotKeys, bool padTransKeys)
  1165. {
  1166. String oldName(fromSeq);
  1167. if (path.getExtension().equal("dsq", String::NoCase))
  1168. {
  1169. S32 oldSeqCount = sequences.size();
  1170. // DSQ source file
  1171. char filenameBuf[1024];
  1172. Con::expandScriptFilename(filenameBuf, sizeof(filenameBuf), path.getFullPath().c_str());
  1173. FileStream *f;
  1174. if((f = FileStream::createAndOpen( filenameBuf, Torque::FS::File::Read )) == NULL)
  1175. {
  1176. Con::errorf("TSShape::addSequence: Could not load DSQ file '%s'", filenameBuf);
  1177. return false;
  1178. }
  1179. if (!importSequences(f, filenameBuf) || (f->getStatus() != Stream::Ok))
  1180. {
  1181. delete f;
  1182. Con::errorf("TSShape::addSequence: Load sequence file '%s' failed", filenameBuf);
  1183. return false;
  1184. }
  1185. delete f;
  1186. // Rename the new sequence if required (avoid rename if name is not
  1187. // unique (this will be fixed up later, and we don't need 2 errors about it!)
  1188. if (oldName.isEmpty())
  1189. oldName = getName(sequences.last().nameIndex);
  1190. if (!oldName.equal(name))
  1191. {
  1192. if (findSequence(name) == -1)
  1193. {
  1194. // Use a dummy intermediate name since we might be renaming from an
  1195. // existing name (and we want to rename the right sequence!)
  1196. sequences.last().nameIndex = addName("__dummy__");
  1197. renameSequence("__dummy__", name);
  1198. }
  1199. }
  1200. // Check that sequences have unique names
  1201. bool lastSequenceRejected = false;
  1202. for (S32 i = sequences.size()-1; i >= oldSeqCount; i--)
  1203. {
  1204. S32 nameIndex = (i == sequences.size()-1) ? findName(name) : sequences[i].nameIndex;
  1205. S32 seqIndex = findSequence(nameIndex);
  1206. if ((seqIndex != -1) && (seqIndex != i))
  1207. {
  1208. Con::errorf("TSShape::addSequence: Failed to add sequence '%s' "
  1209. "(name already exists)", getName(nameIndex).c_str());
  1210. sequences[i].nameIndex = addName("__dummy__");
  1211. removeSequence("__dummy__");
  1212. if (i == sequences.size())
  1213. lastSequenceRejected = true;
  1214. }
  1215. }
  1216. // @todo:Need to remove keyframes if start!=0 and end!=-1
  1217. TSShape::Sequence& seq = sequences.last();
  1218. // Store information about how this sequence was created
  1219. seq.sourceData.from = String::ToString("%s\t%s", filenameBuf, name.c_str());
  1220. seq.sourceData.total = seq.numKeyframes;
  1221. seq.sourceData.start = ((startFrame < 0) || (startFrame >= seq.numKeyframes)) ? 0 : startFrame;
  1222. seq.sourceData.end = ((endFrame < 0) || (endFrame >= seq.numKeyframes)) ? seq.numKeyframes-1 : endFrame;
  1223. return (sequences.size() != oldSeqCount);
  1224. }
  1225. /* Check that sequence to be added does not already exist */
  1226. if (findSequence(name) != -1)
  1227. {
  1228. Con::errorf("TSShape::addSequence: Cannot add sequence '%s' (name already exists)", name.c_str());
  1229. return false;
  1230. }
  1231. Resource<TSShape> hSrcShape;
  1232. TSShape* srcShape = this; // Assume we are copying an existing sequence
  1233. if (isShapeFileType(path))
  1234. {
  1235. // DTS or DAE source file
  1236. char filenameBuf[1024];
  1237. Con::expandScriptFilename(filenameBuf, sizeof(filenameBuf), path.getFullPath().c_str());
  1238. hSrcShape = ResourceManager::get().load(filenameBuf);
  1239. if (!bool(hSrcShape))
  1240. {
  1241. Con::errorf("TSShape::addSequence: Could not load source shape '%s'", path.getFullPath().c_str());
  1242. return false;
  1243. }
  1244. srcShape = const_cast<TSShape*>((const TSShape*)hSrcShape);
  1245. if (!srcShape->sequences.size())
  1246. {
  1247. Con::errorf("TSShape::addSequence: Source shape '%s' does not contain any sequences", path.getFullPath().c_str());
  1248. return false;
  1249. }
  1250. // If no sequence name is specified, just use the first one
  1251. if (oldName.isEmpty())
  1252. oldName = srcShape->getName(srcShape->sequences[0].nameIndex);
  1253. }
  1254. else
  1255. {
  1256. // Source is an existing sequence
  1257. oldName = path.getFullPath();
  1258. }
  1259. // Find the sequence
  1260. S32 seqIndex = srcShape->findSequence(oldName);
  1261. if (seqIndex < 0)
  1262. {
  1263. Con::errorf("TSShape::addSequence (%s): Could not find sequence named '%s'", path.getFullPath().c_str(), oldName.c_str());
  1264. return false;
  1265. }
  1266. // Check keyframe range
  1267. const TSShape::Sequence* srcSeq = &srcShape->sequences[seqIndex];
  1268. if ((startFrame < 0) || (startFrame >= srcSeq->numKeyframes))
  1269. {
  1270. Con::warnf("TSShape::addSequence (%s): Start keyframe (%d) out of range (0-%d) for sequence '%s'",
  1271. path.getFullPath().c_str(), startFrame, srcSeq->numKeyframes-1, oldName.c_str());
  1272. startFrame = 0;
  1273. }
  1274. if (endFrame < 0)
  1275. endFrame = srcSeq->numKeyframes - 1;
  1276. else if (endFrame >= srcSeq->numKeyframes)
  1277. {
  1278. Con::warnf("TSShape::addSequence (%s): End keyframe (%d) out of range (0-%d) for sequence '%s'",
  1279. path.getFullPath().c_str(), endFrame, srcSeq->numKeyframes-1, oldName.c_str());
  1280. endFrame = srcSeq->numKeyframes - 1;
  1281. }
  1282. // Create array to map source nodes to our nodes
  1283. Vector<S32> nodeMap(srcShape->nodes.size());
  1284. for (S32 i = 0; i < srcShape->nodes.size(); i++)
  1285. nodeMap.push_back(findNode(srcShape->getName(srcShape->nodes[i].nameIndex)));
  1286. // Create array to map source objects to our objects
  1287. Vector<S32> objectMap(srcShape->objects.size());
  1288. for (S32 i = 0; i < srcShape->objects.size(); i++)
  1289. objectMap.push_back(findObject(srcShape->getName(srcShape->objects[i].nameIndex)));
  1290. // Copy the source sequence (need to do it this ugly way instead of just
  1291. // using push_back since srcSeq pointer may change if copying a sequence
  1292. // from inside the shape itself
  1293. sequences.increment();
  1294. TSShape::Sequence& seq = sequences.last();
  1295. srcSeq = &srcShape->sequences[seqIndex]; // update pointer as it may have changed!
  1296. seq = *srcSeq;
  1297. seq.nameIndex = addName(name);
  1298. seq.numKeyframes = endFrame - startFrame + 1;
  1299. if (seq.duration > 0)
  1300. seq.duration *= ((F32)seq.numKeyframes / srcSeq->numKeyframes);
  1301. // Add object states
  1302. // Note: only visibility animation is supported
  1303. seq.frameMatters.clearAll();
  1304. seq.matFrameMatters.clearAll();
  1305. seq.visMatters.clearAll();
  1306. for (S32 i = 0; i < objectMap.size(); i++)
  1307. {
  1308. if (objectMap[i] < 0)
  1309. continue;
  1310. if (srcSeq->visMatters.test(i))
  1311. {
  1312. // Check if visibility is animated within the frames to be copied
  1313. const F32 defaultVis = srcShape->objectStates[i].vis;
  1314. S32 objNum = srcSeq->visMatters.count(i);
  1315. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1316. {
  1317. if (srcShape->getObjectState(*srcSeq, iFrame, objNum).vis != defaultVis)
  1318. {
  1319. seq.visMatters.set(objectMap[i]);
  1320. break;
  1321. }
  1322. }
  1323. }
  1324. }
  1325. TSIntegerSet srcObjectStateSet(srcSeq->frameMatters);
  1326. srcObjectStateSet.overlap(srcSeq->matFrameMatters);
  1327. srcObjectStateSet.overlap(srcSeq->visMatters);
  1328. TSIntegerSet objectStateSet(seq.frameMatters);
  1329. objectStateSet.overlap(seq.matFrameMatters);
  1330. objectStateSet.overlap(seq.visMatters);
  1331. seq.baseObjectState = objectStates.size();
  1332. objectStates.increment(objectStateSet.count()*seq.numKeyframes);
  1333. for (S32 i = 0; i < objectMap.size(); i++)
  1334. {
  1335. if (objectMap[i] < 0)
  1336. continue;
  1337. // Note: only visibility animation is supported
  1338. if (objectStateSet.test(objectMap[i]))
  1339. {
  1340. S32 src = srcSeq->baseObjectState + srcSeq->numKeyframes * srcObjectStateSet.count(i) + startFrame;
  1341. S32 dest = seq.baseObjectState + seq.numKeyframes * objectStateSet.count(objectMap[i]);
  1342. dCopyArray(&objectStates[dest], &srcShape->objectStates[src], seq.numKeyframes);
  1343. }
  1344. }
  1345. // Add ground frames
  1346. F32 ratio = (F32)seq.numKeyframes / srcSeq->numKeyframes;
  1347. S32 groundBase = srcSeq->firstGroundFrame + startFrame*ratio;
  1348. seq.numGroundFrames *= ratio;
  1349. seq.firstGroundFrame = groundTranslations.size();
  1350. groundTranslations.reserve(mMin(groundTranslations.size() + seq.numGroundFrames, srcShape->groundTranslations.size()));
  1351. groundRotations.reserve(mMin(groundRotations.size() + seq.numGroundFrames, srcShape->groundRotations.size()));
  1352. for (S32 i = 0; i < seq.numGroundFrames; i++)
  1353. {
  1354. S32 offset = groundBase + i;
  1355. if (offset >= srcShape->groundTranslations.size())
  1356. {
  1357. Con::errorf("%s groundTranslations out of bounds! [%i/%i] ", path.getFullPath().c_str(), groundBase + i, srcShape->groundTranslations.size());
  1358. offset = srcShape->groundTranslations.size() - 1;
  1359. }
  1360. const Point3F pointValueToCopy = srcShape->groundTranslations[offset];
  1361. groundTranslations.push_back(pointValueToCopy);
  1362. S32 offset2 = groundBase + i;
  1363. if (offset2 >= srcShape->groundRotations.size())
  1364. {
  1365. Con::errorf("%s groundRotations out of bounds! [%i/%i] ", path.getFullPath().c_str(), groundBase + i, srcShape->groundRotations.size());
  1366. offset2 = srcShape->groundRotations.size() - 1;
  1367. }
  1368. const Quat16 quatValueToCopy = srcShape->groundRotations[offset2];
  1369. groundRotations.push_back(quatValueToCopy);
  1370. }
  1371. // Add triggers
  1372. seq.numTriggers = 0;
  1373. seq.firstTrigger = triggers.size();
  1374. F32 seqStartPos = (F32)startFrame / seq.numKeyframes;
  1375. F32 seqEndPos = (F32)endFrame / seq.numKeyframes;
  1376. for (S32 i = 0; i < srcSeq->numTriggers; i++)
  1377. {
  1378. const TSShape::Trigger& srcTrig = srcShape->triggers[srcSeq->firstTrigger + i];
  1379. if ((srcTrig.pos >= seqStartPos) && (srcTrig.pos <= seqEndPos))
  1380. {
  1381. triggers.push_back(srcTrig);
  1382. triggers.last().pos -= seqStartPos;
  1383. seq.numTriggers++;
  1384. }
  1385. }
  1386. // Fixup node matters arrays
  1387. seq.translationMatters.clearAll();
  1388. seq.rotationMatters.clearAll();
  1389. seq.scaleMatters.clearAll();
  1390. for (S32 i = 0; i < nodeMap.size(); i++)
  1391. {
  1392. if (nodeMap[i] < 0)
  1393. continue;
  1394. if (srcSeq->translationMatters.test(i))
  1395. {
  1396. // Check if node position is animated within the frames to be copied
  1397. const Point3F& defaultTrans = srcShape->defaultTranslations[i];
  1398. S32 tranNum = srcSeq->translationMatters.count(i);
  1399. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1400. {
  1401. if (srcShape->getTranslation(*srcSeq, iFrame, tranNum) != defaultTrans)
  1402. {
  1403. seq.translationMatters.set(nodeMap[i]);
  1404. break;
  1405. }
  1406. }
  1407. }
  1408. if (srcSeq->rotationMatters.test(i))
  1409. {
  1410. // Check if node rotation is animated within the frames to be copied
  1411. const QuatF defaultRot = srcShape->defaultRotations[i].getQuatF();
  1412. S32 rotNum = srcSeq->rotationMatters.count(i);
  1413. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1414. {
  1415. QuatF temp;
  1416. if (srcShape->getRotation(*srcSeq, iFrame, rotNum, &temp) != defaultRot)
  1417. {
  1418. seq.rotationMatters.set(nodeMap[i]);
  1419. break;
  1420. }
  1421. }
  1422. }
  1423. if (srcSeq->scaleMatters.test(i))
  1424. {
  1425. S32 scaleNum = srcSeq->scaleMatters.count(i);
  1426. // Check if node scale is animated within the frames to be copied
  1427. if (srcSeq->animatesArbitraryScale())
  1428. {
  1429. TSScale defaultScale;
  1430. defaultScale.identity();
  1431. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1432. {
  1433. TSScale temp;
  1434. if (!(srcShape->getArbitraryScale(*srcSeq, iFrame, scaleNum, &temp) == defaultScale))
  1435. {
  1436. seq.scaleMatters.set(nodeMap[i]);
  1437. break;
  1438. }
  1439. }
  1440. }
  1441. else if (srcSeq->animatesAlignedScale())
  1442. {
  1443. const Point3F defaultScale(Point3F::One);
  1444. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1445. {
  1446. if (srcShape->getAlignedScale(*srcSeq, iFrame, scaleNum) != defaultScale)
  1447. {
  1448. seq.scaleMatters.set(nodeMap[i]);
  1449. break;
  1450. }
  1451. }
  1452. }
  1453. else if (srcSeq->animatesUniformScale())
  1454. {
  1455. const F32 defaultScale = 1.0f;
  1456. for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++)
  1457. {
  1458. if (srcShape->getUniformScale(*srcSeq, iFrame, scaleNum) != defaultScale)
  1459. {
  1460. seq.scaleMatters.set(nodeMap[i]);
  1461. break;
  1462. }
  1463. }
  1464. }
  1465. }
  1466. }
  1467. // Resize the node transform arrays
  1468. seq.baseTranslation = nodeTranslations.size();
  1469. nodeTranslations.increment(seq.translationMatters.count()*seq.numKeyframes);
  1470. seq.baseRotation = nodeRotations.size();
  1471. nodeRotations.increment(seq.rotationMatters.count()*seq.numKeyframes);
  1472. if (seq.flags & TSShape::ArbitraryScale)
  1473. {
  1474. S32 scaleCount = seq.scaleMatters.count();
  1475. seq.baseScale = nodeArbitraryScaleRots.size();
  1476. nodeArbitraryScaleRots.increment(scaleCount*seq.numKeyframes);
  1477. nodeArbitraryScaleFactors.increment(scaleCount*seq.numKeyframes);
  1478. }
  1479. else if (seq.flags & TSShape::AlignedScale)
  1480. {
  1481. seq.baseScale = nodeAlignedScales.size();
  1482. nodeAlignedScales.increment(seq.scaleMatters.count()*seq.numKeyframes);
  1483. }
  1484. else
  1485. {
  1486. seq.baseScale = nodeUniformScales.size();
  1487. nodeUniformScales.increment(seq.scaleMatters.count()*seq.numKeyframes);
  1488. }
  1489. // Add node transforms (remap from source node indices to our node indices). As
  1490. // well as copying animated node translations and rotations, also handle when the
  1491. // default translation and rotation are different between the source and
  1492. // destination shapes.
  1493. for (S32 i = 0; i < nodeMap.size(); i++)
  1494. {
  1495. if (nodeMap[i] < 0)
  1496. continue;
  1497. if (seq.translationMatters.test(nodeMap[i]))
  1498. {
  1499. S32 src = srcSeq->baseTranslation + srcSeq->numKeyframes * srcSeq->translationMatters.count(i) + startFrame;
  1500. S32 dest = seq.baseTranslation + seq.numKeyframes * seq.translationMatters.count(nodeMap[i]);
  1501. dCopyArray(&nodeTranslations[dest], &srcShape->nodeTranslations[src], seq.numKeyframes);
  1502. }
  1503. else if (padTransKeys && (defaultTranslations[nodeMap[i]] != srcShape->defaultTranslations[i]))
  1504. {
  1505. seq.translationMatters.set(nodeMap[i]);
  1506. S32 dest = seq.baseTranslation + seq.numKeyframes * seq.translationMatters.count(nodeMap[i]);
  1507. for (S32 j = 0; j < seq.numKeyframes; j++)
  1508. nodeTranslations.insert(dest, srcShape->defaultTranslations[i]);
  1509. }
  1510. if (seq.rotationMatters.test(nodeMap[i]))
  1511. {
  1512. S32 src = srcSeq->baseRotation + srcSeq->numKeyframes * srcSeq->rotationMatters.count(i) + startFrame;
  1513. S32 dest = seq.baseRotation + seq.numKeyframes * seq.rotationMatters.count(nodeMap[i]);
  1514. dCopyArray(&nodeRotations[dest], &srcShape->nodeRotations[src], seq.numKeyframes);
  1515. }
  1516. else if (padRotKeys && (defaultRotations[nodeMap[i]] != srcShape->defaultRotations[i]))
  1517. {
  1518. seq.rotationMatters.set(nodeMap[i]);
  1519. S32 dest = seq.baseRotation + seq.numKeyframes * seq.rotationMatters.count(nodeMap[i]);
  1520. for (S32 j = 0; j < seq.numKeyframes; j++)
  1521. nodeRotations.insert(dest, srcShape->defaultRotations[i]);
  1522. }
  1523. if (seq.scaleMatters.test(nodeMap[i]))
  1524. {
  1525. S32 src = srcSeq->baseScale + srcSeq->numKeyframes * srcSeq->scaleMatters.count(i)+ startFrame;
  1526. S32 dest = seq.baseScale + seq.numKeyframes * seq.scaleMatters.count(nodeMap[i]);
  1527. if (seq.flags & TSShape::ArbitraryScale)
  1528. {
  1529. dCopyArray(&nodeArbitraryScaleRots[dest], &srcShape->nodeArbitraryScaleRots[src], seq.numKeyframes);
  1530. dCopyArray(&nodeArbitraryScaleFactors[dest], &srcShape->nodeArbitraryScaleFactors[src], seq.numKeyframes);
  1531. }
  1532. else if (seq.flags & TSShape::AlignedScale)
  1533. dCopyArray(&nodeAlignedScales[dest], &srcShape->nodeAlignedScales[src], seq.numKeyframes);
  1534. else
  1535. dCopyArray(&nodeUniformScales[dest], &srcShape->nodeUniformScales[src], seq.numKeyframes);
  1536. }
  1537. }
  1538. // Set shape flags (only the most significant scale type)
  1539. U32 curVal = mFlags & AnyScale;
  1540. mFlags &= ~(AnyScale);
  1541. mFlags |= getMax(curVal, seq.flags & AnyScale); // take the larger value (can only convert upwards)
  1542. // Set sequence flags
  1543. seq.dirtyFlags = 0;
  1544. if (seq.rotationMatters.testAll() || seq.translationMatters.testAll() || seq.scaleMatters.testAll())
  1545. seq.dirtyFlags |= TSShapeInstance::TransformDirty;
  1546. if (seq.visMatters.testAll())
  1547. seq.dirtyFlags |= TSShapeInstance::VisDirty;
  1548. if (seq.frameMatters.testAll())
  1549. seq.dirtyFlags |= TSShapeInstance::FrameDirty;
  1550. if (seq.matFrameMatters.testAll())
  1551. seq.dirtyFlags |= TSShapeInstance::MatFrameDirty;
  1552. // Store information about how this sequence was created
  1553. String fromData = path.getFullPath();
  1554. if (assetId.isNotEmpty() && AssetDatabase.isDeclaredAsset(assetId.c_str()))
  1555. fromData = assetId;
  1556. seq.sourceData.from = String::ToString("%s\t%s", fromData.c_str(), oldName.c_str());
  1557. seq.sourceData.total = srcSeq->numKeyframes;
  1558. seq.sourceData.start = startFrame;
  1559. seq.sourceData.end = endFrame;
  1560. return true;
  1561. }
  1562. bool TSShape::removeSequence(const String& name)
  1563. {
  1564. // Find the sequence to be removed
  1565. S32 seqIndex = findSequence(name);
  1566. if (seqIndex < 0)
  1567. {
  1568. Con::errorf("TSShape::removeSequence: Could not find sequence '%s'", name.c_str());
  1569. return false;
  1570. }
  1571. TSShape::Sequence& seq = sequences[seqIndex];
  1572. // Remove the node transforms for this sequence
  1573. S32 transCount = eraseStates(nodeTranslations, seq.translationMatters, seq.baseTranslation, seq.numKeyframes);
  1574. S32 rotCount = eraseStates(nodeRotations, seq.rotationMatters, seq.baseRotation, seq.numKeyframes);
  1575. S32 scaleCount = 0;
  1576. if (seq.flags & TSShape::ArbitraryScale)
  1577. {
  1578. scaleCount = eraseStates(nodeArbitraryScaleRots, seq.scaleMatters, seq.baseScale, seq.numKeyframes);
  1579. eraseStates(nodeArbitraryScaleFactors, seq.scaleMatters, seq.baseScale, seq.numKeyframes);
  1580. }
  1581. else if (seq.flags & TSShape::AlignedScale)
  1582. scaleCount = eraseStates(nodeAlignedScales, seq.scaleMatters, seq.baseScale, seq.numKeyframes);
  1583. else
  1584. scaleCount = eraseStates(nodeUniformScales, seq.scaleMatters, seq.baseScale, seq.numKeyframes);
  1585. // Remove the object states for this sequence
  1586. TSIntegerSet objMatters(seq.frameMatters);
  1587. objMatters.overlap(seq.matFrameMatters);
  1588. objMatters.overlap(seq.visMatters);
  1589. S32 objCount = eraseStates(objectStates, objMatters, seq.baseObjectState, seq.numKeyframes);
  1590. // Remove groundframes and triggers
  1591. TSIntegerSet dummy;
  1592. eraseStates(groundTranslations, dummy, seq.firstGroundFrame, seq.numGroundFrames, 0);
  1593. eraseStates(groundRotations, dummy, seq.firstGroundFrame, seq.numGroundFrames, 0);
  1594. eraseStates(triggers, dummy, seq.firstTrigger, seq.numTriggers, 0);
  1595. // Fixup the base indices of the other sequences
  1596. for (S32 i = seqIndex + 1; i < sequences.size(); i++)
  1597. {
  1598. sequences[i].baseTranslation -= transCount;
  1599. sequences[i].baseRotation -= rotCount;
  1600. sequences[i].baseScale -= scaleCount;
  1601. sequences[i].baseObjectState -= objCount;
  1602. sequences[i].firstGroundFrame -= seq.numGroundFrames;
  1603. sequences[i].firstTrigger -= seq.numTriggers;
  1604. }
  1605. // Remove the sequence itself
  1606. sequences.erase(seqIndex);
  1607. // Remove the sequence name if it is no longer in use
  1608. removeName(name);
  1609. return true;
  1610. }
  1611. //-----------------------------------------------------------------------------
  1612. bool TSShape::addTrigger(const String& seqName, S32 keyframe, S32 state)
  1613. {
  1614. // Find the sequence
  1615. S32 seqIndex = findSequence(seqName);
  1616. if (seqIndex < 0)
  1617. {
  1618. Con::errorf("TSShape::addTrigger: Could not find sequence '%s'", seqName.c_str());
  1619. return false;
  1620. }
  1621. TSShape::Sequence& seq = sequences[seqIndex];
  1622. if (keyframe >= seq.numKeyframes)
  1623. {
  1624. Con::errorf("TSShape::addTrigger: Keyframe out of range (0-%d for sequence '%s')",
  1625. seq.numKeyframes-1, seqName.c_str());
  1626. return false;
  1627. }
  1628. // Encode the trigger state
  1629. if (state < 0)
  1630. state = 1 << (-state-1);
  1631. else if (state > 0)
  1632. state = (1 << (state-1)) | TSShape::Trigger::StateOn;
  1633. // Fixup seq.firstTrigger if this sequence does not have any triggers yet
  1634. if (seq.numTriggers == 0)
  1635. {
  1636. seq.firstTrigger = 0;
  1637. for (S32 i = 0; i < seqIndex; i++)
  1638. seq.firstTrigger += sequences[i].numTriggers;
  1639. }
  1640. // Find where to insert the trigger (sorted by keyframe)
  1641. S32 trigIndex;
  1642. for (trigIndex = seq.firstTrigger; trigIndex < (seq.firstTrigger + seq.numTriggers); trigIndex++)
  1643. {
  1644. const TSShape::Trigger& trig = triggers[trigIndex];
  1645. if ((S32)(trig.pos * seq.numKeyframes) > keyframe)
  1646. break;
  1647. }
  1648. // Create the new trigger
  1649. TSShape::Trigger trig;
  1650. trig.pos = (F32)keyframe / getMax(1, seq.numKeyframes-1);
  1651. trig.state = state;
  1652. triggers.insert(trigIndex, trig);
  1653. seq.numTriggers++;
  1654. // set invert for other triggers if needed
  1655. if ((trig.state & TSShape::Trigger::StateOn) == 0)
  1656. {
  1657. U32 offTrigger = (trig.state & TSShape::Trigger::StateMask);
  1658. for (S32 i = 0; i < seq.numTriggers; i++)
  1659. {
  1660. if (triggers[seq.firstTrigger + i].state & offTrigger)
  1661. triggers[seq.firstTrigger + i].state |= TSShape::Trigger::InvertOnReverse;
  1662. }
  1663. }
  1664. // fixup firstTrigger index for other sequences
  1665. for (S32 i = seqIndex + 1; i < sequences.size(); i++)
  1666. {
  1667. if (sequences[i].numTriggers > 0)
  1668. sequences[i].firstTrigger++;
  1669. }
  1670. // set MakePath flag so triggers will be animated
  1671. seq.flags |= TSShape::MakePath;
  1672. return true;
  1673. }
  1674. bool TSShape::removeTrigger(const String& seqName, S32 keyframe, S32 state)
  1675. {
  1676. // Find the sequence
  1677. S32 seqIndex = findSequence(seqName);
  1678. if (seqIndex < 0)
  1679. {
  1680. Con::errorf("TSShape::removeTrigger: Could not find sequence '%s'", seqName.c_str());
  1681. return false;
  1682. }
  1683. TSShape::Sequence& seq = sequences[seqIndex];
  1684. if (keyframe >= seq.numKeyframes)
  1685. {
  1686. Con::errorf("TSShape::removeTrigger: Keyframe out of range (0-%d for sequence '%s')",
  1687. seq.numKeyframes-1, seqName.c_str());
  1688. return false;
  1689. }
  1690. // Encode the trigger state
  1691. if (state < 0)
  1692. state = 1 << (-state-1);
  1693. else if (state > 0)
  1694. state = (1 << (state-1)) | TSShape::Trigger::StateOn;
  1695. // Find and remove the trigger
  1696. for (S32 trigIndex = seq.firstTrigger; trigIndex < (seq.firstTrigger + seq.numTriggers); trigIndex++)
  1697. {
  1698. TSShape::Trigger& trig = triggers[trigIndex];
  1699. S32 cmpFrame = (S32)(trig.pos * (seq.numKeyframes-1) + 0.5f);
  1700. S32 cmpState = trig.state & (~TSShape::Trigger::InvertOnReverse);
  1701. if ((cmpFrame == keyframe) && (cmpState == state))
  1702. {
  1703. triggers.erase(trigIndex);
  1704. seq.numTriggers--;
  1705. // Fix up firstTrigger for other sequences
  1706. for (S32 i = seqIndex + 1; i < sequences.size(); i++)
  1707. {
  1708. if (sequences[i].numTriggers > 0)
  1709. sequences[i].firstTrigger--;
  1710. }
  1711. // Clear MakePath flag if no more triggers
  1712. if ( seq.numTriggers == 0 )
  1713. seq.flags &= (~TSShape::MakePath);
  1714. return true;
  1715. }
  1716. }
  1717. Con::errorf("TSShape::removeTrigger: Could not find trigger (%d, %d) for sequence '%s'",
  1718. keyframe, state, seqName.c_str());
  1719. return false;
  1720. }
  1721. void TSShape::getNodeKeyframe(S32 nodeIndex, const TSShape::Sequence& seq, S32 keyframe, MatrixF* mat) const
  1722. {
  1723. // Get the node rotation and translation
  1724. QuatF rot;
  1725. if (seq.rotationMatters.test(nodeIndex))
  1726. {
  1727. S32 index = seq.rotationMatters.count(nodeIndex) * seq.numKeyframes + keyframe;
  1728. nodeRotations[seq.baseRotation + index].getQuatF(&rot);
  1729. }
  1730. else
  1731. defaultRotations[nodeIndex].getQuatF(&rot);
  1732. Point3F trans;
  1733. if (seq.translationMatters.test(nodeIndex))
  1734. {
  1735. S32 index = seq.translationMatters.count(nodeIndex) * seq.numKeyframes + keyframe;
  1736. trans = nodeTranslations[seq.baseTranslation + index];
  1737. }
  1738. else
  1739. trans = defaultTranslations[nodeIndex];
  1740. // Set the keyframe matrix
  1741. rot.setMatrix(mat);
  1742. mat->setPosition(trans);
  1743. }
  1744. bool TSShape::setSequenceBlend(const String& seqName, bool blend, const String& blendRefSeqName, S32 blendRefFrame)
  1745. {
  1746. // Find the target sequence
  1747. S32 seqIndex = findSequence(seqName);
  1748. if (seqIndex < 0)
  1749. {
  1750. Con::errorf("TSShape::setSequenceBlend: Could not find sequence named '%s'", seqName.c_str());
  1751. return false;
  1752. }
  1753. TSShape::Sequence& seq = sequences[seqIndex];
  1754. // Ignore if blend flag is already correct
  1755. if (seq.isBlend() == blend)
  1756. return true;
  1757. // Find the sequence containing the reference frame
  1758. S32 blendRefSeqIndex = findSequence(blendRefSeqName);
  1759. if (blendRefSeqIndex < 0)
  1760. {
  1761. Con::errorf("TSShape::setSequenceBlend: Could not find reference sequence named '%s'", blendRefSeqName.c_str());
  1762. return false;
  1763. }
  1764. TSShape::Sequence& blendRefSeq = sequences[blendRefSeqIndex];
  1765. if ((blendRefFrame < 0) || (blendRefFrame >= blendRefSeq.numKeyframes))
  1766. {
  1767. Con::errorf("TSShape::setSequenceBlend: Reference frame out of range (0-%d)", blendRefSeq.numKeyframes-1);
  1768. return false;
  1769. }
  1770. // Set the new flag
  1771. if (blend)
  1772. seq.flags |= TSShape::Blend;
  1773. else
  1774. seq.flags &= (~TSShape::Blend);
  1775. // For each animated node in the target sequence, need to add or subtract the
  1776. // reference keyframe from each frame
  1777. TSIntegerSet nodeMatters(seq.rotationMatters);
  1778. nodeMatters.overlap(seq.translationMatters);
  1779. S32 end = nodeMatters.end();
  1780. for (S32 nodeIndex = nodeMatters.start(); nodeIndex < end; nodeMatters.next(nodeIndex))
  1781. {
  1782. MatrixF refMat;
  1783. getNodeKeyframe(nodeIndex, blendRefSeq, blendRefFrame, &refMat);
  1784. // Add or subtract the reference?
  1785. if (blend)
  1786. refMat.inverse();
  1787. bool updateRot(false), updateTrans(false);
  1788. S32 rotOffset(0), transOffset(0);
  1789. if (seq.rotationMatters.test(nodeIndex))
  1790. {
  1791. updateRot = true;
  1792. rotOffset = seq.baseRotation + seq.rotationMatters.count(nodeIndex) * seq.numKeyframes;
  1793. }
  1794. if (seq.translationMatters.test(nodeIndex))
  1795. {
  1796. updateTrans = true;
  1797. transOffset = seq.baseTranslation + seq.translationMatters.count(nodeIndex) * seq.numKeyframes;
  1798. }
  1799. for (S32 frame = 0; frame < seq.numKeyframes; frame++)
  1800. {
  1801. MatrixF oldMat;
  1802. getNodeKeyframe(nodeIndex, seq, frame, &oldMat);
  1803. MatrixF newMat;
  1804. newMat.mul(refMat, oldMat);
  1805. if (updateRot)
  1806. nodeRotations[rotOffset + frame].set(QuatF(newMat));
  1807. if (updateTrans)
  1808. nodeTranslations[transOffset + frame] = newMat.getPosition();
  1809. }
  1810. }
  1811. // Update sequence blend information
  1812. seq.sourceData.blendSeq = blendRefSeqName;
  1813. seq.sourceData.blendFrame = blendRefFrame;
  1814. return true;
  1815. }
  1816. bool TSShape::setSequenceGroundSpeed(const String& seqName, const Point3F& trans, const Point3F& rot)
  1817. {
  1818. // Find the sequence
  1819. S32 seqIndex = findSequence(seqName);
  1820. if (seqIndex < 0)
  1821. {
  1822. Con::errorf("setSequenceGroundSpeed: Could not find sequence named '%s'", seqName.c_str());
  1823. return false;
  1824. }
  1825. TSShape::Sequence& seq = sequences[seqIndex];
  1826. // Determine how many ground-frames to generate (FPS=10, at least 1 frame)
  1827. const F32 groundFrameRate = 10.0f;
  1828. S32 numFrames = getMax(1, (S32)(seq.duration * groundFrameRate));
  1829. // Allocate space for the frames (add/delete frames as required)
  1830. S32 frameAdjust = numFrames - seq.numGroundFrames;
  1831. for (S32 i = 0; i < mAbs(frameAdjust); i++)
  1832. {
  1833. if (frameAdjust > 0)
  1834. {
  1835. groundTranslations.insert(seq.firstGroundFrame);
  1836. groundRotations.insert(seq.firstGroundFrame);
  1837. }
  1838. else
  1839. {
  1840. groundTranslations.erase(seq.firstGroundFrame);
  1841. groundRotations.erase(seq.firstGroundFrame);
  1842. }
  1843. }
  1844. // Fixup ground frame indices
  1845. seq.numGroundFrames += frameAdjust;
  1846. for (S32 i = seqIndex + 1; i < sequences.size(); i++)
  1847. sequences[i].firstGroundFrame += frameAdjust;
  1848. // Generate the ground-frames
  1849. Point3F adjTrans = trans;
  1850. Point3F adjRot = rot;
  1851. if (seq.numGroundFrames > 0)
  1852. {
  1853. adjTrans /= seq.numGroundFrames;
  1854. adjRot /= seq.numGroundFrames;
  1855. }
  1856. QuatF rotSpeed(adjRot);
  1857. QuatF groundRot(rotSpeed);
  1858. for (S32 i = 0; i < seq.numGroundFrames; i++)
  1859. {
  1860. groundTranslations[seq.firstGroundFrame + i] = adjTrans * (i + 1);
  1861. groundRotations[seq.firstGroundFrame + i].set(groundRot);
  1862. groundRot *= rotSpeed;
  1863. }
  1864. // set MakePath flag so ground frames will be animated
  1865. seq.flags |= TSShape::MakePath;
  1866. return true;
  1867. }
  1868. void TSShape::makeEditable()
  1869. {
  1870. mNeedReinit = true;
  1871. if (mShapeVertexData.base == NULL)
  1872. return;
  1873. for (U32 i = 0; i < meshes.size(); i++)
  1874. {
  1875. if (meshes[i])
  1876. {
  1877. meshes[i]->makeEditable();
  1878. }
  1879. }
  1880. mShapeVertexData.set(NULL, 0);
  1881. }
  1882. bool TSShape::needsReinit()
  1883. {
  1884. return mVertexSize == 0 || mShapeVertexData.base == NULL || mNeedReinit;
  1885. }