ImageAsset.cpp 26 KB

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