tsMesh.cpp 107 KB

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