meshComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 "console/consoleTypes.h"
  24. #include "T3D/components/render/meshComponent.h"
  25. #include "core/util/safeDelete.h"
  26. #include "core/resourceManager.h"
  27. #include "core/stream/fileStream.h"
  28. #include "console/consoleTypes.h"
  29. #include "console/consoleObject.h"
  30. #include "core/stream/bitStream.h"
  31. #include "sim/netConnection.h"
  32. #include "gfx/gfxTransformSaver.h"
  33. #include "console/engineAPI.h"
  34. #include "lighting/lightQuery.h"
  35. #include "scene/sceneManager.h"
  36. #include "gfx/bitmap/ddsFile.h"
  37. #include "gfx/bitmap/ddsUtils.h"
  38. #include "gfx/gfxTextureManager.h"
  39. #include "materials/materialFeatureTypes.h"
  40. #include "renderInstance/renderImposterMgr.h"
  41. #include "util/imposterCapture.h"
  42. #include "gfx/sim/debugDraw.h"
  43. #include "gfx/gfxDrawUtil.h"
  44. #include "materials/materialManager.h"
  45. #include "materials/matInstance.h"
  46. #include "core/strings/findMatch.h"
  47. #include "T3D/components/render/meshComponent_ScriptBinding.h"
  48. //////////////////////////////////////////////////////////////////////////
  49. // Constructor/Destructor
  50. //////////////////////////////////////////////////////////////////////////
  51. MeshComponent::MeshComponent() : Component()
  52. {
  53. mShapeName = StringTable->insert("");
  54. mShapeAsset = StringTable->insert("");
  55. mShapeInstance = NULL;
  56. mChangingMaterials.clear();
  57. mMaterials.clear();
  58. mFriendlyName = "Mesh Component";
  59. mComponentType = "Render";
  60. mDescription = getDescriptionText("Causes the object to render a non-animating 3d shape using the file provided.");
  61. mNetworked = true;
  62. mNetFlags.set(Ghostable | ScopeAlways);
  63. }
  64. MeshComponent::~MeshComponent(){}
  65. IMPLEMENT_CO_NETOBJECT_V1(MeshComponent);
  66. //==========================================================================================
  67. void MeshComponent::boneObject::addObject(SimObject* object)
  68. {
  69. SceneObject* sc = dynamic_cast<SceneObject*>(object);
  70. if(sc && mOwner)
  71. {
  72. if(TSShape* shape = mOwner->getShape())
  73. {
  74. S32 nodeID = shape->findNode(mBoneName);
  75. //we may have a offset on the shape's center
  76. //so make sure we accomodate for that when setting up the mount offsets
  77. MatrixF mat = mOwner->getNodeTransform(nodeID);
  78. mOwner->getOwner()->mountObject(sc, nodeID, mat);
  79. }
  80. }
  81. }
  82. bool MeshComponent::onAdd()
  83. {
  84. if(! Parent::onAdd())
  85. return false;
  86. // Register for the resource change signal.
  87. ResourceManager::get().getChangedSignal().notify( this, &MeshComponent::_onResourceChanged );
  88. return true;
  89. }
  90. void MeshComponent::onComponentAdd()
  91. {
  92. Parent::onComponentAdd();
  93. //get the default shape, if any
  94. updateShape();
  95. }
  96. void MeshComponent::onRemove()
  97. {
  98. Parent::onRemove();
  99. SAFE_DELETE(mShapeInstance);
  100. }
  101. void MeshComponent::onComponentRemove()
  102. {
  103. if(mOwner)
  104. {
  105. Point3F pos = mOwner->getPosition(); //store our center pos
  106. mOwner->setObjectBox(Box3F(Point3F(-1,-1,-1), Point3F(1,1,1)));
  107. mOwner->setPosition(pos);
  108. }
  109. Parent::onComponentRemove();
  110. }
  111. void MeshComponent::initPersistFields()
  112. {
  113. Parent::initPersistFields();
  114. //create a hook to our internal variables
  115. addGroup("Model");
  116. addProtectedField("MeshAsset", TypeAssetId, Offset(mShapeAsset, MeshComponent), &_setMesh, &defaultProtectedGetFn,
  117. "The asset Id used for the mesh.", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  118. endGroup("Model");
  119. }
  120. bool MeshComponent::_setMesh(void *object, const char *index, const char *data)
  121. {
  122. MeshComponent *rbI = static_cast<MeshComponent*>(object);
  123. // Sanity!
  124. AssertFatal(data != NULL, "Cannot use a NULL asset Id.");
  125. return rbI->setMeshAsset(data);
  126. }
  127. bool MeshComponent::_setShape( void *object, const char *index, const char *data )
  128. {
  129. MeshComponent *rbI = static_cast<MeshComponent*>(object);
  130. rbI->mShapeName = StringTable->insert(data);
  131. rbI->updateShape(); //make sure we force the update to resize the owner bounds
  132. rbI->setMaskBits(ShapeMask);
  133. return true;
  134. }
  135. bool MeshComponent::setMeshAsset(const char* assetName)
  136. {
  137. // Fetch the asset Id.
  138. mMeshAssetId = StringTable->insert(assetName);
  139. mMeshAsset.setAssetId(mMeshAssetId);
  140. if (mMeshAsset.isNull())
  141. {
  142. Con::errorf("[MeshComponent] Failed to load mesh asset.");
  143. return false;
  144. }
  145. mShapeName = mMeshAssetId;
  146. mShapeAsset = mShapeName;
  147. updateShape(); //make sure we force the update to resize the owner bounds
  148. setMaskBits(ShapeMask);
  149. return true;
  150. }
  151. void MeshComponent::_onResourceChanged( const Torque::Path &path )
  152. {
  153. if ( path != Torque::Path( mShapeName ) )
  154. return;
  155. updateShape();
  156. setMaskBits(ShapeMask);
  157. }
  158. void MeshComponent::inspectPostApply()
  159. {
  160. Parent::inspectPostApply();
  161. }
  162. U32 MeshComponent::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  163. {
  164. U32 retMask = Parent::packUpdate(con, mask, stream);
  165. if (!mOwner || con->getGhostIndex(mOwner) == -1)
  166. {
  167. stream->writeFlag(false);
  168. stream->writeFlag(false);
  169. if (mask & ShapeMask)
  170. retMask |= ShapeMask;
  171. if (mask & MaterialMask)
  172. retMask |= MaterialMask;
  173. return retMask;
  174. }
  175. if (stream->writeFlag(mask & ShapeMask))
  176. {
  177. stream->writeString(mShapeName);
  178. }
  179. if (stream->writeFlag( mask & MaterialMask ))
  180. {
  181. stream->writeInt(mChangingMaterials.size(), 16);
  182. for(U32 i=0; i < mChangingMaterials.size(); i++)
  183. {
  184. stream->writeInt(mChangingMaterials[i].slot, 16);
  185. NetStringHandle matNameStr = mChangingMaterials[i].matName.c_str();
  186. con->packNetStringHandleU(stream, matNameStr);
  187. }
  188. mChangingMaterials.clear();
  189. }
  190. return retMask;
  191. }
  192. void MeshComponent::unpackUpdate(NetConnection *con, BitStream *stream)
  193. {
  194. Parent::unpackUpdate(con, stream);
  195. if(stream->readFlag())
  196. {
  197. mShapeName = stream->readSTString();
  198. setMeshAsset(mShapeName);
  199. updateShape();
  200. }
  201. if(stream->readFlag())
  202. {
  203. mChangingMaterials.clear();
  204. U32 materialCount = stream->readInt(16);
  205. for(U32 i=0; i < materialCount; i++)
  206. {
  207. matMap newMatMap;
  208. newMatMap.slot = stream->readInt(16);
  209. newMatMap.matName = String(con->unpackNetStringHandleU(stream).getString());
  210. mChangingMaterials.push_back(newMatMap);
  211. }
  212. updateMaterials();
  213. }
  214. }
  215. void MeshComponent::prepRenderImage( SceneRenderState *state )
  216. {
  217. if (!mEnabled || !mOwner || !mShapeInstance)
  218. return;
  219. Point3F cameraOffset;
  220. mOwner->getRenderTransform().getColumn(3, &cameraOffset);
  221. cameraOffset -= state->getDiffuseCameraPosition();
  222. F32 dist = cameraOffset.len();
  223. if (dist < 0.01f)
  224. dist = 0.01f;
  225. Point3F objScale = getOwner()->getScale();
  226. F32 invScale = (1.0f / getMax(getMax(objScale.x, objScale.y), objScale.z));
  227. mShapeInstance->setDetailFromDistance(state, dist * invScale);
  228. if (mShapeInstance->getCurrentDetail() < 0)
  229. return;
  230. GFXTransformSaver saver;
  231. // Set up our TS render state.
  232. TSRenderState rdata;
  233. rdata.setSceneState(state);
  234. rdata.setFadeOverride(1.0f);
  235. rdata.setOriginSort(false);
  236. // We might have some forward lit materials
  237. // so pass down a query to gather lights.
  238. LightQuery query;
  239. query.init(mOwner->getWorldSphere());
  240. rdata.setLightQuery(&query);
  241. MatrixF mat = mOwner->getRenderTransform();
  242. Point3F renderPos = mat.getPosition();
  243. EulerF renderRot = mat.toEuler();
  244. mat.scale(objScale);
  245. GFX->setWorldMatrix(mat);
  246. mShapeInstance->render(rdata);
  247. }
  248. void MeshComponent::updateShape()
  249. {
  250. bool isServer = isServerObject();
  251. if ((mShapeName && mShapeName[0] != '\0') || (mShapeAsset && mShapeAsset[0] != '\0'))
  252. {
  253. if (mMeshAsset == NULL)
  254. return;
  255. mShape = mMeshAsset->getShape();
  256. if (!mShape)
  257. return;
  258. setupShape();
  259. //Do this on both the server and client
  260. S32 materialCount = mShape->materialList->getMaterialNameList().size();
  261. if(isServerObject())
  262. {
  263. //we need to update the editor
  264. for (U32 i = 0; i < mFields.size(); i++)
  265. {
  266. //find any with the materialslot title and clear them out
  267. if (FindMatch::isMatch("MaterialSlot*", mFields[i].mFieldName, false))
  268. {
  269. setDataField(mFields[i].mFieldName, NULL, "");
  270. mFields.erase(i);
  271. continue;
  272. }
  273. }
  274. //next, get a listing of our materials in the shape, and build our field list for them
  275. char matFieldName[128];
  276. if(materialCount > 0)
  277. mComponentGroup = StringTable->insert("Materials");
  278. for(U32 i=0; i < materialCount; i++)
  279. {
  280. String materialname = mShape->materialList->getMaterialName(i);
  281. if(materialname == String("ShapeBounds"))
  282. continue;
  283. dSprintf(matFieldName, 128, "MaterialSlot%d", i);
  284. addComponentField(matFieldName, "A material used in the shape file", "TypeAssetId", materialname, "");
  285. }
  286. if(materialCount > 0)
  287. mComponentGroup = "";
  288. }
  289. if(mOwner != NULL)
  290. {
  291. Point3F min, max, pos;
  292. pos = mOwner->getPosition();
  293. mOwner->getWorldToObj().mulP(pos);
  294. min = mShape->bounds.minExtents;
  295. max = mShape->bounds.maxExtents;
  296. mShapeBounds.set(min, max);
  297. mOwner->setObjectBox(Box3F(min, max));
  298. if( mOwner->getSceneManager() != NULL )
  299. mOwner->getSceneManager()->notifyObjectDirty( mOwner );
  300. }
  301. //finally, notify that our shape was changed
  302. onShapeInstanceChanged.trigger(this);
  303. }
  304. }
  305. void MeshComponent::setupShape()
  306. {
  307. mShapeInstance = new TSShapeInstance(mShape, true);
  308. }
  309. void MeshComponent::updateMaterials()
  310. {
  311. if (mChangingMaterials.empty() || !mShape)
  312. return;
  313. TSMaterialList* pMatList = mShapeInstance->getMaterialList();
  314. pMatList->setTextureLookupPath(getShapeResource().getPath().getPath());
  315. const Vector<String> &materialNames = pMatList->getMaterialNameList();
  316. for ( S32 i = 0; i < materialNames.size(); i++ )
  317. {
  318. const String &pName = materialNames[i];
  319. for(U32 m=0; m < mChangingMaterials.size(); m++)
  320. {
  321. if(mChangingMaterials[m].slot == i)
  322. {
  323. pMatList->renameMaterial( i, mChangingMaterials[m].matName );
  324. }
  325. }
  326. mChangingMaterials.clear();
  327. }
  328. // Initialize the material instances
  329. mShapeInstance->initMaterialList();
  330. }
  331. MatrixF MeshComponent::getNodeTransform(S32 nodeIdx)
  332. {
  333. if (mShape)
  334. {
  335. S32 nodeCount = getShape()->nodes.size();
  336. if(nodeIdx >= 0 && nodeIdx < nodeCount)
  337. {
  338. //animate();
  339. MatrixF mountTransform = mShapeInstance->mNodeTransforms[nodeIdx];
  340. mountTransform.mul(mOwner->getRenderTransform());
  341. return mountTransform;
  342. }
  343. }
  344. return MatrixF::Identity;
  345. }
  346. S32 MeshComponent::getNodeByName(String nodeName)
  347. {
  348. if (mShape)
  349. {
  350. S32 nodeIdx = getShape()->findNode(nodeName);
  351. return nodeIdx;
  352. }
  353. return -1;
  354. }
  355. bool MeshComponent::castRayRendered(const Point3F &start, const Point3F &end, RayInfo *info)
  356. {
  357. return false;
  358. }
  359. void MeshComponent::mountObjectToNode(SceneObject* objB, String node, MatrixF txfm)
  360. {
  361. const char* test;
  362. test = node.c_str();
  363. if(dIsdigit(test[0]))
  364. {
  365. getOwner()->mountObject(objB, dAtoi(node), txfm);
  366. }
  367. else
  368. {
  369. if(TSShape* shape = getShape())
  370. {
  371. S32 idx = shape->findNode(node);
  372. getOwner()->mountObject(objB, idx, txfm);
  373. }
  374. }
  375. }
  376. void MeshComponent::onDynamicModified(const char* slotName, const char* newValue)
  377. {
  378. if(FindMatch::isMatch( "materialslot*", slotName, false ))
  379. {
  380. if(!getShape())
  381. return;
  382. S32 slot = -1;
  383. String outStr( String::GetTrailingNumber( slotName, slot ) );
  384. if(slot == -1)
  385. return;
  386. bool found = false;
  387. for(U32 i=0; i < mChangingMaterials.size(); i++)
  388. {
  389. if(mChangingMaterials[i].slot == slot)
  390. {
  391. mChangingMaterials[i].matName = String(newValue);
  392. found = true;
  393. }
  394. }
  395. if(!found)
  396. {
  397. matMap newMatMap;
  398. newMatMap.slot = slot;
  399. newMatMap.matName = String(newValue);
  400. mChangingMaterials.push_back(newMatMap);
  401. }
  402. setMaskBits(MaterialMask);
  403. }
  404. Parent::onDynamicModified(slotName, newValue);
  405. }
  406. void MeshComponent::changeMaterial(U32 slot, const char* newMat)
  407. {
  408. char fieldName[512];
  409. //update our respective field
  410. dSprintf(fieldName, 512, "materialSlot%d", slot);
  411. setDataField(fieldName, NULL, newMat);
  412. }
  413. void MeshComponent::onInspect()
  414. {
  415. }
  416. void MeshComponent::onEndInspect()
  417. {
  418. }