AtlasBuilderWorker.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "AtlasBuilderWorker.h"
  9. #include <AzCore/Math/MathIntrinsics.h>
  10. #include <AzCore/std/string/conversions.h>
  11. #include <AzCore/Serialization/Utils.h>
  12. #include <AzCore/Serialization/SerializeContext.h>
  13. #include <AzCore/std/sort.h>
  14. #include <AzCore/IO/FileIO.h>
  15. #include <AzCore/IO/SystemFile.h>
  16. #include <AzCore/std/string/regex.h>
  17. #include <AzFramework/StringFunc/StringFunc.h>
  18. #include <AzFramework/API/ApplicationAPI.h>
  19. #include <AzFramework/IO/LocalFileIO.h>
  20. #include <AzToolsFramework/API/EditorAssetSystemAPI.h>
  21. #include <Atom/ImageProcessing/ImageObject.h>
  22. #include <Atom/ImageProcessing/ImageProcessingBus.h>
  23. #include <Atom/ImageProcessing/PixelFormats.h>
  24. #include <Atom/RPI.Reflect/Image/StreamingImageAsset.h>
  25. #include <qimage.h>
  26. #include <QString>
  27. #include <QDir>
  28. #include <qfileinfo.h>
  29. namespace TextureAtlasBuilder
  30. {
  31. //! Used for sorting ImageDimensions
  32. bool operator<(ImageDimension a, ImageDimension b);
  33. //! Used to expose the ImageDimension in a pair to AZStd::Sort
  34. bool operator<(IndexImageDimension a, IndexImageDimension b);
  35. //! Returns true if two coordinate sets overlap
  36. bool Collides(AtlasCoordinates a, AtlasCoordinates b);
  37. //! Returns true if item collides with any object in list
  38. bool Collides(AtlasCoordinates item, AZStd::vector<AtlasCoordinates> list);
  39. //! Returns the portion of the second item that overlaps with the first
  40. AtlasCoordinates GetOverlap(AtlasCoordinates a, AtlasCoordinates b);
  41. //! Performs an operation that copies a pixel to the output
  42. void SetPixels(AZ::u8* dest, const AZ::u8* source, int destBytes);
  43. //! Checks if we can insert an image into a slot
  44. bool CanInsert(AtlasCoordinates slot, ImageDimension image, int padding, int farRight, int farBot);
  45. //! Adds the necessary padding to an Atlas Coordinate
  46. void AddPadding(AtlasCoordinates& slot, int padding, int farRight, int farBot);
  47. //! Counts leading zeros
  48. uint32_t CountLeadingZeros32(uint32_t x)
  49. {
  50. return x == 0 ? 32 : az_clz_u32(x);
  51. }
  52. //! Integer log2
  53. uint32_t IntegerLog2(uint32_t x)
  54. {
  55. return 31 - CountLeadingZeros32(x);
  56. }
  57. bool IsFolderPath(const AZStd::string& path)
  58. {
  59. bool hasExtension = AzFramework::StringFunc::Path::HasExtension(path.c_str());
  60. return !hasExtension;
  61. }
  62. bool HasTrailingSlash(const AZStd::string& path)
  63. {
  64. size_t pathLength = path.size();
  65. return (pathLength > 0 && (path.at(pathLength - 1) == '/' || path.at(pathLength - 1) == '\\'));
  66. }
  67. bool GetCanonicalPathFromFullPath(const AZStd::string& fullPath, AZStd::string& canonicalPathOut)
  68. {
  69. AZStd::string curPath = fullPath;
  70. // We avoid using LocalFileIO::ConvertToAbsolutePath for this because it does not behave consistently across platforms.
  71. // On non-Windows platforms, LocalFileIO::ConvertToAbsolutePath requires that the path exist, otherwise the path
  72. // remains unchanged. This won't work for paths that include wildcards.
  73. // Also, on non-Windows platforms, if the path is already a full path, it will remain unchanged even if it contains
  74. // "./" or "../" somewhere other than the beginning of the path
  75. // Normalize path
  76. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePathKeepCase, curPath);
  77. const AZStd::string slash("/");
  78. // Replace "/./" occurrances with "/"
  79. const AZStd::string slashDotSlash("/./");
  80. bool replaced = false;
  81. do
  82. {
  83. // Replace first occurrance
  84. replaced = AzFramework::StringFunc::Replace(curPath, slashDotSlash.c_str(), slash.c_str(), false, true, false);
  85. } while (replaced);
  86. // Replace "/xxx/../" with "/"
  87. const AZStd::regex slashDotDotSlash("\\/[^/.]*\\/\\.\\.\\/");
  88. AZStd::string prevPath;
  89. while (prevPath != curPath)
  90. {
  91. prevPath = curPath;
  92. curPath = AZStd::regex_replace(prevPath, slashDotDotSlash, slash, AZStd::regex_constants::match_flag_type::format_first_only);
  93. }
  94. if ((curPath.find("..") != AZStd::string::npos) || (curPath.find("./") != AZStd::string::npos) || (curPath.find("/.") != AZStd::string::npos))
  95. {
  96. return false;
  97. }
  98. canonicalPathOut = curPath;
  99. return true;
  100. }
  101. bool ResolveRelativePath(const AZStd::string& relativePath, const AZStd::string& watchDirectory, AZStd::string& resolvedFullPathOut)
  102. {
  103. bool resolved = false;
  104. if (relativePath[0] == '@')
  105. {
  106. // Get full path by resolving the alias at the front of the path
  107. char resolvedPath[AZ_MAX_PATH_LEN];
  108. AZ::IO::FileIOBase::GetInstance()->ResolvePath(relativePath.c_str(), resolvedPath, AZ_MAX_PATH_LEN);
  109. resolvedFullPathOut = resolvedPath;
  110. resolved = true;
  111. }
  112. else
  113. {
  114. // Get full path by appending the relative path to the watch directory
  115. AZStd::string fullPath = watchDirectory;
  116. fullPath.append("/");
  117. fullPath.append(relativePath);
  118. // Resolve to canonical path (remove "./" and "../")
  119. resolved = GetCanonicalPathFromFullPath(fullPath, resolvedFullPathOut);
  120. }
  121. return resolved;
  122. }
  123. bool GetAbsoluteSourcePathFromRelativePath(const AZStd::string& relativeSourcePath, AZStd::string& absoluteSourcePathOut)
  124. {
  125. bool result = false;
  126. AZ::Data::AssetInfo info;
  127. AZStd::string watchFolder;
  128. AzToolsFramework::AssetSystemRequestBus::BroadcastResult(result, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, relativeSourcePath.c_str(), info, watchFolder);
  129. if (result)
  130. {
  131. absoluteSourcePathOut = AZStd::string::format("%s/%s", watchFolder.c_str(), info.m_relativePath.c_str());
  132. // Normalize path
  133. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePathKeepCase, absoluteSourcePathOut);
  134. }
  135. return result;
  136. }
  137. // Reflect the input parameters
  138. void AtlasBuilderInput::Reflect(AZ::ReflectContext* context)
  139. {
  140. if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context))
  141. {
  142. serialize->Class<AtlasBuilderInput>()
  143. ->Version(1)
  144. ->Field("Force Square", &AtlasBuilderInput::m_forceSquare)
  145. ->Field("Force Power of Two", &AtlasBuilderInput::m_forcePowerOf2)
  146. ->Field("Include White Texture", &AtlasBuilderInput::m_includeWhiteTexture)
  147. ->Field("Maximum Dimension", &AtlasBuilderInput::m_maxDimension)
  148. ->Field("Padding", &AtlasBuilderInput::m_padding)
  149. ->Field("UnusedColor", &AtlasBuilderInput::m_unusedColor)
  150. ->Field("PresetName", &AtlasBuilderInput::m_presetName)
  151. ->Field("Textures to Add", &AtlasBuilderInput::m_filePaths);
  152. }
  153. }
  154. // Supports a custom parser format
  155. AtlasBuilderInput AtlasBuilderInput::ReadFromFile(const AZStd::string& path, const AZStd::string& directory, bool& valid)
  156. {
  157. // Open the file
  158. AZ::IO::FileIOBase* input = AZ::IO::FileIOBase::GetInstance();
  159. AZ::IO::HandleType handle;
  160. input->Open(path.c_str(), AZ::IO::OpenMode::ModeRead, handle);
  161. // Read the file
  162. AZ::u64 size;
  163. input->Size(handle, size);
  164. char* buffer = new char[size + 1];
  165. input->Read(handle, buffer, size);
  166. buffer[size] = 0;
  167. // Close the file
  168. input->Close(handle);
  169. // Prepare the output
  170. AtlasBuilderInput data;
  171. // Parse the input into lines
  172. AZStd::vector<AZStd::string> lines;
  173. AzFramework::StringFunc::Tokenize(buffer, lines, "\n\t");
  174. delete[] buffer;
  175. // Parse the individual lines
  176. for (auto line : lines)
  177. {
  178. line = AzFramework::StringFunc::TrimWhiteSpace(line, true, true);
  179. // Check for comments and empty lines
  180. if ((line.length() >= 2 && line[0] == '/' && line[1] == '/') || line.length() < 1)
  181. {
  182. continue;
  183. }
  184. else if (line.find('=') != -1)
  185. {
  186. AZStd::vector<AZStd::string> args;
  187. AzFramework::StringFunc::Tokenize(line.c_str(), args, '=', true, true);
  188. if (args.size() > 2)
  189. {
  190. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to parse line: Excessive '=' symbols were found: \"%s\"", line.c_str()).c_str());
  191. valid = false;
  192. }
  193. // Trim whitespace
  194. args[0] = AzFramework::StringFunc::TrimWhiteSpace(args[0], true, true);
  195. args[1] = AzFramework::StringFunc::TrimWhiteSpace(args[1], true, true);
  196. // No case sensitivity for property names
  197. AZStd::to_lower(args[0].begin(), args[0].end());
  198. // Keep track of if the value is rejected
  199. bool accepted = false;
  200. if (args[0] == "square")
  201. {
  202. accepted = AzFramework::StringFunc::LooksLikeBool(args[1].c_str());
  203. if (accepted)
  204. {
  205. data.m_forceSquare = AzFramework::StringFunc::ToBool(args[1].c_str());
  206. }
  207. }
  208. else if (args[0] == "poweroftwo")
  209. {
  210. accepted = AzFramework::StringFunc::LooksLikeBool(args[1].c_str());
  211. if (accepted)
  212. {
  213. data.m_forcePowerOf2 = AzFramework::StringFunc::ToBool(args[1].c_str());
  214. }
  215. }
  216. else if (args[0] == "whitetexture")
  217. {
  218. accepted = AzFramework::StringFunc::LooksLikeBool(args[1].c_str());
  219. if (accepted)
  220. {
  221. data.m_includeWhiteTexture = AzFramework::StringFunc::ToBool(args[1].c_str());
  222. }
  223. }
  224. else if (args[0] == "maxdimension")
  225. {
  226. accepted = AzFramework::StringFunc::LooksLikeInt(args[1].c_str());
  227. if (accepted)
  228. {
  229. data.m_maxDimension = AzFramework::StringFunc::ToInt(args[1].c_str());
  230. }
  231. }
  232. else if (args[0] == "padding")
  233. {
  234. accepted = AzFramework::StringFunc::LooksLikeInt(args[1].c_str());
  235. if (accepted)
  236. {
  237. data.m_padding = AzFramework::StringFunc::ToInt(args[1].c_str());
  238. }
  239. }
  240. else if (args[0] == "unusedcolor")
  241. {
  242. accepted = args[1].at(0) == '#' && args[1].length() == 9;
  243. if (accepted)
  244. {
  245. AZStd::string color = AZStd::string::format("%s%s%s%s", args[1].substr(7).c_str(), args[1].substr(5, 2).c_str(),
  246. args[1].substr(3, 2).c_str(), args[1].substr(1, 2).c_str());
  247. data.m_unusedColor.FromU32(static_cast<AZ::u32>(AZStd::stoul(color, nullptr, 16)));
  248. }
  249. }
  250. else if (args[0] == "presetname")
  251. {
  252. accepted = true;
  253. data.m_presetName = args[1];
  254. }
  255. else
  256. {
  257. // Supress accepted error because this error superceeds it
  258. accepted = true;
  259. valid = false;
  260. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to parse line: Unrecognized property: \"%s\"", args[0].c_str()).c_str());
  261. }
  262. // If the property is recognized but the value is rejected, fail the job
  263. if (!accepted)
  264. {
  265. valid = false;
  266. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to parse line: Invalid value assigned to property: Property: \"%s\" Value: \"%s\"", args[0].c_str(), args[1].c_str()).c_str());
  267. }
  268. }
  269. else if ((line[0] == '-'))
  270. {
  271. // Remove image files
  272. AZStd::string remove = line.substr(1);
  273. remove = AzFramework::StringFunc::TrimWhiteSpace(remove, true, true);
  274. if (remove.find('*') != -1)
  275. {
  276. AZStd::string resolvedAbsolutePath;
  277. bool resolved = ResolveRelativePath(remove, directory, resolvedAbsolutePath);
  278. if (resolved)
  279. {
  280. RemoveFilesUsingWildCard(data.m_filePaths, resolvedAbsolutePath);
  281. }
  282. else
  283. {
  284. valid = false;
  285. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to resolve relative path: %s", remove.c_str()).c_str());
  286. }
  287. }
  288. else if (IsFolderPath(remove))
  289. {
  290. AZStd::string resolvedAbsolutePath;
  291. bool resolved = ResolveRelativePath(remove, directory, resolvedAbsolutePath);
  292. if (resolved)
  293. {
  294. RemoveFolderContents(data.m_filePaths, resolvedAbsolutePath);
  295. }
  296. else
  297. {
  298. valid = false;
  299. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to resolve relative path: %s", remove.c_str()).c_str());
  300. }
  301. }
  302. else
  303. {
  304. // Get the full path to the source image from the relative source path
  305. AZStd::string fullSourceAssetPathName;
  306. bool fullPathFound = GetAbsoluteSourcePathFromRelativePath(remove, fullSourceAssetPathName);
  307. if (!fullPathFound)
  308. {
  309. // Try to resolve relative path as it might be using "./" or "../"
  310. fullPathFound = ResolveRelativePath(remove, directory, fullSourceAssetPathName);
  311. }
  312. if (fullPathFound)
  313. {
  314. for (size_t i = 0; i < data.m_filePaths.size(); ++i)
  315. {
  316. if (data.m_filePaths[i] == fullSourceAssetPathName)
  317. {
  318. data.m_filePaths.erase(data.m_filePaths.begin() + i);
  319. }
  320. }
  321. }
  322. else
  323. {
  324. valid = false;
  325. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to get source asset path for image: %s", remove.c_str()).c_str());
  326. }
  327. }
  328. }
  329. else
  330. {
  331. // Add image files
  332. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePathKeepCase, line);
  333. bool duplicate = false;
  334. if (line.find('*') != -1)
  335. {
  336. AZStd::string resolvedAbsolutePath;
  337. bool resolved = ResolveRelativePath(line, directory, resolvedAbsolutePath);
  338. if (resolved)
  339. {
  340. AddFilesUsingWildCard(data.m_filePaths, resolvedAbsolutePath);
  341. }
  342. else
  343. {
  344. valid = false;
  345. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to resolve relative path: %s", line.c_str()).c_str());
  346. }
  347. }
  348. else if (IsFolderPath(line))
  349. {
  350. AZStd::string resolvedAbsolutePath;
  351. bool resolved = ResolveRelativePath(line, directory, resolvedAbsolutePath);
  352. if (resolved)
  353. {
  354. AddFolderContents(data.m_filePaths, resolvedAbsolutePath, valid);
  355. }
  356. else
  357. {
  358. valid = false;
  359. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to resolve relative path: %s", line.c_str()).c_str());
  360. }
  361. }
  362. else
  363. {
  364. // Get the full path to the source image from the relative source path
  365. AZStd::string fullSourceAssetPathName;
  366. bool fullPathFound = GetAbsoluteSourcePathFromRelativePath(line, fullSourceAssetPathName);
  367. if (!fullPathFound)
  368. {
  369. // Try to resolve relative path as it might be using "./" or "../"
  370. fullPathFound = ResolveRelativePath(line, directory, fullSourceAssetPathName);
  371. }
  372. if (fullPathFound)
  373. {
  374. // Prevent duplicates
  375. for (size_t i = 0; i < data.m_filePaths.size() && !duplicate; ++i)
  376. {
  377. duplicate = data.m_filePaths[i] == fullSourceAssetPathName;
  378. }
  379. if (!duplicate)
  380. {
  381. data.m_filePaths.push_back(fullSourceAssetPathName);
  382. }
  383. }
  384. else
  385. {
  386. valid = false;
  387. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to get source asset path for image: %s", line.c_str()).c_str());
  388. }
  389. }
  390. }
  391. }
  392. return data;
  393. }
  394. void AtlasBuilderInput::AddFilesUsingWildCard(AZStd::vector<AZStd::string>& paths, const AZStd::string& insert)
  395. {
  396. const AZStd::string& fullPath = insert;
  397. AZStd::vector<AZStd::string> candidates;
  398. AZStd::string fixedPath = fullPath.substr(0, fullPath.find('*'));
  399. fixedPath = fixedPath.substr(0, fixedPath.find_last_of('/'));
  400. candidates.push_back(fixedPath);
  401. AZStd::vector<AZStd::string> wildPath;
  402. AzFramework::StringFunc::Tokenize(fullPath.substr(fixedPath.length()).c_str(), wildPath, "/");
  403. for (size_t i = 0; i < wildPath.size() && candidates.size() > 0; ++i)
  404. {
  405. AZStd::vector<AZStd::string> nextCandidates;
  406. for (size_t j = 0; j < candidates.size(); ++j)
  407. {
  408. AZStd::string compare = AZStd::string::format("%s/%s", candidates[j].c_str(), wildPath[i].c_str());
  409. QDir inputFolder(candidates[j].c_str());
  410. if (inputFolder.exists())
  411. {
  412. QFileInfoList entries = inputFolder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Files);
  413. for (const QFileInfo& entry : entries)
  414. {
  415. AZStd::string child = (entry.filePath().toStdString()).c_str();
  416. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePathKeepCase, child);
  417. if (DoesPathnameMatchWildCard(compare, child))
  418. {
  419. nextCandidates.push_back(child);
  420. }
  421. }
  422. }
  423. }
  424. candidates = nextCandidates;
  425. }
  426. for (size_t i = 0; i < candidates.size(); ++i)
  427. {
  428. if (!IsFolderPath(candidates[i]) && !HasTrailingSlash(fullPath))
  429. {
  430. AZStd::string ext;
  431. AzFramework::StringFunc::Path::GetExtension(candidates[i].c_str(), ext, false);
  432. if (ext != "dds")
  433. {
  434. bool duplicate = false;
  435. for (size_t j = 0; j < paths.size() && !duplicate; ++j)
  436. {
  437. duplicate = paths[j] == candidates[i];
  438. }
  439. if (!duplicate)
  440. {
  441. paths.push_back(candidates[i]);
  442. }
  443. }
  444. }
  445. else if (IsFolderPath(candidates[i]) && HasTrailingSlash(fullPath))
  446. {
  447. bool waste = true;
  448. AddFolderContents(paths, candidates[i], waste);
  449. }
  450. }
  451. }
  452. void AtlasBuilderInput::RemoveFilesUsingWildCard(AZStd::vector<AZStd::string>& paths, const AZStd::string& remove)
  453. {
  454. bool isDir = (remove.at(remove.length() - 1) == '/');
  455. for (size_t i = 0; i < paths.size(); ++i)
  456. {
  457. if (isDir ? DoesWildCardDirectoryIncludePathname(remove, paths[i]) : DoesPathnameMatchWildCard(remove, paths[i]))
  458. {
  459. paths.erase(paths.begin() + i);
  460. --i;
  461. }
  462. }
  463. }
  464. // Tells us if the child follows the rule
  465. bool AtlasBuilderInput::DoesPathnameMatchWildCard(const AZStd::string& rule, const AZStd::string& child)
  466. {
  467. AZStd::vector<AZStd::string> rulePathTokens;
  468. AzFramework::StringFunc::Tokenize(rule.c_str(), rulePathTokens, "/");
  469. AZStd::vector<AZStd::string> pathTokens;
  470. AzFramework::StringFunc::Tokenize(child.c_str(), pathTokens, "/");
  471. if (rulePathTokens.size() != pathTokens.size())
  472. {
  473. return false;
  474. }
  475. for (size_t i = 0; i < rulePathTokens.size(); ++i)
  476. {
  477. if (!TokenMatchesWildcard(rulePathTokens[i], pathTokens[i]))
  478. {
  479. return false;
  480. }
  481. }
  482. return true;
  483. }
  484. bool AtlasBuilderInput::DoesWildCardDirectoryIncludePathname(const AZStd::string& rule, const AZStd::string& child)
  485. {
  486. AZStd::vector<AZStd::string> rulePathTokens;
  487. AzFramework::StringFunc::Tokenize(rule.c_str(), rulePathTokens, "/");
  488. AZStd::vector<AZStd::string> pathTokens;
  489. AzFramework::StringFunc::Tokenize(child.c_str(), pathTokens, "/");
  490. if (rulePathTokens.size() >= pathTokens.size())
  491. {
  492. return false;
  493. }
  494. for (size_t i = 0; i < rulePathTokens.size(); ++i)
  495. {
  496. if (!TokenMatchesWildcard(rulePathTokens[i], pathTokens[i]))
  497. {
  498. return false;
  499. }
  500. }
  501. return true;
  502. }
  503. bool AtlasBuilderInput::TokenMatchesWildcard(const AZStd::string& rule, const AZStd::string& child)
  504. {
  505. AZStd::vector<AZStd::string> ruleTokens;
  506. AzFramework::StringFunc::Tokenize(rule.c_str(), ruleTokens, "*");
  507. size_t pos = 0;
  508. int token = 0;
  509. if (rule.at(0) != '*' && child.find(ruleTokens[0]) != 0)
  510. {
  511. return false;
  512. }
  513. while (pos != AZStd::string::npos && token < ruleTokens.size())
  514. {
  515. pos = child.find(ruleTokens[token], pos);
  516. if (pos != AZStd::string::npos)
  517. {
  518. pos += ruleTokens[token].size();
  519. }
  520. ++token;
  521. }
  522. return pos == child.size() || (pos != AZStd::string::npos && rule.at(rule.length() - 1) == '*');
  523. }
  524. // Replaces all folder paths with the files they contain
  525. void AtlasBuilderInput::AddFolderContents(AZStd::vector<AZStd::string>& paths, const AZStd::string& insert, bool& valid)
  526. {
  527. QDir inputFolder(insert.c_str());
  528. if (inputFolder.exists())
  529. {
  530. QFileInfoList entries = inputFolder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Files);
  531. for (const QFileInfo& entry : entries)
  532. {
  533. AZStd::string child = (entry.filePath().toStdString()).c_str();
  534. AZStd::string ext;
  535. bool isDir = !AzFramework::StringFunc::Path::GetExtension(child.c_str(), ext, false);
  536. if (isDir)
  537. {
  538. AddFolderContents(paths, child, valid);
  539. }
  540. else if (ext != "dds")
  541. {
  542. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePathKeepCase, child);
  543. bool duplicate = false;
  544. for (size_t i = 0; i < paths.size() && !duplicate; ++i)
  545. {
  546. duplicate = paths[i] == child;
  547. }
  548. if (!duplicate)
  549. {
  550. paths.push_back(child);
  551. }
  552. }
  553. }
  554. }
  555. else
  556. {
  557. valid = false;
  558. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to find requested directory: %s", insert.c_str()).c_str());
  559. }
  560. }
  561. // Removes all of the contents of a folder
  562. void AtlasBuilderInput::RemoveFolderContents(AZStd::vector<AZStd::string>& paths, const AZStd::string& remove)
  563. {
  564. AZStd::string folder = remove;
  565. AzFramework::StringFunc::Strip(folder, "/", false, false, true);
  566. folder.append("/");
  567. for (size_t i = 0; i < paths.size(); ++i)
  568. {
  569. if (paths[i].find(folder) == 0)
  570. {
  571. paths.erase(paths.begin() + i);
  572. --i;
  573. }
  574. }
  575. }
  576. // Note - Shutdown will be called on a different thread than your process job thread
  577. void AtlasBuilderWorker::ShutDown() { m_isShuttingDown = true; }
  578. void AtlasBuilderWorker::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request,
  579. AssetBuilderSDK::CreateJobsResponse& response)
  580. {
  581. // Read in settings/filepaths to set dependencies
  582. AZStd::string fullPath;
  583. AzFramework::StringFunc::Path::Join(
  584. request.m_watchFolder.c_str(), request.m_sourceFile.c_str(), fullPath, true, true);
  585. // Check if input is valid
  586. bool valid = true;
  587. AtlasBuilderInput input = AtlasBuilderInput::ReadFromFile(fullPath, request.m_watchFolder, valid);
  588. // Set dependencies
  589. for (int i = 0; i < input.m_filePaths.size(); ++i)
  590. {
  591. AssetBuilderSDK::SourceFileDependency dependency;
  592. dependency.m_sourceFileDependencyPath = input.m_filePaths[i].c_str();
  593. response.m_sourceFileDependencyList.push_back(dependency);
  594. }
  595. // We process the same file for all platforms
  596. for (const AssetBuilderSDK::PlatformInfo& info : request.m_enabledPlatforms)
  597. {
  598. bool doesSupportPlatform = false;
  599. ImageProcessingAtom::ImageBuilderRequestBus::BroadcastResult(doesSupportPlatform,
  600. &ImageProcessingAtom::ImageBuilderRequests::DoesSupportPlatform,
  601. info.m_identifier);
  602. if (doesSupportPlatform)
  603. {
  604. AssetBuilderSDK::JobDescriptor descriptor = GetJobDescriptor(request.m_sourceFile, input);
  605. descriptor.SetPlatformIdentifier(info.m_identifier.c_str());
  606. response.m_createJobOutputs.push_back(descriptor);
  607. }
  608. }
  609. if (valid)
  610. {
  611. response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success;
  612. }
  613. return;
  614. }
  615. AssetBuilderSDK::JobDescriptor AtlasBuilderWorker::GetJobDescriptor(const AZStd::string& sourceFile, const AtlasBuilderInput& input)
  616. {
  617. // Get the extension of the file
  618. AZStd::string ext;
  619. AzFramework::StringFunc::Path::GetExtension(sourceFile.c_str(), ext, false);
  620. AZStd::to_upper(ext.begin(), ext.end());
  621. AssetBuilderSDK::JobDescriptor descriptor;
  622. descriptor.m_jobKey = ext + " Atlas";
  623. descriptor.m_critical = false;
  624. descriptor.m_jobParameters[AZ_CRC("forceSquare")] = input.m_forceSquare ? "true" : "false";
  625. descriptor.m_jobParameters[AZ_CRC("forcePowerOf2")] = input.m_forcePowerOf2 ? "true" : "false";
  626. descriptor.m_jobParameters[AZ_CRC("includeWhiteTexture")] = input.m_includeWhiteTexture ? "true" : "false";
  627. descriptor.m_jobParameters[AZ_CRC("padding")] = AZStd::to_string(input.m_padding);
  628. descriptor.m_jobParameters[AZ_CRC("maxDimension")] = AZStd::to_string(input.m_maxDimension);
  629. descriptor.m_jobParameters[AZ_CRC("filePaths")] = AZStd::to_string(input.m_filePaths.size());
  630. AZ::u32 col = input.m_unusedColor.ToU32();
  631. descriptor.m_jobParameters[AZ_CRC("unusedColor")] = AZStd::to_string(*reinterpret_cast<int*>(&col));
  632. descriptor.m_jobParameters[AZ_CRC("presetName")] = input.m_presetName;
  633. // The starting point for the list
  634. const int start = static_cast<int>(descriptor.m_jobParameters.size()) + 1;
  635. descriptor.m_jobParameters[AZ_CRC("startPoint")] = AZStd::to_string(start);
  636. for (int i = 0; i < input.m_filePaths.size(); ++i)
  637. {
  638. descriptor.m_jobParameters[start + i] = input.m_filePaths[i];
  639. }
  640. return descriptor;
  641. }
  642. void AtlasBuilderWorker::ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request,
  643. AssetBuilderSDK::ProcessJobResponse& response)
  644. {
  645. // Before we begin, let's make sure we are not meant to abort.
  646. AssetBuilderSDK::JobCancelListener jobCancelListener(request.m_jobId);
  647. const AZStd::string path = request.m_fullPath;
  648. // read in settings/filepaths
  649. AtlasBuilderInput input;
  650. input.m_forceSquare = AzFramework::StringFunc::ToBool(request.m_jobDescription.m_jobParameters.find(AZ_CRC("forceSquare"))->second.c_str());
  651. input.m_forcePowerOf2 = AzFramework::StringFunc::ToBool(request.m_jobDescription.m_jobParameters.find(AZ_CRC("forcePowerOf2"))->second.c_str());
  652. input.m_includeWhiteTexture = AzFramework::StringFunc::ToBool(request.m_jobDescription.m_jobParameters.find(AZ_CRC("includeWhiteTexture"))->second.c_str());
  653. input.m_padding = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("padding"))->second.c_str());
  654. input.m_maxDimension = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("maxDimension"))->second.c_str());
  655. int startAsInt = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("startPoint"))->second.c_str());
  656. int sizeAsInt = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("filePaths"))->second.c_str());
  657. AZ::u32 start = static_cast<AZ::u32>(AZStd::max(0, startAsInt));
  658. AZ::u32 size = static_cast<AZ::u32>(AZStd::max(0, sizeAsInt));
  659. int col = AzFramework::StringFunc::ToInt(request.m_jobDescription.m_jobParameters.find(AZ_CRC("unusedColor"))->second.c_str());
  660. input.m_unusedColor.FromU32(*reinterpret_cast<AZ::u32*>(&col));
  661. input.m_presetName = request.m_jobDescription.m_jobParameters.find(AZ_CRC("presetName"))->second;
  662. for (AZ::u32 i = 0; i < size; ++i)
  663. {
  664. input.m_filePaths.push_back(request.m_jobDescription.m_jobParameters.find(start + i)->second);
  665. }
  666. if (input.m_filePaths.empty())
  667. {
  668. AZ_Error("AtlasBuilder", false, "No image files specified. Cannot create an empty atlas.");
  669. return;
  670. }
  671. // Don't allow padding to be less than zero
  672. if (input.m_padding < 0)
  673. {
  674. input.m_padding = 0;
  675. }
  676. if (input.m_presetName.empty())
  677. {
  678. // Default to the TextureAtlas preset which is currently set to use compression
  679. const AZStd::string defaultPresetName = "UserInterface_Compressed";
  680. input.m_presetName = defaultPresetName;
  681. }
  682. bool isFormatSquarePow2 = false;
  683. ImageProcessingAtom::ImageBuilderRequestBus::BroadcastResult(isFormatSquarePow2,
  684. &ImageProcessingAtom::ImageBuilderRequests::IsPresetFormatSquarePow2,
  685. input.m_presetName, request.m_platformInfo.m_identifier);
  686. if (isFormatSquarePow2)
  687. {
  688. // Override the user config settings to force square and power of 2.
  689. // Otherwise the image conversion process will stretch the image to satisfy these requirements
  690. input.m_forceSquare = true;
  691. input.m_forcePowerOf2 = true;
  692. }
  693. // Read in images
  694. AZStd::vector<ImageProcessingAtom::IImageObjectPtr> images;
  695. AZ::u64 totalArea = 0;
  696. int maxArea = input.m_maxDimension * input.m_maxDimension;
  697. bool sizeFailure = false;
  698. for (int i = 0; i < input.m_filePaths.size() && !jobCancelListener.IsCancelled(); ++i)
  699. {
  700. ImageProcessingAtom::IImageObjectPtr inputImage;
  701. ImageProcessingAtom::ImageProcessingRequestBus::BroadcastResult(inputImage, &ImageProcessingAtom::ImageProcessingRequests::LoadImage, input.m_filePaths[i]);
  702. // Check if we were able to load the image
  703. if (inputImage)
  704. {
  705. images.push_back(inputImage);
  706. totalArea += inputImage->GetWidth(0) * inputImage->GetHeight(0);
  707. }
  708. else
  709. {
  710. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to load file: %s", input.m_filePaths[i].c_str()).c_str());
  711. return;
  712. }
  713. if (maxArea < totalArea)
  714. {
  715. sizeFailure = true;
  716. }
  717. }
  718. // If we get cancelled, return
  719. if (jobCancelListener.IsCancelled())
  720. {
  721. return;
  722. }
  723. if (sizeFailure)
  724. {
  725. AZ_Error("AtlasBuilder", false, AZStd::string::format("Total image area exceeds maximum alotted area. %llu > %d", totalArea, maxArea).c_str());
  726. return;
  727. }
  728. // Convert all image paths to their output format referenced at runtime
  729. for (auto& filePath : input.m_filePaths)
  730. {
  731. // Get path relative to the watch folder
  732. bool result = false;
  733. AZ::Data::AssetInfo info;
  734. AZStd::string watchFolder;
  735. AzToolsFramework::AssetSystemRequestBus::BroadcastResult(result, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, filePath.c_str(), info, watchFolder);
  736. if (!result)
  737. {
  738. AZ_Error("AtlasBuilder", false, AZStd::string::format("Atlas Builder unable to get relative source path for image: %s", filePath.c_str()).c_str());
  739. return;
  740. }
  741. // Remove extension
  742. filePath = info.m_relativePath.substr(0, info.m_relativePath.find_last_of('.'));
  743. // Normalize path
  744. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePathKeepCase, filePath);
  745. }
  746. // Add white texture if we need to
  747. if (input.m_includeWhiteTexture)
  748. {
  749. ImageProcessingAtom::IImageObjectPtr texture;
  750. ImageProcessingAtom::ImageBuilderRequestBus::BroadcastResult(texture,
  751. &ImageProcessingAtom::ImageBuilderRequests::CreateImage,
  752. aznumeric_cast<AZ::u32>(cellSize),
  753. aznumeric_cast<AZ::u32>(cellSize),
  754. 1,
  755. ImageProcessingAtom::EPixelFormat::ePixelFormat_R8G8B8A8);
  756. // Make the texture white
  757. texture->ClearColor(1, 1, 1, 1);
  758. images.push_back(texture);
  759. input.m_filePaths.push_back("WhiteTexture");
  760. }
  761. // Generate algorithm inputs
  762. ImageDimensionData data;
  763. for (int i = 0; i < images.size(); ++i)
  764. {
  765. data.push_back(IndexImageDimension(i,
  766. ImageDimension(images[i]->GetWidth(0),
  767. images[i]->GetHeight(0))));
  768. }
  769. AZStd::sort(data.begin(), data.end());
  770. // Run algorithm
  771. // Variables that keep track of the optimal solution
  772. int resultWidth = -1;
  773. int resultHeight = -1;
  774. // Check that the max dimension is not large enough for the area to loop past the maximum integer
  775. // This is important because we do not want the area to be calculated negative
  776. if (input.m_maxDimension > 65535)
  777. {
  778. input.m_maxDimension = 65535;
  779. }
  780. // Get the optimal mappings based on the input settings
  781. AZStd::vector<AtlasCoordinates> paddedMap;
  782. size_t amountFit = 0;
  783. if (!TryTightening(
  784. input, data, GetWidest(data), GetTallest(data), aznumeric_cast<int>(totalArea), input.m_padding, resultWidth, resultHeight, amountFit, paddedMap))
  785. {
  786. AZ_Error("AtlasBuilder", false, AZStd::string::format("Cannot fit images into given maximum atlas size (%dx%d). Only %zu out of %zu images fit.", input.m_maxDimension, input.m_maxDimension, amountFit, input.m_filePaths.size()).c_str());
  787. // For some reason, failing the assert isn't enough to stop the Asset builder. It will still fail further
  788. // down when it tries to assemble the atlas, but returning here is cleaner.
  789. return;
  790. }
  791. // Move coordinates from algorithm space to padded result space
  792. TextureAtlasNamespace::AtlasCoordinateSets output;
  793. resultWidth = 0;
  794. resultHeight = 0;
  795. AZStd::vector<AtlasCoordinates> map;
  796. for (int i = 0; i < paddedMap.size(); ++i)
  797. {
  798. map.push_back(AtlasCoordinates(paddedMap[i].GetLeft(), paddedMap[i].GetLeft() + images[data[i].first]->GetWidth(0), paddedMap[i].GetTop(), paddedMap[i].GetTop() + images[data[i].first]->GetHeight(0)));
  799. resultHeight = resultHeight > map[i].GetBottom() ? resultHeight : map[i].GetBottom();
  800. resultWidth = resultWidth > map[i].GetRight() ? resultWidth : map[i].GetRight();
  801. const AZStd::string& outputFilePath = input.m_filePaths[data[i].first];
  802. output.push_back(AZStd::pair<AZStd::string, AtlasCoordinates>(outputFilePath, map[i]));
  803. }
  804. if (input.m_forcePowerOf2)
  805. {
  806. resultWidth = aznumeric_cast<int>(pow(2, 1 + IntegerLog2(static_cast<uint32_t>(resultWidth - 1))));
  807. resultHeight = aznumeric_cast<int>(pow(2, 1 + IntegerLog2(static_cast<uint32_t>(resultHeight - 1))));
  808. }
  809. else
  810. {
  811. resultWidth = (resultWidth + (cellSize - 1)) / cellSize * cellSize;
  812. resultHeight = (resultHeight + (cellSize - 1)) / cellSize * cellSize;
  813. }
  814. if (input.m_forceSquare)
  815. {
  816. if (resultWidth > resultHeight)
  817. {
  818. resultHeight = resultWidth;
  819. }
  820. else
  821. {
  822. resultWidth = resultHeight;
  823. }
  824. }
  825. // Process texture sheet
  826. ImageProcessingAtom::IImageObjectPtr outImage;
  827. ImageProcessingAtom::ImageBuilderRequestBus::BroadcastResult(outImage,
  828. &ImageProcessingAtom::ImageBuilderRequests::CreateImage,
  829. aznumeric_cast<AZ::u32>(resultWidth),
  830. aznumeric_cast<AZ::u32>(resultHeight),
  831. 1,
  832. ImageProcessingAtom::EPixelFormat::ePixelFormat_R8G8B8A8);
  833. // Clear the sheet
  834. outImage->ClearColor(input.m_unusedColor.GetR(), input.m_unusedColor.GetG(), input.m_unusedColor.GetB(), input.m_unusedColor.GetA());
  835. AZ::u8* outBuffer = nullptr;
  836. AZ::u32 outPitch;
  837. outImage->GetImagePointer(0, outBuffer, outPitch);
  838. // Copy images over
  839. for (int i = 0; i < map.size() && !jobCancelListener.IsCancelled(); ++i)
  840. {
  841. AZ::u8* inBuffer = nullptr;
  842. AZ::u32 inPitch;
  843. images[data[i].first]->GetImagePointer(0, inBuffer, inPitch);
  844. int j = 0;
  845. // The padding calculated here is the amount of excess horizontal space measured in bytes that are in each
  846. // row of the destination space AFTER the placement of the source row.
  847. int rightPadding = (paddedMap[i].GetRight() - map[i].GetRight() - input.m_padding);
  848. if (map[i].GetRight() + rightPadding > resultWidth)
  849. {
  850. rightPadding = resultWidth - map[i].GetRight();
  851. }
  852. rightPadding *= bytesPerPixel;
  853. int bottomPadding = (paddedMap[i].GetBottom() - map[i].GetBottom() - input.m_padding);
  854. if (map[i].GetBottom() + bottomPadding > resultHeight)
  855. {
  856. bottomPadding = resultHeight - map[i].GetBottom();
  857. }
  858. int leftPadding = 0;
  859. if (map[i].GetLeft() - input.m_padding >= 0)
  860. {
  861. leftPadding = input.m_padding * bytesPerPixel;
  862. }
  863. int topPadding = 0;
  864. if (map[i].GetTop() - input.m_padding >= 0)
  865. {
  866. topPadding = input.m_padding;
  867. }
  868. for (j = 0; j < map[i].GetHeight(); ++j)
  869. {
  870. // When we multiply `map[i].GetLeft()` by 4, we are changing the measure from atlas space, to byte array
  871. // space. The number is 4 because in this format, each pixel is 4 bytes long.
  872. memcpy(outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel),
  873. inBuffer + inPitch * j,
  874. inPitch);
  875. // Fill in the last bit of the row in the destination space with the same colors
  876. SetPixels(outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel) + inPitch,
  877. outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel) + inPitch - bytesPerPixel,
  878. rightPadding);
  879. // Fill in the first bit of the row in the destination space with the same colors
  880. SetPixels(outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding,
  881. outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel),
  882. leftPadding);
  883. }
  884. // Fill in the last few rows of the buffer with the same colors
  885. for (; j < map[i].GetHeight() + bottomPadding; ++j)
  886. {
  887. memcpy(outBuffer + (map[i].GetTop() + j) * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding,
  888. outBuffer + (map[i].GetBottom() - 1) * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding,
  889. inPitch + leftPadding + rightPadding);
  890. }
  891. for (j = 1; j <= topPadding; ++j)
  892. {
  893. memcpy(outBuffer + (map[i].GetTop() - j) * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding,
  894. outBuffer + map[i].GetTop() * outPitch + (map[i].GetLeft() * bytesPerPixel) - leftPadding,
  895. inPitch + rightPadding + leftPadding);
  896. }
  897. }
  898. // If we get cancelled, return
  899. if (jobCancelListener.IsCancelled())
  900. {
  901. return;
  902. }
  903. // Output Atlas Coordinates
  904. AZStd::string fileName;
  905. AZStd::string outputPath;
  906. AzFramework::StringFunc::Path::GetFullFileName(request.m_sourceFile.c_str(), fileName);
  907. fileName = fileName.append("idx");
  908. AzFramework::StringFunc::Path::Join(
  909. request.m_tempDirPath.c_str(), fileName.c_str(), outputPath, true, true);
  910. // Output texture sheet
  911. AZStd::string imageFileName, imageOutputPath;
  912. AzFramework::StringFunc::Path::GetFileName(request.m_sourceFile.c_str(), imageFileName);
  913. imageFileName += ".texatlas";
  914. AzFramework::StringFunc::Path::Join(
  915. request.m_tempDirPath.c_str(), imageFileName.c_str(), imageOutputPath, true, true);
  916. AZStd::vector<AssetBuilderSDK::JobProduct> outProducts;
  917. ImageProcessingAtom::ImageBuilderRequestBus::BroadcastResult(outProducts,
  918. &ImageProcessingAtom::ImageBuilderRequests::ConvertImageObject,
  919. outImage,
  920. input.m_presetName,
  921. request.m_platformInfo.m_identifier,
  922. imageOutputPath,
  923. request.m_sourceFileUUID,
  924. request.m_sourceFile);
  925. if (!outProducts.empty())
  926. {
  927. TextureAtlasNamespace::TextureAtlasRequestBus::Broadcast(
  928. &TextureAtlasNamespace::TextureAtlasRequests::SaveAtlasToFile, outputPath, output, resultWidth, resultHeight);
  929. response.m_outputProducts.push_back(AssetBuilderSDK::JobProduct(outputPath));
  930. response.m_outputProducts[static_cast<int>(Product::TexatlasidxProduct)].m_productAssetType = azrtti_typeid<TextureAtlasNamespace::TextureAtlasAsset>();
  931. response.m_outputProducts[static_cast<int>(Product::TexatlasidxProduct)].m_productSubID = 0;
  932. // The Image Processing Gem can produce multiple output files under certain
  933. // circumstances, but the texture atlas is not expected to produce such output
  934. if (outProducts.size() > 1)
  935. {
  936. AZ_Error("AtlasBuilder", false, "Image processing resulted in multiple output files. Texture atlas is expected to produce one output.");
  937. response.m_outputProducts.clear();
  938. return;
  939. }
  940. response.m_outputProducts.push_back(outProducts[0]);
  941. // The texatlasidx file is a data file that indicates where the original parts are inside the atlas,
  942. // and this would usually imply that it refers to its dds file in some way or needs it to function.
  943. // The texatlasidx file should be the one that depends on the DDS because it's possible to use the DDS
  944. // without the texatlasid, but not the other way around
  945. AZ::Data::AssetId productAssetId(request.m_sourceFileUUID, response.m_outputProducts.back().m_productSubID);
  946. response.m_outputProducts[static_cast<int>(Product::TexatlasidxProduct)].m_dependencies.push_back(AssetBuilderSDK::ProductDependency(productAssetId, 0));
  947. response.m_outputProducts[static_cast<int>(Product::TexatlasidxProduct)].m_dependenciesHandled = true; // We've populated the dependencies immediately above so it's OK to tell the AP we've handled dependencies
  948. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  949. }
  950. }
  951. bool AtlasBuilderWorker::TryPack(const ImageDimensionData& images,
  952. int targetWidth,
  953. int targetHeight,
  954. int padding,
  955. size_t& amountFit,
  956. AZStd::vector<AtlasCoordinates>& out)
  957. {
  958. // Start with one open slot and initialize a vector to store the closed products
  959. AZStd::vector<AtlasCoordinates> open;
  960. AZStd::vector<AtlasCoordinates> closed;
  961. open.push_back(AtlasCoordinates(0, targetWidth, 0, targetHeight));
  962. bool slotNotFound = false;
  963. for (size_t i = 0; i < images.size() && !slotNotFound; ++i)
  964. {
  965. slotNotFound = true;
  966. // Try to place the image in every open slot
  967. for (size_t j = 0; j < open.size(); ++j)
  968. {
  969. if (CanInsert(open[j], images[i].second, padding, targetWidth, targetHeight))
  970. {
  971. // if it fits, subdivide the excess space in the slot, add it back to the open list and place the
  972. // filled space into the closed vector
  973. slotNotFound = false;
  974. AtlasCoordinates spent(open[j].GetLeft(),
  975. open[j].GetLeft() + images[i].second.m_width,
  976. open[j].GetTop(),
  977. open[j].GetTop() + images[i].second.m_height);
  978. // We are going to try pushing the object up / left to try to avoid creating tight open spaces.
  979. bool needTrim = false;
  980. AtlasCoordinates coords = spent;
  981. // Modifying left will preserve width
  982. coords.SetLeft(coords.GetLeft() - 1);
  983. AddPadding(coords, padding, targetWidth, targetHeight);
  984. while (spent.GetLeft() > 0 && !Collides(coords, closed))
  985. {
  986. spent.SetLeft(coords.GetLeft());
  987. coords = spent;
  988. coords.SetLeft(coords.GetLeft() - 1);
  989. AddPadding(coords, padding, targetWidth, targetHeight);
  990. needTrim = true;
  991. }
  992. // Refocus the search to see if we can push up
  993. coords = spent;
  994. coords.SetTop(coords.GetTop() - 1);
  995. AddPadding(coords, padding, targetWidth, targetHeight);
  996. while (spent.GetTop() > 0 && !Collides(coords, closed))
  997. {
  998. spent.SetTop(coords.GetTop());
  999. coords = spent;
  1000. coords.SetTop(coords.GetTop() - 1);
  1001. AddPadding(coords, padding, targetWidth, targetHeight);
  1002. needTrim = true;
  1003. }
  1004. AddPadding(spent, padding, targetWidth, targetHeight);
  1005. if (needTrim)
  1006. {
  1007. TrimOverlap(open, spent);
  1008. closed.push_back(spent);
  1009. break;
  1010. }
  1011. AtlasCoordinates bigCoords;
  1012. AtlasCoordinates smallCoords;
  1013. // Create the largest possible subdivision and another subdivision that uses the left over space
  1014. if (open[j].GetBottom() - spent.GetBottom() < open[j].GetRight() - spent.GetRight())
  1015. {
  1016. smallCoords = AtlasCoordinates(
  1017. open[j].GetLeft(), spent.GetRight(), spent.GetBottom(), open[j].GetBottom());
  1018. bigCoords = AtlasCoordinates(spent.GetRight(), open[j].GetRight(), open[j].GetTop(), smallCoords.GetBottom());
  1019. }
  1020. else
  1021. {
  1022. bigCoords = AtlasCoordinates(
  1023. open[j].GetLeft(), open[j].GetRight(), spent.GetBottom(), open[j].GetBottom());
  1024. smallCoords = AtlasCoordinates(spent.GetRight(), open[j].GetRight(), open[j].GetTop(), bigCoords.GetTop());
  1025. }
  1026. open.erase(open.begin() + j, open.begin() + j + 1);
  1027. if (bigCoords.GetHeight() > 0 && bigCoords.GetHeight() > 0)
  1028. {
  1029. InsertInOrder(open, bigCoords);
  1030. }
  1031. if (smallCoords.GetHeight() > 0 && smallCoords.GetHeight() > 0)
  1032. {
  1033. InsertInOrder(open, smallCoords);
  1034. }
  1035. closed.push_back(spent);
  1036. break;
  1037. }
  1038. }
  1039. if (slotNotFound)
  1040. {
  1041. // If no single open slot can fit the object, do one last check to see if we can fit it in at any open
  1042. // corner. The reason we perform this check is in case the object can be fit across multiple different
  1043. // open spaces. If there is a space that an object can be fit in, it will probably involve the top left
  1044. // corner of that object in the top left corner of an open slot. This may miss some odd fits, but due to
  1045. // the nature of the packing algorithm, such solutions are highly unlikely to exist. If we wanted to
  1046. // expand the algorithm, we could theoretically base it on edges instead of corners to find all results,
  1047. // but it would not be time efficient.
  1048. for (size_t j = 0; j < open.size(); ++j)
  1049. {
  1050. AtlasCoordinates insert = AtlasCoordinates(open[j].GetLeft(),
  1051. open[j].GetLeft() + images[i].second.m_width,
  1052. open[j].GetTop(),
  1053. open[j].GetTop() + images[i].second.m_height);
  1054. AddPadding(insert, padding, targetWidth, targetHeight);
  1055. if (insert.GetRight() <= targetWidth && insert.GetBottom() <= targetHeight)
  1056. {
  1057. bool collision = Collides(insert, closed);
  1058. if (!collision)
  1059. {
  1060. closed.push_back(insert);
  1061. // Trim overlapping open slots
  1062. TrimOverlap(open, insert);
  1063. slotNotFound = false;
  1064. break;
  1065. }
  1066. }
  1067. }
  1068. }
  1069. }
  1070. // If we succeeded, update the output
  1071. if (!slotNotFound)
  1072. {
  1073. out = closed;
  1074. }
  1075. amountFit = amountFit > closed.size() ? amountFit : closed.size();
  1076. return !slotNotFound;
  1077. }
  1078. // Modifies slotList so that no items in slotList overlap with item
  1079. void AtlasBuilderWorker::TrimOverlap(AZStd::vector<AtlasCoordinates>& slotList, AtlasCoordinates item)
  1080. {
  1081. for (size_t i = 0; i < slotList.size(); ++i)
  1082. {
  1083. if (Collides(slotList[i], item))
  1084. {
  1085. // Subdivide the overlapping slot to seperate overlapping and non overlapping portions
  1086. AtlasCoordinates overlap = GetOverlap(item, slotList[i]);
  1087. AZStd::vector<AtlasCoordinates> excess;
  1088. excess.push_back(AtlasCoordinates(
  1089. slotList[i].GetLeft(), overlap.GetRight(), slotList[i].GetTop(), overlap.GetTop()));
  1090. excess.push_back(AtlasCoordinates(
  1091. slotList[i].GetLeft(), overlap.GetLeft(), overlap.GetTop(), slotList[i].GetBottom()));
  1092. excess.push_back(AtlasCoordinates(
  1093. overlap.GetRight(), slotList[i].GetRight(), slotList[i].GetTop(), overlap.GetBottom()));
  1094. excess.push_back(AtlasCoordinates(
  1095. overlap.GetLeft(), slotList[i].GetRight(), overlap.GetBottom(), slotList[i].GetBottom()));
  1096. slotList.erase(slotList.begin() + i);
  1097. for (size_t j = 0; j < excess.size(); ++j)
  1098. {
  1099. if (excess[j].GetWidth() > 0 && excess[j].GetHeight() > 0)
  1100. {
  1101. InsertInOrder(slotList, excess[j]);
  1102. }
  1103. }
  1104. --i;
  1105. }
  1106. }
  1107. }
  1108. // This function interprets input and performs the proper tightening option
  1109. bool AtlasBuilderWorker::TryTightening(AtlasBuilderInput input,
  1110. const ImageDimensionData& images,
  1111. int smallestWidth,
  1112. int smallestHeight,
  1113. int targetArea,
  1114. int padding,
  1115. int& resultWidth,
  1116. int& resultHeight,
  1117. size_t& amountFit,
  1118. AZStd::vector<AtlasCoordinates>& out)
  1119. {
  1120. if (input.m_forceSquare)
  1121. {
  1122. return TryTighteningSquare(images,
  1123. smallestWidth > smallestHeight ? smallestWidth : smallestHeight,
  1124. input.m_maxDimension,
  1125. targetArea,
  1126. input.m_forcePowerOf2,
  1127. padding,
  1128. resultWidth,
  1129. resultHeight,
  1130. amountFit,
  1131. out);
  1132. }
  1133. else
  1134. {
  1135. return TryTighteningOptimal(images,
  1136. smallestWidth,
  1137. smallestHeight,
  1138. input.m_maxDimension,
  1139. targetArea,
  1140. input.m_forcePowerOf2,
  1141. padding,
  1142. resultWidth,
  1143. resultHeight,
  1144. amountFit,
  1145. out);
  1146. }
  1147. }
  1148. // Finds the optimal square solution by starting with the ideal solution and expanding the size of the space until everything fits
  1149. bool AtlasBuilderWorker::TryTighteningSquare(const ImageDimensionData& images,
  1150. int lowerBound,
  1151. int maxDimension,
  1152. int targetArea,
  1153. bool powerOfTwo,
  1154. int padding,
  1155. int& resultWidth,
  1156. int& resultHeight,
  1157. size_t& amountFit,
  1158. AZStd::vector<AtlasCoordinates>& out)
  1159. {
  1160. // Square solution cannot be smaller than the target area
  1161. int dimension = aznumeric_cast<int>(sqrt(static_cast<float>(targetArea)));
  1162. // Solution cannot be smaller than the smallest side
  1163. dimension = dimension > lowerBound ? dimension : lowerBound;
  1164. if (powerOfTwo)
  1165. {
  1166. // Starting dimension needs to be rounded up to the nearest power of two
  1167. dimension = aznumeric_cast<int>(pow(2, 1 + IntegerLog2(static_cast<uint32_t>(dimension - 1))));
  1168. }
  1169. AZStd::vector<AtlasCoordinates> track;
  1170. // Expand the square until the contents fit
  1171. while (!TryPack(images, dimension, dimension, padding, amountFit, track) && dimension <= maxDimension)
  1172. {
  1173. // Step to the next valid value
  1174. dimension = powerOfTwo ? dimension * 2 : dimension + cellSize;
  1175. }
  1176. // Make sure we found a solution
  1177. if (dimension > maxDimension)
  1178. {
  1179. return false;
  1180. }
  1181. resultHeight = dimension;
  1182. resultWidth = dimension;
  1183. out = track;
  1184. return true;
  1185. }
  1186. // Finds the optimal solution by starting with a somewhat optimal solution and searching for better solutions
  1187. bool AtlasBuilderWorker::TryTighteningOptimal(const ImageDimensionData& images,
  1188. int smallestWidth,
  1189. int smallestHeight,
  1190. int maxDimension,
  1191. int targetArea,
  1192. bool powerOfTwo,
  1193. int padding,
  1194. int& resultWidth,
  1195. int& resultHeight,
  1196. size_t& amountFit,
  1197. AZStd::vector<AtlasCoordinates>& out)
  1198. {
  1199. AZStd::vector<AtlasCoordinates> track;
  1200. // round max dimension down to a multiple of cellSize
  1201. AZ::u32 maxDimensionRounded = maxDimension - (maxDimension % cellSize);
  1202. // The starting width is the larger of the widest individual texture and the width required
  1203. // to fit the total texture area given the max dimension
  1204. AZ::u32 smallestWidthDueToArea = targetArea / maxDimensionRounded;
  1205. AZ::u32 minWidth = AZStd::max(static_cast<AZ::u32>(smallestWidth), smallestWidthDueToArea);
  1206. if (powerOfTwo)
  1207. {
  1208. // Starting dimension needs to be rounded up to the nearest power of two
  1209. minWidth = aznumeric_cast<AZ::u32>(pow(2, 1 + IntegerLog2(static_cast<uint32_t>(minWidth - 1))));
  1210. }
  1211. // Round min width up to the nearest compression unit
  1212. minWidth = (minWidth + (cellSize - 1)) / cellSize * cellSize;
  1213. AZ::u32 height = 0;
  1214. // Finds the optimal thin solution
  1215. // This uses a standard binary search to find the smallest width that can pack everything
  1216. AZ::u32 lower = minWidth;
  1217. AZ::u32 upper = maxDimensionRounded;
  1218. AZ::u32 width = 0;
  1219. while (lower <= upper)
  1220. {
  1221. AZ::u32 testWidth = (lower + upper) / 2; // must be divisible by cellSize because lower and upper are
  1222. bool canPack = TryPack(images, testWidth, maxDimension, padding, amountFit, track);
  1223. if (canPack)
  1224. {
  1225. // it packed, continue looking for smaller widths that pack
  1226. width = testWidth; // best fit so far
  1227. upper = testWidth - cellSize;
  1228. }
  1229. else
  1230. {
  1231. // it failed to pack, don't try any widths smaller than this
  1232. lower = testWidth + cellSize;
  1233. }
  1234. }
  1235. // Make sure we found a solution
  1236. if (width == 0)
  1237. {
  1238. return false;
  1239. }
  1240. // Find the height of the solution
  1241. for (int i = 0; i < track.size(); ++i)
  1242. {
  1243. uint32_t bottom = static_cast<uint32_t>(AZStd::max(0, track[i].GetBottom()));
  1244. if (height < bottom)
  1245. {
  1246. height = bottom;
  1247. }
  1248. }
  1249. // Fix height for power of two when applicable
  1250. if (powerOfTwo)
  1251. {
  1252. // Starting dimensions need to be rounded up to the nearest power of two
  1253. height = aznumeric_cast<AZ::u32>(pow(2, 1 + IntegerLog2(static_cast<uint32_t>(height - 1))));
  1254. }
  1255. AZ::u32 resultArea = height * width;
  1256. // This for loop starts with the optimal thin width and makes it wider at each step. For each width, it
  1257. // calculates what height would be neccesary to have a more optimal solution than the stored solution. If the
  1258. // more optimal solution is valid, it tries shrinking the height until the solution fails. The loop ends when it
  1259. // is determined that a valid solution cannot exist at further steps
  1260. for (AZ::u32 testWidth = width; testWidth <= maxDimensionRounded && resultArea / testWidth >= static_cast<AZ::u32>(smallestHeight);
  1261. testWidth = powerOfTwo ? testWidth * 2 : testWidth + cellSize)
  1262. {
  1263. // The area of test height and width should be equal or less than resultArea
  1264. // Note: We don't need to force powers of two here because the Area and the width are already powers of two
  1265. int testHeight = resultArea / testWidth * cellSize / cellSize;
  1266. // Try the tighter pack
  1267. while (TryPack(images, static_cast<int>(testWidth), testHeight, padding, amountFit, track))
  1268. {
  1269. // Loop and continue to shrink the height until you cannot do so any further
  1270. width = testWidth;
  1271. height = testHeight;
  1272. resultArea = height * width;
  1273. // Try to step down a level
  1274. testHeight = powerOfTwo ? testHeight / 2 : testHeight - cellSize;
  1275. }
  1276. }
  1277. // Output the results of the function
  1278. out = track;
  1279. resultHeight = height;
  1280. resultWidth = width;
  1281. return true;
  1282. }
  1283. // Allows us to keep the list of open spaces in order from lowest to highest area
  1284. void AtlasBuilderWorker::InsertInOrder(AZStd::vector<AtlasCoordinates>& slotList, AtlasCoordinates item)
  1285. {
  1286. int area = item.GetWidth() * item.GetHeight();
  1287. for (size_t i = 0; i < slotList.size(); ++i)
  1288. {
  1289. if (area < slotList[i].GetWidth() * slotList[i].GetHeight())
  1290. {
  1291. slotList.insert(slotList.begin() + i, item);
  1292. return;
  1293. }
  1294. }
  1295. slotList.push_back(item);
  1296. }
  1297. // Defines priority so that sorting can be meaningful. It may seem odd that larger items are "less than" smaller
  1298. // ones, but as this is a deduction of priority, not value, it is correct.
  1299. bool operator<(ImageDimension a, ImageDimension b)
  1300. {
  1301. // Prioritize first by longest size
  1302. if ((a.m_width > a.m_height ? a.m_width : a.m_height) != (b.m_width > b.m_height ? b.m_width : b.m_height))
  1303. {
  1304. return (a.m_width > a.m_height ? a.m_width : a.m_height) > (b.m_width > b.m_height ? b.m_width : b.m_height);
  1305. }
  1306. // Prioritize second by the length of the smaller side
  1307. if (a.m_width * a.m_height != b.m_width * b.m_height)
  1308. {
  1309. return a.m_width * a.m_height > b.m_width * b.m_height;
  1310. }
  1311. // Prioritize wider objects over taller objects for objects of the same size
  1312. else
  1313. {
  1314. return a.m_width > b.m_width;
  1315. }
  1316. }
  1317. // Exposes priority logic to the sorting algorithm
  1318. bool operator<(IndexImageDimension a, IndexImageDimension b) { return a.second < b.second; }
  1319. // Tests if two coordinate sets intersect
  1320. bool Collides(AtlasCoordinates a, AtlasCoordinates b)
  1321. {
  1322. return !((a.GetRight() <= b.GetLeft()) || (a.GetBottom() <= b.GetTop()) || (b.GetRight() <= a.GetLeft())
  1323. || (b.GetBottom() <= a.GetTop()));
  1324. }
  1325. // Tests if an item collides with any items in a list
  1326. bool Collides(AtlasCoordinates item, AZStd::vector<AtlasCoordinates> list)
  1327. {
  1328. for (size_t i = 0; i < list.size(); ++i)
  1329. {
  1330. if (Collides(list[i], item))
  1331. {
  1332. return true;
  1333. }
  1334. }
  1335. return false;
  1336. }
  1337. // Returns the overlap of two intersecting coordinate sets
  1338. AtlasCoordinates GetOverlap(AtlasCoordinates a, AtlasCoordinates b)
  1339. {
  1340. return AtlasCoordinates(b.GetLeft() > a.GetLeft() ? b.GetLeft() : a.GetLeft(),
  1341. b.GetRight() < a.GetRight() ? b.GetRight() : a.GetRight(),
  1342. b.GetTop() > a.GetTop() ? b.GetTop() : a.GetTop(),
  1343. b.GetBottom() < a.GetBottom() ? b.GetBottom() : a.GetBottom());
  1344. }
  1345. // Returns the width of the widest element in imageList
  1346. int AtlasBuilderWorker::GetWidest(const ImageDimensionData& imageList)
  1347. {
  1348. int max = 0;
  1349. for (size_t i = 0; i < imageList.size(); ++i)
  1350. {
  1351. if (max < imageList[i].second.m_width)
  1352. {
  1353. max = imageList[i].second.m_width;
  1354. }
  1355. }
  1356. return max;
  1357. }
  1358. // Returns the height of the tallest element in imageList
  1359. int AtlasBuilderWorker::GetTallest(const ImageDimensionData& imageList)
  1360. {
  1361. int max = 0;
  1362. for (size_t i = 0; i < imageList.size(); ++i)
  1363. {
  1364. if (max < imageList[i].second.m_height)
  1365. {
  1366. max = imageList[i].second.m_height;
  1367. }
  1368. }
  1369. return max;
  1370. }
  1371. // Performs an operation that copies a pixel to the output
  1372. void SetPixels(AZ::u8* dest, const AZ::u8* source, int destBytes)
  1373. {
  1374. if (destBytes >= bytesPerPixel)
  1375. {
  1376. memcpy(dest, source, bytesPerPixel);
  1377. int bytesCopied = bytesPerPixel;
  1378. while (bytesCopied * 2 < destBytes)
  1379. {
  1380. memcpy(dest + bytesCopied, dest, bytesCopied);
  1381. bytesCopied *= 2;
  1382. }
  1383. memcpy(dest + bytesCopied, dest, destBytes - bytesCopied);
  1384. }
  1385. }
  1386. // Checks if we can insert an image into a slot
  1387. bool CanInsert(AtlasCoordinates slot, ImageDimension image, int padding, int farRight, int farBot)
  1388. {
  1389. int right = slot.GetLeft() + image.m_width;
  1390. if (slot.GetRight() < farRight)
  1391. {
  1392. // Add padding for my right border
  1393. right += padding;
  1394. // Round up to the nearest compression unit
  1395. right = (right + (cellSize - 1)) / cellSize * cellSize;
  1396. // Add padding for an adjacent unit's left border
  1397. right += padding;
  1398. }
  1399. int bot = slot.GetTop() + image.m_height;
  1400. if (slot.GetBottom() < farBot)
  1401. {
  1402. // Add padding for my right border
  1403. bot += padding;
  1404. // Round up to the nearest compression unit
  1405. bot = (bot + (cellSize - 1)) / cellSize * cellSize;
  1406. // Add padding for an adjacent unit's left border
  1407. bot += padding;
  1408. }
  1409. return slot.GetRight() >= right && slot.GetBottom() >= bot;
  1410. }
  1411. // Adds the necessary padding to an Atlas Coordinate
  1412. void AddPadding(AtlasCoordinates& slot, int padding, [[maybe_unused]] int farRight, [[maybe_unused]] int farBot)
  1413. {
  1414. // Add padding for my right border
  1415. int right = slot.GetRight() + padding;
  1416. // Round up to the nearest compression unit
  1417. right = (right + (cellSize - 1)) / cellSize * cellSize;
  1418. // Add padding for an adjacent unit's left border
  1419. right += padding;
  1420. // Add padding for my right border
  1421. int bot = slot.GetBottom() + padding;
  1422. // Round up to the nearest compression unit
  1423. bot = (bot + (cellSize - 1)) / cellSize * cellSize;
  1424. // Add padding for an adjacent unit's left border
  1425. bot += padding;
  1426. slot.SetRight(right);
  1427. slot.SetBottom(bot);
  1428. }
  1429. }