tsStatic.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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 "T3D/tsStatic.h"
  24. #include "core/resourceManager.h"
  25. #include "core/stream/bitStream.h"
  26. #include "scene/sceneRenderState.h"
  27. #include "scene/sceneManager.h"
  28. #include "scene/sceneObjectLightingPlugin.h"
  29. #include "lighting/lightManager.h"
  30. #include "math/mathIO.h"
  31. #include "ts/tsShapeInstance.h"
  32. #include "ts/tsMaterialList.h"
  33. #include "console/consoleTypes.h"
  34. #include "T3D/shapeBase.h"
  35. #include "sim/netConnection.h"
  36. #include "gfx/gfxDevice.h"
  37. #include "gfx/gfxTransformSaver.h"
  38. #include "ts/tsRenderState.h"
  39. #include "collision/boxConvex.h"
  40. #include "T3D/physics/physicsPlugin.h"
  41. #include "T3D/physics/physicsBody.h"
  42. #include "T3D/physics/physicsCollision.h"
  43. #include "materials/materialDefinition.h"
  44. #include "materials/materialManager.h"
  45. #include "materials/matInstance.h"
  46. #include "materials/materialFeatureData.h"
  47. #include "materials/materialFeatureTypes.h"
  48. #include "console/engineAPI.h"
  49. using namespace Torque;
  50. extern bool gEditingMission;
  51. IMPLEMENT_CO_NETOBJECT_V1(TSStatic);
  52. ConsoleDocClass( TSStatic,
  53. "@brief A static object derived from a 3D model file and placed within the game world.\n\n"
  54. "TSStatic is the most basic 3D shape in Torque. Unlike StaticShape it doesn't make use of "
  55. "a datablock. It derrives directly from SceneObject. This makes TSStatic extremely light "
  56. "weight, which is why the Tools use this class when you want to drop in a DTS or DAE object.\n\n"
  57. "While a TSStatic doesn't provide any motion -- it stays were you initally put it -- it does allow for "
  58. "a single ambient animation sequence to play when the object is first added to the scene.\n\n"
  59. "@tsexample\n"
  60. "new TSStatic(Team1Base) {\n"
  61. " shapeName = \"art/shapes/desertStructures/station01.dts\";\n"
  62. " playAmbient = \"1\";\n"
  63. " receiveSunLight = \"1\";\n"
  64. " receiveLMLighting = \"1\";\n"
  65. " useCustomAmbientLighting = \"0\";\n"
  66. " customAmbientLighting = \"0 0 0 1\";\n"
  67. " collisionType = \"Visible Mesh\";\n"
  68. " decalType = \"Collision Mesh\";\n"
  69. " allowPlayerStep = \"1\";\n"
  70. " renderNormals = \"0\";\n"
  71. " forceDetail = \"-1\";\n"
  72. " position = \"315.18 -180.418 244.313\";\n"
  73. " rotation = \"0 0 1 195.952\";\n"
  74. " scale = \"1 1 1\";\n"
  75. " isRenderEnabled = \"true\";\n"
  76. " canSaveDynamicFields = \"1\";\n"
  77. "};\n"
  78. "@endtsexample\n"
  79. "@ingroup gameObjects\n"
  80. );
  81. TSStatic::TSStatic()
  82. {
  83. mNetFlags.set(Ghostable | ScopeAlways);
  84. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  85. mShapeName = "";
  86. mShapeInstance = NULL;
  87. mPlayAmbient = true;
  88. mAmbientThread = NULL;
  89. mAllowPlayerStep = true;
  90. mConvexList = new Convex;
  91. mRenderNormalScalar = 0;
  92. mForceDetail = -1;
  93. mMeshCulling = false;
  94. mUseOriginSort = false;
  95. mPhysicsRep = NULL;
  96. mCollisionType = CollisionMesh;
  97. mDecalType = CollisionMesh;
  98. }
  99. TSStatic::~TSStatic()
  100. {
  101. delete mConvexList;
  102. mConvexList = NULL;
  103. }
  104. ImplementEnumType( TSMeshType,
  105. "Type of mesh data available in a shape.\n"
  106. "@ingroup gameObjects" )
  107. { TSStatic::None, "None", "No mesh data." },
  108. { TSStatic::Bounds, "Bounds", "Bounding box of the shape." },
  109. { TSStatic::CollisionMesh, "Collision Mesh", "Specifically desingated \"collision\" meshes." },
  110. { TSStatic::VisibleMesh, "Visible Mesh", "Rendered mesh polygons." },
  111. EndImplementEnumType;
  112. void TSStatic::initPersistFields()
  113. {
  114. addGroup("Media");
  115. addField("shapeName", TypeShapeFilename, Offset( mShapeName, TSStatic ),
  116. "%Path and filename of the model file (.DTS, .DAE) to use for this TSStatic." );
  117. addProtectedField( "skin", TypeRealString, Offset( mAppliedSkinName, TSStatic ), &_setFieldSkin, &_getFieldSkin,
  118. "@brief The skin applied to the shape.\n\n"
  119. "'Skinning' the shape effectively renames the material targets, allowing "
  120. "different materials to be used on different instances of the same model.\n\n"
  121. "Any material targets that start with the old skin name have that part "
  122. "of the name replaced with the new skin name. The initial old skin name is "
  123. "\"base\". For example, if a new skin of \"blue\" was applied to a model "
  124. "that had material targets <i>base_body</i> and <i>face</i>, the new targets "
  125. "would be <i>blue_body</i> and <i>face</i>. Note that <i>face</i> was not "
  126. "renamed since it did not start with the old skin name of \"base\".\n\n"
  127. "To support models that do not use the default \"base\" naming convention, "
  128. "you can also specify the part of the name to replace in the skin field "
  129. "itself. For example, if a model had a material target called <i>shapemat</i>, "
  130. "we could apply a new skin \"shape=blue\", and the material target would be "
  131. "renamed to <i>bluemat</i> (note \"shape\" has been replaced with \"blue\").\n\n"
  132. "Multiple skin updates can also be applied at the same time by separating "
  133. "them with a semicolon. For example: \"base=blue;face=happy_face\".\n\n"
  134. "Material targets are only renamed if an existing Material maps to that "
  135. "name, or if there is a diffuse texture in the model folder with the same "
  136. "name as the new target.\n\n" );
  137. endGroup("Media");
  138. addGroup("Rendering");
  139. addField( "playAmbient", TypeBool, Offset( mPlayAmbient, TSStatic ),
  140. "Enables automatic playing of the animation sequence named \"ambient\" (if it exists) when the TSStatic is loaded.");
  141. addField( "meshCulling", TypeBool, Offset( mMeshCulling, TSStatic ),
  142. "Enables detailed culling of meshes within the TSStatic. Should only be used "
  143. "with large complex shapes like buildings which contain many submeshes." );
  144. addField( "originSort", TypeBool, Offset( mUseOriginSort, TSStatic ),
  145. "Enables translucent sorting of the TSStatic by its origin instead of the bounds." );
  146. endGroup("Rendering");
  147. addGroup("Collision");
  148. addField( "collisionType", TypeTSMeshType, Offset( mCollisionType, TSStatic ),
  149. "The type of mesh data to use for collision queries." );
  150. addField( "decalType", TypeTSMeshType, Offset( mDecalType, TSStatic ),
  151. "The type of mesh data used to clip decal polygons against." );
  152. addField( "allowPlayerStep", TypeBool, Offset( mAllowPlayerStep, TSStatic ),
  153. "@brief Allow a Player to walk up sloping polygons in the TSStatic (based on the collisionType).\n\n"
  154. "When set to false, the slightest bump will stop the player from walking on top of the object.\n");
  155. endGroup("Collision");
  156. addGroup("Debug");
  157. addField( "renderNormals", TypeF32, Offset( mRenderNormalScalar, TSStatic ),
  158. "Debug rendering mode shows the normals for each point in the TSStatic's mesh." );
  159. addField( "forceDetail", TypeS32, Offset( mForceDetail, TSStatic ),
  160. "Forces rendering to a particular detail level." );
  161. endGroup("Debug");
  162. Parent::initPersistFields();
  163. }
  164. bool TSStatic::_setFieldSkin( void *object, const char *index, const char *data )
  165. {
  166. TSStatic *ts = static_cast<TSStatic*>( object );
  167. if ( ts )
  168. ts->setSkinName( data );
  169. return false;
  170. }
  171. const char *TSStatic::_getFieldSkin( void *object, const char *data )
  172. {
  173. TSStatic *ts = static_cast<TSStatic*>( object );
  174. return ts ? ts->mSkinNameHandle.getString() : "";
  175. }
  176. void TSStatic::inspectPostApply()
  177. {
  178. // Apply any transformations set in the editor
  179. Parent::inspectPostApply();
  180. if(isServerObject())
  181. {
  182. setMaskBits(AdvancedStaticOptionsMask);
  183. prepCollision();
  184. }
  185. _updateShouldTick();
  186. }
  187. bool TSStatic::onAdd()
  188. {
  189. PROFILE_SCOPE(TSStatic_onAdd);
  190. if ( isServerObject() )
  191. {
  192. // Handle the old "usePolysoup" field
  193. SimFieldDictionary* fieldDict = getFieldDictionary();
  194. if ( fieldDict )
  195. {
  196. StringTableEntry slotName = StringTable->insert( "usePolysoup" );
  197. SimFieldDictionary::Entry * entry = fieldDict->findDynamicField( slotName );
  198. if ( entry )
  199. {
  200. // Was "usePolysoup" set?
  201. bool usePolysoup = dAtob( entry->value );
  202. // "usePolysoup" maps to the new VisibleMesh type
  203. if ( usePolysoup )
  204. mCollisionType = VisibleMesh;
  205. // Remove the field in favor on the new "collisionType" field
  206. fieldDict->setFieldValue( slotName, "" );
  207. }
  208. }
  209. }
  210. if ( !Parent::onAdd() )
  211. return false;
  212. // Setup the shape.
  213. if ( !_createShape() )
  214. {
  215. Con::errorf( "TSStatic::onAdd() - Shape creation failed!" );
  216. return false;
  217. }
  218. setRenderTransform(mObjToWorld);
  219. // Register for the resource change signal.
  220. ResourceManager::get().getChangedSignal().notify( this, &TSStatic::_onResourceChanged );
  221. addToScene();
  222. _updateShouldTick();
  223. return true;
  224. }
  225. bool TSStatic::_createShape()
  226. {
  227. // Cleanup before we create.
  228. mCollisionDetails.clear();
  229. mLOSDetails.clear();
  230. SAFE_DELETE( mPhysicsRep );
  231. SAFE_DELETE( mShapeInstance );
  232. mAmbientThread = NULL;
  233. mShape = NULL;
  234. if (!mShapeName || mShapeName[0] == '\0')
  235. {
  236. Con::errorf( "TSStatic::_createShape() - No shape name!" );
  237. return false;
  238. }
  239. mShapeHash = _StringTable::hashString(mShapeName);
  240. mShape = ResourceManager::get().load(mShapeName);
  241. if ( bool(mShape) == false )
  242. {
  243. Con::errorf( "TSStatic::_createShape() - Unable to load shape: %s", mShapeName );
  244. return false;
  245. }
  246. if ( isClientObject() &&
  247. !mShape->preloadMaterialList(mShape.getPath()) &&
  248. NetConnection::filesWereDownloaded() )
  249. return false;
  250. mObjBox = mShape->bounds;
  251. resetWorldBox();
  252. mShapeInstance = new TSShapeInstance( mShape, isClientObject() );
  253. if( isGhost() )
  254. {
  255. // Reapply the current skin
  256. mAppliedSkinName = "";
  257. reSkin();
  258. }
  259. prepCollision();
  260. // Find the "ambient" animation if it exists
  261. S32 ambientSeq = mShape->findSequence("ambient");
  262. if ( ambientSeq > -1 && !mAmbientThread )
  263. mAmbientThread = mShapeInstance->addThread();
  264. if ( mAmbientThread )
  265. mShapeInstance->setSequence( mAmbientThread, ambientSeq, 0);
  266. return true;
  267. }
  268. void TSStatic::prepCollision()
  269. {
  270. // Let the client know that the collision was updated
  271. setMaskBits( UpdateCollisionMask );
  272. // Allow the ShapeInstance to prep its collision if it hasn't already
  273. if ( mShapeInstance )
  274. mShapeInstance->prepCollision();
  275. // Cleanup any old collision data
  276. mCollisionDetails.clear();
  277. mLOSDetails.clear();
  278. mConvexList->nukeList();
  279. if ( mCollisionType == CollisionMesh || mCollisionType == VisibleMesh )
  280. mShape->findColDetails( mCollisionType == VisibleMesh, &mCollisionDetails, &mLOSDetails );
  281. _updatePhysics();
  282. }
  283. void TSStatic::_updatePhysics()
  284. {
  285. SAFE_DELETE( mPhysicsRep );
  286. if ( !PHYSICSMGR || mCollisionType == None )
  287. return;
  288. PhysicsCollision *colShape = NULL;
  289. if ( mCollisionType == Bounds )
  290. {
  291. MatrixF offset( true );
  292. offset.setPosition( mShape->center );
  293. colShape = PHYSICSMGR->createCollision();
  294. colShape->addBox( getObjBox().getExtents() * 0.5f * mObjScale, offset );
  295. }
  296. else
  297. colShape = mShape->buildColShape( mCollisionType == VisibleMesh, getScale() );
  298. if ( colShape )
  299. {
  300. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  301. mPhysicsRep = PHYSICSMGR->createBody();
  302. mPhysicsRep->init( colShape, 0, 0, this, world );
  303. mPhysicsRep->setTransform( getTransform() );
  304. }
  305. }
  306. void TSStatic::onRemove()
  307. {
  308. SAFE_DELETE( mPhysicsRep );
  309. mConvexList->nukeList();
  310. removeFromScene();
  311. // Remove the resource change signal.
  312. ResourceManager::get().getChangedSignal().remove( this, &TSStatic::_onResourceChanged );
  313. delete mShapeInstance;
  314. mShapeInstance = NULL;
  315. mAmbientThread = NULL;
  316. Parent::onRemove();
  317. }
  318. void TSStatic::_onResourceChanged( const Torque::Path &path )
  319. {
  320. if ( path != Path( mShapeName ) )
  321. return;
  322. _createShape();
  323. _updateShouldTick();
  324. }
  325. void TSStatic::setSkinName( const char *name )
  326. {
  327. if ( !isGhost() )
  328. {
  329. if ( name[0] != '\0' )
  330. {
  331. // Use tags for better network performance
  332. // Should be a tag, but we'll convert to one if it isn't.
  333. if ( name[0] == StringTagPrefixByte )
  334. mSkinNameHandle = NetStringHandle( U32(dAtoi(name + 1)) );
  335. else
  336. mSkinNameHandle = NetStringHandle( name );
  337. }
  338. else
  339. mSkinNameHandle = NetStringHandle();
  340. setMaskBits( SkinMask );
  341. }
  342. }
  343. void TSStatic::reSkin()
  344. {
  345. if ( isGhost() && mShapeInstance && mSkinNameHandle.isValidString() )
  346. {
  347. Vector<String> skins;
  348. String(mSkinNameHandle.getString()).split( ";", skins );
  349. for (int i = 0; i < skins.size(); i++)
  350. {
  351. String oldSkin( mAppliedSkinName.c_str() );
  352. String newSkin( skins[i] );
  353. // Check if the skin handle contains an explicit "old" base string. This
  354. // allows all models to support skinning, even if they don't follow the
  355. // "base_xxx" material naming convention.
  356. S32 split = newSkin.find( '=' ); // "old=new" format skin?
  357. if ( split != String::NPos )
  358. {
  359. oldSkin = newSkin.substr( 0, split );
  360. newSkin = newSkin.erase( 0, split+1 );
  361. }
  362. mShapeInstance->reSkin( newSkin, oldSkin );
  363. mAppliedSkinName = newSkin;
  364. }
  365. }
  366. }
  367. void TSStatic::processTick( const Move *move )
  368. {
  369. AssertFatal( mPlayAmbient && mAmbientThread, "TSSTatic::adanceTime called with nothing to play." );
  370. if ( isServerObject() )
  371. mShapeInstance->advanceTime( TickSec, mAmbientThread );
  372. }
  373. void TSStatic::interpolateTick( F32 delta )
  374. {
  375. }
  376. void TSStatic::advanceTime( F32 dt )
  377. {
  378. AssertFatal( mPlayAmbient && mAmbientThread, "TSSTatic::advanceTime called with nothing to play." );
  379. mShapeInstance->advanceTime( dt, mAmbientThread );
  380. }
  381. void TSStatic::_updateShouldTick()
  382. {
  383. bool shouldTick = mPlayAmbient && mAmbientThread;
  384. if ( isTicking() != shouldTick )
  385. setProcessTick( shouldTick );
  386. }
  387. void TSStatic::prepRenderImage( SceneRenderState* state )
  388. {
  389. if( !mShapeInstance )
  390. return;
  391. Point3F cameraOffset;
  392. getRenderTransform().getColumn(3,&cameraOffset);
  393. cameraOffset -= state->getDiffuseCameraPosition();
  394. F32 dist = cameraOffset.len();
  395. if (dist < 0.01f)
  396. dist = 0.01f;
  397. F32 invScale = (1.0f/getMax(getMax(mObjScale.x,mObjScale.y),mObjScale.z));
  398. if ( mForceDetail == -1 )
  399. mShapeInstance->setDetailFromDistance( state, dist * invScale );
  400. else
  401. mShapeInstance->setCurrentDetail( mForceDetail );
  402. if ( mShapeInstance->getCurrentDetail() < 0 )
  403. return;
  404. GFXTransformSaver saver;
  405. // Set up our TS render state.
  406. TSRenderState rdata;
  407. rdata.setSceneState( state );
  408. rdata.setFadeOverride( 1.0f );
  409. rdata.setOriginSort( mUseOriginSort );
  410. // If we have submesh culling enabled then prepare
  411. // the object space frustum to pass to the shape.
  412. Frustum culler;
  413. if ( mMeshCulling )
  414. {
  415. culler = state->getCullingFrustum();
  416. MatrixF xfm( true );
  417. xfm.scale( Point3F::One / getScale() );
  418. xfm.mul( getRenderWorldTransform() );
  419. xfm.mul( culler.getTransform() );
  420. culler.setTransform( xfm );
  421. rdata.setCuller( &culler );
  422. }
  423. // We might have some forward lit materials
  424. // so pass down a query to gather lights.
  425. LightQuery query;
  426. query.init( getWorldSphere() );
  427. rdata.setLightQuery( &query );
  428. MatrixF mat = getRenderTransform();
  429. mat.scale( mObjScale );
  430. GFX->setWorldMatrix( mat );
  431. mShapeInstance->animate();
  432. mShapeInstance->render( rdata );
  433. if ( mRenderNormalScalar > 0 )
  434. {
  435. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  436. ri->renderDelegate.bind( this, &TSStatic::_renderNormals );
  437. ri->type = RenderPassManager::RIT_Editor;
  438. state->getRenderPass()->addInst( ri );
  439. }
  440. }
  441. void TSStatic::_renderNormals( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  442. {
  443. PROFILE_SCOPE( TSStatic_RenderNormals );
  444. GFXTransformSaver saver;
  445. MatrixF mat = getRenderTransform();
  446. mat.scale( mObjScale );
  447. GFX->multWorld( mat );
  448. S32 dl = mShapeInstance->getCurrentDetail();
  449. mShapeInstance->renderDebugNormals( mRenderNormalScalar, dl );
  450. }
  451. void TSStatic::onScaleChanged()
  452. {
  453. Parent::onScaleChanged();
  454. if ( mPhysicsRep )
  455. {
  456. // If the editor is enabled delay the scale operation
  457. // by a few milliseconds so that we're not rebuilding
  458. // during an active scale drag operation.
  459. if ( gEditingMission )
  460. mPhysicsRep->queueCallback( 500, Delegate<void()>( this, &TSStatic::_updatePhysics ) );
  461. else
  462. _updatePhysics();
  463. }
  464. }
  465. void TSStatic::setTransform(const MatrixF & mat)
  466. {
  467. Parent::setTransform(mat);
  468. setMaskBits( TransformMask );
  469. if ( mPhysicsRep )
  470. mPhysicsRep->setTransform( mat );
  471. // Since this is a static it's render transform changes 1
  472. // to 1 with it's collision transform... no interpolation.
  473. setRenderTransform(mat);
  474. }
  475. U32 TSStatic::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  476. {
  477. U32 retMask = Parent::packUpdate(con, mask, stream);
  478. mathWrite( *stream, getTransform() );
  479. mathWrite( *stream, getScale() );
  480. stream->writeString( mShapeName );
  481. if ( stream->writeFlag( mask & UpdateCollisionMask ) )
  482. stream->write( (U32)mCollisionType );
  483. if ( stream->writeFlag( mask & SkinMask ) )
  484. con->packNetStringHandleU( stream, mSkinNameHandle );
  485. stream->write( (U32)mDecalType );
  486. stream->writeFlag( mAllowPlayerStep );
  487. stream->writeFlag( mMeshCulling );
  488. stream->writeFlag( mUseOriginSort );
  489. stream->write( mRenderNormalScalar );
  490. stream->write( mForceDetail );
  491. stream->writeFlag( mPlayAmbient );
  492. if ( mLightPlugin )
  493. retMask |= mLightPlugin->packUpdate(this, AdvancedStaticOptionsMask, con, mask, stream);
  494. return retMask;
  495. }
  496. void TSStatic::unpackUpdate(NetConnection *con, BitStream *stream)
  497. {
  498. Parent::unpackUpdate(con, stream);
  499. MatrixF mat;
  500. Point3F scale;
  501. mathRead( *stream, &mat );
  502. mathRead( *stream, &scale );
  503. setScale( scale);
  504. setTransform(mat);
  505. mShapeName = stream->readSTString();
  506. if ( stream->readFlag() ) // UpdateCollisionMask
  507. {
  508. U32 collisionType = CollisionMesh;
  509. stream->read( &collisionType );
  510. // Handle it if we have changed CollisionType's
  511. if ( (MeshType)collisionType != mCollisionType )
  512. {
  513. mCollisionType = (MeshType)collisionType;
  514. if ( isProperlyAdded() && mShapeInstance )
  515. prepCollision();
  516. }
  517. }
  518. if (stream->readFlag()) // SkinMask
  519. {
  520. NetStringHandle skinDesiredNameHandle = con->unpackNetStringHandleU(stream);;
  521. if (mSkinNameHandle != skinDesiredNameHandle)
  522. {
  523. mSkinNameHandle = skinDesiredNameHandle;
  524. reSkin();
  525. }
  526. }
  527. stream->read( (U32*)&mDecalType );
  528. mAllowPlayerStep = stream->readFlag();
  529. mMeshCulling = stream->readFlag();
  530. mUseOriginSort = stream->readFlag();
  531. stream->read( &mRenderNormalScalar );
  532. stream->read( &mForceDetail );
  533. mPlayAmbient = stream->readFlag();
  534. if ( mLightPlugin )
  535. {
  536. mLightPlugin->unpackUpdate(this, con, stream);
  537. }
  538. if ( isProperlyAdded() )
  539. _updateShouldTick();
  540. }
  541. //----------------------------------------------------------------------------
  542. bool TSStatic::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  543. {
  544. if ( mCollisionType == None )
  545. return false;
  546. if ( !mShapeInstance )
  547. return false;
  548. if ( mCollisionType == Bounds )
  549. {
  550. F32 st, et, fst = 0.0f, fet = 1.0f;
  551. F32 *bmin = &mObjBox.minExtents.x;
  552. F32 *bmax = &mObjBox.maxExtents.x;
  553. F32 const *si = &start.x;
  554. F32 const *ei = &end.x;
  555. for ( U32 i = 0; i < 3; i++ )
  556. {
  557. if (*si < *ei)
  558. {
  559. if ( *si > *bmax || *ei < *bmin )
  560. return false;
  561. F32 di = *ei - *si;
  562. st = ( *si < *bmin ) ? ( *bmin - *si ) / di : 0.0f;
  563. et = ( *ei > *bmax ) ? ( *bmax - *si ) / di : 1.0f;
  564. }
  565. else
  566. {
  567. if ( *ei > *bmax || *si < *bmin )
  568. return false;
  569. F32 di = *ei - *si;
  570. st = ( *si > *bmax ) ? ( *bmax - *si ) / di : 0.0f;
  571. et = ( *ei < *bmin ) ? ( *bmin - *si ) / di : 1.0f;
  572. }
  573. if ( st > fst ) fst = st;
  574. if ( et < fet ) fet = et;
  575. if ( fet < fst )
  576. return false;
  577. bmin++; bmax++;
  578. si++; ei++;
  579. }
  580. info->normal = start - end;
  581. info->normal.normalizeSafe();
  582. getTransform().mulV( info->normal );
  583. info->t = fst;
  584. info->object = this;
  585. info->point.interpolate( start, end, fst );
  586. info->material = NULL;
  587. return true;
  588. }
  589. else
  590. {
  591. RayInfo shortest = *info;
  592. RayInfo localInfo;
  593. shortest.t = 1e8f;
  594. localInfo.generateTexCoord = info->generateTexCoord;
  595. for ( U32 i = 0; i < mLOSDetails.size(); i++ )
  596. {
  597. mShapeInstance->animate( mLOSDetails[i] );
  598. if ( mShapeInstance->castRayOpcode( mLOSDetails[i], start, end, &localInfo ) )
  599. {
  600. localInfo.object = this;
  601. if (localInfo.t < shortest.t)
  602. shortest = localInfo;
  603. }
  604. }
  605. if (shortest.object == this)
  606. {
  607. // Copy out the shortest time...
  608. *info = shortest;
  609. return true;
  610. }
  611. }
  612. return false;
  613. }
  614. bool TSStatic::castRayRendered(const Point3F &start, const Point3F &end, RayInfo *info)
  615. {
  616. if ( !mShapeInstance )
  617. return false;
  618. // Cast the ray against the currently visible detail
  619. RayInfo localInfo;
  620. bool res = mShapeInstance->castRayOpcode( mShapeInstance->getCurrentDetail(), start, end, &localInfo );
  621. if ( res )
  622. {
  623. *info = localInfo;
  624. info->object = this;
  625. return true;
  626. }
  627. return false;
  628. }
  629. bool TSStatic::buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF &)
  630. {
  631. if ( !mShapeInstance )
  632. return false;
  633. // This is safe to set even if we're not outputing
  634. polyList->setTransform( &mObjToWorld, mObjScale );
  635. polyList->setObject( this );
  636. if ( context == PLC_Export )
  637. {
  638. // Use highest detail level
  639. S32 dl = 0;
  640. // Try to call on the client so we can export materials
  641. if ( isServerObject() && getClientObject() )
  642. dynamic_cast<TSStatic*>(getClientObject())->mShapeInstance->buildPolyList( polyList, dl );
  643. else
  644. mShapeInstance->buildPolyList( polyList, dl );
  645. }
  646. else if ( context == PLC_Selection )
  647. {
  648. // Use the last rendered detail level
  649. S32 dl = mShapeInstance->getCurrentDetail();
  650. mShapeInstance->buildPolyListOpcode( dl, polyList, box );
  651. }
  652. else
  653. {
  654. // Figure out the mesh type we're looking for.
  655. MeshType meshType = ( context == PLC_Decal ) ? mDecalType : mCollisionType;
  656. if ( meshType == None )
  657. return false;
  658. else if ( meshType == Bounds )
  659. polyList->addBox( mObjBox );
  660. else if ( meshType == VisibleMesh )
  661. mShapeInstance->buildPolyList( polyList, 0 );
  662. else
  663. {
  664. // Everything else is done from the collision meshes
  665. // which may be built from either the visual mesh or
  666. // special collision geometry.
  667. for ( U32 i = 0; i < mCollisionDetails.size(); i++ )
  668. mShapeInstance->buildPolyListOpcode( mCollisionDetails[i], polyList, box );
  669. }
  670. }
  671. return true;
  672. }
  673. void TSStatic::buildConvex(const Box3F& box, Convex* convex)
  674. {
  675. if ( mCollisionType == None )
  676. return;
  677. if ( mShapeInstance == NULL )
  678. return;
  679. // These should really come out of a pool
  680. mConvexList->collectGarbage();
  681. if ( mCollisionType == Bounds )
  682. {
  683. // Just return a box convex for the entire shape...
  684. Convex* cc = 0;
  685. CollisionWorkingList& wl = convex->getWorkingList();
  686. for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext)
  687. {
  688. if (itr->mConvex->getType() == BoxConvexType &&
  689. itr->mConvex->getObject() == this)
  690. {
  691. cc = itr->mConvex;
  692. break;
  693. }
  694. }
  695. if (cc)
  696. return;
  697. // Create a new convex.
  698. BoxConvex* cp = new BoxConvex;
  699. mConvexList->registerObject(cp);
  700. convex->addToWorkingList(cp);
  701. cp->init(this);
  702. mObjBox.getCenter(&cp->mCenter);
  703. cp->mSize.x = mObjBox.len_x() / 2.0f;
  704. cp->mSize.y = mObjBox.len_y() / 2.0f;
  705. cp->mSize.z = mObjBox.len_z() / 2.0f;
  706. }
  707. else // CollisionMesh || VisibleMesh
  708. {
  709. TSStaticPolysoupConvex::smCurObject = this;
  710. for (U32 i = 0; i < mCollisionDetails.size(); i++)
  711. mShapeInstance->buildConvexOpcode( mObjToWorld, mObjScale, mCollisionDetails[i], box, convex, mConvexList );
  712. TSStaticPolysoupConvex::smCurObject = NULL;
  713. }
  714. }
  715. SceneObject* TSStaticPolysoupConvex::smCurObject = NULL;
  716. TSStaticPolysoupConvex::TSStaticPolysoupConvex()
  717. : box( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f ),
  718. normal( 0.0f, 0.0f, 0.0f, 0.0f ),
  719. idx( 0 ),
  720. mesh( NULL )
  721. {
  722. mType = TSPolysoupConvexType;
  723. for ( U32 i = 0; i < 4; ++i )
  724. {
  725. verts[i].set( 0.0f, 0.0f, 0.0f );
  726. }
  727. }
  728. Point3F TSStaticPolysoupConvex::support(const VectorF& vec) const
  729. {
  730. F32 bestDot = mDot( verts[0], vec );
  731. const Point3F *bestP = &verts[0];
  732. for(S32 i=1; i<4; i++)
  733. {
  734. F32 newD = mDot(verts[i], vec);
  735. if(newD > bestDot)
  736. {
  737. bestDot = newD;
  738. bestP = &verts[i];
  739. }
  740. }
  741. return *bestP;
  742. }
  743. Box3F TSStaticPolysoupConvex::getBoundingBox() const
  744. {
  745. Box3F wbox = box;
  746. wbox.minExtents.convolve( mObject->getScale() );
  747. wbox.maxExtents.convolve( mObject->getScale() );
  748. mObject->getTransform().mul(wbox);
  749. return wbox;
  750. }
  751. Box3F TSStaticPolysoupConvex::getBoundingBox(const MatrixF& mat, const Point3F& scale) const
  752. {
  753. AssertISV(false, "TSStaticPolysoupConvex::getBoundingBox(m,p) - Not implemented. -- XEA");
  754. return box;
  755. }
  756. void TSStaticPolysoupConvex::getPolyList(AbstractPolyList *list)
  757. {
  758. // Transform the list into object space and set the pointer to the object
  759. MatrixF i( mObject->getTransform() );
  760. Point3F iS( mObject->getScale() );
  761. list->setTransform(&i, iS);
  762. list->setObject(mObject);
  763. // Add only the original collision triangle
  764. S32 base = list->addPoint(verts[0]);
  765. list->addPoint(verts[2]);
  766. list->addPoint(verts[1]);
  767. list->begin(0, (U32)idx ^ (U32)mesh);
  768. list->vertex(base + 2);
  769. list->vertex(base + 1);
  770. list->vertex(base + 0);
  771. list->plane(base + 0, base + 1, base + 2);
  772. list->end();
  773. }
  774. void TSStaticPolysoupConvex::getFeatures(const MatrixF& mat,const VectorF& n, ConvexFeature* cf)
  775. {
  776. cf->material = 0;
  777. cf->object = mObject;
  778. // For a tetrahedron this is pretty easy... first
  779. // convert everything into world space.
  780. Point3F tverts[4];
  781. mat.mulP(verts[0], &tverts[0]);
  782. mat.mulP(verts[1], &tverts[1]);
  783. mat.mulP(verts[2], &tverts[2]);
  784. mat.mulP(verts[3], &tverts[3]);
  785. // points...
  786. S32 firstVert = cf->mVertexList.size();
  787. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[0];
  788. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[1];
  789. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[2];
  790. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[3];
  791. // edges...
  792. cf->mEdgeList.increment();
  793. cf->mEdgeList.last().vertex[0] = firstVert+0;
  794. cf->mEdgeList.last().vertex[1] = firstVert+1;
  795. cf->mEdgeList.increment();
  796. cf->mEdgeList.last().vertex[0] = firstVert+1;
  797. cf->mEdgeList.last().vertex[1] = firstVert+2;
  798. cf->mEdgeList.increment();
  799. cf->mEdgeList.last().vertex[0] = firstVert+2;
  800. cf->mEdgeList.last().vertex[1] = firstVert+0;
  801. cf->mEdgeList.increment();
  802. cf->mEdgeList.last().vertex[0] = firstVert+3;
  803. cf->mEdgeList.last().vertex[1] = firstVert+0;
  804. cf->mEdgeList.increment();
  805. cf->mEdgeList.last().vertex[0] = firstVert+3;
  806. cf->mEdgeList.last().vertex[1] = firstVert+1;
  807. cf->mEdgeList.increment();
  808. cf->mEdgeList.last().vertex[0] = firstVert+3;
  809. cf->mEdgeList.last().vertex[1] = firstVert+2;
  810. // triangles...
  811. cf->mFaceList.increment();
  812. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[0]);
  813. cf->mFaceList.last().vertex[0] = firstVert+2;
  814. cf->mFaceList.last().vertex[1] = firstVert+1;
  815. cf->mFaceList.last().vertex[2] = firstVert+0;
  816. cf->mFaceList.increment();
  817. cf->mFaceList.last().normal = PlaneF(tverts[1], tverts[0], tverts[3]);
  818. cf->mFaceList.last().vertex[0] = firstVert+1;
  819. cf->mFaceList.last().vertex[1] = firstVert+0;
  820. cf->mFaceList.last().vertex[2] = firstVert+3;
  821. cf->mFaceList.increment();
  822. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[3]);
  823. cf->mFaceList.last().vertex[0] = firstVert+2;
  824. cf->mFaceList.last().vertex[1] = firstVert+1;
  825. cf->mFaceList.last().vertex[2] = firstVert+3;
  826. cf->mFaceList.increment();
  827. cf->mFaceList.last().normal = PlaneF(tverts[0], tverts[2], tverts[3]);
  828. cf->mFaceList.last().vertex[0] = firstVert+0;
  829. cf->mFaceList.last().vertex[1] = firstVert+2;
  830. cf->mFaceList.last().vertex[2] = firstVert+3;
  831. // All done!
  832. }
  833. //------------------------------------------------------------------------
  834. //These functions are duplicated in tsStatic and shapeBase.
  835. //They each function a little differently; but achieve the same purpose of gathering
  836. //target names/counts without polluting simObject.
  837. DefineEngineMethod( TSStatic, getTargetName, const char*, ( S32 index ),(0),
  838. "Get the name of the indexed shape material.\n"
  839. "@param index index of the material to get (valid range is 0 - getTargetCount()-1).\n"
  840. "@return the name of the indexed material.\n"
  841. "@see getTargetCount()\n")
  842. {
  843. TSStatic *obj = dynamic_cast< TSStatic* > ( object );
  844. if(obj)
  845. {
  846. // Try to use the client object (so we get the reskinned targets in the Material Editor)
  847. if ((TSStatic*)obj->getClientObject())
  848. obj = (TSStatic*)obj->getClientObject();
  849. return obj->getShapeInstance()->getTargetName(index);
  850. }
  851. return "";
  852. }
  853. DefineEngineMethod( TSStatic, getTargetCount, S32,(),,
  854. "Get the number of materials in the shape.\n"
  855. "@return the number of materials in the shape.\n"
  856. "@see getTargetName()\n")
  857. {
  858. TSStatic *obj = dynamic_cast< TSStatic* > ( object );
  859. if(obj)
  860. {
  861. // Try to use the client object (so we get the reskinned targets in the Material Editor)
  862. if ((TSStatic*)obj->getClientObject())
  863. obj = (TSStatic*)obj->getClientObject();
  864. return obj->getShapeInstance()->getTargetCount();
  865. }
  866. return -1;
  867. }
  868. // This method is able to change materials per map to with others. The material that is being replaced is being mapped to
  869. // unmapped_mat as a part of this transition
  870. DefineEngineMethod( TSStatic, changeMaterial, void, ( const char* mapTo, Material* oldMat, Material* newMat ),("",NULL,NULL),
  871. "@brief Change one of the materials on the shape.\n\n"
  872. "This method changes materials per mapTo with others. The material that "
  873. "is being replaced is mapped to unmapped_mat as a part of this transition.\n"
  874. "@note Warning, right now this only sort of works. It doesn't do a live "
  875. "update like it should.\n"
  876. "@param mapTo the name of the material target to remap (from getTargetName)\n"
  877. "@param oldMat the old Material that was mapped \n"
  878. "@param newMat the new Material to map\n\n"
  879. "@tsexample\n"
  880. "// remap the first material in the shape\n"
  881. "%mapTo = %obj.getTargetName( 0 );\n"
  882. "%obj.changeMaterial( %mapTo, 0, MyMaterial );\n"
  883. "@endtsexample\n" )
  884. {
  885. // if no valid new material, theres no reason for doing this
  886. if( !newMat )
  887. {
  888. Con::errorf("TSShape::changeMaterial failed: New material does not exist!");
  889. return;
  890. }
  891. // Check the mapTo name exists for this shape
  892. S32 matIndex = object->getShape()->materialList->getMaterialNameList().find_next(String(mapTo));
  893. if (matIndex < 0)
  894. {
  895. Con::errorf("TSShape::changeMaterial failed: Invalid mapTo name '%s'", mapTo);
  896. return;
  897. }
  898. // Lets remap the old material off, so as to let room for our current material room to claim its spot
  899. if( oldMat )
  900. oldMat->mMapTo = String("unmapped_mat");
  901. newMat->mMapTo = mapTo;
  902. // Map the material by name in the matmgr
  903. MATMGR->mapMaterial( mapTo, newMat->getName() );
  904. // Replace instances with the new material being traded in. Lets make sure that we only
  905. // target the specific targets per inst, this is actually doing more than we thought
  906. delete object->getShape()->materialList->mMatInstList[matIndex];
  907. object->getShape()->materialList->mMatInstList[matIndex] = newMat->createMatInstance();
  908. // Finish up preparing the material instances for rendering
  909. const GFXVertexFormat *flags = getGFXVertexFormat<GFXVertexPNTTB>();
  910. FeatureSet features = MATMGR->getDefaultFeatures();
  911. object->getShape()->materialList->getMaterialInst(matIndex)->init( features, flags );
  912. }
  913. DefineEngineMethod( TSStatic, getModelFile, const char *, (),,
  914. "@brief Get the model filename used by this shape.\n\n"
  915. "@return the shape filename\n\n"
  916. "@tsexample\n"
  917. "// Acquire the model filename used on this shape.\n"
  918. "%modelFilename = %obj.getModelFile();\n"
  919. "@endtsexample\n"
  920. )
  921. {
  922. return object->getShapeFileName();
  923. }