MaterialAsset.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 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. #ifndef MATERIALASSET_H
  23. #include "MaterialAsset.h"
  24. #endif
  25. #ifndef _ASSET_MANAGER_H_
  26. #include "assets/assetManager.h"
  27. #endif
  28. #ifndef _CONSOLETYPES_H_
  29. #include "console/consoleTypes.h"
  30. #endif
  31. #ifndef _TAML_
  32. #include "persistence/taml/taml.h"
  33. #endif
  34. #ifndef _ASSET_PTR_H_
  35. #include "assets/assetPtr.h"
  36. #endif
  37. #include "T3D/assets/assetImporter.h"
  38. StringTableEntry MaterialAsset::smNoMaterialAssetFallback = NULL;
  39. //-----------------------------------------------------------------------------
  40. IMPLEMENT_CONOBJECT(MaterialAsset);
  41. ConsoleType(MaterialAssetPtr, TypeMaterialAssetPtr, MaterialAsset, ASSET_ID_FIELD_PREFIX)
  42. //-----------------------------------------------------------------------------
  43. ConsoleGetType(TypeMaterialAssetPtr)
  44. {
  45. // Fetch asset Id.
  46. return (*((AssetPtr<MaterialAsset>*)dptr)).getAssetId();
  47. }
  48. //-----------------------------------------------------------------------------
  49. ConsoleSetType(TypeMaterialAssetPtr)
  50. {
  51. // Was a single argument specified?
  52. if (argc == 1)
  53. {
  54. // Yes, so fetch field value.
  55. const char* pFieldValue = argv[0];
  56. // Fetch asset pointer.
  57. AssetPtr<MaterialAsset>* pAssetPtr = dynamic_cast<AssetPtr<MaterialAsset>*>((AssetPtrBase*)(dptr));
  58. // Is the asset pointer the correct type?
  59. if (pAssetPtr == NULL)
  60. {
  61. // No, so fail.
  62. //Con::warnf("(TypeMaterialAssetPtr) - Failed to set asset Id '%d'.", pFieldValue);
  63. return;
  64. }
  65. // Set asset.
  66. pAssetPtr->setAssetId(pFieldValue);
  67. return;
  68. }
  69. // Warn.
  70. Con::warnf("(TypeMaterialAssetPtr) - Cannot set multiple args to a single asset.");
  71. }
  72. ConsoleType(assetIdString, TypeMaterialAssetId, const char*, ASSET_ID_FIELD_PREFIX)
  73. ConsoleGetType(TypeMaterialAssetId)
  74. {
  75. // Fetch asset Id.
  76. return *((const char**)(dptr));
  77. }
  78. ConsoleSetType(TypeMaterialAssetId)
  79. {
  80. // Was a single argument specified?
  81. if (argc == 1)
  82. {
  83. // Yes, so fetch field value.
  84. const char* pFieldValue = argv[0];
  85. // Fetch asset Id.
  86. StringTableEntry* assetId = (StringTableEntry*)(dptr);
  87. // Update asset value.
  88. *assetId = StringTable->insert(pFieldValue);
  89. return;
  90. }
  91. // Warn.
  92. Con::warnf("(TypeMaterialAssetId) - Cannot set multiple args to a single asset.");
  93. }
  94. //-----------------------------------------------------------------------------
  95. MaterialAsset::MaterialAsset()
  96. {
  97. mShaderGraphFile = "";
  98. mScriptFile = StringTable->EmptyString();
  99. mScriptPath = StringTable->EmptyString();
  100. mMatDefinitionName = StringTable->EmptyString();
  101. mMaterialDefinition = nullptr;
  102. }
  103. //-----------------------------------------------------------------------------
  104. MaterialAsset::~MaterialAsset()
  105. {
  106. //SAFE_DELETE(mMaterialDefinition);
  107. }
  108. //-----------------------------------------------------------------------------
  109. void MaterialAsset::consoleInit()
  110. {
  111. Parent::consoleInit();
  112. Con::addVariable("$Core::NoMaterialAssetFallback", TypeString, &smNoMaterialAssetFallback,
  113. "The assetId of the material to display when the requested material asset is missing.\n"
  114. "@ingroup GFX\n");
  115. smNoMaterialAssetFallback = StringTable->insert(Con::getVariable("$Core::NoMaterialAssetFallback"));
  116. }
  117. void MaterialAsset::initPersistFields()
  118. {
  119. // Call parent.
  120. Parent::initPersistFields();
  121. //addField("shaderGraph", TypeRealString, Offset(mShaderGraphFile, MaterialAsset), "");
  122. //addProtectedField("scriptFile", TypeAssetLooseFilePath, Offset(mScriptFile, MaterialAsset),
  123. // &setScriptFile, &getScriptFile, "Path to the file containing the material definition.");
  124. addField("scriptFile", TypeAssetLooseFilePath, Offset(mScriptFile, MaterialAsset), "");
  125. addField("materialDefinitionName", TypeString, Offset(mMatDefinitionName, MaterialAsset), "Name of the material definition this asset is for.");
  126. }
  127. void MaterialAsset::initializeAsset()
  128. {
  129. // Call parent.
  130. Parent::initializeAsset();
  131. mScriptPath = getOwned() ? expandAssetFilePath(mScriptFile) : mScriptPath;
  132. if (mMatDefinitionName == StringTable->EmptyString())
  133. {
  134. mLoadedState = Failed;
  135. return;
  136. }
  137. if (size() != 0 && mScriptPath == StringTable->EmptyString())
  138. {
  139. mLoadedState = EmbeddedDefinition;
  140. }
  141. else if (Torque::FS::IsScriptFile(mScriptPath))
  142. {
  143. if (!Sim::findObject(mMatDefinitionName))
  144. {
  145. if (Con::executeFile(mScriptPath, false, false))
  146. {
  147. mLoadedState = ScriptLoaded;
  148. }
  149. else
  150. {
  151. mLoadedState = Failed;
  152. }
  153. }
  154. else
  155. {
  156. mLoadedState = DefinitionAlreadyExists;
  157. }
  158. }
  159. loadMaterial();
  160. }
  161. void MaterialAsset::onAssetRefresh()
  162. {
  163. mScriptPath = getOwned() ? expandAssetFilePath(mScriptFile) : mScriptPath;
  164. if (mMatDefinitionName == StringTable->EmptyString())
  165. {
  166. mLoadedState = Failed;
  167. return;
  168. }
  169. if (Torque::FS::IsScriptFile(mScriptPath))
  170. {
  171. //Since we're refreshing, we can assume that the file we're executing WILL have an existing definition.
  172. //But that definition, whatever it is, is the 'correct' one, so we enable the Replace Existing behavior
  173. //when the engine encounters a named object conflict.
  174. String redefineBehaviorPrev = Con::getVariable("$Con::redefineBehavior");
  175. Con::setVariable("$Con::redefineBehavior", "replaceExisting");
  176. if (Con::executeFile(mScriptPath, false, false))
  177. mLoadedState = ScriptLoaded;
  178. else
  179. mLoadedState = Failed;
  180. //And now that we've executed, switch back to the prior behavior
  181. Con::setVariable("$Con::redefineBehavior", redefineBehaviorPrev.c_str());
  182. }
  183. loadMaterial();
  184. }
  185. void MaterialAsset::setScriptFile(const char* pScriptFile)
  186. {
  187. // Sanity!
  188. AssertFatal(pScriptFile != NULL, "Cannot use a NULL script file.");
  189. pScriptFile = StringTable->insert(pScriptFile, true);
  190. // Update.
  191. mScriptFile = getOwned() ? expandAssetFilePath(pScriptFile) : pScriptFile;
  192. // Refresh the asset.
  193. refreshAsset();
  194. }
  195. //------------------------------------------------------------------------------
  196. void MaterialAsset::loadMaterial()
  197. {
  198. if (mMaterialDefinition)
  199. {
  200. mMaterialDefinition->safeDeleteObject();
  201. }
  202. if (mLoadedState == EmbeddedDefinition)
  203. {
  204. if (size() != 0)
  205. {
  206. for (U32 i = 0; i < size(); i++)
  207. {
  208. mMaterialDefinition = dynamic_cast<Material*>(getObject(i));
  209. if (mMaterialDefinition)
  210. {
  211. mLoadedState = Ok;
  212. mMaterialDefinition->setInternalName(getAssetId());
  213. mMaterialDefinition->reload();
  214. return;
  215. }
  216. }
  217. }
  218. }
  219. else if ((mLoadedState == ScriptLoaded || mLoadedState == DefinitionAlreadyExists) && mMatDefinitionName != StringTable->EmptyString())
  220. {
  221. Material* matDef;
  222. if (!Sim::findObject(mMatDefinitionName, matDef))
  223. {
  224. Con::errorf("MaterialAsset: Unable to find the Material %s", mMatDefinitionName);
  225. mLoadedState = BadFileReference;
  226. return;
  227. }
  228. mMaterialDefinition = matDef;
  229. mLoadedState = Ok;
  230. mMaterialDefinition->setInternalName(getAssetId());
  231. mMaterialDefinition->reload();
  232. return;
  233. }
  234. mLoadedState = Failed;
  235. }
  236. //------------------------------------------------------------------------------
  237. void MaterialAsset::copyTo(SimObject* object)
  238. {
  239. // Call to parent.
  240. Parent::copyTo(object);
  241. }
  242. //------------------------------------------------------------------------------
  243. U32 MaterialAsset::getAssetByMaterialName(StringTableEntry matName, AssetPtr<MaterialAsset>* matAsset)
  244. {
  245. AssetQuery query;
  246. U32 foundAssetcount = AssetDatabase.findAssetType(&query, "MaterialAsset");
  247. if (foundAssetcount == 0)
  248. {
  249. //Didn't work, so have us fall back to a placeholder asset
  250. matAsset->setAssetId(MaterialAsset::smNoMaterialAssetFallback);
  251. if (matAsset->isNull())
  252. {
  253. //Well that's bad, loading the fallback failed.
  254. Con::warnf("MaterialAsset::getAssetByMaterialName - Finding of asset associated with material name %s failed with no fallback asset", matName);
  255. return AssetErrCode::Failed;
  256. }
  257. //handle noshape not being loaded itself
  258. if ((*matAsset)->mLoadedState == BadFileReference)
  259. {
  260. Con::warnf("MaterialAsset::getAssetByMaterialName - Finding of associated with aterial name %s failed, and fallback asset reported error of Bad File Reference.", matName);
  261. return AssetErrCode::BadFileReference;
  262. }
  263. Con::warnf("MaterialAsset::getAssetByMaterialName - Finding of associated with aterial name %s failed, utilizing fallback asset", matName);
  264. (*matAsset)->mLoadedState = AssetErrCode::UsingFallback;
  265. return AssetErrCode::UsingFallback;
  266. }
  267. else
  268. {
  269. for (U32 i = 0; i < foundAssetcount; i++)
  270. {
  271. MaterialAsset* tMatAsset = AssetDatabase.acquireAsset<MaterialAsset>(query.mAssetList[i]);
  272. if (tMatAsset && tMatAsset->getMaterialDefinitionName() == matName)
  273. {
  274. matAsset->setAssetId(query.mAssetList[i]);
  275. AssetDatabase.releaseAsset(query.mAssetList[i]);
  276. return (*matAsset)->mLoadedState;
  277. }
  278. AssetDatabase.releaseAsset(query.mAssetList[i]); //cleanup if that's not the one we needed
  279. }
  280. }
  281. //Somehow we failed to bind an asset, so just use the fallback and mark the failure
  282. matAsset->setAssetId(MaterialAsset::smNoMaterialAssetFallback);
  283. (*matAsset)->mLoadedState = AssetErrCode::UsingFallback;
  284. return AssetErrCode::UsingFallback;
  285. }
  286. StringTableEntry MaterialAsset::getAssetIdByMaterialName(StringTableEntry matName)
  287. {
  288. if (matName == StringTable->EmptyString())
  289. return StringTable->EmptyString();
  290. StringTableEntry materialAssetId = MaterialAsset::smNoMaterialAssetFallback;
  291. AssetQuery query;
  292. U32 foundCount = AssetDatabase.findAssetType(&query, "MaterialAsset");
  293. if (foundCount != 0)
  294. {
  295. for (U32 i = 0; i < foundCount; i++)
  296. {
  297. MaterialAsset* matAsset = AssetDatabase.acquireAsset<MaterialAsset>(query.mAssetList[i]);
  298. if (matAsset && matAsset->getMaterialDefinitionName() == matName)
  299. {
  300. materialAssetId = matAsset->getAssetId();
  301. AssetDatabase.releaseAsset(query.mAssetList[i]);
  302. break;
  303. }
  304. AssetDatabase.releaseAsset(query.mAssetList[i]);
  305. }
  306. }
  307. return materialAssetId;
  308. }
  309. U32 MaterialAsset::getAssetById(StringTableEntry assetId, AssetPtr<MaterialAsset>* materialAsset)
  310. {
  311. (*materialAsset) = assetId;
  312. if (materialAsset->notNull())
  313. {
  314. return (*materialAsset)->mLoadedState;
  315. }
  316. else
  317. {
  318. //Didn't work, so have us fall back to a placeholder asset
  319. materialAsset->setAssetId(MaterialAsset::smNoMaterialAssetFallback);
  320. if (materialAsset->isNull())
  321. {
  322. //Well that's bad, loading the fallback failed.
  323. Con::warnf("MaterialAsset::getAssetById - Finding of asset with id %s failed with no fallback asset", assetId);
  324. return AssetErrCode::Failed;
  325. }
  326. //handle noshape not being loaded itself
  327. if ((*materialAsset)->mLoadedState == BadFileReference)
  328. {
  329. Con::warnf("MaterialAsset::getAssetById - Finding of asset with id %s failed, and fallback asset reported error of Bad File Reference.", assetId);
  330. return AssetErrCode::BadFileReference;
  331. }
  332. Con::warnf("MaterialAsset::getAssetById - Finding of asset with id %s failed, utilizing fallback asset", assetId);
  333. (*materialAsset)->mLoadedState = AssetErrCode::UsingFallback;
  334. return AssetErrCode::UsingFallback;
  335. }
  336. }
  337. SimObjectPtr<Material> MaterialAsset::findMaterialDefinitionByAssetId(StringTableEntry assetId)
  338. {
  339. SimSet* matSet = MATMGR->getMaterialSet();
  340. if (matSet)
  341. {
  342. SimObjectPtr<Material> matDef = dynamic_cast<Material*>(matSet->findObjectByInternalName(assetId));
  343. return matDef;
  344. }
  345. return nullptr;
  346. }
  347. #ifdef TORQUE_TOOLS
  348. DefineEngineStaticMethod(MaterialAsset, getAssetIdByMaterialName, const char*, (const char* materialName), (""),
  349. "Queries the Asset Database to see if any asset exists that is associated with the provided material name.\n"
  350. "@return The AssetId of the associated asset, if any.")
  351. {
  352. return MaterialAsset::getAssetIdByMaterialName(StringTable->insert(materialName));
  353. }
  354. //MaterialAsset::findMaterialDefinitionByAssetId("Prototyping:Detail")
  355. DefineEngineStaticMethod(MaterialAsset, findMaterialDefinitionByAssetId, S32, (const char* assetId), (""),
  356. "Queries the MaterialSet to see if any MaterialDefinition exists that is associated to the provided assetId.\n"
  357. "@return The MaterialDefinition Id associated to the assetId, if any")
  358. {
  359. SimObjectPtr<Material> matDef = MaterialAsset::findMaterialDefinitionByAssetId(StringTable->insert(assetId));
  360. if (matDef.isNull())
  361. return SimObjectId(0);
  362. else
  363. return matDef->getId();
  364. }
  365. DefineEngineMethod(MaterialAsset, getScriptPath, const char*, (), ,
  366. "Gets the script file path for the asset.")
  367. {
  368. return object->getScriptPath();
  369. }
  370. #endif
  371. #ifdef TORQUE_TOOLS
  372. //-----------------------------------------------------------------------------
  373. // GuiInspectorTypeAssetId
  374. //-----------------------------------------------------------------------------
  375. IMPLEMENT_CONOBJECT(GuiInspectorTypeMaterialAssetPtr);
  376. ConsoleDocClass(GuiInspectorTypeMaterialAssetPtr,
  377. "@brief Inspector field type for Shapes\n\n"
  378. "Editor use only.\n\n"
  379. "@internal"
  380. );
  381. void GuiInspectorTypeMaterialAssetPtr::consoleInit()
  382. {
  383. Parent::consoleInit();
  384. ConsoleBaseType::getType(TypeMaterialAssetPtr)->setInspectorFieldType("GuiInspectorTypeMaterialAssetPtr");
  385. }
  386. GuiControl* GuiInspectorTypeMaterialAssetPtr::constructEditControl()
  387. {
  388. // Create base filename edit controls
  389. GuiControl* retCtrl = Parent::constructEditControl();
  390. if (retCtrl == NULL)
  391. return retCtrl;
  392. // Change filespec
  393. char szBuffer[512];
  394. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"MaterialAsset\", \"AssetBrowser.changeAsset\", %s, %s);",
  395. mInspector->getIdString(), mCaption);
  396. mBrowseButton->setField("Command", szBuffer);
  397. setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
  398. // Create "Open in Editor" button
  399. mEditButton = new GuiBitmapButtonCtrl();
  400. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.editAsset(%d.getText());", retCtrl->getId());
  401. mEditButton->setField("Command", szBuffer);
  402. char bitmapName[512] = "ToolsModule:material_editor_n_image";
  403. mEditButton->setBitmap(StringTable->insert(bitmapName));
  404. mEditButton->setDataField(StringTable->insert("Profile"), NULL, "GuiButtonProfile");
  405. mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
  406. mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
  407. mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Open this asset in the Material Editor");
  408. mEditButton->registerObject();
  409. addObject(mEditButton);
  410. return retCtrl;
  411. }
  412. bool GuiInspectorTypeMaterialAssetPtr::updateRects()
  413. {
  414. S32 dividerPos, dividerMargin;
  415. mInspector->getDivider(dividerPos, dividerMargin);
  416. Point2I fieldExtent = getExtent();
  417. Point2I fieldPos = getPosition();
  418. mCaptionRect.set(0, 0, fieldExtent.x - dividerPos - dividerMargin, fieldExtent.y);
  419. mEditCtrlRect.set(fieldExtent.x - dividerPos + dividerMargin, 1, dividerPos - dividerMargin - 34, fieldExtent.y);
  420. bool resized = mEdit->resize(mEditCtrlRect.point, mEditCtrlRect.extent);
  421. if (mBrowseButton != NULL)
  422. {
  423. mBrowseRect.set(fieldExtent.x - 32, 2, 14, fieldExtent.y - 4);
  424. resized |= mBrowseButton->resize(mBrowseRect.point, mBrowseRect.extent);
  425. }
  426. if (mEditButton != NULL)
  427. {
  428. RectI shapeEdRect(fieldExtent.x - 16, 2, 14, fieldExtent.y - 4);
  429. resized |= mEditButton->resize(shapeEdRect.point, shapeEdRect.extent);
  430. }
  431. return resized;
  432. }
  433. IMPLEMENT_CONOBJECT(GuiInspectorTypeMaterialAssetId);
  434. ConsoleDocClass(GuiInspectorTypeMaterialAssetId,
  435. "@brief Inspector field type for Material Assets\n\n"
  436. "Editor use only.\n\n"
  437. "@internal"
  438. );
  439. void GuiInspectorTypeMaterialAssetId::consoleInit()
  440. {
  441. Parent::consoleInit();
  442. ConsoleBaseType::getType(TypeMaterialAssetId)->setInspectorFieldType("GuiInspectorTypeMaterialAssetId");
  443. }
  444. #endif