GenericOnDemandTextureLoader.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated July 28, 2023. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2023, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software or
  13. * otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE
  27. * SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #define SPINE_OPTIONAL_ON_DEMAND_LOADING
  30. #if SPINE_OPTIONAL_ON_DEMAND_LOADING
  31. using System;
  32. using System.Collections.Generic;
  33. using System.Linq;
  34. using UnityEngine;
  35. namespace Spine.Unity {
  36. /// <summary>
  37. /// Interface to derive a concrete target reference struct from which holds
  38. /// an on-demand loading reference to the target texture to be loaded.
  39. /// </summary>
  40. public interface ITargetTextureReference {
  41. #if UNITY_EDITOR
  42. Texture EditorTexture { get; }
  43. #endif
  44. }
  45. /// <summary>
  46. /// Interface to derive a concrete request handler struct from which covers
  47. /// a single texture loading request.
  48. /// </summary>
  49. public interface IOnDemandRequest {
  50. bool WasRequested { get; }
  51. bool WasSuccessfullyLoaded { get; }
  52. bool IsTarget (Texture texture);
  53. void Release ();
  54. }
  55. /// <summary>
  56. /// Base class to derive your own OnDemandTextureLoader subclasses from which already provides
  57. /// the general loading and unloading framework.
  58. /// For reference, see the <see cref="AddressablesTextureLoader"/> class available
  59. /// in the com.esotericsoftware.spine.addressables UPM package.
  60. /// </summary>
  61. /// <typeparam name="TargetReference">The implementation struct which holds an on-demand loading reference
  62. /// to the target texture to be loaded, derived from ITargetTextureReference.</typeparam>
  63. /// <typeparam name="TextureRequest">The implementation struct covering a single texture loading request,
  64. /// derived from IOnDemandRequest</typeparam>
  65. [System.Serializable]
  66. public abstract class GenericOnDemandTextureLoader<TargetReference, TextureRequest> : OnDemandTextureLoader
  67. where TargetReference : ITargetTextureReference
  68. where TextureRequest : IOnDemandRequest {
  69. [System.Serializable]
  70. public struct PlaceholderTextureMapping {
  71. public Texture placeholderTexture;
  72. public TargetReference targetTextureReference;
  73. }
  74. /// <summary>
  75. /// Unfortunately serialization of jagged arrays PlaceholderTextureMapping[][] is not supported,
  76. /// so we need to use this class with a 1D-array PlaceholderMaterialMapping[] as a workaround.
  77. /// </summary>
  78. [System.Serializable]
  79. public struct PlaceholderMaterialMapping {
  80. public PlaceholderTextureMapping[] textures;
  81. }
  82. // Note: not System.Serializabe on purpose. Would be unnecessary and causes problems otherwise.
  83. public struct MaterialOnDemandData {
  84. public int lastFrameRequested;
  85. public TextureRequest[] textureRequests;
  86. }
  87. void Reset () {
  88. Clear(clearAtlasAsset: true);
  89. }
  90. public override void Clear (bool clearAtlasAsset = false) {
  91. if (clearAtlasAsset) atlasAsset = null;
  92. placeholderMap = null;
  93. loadedDataAtMaterial = null;
  94. }
  95. public override string GetPlaceholderTextureName (string originalTextureName) {
  96. return originalTextureName + "_low";
  97. }
  98. public override bool AssignPlaceholderTextures (out IEnumerable<Material> modifiedMaterials) {
  99. modifiedMaterials = null;
  100. if (!atlasAsset) return false;
  101. int materialIndex = 0;
  102. foreach (Material targetMaterial in atlasAsset.Materials) {
  103. if (materialIndex >= placeholderMap.Length) {
  104. Debug.LogError(string.Format("Failed to assign placeholder textures at {0}, material #{1} {2}. " +
  105. "It seems like the GenericOnDemandTextureLoader asset was not setup accordingly for the AtlasAsset.",
  106. atlasAsset, materialIndex + 1, targetMaterial), this);
  107. return false;
  108. }
  109. Texture activeTexture = targetMaterial.mainTexture;
  110. int textureIndex = 0; // Todo: currently only main texture is supported.
  111. int mapIndex = materialIndex;
  112. #if UNITY_EDITOR
  113. if (!Application.isPlaying) {
  114. int foundMapIndex = Array.FindIndex(placeholderMap,
  115. entry => entry.textures[textureIndex].targetTextureReference.EditorTexture == activeTexture);
  116. if (foundMapIndex >= 0)
  117. mapIndex = foundMapIndex;
  118. }
  119. #endif
  120. Texture placeholderTexture = placeholderMap[mapIndex].textures[textureIndex].placeholderTexture;
  121. if (placeholderTexture == null) {
  122. Debug.LogWarning(string.Format("Placeholder texture set to null at {0}, for material #{1} {2}. " +
  123. "It seems like the GenericOnDemandTextureLoader asset was not setup accordingly for the AtlasAsset.",
  124. atlasAsset, materialIndex + 1, targetMaterial), this);
  125. } else {
  126. targetMaterial.mainTexture = placeholderTexture;
  127. }
  128. ++materialIndex;
  129. }
  130. modifiedMaterials = atlasAsset.Materials;
  131. return true;
  132. }
  133. public override bool HasPlaceholderTexturesAssigned (out List<Material> placeholderMaterials) {
  134. placeholderMaterials = null;
  135. if (!atlasAsset) return false;
  136. bool anyPlaceholderAssigned = false;
  137. int materialIndex = 0;
  138. foreach (Material material in atlasAsset.Materials) {
  139. if (materialIndex >= placeholderMap.Length)
  140. return false;
  141. bool hasPlaceholderAssigned = HasPlaceholderAssigned(material);
  142. if (hasPlaceholderAssigned) {
  143. anyPlaceholderAssigned = true;
  144. if (placeholderMaterials == null) placeholderMaterials = new List<Material>();
  145. placeholderMaterials.Add(material);
  146. }
  147. materialIndex++;
  148. }
  149. return anyPlaceholderAssigned;
  150. }
  151. public override bool AssignTargetTextures (out IEnumerable<Material> modifiedMaterials) {
  152. modifiedMaterials = null;
  153. if (!atlasAsset) return false;
  154. BeginCustomTextureLoading();
  155. int i = 0;
  156. foreach (Material targetMaterial in atlasAsset.Materials) {
  157. if (i >= placeholderMap.Length) {
  158. Debug.LogError(string.Format("Failed to assign target textures at {0}, material #{1} {2}. " +
  159. "It seems like the OnDemandTextureLoader asset was not setup accordingly for the AtlasAsset.",
  160. atlasAsset, i + 1, targetMaterial), this);
  161. return false;
  162. }
  163. AssignTargetTextures(targetMaterial, i);
  164. ++i;
  165. }
  166. modifiedMaterials = atlasAsset.Materials;
  167. EndCustomTextureLoading();
  168. return true;
  169. }
  170. public override void BeginCustomTextureLoading () {
  171. if (loadedDataAtMaterial == null || (loadedDataAtMaterial.Length == 0 && placeholderMap.Length > 0)) {
  172. loadedDataAtMaterial = new MaterialOnDemandData[placeholderMap.Length];
  173. for (int i = 0, count = loadedDataAtMaterial.Length; i < count; ++i) {
  174. loadedDataAtMaterial[i].lastFrameRequested = -1;
  175. PlaceholderTextureMapping[] textures = placeholderMap[i].textures;
  176. if (textures == null)
  177. continue;
  178. int texturesAtMaterial = textures.Length;
  179. loadedDataAtMaterial[i].textureRequests = new TextureRequest[texturesAtMaterial];
  180. }
  181. }
  182. }
  183. public override void EndCustomTextureLoading () {
  184. #if UNITY_EDITOR
  185. if (!Application.isPlaying)
  186. return;
  187. #endif
  188. UnloadUnusedTextures();
  189. }
  190. public override bool HasPlaceholderAssigned (Material material) {
  191. Texture currentTexture = material.mainTexture;
  192. int textureIndex = 0; // Todo: currently only main texture is supported.
  193. int foundMaterialIndex = Array.FindIndex(placeholderMap, entry => entry.textures[textureIndex].placeholderTexture == currentTexture);
  194. return foundMaterialIndex >= 0;
  195. }
  196. public override void RequestLoadMaterialTextures (Material material, ref Material overrideMaterial) {
  197. if (!material || !material.mainTexture) return;
  198. Texture currentTexture = material.mainTexture;
  199. int textureIndex = 0; // Todo: currently only main texture is supported.
  200. int foundMaterialIndex = Array.FindIndex(placeholderMap, entry => entry.textures[textureIndex].placeholderTexture == currentTexture);
  201. if (foundMaterialIndex >= 0)
  202. RequestLoadTexture(material, foundMaterialIndex, textureIndex, null);
  203. int loadedMaterialIndex = Array.FindIndex(loadedDataAtMaterial, entry =>
  204. entry.textureRequests[textureIndex].WasRequested &&
  205. entry.textureRequests[textureIndex].IsTarget(currentTexture));
  206. if (loadedMaterialIndex >= 0)
  207. loadedDataAtMaterial[loadedMaterialIndex].lastFrameRequested = Time.frameCount;
  208. }
  209. public override void RequestLoadTexture (Texture placeholderTexture, ref Texture replacementTexture,
  210. System.Action<Texture> onTextureLoaded = null) {
  211. if (placeholderTexture == null) return;
  212. Texture currentTexture = placeholderTexture;
  213. int textureIndex = 0; // Todo: currently only main texture is supported.
  214. int foundMaterialIndex = Array.FindIndex(placeholderMap, entry => entry.textures[textureIndex].placeholderTexture == currentTexture);
  215. if (foundMaterialIndex >= 0) {
  216. Material material = atlasAsset.Materials.ElementAt(foundMaterialIndex);
  217. Texture loadedTexture = RequestLoadTexture(material, foundMaterialIndex, textureIndex, onTextureLoaded);
  218. if (loadedTexture != null)
  219. replacementTexture = loadedTexture;
  220. }
  221. int loadedMaterialIndex = Array.FindIndex(loadedDataAtMaterial, entry =>
  222. entry.textureRequests[textureIndex].WasRequested &&
  223. entry.textureRequests[textureIndex].IsTarget(placeholderTexture));
  224. if (loadedMaterialIndex >= 0)
  225. loadedDataAtMaterial[loadedMaterialIndex].lastFrameRequested = Time.frameCount;
  226. }
  227. protected void AssignTargetTextures (Material material, int materialIndex) {
  228. int textureIndex = 0; // Todo: currently only main texture is supported.
  229. RequestLoadTexture(material, materialIndex, textureIndex, null);
  230. }
  231. protected virtual Texture RequestLoadTexture (Material material, int materialIndex, int textureIndex,
  232. System.Action<Texture> onTextureLoaded) {
  233. PlaceholderTextureMapping[] placeholderTextures = placeholderMap[materialIndex].textures;
  234. if (placeholderTextures == null || textureIndex >= placeholderTextures.Length)
  235. return null;
  236. TargetReference targetReference = placeholderTextures[textureIndex].targetTextureReference;
  237. loadedDataAtMaterial[materialIndex].lastFrameRequested = Time.frameCount;
  238. #if UNITY_EDITOR
  239. if (!Application.isPlaying) {
  240. if (targetReference.EditorTexture != null) {
  241. material.mainTexture = targetReference.EditorTexture;
  242. if (onTextureLoaded != null) onTextureLoaded(targetReference.EditorTexture);
  243. }
  244. return targetReference.EditorTexture;
  245. }
  246. #endif
  247. MaterialOnDemandData materialData = loadedDataAtMaterial[materialIndex];
  248. if (materialData.textureRequests[textureIndex].WasRequested) {
  249. Texture loadedTexture = GetAlreadyLoadedTexture(materialIndex, textureIndex);
  250. if (loadedTexture != null) {
  251. material.mainTexture = loadedTexture;
  252. if (onTextureLoaded != null) onTextureLoaded(loadedTexture);
  253. }
  254. return loadedTexture;
  255. }
  256. CreateTextureRequest(targetReference, materialData, textureIndex, material, onTextureLoaded);
  257. return null;
  258. }
  259. public abstract Texture GetAlreadyLoadedTexture (int materialIndex, int textureIndex);
  260. public abstract void CreateTextureRequest (TargetReference targetReference,
  261. MaterialOnDemandData materialData, int textureIndex, Material materialToUpdate,
  262. System.Action<Texture> onTextureLoaded);
  263. public virtual void UnloadUnusedTextures () {
  264. int currentFrameCount = Time.frameCount;
  265. float timePerFrame = Time.smoothDeltaTime;
  266. float deltaFramesToUnload = unloadAfterSecondsUnused / timePerFrame;
  267. for (int materialIndex = 0, materialCount = loadedDataAtMaterial.Length; materialIndex < materialCount; ++materialIndex) {
  268. MaterialOnDemandData materialData = loadedDataAtMaterial[materialIndex];
  269. int textureCount = materialData.textureRequests.Length;
  270. for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex) {
  271. TextureRequest textureRequest = materialData.textureRequests[textureIndex];
  272. if (textureRequest.WasSuccessfullyLoaded &&
  273. currentFrameCount - materialData.lastFrameRequested > deltaFramesToUnload) {
  274. RequestUnloadTexture(materialIndex, textureIndex);
  275. }
  276. }
  277. }
  278. }
  279. public virtual void RequestUnloadTexture (int materialIndex, int textureIndex) {
  280. if (materialIndex >= loadedDataAtMaterial.Length) return;
  281. bool wasReleased = false;
  282. PlaceholderTextureMapping[] placeholderTextures = placeholderMap[materialIndex].textures;
  283. MaterialOnDemandData materialData = loadedDataAtMaterial[materialIndex];
  284. if (materialData.textureRequests[textureIndex].WasRequested) {
  285. materialData.textureRequests[textureIndex].Release();
  286. wasReleased = true;
  287. }
  288. // reset material textures to placeholder textures.
  289. Material targetMaterial = atlasAsset.Materials.ElementAt(materialIndex);
  290. if (targetMaterial) {
  291. targetMaterial.mainTexture = placeholderTextures[textureIndex].placeholderTexture;
  292. if (wasReleased)
  293. OnTextureUnloaded(targetMaterial, textureIndex);
  294. }
  295. }
  296. public int maxPlaceholderSize = 128;
  297. public float unloadAfterSecondsUnused = 60.0f;
  298. /// <summary>A map from placeholder to on-demand-loaded target textures.
  299. /// This array holds PlaceholderMaterialMapping for each Material,
  300. /// where each <c>PlaceholderMaterialMapping.textures</c> contains a Texture-to-TextureReference mapping
  301. /// for each Texture at the Material.</summary>
  302. public PlaceholderMaterialMapping[] placeholderMap;
  303. /// <summary>An array holding loaded data for each Material.</summary>
  304. protected MaterialOnDemandData[] loadedDataAtMaterial;
  305. }
  306. }
  307. #endif