MaterialAsset.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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("materialDefinitionName", TypeString, Offset(mMatDefinitionName, MaterialAsset), "Name of the material definition this asset is for.");
  125. }
  126. void MaterialAsset::initializeAsset()
  127. {
  128. // Call parent.
  129. Parent::initializeAsset();
  130. mScriptPath = getOwned() ? expandAssetFilePath(mScriptFile) : mScriptPath;
  131. if (mMatDefinitionName == StringTable->EmptyString())
  132. {
  133. mLoadedState = Failed;
  134. return;
  135. }
  136. if (Torque::FS::IsScriptFile(mScriptPath))
  137. {
  138. if (!Sim::findObject(mMatDefinitionName))
  139. {
  140. if (Con::executeFile(mScriptPath, false, false))
  141. {
  142. mLoadedState = ScriptLoaded;
  143. }
  144. else
  145. {
  146. mLoadedState = Failed;
  147. }
  148. }
  149. else
  150. {
  151. mLoadedState = DefinitionAlreadyExists;
  152. }
  153. }
  154. loadMaterial();
  155. }
  156. void MaterialAsset::onAssetRefresh()
  157. {
  158. mScriptPath = getOwned() ? expandAssetFilePath(mScriptFile) : mScriptPath;
  159. if (mMatDefinitionName == StringTable->EmptyString())
  160. {
  161. mLoadedState = Failed;
  162. return;
  163. }
  164. if (Torque::FS::IsScriptFile(mScriptPath))
  165. {
  166. //Since we're refreshing, we can assume that the file we're executing WILL have an existing definition.
  167. //But that definition, whatever it is, is the 'correct' one, so we enable the Replace Existing behavior
  168. //when the engine encounters a named object conflict.
  169. String redefineBehaviorPrev = Con::getVariable("$Con::redefineBehavior");
  170. Con::setVariable("$Con::redefineBehavior", "replaceExisting");
  171. if (Con::executeFile(mScriptPath, false, false))
  172. mLoadedState = ScriptLoaded;
  173. else
  174. mLoadedState = Failed;
  175. //And now that we've executed, switch back to the prior behavior
  176. Con::setVariable("$Con::redefineBehavior", redefineBehaviorPrev.c_str());
  177. }
  178. loadMaterial();
  179. }
  180. void MaterialAsset::setScriptFile(const char* pScriptFile)
  181. {
  182. // Sanity!
  183. AssertFatal(pScriptFile != NULL, "Cannot use a NULL script file.");
  184. // Fetch image file.
  185. pScriptFile = StringTable->insert(pScriptFile, true);
  186. // Update.
  187. mScriptFile = getOwned() ? expandAssetFilePath(pScriptFile) : pScriptFile;
  188. // Refresh the asset.
  189. refreshAsset();
  190. }
  191. //------------------------------------------------------------------------------
  192. void MaterialAsset::loadMaterial()
  193. {
  194. if (mMaterialDefinition)
  195. SAFE_DELETE(mMaterialDefinition);
  196. if ((mLoadedState == ScriptLoaded || mLoadedState == DefinitionAlreadyExists) && mMatDefinitionName != StringTable->EmptyString())
  197. {
  198. Material* matDef;
  199. if (!Sim::findObject(mMatDefinitionName, matDef))
  200. {
  201. Con::errorf("MaterialAsset: Unable to find the Material %s", mMatDefinitionName);
  202. mLoadedState = BadFileReference;
  203. return;
  204. }
  205. mMaterialDefinition = matDef;
  206. mLoadedState = Ok;
  207. mMaterialDefinition->reload();
  208. return;
  209. }
  210. mLoadedState = Failed;
  211. }
  212. //------------------------------------------------------------------------------
  213. void MaterialAsset::copyTo(SimObject* object)
  214. {
  215. // Call to parent.
  216. Parent::copyTo(object);
  217. }
  218. //------------------------------------------------------------------------------
  219. U32 MaterialAsset::getAssetByMaterialName(StringTableEntry matName, AssetPtr<MaterialAsset>* matAsset)
  220. {
  221. AssetQuery query;
  222. U32 foundAssetcount = AssetDatabase.findAssetType(&query, "MaterialAsset");
  223. if (foundAssetcount == 0)
  224. {
  225. //Didn't work, so have us fall back to a placeholder asset
  226. matAsset->setAssetId(MaterialAsset::smNoMaterialAssetFallback);
  227. if (matAsset->isNull())
  228. {
  229. //Well that's bad, loading the fallback failed.
  230. Con::warnf("MaterialAsset::getAssetByMaterialName - Finding of asset associated with material name %s failed with no fallback asset", matName);
  231. return AssetErrCode::Failed;
  232. }
  233. //handle noshape not being loaded itself
  234. if ((*matAsset)->mLoadedState == BadFileReference)
  235. {
  236. Con::warnf("ShapeAsset::getAssetByMaterialName - Finding of associated with aterial name %s failed, and fallback asset reported error of Bad File Reference.", matName);
  237. return AssetErrCode::BadFileReference;
  238. }
  239. Con::warnf("ShapeAsset::getAssetByMaterialName - Finding of associated with aterial name %s failed, utilizing fallback asset", matName);
  240. (*matAsset)->mLoadedState = AssetErrCode::UsingFallback;
  241. return AssetErrCode::UsingFallback;
  242. }
  243. else
  244. {
  245. for (U32 i = 0; i < foundAssetcount; i++)
  246. {
  247. MaterialAsset* tMatAsset = AssetDatabase.acquireAsset<MaterialAsset>(query.mAssetList[i]);
  248. if (tMatAsset && tMatAsset->getMaterialDefinitionName() == matName)
  249. {
  250. matAsset->setAssetId(query.mAssetList[i]);
  251. AssetDatabase.releaseAsset(query.mAssetList[i]);
  252. return (*matAsset)->mLoadedState;
  253. }
  254. AssetDatabase.releaseAsset(query.mAssetList[i]); //cleanup if that's not the one we needed
  255. }
  256. }
  257. //Somehow we failed to bind an asset, so just use the fallback and mark the failure
  258. matAsset->setAssetId(MaterialAsset::smNoMaterialAssetFallback);
  259. (*matAsset)->mLoadedState = AssetErrCode::UsingFallback;
  260. return AssetErrCode::UsingFallback;
  261. }
  262. StringTableEntry MaterialAsset::getAssetIdByMaterialName(StringTableEntry matName)
  263. {
  264. if (matName == StringTable->EmptyString())
  265. return StringTable->EmptyString();
  266. StringTableEntry materialAssetId = MaterialAsset::smNoMaterialAssetFallback;
  267. AssetQuery query;
  268. U32 foundCount = AssetDatabase.findAssetType(&query, "MaterialAsset");
  269. if (foundCount != 0)
  270. {
  271. for (U32 i = 0; i < foundCount; i++)
  272. {
  273. MaterialAsset* matAsset = AssetDatabase.acquireAsset<MaterialAsset>(query.mAssetList[i]);
  274. if (matAsset && matAsset->getMaterialDefinitionName() == matName)
  275. {
  276. materialAssetId = matAsset->getAssetId();
  277. AssetDatabase.releaseAsset(query.mAssetList[i]);
  278. break;
  279. }
  280. AssetDatabase.releaseAsset(query.mAssetList[i]);
  281. }
  282. }
  283. return materialAssetId;
  284. }
  285. U32 MaterialAsset::getAssetById(StringTableEntry assetId, AssetPtr<MaterialAsset>* materialAsset)
  286. {
  287. (*materialAsset) = assetId;
  288. if (materialAsset->notNull())
  289. {
  290. return (*materialAsset)->mLoadedState;
  291. }
  292. else
  293. {
  294. //Didn't work, so have us fall back to a placeholder asset
  295. materialAsset->setAssetId(MaterialAsset::smNoMaterialAssetFallback);
  296. if (materialAsset->isNull())
  297. {
  298. //Well that's bad, loading the fallback failed.
  299. Con::warnf("MaterialAsset::getAssetById - Finding of asset with id %s failed with no fallback asset", assetId);
  300. return AssetErrCode::Failed;
  301. }
  302. //handle noshape not being loaded itself
  303. if ((*materialAsset)->mLoadedState == BadFileReference)
  304. {
  305. Con::warnf("MaterialAsset::getAssetById - Finding of asset with id %s failed, and fallback asset reported error of Bad File Reference.", assetId);
  306. return AssetErrCode::BadFileReference;
  307. }
  308. Con::warnf("MaterialAsset::getAssetById - Finding of asset with id %s failed, utilizing fallback asset", assetId);
  309. (*materialAsset)->mLoadedState = AssetErrCode::UsingFallback;
  310. return AssetErrCode::UsingFallback;
  311. }
  312. }
  313. #ifdef TORQUE_TOOLS
  314. DefineEngineStaticMethod(MaterialAsset, getAssetIdByMaterialName, const char*, (const char* materialName), (""),
  315. "Queries the Asset Database to see if any asset exists that is associated with the provided material name.\n"
  316. "@return The AssetId of the associated asset, if any.")
  317. {
  318. return MaterialAsset::getAssetIdByMaterialName(StringTable->insert(materialName));
  319. }
  320. DefineEngineMethod(MaterialAsset, getScriptPath, const char*, (), ,
  321. "Queries the Asset Database to see if any asset exists that is associated with the provided material name.\n"
  322. "@return The AssetId of the associated asset, if any.")
  323. {
  324. return object->getScriptPath();
  325. }
  326. #endif
  327. //-----------------------------------------------------------------------------
  328. // GuiInspectorTypeAssetId
  329. //-----------------------------------------------------------------------------
  330. IMPLEMENT_CONOBJECT(GuiInspectorTypeMaterialAssetPtr);
  331. ConsoleDocClass(GuiInspectorTypeMaterialAssetPtr,
  332. "@brief Inspector field type for Shapes\n\n"
  333. "Editor use only.\n\n"
  334. "@internal"
  335. );
  336. void GuiInspectorTypeMaterialAssetPtr::consoleInit()
  337. {
  338. Parent::consoleInit();
  339. ConsoleBaseType::getType(TypeMaterialAssetPtr)->setInspectorFieldType("GuiInspectorTypeMaterialAssetPtr");
  340. }
  341. GuiControl* GuiInspectorTypeMaterialAssetPtr::constructEditControl()
  342. {
  343. // Create base filename edit controls
  344. GuiControl* retCtrl = Parent::constructEditControl();
  345. if (retCtrl == NULL)
  346. return retCtrl;
  347. // Change filespec
  348. char szBuffer[512];
  349. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"MaterialAsset\", \"AssetBrowser.changeAsset\", %s, \"\");",
  350. getIdString());
  351. mBrowseButton->setField("Command", szBuffer);
  352. setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
  353. // Create "Open in Editor" button
  354. mEditButton = new GuiBitmapButtonCtrl();
  355. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.editAsset(%d.getText());", retCtrl->getId());
  356. mEditButton->setField("Command", szBuffer);
  357. char bitmapName[512] = "ToolsModule:material_editor_n_image";
  358. mEditButton->setBitmap(StringTable->insert(bitmapName));
  359. mEditButton->setDataField(StringTable->insert("Profile"), NULL, "GuiButtonProfile");
  360. mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
  361. mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
  362. mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Open this asset in the Material Editor");
  363. mEditButton->registerObject();
  364. addObject(mEditButton);
  365. return retCtrl;
  366. }
  367. bool GuiInspectorTypeMaterialAssetPtr::updateRects()
  368. {
  369. S32 dividerPos, dividerMargin;
  370. mInspector->getDivider(dividerPos, dividerMargin);
  371. Point2I fieldExtent = getExtent();
  372. Point2I fieldPos = getPosition();
  373. mCaptionRect.set(0, 0, fieldExtent.x - dividerPos - dividerMargin, fieldExtent.y);
  374. mEditCtrlRect.set(fieldExtent.x - dividerPos + dividerMargin, 1, dividerPos - dividerMargin - 34, fieldExtent.y);
  375. bool resized = mEdit->resize(mEditCtrlRect.point, mEditCtrlRect.extent);
  376. if (mBrowseButton != NULL)
  377. {
  378. mBrowseRect.set(fieldExtent.x - 32, 2, 14, fieldExtent.y - 4);
  379. resized |= mBrowseButton->resize(mBrowseRect.point, mBrowseRect.extent);
  380. }
  381. if (mEditButton != NULL)
  382. {
  383. RectI shapeEdRect(fieldExtent.x - 16, 2, 14, fieldExtent.y - 4);
  384. resized |= mEditButton->resize(shapeEdRect.point, shapeEdRect.extent);
  385. }
  386. return resized;
  387. }
  388. IMPLEMENT_CONOBJECT(GuiInspectorTypeMaterialAssetId);
  389. ConsoleDocClass(GuiInspectorTypeMaterialAssetId,
  390. "@brief Inspector field type for Material Assets\n\n"
  391. "Editor use only.\n\n"
  392. "@internal"
  393. );
  394. void GuiInspectorTypeMaterialAssetId::consoleInit()
  395. {
  396. Parent::consoleInit();
  397. ConsoleBaseType::getType(TypeMaterialAssetId)->setInspectorFieldType("GuiInspectorTypeMaterialAssetId");
  398. }