meshComponent.cpp 14 KB

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