tsStatic.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "T3D/tsStatic.h"
  28. #include "core/resourceManager.h"
  29. #include "core/stream/bitStream.h"
  30. #include "scene/sceneRenderState.h"
  31. #include "scene/sceneManager.h"
  32. #include "scene/sceneObjectLightingPlugin.h"
  33. #include "lighting/lightManager.h"
  34. #include "math/mathIO.h"
  35. #include "ts/tsShapeInstance.h"
  36. #include "ts/tsMaterialList.h"
  37. #include "console/consoleTypes.h"
  38. #include "T3D/shapeBase.h"
  39. #include "sim/netConnection.h"
  40. #include "gfx/gfxDevice.h"
  41. #include "gfx/gfxTransformSaver.h"
  42. #include "ts/tsRenderState.h"
  43. #include "collision/boxConvex.h"
  44. #include "T3D/physics/physicsPlugin.h"
  45. #include "T3D/physics/physicsBody.h"
  46. #include "T3D/physics/physicsCollision.h"
  47. #include "materials/materialDefinition.h"
  48. #include "materials/materialManager.h"
  49. #include "materials/matInstance.h"
  50. #include "materials/materialFeatureData.h"
  51. #include "materials/materialFeatureTypes.h"
  52. #include "console/engineAPI.h"
  53. #include "T3D/accumulationVolume.h"
  54. using namespace Torque;
  55. extern bool gEditingMission;
  56. #ifdef TORQUE_AFX_ENABLED
  57. #include "afx/ce/afxZodiacMgr.h"
  58. #endif
  59. IMPLEMENT_CO_NETOBJECT_V1(TSStatic);
  60. ConsoleDocClass( TSStatic,
  61. "@brief A static object derived from a 3D model file and placed within the game world.\n\n"
  62. "TSStatic is the most basic 3D shape in Torque. Unlike StaticShape it doesn't make use of "
  63. "a datablock. It derrives directly from SceneObject. This makes TSStatic extremely light "
  64. "weight, which is why the Tools use this class when you want to drop in a DTS or DAE object.\n\n"
  65. "While a TSStatic doesn't provide any motion -- it stays were you initally put it -- it does allow for "
  66. "a single ambient animation sequence to play when the object is first added to the scene.\n\n"
  67. "@tsexample\n"
  68. "new TSStatic(Team1Base) {\n"
  69. " shapeName = \"art/shapes/desertStructures/station01.dts\";\n"
  70. " playAmbient = \"1\";\n"
  71. " receiveSunLight = \"1\";\n"
  72. " receiveLMLighting = \"1\";\n"
  73. " useCustomAmbientLighting = \"0\";\n"
  74. " customAmbientLighting = \"0 0 0 1\";\n"
  75. " collisionType = \"Visible Mesh\";\n"
  76. " decalType = \"Collision Mesh\";\n"
  77. " allowPlayerStep = \"1\";\n"
  78. " renderNormals = \"0\";\n"
  79. " forceDetail = \"-1\";\n"
  80. " position = \"315.18 -180.418 244.313\";\n"
  81. " rotation = \"0 0 1 195.952\";\n"
  82. " scale = \"1 1 1\";\n"
  83. " isRenderEnabled = \"true\";\n"
  84. " canSaveDynamicFields = \"1\";\n"
  85. "};\n"
  86. "@endtsexample\n"
  87. "@ingroup gameObjects\n"
  88. );
  89. TSStatic::TSStatic()
  90. :
  91. cubeDescId( 0 ),
  92. reflectorDesc( NULL )
  93. {
  94. mNetFlags.set(Ghostable | ScopeAlways);
  95. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  96. mShapeName = "";
  97. mShapeInstance = NULL;
  98. mPlayAmbient = true;
  99. mAmbientThread = NULL;
  100. mAllowPlayerStep = false;
  101. mConvexList = new Convex;
  102. mRenderNormalScalar = 0;
  103. mForceDetail = -1;
  104. mMeshCulling = false;
  105. mUseOriginSort = false;
  106. mUseAlphaFade = false;
  107. mAlphaFadeStart = 100.0f;
  108. mAlphaFadeEnd = 150.0f;
  109. mInvertAlphaFade = false;
  110. mAlphaFade = 1.0f;
  111. mPhysicsRep = NULL;
  112. mCollisionType = CollisionMesh;
  113. mDecalType = CollisionMesh;
  114. mIgnoreZodiacs = false;
  115. mHasGradients = false;
  116. mInvertGradientRange = false;
  117. mGradientRangeUser.set(0.0f, 180.0f);
  118. #ifdef TORQUE_AFX_ENABLED
  119. afxZodiacData::convertGradientRangeFromDegrees(mGradientRange, mGradientRangeUser);
  120. #endif
  121. }
  122. TSStatic::~TSStatic()
  123. {
  124. delete mConvexList;
  125. mConvexList = NULL;
  126. }
  127. ImplementEnumType( TSMeshType,
  128. "Type of mesh data available in a shape.\n"
  129. "@ingroup gameObjects" )
  130. { TSStatic::None, "None", "No mesh data." },
  131. { TSStatic::Bounds, "Bounds", "Bounding box of the shape." },
  132. { TSStatic::CollisionMesh, "Collision Mesh", "Specifically desingated \"collision\" meshes." },
  133. { TSStatic::VisibleMesh, "Visible Mesh", "Rendered mesh polygons." },
  134. EndImplementEnumType;
  135. void TSStatic::initPersistFields()
  136. {
  137. addGroup("Media");
  138. addField("shapeName", TypeShapeFilename, Offset( mShapeName, TSStatic ),
  139. "%Path and filename of the model file (.DTS, .DAE) to use for this TSStatic." );
  140. addProtectedField( "skin", TypeRealString, Offset( mAppliedSkinName, TSStatic ), &_setFieldSkin, &_getFieldSkin,
  141. "@brief The skin applied to the shape.\n\n"
  142. "'Skinning' the shape effectively renames the material targets, allowing "
  143. "different materials to be used on different instances of the same model.\n\n"
  144. "Any material targets that start with the old skin name have that part "
  145. "of the name replaced with the new skin name. The initial old skin name is "
  146. "\"base\". For example, if a new skin of \"blue\" was applied to a model "
  147. "that had material targets <i>base_body</i> and <i>face</i>, the new targets "
  148. "would be <i>blue_body</i> and <i>face</i>. Note that <i>face</i> was not "
  149. "renamed since it did not start with the old skin name of \"base\".\n\n"
  150. "To support models that do not use the default \"base\" naming convention, "
  151. "you can also specify the part of the name to replace in the skin field "
  152. "itself. For example, if a model had a material target called <i>shapemat</i>, "
  153. "we could apply a new skin \"shape=blue\", and the material target would be "
  154. "renamed to <i>bluemat</i> (note \"shape\" has been replaced with \"blue\").\n\n"
  155. "Multiple skin updates can also be applied at the same time by separating "
  156. "them with a semicolon. For example: \"base=blue;face=happy_face\".\n\n"
  157. "Material targets are only renamed if an existing Material maps to that "
  158. "name, or if there is a diffuse texture in the model folder with the same "
  159. "name as the new target.\n\n" );
  160. endGroup("Media");
  161. addGroup("Rendering");
  162. addField( "playAmbient", TypeBool, Offset( mPlayAmbient, TSStatic ),
  163. "Enables automatic playing of the animation sequence named \"ambient\" (if it exists) when the TSStatic is loaded.");
  164. addField( "meshCulling", TypeBool, Offset( mMeshCulling, TSStatic ),
  165. "Enables detailed culling of meshes within the TSStatic. Should only be used "
  166. "with large complex shapes like buildings which contain many submeshes." );
  167. addField( "originSort", TypeBool, Offset( mUseOriginSort, TSStatic ),
  168. "Enables translucent sorting of the TSStatic by its origin instead of the bounds." );
  169. endGroup("Rendering");
  170. addGroup( "Reflection" );
  171. addField( "cubeReflectorDesc", TypeRealString, Offset( cubeDescName, TSStatic ),
  172. "References a ReflectorDesc datablock that defines performance and quality properties for dynamic reflections.\n");
  173. endGroup( "Reflection" );
  174. addGroup("Collision");
  175. addField( "collisionType", TypeTSMeshType, Offset( mCollisionType, TSStatic ),
  176. "The type of mesh data to use for collision queries." );
  177. addField( "decalType", TypeTSMeshType, Offset( mDecalType, TSStatic ),
  178. "The type of mesh data used to clip decal polygons against." );
  179. addField( "allowPlayerStep", TypeBool, Offset( mAllowPlayerStep, TSStatic ),
  180. "@brief Allow a Player to walk up sloping polygons in the TSStatic (based on the collisionType).\n\n"
  181. "When set to false, the slightest bump will stop the player from walking on top of the object.\n");
  182. endGroup("Collision");
  183. addGroup( "AlphaFade" );
  184. addField( "alphaFadeEnable", TypeBool, Offset(mUseAlphaFade, TSStatic), "Turn on/off Alpha Fade" );
  185. addField( "alphaFadeStart", TypeF32, Offset(mAlphaFadeStart, TSStatic), "Distance of start Alpha Fade" );
  186. addField( "alphaFadeEnd", TypeF32, Offset(mAlphaFadeEnd, TSStatic), "Distance of end Alpha Fade" );
  187. addField( "alphaFadeInverse", TypeBool, Offset(mInvertAlphaFade, TSStatic), "Invert Alpha Fade's Start & End Distance" );
  188. endGroup( "AlphaFade" );
  189. addGroup("Debug");
  190. addField( "renderNormals", TypeF32, Offset( mRenderNormalScalar, TSStatic ),
  191. "Debug rendering mode shows the normals for each point in the TSStatic's mesh." );
  192. addField( "forceDetail", TypeS32, Offset( mForceDetail, TSStatic ),
  193. "Forces rendering to a particular detail level." );
  194. endGroup("Debug");
  195. addGroup("AFX");
  196. addField("ignoreZodiacs", TypeBool, Offset(mIgnoreZodiacs, TSStatic));
  197. addField("useGradientRange", TypeBool, Offset(mHasGradients, TSStatic));
  198. addField("gradientRange", TypePoint2F, Offset(mGradientRangeUser, TSStatic));
  199. addField("invertGradientRange", TypeBool, Offset(mInvertGradientRange, TSStatic));
  200. endGroup("AFX");
  201. Parent::initPersistFields();
  202. }
  203. bool TSStatic::_setFieldSkin( void *object, const char *index, const char *data )
  204. {
  205. TSStatic *ts = static_cast<TSStatic*>( object );
  206. if ( ts )
  207. ts->setSkinName( data );
  208. return false;
  209. }
  210. const char *TSStatic::_getFieldSkin( void *object, const char *data )
  211. {
  212. TSStatic *ts = static_cast<TSStatic*>( object );
  213. return ts ? ts->mSkinNameHandle.getString() : "";
  214. }
  215. void TSStatic::inspectPostApply()
  216. {
  217. // Apply any transformations set in the editor
  218. Parent::inspectPostApply();
  219. if(isServerObject())
  220. {
  221. setMaskBits(AdvancedStaticOptionsMask);
  222. prepCollision();
  223. }
  224. _updateShouldTick();
  225. }
  226. bool TSStatic::onAdd()
  227. {
  228. PROFILE_SCOPE(TSStatic_onAdd);
  229. if ( isServerObject() )
  230. {
  231. // Handle the old "usePolysoup" field
  232. SimFieldDictionary* fieldDict = getFieldDictionary();
  233. if ( fieldDict )
  234. {
  235. StringTableEntry slotName = StringTable->insert( "usePolysoup" );
  236. SimFieldDictionary::Entry * entry = fieldDict->findDynamicField( slotName );
  237. if ( entry )
  238. {
  239. // Was "usePolysoup" set?
  240. bool usePolysoup = dAtob( entry->value );
  241. // "usePolysoup" maps to the new VisibleMesh type
  242. if ( usePolysoup )
  243. mCollisionType = VisibleMesh;
  244. // Remove the field in favor on the new "collisionType" field
  245. fieldDict->setFieldValue( slotName, "" );
  246. }
  247. }
  248. }
  249. if ( !Parent::onAdd() )
  250. return false;
  251. // Setup the shape.
  252. if ( !_createShape() )
  253. {
  254. Con::errorf( "TSStatic::onAdd() - Shape creation failed!" );
  255. return false;
  256. }
  257. setRenderTransform(mObjToWorld);
  258. // Register for the resource change signal.
  259. ResourceManager::get().getChangedSignal().notify( this, &TSStatic::_onResourceChanged );
  260. addToScene();
  261. if ( isClientObject() )
  262. {
  263. mCubeReflector.unregisterReflector();
  264. if ( reflectorDesc )
  265. mCubeReflector.registerReflector( this, reflectorDesc );
  266. }
  267. _updateShouldTick();
  268. // Accumulation and environment mapping
  269. if (isClientObject() && mShapeInstance)
  270. {
  271. AccumulationVolume::addObject(this);
  272. }
  273. return true;
  274. }
  275. bool TSStatic::_createShape()
  276. {
  277. // Cleanup before we create.
  278. mCollisionDetails.clear();
  279. mDecalDetails.clear();
  280. mDecalDetailsPtr = 0;
  281. mLOSDetails.clear();
  282. SAFE_DELETE( mPhysicsRep );
  283. SAFE_DELETE( mShapeInstance );
  284. mAmbientThread = NULL;
  285. mShape = NULL;
  286. if (!mShapeName || mShapeName[0] == '\0')
  287. {
  288. Con::errorf( "TSStatic::_createShape() - No shape name!" );
  289. return false;
  290. }
  291. mShapeHash = _StringTable::hashString(mShapeName);
  292. mShape = ResourceManager::get().load(mShapeName);
  293. if ( bool(mShape) == false )
  294. {
  295. Con::errorf( "TSStatic::_createShape() - Unable to load shape: %s", mShapeName );
  296. return false;
  297. }
  298. if ( isClientObject() &&
  299. !mShape->preloadMaterialList(mShape.getPath()) &&
  300. NetConnection::filesWereDownloaded() )
  301. return false;
  302. mObjBox = mShape->mBounds;
  303. resetWorldBox();
  304. mShapeInstance = new TSShapeInstance( mShape, isClientObject() );
  305. if (isClientObject())
  306. mShapeInstance->cloneMaterialList();
  307. if( isGhost() )
  308. {
  309. // Reapply the current skin
  310. mAppliedSkinName = "";
  311. reSkin();
  312. }
  313. prepCollision();
  314. // Find the "ambient" animation if it exists
  315. S32 ambientSeq = mShape->findSequence("ambient");
  316. if ( ambientSeq > -1 && !mAmbientThread )
  317. mAmbientThread = mShapeInstance->addThread();
  318. if ( mAmbientThread )
  319. mShapeInstance->setSequence( mAmbientThread, ambientSeq, 0);
  320. // Resolve CubeReflectorDesc.
  321. if ( cubeDescName.isNotEmpty() )
  322. {
  323. Sim::findObject( cubeDescName, reflectorDesc );
  324. }
  325. else if( cubeDescId > 0 )
  326. {
  327. Sim::findObject( cubeDescId, reflectorDesc );
  328. }
  329. return true;
  330. }
  331. void TSStatic::prepCollision()
  332. {
  333. // Let the client know that the collision was updated
  334. setMaskBits( UpdateCollisionMask );
  335. // Allow the ShapeInstance to prep its collision if it hasn't already
  336. if ( mShapeInstance )
  337. mShapeInstance->prepCollision();
  338. // Cleanup any old collision data
  339. mCollisionDetails.clear();
  340. mDecalDetails.clear();
  341. mDecalDetailsPtr = 0;
  342. mLOSDetails.clear();
  343. mConvexList->nukeList();
  344. if ( mCollisionType == CollisionMesh || mCollisionType == VisibleMesh )
  345. {
  346. mShape->findColDetails( mCollisionType == VisibleMesh, &mCollisionDetails, &mLOSDetails );
  347. if ( mDecalType == mCollisionType )
  348. {
  349. mDecalDetailsPtr = &mCollisionDetails;
  350. }
  351. else if ( mDecalType == CollisionMesh || mDecalType == VisibleMesh )
  352. {
  353. mShape->findColDetails( mDecalType == VisibleMesh, &mDecalDetails, 0 );
  354. mDecalDetailsPtr = &mDecalDetails;
  355. }
  356. }
  357. else if ( mDecalType == CollisionMesh || mDecalType == VisibleMesh )
  358. {
  359. mShape->findColDetails( mDecalType == VisibleMesh, &mDecalDetails, 0 );
  360. mDecalDetailsPtr = &mDecalDetails;
  361. }
  362. _updatePhysics();
  363. }
  364. void TSStatic::_updatePhysics()
  365. {
  366. SAFE_DELETE( mPhysicsRep );
  367. if ( !PHYSICSMGR || mCollisionType == None )
  368. return;
  369. PhysicsCollision *colShape = NULL;
  370. if ( mCollisionType == Bounds )
  371. {
  372. MatrixF offset( true );
  373. offset.setPosition( mShape->center );
  374. colShape = PHYSICSMGR->createCollision();
  375. colShape->addBox( getObjBox().getExtents() * 0.5f * mObjScale, offset );
  376. }
  377. else
  378. colShape = mShape->buildColShape( mCollisionType == VisibleMesh, getScale() );
  379. if ( colShape )
  380. {
  381. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  382. mPhysicsRep = PHYSICSMGR->createBody();
  383. mPhysicsRep->init( colShape, 0, 0, this, world );
  384. mPhysicsRep->setTransform( getTransform() );
  385. }
  386. }
  387. void TSStatic::onRemove()
  388. {
  389. SAFE_DELETE( mPhysicsRep );
  390. // Accumulation
  391. if ( isClientObject() && mShapeInstance )
  392. {
  393. if ( mShapeInstance->hasAccumulation() )
  394. AccumulationVolume::removeObject(this);
  395. }
  396. mConvexList->nukeList();
  397. removeFromScene();
  398. // Remove the resource change signal.
  399. ResourceManager::get().getChangedSignal().remove( this, &TSStatic::_onResourceChanged );
  400. delete mShapeInstance;
  401. mShapeInstance = NULL;
  402. mAmbientThread = NULL;
  403. if ( isClientObject() )
  404. mCubeReflector.unregisterReflector();
  405. Parent::onRemove();
  406. }
  407. void TSStatic::_onResourceChanged( const Torque::Path &path )
  408. {
  409. if ( path != Path( mShapeName ) )
  410. return;
  411. _createShape();
  412. _updateShouldTick();
  413. }
  414. void TSStatic::setSkinName( const char *name )
  415. {
  416. if ( !isGhost() )
  417. {
  418. if ( name[0] != '\0' )
  419. {
  420. // Use tags for better network performance
  421. // Should be a tag, but we'll convert to one if it isn't.
  422. if ( name[0] == StringTagPrefixByte )
  423. mSkinNameHandle = NetStringHandle( U32(dAtoi(name + 1)) );
  424. else
  425. mSkinNameHandle = NetStringHandle( name );
  426. }
  427. else
  428. mSkinNameHandle = NetStringHandle();
  429. setMaskBits( SkinMask );
  430. }
  431. }
  432. void TSStatic::reSkin()
  433. {
  434. if ( isGhost() && mShapeInstance && mSkinNameHandle.isValidString() )
  435. {
  436. mShapeInstance->resetMaterialList();
  437. Vector<String> skins;
  438. String(mSkinNameHandle.getString()).split( ";", skins );
  439. for (S32 i = 0; i < skins.size(); i++)
  440. {
  441. String oldSkin( mAppliedSkinName.c_str() );
  442. String newSkin( skins[i] );
  443. // Check if the skin handle contains an explicit "old" base string. This
  444. // allows all models to support skinning, even if they don't follow the
  445. // "base_xxx" material naming convention.
  446. S32 split = newSkin.find( '=' ); // "old=new" format skin?
  447. if ( split != String::NPos )
  448. {
  449. oldSkin = newSkin.substr( 0, split );
  450. newSkin = newSkin.erase( 0, split+1 );
  451. }
  452. mShapeInstance->reSkin( newSkin, oldSkin );
  453. mAppliedSkinName = newSkin;
  454. }
  455. }
  456. }
  457. void TSStatic::processTick( const Move *move )
  458. {
  459. if ( isServerObject() && mPlayAmbient && mAmbientThread )
  460. mShapeInstance->advanceTime( TickSec, mAmbientThread );
  461. if ( isMounted() )
  462. {
  463. MatrixF mat( true );
  464. mMount.object->getMountTransform(mMount.node, mMount.xfm, &mat );
  465. setTransform( mat );
  466. }
  467. }
  468. void TSStatic::interpolateTick( F32 delta )
  469. {
  470. }
  471. void TSStatic::advanceTime( F32 dt )
  472. {
  473. if ( mPlayAmbient && mAmbientThread )
  474. mShapeInstance->advanceTime( dt, mAmbientThread );
  475. if ( isMounted() )
  476. {
  477. MatrixF mat( true );
  478. mMount.object->getRenderMountTransform( dt, mMount.node, mMount.xfm, &mat );
  479. setRenderTransform( mat );
  480. }
  481. }
  482. void TSStatic::_updateShouldTick()
  483. {
  484. bool shouldTick = (mPlayAmbient && mAmbientThread) || isMounted();
  485. if ( isTicking() != shouldTick )
  486. setProcessTick( shouldTick );
  487. }
  488. void TSStatic::prepRenderImage( SceneRenderState* state )
  489. {
  490. if( !mShapeInstance )
  491. return;
  492. Point3F cameraOffset;
  493. getRenderTransform().getColumn(3,&cameraOffset);
  494. cameraOffset -= state->getDiffuseCameraPosition();
  495. F32 dist = cameraOffset.len();
  496. if (dist < 0.01f)
  497. dist = 0.01f;
  498. if (mUseAlphaFade)
  499. {
  500. mAlphaFade = 1.0f;
  501. if ((mAlphaFadeStart < mAlphaFadeEnd) && mAlphaFadeStart > 0.1f)
  502. {
  503. if (mInvertAlphaFade)
  504. {
  505. if (dist <= mAlphaFadeStart)
  506. {
  507. return;
  508. }
  509. if (dist < mAlphaFadeEnd)
  510. {
  511. mAlphaFade = ((dist - mAlphaFadeStart) / (mAlphaFadeEnd - mAlphaFadeStart));
  512. }
  513. }
  514. else
  515. {
  516. if (dist >= mAlphaFadeEnd)
  517. {
  518. return;
  519. }
  520. if (dist > mAlphaFadeStart)
  521. {
  522. mAlphaFade -= ((dist - mAlphaFadeStart) / (mAlphaFadeEnd - mAlphaFadeStart));
  523. }
  524. }
  525. }
  526. }
  527. F32 invScale = (1.0f/getMax(getMax(mObjScale.x,mObjScale.y),mObjScale.z));
  528. // If we're currently rendering our own reflection we
  529. // don't want to render ourselves into it.
  530. if ( mCubeReflector.isRendering() )
  531. return;
  532. if ( mForceDetail == -1 )
  533. mShapeInstance->setDetailFromDistance( state, dist * invScale );
  534. else
  535. mShapeInstance->setCurrentDetail( mForceDetail );
  536. if ( mShapeInstance->getCurrentDetail() < 0 )
  537. return;
  538. GFXTransformSaver saver;
  539. // Set up our TS render state.
  540. TSRenderState rdata;
  541. rdata.setSceneState( state );
  542. rdata.setFadeOverride( 1.0f );
  543. rdata.setOriginSort( mUseOriginSort );
  544. if ( mCubeReflector.isEnabled() )
  545. rdata.setCubemap( mCubeReflector.getCubemap() );
  546. // Acculumation
  547. rdata.setAccuTex(mAccuTex);
  548. // If we have submesh culling enabled then prepare
  549. // the object space frustum to pass to the shape.
  550. Frustum culler;
  551. if ( mMeshCulling )
  552. {
  553. culler = state->getCullingFrustum();
  554. MatrixF xfm( true );
  555. xfm.scale( Point3F::One / getScale() );
  556. xfm.mul( getRenderWorldTransform() );
  557. xfm.mul( culler.getTransform() );
  558. culler.setTransform( xfm );
  559. rdata.setCuller( &culler );
  560. }
  561. // We might have some forward lit materials
  562. // so pass down a query to gather lights.
  563. LightQuery query;
  564. query.init( getWorldSphere() );
  565. rdata.setLightQuery( &query );
  566. MatrixF mat = getRenderTransform();
  567. mat.scale( mObjScale );
  568. GFX->setWorldMatrix( mat );
  569. if ( state->isDiffusePass() && mCubeReflector.isEnabled() && mCubeReflector.getOcclusionQuery() )
  570. {
  571. RenderPassManager *pass = state->getRenderPass();
  572. OccluderRenderInst *ri = pass->allocInst<OccluderRenderInst>();
  573. ri->type = RenderPassManager::RIT_Occluder;
  574. ri->query = mCubeReflector.getOcclusionQuery();
  575. mObjToWorld.mulP( mObjBox.getCenter(), &ri->position );
  576. ri->scale.set( mObjBox.getExtents() );
  577. ri->orientation = pass->allocUniqueXform( mObjToWorld );
  578. ri->isSphere = false;
  579. state->getRenderPass()->addInst( ri );
  580. }
  581. mShapeInstance->animate();
  582. if(mShapeInstance)
  583. {
  584. if (mUseAlphaFade)
  585. {
  586. mShapeInstance->setAlphaAlways(mAlphaFade);
  587. S32 s = mShapeInstance->mMeshObjects.size();
  588. for(S32 x = 0; x < s; x++)
  589. {
  590. mShapeInstance->mMeshObjects[x].visible = mAlphaFade;
  591. }
  592. }
  593. }
  594. mShapeInstance->render( rdata );
  595. #ifdef TORQUE_AFX_ENABLED
  596. if (!mIgnoreZodiacs && mDecalDetailsPtr != 0)
  597. afxZodiacMgr::renderPolysoupZodiacs(state, this);
  598. #endif
  599. if ( mRenderNormalScalar > 0 )
  600. {
  601. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  602. ri->renderDelegate.bind( this, &TSStatic::_renderNormals );
  603. ri->type = RenderPassManager::RIT_Editor;
  604. state->getRenderPass()->addInst( ri );
  605. }
  606. }
  607. void TSStatic::_renderNormals( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  608. {
  609. PROFILE_SCOPE( TSStatic_RenderNormals );
  610. GFXTransformSaver saver;
  611. MatrixF mat = getRenderTransform();
  612. mat.scale( mObjScale );
  613. GFX->multWorld( mat );
  614. S32 dl = mShapeInstance->getCurrentDetail();
  615. mShapeInstance->renderDebugNormals( mRenderNormalScalar, dl );
  616. }
  617. void TSStatic::onScaleChanged()
  618. {
  619. Parent::onScaleChanged();
  620. if ( mPhysicsRep )
  621. {
  622. // If the editor is enabled delay the scale operation
  623. // by a few milliseconds so that we're not rebuilding
  624. // during an active scale drag operation.
  625. if ( gEditingMission )
  626. mPhysicsRep->queueCallback( 500, Delegate<void()>( this, &TSStatic::_updatePhysics ) );
  627. else
  628. _updatePhysics();
  629. }
  630. setMaskBits( ScaleMask );
  631. }
  632. void TSStatic::setTransform(const MatrixF & mat)
  633. {
  634. Parent::setTransform(mat);
  635. if ( !isMounted() )
  636. setMaskBits( TransformMask );
  637. if ( mPhysicsRep )
  638. mPhysicsRep->setTransform( mat );
  639. // Accumulation
  640. if ( isClientObject() && mShapeInstance )
  641. {
  642. if ( mShapeInstance->hasAccumulation() )
  643. AccumulationVolume::updateObject(this);
  644. }
  645. // Since this is a static it's render transform changes 1
  646. // to 1 with it's collision transform... no interpolation.
  647. setRenderTransform(mat);
  648. }
  649. U32 TSStatic::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  650. {
  651. U32 retMask = Parent::packUpdate(con, mask, stream);
  652. if ( stream->writeFlag( mask & TransformMask ) )
  653. mathWrite( *stream, getTransform() );
  654. if ( stream->writeFlag( mask & ScaleMask ) )
  655. {
  656. // Only write one bit if the scale is one.
  657. if ( stream->writeFlag( mObjScale != Point3F::One ) )
  658. mathWrite( *stream, mObjScale );
  659. }
  660. if ( stream->writeFlag( mask & UpdateCollisionMask ) )
  661. stream->write( (U32)mCollisionType );
  662. if ( stream->writeFlag( mask & SkinMask ) )
  663. con->packNetStringHandleU( stream, mSkinNameHandle );
  664. if (stream->writeFlag(mask & AdvancedStaticOptionsMask))
  665. {
  666. stream->writeString(mShapeName);
  667. stream->write((U32)mDecalType);
  668. stream->writeFlag(mAllowPlayerStep);
  669. stream->writeFlag(mMeshCulling);
  670. stream->writeFlag(mUseOriginSort);
  671. stream->write(mRenderNormalScalar);
  672. stream->write(mForceDetail);
  673. stream->writeFlag(mPlayAmbient);
  674. }
  675. if ( stream->writeFlag(mUseAlphaFade) )
  676. {
  677. stream->write(mAlphaFadeStart);
  678. stream->write(mAlphaFadeEnd);
  679. stream->write(mInvertAlphaFade);
  680. }
  681. stream->writeFlag(mIgnoreZodiacs);
  682. if (stream->writeFlag(mHasGradients))
  683. {
  684. stream->writeFlag(mInvertGradientRange);
  685. stream->write(mGradientRange.x);
  686. stream->write(mGradientRange.y);
  687. }
  688. if ( mLightPlugin )
  689. retMask |= mLightPlugin->packUpdate(this, AdvancedStaticOptionsMask, con, mask, stream);
  690. if( stream->writeFlag( reflectorDesc != NULL ) )
  691. {
  692. stream->writeRangedU32( reflectorDesc->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  693. }
  694. return retMask;
  695. }
  696. void TSStatic::unpackUpdate(NetConnection *con, BitStream *stream)
  697. {
  698. Parent::unpackUpdate(con, stream);
  699. if ( stream->readFlag() ) // TransformMask
  700. {
  701. MatrixF mat;
  702. mathRead( *stream, &mat );
  703. setTransform(mat);
  704. setRenderTransform(mat);
  705. }
  706. if ( stream->readFlag() ) // ScaleMask
  707. {
  708. if ( stream->readFlag() )
  709. {
  710. VectorF scale;
  711. mathRead( *stream, &scale );
  712. setScale( scale );
  713. }
  714. else
  715. setScale( Point3F::One );
  716. }
  717. if ( stream->readFlag() ) // UpdateCollisionMask
  718. {
  719. U32 collisionType = CollisionMesh;
  720. stream->read( &collisionType );
  721. // Handle it if we have changed CollisionType's
  722. if ( (MeshType)collisionType != mCollisionType )
  723. {
  724. mCollisionType = (MeshType)collisionType;
  725. if ( isProperlyAdded() && mShapeInstance )
  726. prepCollision();
  727. }
  728. }
  729. if (stream->readFlag()) // SkinMask
  730. {
  731. NetStringHandle skinDesiredNameHandle = con->unpackNetStringHandleU(stream);;
  732. if (mSkinNameHandle != skinDesiredNameHandle)
  733. {
  734. mSkinNameHandle = skinDesiredNameHandle;
  735. reSkin();
  736. }
  737. }
  738. if (stream->readFlag()) // AdvancedStaticOptionsMask
  739. {
  740. mShapeName = stream->readSTString();
  741. stream->read((U32*)&mDecalType);
  742. mAllowPlayerStep = stream->readFlag();
  743. mMeshCulling = stream->readFlag();
  744. mUseOriginSort = stream->readFlag();
  745. stream->read(&mRenderNormalScalar);
  746. stream->read(&mForceDetail);
  747. mPlayAmbient = stream->readFlag();
  748. }
  749. mUseAlphaFade = stream->readFlag();
  750. if (mUseAlphaFade)
  751. {
  752. stream->read(&mAlphaFadeStart);
  753. stream->read(&mAlphaFadeEnd);
  754. stream->read(&mInvertAlphaFade);
  755. }
  756. mIgnoreZodiacs = stream->readFlag();
  757. mHasGradients = stream->readFlag();
  758. if (mHasGradients)
  759. {
  760. mInvertGradientRange = stream->readFlag();
  761. stream->read(&mGradientRange.x);
  762. stream->read(&mGradientRange.y);
  763. }
  764. if ( mLightPlugin )
  765. {
  766. mLightPlugin->unpackUpdate(this, con, stream);
  767. }
  768. if( stream->readFlag() )
  769. {
  770. cubeDescId = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  771. }
  772. if ( isProperlyAdded() )
  773. _updateShouldTick();
  774. set_special_typing();
  775. }
  776. //----------------------------------------------------------------------------
  777. bool TSStatic::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  778. {
  779. if ( mCollisionType == None )
  780. return false;
  781. if ( !mShapeInstance )
  782. return false;
  783. if ( mCollisionType == Bounds )
  784. {
  785. F32 fst;
  786. if (!mObjBox.collideLine(start, end, &fst, &info->normal))
  787. return false;
  788. info->t = fst;
  789. info->object = this;
  790. info->point.interpolate( start, end, fst );
  791. info->material = NULL;
  792. return true;
  793. }
  794. else
  795. {
  796. RayInfo shortest = *info;
  797. RayInfo localInfo;
  798. shortest.t = 1e8f;
  799. localInfo.generateTexCoord = info->generateTexCoord;
  800. for ( U32 i = 0; i < mLOSDetails.size(); i++ )
  801. {
  802. mShapeInstance->animate( mLOSDetails[i] );
  803. if ( mShapeInstance->castRayOpcode( mLOSDetails[i], start, end, &localInfo ) )
  804. {
  805. localInfo.object = this;
  806. if (localInfo.t < shortest.t)
  807. shortest = localInfo;
  808. }
  809. }
  810. if (shortest.object == this)
  811. {
  812. // Copy out the shortest time...
  813. *info = shortest;
  814. return true;
  815. }
  816. }
  817. return false;
  818. }
  819. bool TSStatic::castRayRendered(const Point3F &start, const Point3F &end, RayInfo *info)
  820. {
  821. if ( !mShapeInstance )
  822. return false;
  823. // Cast the ray against the currently visible detail
  824. RayInfo localInfo;
  825. if (info && info->generateTexCoord)
  826. localInfo.generateTexCoord = true;
  827. bool res = mShapeInstance->castRayOpcode( mShapeInstance->getCurrentDetail(), start, end, &localInfo );
  828. if ( res )
  829. {
  830. *info = localInfo;
  831. info->object = this;
  832. return true;
  833. }
  834. return false;
  835. }
  836. bool TSStatic::buildPolyList(PolyListContext context, AbstractPolyList* polyList, const Box3F &box, const SphereF &)
  837. {
  838. if ( !mShapeInstance )
  839. return false;
  840. // This is safe to set even if we're not outputing
  841. polyList->setTransform( &mObjToWorld, mObjScale );
  842. polyList->setObject( this );
  843. if ( context == PLC_Export )
  844. {
  845. // Use highest detail level
  846. S32 dl = 0;
  847. // Try to call on the client so we can export materials
  848. if ( isServerObject() && getClientObject() )
  849. dynamic_cast<TSStatic*>(getClientObject())->mShapeInstance->buildPolyList( polyList, dl );
  850. else
  851. mShapeInstance->buildPolyList( polyList, dl );
  852. }
  853. else if ( context == PLC_Selection )
  854. {
  855. // Use the last rendered detail level
  856. S32 dl = mShapeInstance->getCurrentDetail();
  857. mShapeInstance->buildPolyListOpcode( dl, polyList, box );
  858. }
  859. else
  860. {
  861. // Figure out the mesh type we're looking for.
  862. MeshType meshType = ( context == PLC_Decal ) ? mDecalType : mCollisionType;
  863. if ( meshType == None )
  864. return false;
  865. else if ( meshType == Bounds )
  866. polyList->addBox( mObjBox );
  867. else if ( meshType == VisibleMesh )
  868. mShapeInstance->buildPolyList( polyList, 0 );
  869. else if (context == PLC_Decal && mDecalDetailsPtr != 0)
  870. {
  871. for ( U32 i = 0; i < mDecalDetailsPtr->size(); i++ )
  872. mShapeInstance->buildPolyListOpcode( (*mDecalDetailsPtr)[i], polyList, box );
  873. }
  874. else
  875. {
  876. // Everything else is done from the collision meshes
  877. // which may be built from either the visual mesh or
  878. // special collision geometry.
  879. for ( U32 i = 0; i < mCollisionDetails.size(); i++ )
  880. mShapeInstance->buildPolyListOpcode( mCollisionDetails[i], polyList, box );
  881. }
  882. }
  883. return true;
  884. }
  885. bool TSStatic::buildExportPolyList(ColladaUtils::ExportData* exportData, const Box3F &box, const SphereF &)
  886. {
  887. if (!mShapeInstance)
  888. return false;
  889. if (mCollisionType == Bounds)
  890. {
  891. ColladaUtils::ExportData::colMesh* colMesh;
  892. exportData->colMeshes.increment();
  893. colMesh = &exportData->colMeshes.last();
  894. colMesh->mesh.setTransform(&mObjToWorld, mObjScale);
  895. colMesh->mesh.setObject(this);
  896. colMesh->mesh.addBox(mObjBox);
  897. colMesh->colMeshName = String::ToString("ColBox%d-1", exportData->colMeshes.size());
  898. }
  899. else if (mCollisionType == VisibleMesh)
  900. {
  901. ColladaUtils::ExportData::colMesh* colMesh;
  902. exportData->colMeshes.increment();
  903. colMesh = &exportData->colMeshes.last();
  904. colMesh->mesh.setTransform(&mObjToWorld, mObjScale);
  905. colMesh->mesh.setObject(this);
  906. mShapeInstance->buildPolyList(&colMesh->mesh, 0);
  907. colMesh->colMeshName = String::ToString("ColMesh%d-1", exportData->colMeshes.size());
  908. }
  909. else if (mCollisionType == CollisionMesh)
  910. {
  911. // Everything else is done from the collision meshes
  912. // which may be built from either the visual mesh or
  913. // special collision geometry.
  914. for (U32 i = 0; i < mCollisionDetails.size(); i++)
  915. {
  916. ColladaUtils::ExportData::colMesh* colMesh;
  917. exportData->colMeshes.increment();
  918. colMesh = &exportData->colMeshes.last();
  919. colMesh->mesh.setTransform(&mObjToWorld, mObjScale);
  920. colMesh->mesh.setObject(this);
  921. mShapeInstance->buildPolyListOpcode(mCollisionDetails[i], &colMesh->mesh, box);
  922. colMesh->colMeshName = String::ToString("ColMesh%d-1", exportData->colMeshes.size());
  923. }
  924. }
  925. //Next, process the LOD levels and materials.
  926. if (isServerObject() && getClientObject())
  927. {
  928. TSStatic* clientShape = dynamic_cast<TSStatic*>(getClientObject());
  929. exportData->meshData.increment();
  930. //Prep a meshData for this shape in particular
  931. ColladaUtils::ExportData::meshLODData* meshData = &exportData->meshData.last();
  932. //Fill out the info we'll need later to actually append our mesh data for the detail levels during the processing phase
  933. meshData->shapeInst = clientShape->mShapeInstance;
  934. meshData->originatingObject = this;
  935. meshData->meshTransform = mObjToWorld;
  936. meshData->scale = mObjScale;
  937. //Iterate over all our detail levels
  938. for (U32 i = 0; i < clientShape->mShapeInstance->getNumDetails(); i++)
  939. {
  940. TSShape::Detail detail = clientShape->mShapeInstance->getShape()->details[i];
  941. String detailName = String::ToLower(clientShape->mShapeInstance->getShape()->getName(detail.nameIndex));
  942. //Skip it if it's a collision or line of sight element
  943. if (detailName.startsWith("col") || detailName.startsWith("los"))
  944. continue;
  945. meshData->meshDetailLevels.increment();
  946. ColladaUtils::ExportData::detailLevel* curDetail = &meshData->meshDetailLevels.last();
  947. //Make sure we denote the size this detail level has
  948. curDetail->size = detail.size;
  949. }
  950. }
  951. return true;
  952. }
  953. void TSStatic::buildConvex(const Box3F& box, Convex* convex)
  954. {
  955. if ( mCollisionType == None )
  956. return;
  957. if ( mShapeInstance == NULL )
  958. return;
  959. // These should really come out of a pool
  960. mConvexList->collectGarbage();
  961. if ( mCollisionType == Bounds )
  962. {
  963. // Just return a box convex for the entire shape...
  964. Convex* cc = 0;
  965. CollisionWorkingList& wl = convex->getWorkingList();
  966. for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext)
  967. {
  968. if (itr->mConvex->getType() == BoxConvexType &&
  969. itr->mConvex->getObject() == this)
  970. {
  971. cc = itr->mConvex;
  972. break;
  973. }
  974. }
  975. if (cc)
  976. return;
  977. // Create a new convex.
  978. BoxConvex* cp = new BoxConvex;
  979. mConvexList->registerObject(cp);
  980. convex->addToWorkingList(cp);
  981. cp->init(this);
  982. mObjBox.getCenter(&cp->mCenter);
  983. cp->mSize.x = mObjBox.len_x() / 2.0f;
  984. cp->mSize.y = mObjBox.len_y() / 2.0f;
  985. cp->mSize.z = mObjBox.len_z() / 2.0f;
  986. }
  987. else // CollisionMesh || VisibleMesh
  988. {
  989. TSStaticPolysoupConvex::smCurObject = this;
  990. for (U32 i = 0; i < mCollisionDetails.size(); i++)
  991. mShapeInstance->buildConvexOpcode( mObjToWorld, mObjScale, mCollisionDetails[i], box, convex, mConvexList );
  992. TSStaticPolysoupConvex::smCurObject = NULL;
  993. }
  994. }
  995. SceneObject* TSStaticPolysoupConvex::smCurObject = NULL;
  996. TSStaticPolysoupConvex::TSStaticPolysoupConvex()
  997. : box( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f ),
  998. normal( 0.0f, 0.0f, 0.0f, 0.0f ),
  999. idx( 0 ),
  1000. mesh( NULL )
  1001. {
  1002. mType = TSPolysoupConvexType;
  1003. for ( U32 i = 0; i < 4; ++i )
  1004. {
  1005. verts[i].set( 0.0f, 0.0f, 0.0f );
  1006. }
  1007. }
  1008. Point3F TSStaticPolysoupConvex::support(const VectorF& vec) const
  1009. {
  1010. F32 bestDot = mDot( verts[0], vec );
  1011. const Point3F *bestP = &verts[0];
  1012. for(S32 i=1; i<4; i++)
  1013. {
  1014. F32 newD = mDot(verts[i], vec);
  1015. if(newD > bestDot)
  1016. {
  1017. bestDot = newD;
  1018. bestP = &verts[i];
  1019. }
  1020. }
  1021. return *bestP;
  1022. }
  1023. Box3F TSStaticPolysoupConvex::getBoundingBox() const
  1024. {
  1025. Box3F wbox = box;
  1026. wbox.minExtents.convolve( mObject->getScale() );
  1027. wbox.maxExtents.convolve( mObject->getScale() );
  1028. mObject->getTransform().mul(wbox);
  1029. return wbox;
  1030. }
  1031. Box3F TSStaticPolysoupConvex::getBoundingBox(const MatrixF& mat, const Point3F& scale) const
  1032. {
  1033. AssertISV(false, "TSStaticPolysoupConvex::getBoundingBox(m,p) - Not implemented. -- XEA");
  1034. return box;
  1035. }
  1036. void TSStaticPolysoupConvex::getPolyList(AbstractPolyList *list)
  1037. {
  1038. // Transform the list into object space and set the pointer to the object
  1039. MatrixF i( mObject->getTransform() );
  1040. Point3F iS( mObject->getScale() );
  1041. list->setTransform(&i, iS);
  1042. list->setObject(mObject);
  1043. // Add only the original collision triangle
  1044. S32 base = list->addPoint(verts[0]);
  1045. list->addPoint(verts[2]);
  1046. list->addPoint(verts[1]);
  1047. list->begin(0, (U32)idx ^ (uintptr_t)mesh);
  1048. list->vertex(base + 2);
  1049. list->vertex(base + 1);
  1050. list->vertex(base + 0);
  1051. list->plane(base + 0, base + 1, base + 2);
  1052. list->end();
  1053. }
  1054. void TSStaticPolysoupConvex::getFeatures(const MatrixF& mat,const VectorF& n, ConvexFeature* cf)
  1055. {
  1056. cf->material = 0;
  1057. cf->object = mObject;
  1058. // For a tetrahedron this is pretty easy... first
  1059. // convert everything into world space.
  1060. Point3F tverts[4];
  1061. mat.mulP(verts[0], &tverts[0]);
  1062. mat.mulP(verts[1], &tverts[1]);
  1063. mat.mulP(verts[2], &tverts[2]);
  1064. mat.mulP(verts[3], &tverts[3]);
  1065. // points...
  1066. S32 firstVert = cf->mVertexList.size();
  1067. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[0];
  1068. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[1];
  1069. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[2];
  1070. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[3];
  1071. // edges...
  1072. cf->mEdgeList.increment();
  1073. cf->mEdgeList.last().vertex[0] = firstVert+0;
  1074. cf->mEdgeList.last().vertex[1] = firstVert+1;
  1075. cf->mEdgeList.increment();
  1076. cf->mEdgeList.last().vertex[0] = firstVert+1;
  1077. cf->mEdgeList.last().vertex[1] = firstVert+2;
  1078. cf->mEdgeList.increment();
  1079. cf->mEdgeList.last().vertex[0] = firstVert+2;
  1080. cf->mEdgeList.last().vertex[1] = firstVert+0;
  1081. cf->mEdgeList.increment();
  1082. cf->mEdgeList.last().vertex[0] = firstVert+3;
  1083. cf->mEdgeList.last().vertex[1] = firstVert+0;
  1084. cf->mEdgeList.increment();
  1085. cf->mEdgeList.last().vertex[0] = firstVert+3;
  1086. cf->mEdgeList.last().vertex[1] = firstVert+1;
  1087. cf->mEdgeList.increment();
  1088. cf->mEdgeList.last().vertex[0] = firstVert+3;
  1089. cf->mEdgeList.last().vertex[1] = firstVert+2;
  1090. // triangles...
  1091. cf->mFaceList.increment();
  1092. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[0]);
  1093. cf->mFaceList.last().vertex[0] = firstVert+2;
  1094. cf->mFaceList.last().vertex[1] = firstVert+1;
  1095. cf->mFaceList.last().vertex[2] = firstVert+0;
  1096. cf->mFaceList.increment();
  1097. cf->mFaceList.last().normal = PlaneF(tverts[1], tverts[0], tverts[3]);
  1098. cf->mFaceList.last().vertex[0] = firstVert+1;
  1099. cf->mFaceList.last().vertex[1] = firstVert+0;
  1100. cf->mFaceList.last().vertex[2] = firstVert+3;
  1101. cf->mFaceList.increment();
  1102. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[3]);
  1103. cf->mFaceList.last().vertex[0] = firstVert+2;
  1104. cf->mFaceList.last().vertex[1] = firstVert+1;
  1105. cf->mFaceList.last().vertex[2] = firstVert+3;
  1106. cf->mFaceList.increment();
  1107. cf->mFaceList.last().normal = PlaneF(tverts[0], tverts[2], tverts[3]);
  1108. cf->mFaceList.last().vertex[0] = firstVert+0;
  1109. cf->mFaceList.last().vertex[1] = firstVert+2;
  1110. cf->mFaceList.last().vertex[2] = firstVert+3;
  1111. // All done!
  1112. }
  1113. void TSStatic::onMount( SceneObject *obj, S32 node )
  1114. {
  1115. Parent::onMount(obj, node);
  1116. _updateShouldTick();
  1117. }
  1118. void TSStatic::onUnmount( SceneObject *obj, S32 node )
  1119. {
  1120. Parent::onUnmount( obj, node );
  1121. setMaskBits( TransformMask );
  1122. _updateShouldTick();
  1123. }
  1124. U32 TSStatic::getNumDetails()
  1125. {
  1126. if (isServerObject() && getClientObject())
  1127. {
  1128. TSStatic* clientShape = dynamic_cast<TSStatic*>(getClientObject());
  1129. return clientShape->mShapeInstance->getNumDetails();
  1130. }
  1131. return 0;
  1132. };
  1133. //------------------------------------------------------------------------
  1134. //These functions are duplicated in tsStatic and shapeBase.
  1135. //They each function a little differently; but achieve the same purpose of gathering
  1136. //target names/counts without polluting simObject.
  1137. DefineEngineMethod( TSStatic, getTargetName, const char*, ( S32 index ),(0),
  1138. "Get the name of the indexed shape material.\n"
  1139. "@param index index of the material to get (valid range is 0 - getTargetCount()-1).\n"
  1140. "@return the name of the indexed material.\n"
  1141. "@see getTargetCount()\n")
  1142. {
  1143. TSStatic *obj = dynamic_cast< TSStatic* > ( object );
  1144. if(obj)
  1145. {
  1146. // Try to use the client object (so we get the reskinned targets in the Material Editor)
  1147. if ((TSStatic*)obj->getClientObject())
  1148. obj = (TSStatic*)obj->getClientObject();
  1149. return obj->getShapeInstance()->getTargetName(index);
  1150. }
  1151. return "";
  1152. }
  1153. DefineEngineMethod( TSStatic, getTargetCount, S32,(),,
  1154. "Get the number of materials in the shape.\n"
  1155. "@return the number of materials in the shape.\n"
  1156. "@see getTargetName()\n")
  1157. {
  1158. TSStatic *obj = dynamic_cast< TSStatic* > ( object );
  1159. if(obj)
  1160. {
  1161. // Try to use the client object (so we get the reskinned targets in the Material Editor)
  1162. if ((TSStatic*)obj->getClientObject())
  1163. obj = (TSStatic*)obj->getClientObject();
  1164. return obj->getShapeInstance()->getTargetCount();
  1165. }
  1166. return -1;
  1167. }
  1168. // This method is able to change materials per map to with others. The material that is being replaced is being mapped to
  1169. // unmapped_mat as a part of this transition
  1170. DefineEngineMethod( TSStatic, changeMaterial, void, ( const char* mapTo, Material* oldMat, Material* newMat ),("",nullAsType<Material*>(),nullAsType<Material*>()),
  1171. "@brief Change one of the materials on the shape.\n\n"
  1172. "This method changes materials per mapTo with others. The material that "
  1173. "is being replaced is mapped to unmapped_mat as a part of this transition.\n"
  1174. "@note Warning, right now this only sort of works. It doesn't do a live "
  1175. "update like it should.\n"
  1176. "@param mapTo the name of the material target to remap (from getTargetName)\n"
  1177. "@param oldMat the old Material that was mapped \n"
  1178. "@param newMat the new Material to map\n\n"
  1179. "@tsexample\n"
  1180. "// remap the first material in the shape\n"
  1181. "%mapTo = %obj.getTargetName( 0 );\n"
  1182. "%obj.changeMaterial( %mapTo, 0, MyMaterial );\n"
  1183. "@endtsexample\n" )
  1184. {
  1185. // if no valid new material, theres no reason for doing this
  1186. if( !newMat )
  1187. {
  1188. Con::errorf("TSShape::changeMaterial failed: New material does not exist!");
  1189. return;
  1190. }
  1191. TSMaterialList* shapeMaterialList = object->getShape()->materialList;
  1192. // Check the mapTo name exists for this shape
  1193. S32 matIndex = shapeMaterialList->getMaterialNameList().find_next(String(mapTo));
  1194. if (matIndex < 0)
  1195. {
  1196. Con::errorf("TSShape::changeMaterial failed: Invalid mapTo name '%s'", mapTo);
  1197. return;
  1198. }
  1199. // Lets remap the old material off, so as to let room for our current material room to claim its spot
  1200. if( oldMat )
  1201. oldMat->mMapTo = String("unmapped_mat");
  1202. newMat->mMapTo = mapTo;
  1203. // Map the material by name in the matmgr
  1204. MATMGR->mapMaterial( mapTo, newMat->getName() );
  1205. // Replace instances with the new material being traded in. Lets make sure that we only
  1206. // target the specific targets per inst, this is actually doing more than we thought
  1207. delete shapeMaterialList->mMatInstList[matIndex];
  1208. shapeMaterialList->mMatInstList[matIndex] = newMat->createMatInstance();
  1209. // Finish up preparing the material instances for rendering
  1210. const GFXVertexFormat *flags = getGFXVertexFormat<GFXVertexPNTTB>();
  1211. FeatureSet features = MATMGR->getDefaultFeatures();
  1212. shapeMaterialList->getMaterialInst(matIndex)->init(features, flags);
  1213. }
  1214. DefineEngineMethod( TSStatic, getModelFile, const char *, (),,
  1215. "@brief Get the model filename used by this shape.\n\n"
  1216. "@return the shape filename\n\n"
  1217. "@tsexample\n"
  1218. "// Acquire the model filename used on this shape.\n"
  1219. "%modelFilename = %obj.getModelFile();\n"
  1220. "@endtsexample\n"
  1221. )
  1222. {
  1223. return object->getShapeFileName();
  1224. }
  1225. void TSStatic::set_special_typing()
  1226. {
  1227. if (mCollisionType == VisibleMesh || mCollisionType == CollisionMesh)
  1228. mTypeMask |= InteriorLikeObjectType;
  1229. else
  1230. mTypeMask &= ~InteriorLikeObjectType;
  1231. }
  1232. void TSStatic::onStaticModified(const char* slotName, const char*newValue)
  1233. {
  1234. #ifdef TORQUE_AFX_ENABLED
  1235. if (slotName == afxZodiacData::GradientRangeSlot)
  1236. {
  1237. afxZodiacData::convertGradientRangeFromDegrees(mGradientRange, mGradientRangeUser);
  1238. return;
  1239. }
  1240. #endif
  1241. set_special_typing();
  1242. }
  1243. void TSStatic::setSelectionFlags(U8 flags)
  1244. {
  1245. Parent::setSelectionFlags(flags);
  1246. if (!mShapeInstance || !isClientObject())
  1247. return;
  1248. if (!mShapeInstance->ownMaterialList())
  1249. return;
  1250. TSMaterialList* pMatList = mShapeInstance->getMaterialList();
  1251. for (S32 j = 0; j < pMatList->size(); j++)
  1252. {
  1253. BaseMatInstance * bmi = pMatList->getMaterialInst(j);
  1254. bmi->setSelectionHighlighting(needsSelectionHighlighting());
  1255. }
  1256. }