tsMesh.cpp 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121
  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/tsMesh.h"
  24. #include "ts/tsMeshIntrinsics.h"
  25. #include "ts/tsDecal.h"
  26. #include "ts/tsSortedMesh.h"
  27. #include "ts/tsShape.h"
  28. #include "ts/tsShapeInstance.h"
  29. #include "ts/tsRenderState.h"
  30. #include "ts/tsMaterialList.h"
  31. #include "ts/instancingMatHook.h"
  32. #include "math/mMath.h"
  33. #include "math/mathIO.h"
  34. #include "math/mathUtils.h"
  35. #include "console/console.h"
  36. #include "scene/sceneObject.h"
  37. #include "core/bitRender.h"
  38. #include "collision/convex.h"
  39. #include "collision/optimizedPolyList.h"
  40. #include "core/frameAllocator.h"
  41. #include "platform/profiler.h"
  42. #include "materials/sceneData.h"
  43. #include "materials/materialManager.h"
  44. #include "scene/sceneManager.h"
  45. #include "scene/sceneRenderState.h"
  46. #include "materials/matInstance.h"
  47. #include "renderInstance/renderPassManager.h"
  48. #include "materials/customMaterialDefinition.h"
  49. #include "gfx/util/triListOpt.h"
  50. #include "util/triRayCheck.h"
  51. #include "opcode/Opcode.h"
  52. #if defined(TORQUE_OS_XENON)
  53. # include "platformXbox/platformXbox.h"
  54. #endif
  55. GFXPrimitiveType drawTypes[] = { GFXTriangleList, GFXTriangleStrip };
  56. #define getDrawType(a) (drawTypes[a])
  57. // structures used to share data between detail levels...
  58. // used (and valid) during load only
  59. Vector<Point3F*> TSMesh::smVertsList;
  60. Vector<Point3F*> TSMesh::smNormsList;
  61. Vector<U8*> TSMesh::smEncodedNormsList;
  62. Vector<Point2F*> TSMesh::smTVertsList;
  63. Vector<Point2F*> TSMesh::smTVerts2List;
  64. Vector<ColorI*> TSMesh::smColorsList;
  65. Vector<bool> TSMesh::smDataCopied;
  66. Vector<MatrixF*> TSSkinMesh::smInitTransformList;
  67. Vector<S32*> TSSkinMesh::smVertexIndexList;
  68. Vector<S32*> TSSkinMesh::smBoneIndexList;
  69. Vector<F32*> TSSkinMesh::smWeightList;
  70. Vector<S32*> TSSkinMesh::smNodeIndexList;
  71. Vector<Point3F> gNormalStore;
  72. bool TSMesh::smUseTriangles = false; // convert all primitives to triangle lists on load
  73. bool TSMesh::smUseOneStrip = true; // join triangle strips into one long strip on load
  74. S32 TSMesh::smMinStripSize = 1; // smallest number of _faces_ allowed per strip (all else put in tri list)
  75. bool TSMesh::smUseEncodedNormals = false;
  76. const F32 TSMesh::VISIBILITY_EPSILON = 0.0001f;
  77. S32 TSMesh::smMaxInstancingVerts = 200;
  78. // quick function to force object to face camera -- currently throws out roll :(
  79. void tsForceFaceCamera( MatrixF *mat, const Point3F *objScale )
  80. {
  81. Point4F p;
  82. mat->getColumn( 3, &p );
  83. mat->identity();
  84. mat->setColumn( 3, p );
  85. if ( objScale )
  86. {
  87. MatrixF scale( true );
  88. scale.scale( *objScale );
  89. mat->mul( scale );
  90. }
  91. }
  92. //-----------------------------------------------------
  93. // TSMesh render methods
  94. //-----------------------------------------------------
  95. void TSMesh::render( TSVertexBufferHandle &instanceVB, GFXPrimitiveBufferHandle &instancePB )
  96. {
  97. // A TSMesh never uses the instanceVB.
  98. TORQUE_UNUSED( instanceVB );
  99. TORQUE_UNUSED( instancePB );
  100. innerRender( mVB, mPB );
  101. }
  102. void TSMesh::innerRender( TSVertexBufferHandle &vb, GFXPrimitiveBufferHandle &pb )
  103. {
  104. if ( !vb.isValid() || !pb.isValid() )
  105. return;
  106. GFX->setVertexBuffer( vb );
  107. GFX->setPrimitiveBuffer( pb );
  108. for( U32 p = 0; p < primitives.size(); p++ )
  109. GFX->drawPrimitive( p );
  110. }
  111. void TSMesh::render( TSMaterialList *materials,
  112. const TSRenderState &rdata,
  113. bool isSkinDirty,
  114. const Vector<MatrixF> &transforms,
  115. TSVertexBufferHandle &vertexBuffer,
  116. GFXPrimitiveBufferHandle &primitiveBuffer )
  117. {
  118. // These are only used by TSSkinMesh.
  119. TORQUE_UNUSED( isSkinDirty );
  120. TORQUE_UNUSED( transforms );
  121. TORQUE_UNUSED( vertexBuffer );
  122. TORQUE_UNUSED( primitiveBuffer );
  123. // Pass our shared VB.
  124. innerRender( materials, rdata, mVB, mPB );
  125. }
  126. void TSMesh::innerRender( TSMaterialList *materials, const TSRenderState &rdata, TSVertexBufferHandle &vb, GFXPrimitiveBufferHandle &pb )
  127. {
  128. PROFILE_SCOPE( TSMesh_InnerRender );
  129. if( vertsPerFrame <= 0 )
  130. return;
  131. F32 meshVisibility = rdata.getFadeOverride() * mVisibility;
  132. if ( meshVisibility < VISIBILITY_EPSILON )
  133. return;
  134. const SceneRenderState *state = rdata.getSceneState();
  135. RenderPassManager *renderPass = state->getRenderPass();
  136. MeshRenderInst *coreRI = renderPass->allocInst<MeshRenderInst>();
  137. coreRI->type = RenderPassManager::RIT_Mesh;
  138. // Pass accumulation texture along.
  139. coreRI->accuTex = rdata.getAccuTex();
  140. const MatrixF &objToWorld = GFX->getWorldMatrix();
  141. // Sort by the center point or the bounds.
  142. if ( rdata.useOriginSort() )
  143. coreRI->sortDistSq = ( objToWorld.getPosition() - state->getCameraPosition() ).lenSquared();
  144. else
  145. {
  146. Box3F rBox = mBounds;
  147. objToWorld.mul( rBox );
  148. coreRI->sortDistSq = rBox.getSqDistanceToPoint( state->getCameraPosition() );
  149. }
  150. if (getFlags(Billboard))
  151. {
  152. Point3F camPos = state->getDiffuseCameraPosition();
  153. Point3F objPos;
  154. objToWorld.getColumn(3, &objPos);
  155. Point3F targetVector = camPos - objPos;
  156. if(getFlags(BillboardZAxis))
  157. targetVector.z = 0.0f;
  158. targetVector.normalize();
  159. MatrixF orient = MathUtils::createOrientFromDir(targetVector);
  160. orient.setPosition(objPos);
  161. orient.scale(objToWorld.getScale());
  162. coreRI->objectToWorld = renderPass->allocUniqueXform( orient );
  163. }
  164. else
  165. coreRI->objectToWorld = renderPass->allocUniqueXform( objToWorld );
  166. coreRI->worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  167. coreRI->projection = renderPass->allocSharedXform(RenderPassManager::Projection);
  168. AssertFatal( vb.isValid(), "TSMesh::innerRender() - Got invalid vertex buffer!" );
  169. AssertFatal( pb.isValid(), "TSMesh::innerRender() - Got invalid primitive buffer!" );
  170. coreRI->vertBuff = &vb;
  171. coreRI->primBuff = &pb;
  172. coreRI->defaultKey2 = (uintptr_t) coreRI->vertBuff;
  173. coreRI->materialHint = rdata.getMaterialHint();
  174. coreRI->visibility = meshVisibility;
  175. coreRI->cubemap = rdata.getCubemap();
  176. // NOTICE: SFXBB is removed and refraction is disabled!
  177. //coreRI->backBuffTex = GFX->getSfxBackBuffer();
  178. for ( S32 i = 0; i < primitives.size(); i++ )
  179. {
  180. const TSDrawPrimitive &draw = primitives[i];
  181. // We need to have a material.
  182. if ( draw.matIndex & TSDrawPrimitive::NoMaterial )
  183. continue;
  184. #ifdef TORQUE_DEBUG_BREAK_INSPECT
  185. // for inspection if you happen to be running in a debugger and can't do bit
  186. // operations in your head.
  187. S32 triangles = draw.matIndex & TSDrawPrimitive::Triangles;
  188. S32 strip = draw.matIndex & TSDrawPrimitive::Strip;
  189. S32 fan = draw.matIndex & TSDrawPrimitive::Fan;
  190. S32 indexed = draw.matIndex & TSDrawPrimitive::Indexed;
  191. S32 type = draw.matIndex & TSDrawPrimitive::TypeMask;
  192. TORQUE_UNUSED(triangles);
  193. TORQUE_UNUSED(strip);
  194. TORQUE_UNUSED(fan);
  195. TORQUE_UNUSED(indexed);
  196. TORQUE_UNUSED(type);
  197. //define TORQUE_DEBUG_BREAK_INSPECT, and insert debug break here to inspect the above elements at runtime
  198. #endif
  199. const U32 matIndex = draw.matIndex & TSDrawPrimitive::MaterialMask;
  200. BaseMatInstance *matInst = materials->getMaterialInst( matIndex );
  201. #ifndef TORQUE_OS_MAC
  202. // Get the instancing material if this mesh qualifies.
  203. if ( meshType != SkinMeshType && pb->mPrimitiveArray[i].numVertices < smMaxInstancingVerts )
  204. matInst = InstancingMaterialHook::getInstancingMat( matInst );
  205. #endif
  206. // If we don't have a material instance after the overload then
  207. // there is nothing to render... skip this primitive.
  208. matInst = state->getOverrideMaterial( matInst );
  209. if ( !matInst || !matInst->isValid())
  210. continue;
  211. // If the material needs lights then gather them
  212. // here once and set them on the core render inst.
  213. if ( matInst->isForwardLit() && !coreRI->lights[0] && rdata.getLightQuery() )
  214. rdata.getLightQuery()->getLights( coreRI->lights, 8 );
  215. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  216. *ri = *coreRI;
  217. ri->matInst = matInst;
  218. ri->defaultKey = matInst->getStateHint();
  219. ri->primBuffIndex = i;
  220. // Translucent materials need the translucent type.
  221. if ( matInst->getMaterial()->isTranslucent() )
  222. {
  223. ri->type = RenderPassManager::RIT_Translucent;
  224. ri->translucentSort = true;
  225. }
  226. renderPass->addInst( ri );
  227. }
  228. }
  229. const Point3F * TSMesh::getNormals( S32 firstVert )
  230. {
  231. if ( getFlags( UseEncodedNormals ) )
  232. {
  233. gNormalStore.setSize( vertsPerFrame );
  234. for ( S32 i = 0; i < encodedNorms.size(); i++ )
  235. gNormalStore[i] = decodeNormal( encodedNorms[ i + firstVert ] );
  236. return gNormalStore.address();
  237. }
  238. return &norms[firstVert];
  239. }
  240. //-----------------------------------------------------
  241. // TSMesh collision methods
  242. //-----------------------------------------------------
  243. bool TSMesh::buildPolyList( S32 frame, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  244. {
  245. S32 firstVert = vertsPerFrame * frame, i, base = 0;
  246. // add the verts...
  247. if ( vertsPerFrame )
  248. {
  249. if ( mVertexData.isReady() )
  250. {
  251. OptimizedPolyList* opList = dynamic_cast<OptimizedPolyList*>(polyList);
  252. if ( opList )
  253. {
  254. base = opList->mVertexList.size();
  255. for ( i = 0; i < vertsPerFrame; i++ )
  256. {
  257. // Don't use vertex() method as we want to retain the original indices
  258. OptimizedPolyList::VertIndex vert;
  259. vert.vertIdx = opList->insertPoint( mVertexData[ i + firstVert ].vert() );
  260. vert.normalIdx = opList->insertNormal( mVertexData[ i + firstVert ].normal() );
  261. vert.uv0Idx = opList->insertUV0( mVertexData[ i + firstVert ].tvert() );
  262. if ( mHasTVert2 )
  263. vert.uv1Idx = opList->insertUV1( mVertexData[ i + firstVert ].tvert2() );
  264. opList->mVertexList.push_back( vert );
  265. }
  266. }
  267. else
  268. {
  269. base = polyList->addPointAndNormal( mVertexData[firstVert].vert(), mVertexData[firstVert].normal() );
  270. for ( i = 1; i < vertsPerFrame; i++ )
  271. {
  272. polyList->addPointAndNormal( mVertexData[ i + firstVert ].vert(), mVertexData[ i + firstVert ].normal() );
  273. }
  274. }
  275. }
  276. else
  277. {
  278. OptimizedPolyList* opList = dynamic_cast<OptimizedPolyList*>(polyList);
  279. if ( opList )
  280. {
  281. base = opList->mVertexList.size();
  282. for ( i = 0; i < vertsPerFrame; i++ )
  283. {
  284. // Don't use vertex() method as we want to retain the original indices
  285. OptimizedPolyList::VertIndex vert;
  286. vert.vertIdx = opList->insertPoint( verts[ i + firstVert ] );
  287. vert.normalIdx = opList->insertNormal( norms[ i + firstVert ] );
  288. vert.uv0Idx = opList->insertUV0( tverts[ i + firstVert ] );
  289. if ( mHasTVert2 )
  290. vert.uv1Idx = opList->insertUV1( tverts2[ i + firstVert ] );
  291. opList->mVertexList.push_back( vert );
  292. }
  293. }
  294. else
  295. {
  296. base = polyList->addPointAndNormal( verts[firstVert], norms[firstVert] );
  297. for ( i = 1; i < vertsPerFrame; i++ )
  298. polyList->addPointAndNormal( verts[ i + firstVert ], norms[ i + firstVert ] );
  299. }
  300. }
  301. }
  302. // add the polys...
  303. for ( i = 0; i < primitives.size(); i++ )
  304. {
  305. TSDrawPrimitive & draw = primitives[i];
  306. U32 start = draw.start;
  307. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildPolyList (1)" );
  308. U32 matIndex = draw.matIndex & TSDrawPrimitive::MaterialMask;
  309. BaseMatInstance* material = ( materials ? materials->getMaterialInst( matIndex ) : 0 );
  310. // gonna depend on what kind of primitive it is...
  311. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  312. {
  313. for ( S32 j = 0; j < draw.numElements; )
  314. {
  315. U32 idx0 = base + indices[start + j + 0];
  316. U32 idx1 = base + indices[start + j + 1];
  317. U32 idx2 = base + indices[start + j + 2];
  318. polyList->begin(material,surfaceKey++);
  319. polyList->vertex( idx0 );
  320. polyList->vertex( idx1 );
  321. polyList->vertex( idx2 );
  322. polyList->plane( idx0, idx1, idx2 );
  323. polyList->end();
  324. j += 3;
  325. }
  326. }
  327. else
  328. {
  329. AssertFatal( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Strip,"TSMesh::buildPolyList (2)" );
  330. U32 idx0 = base + indices[start + 0];
  331. U32 idx1;
  332. U32 idx2 = base + indices[start + 1];
  333. U32 * nextIdx = &idx1;
  334. for ( S32 j = 2; j < draw.numElements; j++ )
  335. {
  336. *nextIdx = idx2;
  337. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  338. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  339. idx2 = base + indices[start + j];
  340. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  341. continue;
  342. polyList->begin( material, surfaceKey++ );
  343. polyList->vertex( idx0 );
  344. polyList->vertex( idx1 );
  345. polyList->vertex( idx2 );
  346. polyList->plane( idx0, idx1, idx2 );
  347. polyList->end();
  348. }
  349. }
  350. }
  351. return true;
  352. }
  353. bool TSMesh::getFeatures( S32 frame, const MatrixF& mat, const VectorF&, ConvexFeature* cf, U32& )
  354. {
  355. S32 firstVert = vertsPerFrame * frame;
  356. S32 i;
  357. S32 base = cf->mVertexList.size();
  358. for ( i = 0; i < vertsPerFrame; i++ )
  359. {
  360. cf->mVertexList.increment();
  361. mat.mulP( mVertexData[firstVert + i].vert(), &cf->mVertexList.last() );
  362. }
  363. // add the polys...
  364. for ( i = 0; i < primitives.size(); i++ )
  365. {
  366. TSDrawPrimitive & draw = primitives[i];
  367. U32 start = draw.start;
  368. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildPolyList (1)" );
  369. // gonna depend on what kind of primitive it is...
  370. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles)
  371. {
  372. for ( S32 j = 0; j < draw.numElements; j += 3 )
  373. {
  374. PlaneF plane( cf->mVertexList[base + indices[start + j + 0]],
  375. cf->mVertexList[base + indices[start + j + 1]],
  376. cf->mVertexList[base + indices[start + j + 2]]);
  377. cf->mFaceList.increment();
  378. ConvexFeature::Face& lastFace = cf->mFaceList.last();
  379. lastFace.normal = plane;
  380. lastFace.vertex[0] = base + indices[start + j + 0];
  381. lastFace.vertex[1] = base + indices[start + j + 1];
  382. lastFace.vertex[2] = base + indices[start + j + 2];
  383. for ( U32 l = 0; l < 3; l++ )
  384. {
  385. U32 newEdge0, newEdge1;
  386. U32 zero = base + indices[start + j + l];
  387. U32 one = base + indices[start + j + ((l+1)%3)];
  388. newEdge0 = getMin( zero, one );
  389. newEdge1 = getMax( zero, one );
  390. bool found = false;
  391. for ( S32 k = 0; k < cf->mEdgeList.size(); k++ )
  392. {
  393. if ( cf->mEdgeList[k].vertex[0] == newEdge0 &&
  394. cf->mEdgeList[k].vertex[1] == newEdge1)
  395. {
  396. found = true;
  397. break;
  398. }
  399. }
  400. if ( !found )
  401. {
  402. cf->mEdgeList.increment();
  403. cf->mEdgeList.last().vertex[0] = newEdge0;
  404. cf->mEdgeList.last().vertex[1] = newEdge1;
  405. }
  406. }
  407. }
  408. }
  409. else
  410. {
  411. AssertFatal( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Strip,"TSMesh::buildPolyList (2)" );
  412. U32 idx0 = base + indices[start + 0];
  413. U32 idx1;
  414. U32 idx2 = base + indices[start + 1];
  415. U32 * nextIdx = &idx1;
  416. for ( S32 j = 2; j < draw.numElements; j++ )
  417. {
  418. *nextIdx = idx2;
  419. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  420. idx2 = base + indices[start + j];
  421. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  422. continue;
  423. PlaneF plane( cf->mVertexList[idx0],
  424. cf->mVertexList[idx1],
  425. cf->mVertexList[idx2] );
  426. cf->mFaceList.increment();
  427. cf->mFaceList.last().normal = plane;
  428. cf->mFaceList.last().vertex[0] = idx0;
  429. cf->mFaceList.last().vertex[1] = idx1;
  430. cf->mFaceList.last().vertex[2] = idx2;
  431. U32 newEdge0, newEdge1;
  432. newEdge0 = getMin( idx0, idx1 );
  433. newEdge1 = getMax( idx0, idx1 );
  434. bool found = false;
  435. S32 k;
  436. for ( k = 0; k < cf->mEdgeList.size(); k++ )
  437. {
  438. ConvexFeature::Edge currentEdge = cf->mEdgeList[k];
  439. if (currentEdge.vertex[0] == newEdge0 &&
  440. currentEdge.vertex[1] == newEdge1)
  441. {
  442. found = true;
  443. break;
  444. }
  445. }
  446. if ( !found )
  447. {
  448. cf->mEdgeList.increment();
  449. cf->mEdgeList.last().vertex[0] = newEdge0;
  450. cf->mEdgeList.last().vertex[1] = newEdge1;
  451. }
  452. newEdge0 = getMin( idx1, idx2 );
  453. newEdge1 = getMax( idx1, idx2 );
  454. found = false;
  455. for ( k = 0; k < cf->mEdgeList.size(); k++ )
  456. {
  457. if ( cf->mEdgeList[k].vertex[0] == newEdge0 &&
  458. cf->mEdgeList[k].vertex[1] == newEdge1 )
  459. {
  460. found = true;
  461. break;
  462. }
  463. }
  464. if ( !found )
  465. {
  466. cf->mEdgeList.increment();
  467. cf->mEdgeList.last().vertex[0] = newEdge0;
  468. cf->mEdgeList.last().vertex[1] = newEdge1;
  469. }
  470. newEdge0 = getMin(idx0, idx2);
  471. newEdge1 = getMax(idx0, idx2);
  472. found = false;
  473. for ( k = 0; k < cf->mEdgeList.size(); k++ )
  474. {
  475. if ( cf->mEdgeList[k].vertex[0] == newEdge0 &&
  476. cf->mEdgeList[k].vertex[1] == newEdge1 )
  477. {
  478. found = true;
  479. break;
  480. }
  481. }
  482. if ( !found )
  483. {
  484. cf->mEdgeList.increment();
  485. cf->mEdgeList.last().vertex[0] = newEdge0;
  486. cf->mEdgeList.last().vertex[1] = newEdge1;
  487. }
  488. }
  489. }
  490. }
  491. return false;
  492. }
  493. void TSMesh::support( S32 frame, const Point3F &v, F32 *currMaxDP, Point3F *currSupport )
  494. {
  495. if ( vertsPerFrame == 0 )
  496. return;
  497. U32 waterMark = FrameAllocator::getWaterMark();
  498. F32* pDots = (F32*)FrameAllocator::alloc( sizeof(F32) * vertsPerFrame );
  499. S32 firstVert = vertsPerFrame * frame;
  500. m_point3F_bulk_dot( &v.x,
  501. &mVertexData[firstVert].vert().x,
  502. vertsPerFrame,
  503. mVertexData.vertSize(),
  504. pDots );
  505. F32 localdp = *currMaxDP;
  506. S32 index = -1;
  507. for ( S32 i = 0; i < vertsPerFrame; i++ )
  508. {
  509. if ( pDots[i] > localdp )
  510. {
  511. localdp = pDots[i];
  512. index = i;
  513. }
  514. }
  515. FrameAllocator::setWaterMark(waterMark);
  516. if ( index != -1 )
  517. {
  518. *currMaxDP = localdp;
  519. *currSupport = mVertexData[index + firstVert].vert();
  520. }
  521. }
  522. bool TSMesh::castRay( S32 frame, const Point3F & start, const Point3F & end, RayInfo * rayInfo, TSMaterialList* materials )
  523. {
  524. if ( planeNormals.empty() )
  525. buildConvexHull(); // if haven't done it yet...
  526. // Keep track of startTime and endTime. They start out at just under 0 and just over 1, respectively.
  527. // As we check against each plane, prune start and end times back to represent current intersection of
  528. // line with all the planes (or rather with all the half-spaces defined by the planes).
  529. // But, instead of explicitly keeping track of startTime and endTime, keep track as numerator and denominator
  530. // so that we can avoid as many divisions as possible.
  531. // F32 startTime = -0.01f;
  532. F32 startNum = -0.01f;
  533. F32 startDen = 1.00f;
  534. // F32 endTime = 1.01f;
  535. F32 endNum = 1.01f;
  536. F32 endDen = 1.00f;
  537. S32 curPlane = 0;
  538. U32 curMaterial = 0;
  539. bool found = false;
  540. // the following block of code is an optimization...
  541. // it isn't necessary if the longer version of the main loop is used
  542. bool tmpFound;
  543. S32 tmpPlane;
  544. F32 sgn = -1.0f;
  545. F32 * pnum = &startNum;
  546. F32 * pden = &startDen;
  547. S32 * pplane = &curPlane;
  548. bool * pfound = &found;
  549. S32 startPlane = frame * planesPerFrame;
  550. for ( S32 i = startPlane; i < startPlane + planesPerFrame; i++ )
  551. {
  552. // if start & end outside, no collision
  553. // if start & end inside, continue
  554. // if start outside, end inside, or visa versa, find intersection of line with plane
  555. // then update intersection of line with hull (using startTime and endTime)
  556. F32 dot1 = mDot( planeNormals[i], start ) - planeConstants[i];
  557. F32 dot2 = mDot( planeNormals[i], end) - planeConstants[i];
  558. if ( dot1 * dot2 > 0.0f )
  559. {
  560. // same side of the plane...which side -- dot==0 considered inside
  561. if ( dot1 > 0.0f )
  562. return false; // start and end outside of this plane, no collision
  563. // start and end inside plane, continue
  564. continue;
  565. }
  566. //AssertFatal( dot1 / ( dot1 - dot2 ) >= 0.0f && dot1 / ( dot1 - dot2 ) <= 1.0f,"TSMesh::castRay (1)" );
  567. // find intersection (time) with this plane...
  568. // F32 time = dot1 / (dot1-dot2);
  569. F32 num = mFabs( dot1 );
  570. F32 den = mFabs( dot1 - dot2 );
  571. // the following block of code is an optimized version...
  572. // this can be commented out and the following block of code used instead
  573. // if debugging a problem in this code, that should probably be done
  574. // if you want to see how this works, look at the following block of code,
  575. // not this one...
  576. // Note that this does not get optimized appropriately...it is included this way
  577. // as an idea for future optimization.
  578. if ( sgn * dot1 >= 0 )
  579. {
  580. sgn *= -1.0f;
  581. pnum = (F32*) ((dsize_t)pnum ^ (dsize_t)&endNum ^ (dsize_t)&startNum);
  582. pden = (F32*) ((dsize_t)pden ^ (dsize_t)&endDen ^ (dsize_t)&startDen);
  583. pplane = (S32*) ((dsize_t)pplane ^ (dsize_t)&tmpPlane ^ (dsize_t)&curPlane);
  584. pfound = (bool*) ((dsize_t)pfound ^ (dsize_t)&tmpFound ^ (dsize_t)&found);
  585. }
  586. bool noCollision = num * endDen * sgn < endNum * den * sgn && num * startDen * sgn < startNum * den * sgn;
  587. if (num * *pden * sgn < *pnum * den * sgn && !noCollision)
  588. {
  589. *pnum = num;
  590. *pden = den;
  591. *pplane = i;
  592. *pfound = true;
  593. }
  594. else if ( noCollision )
  595. return false;
  596. // if (dot1<=0.0f)
  597. // {
  598. // // start is inside plane, end is outside...chop off end
  599. // if (num*endDen<endNum*den) // if (time<endTime)
  600. // {
  601. // if (num*startDen<startNum*den) //if (time<startTime)
  602. // // no intersection of line and hull
  603. // return false;
  604. // // endTime = time;
  605. // endNum = num;
  606. // endDen = den;
  607. // }
  608. // // else, no need to do anything, just continue (we've been more inside than this)
  609. // }
  610. // else // dot2<=0.0f
  611. // {
  612. // // end is inside poly, start is outside...chop off start
  613. // AssertFatal(dot2<=0.0f,"TSMesh::castRay (2)");
  614. // if (num*startDen>startNum*den) // if (time>startTime)
  615. // {
  616. // if (num*endDen>endNum*den) //if (time>endTime)
  617. // // no intersection of line and hull
  618. // return false;
  619. // // startTime = time;
  620. // startNum = num;
  621. // startDen = den;
  622. // curPlane = i;
  623. // curMaterial = planeMaterials[i-startPlane];
  624. // found = true;
  625. // }
  626. // // else, no need to do anything, just continue (we've been more inside than this)
  627. // }
  628. }
  629. // setup rayInfo
  630. if ( found && rayInfo )
  631. {
  632. curMaterial = planeMaterials[ curPlane - startPlane ];
  633. rayInfo->t = (F32)startNum/(F32)startDen; // finally divide...
  634. rayInfo->normal = planeNormals[curPlane];
  635. if (materials && materials->size() > 0)
  636. rayInfo->material = materials->getMaterialInst( curMaterial );
  637. else
  638. rayInfo->material = NULL;
  639. rayInfo->setContactPoint( start, end );
  640. return true;
  641. }
  642. else if ( found )
  643. return true;
  644. // only way to get here is if start is inside hull...
  645. // we could return null and just plug in garbage for the material and normal...
  646. return false;
  647. }
  648. bool TSMesh::castRayRendered( S32 frame, const Point3F & start, const Point3F & end, RayInfo * rayInfo, TSMaterialList* materials )
  649. {
  650. if( vertsPerFrame <= 0 )
  651. return false;
  652. if( mNumVerts == 0 )
  653. return false;
  654. S32 firstVert = vertsPerFrame * frame;
  655. bool found = false;
  656. F32 best_t = F32_MAX;
  657. U32 bestIdx0 = 0, bestIdx1 = 0, bestIdx2 = 0;
  658. BaseMatInstance* bestMaterial = NULL;
  659. Point3F dir = end - start;
  660. for ( S32 i = 0; i < primitives.size(); i++ )
  661. {
  662. TSDrawPrimitive & draw = primitives[i];
  663. U32 drawStart = draw.start;
  664. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::castRayRendered (1)" );
  665. U32 matIndex = draw.matIndex & TSDrawPrimitive::MaterialMask;
  666. BaseMatInstance* material = ( materials ? materials->getMaterialInst( matIndex ) : 0 );
  667. U32 idx0, idx1, idx2;
  668. // gonna depend on what kind of primitive it is...
  669. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  670. {
  671. for ( S32 j = 0; j < draw.numElements-2; j += 3 )
  672. {
  673. idx0 = indices[drawStart + j + 0];
  674. idx1 = indices[drawStart + j + 1];
  675. idx2 = indices[drawStart + j + 2];
  676. F32 cur_t = 0;
  677. Point2F b;
  678. if(castRayTriangle(start, dir, mVertexData[firstVert + idx0].vert(),
  679. mVertexData[firstVert + idx1].vert(), mVertexData[firstVert + idx2].vert(), cur_t, b))
  680. {
  681. if(cur_t < best_t)
  682. {
  683. best_t = cur_t;
  684. bestIdx0 = idx0;
  685. bestIdx1 = idx1;
  686. bestIdx2 = idx2;
  687. bestMaterial = material;
  688. found = true;
  689. }
  690. }
  691. }
  692. }
  693. else
  694. {
  695. AssertFatal( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Strip,"TSMesh::castRayRendered (2)" );
  696. idx0 = indices[drawStart + 0];
  697. idx2 = indices[drawStart + 1];
  698. U32 * nextIdx = &idx1;
  699. for ( S32 j = 2; j < draw.numElements; j++ )
  700. {
  701. *nextIdx = idx2;
  702. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  703. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  704. idx2 = indices[drawStart + j];
  705. if ( idx0 == idx1 || idx0 == idx2 || idx1 == idx2 )
  706. continue;
  707. F32 cur_t = 0;
  708. Point2F b;
  709. if(castRayTriangle(start, dir, mVertexData[firstVert + idx0].vert(),
  710. mVertexData[firstVert + idx1].vert(), mVertexData[firstVert + idx2].vert(), cur_t, b))
  711. {
  712. if(cur_t < best_t)
  713. {
  714. best_t = cur_t;
  715. bestIdx0 = firstVert + idx0;
  716. bestIdx1 = firstVert + idx1;
  717. bestIdx2 = firstVert + idx2;
  718. bestMaterial = material;
  719. found = true;
  720. }
  721. }
  722. }
  723. }
  724. }
  725. // setup rayInfo
  726. if ( found && rayInfo )
  727. {
  728. rayInfo->t = best_t;
  729. Point3F normal;
  730. mCross(mVertexData[bestIdx2].vert()-mVertexData[bestIdx0].vert(),mVertexData[bestIdx1].vert()-mVertexData[bestIdx0].vert(),&normal);
  731. if ( mDot( normal, normal ) < 0.001f )
  732. {
  733. mCross( mVertexData[bestIdx0].vert() - mVertexData[bestIdx1].vert(), mVertexData[bestIdx2].vert() - mVertexData[bestIdx1].vert(), &normal );
  734. if ( mDot( normal, normal ) < 0.001f )
  735. {
  736. mCross( mVertexData[bestIdx1].vert() - mVertexData[bestIdx2].vert(), mVertexData[bestIdx0].vert() - mVertexData[bestIdx2].vert(), &normal );
  737. }
  738. }
  739. normal.normalize();
  740. rayInfo->normal = normal;
  741. rayInfo->material = bestMaterial;
  742. rayInfo->setContactPoint( start, end );
  743. return true;
  744. }
  745. else if ( found )
  746. return true;
  747. return false;
  748. }
  749. bool TSMesh::addToHull( U32 idx0, U32 idx1, U32 idx2 )
  750. {
  751. // calculate the normal of this triangle... remember, we lose precision
  752. // when we subtract two large numbers that are very close to each other,
  753. // so depending on how we calculate the normal, we could get a
  754. // different result. so, we will calculate the normal three different
  755. // ways and take the one that gives us the largest vector before we
  756. // normalize.
  757. Point3F normal1, normal2, normal3;
  758. mCross(mVertexData[idx2].vert()-mVertexData[idx0].vert(),mVertexData[idx1].vert()-mVertexData[idx0].vert(),&normal1);
  759. mCross(mVertexData[idx0].vert()-mVertexData[idx1].vert(),mVertexData[idx2].vert()-mVertexData[idx1].vert(),&normal2);
  760. mCross(mVertexData[idx1].vert()-mVertexData[idx2].vert(),mVertexData[idx0].vert()-mVertexData[idx2].vert(),&normal3);
  761. Point3F normal = normal1;
  762. F32 greatestMagSquared = mDot(normal1, normal1);
  763. F32 magSquared = mDot(normal2, normal2);
  764. if (magSquared > greatestMagSquared)
  765. {
  766. normal = normal2;
  767. greatestMagSquared = magSquared;
  768. }
  769. magSquared = mDot(normal3, normal3);
  770. if (magSquared > greatestMagSquared)
  771. {
  772. normal = normal3;
  773. greatestMagSquared = magSquared;
  774. }
  775. if (mDot(normal, normal) < 0.00000001f)
  776. return false;
  777. normal.normalize();
  778. F32 k = mDot( normal, mVertexData[idx0].vert() );
  779. for ( S32 i = 0; i < planeNormals.size(); i++ )
  780. {
  781. if ( mDot( planeNormals[i], normal ) > 0.99f && mFabs( k-planeConstants[i] ) < 0.01f )
  782. return false; // this is a repeat...
  783. }
  784. // new plane, add it to the list...
  785. planeNormals.push_back( normal );
  786. planeConstants.push_back( k );
  787. return true;
  788. }
  789. bool TSMesh::buildConvexHull()
  790. {
  791. // already done, return without error
  792. if ( planeNormals.size() )
  793. return true;
  794. bool error = false;
  795. // should probably only have 1 frame, but just in case...
  796. planesPerFrame = 0;
  797. S32 frame, i, j;
  798. for ( frame = 0; frame < numFrames; frame++ )
  799. {
  800. S32 firstVert = vertsPerFrame * frame;
  801. S32 firstPlane = planeNormals.size();
  802. for ( i = 0; i < primitives.size(); i++ )
  803. {
  804. TSDrawPrimitive & draw = primitives[i];
  805. U32 start = draw.start;
  806. AssertFatal( draw.matIndex & TSDrawPrimitive::Indexed,"TSMesh::buildConvexHull (1)" );
  807. // gonna depend on what kind of primitive it is...
  808. if ( (draw.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  809. {
  810. for ( j = 0; j < draw.numElements; j += 3 )
  811. if ( addToHull( indices[start + j + 0] + firstVert,
  812. indices[start + j + 1] + firstVert,
  813. indices[start + j + 2] + firstVert ) && frame == 0 )
  814. planeMaterials.push_back( draw.matIndex & TSDrawPrimitive::MaterialMask );
  815. }
  816. else
  817. {
  818. AssertFatal( (draw.matIndex&TSDrawPrimitive::Strip) == TSDrawPrimitive::Strip,"TSMesh::buildConvexHull (2)" );
  819. U32 idx0 = indices[start + 0] + firstVert;
  820. U32 idx1;
  821. U32 idx2 = indices[start + 1] + firstVert;
  822. U32 * nextIdx = &idx1;
  823. for ( j = 2; j < draw.numElements; j++ )
  824. {
  825. *nextIdx = idx2;
  826. // nextIdx = (j%2)==0 ? &idx0 : &idx1;
  827. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1 );
  828. idx2 = indices[start + j] + firstVert;
  829. if ( addToHull( idx0, idx1, idx2 ) && frame == 0 )
  830. planeMaterials.push_back( draw.matIndex & TSDrawPrimitive::MaterialMask );
  831. }
  832. }
  833. }
  834. // make sure all the verts on this frame are inside all the planes
  835. for ( i = 0; i < vertsPerFrame; i++ )
  836. for ( j = firstPlane; j < planeNormals.size(); j++ )
  837. if ( mDot( mVertexData[firstVert + i].vert(), planeNormals[j] ) - planeConstants[j] < 0.01 ) // .01 == a little slack
  838. error = true;
  839. if ( frame == 0 )
  840. planesPerFrame = planeNormals.size();
  841. if ( (frame + 1) * planesPerFrame != planeNormals.size() )
  842. {
  843. // eek, not all frames have same number of planes...
  844. while ( (frame + 1) * planesPerFrame > planeNormals.size() )
  845. {
  846. // we're short, duplicate last plane till we match
  847. U32 sz = planeNormals.size();
  848. planeNormals.increment();
  849. planeNormals.last() = planeNormals[sz-1];
  850. planeConstants.increment();
  851. planeConstants.last() = planeConstants[sz-1];
  852. }
  853. while ( (frame + 1) * planesPerFrame < planeNormals.size() )
  854. {
  855. // harsh -- last frame has more than other frames
  856. // duplicate last plane in each frame
  857. for ( S32 k = frame - 1; k >= 0; k-- )
  858. {
  859. planeNormals.insert( k * planesPerFrame + planesPerFrame );
  860. planeNormals[k * planesPerFrame + planesPerFrame] = planeNormals[k * planesPerFrame + planesPerFrame - 1];
  861. planeConstants.insert( k * planesPerFrame + planesPerFrame );
  862. planeConstants[k * planesPerFrame + planesPerFrame] = planeConstants[k * planesPerFrame + planesPerFrame - 1];
  863. if ( k == 0 )
  864. {
  865. planeMaterials.increment();
  866. planeMaterials.last() = planeMaterials[planeMaterials.size() - 2];
  867. }
  868. }
  869. planesPerFrame++;
  870. }
  871. }
  872. AssertFatal( (frame + 1) * planesPerFrame == planeNormals.size(),"TSMesh::buildConvexHull (3)" );
  873. }
  874. return !error;
  875. }
  876. //-----------------------------------------------------
  877. // TSMesh bounds methods
  878. //-----------------------------------------------------
  879. void TSMesh::computeBounds()
  880. {
  881. MatrixF mat(true);
  882. computeBounds( mat, mBounds, -1, &mCenter, &mRadius );
  883. }
  884. void TSMesh::computeBounds( const MatrixF &transform, Box3F &bounds, S32 frame, Point3F *center, F32 *radius )
  885. {
  886. const Point3F *baseVert = NULL;
  887. S32 stride = 0;
  888. S32 numVerts = 0;
  889. if(mVertexData.isReady())
  890. {
  891. baseVert = &mVertexData[0].vert();
  892. stride = mVertexData.vertSize();
  893. if ( frame < 0 )
  894. numVerts = mNumVerts;
  895. else
  896. {
  897. baseVert = &mVertexData[frame * vertsPerFrame].vert();
  898. numVerts = vertsPerFrame;
  899. }
  900. }
  901. else
  902. {
  903. baseVert = verts.address();
  904. stride = sizeof(Point3F);
  905. if ( frame < 0 )
  906. numVerts = verts.size();
  907. else
  908. {
  909. baseVert += frame * vertsPerFrame;
  910. numVerts = vertsPerFrame;
  911. }
  912. }
  913. computeBounds( baseVert, numVerts, stride, transform, bounds, center, radius );
  914. }
  915. void TSMesh::computeBounds( const Point3F *v, S32 numVerts, S32 stride, const MatrixF &transform, Box3F &bounds, Point3F *center, F32 *radius )
  916. {
  917. const U8 *_vb = reinterpret_cast<const U8 *>(v);
  918. if ( !numVerts )
  919. {
  920. bounds.minExtents = Point3F::Zero;
  921. bounds.maxExtents = Point3F::Zero;
  922. if ( center )
  923. *center = Point3F::Zero;
  924. if ( radius )
  925. *radius = 0;
  926. return;
  927. }
  928. S32 i;
  929. Point3F p;
  930. transform.mulP( *v, &bounds.minExtents );
  931. bounds.maxExtents = bounds.minExtents;
  932. for ( i = 0; i < numVerts; i++ )
  933. {
  934. const Point3F &curVert = *reinterpret_cast<const Point3F *>(_vb + i * stride);
  935. transform.mulP( curVert, &p );
  936. bounds.maxExtents.setMax( p );
  937. bounds.minExtents.setMin( p );
  938. }
  939. Point3F c;
  940. if ( !center )
  941. center = &c;
  942. center->x = 0.5f * (bounds.minExtents.x + bounds.maxExtents.x);
  943. center->y = 0.5f * (bounds.minExtents.y + bounds.maxExtents.y);
  944. center->z = 0.5f * (bounds.minExtents.z + bounds.maxExtents.z);
  945. if ( radius )
  946. {
  947. *radius = 0.0f;
  948. for ( i = 0; i < numVerts; i++ )
  949. {
  950. const Point3F &curVert = *reinterpret_cast<const Point3F *>(_vb + i * stride);
  951. transform.mulP( curVert, &p );
  952. p -= *center;
  953. *radius = getMax( *radius, mDot( p, p ) );
  954. }
  955. *radius = mSqrt( *radius );
  956. }
  957. }
  958. //-----------------------------------------------------
  959. S32 TSMesh::getNumPolys() const
  960. {
  961. S32 count = 0;
  962. for ( S32 i = 0; i < primitives.size(); i++ )
  963. {
  964. switch (primitives[i].matIndex & TSDrawPrimitive::TypeMask)
  965. {
  966. case TSDrawPrimitive::Triangles:
  967. count += primitives[i].numElements / 3;
  968. break;
  969. case TSDrawPrimitive::Fan:
  970. count += primitives[i].numElements - 2;
  971. break;
  972. case TSDrawPrimitive::Strip:
  973. // Don't count degenerate triangles
  974. for ( S32 j = primitives[i].start;
  975. j < primitives[i].start+primitives[i].numElements-2;
  976. j++ )
  977. {
  978. if ((indices[j] != indices[j+1]) &&
  979. (indices[j] != indices[j+2]) &&
  980. (indices[j+1] != indices[j+2]))
  981. count++;
  982. }
  983. break;
  984. }
  985. }
  986. return count;
  987. }
  988. //-----------------------------------------------------
  989. TSMesh::TSMesh() : meshType( StandardMeshType )
  990. {
  991. VECTOR_SET_ASSOCIATION( planeNormals );
  992. VECTOR_SET_ASSOCIATION( planeConstants );
  993. VECTOR_SET_ASSOCIATION( planeMaterials );
  994. parentMesh = -1;
  995. mOptTree = NULL;
  996. mOpMeshInterface = NULL;
  997. mOpTris = NULL;
  998. mOpPoints = NULL;
  999. mDynamic = false;
  1000. mVisibility = 1.0f;
  1001. mHasTVert2 = false;
  1002. mHasColor = false;
  1003. mNumVerts = 0;
  1004. }
  1005. //-----------------------------------------------------
  1006. // TSMesh destructor
  1007. //-----------------------------------------------------
  1008. TSMesh::~TSMesh()
  1009. {
  1010. SAFE_DELETE( mOptTree );
  1011. SAFE_DELETE( mOpMeshInterface );
  1012. SAFE_DELETE_ARRAY( mOpTris );
  1013. SAFE_DELETE_ARRAY( mOpPoints );
  1014. mNumVerts = 0;
  1015. }
  1016. //-----------------------------------------------------
  1017. // TSSkinMesh methods
  1018. //-----------------------------------------------------
  1019. void TSSkinMesh::updateSkin( const Vector<MatrixF> &transforms, TSVertexBufferHandle &instanceVB, GFXPrimitiveBufferHandle &instancePB )
  1020. {
  1021. PROFILE_SCOPE( TSSkinMesh_UpdateSkin );
  1022. AssertFatal(batchDataInitialized, "Batch data not initialized. Call createBatchData() before any skin update is called.");
  1023. // set arrays
  1024. #if defined(TORQUE_MAX_LIB)
  1025. verts.setSize(batchData.initialVerts.size());
  1026. norms.setSize(batchData.initialNorms.size());
  1027. #else
  1028. if ( !batchDataInitialized && encodedNorms.size() )
  1029. {
  1030. // we co-opt responsibility for updating encoded normals from mesh
  1031. gNormalStore.setSize( vertsPerFrame );
  1032. for ( S32 i = 0; i < vertsPerFrame; i++ )
  1033. gNormalStore[i] = decodeNormal( encodedNorms[i] );
  1034. batchData.initialNorms.set( gNormalStore.address(), vertsPerFrame );
  1035. }
  1036. #endif
  1037. static Vector<MatrixF> sBoneTransforms;
  1038. sBoneTransforms.setSize( batchData.nodeIndex.size() );
  1039. // set up bone transforms
  1040. PROFILE_START(TSSkinMesh_UpdateTransforms);
  1041. for( S32 i=0; i<batchData.nodeIndex.size(); i++ )
  1042. {
  1043. S32 node = batchData.nodeIndex[i];
  1044. sBoneTransforms[i].mul( transforms[node], batchData.initialTransforms[i] );
  1045. }
  1046. const MatrixF * matrices = &sBoneTransforms[0];
  1047. PROFILE_END();
  1048. // Perform skinning
  1049. const bool bBatchByVert = !batchData.vertexBatchOperations.empty();
  1050. if(bBatchByVert)
  1051. {
  1052. const Point3F *inVerts = &batchData.initialVerts[0];
  1053. const Point3F *inNorms = &batchData.initialNorms[0];
  1054. Point3F srcVtx, srcNrm;
  1055. AssertFatal( batchData.vertexBatchOperations.size() == batchData.initialVerts.size(), "Assumption failed!" );
  1056. register Point3F skinnedVert;
  1057. register Point3F skinnedNorm;
  1058. for( Vector<BatchData::BatchedVertex>::const_iterator itr = batchData.vertexBatchOperations.begin();
  1059. itr != batchData.vertexBatchOperations.end(); itr++ )
  1060. {
  1061. const BatchData::BatchedVertex &curVert = *itr;
  1062. skinnedVert.zero();
  1063. skinnedNorm.zero();
  1064. for( S32 tOp = 0; tOp < curVert.transformCount; tOp++ )
  1065. {
  1066. const BatchData::TransformOp &transformOp = curVert.transform[tOp];
  1067. const MatrixF& deltaTransform = matrices[transformOp.transformIndex];
  1068. deltaTransform.mulP( inVerts[curVert.vertexIndex], &srcVtx );
  1069. skinnedVert += ( srcVtx * transformOp.weight );
  1070. deltaTransform.mulV( inNorms[curVert.vertexIndex], &srcNrm );
  1071. skinnedNorm += srcNrm * transformOp.weight;
  1072. }
  1073. // Assign results
  1074. __TSMeshVertexBase &dest = mVertexData[curVert.vertexIndex];
  1075. dest.vert(skinnedVert);
  1076. dest.normal(skinnedNorm);
  1077. }
  1078. }
  1079. else // Batch by transform
  1080. {
  1081. U8 *outPtr = reinterpret_cast<U8 *>(mVertexData.address());
  1082. dsize_t outStride = mVertexData.vertSize();
  1083. #if defined(USE_MEM_VERTEX_BUFFERS)
  1084. // Initialize it if NULL.
  1085. // Skinning includes readbacks from memory (argh) so don't allocate with PAGE_WRITECOMBINE
  1086. if( instanceVB.isNull() )
  1087. instanceVB.set( GFX, outStride, mVertexFormat, mNumVerts, GFXBufferTypeDynamic );
  1088. // Grow if needed
  1089. if( instanceVB.getPointer()->mNumVerts < mNumVerts )
  1090. instanceVB.resize( mNumVerts );
  1091. // Lock, and skin directly into the final memory destination
  1092. outPtr = (U8 *)instanceVB.lock();
  1093. if(!outPtr) return;
  1094. #endif
  1095. // Set position/normal to zero so we can accumulate
  1096. zero_vert_normal_bulk(mNumVerts, outPtr, outStride);
  1097. // Iterate over transforms, and perform batch transform x skin_vert
  1098. for(Vector<S32>::const_iterator itr = batchData.transformKeys.begin();
  1099. itr != batchData.transformKeys.end(); itr++)
  1100. {
  1101. const S32 boneXfmIdx = *itr;
  1102. const BatchData::BatchedTransform &curTransform = *batchData.transformBatchOperations.retreive(boneXfmIdx);
  1103. const MatrixF &curBoneMat = matrices[boneXfmIdx];
  1104. const S32 numVerts = curTransform.numElements;
  1105. // Bulk transform points/normals by this transform
  1106. m_matF_x_BatchedVertWeightList(curBoneMat, numVerts, curTransform.alignedMem,
  1107. outPtr, outStride);
  1108. }
  1109. #if defined(USE_MEM_VERTEX_BUFFERS)
  1110. instanceVB.unlock();
  1111. #endif
  1112. }
  1113. }
  1114. S32 QSORT_CALLBACK _sort_BatchedVertWeight( const void *a, const void *b )
  1115. {
  1116. // Sort by vertex index
  1117. const TSSkinMesh::BatchData::BatchedVertWeight &_a = *reinterpret_cast<const TSSkinMesh::BatchData::BatchedVertWeight *>(a);
  1118. const TSSkinMesh::BatchData::BatchedVertWeight &_b = *reinterpret_cast<const TSSkinMesh::BatchData::BatchedVertWeight *>(b);
  1119. return ( _a.vidx - _b.vidx );
  1120. }
  1121. // Batch by vertex is useful to emulate the old skinning, or to build batch data
  1122. // sutable for GPU skinning.
  1123. //#define _BATCH_BY_VERTEX
  1124. void TSSkinMesh::createBatchData()
  1125. {
  1126. if(batchDataInitialized)
  1127. return;
  1128. batchDataInitialized = true;
  1129. S32 * curVtx = vertexIndex.begin();
  1130. S32 * curBone = boneIndex.begin();
  1131. F32 * curWeight = weight.begin();
  1132. const S32 * endVtx = vertexIndex.end();
  1133. // Temp vector to build batch operations
  1134. Vector<BatchData::BatchedVertex> batchOperations;
  1135. bool issuedWeightWarning = false;
  1136. // Build the batch operations
  1137. while( curVtx != endVtx )
  1138. {
  1139. const S32 vidx = *curVtx;
  1140. ++curVtx;
  1141. const S32 midx = *curBone;
  1142. ++curBone;
  1143. const F32 w = *curWeight;
  1144. ++curWeight;
  1145. // Ignore empty weights
  1146. if ( vidx < 0 || midx < 0 || w == 0 )
  1147. continue;
  1148. if( !batchOperations.empty() &&
  1149. batchOperations.last().vertexIndex == vidx )
  1150. {
  1151. AssertFatal( batchOperations.last().transformCount > 0, "Not sure how this happened!" );
  1152. S32 opIdx = batchOperations.last().transformCount++;
  1153. // Limit the number of weights per bone (keep the N largest influences)
  1154. if ( opIdx >= TSSkinMesh::BatchData::maxBonePerVert )
  1155. {
  1156. if ( !issuedWeightWarning )
  1157. {
  1158. issuedWeightWarning = true;
  1159. Con::warnf( "At least one vertex has too many bone weights - limiting "
  1160. "to the largest %d influences (see maxBonePerVert in tsMesh.h).",
  1161. TSSkinMesh::BatchData::maxBonePerVert );
  1162. }
  1163. // Too many weights => find and replace the smallest one
  1164. S32 minIndex = 0;
  1165. F32 minWeight = batchOperations.last().transform[0].weight;
  1166. for ( S32 i = 1; i < batchOperations.last().transformCount; i++ )
  1167. {
  1168. if ( batchOperations.last().transform[i].weight < minWeight )
  1169. {
  1170. minWeight = batchOperations.last().transform[i].weight;
  1171. minIndex = i;
  1172. }
  1173. }
  1174. opIdx = minIndex;
  1175. batchOperations.last().transformCount = TSSkinMesh::BatchData::maxBonePerVert;
  1176. }
  1177. batchOperations.last().transform[opIdx].transformIndex = midx;
  1178. batchOperations.last().transform[opIdx].weight = w;
  1179. }
  1180. else
  1181. {
  1182. batchOperations.increment();
  1183. batchOperations.last().vertexIndex = vidx;
  1184. batchOperations.last().transformCount = 1;
  1185. batchOperations.last().transform[0].transformIndex = midx;
  1186. batchOperations.last().transform[0].weight = w;
  1187. }
  1188. //Con::printf( "[%d] transform idx %d, weight %1.5f", vidx, midx, w );
  1189. }
  1190. //Con::printf("End skin update");
  1191. // Normalize vertex weights (force weights for each vert to sum to 1)
  1192. if ( issuedWeightWarning )
  1193. {
  1194. for ( S32 i = 0; i < batchOperations.size(); i++ )
  1195. {
  1196. BatchData::BatchedVertex& batchOp = batchOperations[i];
  1197. // Sum weights for this vertex
  1198. F32 invTotalWeight = 0;
  1199. for ( S32 j = 0; j < batchOp.transformCount; j++ )
  1200. invTotalWeight += batchOp.transform[j].weight;
  1201. // Then normalize the vertex weights
  1202. invTotalWeight = 1.0f / invTotalWeight;
  1203. for ( S32 j = 0; j < batchOp.transformCount; j++ )
  1204. batchOp.transform[j].weight *= invTotalWeight;
  1205. }
  1206. }
  1207. #ifdef _BATCH_BY_VERTEX
  1208. // Copy data to member, and be done
  1209. batchData.vertexBatchOperations.set(batchOperations.address(), batchOperations.size());
  1210. // Convert to batch-by-transform, which is better for CPU skinning,
  1211. // where-as GPU skinning would data for batch-by-vertex operation
  1212. #else
  1213. // Iterate the batch-by-vertex, and populate the batch-by-transform structs
  1214. for( Vector<BatchData::BatchedVertex>::const_iterator itr = batchOperations.begin();
  1215. itr != batchOperations.end(); itr++ )
  1216. {
  1217. const BatchData::BatchedVertex &curTransform = *itr;
  1218. for( S32 i = 0; i < curTransform.transformCount; i++ )
  1219. {
  1220. const BatchData::TransformOp &transformOp = curTransform.transform[i];
  1221. // Find the proper batched transform, and add this vertex/weight to the
  1222. // list of verts affected by the transform
  1223. BatchData::BatchedTransform *bt = batchData.transformBatchOperations.retreive(transformOp.transformIndex);
  1224. if(!bt)
  1225. {
  1226. bt = new BatchData::BatchedTransform;
  1227. batchData.transformBatchOperations.insert(bt, transformOp.transformIndex);
  1228. bt->_tmpVec = new Vector<BatchData::BatchedVertWeight>;
  1229. batchData.transformKeys.push_back(transformOp.transformIndex);
  1230. }
  1231. bt->_tmpVec->increment();
  1232. BatchData::BatchedVertWeight& tempLast = bt->_tmpVec->last();
  1233. tempLast.vert = batchData.initialVerts[curTransform.vertexIndex];
  1234. tempLast.normal = batchData.initialNorms[curTransform.vertexIndex];
  1235. tempLast.weight = transformOp.weight;
  1236. tempLast.vidx = curTransform.vertexIndex;
  1237. }
  1238. }
  1239. // Now iterate the resulting operations and convert the vectors to aligned
  1240. // memory locations
  1241. const S32 numBatchOps = batchData.transformKeys.size();
  1242. for(S32 i = 0; i < numBatchOps; i++)
  1243. {
  1244. BatchData::BatchedTransform &curTransform = *batchData.transformBatchOperations.retreive(batchData.transformKeys[i]);
  1245. const S32 numVerts = curTransform._tmpVec->size();
  1246. // Allocate a chunk of aligned memory and copy in values
  1247. curTransform.numElements = numVerts;
  1248. curTransform.alignedMem = reinterpret_cast<BatchData::BatchedVertWeight *>(dMalloc_aligned(sizeof(BatchData::BatchedVertWeight) * numVerts, 16));
  1249. AssertFatal(curTransform.alignedMem, "Aligned malloc failed! Debug!");
  1250. constructArrayInPlace(curTransform.alignedMem, numVerts);
  1251. dMemcpy(curTransform.alignedMem, curTransform._tmpVec->address(), numVerts * sizeof(BatchData::BatchedVertWeight));
  1252. // Now free the vector memory
  1253. delete curTransform._tmpVec;
  1254. curTransform._tmpVec = NULL;
  1255. }
  1256. // Now sort the batch data so that the skin function writes close to linear output
  1257. for(S32 i = 0; i < numBatchOps; i++)
  1258. {
  1259. BatchData::BatchedTransform &curTransform = *batchData.transformBatchOperations.retreive(batchData.transformKeys[i]);
  1260. dQsort(curTransform.alignedMem, curTransform.numElements, sizeof(BatchData::BatchedVertWeight), _sort_BatchedVertWeight);
  1261. }
  1262. #endif
  1263. }
  1264. void TSSkinMesh::render( TSVertexBufferHandle &instanceVB, GFXPrimitiveBufferHandle &instancePB )
  1265. {
  1266. innerRender( instanceVB, instancePB );
  1267. }
  1268. void TSSkinMesh::render( TSMaterialList *materials,
  1269. const TSRenderState &rdata,
  1270. bool isSkinDirty,
  1271. const Vector<MatrixF> &transforms,
  1272. TSVertexBufferHandle &vertexBuffer,
  1273. GFXPrimitiveBufferHandle &primitiveBuffer )
  1274. {
  1275. PROFILE_SCOPE(TSSkinMesh_render);
  1276. if( mNumVerts == 0 )
  1277. return;
  1278. // Initialize the vertex data if it needs it
  1279. if(!mVertexData.isReady() )
  1280. _convertToAlignedMeshData(mVertexData, batchData.initialVerts, batchData.initialNorms);
  1281. AssertFatal(mVertexData.size() == mNumVerts, "Vert # mismatch");
  1282. // Initialize the skin batch if that isn't ready
  1283. if(!batchDataInitialized)
  1284. createBatchData();
  1285. const bool vertsChanged = vertexBuffer.isNull() || vertexBuffer->mNumVerts != mNumVerts;
  1286. const bool primsChanged = primitiveBuffer.isNull() || primitiveBuffer->mIndexCount != indices.size();
  1287. if ( primsChanged || vertsChanged || isSkinDirty )
  1288. {
  1289. // Perform skinning
  1290. updateSkin( transforms, vertexBuffer, primitiveBuffer );
  1291. // Update GFX vertex buffer
  1292. _createVBIB( vertexBuffer, primitiveBuffer );
  1293. }
  1294. // render...
  1295. innerRender( materials, rdata, vertexBuffer, primitiveBuffer );
  1296. }
  1297. bool TSSkinMesh::buildPolyList( S32 frame, AbstractPolyList *polyList, U32 &surfaceKey, TSMaterialList *materials )
  1298. {
  1299. // UpdateSkin() here may not be needed...
  1300. // we don't capture skinned
  1301. // verts in the polylist.
  1302. // update verts and normals...
  1303. //if( !smGlowPass && !smRefractPass )
  1304. // updateSkin();
  1305. // render...
  1306. //Parent::buildPolyList( frame,polyList,surfaceKey, materials );
  1307. return false;
  1308. }
  1309. bool TSSkinMesh::castRay( S32 frame, const Point3F &start, const Point3F &end, RayInfo *rayInfo, TSMaterialList *materials )
  1310. {
  1311. TORQUE_UNUSED(frame);
  1312. TORQUE_UNUSED(start);
  1313. TORQUE_UNUSED(end);
  1314. TORQUE_UNUSED(rayInfo);
  1315. TORQUE_UNUSED(materials);
  1316. return false;
  1317. }
  1318. bool TSSkinMesh::buildConvexHull()
  1319. {
  1320. return false; // no error, but we don't do anything either...
  1321. }
  1322. void TSSkinMesh::computeBounds( const MatrixF &transform, Box3F &bounds, S32 frame, Point3F *center, F32 *radius )
  1323. {
  1324. TORQUE_UNUSED(frame);
  1325. if (frame < 0)
  1326. {
  1327. // Use unskinned verts
  1328. TSMesh::computeBounds( batchData.initialVerts.address(), batchData.initialVerts.size(), sizeof(Point3F), transform, bounds, center, radius );
  1329. }
  1330. else
  1331. {
  1332. Point3F *vertStart = reinterpret_cast<Point3F *>(mVertexData.address());
  1333. TSMesh::computeBounds( vertStart, mVertexData.size(), mVertexData.vertSize(), transform, bounds, center, radius );
  1334. }
  1335. }
  1336. //-----------------------------------------------------
  1337. // encoded normals
  1338. //-----------------------------------------------------
  1339. const Point3F TSMesh::smU8ToNormalTable[] =
  1340. {
  1341. Point3F( 0.565061f, -0.270644f, -0.779396f ),
  1342. Point3F( -0.309804f, -0.731114f, 0.607860f ),
  1343. Point3F( -0.867412f, 0.472957f, 0.154619f ),
  1344. Point3F( -0.757488f, 0.498188f, -0.421925f ),
  1345. Point3F( 0.306834f, -0.915340f, 0.260778f ),
  1346. Point3F( 0.098754f, 0.639153f, -0.762713f ),
  1347. Point3F( 0.713706f, -0.558862f, -0.422252f ),
  1348. Point3F( -0.890431f, -0.407603f, -0.202466f ),
  1349. Point3F( 0.848050f, -0.487612f, -0.207475f ),
  1350. Point3F( -0.232226f, 0.776855f, 0.585293f ),
  1351. Point3F( -0.940195f, 0.304490f, -0.152706f ),
  1352. Point3F( 0.602019f, -0.491878f, -0.628991f ),
  1353. Point3F( -0.096835f, -0.494354f, -0.863850f ),
  1354. Point3F( 0.026630f, -0.323659f, -0.945799f ),
  1355. Point3F( 0.019208f, 0.909386f, 0.415510f ),
  1356. Point3F( 0.854440f, 0.491730f, 0.167731f ),
  1357. Point3F( -0.418835f, 0.866521f, -0.271512f ),
  1358. Point3F( 0.465024f, 0.409667f, 0.784809f ),
  1359. Point3F( -0.674391f, -0.691087f, -0.259992f ),
  1360. Point3F( 0.303858f, -0.869270f, -0.389922f ),
  1361. Point3F( 0.991333f, 0.090061f, -0.095640f ),
  1362. Point3F( -0.275924f, -0.369550f, 0.887298f ),
  1363. Point3F( 0.426545f, -0.465962f, 0.775202f ),
  1364. Point3F( -0.482741f, -0.873278f, -0.065920f ),
  1365. Point3F( 0.063616f, 0.932012f, -0.356800f ),
  1366. Point3F( 0.624786f, -0.061315f, 0.778385f ),
  1367. Point3F( -0.530300f, 0.416850f, 0.738253f ),
  1368. Point3F( 0.312144f, -0.757028f, -0.573999f ),
  1369. Point3F( 0.399288f, -0.587091f, -0.704197f ),
  1370. Point3F( -0.132698f, 0.482877f, 0.865576f ),
  1371. Point3F( 0.950966f, 0.306530f, 0.041268f ),
  1372. Point3F( -0.015923f, -0.144300f, 0.989406f ),
  1373. Point3F( -0.407522f, -0.854193f, 0.322925f ),
  1374. Point3F( -0.932398f, 0.220464f, 0.286408f ),
  1375. Point3F( 0.477509f, 0.876580f, 0.059936f ),
  1376. Point3F( 0.337133f, 0.932606f, -0.128796f ),
  1377. Point3F( -0.638117f, 0.199338f, 0.743687f ),
  1378. Point3F( -0.677454f, 0.445349f, 0.585423f ),
  1379. Point3F( -0.446715f, 0.889059f, -0.100099f ),
  1380. Point3F( -0.410024f, 0.909168f, 0.072759f ),
  1381. Point3F( 0.708462f, 0.702103f, -0.071641f ),
  1382. Point3F( -0.048801f, -0.903683f, -0.425411f ),
  1383. Point3F( -0.513681f, -0.646901f, 0.563606f ),
  1384. Point3F( -0.080022f, 0.000676f, -0.996793f ),
  1385. Point3F( 0.066966f, -0.991150f, -0.114615f ),
  1386. Point3F( -0.245220f, 0.639318f, -0.728793f ),
  1387. Point3F( 0.250978f, 0.855979f, 0.452006f ),
  1388. Point3F( -0.123547f, 0.982443f, -0.139791f ),
  1389. Point3F( -0.794825f, 0.030254f, -0.606084f ),
  1390. Point3F( -0.772905f, 0.547941f, 0.319967f ),
  1391. Point3F( 0.916347f, 0.369614f, -0.153928f ),
  1392. Point3F( -0.388203f, 0.105395f, 0.915527f ),
  1393. Point3F( -0.700468f, -0.709334f, 0.078677f ),
  1394. Point3F( -0.816193f, 0.390455f, 0.425880f ),
  1395. Point3F( -0.043007f, 0.769222f, -0.637533f ),
  1396. Point3F( 0.911444f, 0.113150f, 0.395560f ),
  1397. Point3F( 0.845801f, 0.156091f, -0.510153f ),
  1398. Point3F( 0.829801f, -0.029340f, 0.557287f ),
  1399. Point3F( 0.259529f, 0.416263f, 0.871418f ),
  1400. Point3F( 0.231128f, -0.845982f, 0.480515f ),
  1401. Point3F( -0.626203f, -0.646168f, 0.436277f ),
  1402. Point3F( -0.197047f, -0.065791f, 0.978184f ),
  1403. Point3F( -0.255692f, -0.637488f, -0.726794f ),
  1404. Point3F( 0.530662f, -0.844385f, -0.073567f ),
  1405. Point3F( -0.779887f, 0.617067f, -0.104899f ),
  1406. Point3F( 0.739908f, 0.113984f, 0.662982f ),
  1407. Point3F( -0.218801f, 0.930194f, -0.294729f ),
  1408. Point3F( -0.374231f, 0.818666f, 0.435589f ),
  1409. Point3F( -0.720250f, -0.028285f, 0.693137f ),
  1410. Point3F( 0.075389f, 0.415049f, 0.906670f ),
  1411. Point3F( -0.539724f, -0.106620f, 0.835063f ),
  1412. Point3F( -0.452612f, -0.754669f, -0.474991f ),
  1413. Point3F( 0.682822f, 0.581234f, -0.442629f ),
  1414. Point3F( 0.002435f, -0.618462f, -0.785811f ),
  1415. Point3F( -0.397631f, 0.110766f, -0.910835f ),
  1416. Point3F( 0.133935f, -0.985438f, 0.104754f ),
  1417. Point3F( 0.759098f, -0.608004f, 0.232595f ),
  1418. Point3F( -0.825239f, -0.256087f, 0.503388f ),
  1419. Point3F( 0.101693f, -0.565568f, 0.818408f ),
  1420. Point3F( 0.386377f, 0.793546f, -0.470104f ),
  1421. Point3F( -0.520516f, -0.840690f, 0.149346f ),
  1422. Point3F( -0.784549f, -0.479672f, 0.392935f ),
  1423. Point3F( -0.325322f, -0.927581f, -0.183735f ),
  1424. Point3F( -0.069294f, -0.428541f, 0.900861f ),
  1425. Point3F( 0.993354f, -0.115023f, -0.004288f ),
  1426. Point3F( -0.123896f, -0.700568f, 0.702747f ),
  1427. Point3F( -0.438031f, -0.120880f, -0.890795f ),
  1428. Point3F( 0.063314f, 0.813233f, 0.578484f ),
  1429. Point3F( 0.322045f, 0.889086f, -0.325289f ),
  1430. Point3F( -0.133521f, 0.875063f, -0.465228f ),
  1431. Point3F( 0.637155f, 0.564814f, 0.524422f ),
  1432. Point3F( 0.260092f, -0.669353f, 0.695930f ),
  1433. Point3F( 0.953195f, 0.040485f, -0.299634f ),
  1434. Point3F( -0.840665f, -0.076509f, 0.536124f ),
  1435. Point3F( -0.971350f, 0.202093f, 0.125047f ),
  1436. Point3F( -0.804307f, -0.396312f, -0.442749f ),
  1437. Point3F( -0.936746f, 0.069572f, 0.343027f ),
  1438. Point3F( 0.426545f, -0.465962f, 0.775202f ),
  1439. Point3F( 0.794542f, -0.227450f, 0.563000f ),
  1440. Point3F( -0.892172f, 0.091169f, -0.442399f ),
  1441. Point3F( -0.312654f, 0.541264f, 0.780564f ),
  1442. Point3F( 0.590603f, -0.735618f, -0.331743f ),
  1443. Point3F( -0.098040f, -0.986713f, 0.129558f ),
  1444. Point3F( 0.569646f, 0.283078f, -0.771603f ),
  1445. Point3F( 0.431051f, -0.407385f, -0.805129f ),
  1446. Point3F( -0.162087f, -0.938749f, -0.304104f ),
  1447. Point3F( 0.241533f, -0.359509f, 0.901341f ),
  1448. Point3F( -0.576191f, 0.614939f, 0.538380f ),
  1449. Point3F( -0.025110f, 0.085740f, 0.996001f ),
  1450. Point3F( -0.352693f, -0.198168f, 0.914515f ),
  1451. Point3F( -0.604577f, 0.700711f, 0.378802f ),
  1452. Point3F( 0.465024f, 0.409667f, 0.784809f ),
  1453. Point3F( -0.254684f, -0.030474f, -0.966544f ),
  1454. Point3F( -0.604789f, 0.791809f, 0.085259f ),
  1455. Point3F( -0.705147f, -0.399298f, 0.585943f ),
  1456. Point3F( 0.185691f, 0.017236f, -0.982457f ),
  1457. Point3F( 0.044588f, 0.973094f, 0.226052f ),
  1458. Point3F( -0.405463f, 0.642367f, 0.650357f ),
  1459. Point3F( -0.563959f, 0.599136f, -0.568319f ),
  1460. Point3F( 0.367162f, -0.072253f, -0.927347f ),
  1461. Point3F( 0.960429f, -0.213570f, -0.178783f ),
  1462. Point3F( -0.192629f, 0.906005f, 0.376893f ),
  1463. Point3F( -0.199718f, -0.359865f, -0.911378f ),
  1464. Point3F( 0.485072f, 0.121233f, -0.866030f ),
  1465. Point3F( 0.467163f, -0.874294f, 0.131792f ),
  1466. Point3F( -0.638953f, -0.716603f, 0.279677f ),
  1467. Point3F( -0.622710f, 0.047813f, -0.780990f ),
  1468. Point3F( 0.828724f, -0.054433f, -0.557004f ),
  1469. Point3F( 0.130241f, 0.991080f, 0.028245f ),
  1470. Point3F( 0.310995f, -0.950076f, -0.025242f ),
  1471. Point3F( 0.818118f, 0.275336f, 0.504850f ),
  1472. Point3F( 0.676328f, 0.387023f, 0.626733f ),
  1473. Point3F( -0.100433f, 0.495114f, -0.863004f ),
  1474. Point3F( -0.949609f, -0.240681f, -0.200786f ),
  1475. Point3F( -0.102610f, 0.261831f, -0.959644f ),
  1476. Point3F( -0.845732f, -0.493136f, 0.203850f ),
  1477. Point3F( 0.672617f, -0.738838f, 0.041290f ),
  1478. Point3F( 0.380465f, 0.875938f, 0.296613f ),
  1479. Point3F( -0.811223f, 0.262027f, -0.522742f ),
  1480. Point3F( -0.074423f, -0.775670f, -0.626736f ),
  1481. Point3F( -0.286499f, 0.755850f, -0.588735f ),
  1482. Point3F( 0.291182f, -0.276189f, -0.915933f ),
  1483. Point3F( -0.638117f, 0.199338f, 0.743687f ),
  1484. Point3F( 0.439922f, -0.864433f, -0.243359f ),
  1485. Point3F( 0.177649f, 0.206919f, 0.962094f ),
  1486. Point3F( 0.277107f, 0.948521f, 0.153361f ),
  1487. Point3F( 0.507629f, 0.661918f, -0.551523f ),
  1488. Point3F( -0.503110f, -0.579308f, -0.641313f ),
  1489. Point3F( 0.600522f, 0.736495f, -0.311364f ),
  1490. Point3F( -0.691096f, -0.715301f, -0.103592f ),
  1491. Point3F( -0.041083f, -0.858497f, 0.511171f ),
  1492. Point3F( 0.207773f, -0.480062f, -0.852274f ),
  1493. Point3F( 0.795719f, 0.464614f, 0.388543f ),
  1494. Point3F( -0.100433f, 0.495114f, -0.863004f ),
  1495. Point3F( 0.703249f, 0.065157f, -0.707951f ),
  1496. Point3F( -0.324171f, -0.941112f, 0.096024f ),
  1497. Point3F( -0.134933f, -0.940212f, 0.312722f ),
  1498. Point3F( -0.438240f, 0.752088f, -0.492249f ),
  1499. Point3F( 0.964762f, -0.198855f, 0.172311f ),
  1500. Point3F( -0.831799f, 0.196807f, 0.519015f ),
  1501. Point3F( -0.508008f, 0.819902f, 0.263986f ),
  1502. Point3F( 0.471075f, -0.001146f, 0.882092f ),
  1503. Point3F( 0.919512f, 0.246162f, -0.306435f ),
  1504. Point3F( -0.960050f, 0.279828f, -0.001187f ),
  1505. Point3F( 0.110232f, -0.847535f, -0.519165f ),
  1506. Point3F( 0.208229f, 0.697360f, 0.685806f ),
  1507. Point3F( -0.199680f, -0.560621f, 0.803637f ),
  1508. Point3F( 0.170135f, -0.679985f, -0.713214f ),
  1509. Point3F( 0.758371f, -0.494907f, 0.424195f ),
  1510. Point3F( 0.077734f, -0.755978f, 0.649965f ),
  1511. Point3F( 0.612831f, -0.672475f, 0.414987f ),
  1512. Point3F( 0.142776f, 0.836698f, -0.528726f ),
  1513. Point3F( -0.765185f, 0.635778f, 0.101382f ),
  1514. Point3F( 0.669873f, -0.419737f, 0.612447f ),
  1515. Point3F( 0.593549f, 0.194879f, 0.780847f ),
  1516. Point3F( 0.646930f, 0.752173f, 0.125368f ),
  1517. Point3F( 0.837721f, 0.545266f, -0.030127f ),
  1518. Point3F( 0.541505f, 0.768070f, 0.341820f ),
  1519. Point3F( 0.760679f, -0.365715f, -0.536301f ),
  1520. Point3F( 0.381516f, 0.640377f, 0.666605f ),
  1521. Point3F( 0.565794f, -0.072415f, -0.821361f ),
  1522. Point3F( -0.466072f, -0.401588f, 0.788356f ),
  1523. Point3F( 0.987146f, 0.096290f, 0.127560f ),
  1524. Point3F( 0.509709f, -0.688886f, -0.515396f ),
  1525. Point3F( -0.135132f, -0.988046f, -0.074192f ),
  1526. Point3F( 0.600499f, 0.476471f, -0.642166f ),
  1527. Point3F( -0.732326f, -0.275320f, -0.622815f ),
  1528. Point3F( -0.881141f, -0.470404f, 0.048078f ),
  1529. Point3F( 0.051548f, 0.601042f, 0.797553f ),
  1530. Point3F( 0.402027f, -0.763183f, 0.505891f ),
  1531. Point3F( 0.404233f, -0.208288f, 0.890624f ),
  1532. Point3F( -0.311793f, 0.343843f, 0.885752f ),
  1533. Point3F( 0.098132f, -0.937014f, 0.335223f ),
  1534. Point3F( 0.537158f, 0.830585f, -0.146936f ),
  1535. Point3F( 0.725277f, 0.298172f, -0.620538f ),
  1536. Point3F( -0.882025f, 0.342976f, -0.323110f ),
  1537. Point3F( -0.668829f, 0.424296f, -0.610443f ),
  1538. Point3F( -0.408835f, -0.476442f, -0.778368f ),
  1539. Point3F( 0.809472f, 0.397249f, -0.432375f ),
  1540. Point3F( -0.909184f, -0.205938f, -0.361903f ),
  1541. Point3F( 0.866930f, -0.347934f, -0.356895f ),
  1542. Point3F( 0.911660f, -0.141281f, -0.385897f ),
  1543. Point3F( -0.431404f, -0.844074f, -0.318480f ),
  1544. Point3F( -0.950593f, -0.073496f, 0.301614f ),
  1545. Point3F( -0.719716f, 0.626915f, -0.298305f ),
  1546. Point3F( -0.779887f, 0.617067f, -0.104899f ),
  1547. Point3F( -0.475899f, -0.542630f, 0.692151f ),
  1548. Point3F( 0.081952f, -0.157248f, -0.984153f ),
  1549. Point3F( 0.923990f, -0.381662f, -0.024025f ),
  1550. Point3F( -0.957998f, 0.120979f, -0.260008f ),
  1551. Point3F( 0.306601f, 0.227975f, -0.924134f ),
  1552. Point3F( -0.141244f, 0.989182f, 0.039601f ),
  1553. Point3F( 0.077097f, 0.186288f, -0.979466f ),
  1554. Point3F( -0.630407f, -0.259801f, 0.731499f ),
  1555. Point3F( 0.718150f, 0.637408f, 0.279233f ),
  1556. Point3F( 0.340946f, 0.110494f, 0.933567f ),
  1557. Point3F( -0.396671f, 0.503020f, -0.767869f ),
  1558. Point3F( 0.636943f, -0.245005f, 0.730942f ),
  1559. Point3F( -0.849605f, -0.518660f, -0.095724f ),
  1560. Point3F( -0.388203f, 0.105395f, 0.915527f ),
  1561. Point3F( -0.280671f, -0.776541f, -0.564099f ),
  1562. Point3F( -0.601680f, 0.215451f, -0.769131f ),
  1563. Point3F( -0.660112f, -0.632371f, -0.405412f ),
  1564. Point3F( 0.921096f, 0.284072f, 0.266242f ),
  1565. Point3F( 0.074850f, -0.300846f, 0.950731f ),
  1566. Point3F( 0.943952f, -0.067062f, 0.323198f ),
  1567. Point3F( -0.917838f, -0.254589f, 0.304561f ),
  1568. Point3F( 0.889843f, -0.409008f, 0.202219f ),
  1569. Point3F( -0.565849f, 0.753721f, -0.334246f ),
  1570. Point3F( 0.791460f, 0.555918f, -0.254060f ),
  1571. Point3F( 0.261936f, 0.703590f, -0.660568f ),
  1572. Point3F( -0.234406f, 0.952084f, 0.196444f ),
  1573. Point3F( 0.111205f, 0.979492f, -0.168014f ),
  1574. Point3F( -0.869844f, -0.109095f, -0.481113f ),
  1575. Point3F( -0.337728f, -0.269701f, -0.901777f ),
  1576. Point3F( 0.366793f, 0.408875f, -0.835634f ),
  1577. Point3F( -0.098749f, 0.261316f, 0.960189f ),
  1578. Point3F( -0.272379f, -0.847100f, 0.456324f ),
  1579. Point3F( -0.319506f, 0.287444f, -0.902935f ),
  1580. Point3F( 0.873383f, -0.294109f, 0.388203f ),
  1581. Point3F( -0.088950f, 0.710450f, 0.698104f ),
  1582. Point3F( 0.551238f, -0.786552f, 0.278340f ),
  1583. Point3F( 0.724436f, -0.663575f, -0.186712f ),
  1584. Point3F( 0.529741f, -0.606539f, 0.592861f ),
  1585. Point3F( -0.949743f, -0.282514f, 0.134809f ),
  1586. Point3F( 0.155047f, 0.419442f, -0.894443f ),
  1587. Point3F( -0.562653f, -0.329139f, -0.758346f ),
  1588. Point3F( 0.816407f, -0.576953f, 0.024576f ),
  1589. Point3F( 0.178550f, -0.950242f, -0.255266f ),
  1590. Point3F( 0.479571f, 0.706691f, 0.520192f ),
  1591. Point3F( 0.391687f, 0.559884f, -0.730145f ),
  1592. Point3F( 0.724872f, -0.205570f, -0.657496f ),
  1593. Point3F( -0.663196f, -0.517587f, -0.540624f ),
  1594. Point3F( -0.660054f, -0.122486f, -0.741165f ),
  1595. Point3F( -0.531989f, 0.374711f, -0.759328f ),
  1596. Point3F( 0.194979f, -0.059120f, 0.979024f )
  1597. };
  1598. U8 TSMesh::encodeNormal( const Point3F &normal )
  1599. {
  1600. U8 bestIndex = 0;
  1601. F32 bestDot = -10E30f;
  1602. for ( U32 i = 0; i < 256; i++ )
  1603. {
  1604. F32 dot = mDot( normal, smU8ToNormalTable[i] );
  1605. if ( dot > bestDot )
  1606. {
  1607. bestIndex = i;
  1608. bestDot = dot;
  1609. }
  1610. }
  1611. return bestIndex;
  1612. }
  1613. //-----------------------------------------------------
  1614. // TSMesh assemble from/ dissemble to memory buffer
  1615. //-----------------------------------------------------
  1616. #define tsalloc TSShape::smTSAlloc
  1617. TSMesh* TSMesh::assembleMesh( U32 meshType, bool skip )
  1618. {
  1619. static TSMesh tempStandardMesh;
  1620. static TSSkinMesh tempSkinMesh;
  1621. static TSDecalMesh tempDecalMesh;
  1622. static TSSortedMesh tempSortedMesh;
  1623. bool justSize = skip || !tsalloc.allocShape32(0); // if this returns NULL, we're just sizing memory block
  1624. // a little funny business because we pretend decals are derived from meshes
  1625. S32 * ret = NULL;
  1626. TSMesh * mesh = NULL;
  1627. TSDecalMesh * decal = NULL;
  1628. if ( justSize )
  1629. {
  1630. switch ( meshType )
  1631. {
  1632. case StandardMeshType :
  1633. {
  1634. ret = (S32*)&tempStandardMesh;
  1635. mesh = &tempStandardMesh;
  1636. tsalloc.allocShape32( sizeof(TSMesh) >> 2 );
  1637. break;
  1638. }
  1639. case SkinMeshType :
  1640. {
  1641. ret = (S32*)&tempSkinMesh;
  1642. mesh = &tempSkinMesh;
  1643. tsalloc.allocShape32( sizeof(TSSkinMesh) >> 2 );
  1644. break;
  1645. }
  1646. case DecalMeshType :
  1647. {
  1648. ret = (S32*)&tempDecalMesh;
  1649. decal = &tempDecalMesh;
  1650. tsalloc.allocShape32( sizeof(TSDecalMesh) >> 2 );
  1651. break;
  1652. }
  1653. case SortedMeshType :
  1654. {
  1655. ret = (S32*)&tempSortedMesh;
  1656. mesh = &tempSortedMesh;
  1657. tsalloc.allocShape32( sizeof(TSSortedMesh) >> 2 );
  1658. break;
  1659. }
  1660. }
  1661. }
  1662. else
  1663. {
  1664. switch ( meshType )
  1665. {
  1666. case StandardMeshType :
  1667. {
  1668. ret = tsalloc.allocShape32( sizeof(TSMesh) >> 2 );
  1669. constructInPlace( (TSMesh*)ret );
  1670. mesh = (TSMesh*)ret;
  1671. break;
  1672. }
  1673. case SkinMeshType :
  1674. {
  1675. ret = tsalloc.allocShape32( sizeof(TSSkinMesh) >> 2 );
  1676. constructInPlace( (TSSkinMesh*)ret );
  1677. mesh = (TSSkinMesh*)ret;
  1678. break;
  1679. }
  1680. case DecalMeshType :
  1681. {
  1682. ret = tsalloc.allocShape32( sizeof(TSDecalMesh) >> 2 );
  1683. constructInPlace((TSDecalMesh*)ret);
  1684. decal = (TSDecalMesh*)ret;
  1685. break;
  1686. }
  1687. case SortedMeshType :
  1688. {
  1689. ret = tsalloc.allocShape32( sizeof(TSSortedMesh) >> 2 );
  1690. constructInPlace( (TSSortedMesh*)ret );
  1691. mesh = (TSSortedMesh*)ret;
  1692. break;
  1693. }
  1694. }
  1695. }
  1696. tsalloc.setSkipMode( skip );
  1697. if ( mesh )
  1698. mesh->assemble( skip );
  1699. if ( decal )
  1700. decal->assemble( skip );
  1701. tsalloc.setSkipMode( false );
  1702. return (TSMesh*)ret;
  1703. }
  1704. void TSMesh::convertToTris( const TSDrawPrimitive *primitivesIn,
  1705. const S32 *indicesIn,
  1706. S32 numPrimIn,
  1707. S32 &numPrimOut,
  1708. S32 &numIndicesOut,
  1709. TSDrawPrimitive *primitivesOut,
  1710. S32 *indicesOut ) const
  1711. {
  1712. S32 prevMaterial = -99999;
  1713. TSDrawPrimitive * newDraw = NULL;
  1714. numPrimOut = 0;
  1715. numIndicesOut = 0;
  1716. for ( S32 i = 0; i < numPrimIn; i++ )
  1717. {
  1718. S32 newMat = primitivesIn[i].matIndex;
  1719. newMat &= ~TSDrawPrimitive::TypeMask;
  1720. U32 start = primitivesIn[i].start;
  1721. U32 prevStart = (i > 0) ? primitivesIn[i-1].start : start;
  1722. U32 numElements = primitivesIn[i].numElements;
  1723. // Add a new primitive if changing materials, or if this primitive
  1724. // indexes vertices in a different 16-bit range
  1725. if ( ( newMat != prevMaterial ) ||
  1726. ((indicesIn[prevStart] ^ indicesIn[start]) & 0xFFFF0000) )
  1727. {
  1728. if ( primitivesOut )
  1729. {
  1730. newDraw = &primitivesOut[numPrimOut];
  1731. newDraw->start = numIndicesOut;
  1732. newDraw->numElements = 0;
  1733. newDraw->matIndex = newMat | TSDrawPrimitive::Triangles;
  1734. }
  1735. numPrimOut++;
  1736. prevMaterial = newMat;
  1737. }
  1738. // gonna depend on what kind of primitive it is...
  1739. if ( (primitivesIn[i].matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles)
  1740. {
  1741. for ( S32 j = 0; j < numElements; j += 3 )
  1742. {
  1743. if ( indicesOut )
  1744. {
  1745. indicesOut[numIndicesOut + 0] = indicesIn[start + j + 0];
  1746. indicesOut[numIndicesOut + 1] = indicesIn[start + j + 1];
  1747. indicesOut[numIndicesOut + 2] = indicesIn[start + j + 2];
  1748. }
  1749. if ( newDraw )
  1750. newDraw->numElements += 3;
  1751. numIndicesOut += 3;
  1752. }
  1753. }
  1754. else
  1755. {
  1756. U32 idx0 = indicesIn[start + 0];
  1757. U32 idx1;
  1758. U32 idx2 = indicesIn[start + 1];
  1759. U32 * nextIdx = &idx1;
  1760. for ( S32 j = 2; j < numElements; j++ )
  1761. {
  1762. *nextIdx = idx2;
  1763. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  1764. idx2 = indicesIn[start + j];
  1765. if ( idx0 == idx1 || idx1 == idx2 || idx2 == idx0 )
  1766. continue;
  1767. if ( indicesOut )
  1768. {
  1769. indicesOut[numIndicesOut+0] = idx0;
  1770. indicesOut[numIndicesOut+1] = idx1;
  1771. indicesOut[numIndicesOut+2] = idx2;
  1772. }
  1773. if ( newDraw )
  1774. newDraw->numElements += 3;
  1775. numIndicesOut += 3;
  1776. }
  1777. }
  1778. }
  1779. }
  1780. void unwindStrip( const S32 * indices, S32 numElements, Vector<S32> &triIndices )
  1781. {
  1782. U32 idx0 = indices[0];
  1783. U32 idx1;
  1784. U32 idx2 = indices[1];
  1785. U32 * nextIdx = &idx1;
  1786. for ( S32 j = 2; j < numElements; j++ )
  1787. {
  1788. *nextIdx = idx2;
  1789. nextIdx = (U32*) ( (dsize_t)nextIdx ^ (dsize_t)&idx0 ^ (dsize_t)&idx1);
  1790. idx2 = indices[j];
  1791. if ( idx0 == idx1 || idx1 == idx2 || idx2 == idx0 )
  1792. continue;
  1793. triIndices.push_back( idx0 );
  1794. triIndices.push_back( idx1 );
  1795. triIndices.push_back( idx2 );
  1796. }
  1797. }
  1798. void TSMesh::convertToSingleStrip( const TSDrawPrimitive *primitivesIn,
  1799. const S32 *indicesIn,
  1800. S32 numPrimIn,
  1801. S32 &numPrimOut,
  1802. S32 &numIndicesOut,
  1803. TSDrawPrimitive *primitivesOut,
  1804. S32 *indicesOut ) const
  1805. {
  1806. S32 prevMaterial = -99999;
  1807. TSDrawPrimitive * newDraw = NULL;
  1808. TSDrawPrimitive * newTris = NULL;
  1809. Vector<S32> triIndices;
  1810. S32 curDrawOut = 0;
  1811. numPrimOut = 0;
  1812. numIndicesOut = 0;
  1813. for ( S32 i = 0; i < numPrimIn; i++ )
  1814. {
  1815. S32 newMat = primitivesIn[i].matIndex;
  1816. U32 start = primitivesIn[i].start;
  1817. U32 prevStart = (i > 0) ? primitivesIn[i-1].start : start;
  1818. U32 numElements = primitivesIn[i].numElements;
  1819. // Add a new primitive if changing materials, or if this primitive
  1820. // indexes vertices in a different 16-bit range
  1821. if ( ( newMat != prevMaterial ) ||
  1822. ((indicesIn[prevStart] ^ indicesIn[start]) & 0xFFFF0000) )
  1823. {
  1824. // before adding the new primitive, transfer triangle indices
  1825. if ( triIndices.size() )
  1826. {
  1827. if ( newTris && indicesOut )
  1828. {
  1829. newTris->start = numIndicesOut;
  1830. newTris->numElements = triIndices.size();
  1831. dMemcpy(&indicesOut[numIndicesOut],triIndices.address(),triIndices.size()*sizeof(U32));
  1832. }
  1833. numIndicesOut += triIndices.size();
  1834. triIndices.clear();
  1835. newTris = NULL;
  1836. }
  1837. if ( primitivesOut )
  1838. {
  1839. newDraw = &primitivesOut[numPrimOut];
  1840. newDraw->start = numIndicesOut;
  1841. newDraw->numElements = 0;
  1842. newDraw->matIndex = newMat;
  1843. }
  1844. numPrimOut++;
  1845. curDrawOut = 0;
  1846. prevMaterial = newMat;
  1847. }
  1848. // gonna depend on what kind of primitive it is...
  1849. // from above we know it's the same kind as the one we're building...
  1850. if ( (primitivesIn[i].matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles)
  1851. {
  1852. // triangles primitive...add to it
  1853. for ( S32 j = 0; j < numElements; j += 3 )
  1854. {
  1855. if ( indicesOut )
  1856. {
  1857. indicesOut[numIndicesOut + 0] = indicesIn[start + j + 0];
  1858. indicesOut[numIndicesOut + 1] = indicesIn[start + j + 1];
  1859. indicesOut[numIndicesOut + 2] = indicesIn[start + j + 2];
  1860. }
  1861. if ( newDraw )
  1862. newDraw->numElements += 3;
  1863. numIndicesOut += 3;
  1864. }
  1865. }
  1866. else
  1867. {
  1868. // strip primitive...
  1869. // if numElements less than smSmallestStripSize, add to triangles...
  1870. if ( numElements < smMinStripSize + 2 )
  1871. {
  1872. // put triangle indices aside until material changes...
  1873. if ( triIndices.empty() )
  1874. {
  1875. // set up for new triangle primitive and add it if we are copying data right now
  1876. if ( primitivesOut )
  1877. {
  1878. newTris = &primitivesOut[numPrimOut];
  1879. newTris->matIndex = newMat;
  1880. newTris->matIndex &= ~(TSDrawPrimitive::Triangles|TSDrawPrimitive::Strip);
  1881. newTris->matIndex |= TSDrawPrimitive::Triangles;
  1882. }
  1883. numPrimOut++;
  1884. }
  1885. unwindStrip( indicesIn + start, numElements, triIndices );
  1886. }
  1887. else
  1888. {
  1889. // strip primitive...add to it
  1890. if ( indicesOut )
  1891. {
  1892. if ( curDrawOut & 1 )
  1893. {
  1894. indicesOut[numIndicesOut + 0] = indicesOut[numIndicesOut - 1];
  1895. indicesOut[numIndicesOut + 1] = indicesOut[numIndicesOut - 1];
  1896. indicesOut[numIndicesOut + 2] = indicesIn[start];
  1897. dMemcpy(indicesOut+numIndicesOut+3,indicesIn+start,numElements*sizeof(U32));
  1898. }
  1899. else if ( curDrawOut )
  1900. {
  1901. indicesOut[numIndicesOut + 0] = indicesOut[numIndicesOut - 1];
  1902. indicesOut[numIndicesOut + 1] = indicesIn[start];
  1903. dMemcpy(indicesOut+numIndicesOut+2,indicesIn+start,numElements*sizeof(U32));
  1904. }
  1905. else
  1906. dMemcpy(indicesOut+numIndicesOut,indicesIn+start,numElements*sizeof(U32));
  1907. }
  1908. S32 added = numElements;
  1909. added += curDrawOut ? (curDrawOut&1 ? 3 : 2) : 0;
  1910. if ( newDraw )
  1911. newDraw->numElements += added;
  1912. numIndicesOut += added;
  1913. curDrawOut += added;
  1914. }
  1915. }
  1916. }
  1917. // spit out tris before leaving
  1918. // before adding the new primitive, transfer triangle indices
  1919. if ( triIndices.size() )
  1920. {
  1921. if ( newTris && indicesOut )
  1922. {
  1923. newTris->start = numIndicesOut;
  1924. newTris->numElements = triIndices.size();
  1925. dMemcpy(&indicesOut[numIndicesOut],triIndices.address(),triIndices.size()*sizeof(U32));
  1926. }
  1927. numIndicesOut += triIndices.size();
  1928. triIndices.clear();
  1929. newTris = NULL;
  1930. }
  1931. }
  1932. // this method does none of the converting that the above methods do, except that small strips are converted
  1933. // to triangle lists...
  1934. void TSMesh::leaveAsMultipleStrips( const TSDrawPrimitive *primitivesIn,
  1935. const S32 *indicesIn,
  1936. S32 numPrimIn,
  1937. S32 &numPrimOut,
  1938. S32 &numIndicesOut,
  1939. TSDrawPrimitive *primitivesOut,
  1940. S32 *indicesOut ) const
  1941. {
  1942. S32 prevMaterial = -99999;
  1943. TSDrawPrimitive * newDraw = NULL;
  1944. Vector<S32> triIndices;
  1945. numPrimOut = 0;
  1946. numIndicesOut = 0;
  1947. for ( S32 i = 0; i < numPrimIn; i++ )
  1948. {
  1949. S32 newMat = primitivesIn[i].matIndex;
  1950. U32 start = primitivesIn[i].start;
  1951. U32 prevStart = (i > 0) ? primitivesIn[i-1].start : start;
  1952. U32 numElements = primitivesIn[i].numElements;
  1953. // Add a new primitive if changing materials, or if this primitive
  1954. // indexes vertices in a different 16-bit range
  1955. if ( triIndices.size() &&
  1956. (( newMat != prevMaterial ) ||
  1957. ((indicesIn[prevStart] ^ indicesIn[start]) & 0xFFFF0000) ))
  1958. {
  1959. // material just changed and we have triangles lying around
  1960. // add primitive and indices for triangles and clear triIndices
  1961. if ( indicesOut )
  1962. {
  1963. TSDrawPrimitive * newTris = &primitivesOut[numPrimOut];
  1964. newTris->matIndex = prevMaterial;
  1965. newTris->matIndex &= ~(TSDrawPrimitive::Triangles|TSDrawPrimitive::Strip);
  1966. newTris->matIndex |= TSDrawPrimitive::Triangles;
  1967. newTris->start = numIndicesOut;
  1968. newTris->numElements = triIndices.size();
  1969. dMemcpy(&indicesOut[numIndicesOut],triIndices.address(),triIndices.size()*sizeof(U32));
  1970. }
  1971. numPrimOut++;
  1972. numIndicesOut += triIndices.size();
  1973. triIndices.clear();
  1974. }
  1975. // this is a little convoluted because this code was adapted from convertToSingleStrip
  1976. // but we will need a new primitive only if it is a triangle primitive coming in
  1977. // or we have more elements than the min strip size...
  1978. if ( (primitivesIn[i].matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles || numElements>=smMinStripSize+2)
  1979. {
  1980. if ( primitivesOut )
  1981. {
  1982. newDraw = &primitivesOut[numPrimOut];
  1983. newDraw->start = numIndicesOut;
  1984. newDraw->numElements = 0;
  1985. newDraw->matIndex = newMat;
  1986. }
  1987. numPrimOut++;
  1988. }
  1989. prevMaterial = newMat;
  1990. // gonna depend on what kind of primitive it is...
  1991. // from above we know it's the same kind as the one we're building...
  1992. if ( (primitivesIn[i].matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles)
  1993. {
  1994. // triangles primitive...add to it
  1995. for ( S32 j = 0; j < numElements; j += 3 )
  1996. {
  1997. if ( indicesOut )
  1998. {
  1999. indicesOut[numIndicesOut + 0] = indicesIn[start + j + 0];
  2000. indicesOut[numIndicesOut + 1] = indicesIn[start + j + 1];
  2001. indicesOut[numIndicesOut + 2] = indicesIn[start + j + 2];
  2002. }
  2003. if ( newDraw )
  2004. newDraw->numElements += 3;
  2005. numIndicesOut += 3;
  2006. }
  2007. }
  2008. else
  2009. {
  2010. // strip primitive...
  2011. // if numElements less than smSmallestStripSize, add to triangles...
  2012. if ( numElements < smMinStripSize + 2 )
  2013. // put triangle indices aside until material changes...
  2014. unwindStrip( indicesIn + start, numElements, triIndices );
  2015. else
  2016. {
  2017. // strip primitive...add to it
  2018. if ( indicesOut )
  2019. dMemcpy(indicesOut+numIndicesOut,indicesIn+start,numElements*sizeof(U32));
  2020. if ( newDraw )
  2021. newDraw->numElements = numElements;
  2022. numIndicesOut += numElements;
  2023. }
  2024. }
  2025. }
  2026. // spit out tris before leaving
  2027. if ( triIndices.size() )
  2028. {
  2029. // material just changed and we have triangles lying around
  2030. // add primitive and indices for triangles and clear triIndices
  2031. if ( indicesOut )
  2032. {
  2033. TSDrawPrimitive *newTris = &primitivesOut[numPrimOut];
  2034. newTris->matIndex = prevMaterial;
  2035. newTris->matIndex &= ~(TSDrawPrimitive::Triangles|TSDrawPrimitive::Strip);
  2036. newTris->matIndex |= TSDrawPrimitive::Triangles;
  2037. newTris->start = numIndicesOut;
  2038. newTris->numElements = triIndices.size();
  2039. dMemcpy(&indicesOut[numIndicesOut],triIndices.address(),triIndices.size()*sizeof(U32));
  2040. }
  2041. numPrimOut++;
  2042. numIndicesOut += triIndices.size();
  2043. triIndices.clear();
  2044. }
  2045. }
  2046. // This method retrieves data that is shared (or possibly shared) between different meshes.
  2047. // This adds an extra step to the copying of data from the memory buffer to the shape data buffer.
  2048. // If we have no parentMesh, then we either return a pointer to the data in the memory buffer
  2049. // (in the case that we skip this mesh) or copy the data into the shape data buffer and return
  2050. // that pointer (in the case that we don't skip this mesh).
  2051. // If we do have a parent mesh, then we return a pointer to the data in the shape buffer,
  2052. // copying the data in there ourselves if our parent didn't already do it (i.e., if it was skipped).
  2053. S32 * TSMesh::getSharedData32( S32 parentMesh, S32 size, S32 **source, bool skip )
  2054. {
  2055. S32 * ptr;
  2056. if( parentMesh < 0 )
  2057. ptr = skip ? tsalloc.getPointer32( size ) : tsalloc.copyToShape32( size );
  2058. else
  2059. {
  2060. ptr = source[parentMesh];
  2061. // if we skipped the previous mesh (and we're not skipping this one) then
  2062. // we still need to copy points into the shape...
  2063. if ( !smDataCopied[parentMesh] && !skip )
  2064. {
  2065. S32 * tmp = ptr;
  2066. ptr = tsalloc.allocShape32( size );
  2067. if ( ptr && tmp )
  2068. dMemcpy(ptr, tmp, size * sizeof(S32) );
  2069. }
  2070. }
  2071. return ptr;
  2072. }
  2073. S8 * TSMesh::getSharedData8( S32 parentMesh, S32 size, S8 **source, bool skip )
  2074. {
  2075. S8 * ptr;
  2076. if( parentMesh < 0 )
  2077. ptr = skip ? tsalloc.getPointer8( size ) : tsalloc.copyToShape8( size );
  2078. else
  2079. {
  2080. ptr = source[parentMesh];
  2081. // if we skipped the previous mesh (and we're not skipping this one) then
  2082. // we still need to copy points into the shape...
  2083. if ( !smDataCopied[parentMesh] && !skip )
  2084. {
  2085. S8 * tmp = ptr;
  2086. ptr = tsalloc.allocShape8( size );
  2087. if ( ptr && tmp )
  2088. dMemcpy( ptr, tmp, size * sizeof(S32) );
  2089. }
  2090. }
  2091. return ptr;
  2092. }
  2093. void TSMesh::createVBIB()
  2094. {
  2095. AssertFatal( getMeshType() != SkinMeshType, "TSMesh::createVBIB() - Invalid call for skinned mesh type!" );
  2096. _createVBIB( mVB, mPB );
  2097. }
  2098. void TSMesh::_createVBIB( TSVertexBufferHandle &vb, GFXPrimitiveBufferHandle &pb )
  2099. {
  2100. AssertFatal(mVertexData.isReady(), "Call convertToAlignedMeshData() before calling _createVBIB()");
  2101. if ( mNumVerts == 0 || !GFXDevice::devicePresent() )
  2102. return;
  2103. PROFILE_SCOPE( TSMesh_CreateVBIB );
  2104. // Number of verts can change in LOD skinned mesh
  2105. const bool vertsChanged = ( vb && vb->mNumVerts < mNumVerts );
  2106. #if defined(USE_MEM_VERTEX_BUFFERS)
  2107. if(!mDynamic)
  2108. {
  2109. #endif
  2110. // Create the vertex buffer
  2111. if( vertsChanged || vb == NULL )
  2112. vb.set( GFX, mVertSize, mVertexFormat, mNumVerts, mDynamic ?
  2113. #if defined(TORQUE_OS_XENON)
  2114. // Skinned meshes still will occasionally re-skin more than once per frame.
  2115. // This cannot happen on the Xbox360. Until this issue is resolved, use
  2116. // type volatile instead. [1/27/2010 Pat]
  2117. GFXBufferTypeVolatile : GFXBufferTypeStatic );
  2118. #else
  2119. GFXBufferTypeDynamic : GFXBufferTypeStatic );
  2120. #endif
  2121. // Copy from aligned memory right into GPU memory
  2122. U8 *vertData = (U8*)vb.lock();
  2123. if(!vertData) return;
  2124. #if defined(TORQUE_OS_XENON)
  2125. XMemCpyStreaming_WriteCombined( vertData, mVertexData.address(), mVertexData.mem_size() );
  2126. #else
  2127. dMemcpy( vertData, mVertexData.address(), mVertexData.mem_size() );
  2128. #endif
  2129. vb.unlock();
  2130. #if defined(USE_MEM_VERTEX_BUFFERS)
  2131. }
  2132. #endif
  2133. const bool primsChanged = ( pb.isValid() && pb->mIndexCount != indices.size() );
  2134. if( primsChanged || pb.isNull() )
  2135. {
  2136. // go through and create PrimitiveInfo array
  2137. Vector <GFXPrimitive> piArray;
  2138. GFXPrimitive pInfo;
  2139. U32 primitivesSize = primitives.size();
  2140. for ( U32 i = 0; i < primitivesSize; i++ )
  2141. {
  2142. const TSDrawPrimitive & draw = primitives[i];
  2143. GFXPrimitiveType drawType = getDrawType( draw.matIndex >> 30 );
  2144. switch( drawType )
  2145. {
  2146. case GFXTriangleList:
  2147. pInfo.type = drawType;
  2148. pInfo.numPrimitives = draw.numElements / 3;
  2149. pInfo.startIndex = draw.start;
  2150. // Use the first index to determine which 16-bit address space we are operating in
  2151. pInfo.startVertex = indices[draw.start] & 0xFFFF0000;
  2152. pInfo.minIndex = 0; // minIndex are zero based index relative to startVertex. See @GFXDevice
  2153. pInfo.numVertices = getMin((U32)0x10000, mNumVerts - pInfo.startVertex);
  2154. break;
  2155. case GFXTriangleStrip:
  2156. pInfo.type = drawType;
  2157. pInfo.numPrimitives = draw.numElements - 2;
  2158. pInfo.startIndex = draw.start;
  2159. // Use the first index to determine which 16-bit address space we are operating in
  2160. pInfo.startVertex = indices[draw.start] & 0xFFFF0000;
  2161. pInfo.minIndex = 0; // minIndex are zero based index relative to startVertex. See @GFXDevice
  2162. pInfo.numVertices = getMin((U32)0x10000, mNumVerts - pInfo.startVertex);
  2163. break;
  2164. default:
  2165. AssertFatal( false, "WTF?!" );
  2166. }
  2167. piArray.push_back( pInfo );
  2168. }
  2169. pb.set( GFX, indices.size(), piArray.size(), GFXBufferTypeStatic );
  2170. U16 *ibIndices = NULL;
  2171. GFXPrimitive *piInput = NULL;
  2172. pb.lock( &ibIndices, &piInput );
  2173. dCopyArray( ibIndices, indices.address(), indices.size() );
  2174. dMemcpy( piInput, piArray.address(), piArray.size() * sizeof(GFXPrimitive) );
  2175. pb.unlock();
  2176. }
  2177. }
  2178. void TSMesh::assemble( bool skip )
  2179. {
  2180. tsalloc.checkGuard();
  2181. numFrames = tsalloc.get32();
  2182. numMatFrames = tsalloc.get32();
  2183. parentMesh = tsalloc.get32();
  2184. tsalloc.get32( (S32*)&mBounds, 6 );
  2185. tsalloc.get32( (S32*)&mCenter, 3 );
  2186. mRadius = (F32)tsalloc.get32();
  2187. S32 numVerts = tsalloc.get32();
  2188. S32 *ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smVertsList.address(), skip );
  2189. verts.set( (Point3F*)ptr32, numVerts );
  2190. S32 numTVerts = tsalloc.get32();
  2191. ptr32 = getSharedData32( parentMesh, 2 * numTVerts, (S32**)smTVertsList.address(), skip );
  2192. tverts.set( (Point2F*)ptr32, numTVerts );
  2193. if ( TSShape::smReadVersion > 25 )
  2194. {
  2195. numTVerts = tsalloc.get32();
  2196. ptr32 = getSharedData32( parentMesh, 2 * numTVerts, (S32**)smTVerts2List.address(), skip );
  2197. tverts2.set( (Point2F*)ptr32, numTVerts );
  2198. S32 numVColors = tsalloc.get32();
  2199. ptr32 = getSharedData32( parentMesh, numVColors, (S32**)smColorsList.address(), skip );
  2200. colors.set( (ColorI*)ptr32, numVColors );
  2201. }
  2202. S8 *ptr8;
  2203. if ( TSShape::smReadVersion > 21 && TSMesh::smUseEncodedNormals)
  2204. {
  2205. // we have encoded normals and we want to use them...
  2206. if ( parentMesh < 0 )
  2207. tsalloc.getPointer32( numVerts * 3 ); // advance past norms, don't use
  2208. norms.set( NULL, 0 );
  2209. ptr8 = getSharedData8( parentMesh, numVerts, (S8**)smEncodedNormsList.address(), skip );
  2210. encodedNorms.set( ptr8, numVerts );
  2211. }
  2212. else if ( TSShape::smReadVersion > 21 )
  2213. {
  2214. // we have encoded normals but we don't want to use them...
  2215. ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smNormsList.address(), skip );
  2216. norms.set( (Point3F*)ptr32, numVerts );
  2217. if ( parentMesh < 0 )
  2218. tsalloc.getPointer8( numVerts ); // advance past encoded normls, don't use
  2219. encodedNorms.set( NULL, 0 );
  2220. }
  2221. else
  2222. {
  2223. // no encoded normals...
  2224. ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smNormsList.address(), skip );
  2225. norms.set( (Point3F*)ptr32, numVerts );
  2226. encodedNorms.set( NULL, 0 );
  2227. }
  2228. // copy the primitives and indices...how we do this depends on what
  2229. // form we want them in when copied...just get pointers to data for now
  2230. S32 szPrimIn, szIndIn;
  2231. TSDrawPrimitive *primIn;
  2232. S32 *indIn;
  2233. bool deleteInputArrays = false;
  2234. if (TSShape::smReadVersion > 25)
  2235. {
  2236. // mesh primitives (start, numElements) and indices are stored as 32 bit values
  2237. szPrimIn = tsalloc.get32();
  2238. primIn = (TSDrawPrimitive*)tsalloc.getPointer32(szPrimIn*3);
  2239. szIndIn = tsalloc.get32();
  2240. indIn = tsalloc.getPointer32(szIndIn);
  2241. }
  2242. else
  2243. {
  2244. // mesh primitives (start, numElements) indices are stored as 16 bit values
  2245. szPrimIn = tsalloc.get32();
  2246. S16 *prim16 = tsalloc.getPointer16(szPrimIn*2); // primitive: start, numElements
  2247. S32 *prim32 = tsalloc.getPointer32(szPrimIn); // primitive: matIndex
  2248. szIndIn = tsalloc.get32();
  2249. // warn about non-addressable indices
  2250. if ( !skip && szIndIn >= 0x10000 )
  2251. {
  2252. Con::warnf("Mesh contains non-addressable indices, and may not render "
  2253. "correctly. Either split this mesh into pieces of no more than 65k "
  2254. "unique verts prior to export, or use COLLADA.");
  2255. }
  2256. S16 *ind16 = tsalloc.getPointer16(szIndIn);
  2257. // need to copy to temporary arrays
  2258. deleteInputArrays = true;
  2259. primIn = new TSDrawPrimitive[szPrimIn];
  2260. for (S32 i = 0; i < szPrimIn; i++)
  2261. {
  2262. primIn[i].start = prim16[i*2];
  2263. primIn[i].numElements = prim16[i*2+1];
  2264. primIn[i].matIndex = prim32[i];
  2265. }
  2266. indIn = new S32[szIndIn];
  2267. dCopyArray(indIn, ind16, szIndIn);
  2268. }
  2269. // count the number of output primitives and indices
  2270. S32 szPrimOut = szPrimIn, szIndOut = szIndIn;
  2271. if (smUseTriangles)
  2272. convertToTris(primIn, indIn, szPrimIn, szPrimOut, szIndOut, NULL, NULL);
  2273. else if (smUseOneStrip)
  2274. convertToSingleStrip(primIn, indIn, szPrimIn, szPrimOut, szIndOut, NULL, NULL);
  2275. else
  2276. leaveAsMultipleStrips(primIn, indIn, szPrimIn, szPrimOut, szIndOut, NULL, NULL);
  2277. // allocate enough space for the new primitives and indices (all 32 bits)
  2278. TSDrawPrimitive *primOut = (TSDrawPrimitive*)tsalloc.allocShape32(3*szPrimOut);
  2279. S32 *indOut = tsalloc.allocShape32(szIndOut);
  2280. // copy output primitives and indices
  2281. S32 chkPrim = szPrimOut, chkInd = szIndOut;
  2282. if (smUseTriangles)
  2283. convertToTris(primIn, indIn, szPrimIn, chkPrim, chkInd, primOut, indOut);
  2284. else if (smUseOneStrip)
  2285. convertToSingleStrip(primIn, indIn, szPrimIn, chkPrim, chkInd, primOut, indOut);
  2286. else
  2287. leaveAsMultipleStrips(primIn, indIn, szPrimIn, chkPrim, chkInd, primOut, indOut);
  2288. AssertFatal(chkPrim==szPrimOut && chkInd==szIndOut,"TSMesh::primitive conversion");
  2289. // store output
  2290. primitives.set(primOut, szPrimOut);
  2291. indices.set(indOut, szIndOut);
  2292. // delete temporary arrays if necessary
  2293. if (deleteInputArrays)
  2294. {
  2295. delete [] primIn;
  2296. delete [] indIn;
  2297. }
  2298. S32 sz = tsalloc.get32();
  2299. tsalloc.getPointer16( sz ); // skip deprecated merge indices
  2300. tsalloc.align32();
  2301. vertsPerFrame = tsalloc.get32();
  2302. U32 flags = (U32)tsalloc.get32();
  2303. if ( encodedNorms.size() )
  2304. flags |= UseEncodedNormals;
  2305. setFlags( flags );
  2306. tsalloc.checkGuard();
  2307. if ( tsalloc.allocShape32( 0 ) && TSShape::smReadVersion < 19 )
  2308. computeBounds(); // only do this if we copied the data...
  2309. if(getMeshType() != SkinMeshType)
  2310. createTangents(verts, norms);
  2311. }
  2312. void TSMesh::disassemble()
  2313. {
  2314. tsalloc.setGuard();
  2315. tsalloc.set32( numFrames );
  2316. tsalloc.set32( numMatFrames );
  2317. tsalloc.set32( parentMesh );
  2318. tsalloc.copyToBuffer32( (S32*)&mBounds, 6 );
  2319. tsalloc.copyToBuffer32( (S32*)&mCenter, 3 );
  2320. tsalloc.set32( (S32)mRadius );
  2321. // Re-create the vectors
  2322. if(mVertexData.isReady())
  2323. {
  2324. verts.setSize(mNumVerts);
  2325. tverts.setSize(mNumVerts);
  2326. norms.setSize(mNumVerts);
  2327. if(mHasColor)
  2328. colors.setSize(mNumVerts);
  2329. if(mHasTVert2)
  2330. tverts2.setSize(mNumVerts);
  2331. // Fill arrays
  2332. for(U32 i = 0; i < mNumVerts; i++)
  2333. {
  2334. const __TSMeshVertexBase &cv = mVertexData[i];
  2335. verts[i] = cv.vert();
  2336. tverts[i] = cv.tvert();
  2337. norms[i] = cv.normal();
  2338. if(mHasColor)
  2339. cv.color().getColor(&colors[i]);
  2340. if(mHasTVert2)
  2341. tverts2[i] = cv.tvert2();
  2342. }
  2343. }
  2344. // verts...
  2345. tsalloc.set32( verts.size() );
  2346. if ( parentMesh < 0 )
  2347. tsalloc.copyToBuffer32( (S32*)verts.address(), 3 * verts.size() ); // if no parent mesh, then save off our verts
  2348. // tverts...
  2349. tsalloc.set32( tverts.size() );
  2350. if ( parentMesh < 0 )
  2351. tsalloc.copyToBuffer32( (S32*)tverts.address(), 2 * tverts.size() ); // if no parent mesh, then save off our tverts
  2352. if (TSShape::smVersion > 25)
  2353. {
  2354. // tverts2...
  2355. tsalloc.set32( tverts2.size() );
  2356. if ( parentMesh < 0 )
  2357. tsalloc.copyToBuffer32( (S32*)tverts2.address(), 2 * tverts2.size() ); // if no parent mesh, then save off our tverts
  2358. // colors
  2359. tsalloc.set32( colors.size() );
  2360. if ( parentMesh < 0 )
  2361. tsalloc.copyToBuffer32( (S32*)colors.address(), colors.size() ); // if no parent mesh, then save off our tverts
  2362. }
  2363. // norms...
  2364. if ( parentMesh < 0 ) // if no parent mesh, then save off our norms
  2365. tsalloc.copyToBuffer32( (S32*)norms.address(), 3 * norms.size() ); // norms.size()==verts.size() or error...
  2366. // encoded norms...
  2367. if ( parentMesh < 0 )
  2368. {
  2369. // if no parent mesh, compute encoded normals and copy over
  2370. for ( S32 i = 0; i < norms.size(); i++ )
  2371. {
  2372. U8 normIdx = encodedNorms.size() ? encodedNorms[i] : encodeNormal( norms[i] );
  2373. tsalloc.copyToBuffer8( (S8*)&normIdx, 1 );
  2374. }
  2375. }
  2376. // optimize triangle draw order during disassemble
  2377. {
  2378. FrameTemp<TriListOpt::IndexType> tmpIdxs(indices.size());
  2379. for ( S32 i = 0; i < primitives.size(); i++ )
  2380. {
  2381. const TSDrawPrimitive& prim = primitives[i];
  2382. // only optimize triangle lists (strips and fans are assumed to be already optimized)
  2383. if ( (prim.matIndex & TSDrawPrimitive::TypeMask) == TSDrawPrimitive::Triangles )
  2384. {
  2385. TriListOpt::OptimizeTriangleOrdering(verts.size(), prim.numElements,
  2386. indices.address() + prim.start, tmpIdxs.address());
  2387. dCopyArray(indices.address() + prim.start, tmpIdxs.address(),
  2388. prim.numElements);
  2389. }
  2390. }
  2391. }
  2392. if (TSShape::smVersion > 25)
  2393. {
  2394. // primitives...
  2395. tsalloc.set32( primitives.size() );
  2396. tsalloc.copyToBuffer32((S32*)primitives.address(),3*primitives.size());
  2397. // indices...
  2398. tsalloc.set32(indices.size());
  2399. tsalloc.copyToBuffer32((S32*)indices.address(),indices.size());
  2400. }
  2401. else
  2402. {
  2403. // primitives
  2404. tsalloc.set32( primitives.size() );
  2405. for (S32 i=0; i<primitives.size(); i++)
  2406. {
  2407. S16 start = (S16)primitives[i].start;
  2408. S16 numElements = (S16)primitives[i].numElements;
  2409. tsalloc.copyToBuffer16(&start, 1);
  2410. tsalloc.copyToBuffer16(&numElements, 1);
  2411. tsalloc.copyToBuffer32(&(primitives[i].matIndex), 1);
  2412. }
  2413. // indices
  2414. tsalloc.set32(indices.size());
  2415. Vector<S16> s16_indices(indices.size());
  2416. for (S32 i=0; i<indices.size(); i++)
  2417. s16_indices.push_back((S16)indices[i]);
  2418. tsalloc.copyToBuffer16(s16_indices.address(), s16_indices.size());
  2419. }
  2420. // merge indices...DEPRECATED
  2421. tsalloc.set32( 0 );
  2422. // small stuff...
  2423. tsalloc.set32( vertsPerFrame );
  2424. tsalloc.set32( getFlags() );
  2425. tsalloc.setGuard();
  2426. }
  2427. //-----------------------------------------------------------------------------
  2428. // TSSkinMesh assemble from/ dissemble to memory buffer
  2429. //-----------------------------------------------------------------------------
  2430. void TSSkinMesh::assemble( bool skip )
  2431. {
  2432. // avoid a crash on computeBounds...
  2433. batchData.initialVerts.set( NULL, 0 );
  2434. TSMesh::assemble( skip );
  2435. S32 sz = tsalloc.get32();
  2436. S32 numVerts = sz;
  2437. S32 * ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smVertsList.address(), skip );
  2438. batchData.initialVerts.set( (Point3F*)ptr32, sz );
  2439. S8 * ptr8;
  2440. if ( TSShape::smReadVersion>21 && TSMesh::smUseEncodedNormals )
  2441. {
  2442. // we have encoded normals and we want to use them...
  2443. if ( parentMesh < 0 )
  2444. tsalloc.getPointer32( numVerts * 3 ); // advance past norms, don't use
  2445. batchData.initialNorms.set( NULL, 0 );
  2446. ptr8 = getSharedData8( parentMesh, numVerts, (S8**)smEncodedNormsList.address(), skip );
  2447. encodedNorms.set( ptr8, numVerts );
  2448. // Note: we don't set the encoded normals flag because we handle them in updateSkin and
  2449. // hide the fact that we are using them from base class (TSMesh)
  2450. }
  2451. else if ( TSShape::smReadVersion > 21 )
  2452. {
  2453. // we have encoded normals but we don't want to use them...
  2454. ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smNormsList.address(), skip );
  2455. batchData.initialNorms.set( (Point3F*)ptr32, numVerts );
  2456. if ( parentMesh < 0 )
  2457. tsalloc.getPointer8( numVerts ); // advance past encoded normls, don't use
  2458. encodedNorms.set( NULL, 0 );
  2459. }
  2460. else
  2461. {
  2462. // no encoded normals...
  2463. ptr32 = getSharedData32( parentMesh, 3 * numVerts, (S32**)smNormsList.address(), skip );
  2464. batchData.initialNorms.set( (Point3F*)ptr32, numVerts );
  2465. encodedNorms.set( NULL, 0 );
  2466. }
  2467. sz = tsalloc.get32();
  2468. ptr32 = getSharedData32( parentMesh, 16 * sz, (S32**)smInitTransformList.address(), skip );
  2469. batchData.initialTransforms.set( ptr32, sz );
  2470. sz = tsalloc.get32();
  2471. ptr32 = getSharedData32( parentMesh, sz, (S32**)smVertexIndexList.address(), skip );
  2472. vertexIndex.set( ptr32, sz );
  2473. ptr32 = getSharedData32( parentMesh, sz, (S32**)smBoneIndexList.address(), skip );
  2474. boneIndex.set( ptr32, sz );
  2475. ptr32 = getSharedData32( parentMesh, sz, (S32**)smWeightList.address(), skip );
  2476. weight.set( (F32*)ptr32, sz );
  2477. sz = tsalloc.get32();
  2478. ptr32 = getSharedData32( parentMesh, sz, (S32**)smNodeIndexList.address(), skip );
  2479. batchData.nodeIndex.set( ptr32, sz );
  2480. tsalloc.checkGuard();
  2481. if ( tsalloc.allocShape32( 0 ) && TSShape::smReadVersion < 19 )
  2482. TSMesh::computeBounds(); // only do this if we copied the data...
  2483. createTangents(batchData.initialVerts, batchData.initialNorms);
  2484. }
  2485. //-----------------------------------------------------------------------------
  2486. // disassemble
  2487. //-----------------------------------------------------------------------------
  2488. void TSSkinMesh::disassemble()
  2489. {
  2490. TSMesh::disassemble();
  2491. tsalloc.set32( batchData.initialVerts.size() );
  2492. // if we have no parent mesh, then save off our verts & norms
  2493. if ( parentMesh < 0 )
  2494. {
  2495. tsalloc.copyToBuffer32( (S32*)batchData.initialVerts.address(), 3 * batchData.initialVerts.size() );
  2496. // no longer do this here...let tsmesh handle this
  2497. tsalloc.copyToBuffer32( (S32*)batchData.initialNorms.address(), 3 * batchData.initialNorms.size() );
  2498. // if no parent mesh, compute encoded normals and copy over
  2499. for ( S32 i = 0; i < batchData.initialNorms.size(); i++ )
  2500. {
  2501. U8 normIdx = encodedNorms.size() ? encodedNorms[i] : encodeNormal( batchData.initialNorms[i] );
  2502. tsalloc.copyToBuffer8( (S8*)&normIdx, 1 );
  2503. }
  2504. }
  2505. tsalloc.set32( batchData.initialTransforms.size() );
  2506. if ( parentMesh < 0 )
  2507. tsalloc.copyToBuffer32( (S32*)batchData.initialTransforms.address(), batchData.initialTransforms.size() * 16 );
  2508. tsalloc.set32( vertexIndex.size() );
  2509. if ( parentMesh < 0 )
  2510. {
  2511. tsalloc.copyToBuffer32( (S32*)vertexIndex.address(), vertexIndex.size() );
  2512. tsalloc.copyToBuffer32( (S32*)boneIndex.address(), boneIndex.size() );
  2513. tsalloc.copyToBuffer32( (S32*)weight.address(), weight.size() );
  2514. }
  2515. tsalloc.set32( batchData.nodeIndex.size() );
  2516. if ( parentMesh < 0 )
  2517. tsalloc.copyToBuffer32( (S32*)batchData.nodeIndex.address(), batchData.nodeIndex.size() );
  2518. tsalloc.setGuard();
  2519. }
  2520. TSSkinMesh::TSSkinMesh()
  2521. {
  2522. meshType = SkinMeshType;
  2523. mDynamic = true;
  2524. batchDataInitialized = false;
  2525. }
  2526. //-----------------------------------------------------------------------------
  2527. // find tangent vector
  2528. //-----------------------------------------------------------------------------
  2529. inline void TSMesh::findTangent( U32 index1,
  2530. U32 index2,
  2531. U32 index3,
  2532. Point3F *tan0,
  2533. Point3F *tan1,
  2534. const Vector<Point3F> &_verts)
  2535. {
  2536. const Point3F &v1 = _verts[index1];
  2537. const Point3F &v2 = _verts[index2];
  2538. const Point3F &v3 = _verts[index3];
  2539. const Point2F &w1 = tverts[index1];
  2540. const Point2F &w2 = tverts[index2];
  2541. const Point2F &w3 = tverts[index3];
  2542. F32 x1 = v2.x - v1.x;
  2543. F32 x2 = v3.x - v1.x;
  2544. F32 y1 = v2.y - v1.y;
  2545. F32 y2 = v3.y - v1.y;
  2546. F32 z1 = v2.z - v1.z;
  2547. F32 z2 = v3.z - v1.z;
  2548. F32 s1 = w2.x - w1.x;
  2549. F32 s2 = w3.x - w1.x;
  2550. F32 t1 = w2.y - w1.y;
  2551. F32 t2 = w3.y - w1.y;
  2552. F32 denom = (s1 * t2 - s2 * t1);
  2553. if( mFabs( denom ) < 0.0001f )
  2554. {
  2555. // handle degenerate triangles from strips
  2556. if (denom<0) denom = -0.0001f;
  2557. else denom = 0.0001f;
  2558. }
  2559. F32 r = 1.0f / denom;
  2560. Point3F sdir( (t2 * x1 - t1 * x2) * r,
  2561. (t2 * y1 - t1 * y2) * r,
  2562. (t2 * z1 - t1 * z2) * r );
  2563. Point3F tdir( (s1 * x2 - s2 * x1) * r,
  2564. (s1 * y2 - s2 * y1) * r,
  2565. (s1 * z2 - s2 * z1) * r );
  2566. tan0[index1] += sdir;
  2567. tan1[index1] += tdir;
  2568. tan0[index2] += sdir;
  2569. tan1[index2] += tdir;
  2570. tan0[index3] += sdir;
  2571. tan1[index3] += tdir;
  2572. }
  2573. //-----------------------------------------------------------------------------
  2574. // create array of tangent vectors
  2575. //-----------------------------------------------------------------------------
  2576. void TSMesh::createTangents(const Vector<Point3F> &_verts, const Vector<Point3F> &_norms)
  2577. {
  2578. U32 numVerts = _verts.size();
  2579. U32 numNorms = _norms.size();
  2580. if ( numVerts <= 0 || numNorms <= 0 )
  2581. return;
  2582. if( numVerts != numNorms)
  2583. return;
  2584. Vector<Point3F> tan0;
  2585. tan0.setSize( numVerts * 2 );
  2586. Point3F *tan1 = tan0.address() + numVerts;
  2587. dMemset( tan0.address(), 0, sizeof(Point3F) * 2 * numVerts );
  2588. U32 numPrimatives = primitives.size();
  2589. for (S32 i = 0; i < numPrimatives; i++ )
  2590. {
  2591. const TSDrawPrimitive & draw = primitives[i];
  2592. GFXPrimitiveType drawType = getDrawType( draw.matIndex >> 30 );
  2593. U32 p1Index = 0;
  2594. U32 p2Index = 0;
  2595. U32 *baseIdx = &indices[draw.start];
  2596. const U32 numElements = (U32)draw.numElements;
  2597. switch( drawType )
  2598. {
  2599. case GFXTriangleList:
  2600. {
  2601. for( U32 j = 0; j < numElements; j += 3 )
  2602. findTangent( baseIdx[j], baseIdx[j + 1], baseIdx[j + 2], tan0.address(), tan1, _verts );
  2603. break;
  2604. }
  2605. case GFXTriangleStrip:
  2606. {
  2607. p1Index = baseIdx[0];
  2608. p2Index = baseIdx[1];
  2609. for( U32 j = 2; j < numElements; j++ )
  2610. {
  2611. findTangent( p1Index, p2Index, baseIdx[j], tan0.address(), tan1, _verts );
  2612. p1Index = p2Index;
  2613. p2Index = baseIdx[j];
  2614. }
  2615. break;
  2616. }
  2617. default:
  2618. AssertFatal( false, "TSMesh::createTangents: unknown primitive type!" );
  2619. }
  2620. }
  2621. tangents.setSize( numVerts );
  2622. // fill out final info from accumulated basis data
  2623. for( U32 i = 0; i < numVerts; i++ )
  2624. {
  2625. const Point3F &n = _norms[i];
  2626. const Point3F &t = tan0[i];
  2627. const Point3F &b = tan1[i];
  2628. Point3F tempPt = t - n * mDot( n, t );
  2629. tempPt.normalize();
  2630. tangents[i] = tempPt;
  2631. Point3F cp;
  2632. mCross( n, t, &cp );
  2633. tangents[i].w = (mDot( cp, b ) < 0.0f) ? -1.0f : 1.0f;
  2634. }
  2635. }
  2636. void TSMesh::convertToAlignedMeshData()
  2637. {
  2638. if(!mVertexData.isReady())
  2639. _convertToAlignedMeshData(mVertexData, verts, norms);
  2640. }
  2641. void TSSkinMesh::convertToAlignedMeshData()
  2642. {
  2643. if(!mVertexData.isReady())
  2644. _convertToAlignedMeshData(mVertexData, batchData.initialVerts, batchData.initialNorms);
  2645. }
  2646. void TSMesh::_convertToAlignedMeshData( TSMeshVertexArray &vertexData, const Vector<Point3F> &_verts, const Vector<Point3F> &_norms )
  2647. {
  2648. // If mVertexData is ready, and the input array is different than mVertexData
  2649. // use mVertexData to quickly initialize the input array
  2650. if(mVertexData.isReady() && vertexData.address() != mVertexData.address())
  2651. {
  2652. AssertFatal(mVertexData.size() == mNumVerts, "Vertex data length mismatch; no idea how this happened.");
  2653. // There doesn't seem to be an _mm_realloc, even though there is an _aligned_realloc
  2654. // We really shouldn't be re-allocating anyway. Should TSShapeInstance be
  2655. // storing an array of the data structures? That would certainly bloat memory.
  2656. void *aligned_mem = dMalloc_aligned(mVertSize * mNumVerts, 16);
  2657. AssertFatal(aligned_mem, "Aligned malloc failed! Debug!");
  2658. vertexData.set(aligned_mem, mVertSize, mNumVerts);
  2659. vertexData.setReady(true);
  2660. #if defined(TORQUE_OS_XENON)
  2661. XMemCpyStreaming(vertexData.address(), mVertexData.address(), vertexData.mem_size() );
  2662. #else
  2663. dMemcpy(vertexData.address(), mVertexData.address(), vertexData.mem_size());
  2664. #endif
  2665. return;
  2666. }
  2667. AssertFatal(!vertexData.isReady(), "Mesh already converted to aligned data! Re-check code!");
  2668. AssertFatal(_verts.size() == _norms.size() &&
  2669. _verts.size() == tangents.size(),
  2670. "Vectors: verts, norms, tangents must all be the same size");
  2671. mNumVerts = _verts.size();
  2672. // Initialize the vertex data
  2673. vertexData.set(NULL, 0, 0);
  2674. vertexData.setReady(true);
  2675. if(mNumVerts == 0)
  2676. return;
  2677. mHasColor = !colors.empty();
  2678. AssertFatal(!mHasColor || colors.size() == _verts.size(), "Vector of color elements should be the same size as other vectors");
  2679. mHasTVert2 = !tverts2.empty();
  2680. AssertFatal(!mHasTVert2 || tverts2.size() == _verts.size(), "Vector of tvert2 elements should be the same size as other vectors");
  2681. // Create the proper array type
  2682. void *aligned_mem = dMalloc_aligned(mVertSize * mNumVerts, 16);
  2683. AssertFatal(aligned_mem, "Aligned malloc failed! Debug!");
  2684. dMemset(aligned_mem, 0, mNumVerts * mVertSize);
  2685. vertexData.set(aligned_mem, mVertSize, mNumVerts);
  2686. for(U32 i = 0; i < mNumVerts; i++)
  2687. {
  2688. __TSMeshVertexBase &v = vertexData[i];
  2689. v.vert(_verts[i]);
  2690. v.normal(_norms[i]);
  2691. v.tangent(tangents[i]);
  2692. if(i < tverts.size())
  2693. v.tvert(tverts[i]);
  2694. if(mHasTVert2 && i < tverts2.size())
  2695. v.tvert2(tverts2[i]);
  2696. if(mHasColor && i < colors.size())
  2697. v.color(colors[i]);
  2698. }
  2699. // Now that the data is in the aligned struct, free the Vector memory
  2700. verts.free_memory();
  2701. norms.free_memory();
  2702. tangents.free_memory();
  2703. tverts.free_memory();
  2704. tverts2.free_memory();
  2705. colors.free_memory();
  2706. }