tsShapeInstance.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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/tsShapeInstance.h"
  24. #include "ts/tsLastDetail.h"
  25. #include "ts/tsMaterialList.h"
  26. #include "console/consoleTypes.h"
  27. #include "ts/tsDecal.h"
  28. #include "platform/profiler.h"
  29. #include "core/frameAllocator.h"
  30. #include "gfx/gfxDevice.h"
  31. #include "materials/materialManager.h"
  32. #include "materials/materialFeatureTypes.h"
  33. #include "materials/sceneData.h"
  34. #include "materials/matInstance.h"
  35. #include "scene/sceneRenderState.h"
  36. #include "gfx/primBuilder.h"
  37. #include "gfx/gfxDrawUtil.h"
  38. #include "core/module.h"
  39. MODULE_BEGIN( TSShapeInstance )
  40. MODULE_INIT
  41. {
  42. Con::addVariable("$pref::TS::detailAdjust", TypeF32, &TSShapeInstance::smDetailAdjust,
  43. "@brief User perference for scaling the TSShape level of detail.\n"
  44. "The smaller the value the closer the camera must get to see the "
  45. "highest LOD. This setting can have a huge impact on performance in "
  46. "mesh heavy scenes. The default value is 1.\n"
  47. "@ingroup Rendering\n" );
  48. Con::addVariable("$pref::TS::skipLoadDLs", TypeS32, &TSShape::smNumSkipLoadDetails,
  49. "@brief User perference which causes TSShapes to skip loading higher lods.\n"
  50. "This potentialy reduces the GPU resources and materials generated as well as "
  51. "limits the LODs rendered. The default value is 0.\n"
  52. "@see $pref::TS::skipRenderDLs\n"
  53. "@ingroup Rendering\n" );
  54. Con::addVariable("$pref::TS::skipRenderDLs", TypeS32, &TSShapeInstance::smNumSkipRenderDetails,
  55. "@brief User perference which causes TSShapes to skip rendering higher lods.\n"
  56. "This will reduce the number of draw calls and triangles rendered and improve "
  57. "rendering performance when proper LODs have been created for your models. "
  58. "The default value is 0.\n"
  59. "@see $pref::TS::skipLoadDLs\n"
  60. "@ingroup Rendering\n" );
  61. Con::addVariable("$pref::TS::smallestVisiblePixelSize", TypeF32, &TSShapeInstance::smSmallestVisiblePixelSize,
  62. "@brief User perference which sets the smallest pixel size at which TSShapes will skip rendering.\n"
  63. "This will force all shapes to stop rendering when they get smaller than this size. "
  64. "The default value is -1 which disables it.\n"
  65. "@ingroup Rendering\n" );
  66. Con::addVariable("$pref::TS::maxInstancingVerts", TypeS32, &TSMesh::smMaxInstancingVerts,
  67. "@brief Enables mesh instancing on non-skin meshes that have less that this count of verts.\n"
  68. "The default value is 200. Higher values can degrade performance.\n"
  69. "@ingroup Rendering\n" );
  70. }
  71. MODULE_END;
  72. F32 TSShapeInstance::smDetailAdjust = 1.0f;
  73. F32 TSShapeInstance::smSmallestVisiblePixelSize = -1.0f;
  74. S32 TSShapeInstance::smNumSkipRenderDetails = 0;
  75. F32 TSShapeInstance::smLastScreenErrorTolerance = 0.0f;
  76. F32 TSShapeInstance::smLastScaledDistance = 0.0f;
  77. F32 TSShapeInstance::smLastPixelSize = 0.0f;
  78. Vector<QuatF> TSShapeInstance::smNodeCurrentRotations(__FILE__, __LINE__);
  79. Vector<Point3F> TSShapeInstance::smNodeCurrentTranslations(__FILE__, __LINE__);
  80. Vector<F32> TSShapeInstance::smNodeCurrentUniformScales(__FILE__, __LINE__);
  81. Vector<Point3F> TSShapeInstance::smNodeCurrentAlignedScales(__FILE__, __LINE__);
  82. Vector<TSScale> TSShapeInstance::smNodeCurrentArbitraryScales(__FILE__, __LINE__);
  83. Vector<MatrixF> TSShapeInstance::smNodeLocalTransforms(__FILE__, __LINE__);
  84. TSIntegerSet TSShapeInstance::smNodeLocalTransformDirty;
  85. Vector<TSThread*> TSShapeInstance::smRotationThreads(__FILE__, __LINE__);
  86. Vector<TSThread*> TSShapeInstance::smTranslationThreads(__FILE__, __LINE__);
  87. Vector<TSThread*> TSShapeInstance::smScaleThreads(__FILE__, __LINE__);
  88. //-------------------------------------------------------------------------------------
  89. // constructors, destructors, initialization
  90. //-------------------------------------------------------------------------------------
  91. TSShapeInstance::TSShapeInstance( const Resource<TSShape> &shape, bool loadMaterials )
  92. {
  93. VECTOR_SET_ASSOCIATION(mMeshObjects);
  94. VECTOR_SET_ASSOCIATION(mNodeTransforms);
  95. VECTOR_SET_ASSOCIATION(mNodeReferenceRotations);
  96. VECTOR_SET_ASSOCIATION(mNodeReferenceTranslations);
  97. VECTOR_SET_ASSOCIATION(mNodeReferenceUniformScales);
  98. VECTOR_SET_ASSOCIATION(mNodeReferenceScaleFactors);
  99. VECTOR_SET_ASSOCIATION(mNodeReferenceArbitraryScaleRots);
  100. VECTOR_SET_ASSOCIATION(mThreadList);
  101. VECTOR_SET_ASSOCIATION(mTransitionThreads);
  102. mShapeResource = shape;
  103. mShape = mShapeResource;
  104. buildInstanceData( mShape, loadMaterials );
  105. }
  106. TSShapeInstance::TSShapeInstance( TSShape *shape, bool loadMaterials )
  107. {
  108. VECTOR_SET_ASSOCIATION(mMeshObjects);
  109. VECTOR_SET_ASSOCIATION(mNodeTransforms);
  110. VECTOR_SET_ASSOCIATION(mNodeReferenceRotations);
  111. VECTOR_SET_ASSOCIATION(mNodeReferenceTranslations);
  112. VECTOR_SET_ASSOCIATION(mNodeReferenceUniformScales);
  113. VECTOR_SET_ASSOCIATION(mNodeReferenceScaleFactors);
  114. VECTOR_SET_ASSOCIATION(mNodeReferenceArbitraryScaleRots);
  115. VECTOR_SET_ASSOCIATION(mThreadList);
  116. VECTOR_SET_ASSOCIATION(mTransitionThreads);
  117. mShapeResource = NULL;
  118. mShape = shape;
  119. buildInstanceData( mShape, loadMaterials );
  120. }
  121. TSShapeInstance::~TSShapeInstance()
  122. {
  123. mMeshObjects.clear();
  124. while (mThreadList.size())
  125. destroyThread(mThreadList.last());
  126. setMaterialList(NULL);
  127. delete [] mDirtyFlags;
  128. }
  129. void TSShapeInstance::buildInstanceData(TSShape * _shape, bool loadMaterials)
  130. {
  131. mShape = _shape;
  132. debrisRefCount = 0;
  133. mCurrentDetailLevel = 0;
  134. mCurrentIntraDetailLevel = 1.0f;
  135. // all triggers off at start
  136. mTriggerStates = 0;
  137. //
  138. mAlphaAlways = false;
  139. mAlphaAlwaysValue = 1.0f;
  140. // material list...
  141. mMaterialList = NULL;
  142. mOwnMaterialList = false;
  143. mUseOwnBuffer = false;
  144. //
  145. mData = 0;
  146. mScaleCurrentlyAnimated = false;
  147. if(loadMaterials)
  148. setMaterialList(mShape->materialList);
  149. // set up node data
  150. initNodeTransforms();
  151. // add objects to trees
  152. initMeshObjects();
  153. // set up subtree data
  154. S32 ss = mShape->subShapeFirstNode.size(); // we have this many subtrees
  155. mDirtyFlags = new U32[ss];
  156. mGroundThread = NULL;
  157. mCurrentDetailLevel = 0;
  158. animateSubtrees();
  159. // Construct billboards if not done already
  160. if ( loadMaterials && mShapeResource && GFXDevice::devicePresent() )
  161. mShape->setupBillboardDetails( mShapeResource.getPath().getFullPath() );
  162. }
  163. void TSShapeInstance::initNodeTransforms()
  164. {
  165. // set up node data
  166. S32 numNodes = mShape->nodes.size();
  167. mNodeTransforms.setSize(numNodes);
  168. }
  169. void TSShapeInstance::initMeshObjects()
  170. {
  171. // add objects to trees
  172. S32 numObjects = mShape->objects.size();
  173. mMeshObjects.setSize(numObjects);
  174. for (S32 i=0; i<numObjects; i++)
  175. {
  176. const TSObject * obj = &mShape->objects[i];
  177. MeshObjectInstance * objInst = &mMeshObjects[i];
  178. // hook up the object to it's node and transforms.
  179. objInst->mTransforms = &mNodeTransforms;
  180. objInst->nodeIndex = obj->nodeIndex;
  181. // set up list of meshes
  182. if (obj->numMeshes)
  183. objInst->meshList = &mShape->meshes[obj->startMeshIndex];
  184. else
  185. objInst->meshList = NULL;
  186. objInst->object = obj;
  187. objInst->forceHidden = false;
  188. }
  189. }
  190. void TSShapeInstance::setMaterialList( TSMaterialList *matList )
  191. {
  192. // get rid of old list
  193. if ( mOwnMaterialList )
  194. delete mMaterialList;
  195. mMaterialList = matList;
  196. mOwnMaterialList = false;
  197. // If the material list is already be mapped then
  198. // don't bother doing the initializing a second time.
  199. // Note: only check the last material instance as this will catch both
  200. // uninitialised lists, as well as initialised lists that have had new
  201. // materials appended
  202. if ( mMaterialList && !mMaterialList->getMaterialInst( mMaterialList->size()-1 ) )
  203. {
  204. mMaterialList->setTextureLookupPath( mShapeResource.getPath().getPath() );
  205. mMaterialList->mapMaterials();
  206. Material::sAllowTextureTargetAssignment = true;
  207. initMaterialList();
  208. Material::sAllowTextureTargetAssignment = false;
  209. }
  210. }
  211. void TSShapeInstance::cloneMaterialList( const FeatureSet *features )
  212. {
  213. if ( mOwnMaterialList )
  214. return;
  215. Material::sAllowTextureTargetAssignment = true;
  216. mMaterialList = new TSMaterialList(mMaterialList);
  217. initMaterialList( features );
  218. Material::sAllowTextureTargetAssignment = false;
  219. mOwnMaterialList = true;
  220. }
  221. void TSShapeInstance::initMaterialList( const FeatureSet *features )
  222. {
  223. // If we don't have features then use the default.
  224. if ( !features )
  225. features = &MATMGR->getDefaultFeatures();
  226. // Initialize the materials.
  227. mMaterialList->initMatInstances( *features, mShape->getVertexFormat() );
  228. // TODO: It would be good to go thru all the meshes and
  229. // pre-create all the active material hooks for shadows,
  230. // reflections, and instancing. This would keep these
  231. // hiccups from happening at runtime.
  232. }
  233. void TSShapeInstance::reSkin( String newBaseName, String oldBaseName )
  234. {
  235. if( newBaseName.isEmpty() )
  236. newBaseName = "base";
  237. if( oldBaseName.isEmpty() )
  238. oldBaseName = "base";
  239. if ( newBaseName.equal( oldBaseName, String::NoCase ) )
  240. return;
  241. const U32 oldBaseNameLength = oldBaseName.length();
  242. // Make our own copy of the materials list from the resource if necessary
  243. if (ownMaterialList() == false)
  244. cloneMaterialList();
  245. TSMaterialList* pMatList = getMaterialList();
  246. pMatList->setTextureLookupPath( mShapeResource.getPath().getPath() );
  247. // Cycle through the materials
  248. const Vector<String> &materialNames = pMatList->getMaterialNameList();
  249. for ( S32 i = 0; i < materialNames.size(); i++ )
  250. {
  251. // Try changing base
  252. const String &pName = materialNames[i];
  253. if ( pName.compare( oldBaseName, oldBaseNameLength, String::NoCase ) == 0 )
  254. {
  255. String newName( pName );
  256. newName.replace( 0, oldBaseNameLength, newBaseName );
  257. pMatList->renameMaterial( i, newName );
  258. }
  259. }
  260. // Initialize the material instances
  261. initMaterialList();
  262. }
  263. //-------------------------------------------------------------------------------------
  264. // Render & detail selection
  265. //-------------------------------------------------------------------------------------
  266. void TSShapeInstance::renderDebugNormals( F32 normalScalar, S32 dl )
  267. {
  268. if ( dl < 0 )
  269. return;
  270. AssertFatal( dl >= 0 && dl < mShape->details.size(),
  271. "TSShapeInstance::renderDebugNormals() - Bad detail level!" );
  272. static GFXStateBlockRef sb;
  273. if ( sb.isNull() )
  274. {
  275. GFXStateBlockDesc desc;
  276. desc.setCullMode( GFXCullNone );
  277. desc.setZReadWrite( true );
  278. desc.zWriteEnable = false;
  279. desc.vertexColorEnable = true;
  280. sb = GFX->createStateBlock( desc );
  281. }
  282. GFX->setStateBlock( sb );
  283. const TSDetail *detail = &mShape->details[dl];
  284. const S32 ss = detail->subShapeNum;
  285. if ( ss < 0 )
  286. return;
  287. const S32 start = mShape->subShapeFirstObject[ss];
  288. const S32 end = start + mShape->subShapeNumObjects[ss];
  289. for ( S32 i = start; i < end; i++ )
  290. {
  291. MeshObjectInstance *meshObj = &mMeshObjects[i];
  292. if ( !meshObj )
  293. continue;
  294. const MatrixF &meshMat = meshObj->getTransform();
  295. // Then go through each TSMesh...
  296. U32 m = 0;
  297. for( TSMesh *mesh = meshObj->getMesh(m); mesh != NULL; mesh = meshObj->getMesh(m++) )
  298. {
  299. // and pull out the list of normals.
  300. const U32 numNrms = mesh->mNumVerts;
  301. PrimBuild::begin( GFXLineList, 2 * numNrms );
  302. for ( U32 n = 0; n < numNrms; n++ )
  303. {
  304. const TSMesh::__TSMeshVertexBase &v = mesh->mVertexData.getBase(n);
  305. Point3F norm = v.normal();
  306. Point3F vert = v.vert();
  307. meshMat.mulP( vert );
  308. meshMat.mulV( norm );
  309. // Then render them.
  310. PrimBuild::color4f( mFabs( norm.x ), mFabs( norm.y ), mFabs( norm.z ), 1.0f );
  311. PrimBuild::vertex3fv( vert );
  312. PrimBuild::vertex3fv( vert + (norm * normalScalar) );
  313. }
  314. PrimBuild::end();
  315. }
  316. }
  317. }
  318. void TSShapeInstance::renderDebugNodes()
  319. {
  320. GFXDrawUtil *drawUtil = GFX->getDrawUtil();
  321. ColorI color( 255, 0, 0, 255 );
  322. GFXStateBlockDesc desc;
  323. desc.setBlend( false );
  324. desc.setZReadWrite( false, false );
  325. for ( U32 i = 0; i < mNodeTransforms.size(); i++ )
  326. drawUtil->drawTransform( desc, mNodeTransforms[i], NULL, NULL );
  327. }
  328. void TSShapeInstance::listMeshes( const String &state ) const
  329. {
  330. if ( state.equal( "All", String::NoCase ) )
  331. {
  332. for ( U32 i = 0; i < mMeshObjects.size(); i++ )
  333. {
  334. const MeshObjectInstance &mesh = mMeshObjects[i];
  335. Con::warnf( "meshidx %3d, %8s, %s", i, ( mesh.forceHidden ) ? "Hidden" : "Visible", mShape->getMeshName(i).c_str() );
  336. }
  337. }
  338. else if ( state.equal( "Hidden", String::NoCase ) )
  339. {
  340. for ( U32 i = 0; i < mMeshObjects.size(); i++ )
  341. {
  342. const MeshObjectInstance &mesh = mMeshObjects[i];
  343. if ( mesh.forceHidden )
  344. Con::warnf( "meshidx %3d, %8s, %s", i, "Visible", mShape->getMeshName(i).c_str() );
  345. }
  346. }
  347. else if ( state.equal( "Visible", String::NoCase ) )
  348. {
  349. for ( U32 i = 0; i < mMeshObjects.size(); i++ )
  350. {
  351. const MeshObjectInstance &mesh = mMeshObjects[i];
  352. if ( !mesh.forceHidden )
  353. Con::warnf( "meshidx %3d, %8s, %s", i, "Hidden", mShape->getMeshName(i).c_str() );
  354. }
  355. }
  356. else
  357. {
  358. Con::warnf( "TSShapeInstance::listMeshes( %s ) - only All/Hidden/Visible are valid parameters." );
  359. }
  360. }
  361. void TSShapeInstance::render( const TSRenderState &rdata )
  362. {
  363. if (mCurrentDetailLevel<0)
  364. return;
  365. PROFILE_SCOPE( TSShapeInstance_Render );
  366. // alphaIn: we start to alpha-in next detail level when intraDL > 1-alphaIn-alphaOut
  367. // (finishing when intraDL = 1-alphaOut)
  368. // alphaOut: start to alpha-out this detail level when intraDL > 1-alphaOut
  369. // NOTE:
  370. // intraDL is at 1 when if shape were any closer to us we'd be at dl-1,
  371. // intraDL is at 0 when if shape were any farther away we'd be at dl+1
  372. F32 alphaOut = mShape->alphaOut[mCurrentDetailLevel];
  373. F32 alphaIn = mShape->alphaIn[mCurrentDetailLevel];
  374. F32 saveAA = mAlphaAlways ? mAlphaAlwaysValue : 1.0f;
  375. /// This first case is the single detail level render.
  376. if ( mCurrentIntraDetailLevel > alphaIn + alphaOut )
  377. render( rdata, mCurrentDetailLevel, mCurrentIntraDetailLevel );
  378. else if ( mCurrentIntraDetailLevel > alphaOut )
  379. {
  380. // draw this detail level w/ alpha=1 and next detail level w/
  381. // alpha=1-(intraDl-alphaOut)/alphaIn
  382. // first draw next detail level
  383. if ( mCurrentDetailLevel + 1 < mShape->details.size() && mShape->details[ mCurrentDetailLevel + 1 ].size > 0.0f )
  384. {
  385. setAlphaAlways( saveAA * ( alphaIn + alphaOut - mCurrentIntraDetailLevel ) / alphaIn );
  386. render( rdata, mCurrentDetailLevel + 1, 0.0f );
  387. }
  388. setAlphaAlways( saveAA );
  389. render( rdata, mCurrentDetailLevel, mCurrentIntraDetailLevel );
  390. }
  391. else
  392. {
  393. // draw next detail level w/ alpha=1 and this detail level w/
  394. // alpha = 1-intraDL/alphaOut
  395. // first draw next detail level
  396. if ( mCurrentDetailLevel + 1 < mShape->details.size() && mShape->details[ mCurrentDetailLevel + 1 ].size > 0.0f )
  397. render( rdata, mCurrentDetailLevel+1, 0.0f );
  398. setAlphaAlways( saveAA * mCurrentIntraDetailLevel / alphaOut );
  399. render( rdata, mCurrentDetailLevel, mCurrentIntraDetailLevel );
  400. setAlphaAlways( saveAA );
  401. }
  402. }
  403. void TSShapeInstance::setMeshForceHidden( const char *meshName, bool hidden )
  404. {
  405. Vector<MeshObjectInstance>::iterator iter = mMeshObjects.begin();
  406. for ( ; iter != mMeshObjects.end(); iter++ )
  407. {
  408. S32 nameIndex = iter->object->nameIndex;
  409. const char *name = mShape->names[ nameIndex ];
  410. if ( dStrcmp( meshName, name ) == 0 )
  411. {
  412. iter->forceHidden = hidden;
  413. return;
  414. }
  415. }
  416. }
  417. void TSShapeInstance::setMeshForceHidden( S32 meshIndex, bool hidden )
  418. {
  419. AssertFatal( meshIndex > -1 && meshIndex < mMeshObjects.size(),
  420. "TSShapeInstance::setMeshForceHidden - Invalid index!" );
  421. mMeshObjects[meshIndex].forceHidden = hidden;
  422. }
  423. void TSShapeInstance::render( const TSRenderState &rdata, S32 dl, F32 intraDL )
  424. {
  425. AssertFatal( dl >= 0 && dl < mShape->details.size(),"TSShapeInstance::render" );
  426. S32 i;
  427. const TSDetail * detail = &mShape->details[dl];
  428. S32 ss = detail->subShapeNum;
  429. S32 od = detail->objectDetailNum;
  430. // if we're a billboard detail, draw it and exit
  431. if ( ss < 0 )
  432. {
  433. PROFILE_SCOPE( TSShapeInstance_RenderBillboards );
  434. if ( !rdata.isNoRenderTranslucent() && ( TSLastDetail::smCanShadow || !rdata.getSceneState()->isShadowPass() ) )
  435. mShape->billboardDetails[ dl ]->render( rdata, mAlphaAlways ? mAlphaAlwaysValue : 1.0f );
  436. return;
  437. }
  438. S32 start = rdata.isNoRenderNonTranslucent() ? mShape->subShapeFirstTranslucentObject[ss] : mShape->subShapeFirstObject[ss];
  439. S32 end = rdata.isNoRenderTranslucent() ? mShape->subShapeFirstTranslucentObject[ss] : mShape->subShapeFirstObject[ss] + mShape->subShapeNumObjects[ss];
  440. TSVertexBufferHandle *realBuffer;
  441. if (TSShape::smUseHardwareSkinning && !mUseOwnBuffer)
  442. {
  443. // For hardware skinning, just using the buffer associated with the shape will work fine
  444. realBuffer = &mShape->mShapeVertexBuffer;
  445. }
  446. else
  447. {
  448. // For software skinning, we need to update our own buffer each frame
  449. realBuffer = &mSoftwareVertexBuffer;
  450. if (realBuffer->getPointer() == NULL)
  451. {
  452. mShape->getVertexBuffer(*realBuffer, GFXBufferTypeDynamic);
  453. }
  454. if (bufferNeedsUpdate(od, start, end))
  455. {
  456. U8 *buffer = realBuffer->lock();
  457. if (!buffer)
  458. return;
  459. // Base vertex data
  460. dMemcpy(buffer, mShape->mShapeVertexData.base, mShape->mShapeVertexData.size);
  461. // Apply skinned verts (where applicable)
  462. for (i = start; i < end; i++)
  463. {
  464. mMeshObjects[i].updateVertexBuffer(od, buffer);
  465. }
  466. realBuffer->unlock();
  467. }
  468. }
  469. // run through the meshes
  470. for (i=start; i<end; i++)
  471. {
  472. TSRenderState objState = rdata;
  473. // following line is handy for debugging, to see what part of the shape that it is rendering
  474. const char *name = mShape->names[ mMeshObjects[i].object->nameIndex ];
  475. mMeshObjects[i].render( od, *realBuffer, mMaterialList, objState, mAlphaAlways ? mAlphaAlwaysValue : 1.0f, name );
  476. }
  477. }
  478. bool TSShapeInstance::bufferNeedsUpdate(S32 objectDetail, S32 start, S32 end)
  479. {
  480. // run through the meshes
  481. for (U32 i = start; i<end; i++)
  482. {
  483. if (mMeshObjects[i].bufferNeedsUpdate(objectDetail))
  484. return true;
  485. }
  486. return false;
  487. }
  488. void TSShapeInstance::setCurrentDetail( S32 dl, F32 intraDL )
  489. {
  490. PROFILE_SCOPE( TSShapeInstance_setCurrentDetail );
  491. mCurrentDetailLevel = mClamp( dl, -1, mShape->mSmallestVisibleDL );
  492. mCurrentIntraDetailLevel = intraDL > 1.0f ? 1.0f : (intraDL < 0.0f ? 0.0f : intraDL);
  493. // Restrict the chosen detail level by cutoff value.
  494. if ( smNumSkipRenderDetails > 0 && mCurrentDetailLevel >= 0 )
  495. {
  496. S32 cutoff = getMin( smNumSkipRenderDetails, mShape->mSmallestVisibleDL );
  497. if ( mCurrentDetailLevel < cutoff )
  498. {
  499. mCurrentDetailLevel = cutoff;
  500. mCurrentIntraDetailLevel = 1.0f;
  501. }
  502. }
  503. }
  504. S32 TSShapeInstance::setDetailFromPosAndScale( const SceneRenderState *state,
  505. const Point3F &pos,
  506. const Point3F &scale )
  507. {
  508. VectorF camVector = pos - state->getDiffuseCameraPosition();
  509. F32 dist = getMax( camVector.len(), 0.01f );
  510. F32 invScale = ( 1.0f / getMax( getMax( scale.x, scale.y ), scale.z ) );
  511. return setDetailFromDistance( state, dist * invScale );
  512. }
  513. S32 TSShapeInstance::setDetailFromDistance( const SceneRenderState *state, F32 scaledDistance )
  514. {
  515. PROFILE_SCOPE( TSShapeInstance_setDetailFromDistance );
  516. // For debugging/metrics.
  517. smLastScaledDistance = scaledDistance;
  518. // Shortcut if the distance is really close or negative.
  519. if ( scaledDistance <= 0.0f )
  520. {
  521. mShape->mDetailLevelLookup[0].get( mCurrentDetailLevel, mCurrentIntraDetailLevel );
  522. return mCurrentDetailLevel;
  523. }
  524. // The pixel scale is used the linearly scale the lod
  525. // selection based on the viewport size.
  526. //
  527. // The original calculation from TGEA was...
  528. //
  529. // pixelScale = viewport.extent.x * 1.6f / 640.0f;
  530. //
  531. // Since we now work on the viewport height, assuming
  532. // 4:3 aspect ratio, we've changed the reference value
  533. // to 300 to be more compatible with legacy shapes.
  534. //
  535. const F32 pixelScale = (state->getViewport().extent.x / state->getViewport().extent.y)*2;
  536. // This is legacy DTS support for older "multires" based
  537. // meshes. The original crossbow weapon uses this.
  538. //
  539. // If we have more than one detail level and the maxError
  540. // is non-negative then we do some sort of screen error
  541. // metric for detail selection.
  542. //
  543. if ( mShape->mUseDetailFromScreenError )
  544. {
  545. // The pixel size of 1 meter at the input distance.
  546. F32 pixelRadius = state->projectRadius( scaledDistance, 1.0f ) * pixelScale;
  547. static const F32 smScreenError = 5.0f;
  548. return setDetailFromScreenError( smScreenError / pixelRadius );
  549. }
  550. // We're inlining SceneRenderState::projectRadius here to
  551. // skip the unnessasary divide by zero protection.
  552. F32 pixelRadius = ( mShape->radius / scaledDistance ) * state->getWorldToScreenScale().y * pixelScale;
  553. F32 pixelSize = pixelRadius * smDetailAdjust;
  554. if ( pixelSize < smSmallestVisiblePixelSize ) {
  555. mCurrentDetailLevel = -1;
  556. return mCurrentDetailLevel;
  557. }
  558. if ( pixelSize > smSmallestVisiblePixelSize &&
  559. pixelSize <= mShape->mSmallestVisibleSize )
  560. pixelSize = mShape->mSmallestVisibleSize + 0.01f;
  561. // For debugging/metrics.
  562. smLastPixelSize = pixelSize;
  563. // Clamp it to an acceptable range for the lookup table.
  564. U32 index = (U32)mClampF( pixelSize, 0, mShape->mDetailLevelLookup.size() - 1 );
  565. // Check the lookup table for the detail and intra detail levels.
  566. mShape->mDetailLevelLookup[ index ].get( mCurrentDetailLevel, mCurrentIntraDetailLevel );
  567. // Restrict the chosen detail level by cutoff value.
  568. if ( smNumSkipRenderDetails > 0 && mCurrentDetailLevel >= 0 )
  569. {
  570. S32 cutoff = getMin( smNumSkipRenderDetails, mShape->mSmallestVisibleDL );
  571. if ( mCurrentDetailLevel < cutoff )
  572. {
  573. mCurrentDetailLevel = cutoff;
  574. mCurrentIntraDetailLevel = 1.0f;
  575. }
  576. }
  577. return mCurrentDetailLevel;
  578. }
  579. S32 TSShapeInstance::setDetailFromScreenError( F32 errorTolerance )
  580. {
  581. PROFILE_SCOPE( TSShapeInstance_setDetailFromScreenError );
  582. // For debugging/metrics.
  583. smLastScreenErrorTolerance = errorTolerance;
  584. // note: we use 10 time the average error as the metric...this is
  585. // more robust than the maxError...the factor of 10 is to put average error
  586. // on about the same scale as maxError. The errorTOL is how much
  587. // error we are able to tolerate before going to a more detailed version of the
  588. // shape. We look for a pair of details with errors bounding our errorTOL,
  589. // and then we select an interpolation parameter to tween betwen them. Ok, so
  590. // this isn't exactly an error tolerance. A tween value of 0 is the lower poly
  591. // model (higher detail number) and a value of 1 is the higher poly model (lower
  592. // detail number).
  593. // deal with degenerate case first...
  594. // if smallest detail corresponds to less than half tolerable error, then don't even draw
  595. F32 prevErr;
  596. if ( mShape->mSmallestVisibleDL < 0 )
  597. prevErr = 0.0f;
  598. else
  599. prevErr = 10.0f * mShape->details[mShape->mSmallestVisibleDL].averageError * 20.0f;
  600. if ( mShape->mSmallestVisibleDL < 0 || prevErr < errorTolerance )
  601. {
  602. // draw last detail
  603. mCurrentDetailLevel = mShape->mSmallestVisibleDL;
  604. mCurrentIntraDetailLevel = 0.0f;
  605. return mCurrentDetailLevel;
  606. }
  607. // this function is a little odd
  608. // the reason is that the detail numbers correspond to
  609. // when we stop using a given detail level...
  610. // we search the details from most error to least error
  611. // until we fit under the tolerance (errorTOL) and then
  612. // we use the next highest detail (higher error)
  613. for (S32 i = mShape->mSmallestVisibleDL; i >= 0; i-- )
  614. {
  615. F32 err0 = 10.0f * mShape->details[i].averageError;
  616. if ( err0 < errorTolerance )
  617. {
  618. // ok, stop here
  619. // intraDL = 1 corresponds to fully this detail
  620. // intraDL = 0 corresponds to the next lower (higher number) detail
  621. mCurrentDetailLevel = i;
  622. mCurrentIntraDetailLevel = 1.0f - (errorTolerance - err0) / (prevErr - err0);
  623. return mCurrentDetailLevel;
  624. }
  625. prevErr = err0;
  626. }
  627. // get here if we are drawing at DL==0
  628. mCurrentDetailLevel = 0;
  629. mCurrentIntraDetailLevel = 1.0f;
  630. return mCurrentDetailLevel;
  631. }
  632. //-------------------------------------------------------------------------------------
  633. // Object (MeshObjectInstance & PluginObjectInstance) render methods
  634. //-------------------------------------------------------------------------------------
  635. void TSShapeInstance::ObjectInstance::render( S32, TSVertexBufferHandle &vb, TSMaterialList *, TSRenderState &rdata, F32 alpha, const char *meshName )
  636. {
  637. AssertFatal(0,"TSShapeInstance::ObjectInstance::render: no default render method.");
  638. }
  639. void TSShapeInstance::ObjectInstance::updateVertexBuffer( S32 objectDetail, U8 *buffer )
  640. {
  641. AssertFatal(0, "TSShapeInstance::ObjectInstance::updateVertexBuffer: no default vertex buffer update method.");
  642. }
  643. bool TSShapeInstance::ObjectInstance::bufferNeedsUpdate( S32 objectDetai )
  644. {
  645. return false;
  646. }
  647. void TSShapeInstance::MeshObjectInstance::render( S32 objectDetail,
  648. TSVertexBufferHandle &vb,
  649. TSMaterialList *materials,
  650. TSRenderState &rdata,
  651. F32 alpha,
  652. const char *meshName )
  653. {
  654. PROFILE_SCOPE( TSShapeInstance_MeshObjectInstance_render );
  655. if ( forceHidden || ( ( visible * alpha ) <= 0.01f ) )
  656. return;
  657. TSMesh *mesh = getMesh(objectDetail);
  658. if ( !mesh )
  659. return;
  660. const MatrixF &transform = getTransform();
  661. if ( rdata.getCuller() )
  662. {
  663. Box3F box( mesh->getBounds() );
  664. transform.mul( box );
  665. if ( rdata.getCuller()->isCulled( box ) )
  666. return;
  667. }
  668. GFX->pushWorldMatrix();
  669. GFX->multWorld( transform );
  670. mesh->setFade( visible * alpha );
  671. // Pass a hint to the mesh that time has advanced and that the
  672. // skin is dirty and needs to be updated. This should result
  673. // in the skin only updating once per frame in most cases.
  674. const U32 currTime = Sim::getCurrentTime();
  675. bool isSkinDirty = currTime != mLastTime;
  676. // Update active transform list for bones for GPU skinning
  677. if ( mesh->getMeshType() == TSMesh::SkinMeshType )
  678. {
  679. if (isSkinDirty)
  680. {
  681. static_cast<TSSkinMesh*>(mesh)->updateSkinBones(*mTransforms, mActiveTransforms);
  682. }
  683. rdata.setNodeTransforms(mActiveTransforms.address(), mActiveTransforms.size());
  684. }
  685. mesh->render( materials,
  686. rdata,
  687. isSkinDirty,
  688. *mTransforms,
  689. vb,
  690. meshName );
  691. // Update the last render time.
  692. mLastTime = currTime;
  693. GFX->popWorldMatrix();
  694. }
  695. void TSShapeInstance::MeshObjectInstance::updateVertexBuffer(S32 objectDetail, U8 *buffer)
  696. {
  697. PROFILE_SCOPE(TSShapeInstance_MeshObjectInstance_updateVertexBuffer);
  698. if (forceHidden || ((visible) <= 0.01f))
  699. return;
  700. TSMesh *mesh = getMesh(objectDetail);
  701. if (!mesh)
  702. return;
  703. // Update the buffer here
  704. if (mesh->getMeshType() == TSMesh::SkinMeshType)
  705. {
  706. static_cast<TSSkinMesh*>(mesh)->updateSkinBuffer(*mTransforms, buffer);
  707. }
  708. mLastTime = Sim::getCurrentTime();
  709. }
  710. bool TSShapeInstance::MeshObjectInstance::bufferNeedsUpdate( S32 objectDetail )
  711. {
  712. TSMesh *mesh = getMesh(objectDetail);
  713. const U32 currTime = Sim::getCurrentTime();
  714. return mesh && mesh->getMeshType() == TSMesh::SkinMeshType && currTime != mLastTime;
  715. }
  716. TSShapeInstance::MeshObjectInstance::MeshObjectInstance()
  717. : meshList(0), object(0), frame(0), matFrame(0),
  718. visible(1.0f), forceHidden(false), mLastTime( 0 )
  719. {
  720. }
  721. void TSShapeInstance::prepCollision()
  722. {
  723. PROFILE_SCOPE( TSShapeInstance_PrepCollision );
  724. // Iterate over all our meshes and call prepCollision on them...
  725. for(S32 i=0; i<mShape->meshes.size(); i++)
  726. {
  727. if(mShape->meshes[i])
  728. mShape->meshes[i]->prepOpcodeCollision();
  729. }
  730. }
  731. // Returns true is the shape contains any materials with accumulation enabled.
  732. bool TSShapeInstance::hasAccumulation()
  733. {
  734. bool result = false;
  735. for ( U32 i = 0; i < mMaterialList->size(); ++i )
  736. {
  737. BaseMatInstance* mat = mMaterialList->getMaterialInst(i);
  738. if ( mat->hasAccumulation() )
  739. result = true;
  740. }
  741. return result;
  742. }
  743. void TSShapeInstance::setUseOwnBuffer()
  744. {
  745. mUseOwnBuffer = true;
  746. }