ImageAsset.cpp 28 KB

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