meshComponent.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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/gfxTextureManager.h"
  38. #include "materials/materialFeatureTypes.h"
  39. #include "renderInstance/renderImposterMgr.h"
  40. #include "util/imposterCapture.h"
  41. #include "gfx/sim/debugDraw.h"
  42. #include "gfx/gfxDrawUtil.h"
  43. #include "materials/materialManager.h"
  44. #include "materials/matInstance.h"
  45. #include "core/strings/findMatch.h"
  46. #include "T3D/components/render/meshComponent_ScriptBinding.h"
  47. ImplementEnumType(BatchingMode,
  48. "Type of mesh data available in a shape.\n"
  49. "@ingroup gameObjects")
  50. {
  51. MeshComponent::Individual, "Individual", "This mesh is rendered indivudally, wthout batching or instancing."
  52. },
  53. { MeshComponent::StaticBatch, "Static Batching", "Statically batches this mesh together with others to reduce drawcalls." },
  54. //{ MeshComponent::DynamicBatch, "Dynamic Batching", "Dynamical batches this mesh together with others to reduce drawcalls each frame." },
  55. // { MeshComponent::Instanced, "Instanced", "This mesh is rendered as an instance, reducing draw overhead with others that share the same mesh and material." },
  56. EndImplementEnumType;
  57. //////////////////////////////////////////////////////////////////////////
  58. // Constructor/Destructor
  59. //////////////////////////////////////////////////////////////////////////
  60. MeshComponent::MeshComponent() : Component(), mShape(nullptr), mRenderMode(Individual)
  61. {
  62. mFriendlyName = "Mesh Component";
  63. mComponentType = "Render";
  64. mDescription = getDescriptionText("Causes the object to render a non-animating 3d shape using the file provided.");
  65. mNetworked = true;
  66. mShapeName = StringTable->EmptyString();
  67. mShapeAsset = StringTable->EmptyString();
  68. mMeshAsset = StringTable->EmptyString();
  69. mMeshAssetId = StringTable->EmptyString();
  70. mInterfaceData = new MeshRenderSystemInterface();
  71. mRenderMode = Individual;
  72. }
  73. MeshComponent::~MeshComponent()
  74. {
  75. if (mInterfaceData)
  76. SAFE_DELETE(mInterfaceData);
  77. }
  78. IMPLEMENT_CO_NETOBJECT_V1(MeshComponent);
  79. //==========================================================================================
  80. bool MeshComponent::onAdd()
  81. {
  82. if(! Parent::onAdd())
  83. return false;
  84. // Register for the resource change signal.
  85. ResourceManager::get().getChangedSignal().notify( this, &MeshComponent::_onResourceChanged );
  86. return true;
  87. }
  88. void MeshComponent::onComponentAdd()
  89. {
  90. Parent::onComponentAdd();
  91. if (isClientObject())
  92. mInterfaceData->mIsClient = true;
  93. // if (mInterfaceData != nullptr)
  94. // mInterfaceData->mIsClient = isClientObject();
  95. //get the default shape, if any
  96. updateShape();
  97. }
  98. void MeshComponent::onRemove()
  99. {
  100. Parent::onRemove();
  101. }
  102. void MeshComponent::onComponentRemove()
  103. {
  104. if(mOwner)
  105. {
  106. Point3F pos = mOwner->getPosition(); //store our center pos
  107. mOwner->setObjectBox(Box3F(Point3F(-1,-1,-1), Point3F(1,1,1)));
  108. mOwner->setPosition(pos);
  109. }
  110. Parent::onComponentRemove();
  111. }
  112. void MeshComponent::initPersistFields()
  113. {
  114. Parent::initPersistFields();
  115. addGroup("Rendering");
  116. addField("BatchingMode", TypeBatchingMode, Offset(mRenderMode, MeshComponent),
  117. "The mode of batching this shape should be rendered with.");
  118. endGroup("Rendering");
  119. //create a hook to our internal variables
  120. addGroup("Model");
  121. addProtectedField("MeshAsset", TypeShapeAssetPtr, Offset(mShapeAsset, MeshComponent), &_setMesh, &defaultProtectedGetFn,
  122. "The asset Id used for the mesh.", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  123. endGroup("Model");
  124. }
  125. bool MeshComponent::_setMesh(void *object, const char *index, const char *data)
  126. {
  127. MeshComponent *rbI = static_cast<MeshComponent*>(object);
  128. // Sanity!
  129. AssertFatal(data != NULL, "Cannot use a NULL asset Id.");
  130. return rbI->setMeshAsset(data);
  131. }
  132. bool MeshComponent::_setShape( void *object, const char *index, const char *data )
  133. {
  134. MeshComponent *rbI = static_cast<MeshComponent*>(object);
  135. rbI->mShapeName = StringTable->insert(data);
  136. rbI->updateShape(); //make sure we force the update to resize the owner bounds
  137. rbI->setMaskBits(ShapeMask);
  138. return true;
  139. }
  140. bool MeshComponent::setMeshAsset(const char* assetName)
  141. {
  142. // Fetch the asset Id.
  143. if (mInterfaceData == nullptr)
  144. return false;
  145. mMeshAssetId = StringTable->insert(assetName);
  146. mMeshAsset = mMeshAssetId;
  147. if (mMeshAsset.isNull())
  148. {
  149. Con::errorf("[MeshComponent] Failed to load mesh asset.");
  150. return false;
  151. }
  152. mShapeName = mMeshAssetId;
  153. mShapeAsset = mShapeName;
  154. updateShape(); //make sure we force the update to resize the owner bounds
  155. setMaskBits(ShapeMask);
  156. return true;
  157. }
  158. void MeshComponent::updateShape()
  159. {
  160. if (mInterfaceData == nullptr)
  161. return;
  162. //if ((mShapeName && mShapeName[0] != '\0') || (mShapeAsset && mShapeAsset[0] != '\0'))
  163. if ((mShapeName && mShapeName[0] != '\0') || (mMeshAssetId && mMeshAssetId[0] != '\0'))
  164. {
  165. if (mMeshAsset == NULL)
  166. return;
  167. mShape = mMeshAsset->getShape();
  168. if (!mMeshAsset->getShape())
  169. return;
  170. setupShape();
  171. //Do this on both the server and client
  172. S32 materialCount = mMeshAsset->getShape()->materialList->getMaterialNameList().size();
  173. if (isServerObject())
  174. {
  175. //we need to update the editor
  176. for (U32 i = 0; i < mFields.size(); i++)
  177. {
  178. //find any with the materialslot title and clear them out
  179. if (FindMatch::isMatch("MaterialSlot*", mFields[i].mFieldName, false))
  180. {
  181. setDataField(mFields[i].mFieldName, NULL, "");
  182. mFields.erase(i);
  183. continue;
  184. }
  185. }
  186. //next, get a listing of our materials in the shape, and build our field list for them
  187. char matFieldName[128];
  188. if (materialCount > 0)
  189. mComponentGroup = StringTable->insert("Materials");
  190. for (U32 i = 0; i < materialCount; i++)
  191. {
  192. String materialname = mMeshAsset->getShape()->materialList->getMaterialName(i);
  193. if (materialname == String("ShapeBounds"))
  194. continue;
  195. dSprintf(matFieldName, 128, "MaterialSlot%d", i);
  196. addComponentField(matFieldName, "A material used in the shape file", "Material", materialname, "");
  197. }
  198. if (materialCount > 0)
  199. mComponentGroup = "";
  200. }
  201. if (mOwner != NULL)
  202. {
  203. Point3F min, max, pos;
  204. pos = mOwner->getPosition();
  205. mOwner->getWorldToObj().mulP(pos);
  206. min = mMeshAsset->getShape()->mBounds.minExtents;
  207. max = mMeshAsset->getShape()->mBounds.maxExtents;
  208. if (mInterfaceData)
  209. {
  210. mInterfaceData->mBounds.set(min, max);
  211. mInterfaceData->mScale = mOwner->getScale();
  212. mInterfaceData->mTransform = mOwner->getRenderTransform();
  213. }
  214. mOwner->setObjectBox(Box3F(min, max));
  215. mOwner->resetWorldBox();
  216. if (mOwner->getSceneManager() != NULL)
  217. mOwner->getSceneManager()->notifyObjectDirty(mOwner);
  218. }
  219. if (isClientObject() && mInterfaceData)
  220. {
  221. if (mRenderMode == StaticBatch)
  222. {
  223. mInterfaceData->mStatic = true;
  224. OptimizedPolyList geom;
  225. MatrixF transform = mInterfaceData->mTransform;
  226. mInterfaceData->mGeometry.setTransform(&transform, mInterfaceData->mScale);
  227. mInterfaceData->mGeometry.setObject(mOwner);
  228. mInterfaceData->mShapeInstance->buildPolyList(&mInterfaceData->mGeometry, 0);
  229. }
  230. else
  231. {
  232. mInterfaceData->mStatic = false;
  233. }
  234. MeshRenderSystem::rebuildBuffers();
  235. }
  236. //finally, notify that our shape was changed
  237. onShapeInstanceChanged.trigger(this);
  238. }
  239. }
  240. void MeshComponent::setupShape()
  241. {
  242. mInterfaceData->mShapeInstance = new TSShapeInstance(mMeshAsset->getShape(), true);
  243. }
  244. void MeshComponent::_onResourceChanged( const Torque::Path &path )
  245. {
  246. if (mInterfaceData == nullptr)
  247. return;
  248. String filePath;
  249. if (mMeshAsset)
  250. filePath = Torque::Path(mMeshAsset->getShapeFilename());
  251. if (!mMeshAsset || path != Torque::Path(mMeshAsset->getShapeFilename()) )
  252. return;
  253. updateShape();
  254. setMaskBits(ShapeMask);
  255. }
  256. void MeshComponent::inspectPostApply()
  257. {
  258. Parent::inspectPostApply();
  259. }
  260. U32 MeshComponent::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  261. {
  262. U32 retMask = Parent::packUpdate(con, mask, stream);
  263. if (!mOwner || con->getGhostIndex(mOwner) == -1)
  264. {
  265. stream->writeFlag(false);
  266. stream->writeFlag(false);
  267. if (mask & ShapeMask)
  268. retMask |= ShapeMask;
  269. if (mask & MaterialMask)
  270. retMask |= MaterialMask;
  271. return retMask;
  272. }
  273. if (stream->writeFlag(mask & ShapeMask))
  274. {
  275. stream->writeString(mShapeName);
  276. stream->writeInt(mRenderMode, 8);
  277. }
  278. if (stream->writeFlag( mask & MaterialMask ))
  279. {
  280. stream->writeInt(mChangingMaterials.size(), 16);
  281. for(U32 i=0; i < mChangingMaterials.size(); i++)
  282. {
  283. stream->writeInt(mChangingMaterials[i].slot, 16);
  284. NetStringHandle matNameStr = mChangingMaterials[i].assetId.c_str();
  285. con->packNetStringHandleU(stream, matNameStr);
  286. }
  287. mChangingMaterials.clear();
  288. }
  289. return retMask;
  290. }
  291. void MeshComponent::unpackUpdate(NetConnection *con, BitStream *stream)
  292. {
  293. Parent::unpackUpdate(con, stream);
  294. if(stream->readFlag())
  295. {
  296. mShapeName = stream->readSTString();
  297. mRenderMode = (RenderMode)stream->readInt(8);
  298. setMeshAsset(mShapeName);
  299. updateShape();
  300. }
  301. if(stream->readFlag())
  302. {
  303. mChangingMaterials.clear();
  304. U32 materialCount = stream->readInt(16);
  305. for(U32 i=0; i < materialCount; i++)
  306. {
  307. matMap newMatMap;
  308. newMatMap.slot = stream->readInt(16);
  309. newMatMap.assetId = String(con->unpackNetStringHandleU(stream).getString());
  310. //do the lookup, now
  311. newMatMap.matAsset = AssetDatabase.acquireAsset<MaterialAsset>(newMatMap.assetId);
  312. mChangingMaterials.push_back(newMatMap);
  313. }
  314. updateMaterials();
  315. }
  316. }
  317. void MeshComponent::prepRenderImage( SceneRenderState *state )
  318. {
  319. /*if (!mEnabled || !mOwner || !mShapeInstance)
  320. return;
  321. Point3F cameraOffset;
  322. mOwner->getRenderTransform().getColumn(3, &cameraOffset);
  323. cameraOffset -= state->getDiffuseCameraPosition();
  324. F32 dist = cameraOffset.len();
  325. if (dist < 0.01f)
  326. dist = 0.01f;
  327. Point3F objScale = getOwner()->getScale();
  328. F32 invScale = (1.0f / getMax(getMax(objScale.x, objScale.y), objScale.z));
  329. mShapeInstance->setDetailFromDistance(state, dist * invScale);
  330. if (mShapeInstance->getCurrentDetail() < 0)
  331. return;
  332. GFXTransformSaver saver;
  333. // Set up our TS render state.
  334. TSRenderState rdata;
  335. rdata.setSceneState(state);
  336. rdata.setFadeOverride(1.0f);
  337. rdata.setOriginSort(false);
  338. // We might have some forward lit materials
  339. // so pass down a query to gather lights.
  340. LightQuery query;
  341. query.init(mOwner->getWorldSphere());
  342. rdata.setLightQuery(&query);
  343. MatrixF mat = mOwner->getRenderTransform();
  344. if (mOwner->isMounted())
  345. {
  346. MatrixF wrldPos = mOwner->getWorldTransform();
  347. Point3F wrldPosPos = wrldPos.getPosition();
  348. Point3F mntPs = mat.getPosition();
  349. EulerF mntRt = RotationF(mat).asEulerF();
  350. bool tr = true;
  351. }
  352. mat.scale(objScale);
  353. GFX->setWorldMatrix(mat);
  354. mShapeInstance->render(rdata);*/
  355. }
  356. void MeshComponent::updateMaterials()
  357. {
  358. if (mChangingMaterials.empty() || !mMeshAsset->getShape())
  359. return;
  360. TSMaterialList* pMatList = mInterfaceData->mShapeInstance->getMaterialList();
  361. pMatList->setTextureLookupPath(getShapeResource().getPath().getPath());
  362. const Vector<String> &materialNames = pMatList->getMaterialNameList();
  363. for ( S32 i = 0; i < materialNames.size(); i++ )
  364. {
  365. for(U32 m=0; m < mChangingMaterials.size(); m++)
  366. {
  367. if(mChangingMaterials[m].slot == i)
  368. {
  369. //Fetch the actual material asset
  370. pMatList->renameMaterial( i, mChangingMaterials[m].matAsset->getMaterialDefinitionName());
  371. }
  372. }
  373. mChangingMaterials.clear();
  374. }
  375. // Initialize the material instances
  376. mInterfaceData->mShapeInstance->initMaterialList();
  377. }
  378. MatrixF MeshComponent::getNodeTransform(S32 nodeIdx)
  379. {
  380. if (mInterfaceData != nullptr && mMeshAsset->getShape())
  381. {
  382. S32 nodeCount = getShape()->nodes.size();
  383. if(nodeIdx >= 0 && nodeIdx < nodeCount)
  384. {
  385. //animate();
  386. MatrixF nodeTransform = mInterfaceData->mShapeInstance->mNodeTransforms[nodeIdx];
  387. const Point3F& scale = mOwner->getScale();
  388. // The position of the node needs to be scaled.
  389. Point3F position = nodeTransform.getPosition();
  390. position.convolve(scale);
  391. nodeTransform.setPosition(position);
  392. MatrixF finalTransform = MatrixF::Identity;
  393. finalTransform.mul(mOwner->getRenderTransform(), nodeTransform);
  394. return finalTransform;
  395. }
  396. }
  397. return MatrixF::Identity;
  398. }
  399. S32 MeshComponent::getNodeByName(String nodeName)
  400. {
  401. if (mMeshAsset->getShape())
  402. {
  403. S32 nodeIdx = getShape()->findNode(nodeName);
  404. return nodeIdx;
  405. }
  406. return -1;
  407. }
  408. bool MeshComponent::castRayRendered(const Point3F &start, const Point3F &end, RayInfo *info)
  409. {
  410. return false;
  411. }
  412. void MeshComponent::mountObjectToNode(SceneObject* objB, String node, MatrixF txfm)
  413. {
  414. const char* test;
  415. test = node.c_str();
  416. if(dIsdigit(test[0]))
  417. {
  418. getOwner()->mountObject(objB, dAtoi(node), txfm);
  419. }
  420. else
  421. {
  422. if(TSShape* shape = getShape())
  423. {
  424. S32 idx = shape->findNode(node);
  425. getOwner()->mountObject(objB, idx, txfm);
  426. }
  427. }
  428. }
  429. void MeshComponent::onDynamicModified(const char* slotName, const char* newValue)
  430. {
  431. if(FindMatch::isMatch( "materialslot*", slotName, false ))
  432. {
  433. if(!getShape())
  434. return;
  435. S32 slot = -1;
  436. String outStr( String::GetTrailingNumber( slotName, slot ) );
  437. if(slot == -1)
  438. return;
  439. //Safe to assume the inbound value for the material will be a MaterialAsset, so lets do a lookup on the name
  440. MaterialAsset* matAsset = AssetDatabase.acquireAsset<MaterialAsset>(newValue);
  441. if (!matAsset)
  442. return;
  443. bool found = false;
  444. for(U32 i=0; i < mChangingMaterials.size(); i++)
  445. {
  446. if(mChangingMaterials[i].slot == slot)
  447. {
  448. mChangingMaterials[i].matAsset = matAsset;
  449. mChangingMaterials[i].assetId = newValue;
  450. found = true;
  451. }
  452. }
  453. if(!found)
  454. {
  455. matMap newMatMap;
  456. newMatMap.slot = slot;
  457. newMatMap.matAsset = matAsset;
  458. newMatMap.assetId = newValue;
  459. mChangingMaterials.push_back(newMatMap);
  460. }
  461. setMaskBits(MaterialMask);
  462. }
  463. Parent::onDynamicModified(slotName, newValue);
  464. }
  465. void MeshComponent::changeMaterial(U32 slot, MaterialAsset* newMat)
  466. {
  467. char fieldName[512];
  468. //update our respective field
  469. dSprintf(fieldName, 512, "materialSlot%d", slot);
  470. setDataField(fieldName, NULL, newMat->getAssetId());
  471. }
  472. bool MeshComponent::setMatInstField(U32 slot, const char* field, const char* value)
  473. {
  474. TSMaterialList* pMatList = mInterfaceData->mShapeInstance->getMaterialList();
  475. pMatList->setTextureLookupPath(getShapeResource().getPath().getPath());
  476. MaterialParameters* params = pMatList->getMaterialInst(slot)->getMaterialParameters();
  477. if (pMatList->getMaterialInst(slot)->getFeatures().hasFeature(MFT_DiffuseColor))
  478. {
  479. MaterialParameterHandle* handle = pMatList->getMaterialInst(slot)->getMaterialParameterHandle("DiffuseColor");
  480. params->set(handle, LinearColorF(0, 0, 0));
  481. }
  482. return true;
  483. }
  484. void MeshComponent::onInspect()
  485. {
  486. }
  487. void MeshComponent::onEndInspect()
  488. {
  489. }
  490. void MeshComponent::ownerTransformSet(MatrixF *mat)
  491. {
  492. if (mInterfaceData != nullptr)
  493. {
  494. MatrixF newTransform = *mat;
  495. mInterfaceData->mTransform = newTransform;
  496. }
  497. }