ImageAsset.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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 IMAGE_ASSET_H
  23. #include "ImageAsset.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 "gfx/gfxStringEnumTranslate.h"
  38. #include "ImageAssetInspectors.h"
  39. // Debug Profiling.
  40. #include "platform/profiler.h"
  41. #include "T3D/assets/assetImporter.h"
  42. #include "gfx/gfxDrawUtil.h"
  43. #include "gfx/bitmap/ddsFile.h"
  44. #ifdef __clang__
  45. #define STBIWDEF static inline
  46. #endif
  47. #pragma warning( push )
  48. #pragma warning( disable : 4505 ) // unreferenced function removed.
  49. #ifndef STB_IMAGE_IMPLEMENTATION
  50. #define STB_IMAGE_IMPLEMENTATION
  51. #define STB_IMAGE_STATIC
  52. #include "stb_image.h"
  53. #endif
  54. #pragma warning(pop)
  55. //-----------------------------------------------------------------------------
  56. StringTableEntry ImageAsset::smNoImageAssetFallback = NULL;
  57. StringTableEntry ImageAsset::smNamedTargetAssetFallback = NULL;
  58. //-----------------------------------------------------------------------------
  59. IMPLEMENT_CONOBJECT(ImageAsset);
  60. //-----------------------------------------------------------------------------
  61. // REFACTOR
  62. //-----------------------------------------------------------------------------
  63. IMPLEMENT_STRUCT(AssetPtr<ImageAsset>, AssetPtrImageAsset,, "")
  64. END_IMPLEMENT_STRUCT
  65. ConsoleType(ImageAssetPtr, TypeImageAssetPtr, AssetPtr<ImageAsset>, ASSET_ID_FIELD_PREFIX)
  66. ConsoleGetType(TypeImageAssetPtr)
  67. {
  68. // Fetch asset Id.
  69. return (*((AssetPtr<ImageAsset>*)dptr)).getAssetId();
  70. }
  71. ConsoleSetType(TypeImageAssetPtr)
  72. {
  73. // Was a single argument specified?
  74. if (argc == 1)
  75. {
  76. // Yes, so fetch field value.
  77. const char* pFieldValue = argv[0];
  78. // Fetch asset pointer.
  79. AssetPtr<ImageAsset>* pAssetPtr = dynamic_cast<AssetPtr<ImageAsset>*>((AssetPtrBase*)(dptr));
  80. // Is the asset pointer the correct type?
  81. if (pAssetPtr == NULL)
  82. {
  83. Con::warnf("(TypeImageAssetPtr) - Failed to set asset Id '%d'.", pFieldValue);
  84. return;
  85. }
  86. // Set asset.
  87. pAssetPtr->setAssetId(pFieldValue);
  88. return;
  89. }
  90. // Warn.
  91. Con::warnf("(TypeImageAssetPtr) - Cannot set multiple args to a single asset.");
  92. }
  93. //-----------------------------------------------------------------------------
  94. // REFACTOR END
  95. //-----------------------------------------------------------------------------
  96. ImplementEnumType(ImageAssetType,
  97. "Type of mesh data available in a shape.\n"
  98. "@ingroup gameObjects")
  99. { ImageAsset::Albedo, "Albedo", "" },
  100. { ImageAsset::Normal, "Normal", "" },
  101. { ImageAsset::ORMConfig, "ORMConfig", "" },
  102. { ImageAsset::GUI, "GUI", "" },
  103. { ImageAsset::Roughness, "Roughness", "" },
  104. { ImageAsset::AO, "AO", "" },
  105. { ImageAsset::Metalness, "Metalness", "" },
  106. { ImageAsset::Glow, "Glow", "" },
  107. { ImageAsset::Particle, "Particle", "" },
  108. { ImageAsset::Decal, "Decal", "" },
  109. { ImageAsset::Cubemap, "Cubemap", "" },
  110. EndImplementEnumType;
  111. const String ImageAsset::mErrCodeStrings[] =
  112. {
  113. "TooManyMips",
  114. "UnKnown"
  115. };
  116. //-----------------------------------------------------------------------------
  117. ImageAsset::ImageAsset() :
  118. mImageFile(StringTable->EmptyString()),
  119. mUseMips(true),
  120. mIsHDRImage(false),
  121. mImageType(Albedo),
  122. mIsNamedTarget(false),
  123. mImageWidth(-1),
  124. mImageHeight(-1),
  125. mImageDepth(-1),
  126. mImageChannels(-1)
  127. {
  128. mLoadedState = AssetErrCode::NotLoaded;
  129. }
  130. //-----------------------------------------------------------------------------
  131. ImageAsset::~ImageAsset()
  132. {
  133. ImageTextureMap::iterator resIter = mResourceMap.begin();
  134. for (; resIter != mResourceMap.end(); ++resIter)
  135. {
  136. resIter->value.free();
  137. }
  138. mResourceMap.clear();
  139. }
  140. void ImageAsset::consoleInit()
  141. {
  142. Parent::consoleInit();
  143. Con::addVariable("$Core::NoImageAssetFallback", TypeString, &smNoImageAssetFallback,
  144. "The assetId of the texture to display when the requested image asset is missing.\n"
  145. "@ingroup GFX\n");
  146. Con::addVariable("$Core::NamedTargetFallback", TypeString, &smNamedTargetAssetFallback,
  147. "The assetId of the texture to display when the requested image asset is named target.\n"
  148. "@ingroup GFX\n");
  149. smNoImageAssetFallback = StringTable->insert(Con::getVariable("$Core::NoImageAssetFallback"));
  150. smNamedTargetAssetFallback = StringTable->insert(Con::getVariable("$Core::NamedTargetFallback"));
  151. }
  152. //-----------------------------------------------------------------------------
  153. void ImageAsset::initPersistFields()
  154. {
  155. docsURL;
  156. // Call parent.
  157. Parent::initPersistFields();
  158. addProtectedField("imageFile", TypeAssetLooseFilePath, Offset(mImageFile, ImageAsset), &setImageFile, &getImageFile, &writeImageFile, "Path to the image file.");
  159. addProtectedField("useMips", TypeBool, Offset(mUseMips, ImageAsset), &setGenMips, &defaultProtectedGetFn, &writeGenMips, "Generate mip maps?");
  160. addProtectedField("isHDRImage", TypeBool, Offset(mIsHDRImage, ImageAsset), &setTextureHDR, &defaultProtectedGetFn, &writeTextureHDR, "HDR Image?");
  161. addField("imageType", TypeImageAssetType, Offset(mImageType, ImageAsset), "What the main use-case for the image is for.");
  162. }
  163. bool ImageAsset::onAdd()
  164. {
  165. // Call Parent.
  166. if (!Parent::onAdd())
  167. return false;
  168. return true;
  169. }
  170. void ImageAsset::onRemove()
  171. {
  172. Torque::FS::RemoveChangeNotification(mImageFile, this, &ImageAsset::_onResourceChanged);
  173. // Call Parent.
  174. Parent::onRemove();
  175. }
  176. U32 ImageAsset::getAssetByFilename(StringTableEntry fileName, AssetPtr<ImageAsset>* imageAsset)
  177. {
  178. AssetQuery query;
  179. S32 foundAssetcount = AssetDatabase.findAssetLooseFile(&query, fileName);
  180. if (foundAssetcount == 0)
  181. {
  182. //Didn't work, so have us fall back to a placeholder asset
  183. imageAsset->setAssetId(ImageAsset::smNoImageAssetFallback);
  184. if (imageAsset->isNull())
  185. {
  186. //Well that's bad, loading the fallback failed.
  187. Con::warnf("ImageAsset::getAssetByFilename - Finding of asset associated with file %s failed with no fallback asset", fileName);
  188. return AssetErrCode::Failed;
  189. }
  190. //handle noshape not being loaded itself
  191. if ((*imageAsset)->mLoadedState == BadFileReference)
  192. {
  193. Con::warnf("ImageAsset::getAssetByFilename - Finding of associated with file %s failed, and fallback asset reported error of Bad File Reference.", fileName);
  194. return AssetErrCode::BadFileReference;
  195. }
  196. Con::warnf("ImageAsset::getAssetByFilename - Finding of associated with file %s failed, utilizing fallback asset", fileName);
  197. (*imageAsset)->mLoadedState = AssetErrCode::UsingFallback;
  198. return AssetErrCode::UsingFallback;
  199. }
  200. else
  201. {
  202. //acquire and bind the asset, and return it out
  203. imageAsset->setAssetId(query.mAssetList[0]);
  204. return (*imageAsset)->load();
  205. }
  206. }
  207. StringTableEntry ImageAsset::getAssetIdByFilename(StringTableEntry fileName)
  208. {
  209. if (fileName == StringTable->EmptyString())
  210. return StringTable->EmptyString();
  211. StringTableEntry imageAssetId = ImageAsset::smNoImageAssetFallback;
  212. AssetQuery query;
  213. S32 foundAssetcount = AssetDatabase.findAssetLooseFile(&query, fileName);
  214. if (foundAssetcount != 0)
  215. {
  216. //acquire and bind the asset, and return it out
  217. imageAssetId = query.mAssetList[0];
  218. }
  219. else
  220. {
  221. foundAssetcount = AssetDatabase.findAssetType(&query, "ImageAsset");
  222. if (foundAssetcount != 0)
  223. {
  224. // loop all image assets and see if we can find one
  225. // using the same image file/named target.
  226. for (auto imgAsset : query.mAssetList)
  227. {
  228. AssetPtr<ImageAsset> temp = imgAsset;
  229. if (temp.notNull())
  230. {
  231. if (temp->getImageFile() == fileName)
  232. {
  233. return imgAsset;
  234. }
  235. else
  236. {
  237. Torque::Path temp1 = temp->getImageFile();
  238. Torque::Path temp2 = fileName;
  239. if (temp1.getPath() == temp2.getPath() && temp1.getFileName() == temp2.getFileName())
  240. {
  241. return imgAsset;
  242. }
  243. }
  244. }
  245. }
  246. }
  247. else
  248. {
  249. AssetPtr<ImageAsset> imageAsset = imageAssetId; //ensures the fallback is loaded
  250. }
  251. }
  252. return imageAssetId;
  253. }
  254. U32 ImageAsset::getAssetById(StringTableEntry assetId, AssetPtr<ImageAsset>* imageAsset)
  255. {
  256. (*imageAsset) = assetId;
  257. if (imageAsset->notNull())
  258. {
  259. return (*imageAsset)->load();
  260. }
  261. else
  262. {
  263. if (imageAsset->isNull())
  264. {
  265. return AssetErrCode::Failed;
  266. }
  267. //handle fallback not being loaded itself
  268. if ((*imageAsset)->mLoadedState == BadFileReference)
  269. {
  270. Con::warnf("ImageAsset::getAssetById - Finding of asset with id %s failed, and fallback asset reported error of Bad File Reference.", assetId);
  271. return AssetErrCode::BadFileReference;
  272. }
  273. Con::warnf("ImageAsset::getAssetById - Finding of asset with id %s failed, utilizing fallback asset", assetId);
  274. (*imageAsset)->mLoadedState = AssetErrCode::UsingFallback;
  275. return AssetErrCode::UsingFallback;
  276. }
  277. }
  278. void ImageAsset::initializeAsset(void)
  279. {
  280. // Call parent.
  281. Parent::initializeAsset();
  282. // Ensure the image-file is expanded.
  283. if (isNamedTarget())
  284. return;
  285. mImageFile = expandAssetFilePath(mImageFile);
  286. if (getOwned())
  287. Torque::FS::AddChangeNotification(mImageFile, this, &ImageAsset::_onResourceChanged);
  288. populateImage();
  289. }
  290. void ImageAsset::onAssetRefresh(void)
  291. {
  292. // Ignore if not yet added to the sim.
  293. if (!isProperlyAdded())
  294. return;
  295. // Call parent.
  296. Parent::onAssetRefresh();
  297. populateImage();
  298. }
  299. //------------------------------------------------------------------------------
  300. void ImageAsset::copyTo(SimObject* object)
  301. {
  302. // Call to parent.
  303. Parent::copyTo(object);
  304. ImageAsset* pAsset = static_cast<ImageAsset*>(object);
  305. // Sanity!
  306. AssertFatal(pAsset != NULL, "ImageAsset::copyTo() - Object is not the correct type.");
  307. pAsset->setImageFile(getImageFile());
  308. pAsset->setGenMips(getGenMips());
  309. pAsset->setTextureHDR(getTextureHDR());
  310. }
  311. void ImageAsset::setImageFile(StringTableEntry pImageFile)
  312. {
  313. // Sanity!
  314. AssertFatal(pImageFile != NULL, "Cannot use a NULL image file.");
  315. pImageFile = StringTable->insert(pImageFile);
  316. if (pImageFile == mImageFile)
  317. return;
  318. Torque::FS::RemoveChangeNotification(mImageFile, this, &ImageAsset::_onResourceChanged);
  319. if (String(pImageFile).startsWith("#") || String(pImageFile).startsWith("$"))
  320. {
  321. mImageFile = StringTable->insert(pImageFile);
  322. mIsNamedTarget = true;
  323. refreshAsset();
  324. return;
  325. }
  326. mImageFile = getOwned() ? expandAssetFilePath(pImageFile) : StringTable->insert(pImageFile);
  327. refreshAsset();
  328. }
  329. void ImageAsset::setGenMips(const bool pGenMips)
  330. {
  331. if (pGenMips == mUseMips)
  332. return;
  333. mUseMips = pGenMips;
  334. refreshAsset();
  335. }
  336. void ImageAsset::setTextureHDR(const bool pIsHDR)
  337. {
  338. if (pIsHDR == mIsHDRImage)
  339. return;
  340. mIsHDRImage = pIsHDR;
  341. refreshAsset();
  342. }
  343. U32 ImageAsset::load()
  344. {
  345. if (mLoadedState == Ok)
  346. return mLoadedState;
  347. if (!Torque::FS::IsFile(mImageFile))
  348. {
  349. if (isNamedTarget())
  350. {
  351. mLoadedState = Ok;
  352. return mLoadedState;
  353. }
  354. if (mLoadedState != AssetErrCode::BadFileReference && mLoadedState != AssetErrCode::Failed)
  355. Con::errorf("ImageAsset::initializeAsset: Attempted to load file %s but it was not valid!", mImageFile);
  356. mLoadedState = BadFileReference;
  357. return mLoadedState;
  358. }
  359. else
  360. {
  361. mLoadedState = Ok;
  362. }
  363. return mLoadedState;
  364. }
  365. GFXTexHandle ImageAsset::getTexture(GFXTextureProfile* requestedProfile)
  366. {
  367. if (mLoadedState == Ok && mResourceMap.contains(requestedProfile))
  368. {
  369. return mResourceMap.find(requestedProfile)->value;
  370. }
  371. else
  372. {
  373. //try a reload
  374. load();
  375. }
  376. if (isNamedTarget())
  377. {
  378. GFXTexHandle tex;
  379. AssetPtr<ImageAsset> fallbackAsset;
  380. ImageAsset::getAssetById(smNamedTargetAssetFallback, &fallbackAsset);
  381. if (getNamedTarget().isValid())
  382. {
  383. tex = getNamedTarget()->getTexture();
  384. if (tex.isNull())
  385. {
  386. return fallbackAsset->getTexture(requestedProfile);
  387. }
  388. mResourceMap.insert(requestedProfile, tex);
  389. return tex;
  390. }
  391. else
  392. {
  393. return fallbackAsset->getTexture(requestedProfile);
  394. }
  395. }
  396. if (mLoadedState == Ok)
  397. {
  398. //If we don't have an existing map case to the requested format, we'll just create it and insert it in
  399. GFXTexHandle newTex;
  400. newTex.set(mImageFile, requestedProfile, avar("%s %s() - mTextureObject (line %d)", mImageFile, __FUNCTION__, __LINE__));
  401. if (newTex)
  402. {
  403. mResourceMap.insert(requestedProfile, newTex);
  404. return newTex;
  405. }
  406. }
  407. return nullptr;
  408. }
  409. const char* ImageAsset::getImageTypeNameFromType(ImageAsset::ImageTypes type)
  410. {
  411. // must match ImageTypes order
  412. static const char* _names[] = {
  413. "Albedo",
  414. "Normal",
  415. "ORMConfig",
  416. "GUI",
  417. "Roughness",
  418. "AO",
  419. "Metalness",
  420. "Glow",
  421. "Particle",
  422. "Decal",
  423. "Cubemap"
  424. };
  425. if (type < 0 || type >= ImageTypeCount)
  426. {
  427. Con::errorf("ImageAsset::getAdapterNameFromType - Invalid ImageType, defaulting to Albedo");
  428. return _names[Albedo];
  429. }
  430. return _names[type];
  431. }
  432. ImageAsset::ImageTypes ImageAsset::getImageTypeFromName(StringTableEntry name)
  433. {
  434. if (dStrIsEmpty(name))
  435. {
  436. return (ImageTypes)Albedo;
  437. }
  438. S32 ret = -1;
  439. for (S32 i = 0; i < ImageTypeCount; i++)
  440. {
  441. if (!dStricmp(getImageTypeNameFromType((ImageTypes)i), name))
  442. ret = i;
  443. }
  444. if (ret == -1)
  445. {
  446. Con::errorf("ImageAsset::getImageTypeFromName - Invalid ImageType name, defaulting to Albedo");
  447. ret = Albedo;
  448. }
  449. return (ImageTypes)ret;
  450. }
  451. void ImageAsset::_onResourceChanged(const Torque::Path& path)
  452. {
  453. if (path != Torque::Path(mImageFile))
  454. return;
  455. refreshAsset();
  456. }
  457. void ImageAsset::onTamlPreWrite(void)
  458. {
  459. // Call parent.
  460. Parent::onTamlPreWrite();
  461. if (isNamedTarget())
  462. return;
  463. // Ensure the image-file is collapsed.
  464. mImageFile = collapseAssetFilePath(mImageFile);
  465. }
  466. void ImageAsset::onTamlPostWrite(void)
  467. {
  468. // Call parent.
  469. Parent::onTamlPostWrite();
  470. if (isNamedTarget())
  471. return;
  472. // Ensure the image-file is expanded.
  473. mImageFile = expandAssetFilePath(mImageFile);
  474. }
  475. void ImageAsset::onTamlCustomWrite(TamlCustomNodes& customNodes)
  476. {
  477. // Debug Profiling.
  478. PROFILE_SCOPE(ImageAsset_OnTamlCustomWrite);
  479. // Call parent.
  480. Parent::onTamlCustomWrite(customNodes);
  481. TamlCustomNode* pImageMetaData = customNodes.addNode(StringTable->insert("ImageMetadata"));
  482. TamlCustomNode* pImageInfoNode = pImageMetaData->addNode(StringTable->insert("ImageInfo"));
  483. pImageInfoNode->addField(StringTable->insert("ImageWidth"), mImageWidth);
  484. pImageInfoNode->addField(StringTable->insert("ImageHeight"), mImageHeight);
  485. pImageInfoNode->addField(StringTable->insert("ImageDepth"), mImageDepth);
  486. }
  487. void ImageAsset::onTamlCustomRead(const TamlCustomNodes& customNodes)
  488. {
  489. // Debug Profiling.
  490. PROFILE_SCOPE(ImageAsset_OnTamlCustomRead);
  491. // Call parent.
  492. Parent::onTamlCustomRead(customNodes);
  493. const TamlCustomNode* pImageMetaDataNode = customNodes.findNode(StringTable->insert("ImageMetadata"));
  494. if (pImageMetaDataNode != NULL)
  495. {
  496. const TamlCustomNode* pImageInfoNode = pImageMetaDataNode->findNode(StringTable->insert("ImageInfo"));
  497. // Fetch fields.
  498. const TamlCustomFieldVector& fields = pImageInfoNode->getFields();
  499. // Iterate property fields.
  500. for (TamlCustomFieldVector::const_iterator fieldItr = fields.begin(); fieldItr != fields.end(); ++fieldItr)
  501. {
  502. // Fetch field.
  503. const TamlCustomField* pField = *fieldItr;
  504. // Fetch field name.
  505. StringTableEntry fieldName = pField->getFieldName();
  506. if (fieldName == StringTable->insert("ImageWidth"))
  507. {
  508. pField->getFieldValue(mImageWidth);
  509. }
  510. else if (fieldName == StringTable->insert("ImageHeight"))
  511. {
  512. pField->getFieldValue(mImageHeight);
  513. }
  514. else if (fieldName == StringTable->insert("ImageDepth"))
  515. {
  516. pField->getFieldValue(mImageDepth);
  517. }
  518. else
  519. {
  520. // Unknown name so warn.
  521. Con::warnf("ImageAsset::onTamlCustomRead() - Encountered an unknown custom field name of '%s'.", fieldName);
  522. continue;
  523. }
  524. }
  525. }
  526. }
  527. void ImageAsset::populateImage(void)
  528. {
  529. if (Torque::FS::IsFile(mImageFile))
  530. {
  531. if (dStrEndsWith(mImageFile, ".dds"))
  532. {
  533. DDSFile* tempFile = new DDSFile();
  534. FileStream* ddsFs;
  535. if ((ddsFs = FileStream::createAndOpen(mImageFile, Torque::FS::File::Read)) == NULL)
  536. {
  537. Con::errorf("ImageAsset::setImageFile Failed to open ddsfile: %s", mImageFile);
  538. }
  539. if (!tempFile->readHeader(*ddsFs))
  540. {
  541. Con::errorf("ImageAsset::setImageFile Failed to read header of ddsfile: %s", mImageFile);
  542. }
  543. else
  544. {
  545. mImageWidth = tempFile->mWidth;
  546. mImageHeight = tempFile->mHeight;
  547. }
  548. ddsFs->close();
  549. delete tempFile;
  550. }
  551. else
  552. {
  553. if (!stbi_info(mImageFile, &mImageWidth, &mImageHeight, &mImageChannels))
  554. {
  555. StringTableEntry stbErr = stbi_failure_reason();
  556. if (stbErr == StringTable->EmptyString())
  557. stbErr = "ImageAsset::Unkown Error!";
  558. Con::errorf("ImageAsset::setImageFile STB Get file info failed: %s", stbErr);
  559. }
  560. }
  561. // we only support 2d textures..... for now ;)
  562. mImageDepth = 1;
  563. }
  564. }
  565. const char* ImageAsset::getImageInfo()
  566. {
  567. if (isAssetValid())
  568. {
  569. static const U32 bufSize = 2048;
  570. char* returnBuffer = Con::getReturnBuffer(bufSize);
  571. GFXTexHandle newTex = TEXMGR->createTexture(mImageFile, &GFXStaticTextureSRGBProfile);
  572. if (newTex)
  573. {
  574. dSprintf(returnBuffer, bufSize, "%s %d %d %d", GFXStringTextureFormat[newTex->getFormat()], newTex->getHeight(), newTex->getWidth(), newTex->getDepth());
  575. newTex = nullptr;
  576. }
  577. else
  578. {
  579. dSprintf(returnBuffer, bufSize, "ImageAsset::getImageInfo() - Failed to get image info for %s", getAssetId());
  580. }
  581. return returnBuffer;
  582. }
  583. return "";
  584. }
  585. DefineEngineMethod(ImageAsset, getImagePath, const char*, (), ,
  586. "Gets the image filepath of this asset.\n"
  587. "@return File path of the image file.")
  588. {
  589. return object->getImageFile();
  590. }
  591. DefineEngineMethod(ImageAsset, getImageInfo, const char*, (), ,
  592. "Gets the info and properties of the image.\n"
  593. "@return The info/properties of the image.")
  594. {
  595. return object->getImageInfo();
  596. }
  597. DefineEngineMethod(ImageAsset, isNamedTarget, bool, (), ,
  598. "Gets whether this image is a named target.\n"
  599. "@return bool for isNamedTarget.")
  600. {
  601. return object->isNamedTarget();
  602. }
  603. #ifdef TORQUE_TOOLS
  604. DefineEngineStaticMethod(ImageAsset, getAssetIdByFilename, const char*, (const char* filePath), (""),
  605. "Queries the Asset Database to see if any asset exists that is associated with the provided file path.\n"
  606. "@return The AssetId of the associated asset, if any.")
  607. {
  608. return ImageAsset::getAssetIdByFilename(StringTable->insert(filePath));
  609. }
  610. //-----------------------------------------------------------------------------
  611. // GuiInspectorTypeAssetId
  612. //-----------------------------------------------------------------------------
  613. IMPLEMENT_CONOBJECT(GuiInspectorTypeImageAssetPtr);
  614. ConsoleDocClass(GuiInspectorTypeImageAssetPtr,
  615. "@brief Inspector field type for Shapes\n\n"
  616. "Editor use only.\n\n"
  617. "@internal"
  618. );
  619. void GuiInspectorTypeImageAssetPtr::consoleInit()
  620. {
  621. Parent::consoleInit();
  622. ConsoleBaseType::getType(TypeImageAssetPtr)->setInspectorFieldType("GuiInspectorTypeImageAssetPtr");
  623. }
  624. GuiControl* GuiInspectorTypeImageAssetPtr::constructEditControl()
  625. {
  626. // Create base filename edit controls
  627. GuiControl* retCtrl = Parent::constructEditControl();
  628. if (retCtrl == NULL)
  629. return retCtrl;
  630. retCtrl->getRenderTooltipDelegate().bind(this, &GuiInspectorTypeImageAssetPtr::renderTooltip);
  631. // Change filespec
  632. char szBuffer[512];
  633. const char* previewImage;
  634. if (mInspector->getInspectObject() != nullptr)
  635. {
  636. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ImageAsset\", \"AssetBrowser.changeAsset\", %s);",
  637. getIdString());
  638. mBrowseButton->setField("Command", szBuffer);
  639. setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
  640. previewImage = getData();
  641. }
  642. else
  643. {
  644. //if we don't have a target object, we'll be manipulating the desination value directly
  645. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ImageAsset\", \"AssetBrowser.changeAsset\", %s, \"%s\");",
  646. mInspector->getIdString(), mVariableName);
  647. mBrowseButton->setField("Command", szBuffer);
  648. previewImage = Con::getVariable(mVariableName);
  649. }
  650. mLabel = new GuiTextCtrl();
  651. mLabel->registerObject();
  652. mLabel->setControlProfile(mProfile);
  653. mLabel->setText(mCaption);
  654. addObject(mLabel);
  655. //
  656. GuiTextEditCtrl* editTextCtrl = static_cast<GuiTextEditCtrl*>(retCtrl);
  657. GuiControlProfile* toolEditProfile;
  658. if (Sim::findObject("ToolsGuiTextEditProfile", toolEditProfile))
  659. editTextCtrl->setControlProfile(toolEditProfile);
  660. editTextCtrl->setPlaceholderText("(None)");
  661. GuiControlProfile* toolDefaultProfile = nullptr;
  662. Sim::findObject("ToolsGuiDefaultProfile", toolDefaultProfile);
  663. //
  664. mPreviewImage = new GuiBitmapCtrl();
  665. mPreviewImage->registerObject();
  666. if (toolDefaultProfile)
  667. mPreviewImage->setControlProfile(toolDefaultProfile);
  668. updatePreviewImage();
  669. addObject(mPreviewImage);
  670. //
  671. mPreviewBorderButton = new GuiBitmapButtonCtrl();
  672. mPreviewBorderButton->registerObject();
  673. if (toolDefaultProfile)
  674. mPreviewBorderButton->setControlProfile(toolDefaultProfile);
  675. mPreviewBorderButton->_setBitmap(StringTable->insert("ToolsModule:cubemapBtnBorder_n_image"));
  676. mPreviewBorderButton->setField("Command", szBuffer); //clicking the preview does the same thing as the edit button, for simplicity
  677. addObject(mPreviewBorderButton);
  678. //
  679. // Create "Open in Editor" button
  680. mEditButton = new GuiBitmapButtonCtrl();
  681. if (mInspector->getInspectObject() != nullptr)
  682. dSprintf(szBuffer, sizeof(szBuffer), "%d.apply(\"\");", getId());
  683. else
  684. dSprintf(szBuffer, sizeof(szBuffer), "%s = \"\";", mVariableName);
  685. mEditButton->setField("Command", szBuffer);
  686. mEditButton->setBitmap(StringTable->insert("ToolsModule:delete_n_image"));
  687. mEditButton->setSizing(horizResizeRight, vertResizeAspectBottom);
  688. mEditButton->setDataField(StringTable->insert("Profile"), NULL, "ToolsGuiButtonProfile");
  689. mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
  690. mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
  691. mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Clear this ImageAsset");
  692. mEditButton->registerObject();
  693. addObject(mEditButton);
  694. //
  695. mUseHeightOverride = true;
  696. mHeightOverride = 72;
  697. return retCtrl;
  698. }
  699. bool GuiInspectorTypeImageAssetPtr::updateRects()
  700. {
  701. S32 rowSize = 18;
  702. S32 dividerPos, dividerMargin;
  703. mInspector->getDivider(dividerPos, dividerMargin);
  704. Point2I fieldExtent = getExtent();
  705. Point2I fieldPos = getPosition();
  706. mEditCtrlRect.set(0, 0, fieldExtent.x, fieldExtent.y);
  707. mLabel->resize(Point2I(mProfile->mTextOffset.x, 0), Point2I(fieldExtent.x, rowSize));
  708. RectI previewRect = RectI(Point2I(mProfile->mTextOffset.x, rowSize), Point2I(50, 50));
  709. mPreviewBorderButton->resize(previewRect.point, previewRect.extent);
  710. mPreviewImage->resize(previewRect.point, previewRect.extent);
  711. S32 editPos = previewRect.point.x + previewRect.extent.x + 10;
  712. mEdit->resize(Point2I(editPos, rowSize * 1.5), Point2I(fieldExtent.x - editPos - 5 - rowSize, rowSize));
  713. mEditButton->resize(Point2I(mEdit->getPosition().x + mEdit->getExtent().x, mEdit->getPosition().y), Point2I(rowSize, rowSize));
  714. mBrowseButton->setHidden(true);
  715. return true;
  716. }
  717. bool GuiInspectorTypeImageAssetPtr::renderTooltip(const Point2I& hoverPos, const Point2I& cursorPos, const char* tipText)
  718. {
  719. if (!mAwake)
  720. return false;
  721. GuiCanvas* root = getRoot();
  722. if (!root)
  723. return false;
  724. AssetPtr<ImageAsset> imgAsset;
  725. U32 assetState = ImageAsset::getAssetById(getData(), &imgAsset);
  726. if (imgAsset == NULL || assetState == ImageAsset::Failed)
  727. return false;
  728. StringTableEntry filename = imgAsset->getImageFile();
  729. if (!filename || !filename[0])
  730. return false;
  731. StringTableEntry previewFilename = filename;
  732. if (Con::isFunction("getAssetPreviewImage"))
  733. {
  734. ConsoleValue consoleRet = Con::executef("getAssetPreviewImage", filename);
  735. previewFilename = StringTable->insert(consoleRet.getString());
  736. if (AssetDatabase.isDeclaredAsset(previewFilename))
  737. {
  738. ImageAsset* previewAsset = AssetDatabase.acquireAsset<ImageAsset>(previewFilename);
  739. previewFilename = previewAsset->getImageFile();
  740. }
  741. }
  742. GFXTexHandle texture(previewFilename, &GFXStaticTextureSRGBProfile, avar("%s() - tooltip texture (line %d)", __FUNCTION__, __LINE__));
  743. if (texture.isNull())
  744. return false;
  745. // Render image at a reasonable screen size while
  746. // keeping its aspect ratio...
  747. Point2I screensize = getRoot()->getWindowSize();
  748. Point2I offset = hoverPos;
  749. Point2I tipBounds;
  750. U32 texWidth = texture.getWidth();
  751. U32 texHeight = texture.getHeight();
  752. F32 aspect = (F32)texHeight / (F32)texWidth;
  753. const F32 newWidth = 150.0f;
  754. F32 newHeight = aspect * newWidth;
  755. // Offset below cursor image
  756. offset.y += 20; // TODO: Attempt to fix?: root->getCursorExtent().y;
  757. tipBounds.x = newWidth;
  758. tipBounds.y = newHeight;
  759. // Make sure all of the tooltip will be rendered width the app window,
  760. // 5 is given as a buffer against the edge
  761. if (screensize.x < offset.x + tipBounds.x + 5)
  762. offset.x = screensize.x - tipBounds.x - 5;
  763. if (screensize.y < offset.y + tipBounds.y + 5)
  764. offset.y = hoverPos.y - tipBounds.y - 5;
  765. RectI oldClip = GFX->getClipRect();
  766. RectI rect(offset, tipBounds);
  767. GFX->setClipRect(rect);
  768. GFXDrawUtil* drawer = GFX->getDrawUtil();
  769. drawer->clearBitmapModulation();
  770. GFX->getDrawUtil()->drawBitmapStretch(texture, rect);
  771. GFX->setClipRect(oldClip);
  772. return true;
  773. }
  774. void GuiInspectorTypeImageAssetPtr::updateValue()
  775. {
  776. Parent::updateValue();
  777. updatePreviewImage();
  778. }
  779. void GuiInspectorTypeImageAssetPtr::updatePreviewImage()
  780. {
  781. const char* previewImage;
  782. if (mInspector->getInspectObject() != nullptr)
  783. previewImage = getData();
  784. else
  785. previewImage = Con::getVariable(mVariableName);
  786. //if what we're working with isn't even a valid asset, don't present like we found a good one
  787. if (!AssetDatabase.isDeclaredAsset(previewImage))
  788. {
  789. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:unknownImage_image"));
  790. return;
  791. }
  792. String imgPreviewAssetId = String(previewImage) + "_PreviewImage";
  793. imgPreviewAssetId.replace(":", "_");
  794. imgPreviewAssetId = "ToolsModule:" + imgPreviewAssetId;
  795. if (AssetDatabase.isDeclaredAsset(imgPreviewAssetId.c_str()))
  796. {
  797. mPreviewImage->setBitmap(StringTable->insert(imgPreviewAssetId.c_str()));
  798. }
  799. else
  800. {
  801. if (AssetDatabase.isDeclaredAsset(previewImage))
  802. {
  803. mPreviewImage->_setBitmap(previewImage);
  804. }
  805. }
  806. if (mPreviewImage->getBitmapAsset().isNull())
  807. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  808. }
  809. void GuiInspectorTypeImageAssetPtr::setPreviewImage(StringTableEntry assetId)
  810. {
  811. //if what we're working with isn't even a valid asset, don't present like we found a good one
  812. if (!AssetDatabase.isDeclaredAsset(assetId))
  813. {
  814. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:unknownImage_image"));
  815. return;
  816. }
  817. String imgPreviewAssetId = String(assetId) + "_PreviewImage";
  818. imgPreviewAssetId.replace(":", "_");
  819. imgPreviewAssetId = "ToolsModule:" + imgPreviewAssetId;
  820. if (AssetDatabase.isDeclaredAsset(imgPreviewAssetId.c_str()))
  821. {
  822. mPreviewImage->setBitmap(StringTable->insert(imgPreviewAssetId.c_str()));
  823. }
  824. else
  825. {
  826. if (AssetDatabase.isDeclaredAsset(assetId))
  827. {
  828. mPreviewImage->_setBitmap(assetId);
  829. }
  830. }
  831. if (mPreviewImage->getBitmapAsset().isNull())
  832. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  833. }
  834. void GuiInspectorTypeImageAssetPtr::setCaption(StringTableEntry caption)
  835. {
  836. mCaption = caption;
  837. mLabel->setText(mCaption);
  838. }
  839. DefineEngineMethod(GuiInspectorTypeImageAssetPtr, setCaption, void, (String newCaption), , "() - Sets the caption of the field.")
  840. {
  841. object->setCaption(StringTable->insert(newCaption.c_str()));
  842. }
  843. DefineEngineMethod(GuiInspectorTypeImageAssetPtr, setIsDeleteBtnVisible, void, (bool isVisible), (false), "() - Sets if the delete/clear button is visible for the field")
  844. {
  845. object->setIsDeleteBtnVisible(isVisible);
  846. }
  847. #endif