Без опису
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

SpriteSkinUtility.cs 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. using System;
  2. using Unity.Burst;
  3. using Unity.Collections;
  4. using Unity.Mathematics;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using UnityEngine.Rendering;
  7. using UnityEngine.U2D.Common;
  8. #if ENABLE_URP
  9. using UnityEngine.Rendering.Universal;
  10. #endif
  11. namespace UnityEngine.U2D.Animation
  12. {
  13. internal class NativeByteArray
  14. {
  15. public int Length => array.Length;
  16. public bool IsCreated => array.IsCreated;
  17. public byte this[int index] => array[index];
  18. public NativeArray<byte> array
  19. { get; }
  20. public NativeByteArray(NativeArray<byte> array)
  21. {
  22. this.array = array;
  23. }
  24. public void Dispose() => array.Dispose();
  25. }
  26. internal static class SpriteSkinUtility
  27. {
  28. internal static bool CanUseGpuDeformation()
  29. {
  30. return SystemInfo.supportsComputeShaders;
  31. }
  32. internal static bool IsUsingGpuDeformation()
  33. {
  34. #if ENABLE_URP
  35. return CanUseGpuDeformation() &&
  36. GraphicsSettings.currentRenderPipeline != null &&
  37. UniversalRenderPipeline.asset.useSRPBatcher &&
  38. InternalEngineBridge.IsGPUSkinningEnabled();
  39. #else
  40. return false;
  41. #endif
  42. }
  43. internal static bool CanSpriteSkinUseGpuDeformation(SpriteSkin spriteSkin)
  44. {
  45. return IsUsingGpuDeformation() &&
  46. GpuDeformationSystem.DoesShaderSupportGpuDeformation(spriteSkin.spriteRenderer.sharedMaterial);
  47. }
  48. internal static SpriteSkinState Validate(this SpriteSkin spriteSkin)
  49. {
  50. var sprite = spriteSkin.sprite;
  51. if (sprite == null)
  52. return SpriteSkinState.SpriteNotFound;
  53. var bindPoses = sprite.GetBindPoses();
  54. var bindPoseCount = bindPoses.Length;
  55. if (bindPoseCount == 0)
  56. return SpriteSkinState.SpriteHasNoSkinningInformation;
  57. if (spriteSkin.rootBone == null)
  58. return SpriteSkinState.RootTransformNotFound;
  59. if (spriteSkin.boneTransforms == null)
  60. return SpriteSkinState.InvalidTransformArray;
  61. if (bindPoseCount != spriteSkin.boneTransforms.Length)
  62. return SpriteSkinState.InvalidTransformArrayLength;
  63. foreach (var boneTransform in spriteSkin.boneTransforms)
  64. {
  65. if (boneTransform == null)
  66. return SpriteSkinState.TransformArrayContainsNull;
  67. }
  68. var boneWeights = spriteSkin.spriteBoneWeights;
  69. if (!BurstedSpriteSkinUtilities.ValidateBoneWeights(in boneWeights, bindPoseCount))
  70. return SpriteSkinState.InvalidBoneWeights;
  71. return SpriteSkinState.Ready;
  72. }
  73. internal static void CreateBoneHierarchy(this SpriteSkin spriteSkin)
  74. {
  75. if (spriteSkin.spriteRenderer.sprite == null)
  76. throw new InvalidOperationException("SpriteRenderer has no Sprite set");
  77. var spriteBones = spriteSkin.spriteRenderer.sprite.GetBones();
  78. var transforms = new Transform[spriteBones.Length];
  79. Transform root = null;
  80. for (var i = 0; i < spriteBones.Length; ++i)
  81. {
  82. CreateGameObject(i, spriteBones, transforms, spriteSkin.transform);
  83. if (spriteBones[i].parentId < 0 && root == null)
  84. root = transforms[i];
  85. }
  86. spriteSkin.SetRootBone(root);
  87. spriteSkin.SetBoneTransforms(transforms);
  88. }
  89. internal static int GetVertexStreamSize(this Sprite sprite)
  90. {
  91. var vertexStreamSize = 12;
  92. if (sprite.HasVertexAttribute(Rendering.VertexAttribute.Normal))
  93. vertexStreamSize = vertexStreamSize + 12;
  94. if (sprite.HasVertexAttribute(Rendering.VertexAttribute.Tangent))
  95. vertexStreamSize = vertexStreamSize + 16;
  96. return vertexStreamSize;
  97. }
  98. internal static int GetVertexStreamOffset(this Sprite sprite, Rendering.VertexAttribute channel )
  99. {
  100. var hasPosition = sprite.HasVertexAttribute(Rendering.VertexAttribute.Position);
  101. var hasNormals = sprite.HasVertexAttribute(Rendering.VertexAttribute.Normal);
  102. var hasTangents = sprite.HasVertexAttribute(Rendering.VertexAttribute.Tangent);
  103. switch(channel)
  104. {
  105. case Rendering.VertexAttribute.Position:
  106. return hasPosition ? 0 : -1;
  107. case Rendering.VertexAttribute.Normal:
  108. return hasNormals ? 12 : -1;
  109. case Rendering.VertexAttribute.Tangent:
  110. return hasTangents ? (hasNormals ? 24 : 12) : -1;
  111. }
  112. return -1;
  113. }
  114. static void CreateGameObject(int index, SpriteBone[] spriteBones, Transform[] transforms, Transform root)
  115. {
  116. if (transforms[index] == null)
  117. {
  118. var spriteBone = spriteBones[index];
  119. if (spriteBone.parentId >= 0)
  120. CreateGameObject(spriteBone.parentId, spriteBones, transforms, root);
  121. var go = new GameObject(spriteBone.name);
  122. var transform = go.transform;
  123. if (spriteBone.parentId >= 0)
  124. transform.SetParent(transforms[spriteBone.parentId]);
  125. else
  126. transform.SetParent(root);
  127. transform.localPosition = spriteBone.position;
  128. transform.localRotation = spriteBone.rotation;
  129. transform.localScale = Vector3.one;
  130. transforms[index] = transform;
  131. }
  132. }
  133. static int GetHash(Matrix4x4 matrix)
  134. {
  135. unsafe
  136. {
  137. var b = (uint*)&matrix;
  138. {
  139. var c = (char*)b;
  140. return (int)math.hash(c, 16 * sizeof(float));
  141. }
  142. }
  143. }
  144. internal static int CalculateTransformHash(this SpriteSkin spriteSkin)
  145. {
  146. var bits = 0;
  147. var boneTransformHash = GetHash(spriteSkin.transform.localToWorldMatrix) >> bits;
  148. bits++;
  149. foreach (var transform in spriteSkin.boneTransforms)
  150. {
  151. boneTransformHash ^= GetHash(transform.localToWorldMatrix) >> bits;
  152. bits = (bits + 1) % 8;
  153. }
  154. return boneTransformHash;
  155. }
  156. internal unsafe static void Deform(Sprite sprite, Matrix4x4 rootInv, NativeSlice<Vector3> vertices, NativeSlice<Vector4> tangents, NativeSlice<BoneWeight> boneWeights, NativeArray<Matrix4x4> boneTransforms, NativeSlice<Matrix4x4> bindPoses, NativeArray<byte> deformableVertices)
  157. {
  158. var verticesFloat3 = vertices.SliceWithStride<float3>();
  159. var tangentsFloat4 = tangents.SliceWithStride<float4>();
  160. var bindPosesFloat4x4 = bindPoses.SliceWithStride<float4x4>();
  161. var spriteVertexCount = sprite.GetVertexCount();
  162. var spriteVertexStreamSize = sprite.GetVertexStreamSize();
  163. var boneTransformsFloat4x4 = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float4x4>(boneTransforms.GetUnsafePtr(), boneTransforms.Length, Allocator.None);
  164. byte* deformedPosOffset = (byte*)NativeArrayUnsafeUtility.GetUnsafePtr(deformableVertices);
  165. NativeSlice<float3> deformableVerticesFloat3 = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<float3>(deformedPosOffset, spriteVertexStreamSize, spriteVertexCount);
  166. NativeSlice<float4> deformableTangentsFloat4 = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<float4>(deformedPosOffset, spriteVertexStreamSize, 1); // Just Dummy.
  167. if (sprite.HasVertexAttribute(Rendering.VertexAttribute.Tangent))
  168. {
  169. byte* deformedTanOffset = deformedPosOffset + sprite.GetVertexStreamOffset(Rendering.VertexAttribute.Tangent);
  170. deformableTangentsFloat4 = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<float4>(deformedTanOffset, spriteVertexStreamSize, spriteVertexCount);
  171. }
  172. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  173. var handle1 = CreateSafetyChecks<float4x4>(ref boneTransformsFloat4x4);
  174. var handle2 = CreateSafetyChecks<float3>(ref deformableVerticesFloat3);
  175. var handle3 = CreateSafetyChecks<float4>(ref deformableTangentsFloat4);
  176. #endif
  177. if (sprite.HasVertexAttribute(Rendering.VertexAttribute.Tangent))
  178. Deform(rootInv, verticesFloat3, tangentsFloat4, boneWeights, boneTransformsFloat4x4, bindPosesFloat4x4, deformableVerticesFloat3, deformableTangentsFloat4);
  179. else
  180. Deform(rootInv, verticesFloat3, boneWeights, boneTransformsFloat4x4, bindPosesFloat4x4, deformableVerticesFloat3);
  181. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  182. DisposeSafetyChecks(handle1);
  183. DisposeSafetyChecks(handle2);
  184. DisposeSafetyChecks(handle3);
  185. #endif
  186. }
  187. internal static void Deform(float4x4 rootInv, NativeSlice<float3> vertices, NativeSlice<BoneWeight> boneWeights, NativeArray<float4x4> boneTransforms, NativeSlice<float4x4> bindPoses, NativeSlice<float3> deformed)
  188. {
  189. if (boneTransforms.Length == 0)
  190. return;
  191. for (var i = 0; i < boneTransforms.Length; i++)
  192. {
  193. var bindPoseMat = bindPoses[i];
  194. var boneTransformMat = boneTransforms[i];
  195. boneTransforms[i] = math.mul(rootInv, math.mul(boneTransformMat, bindPoseMat));
  196. }
  197. for (var i = 0; i < vertices.Length; i++)
  198. {
  199. var bone0 = boneWeights[i].boneIndex0;
  200. var bone1 = boneWeights[i].boneIndex1;
  201. var bone2 = boneWeights[i].boneIndex2;
  202. var bone3 = boneWeights[i].boneIndex3;
  203. var vertex = vertices[i];
  204. deformed[i] =
  205. math.transform(boneTransforms[bone0], vertex) * boneWeights[i].weight0 +
  206. math.transform(boneTransforms[bone1], vertex) * boneWeights[i].weight1 +
  207. math.transform(boneTransforms[bone2], vertex) * boneWeights[i].weight2 +
  208. math.transform(boneTransforms[bone3], vertex) * boneWeights[i].weight3;
  209. }
  210. }
  211. internal static void Deform(float4x4 rootInv, NativeSlice<float3> vertices, NativeSlice<float4> tangents, NativeSlice<BoneWeight> boneWeights, NativeArray<float4x4> boneTransforms, NativeSlice<float4x4> bindPoses, NativeSlice<float3> deformed, NativeSlice<float4> deformedTangents)
  212. {
  213. if(boneTransforms.Length == 0)
  214. return;
  215. for (var i = 0; i < boneTransforms.Length; i++)
  216. {
  217. var bindPoseMat = bindPoses[i];
  218. var boneTransformMat = boneTransforms[i];
  219. boneTransforms[i] = math.mul(rootInv, math.mul(boneTransformMat, bindPoseMat));
  220. }
  221. for (var i = 0; i < vertices.Length; i++)
  222. {
  223. var bone0 = boneWeights[i].boneIndex0;
  224. var bone1 = boneWeights[i].boneIndex1;
  225. var bone2 = boneWeights[i].boneIndex2;
  226. var bone3 = boneWeights[i].boneIndex3;
  227. var vertex = vertices[i];
  228. deformed[i] =
  229. math.transform(boneTransforms[bone0], vertex) * boneWeights[i].weight0 +
  230. math.transform(boneTransforms[bone1], vertex) * boneWeights[i].weight1 +
  231. math.transform(boneTransforms[bone2], vertex) * boneWeights[i].weight2 +
  232. math.transform(boneTransforms[bone3], vertex) * boneWeights[i].weight3;
  233. var tangent = new float4(tangents[i].xyz, 0.0f);
  234. tangent =
  235. math.mul(boneTransforms[bone0], tangent) * boneWeights[i].weight0 +
  236. math.mul(boneTransforms[bone1], tangent) * boneWeights[i].weight1 +
  237. math.mul(boneTransforms[bone2], tangent) * boneWeights[i].weight2 +
  238. math.mul(boneTransforms[bone3], tangent) * boneWeights[i].weight3;
  239. deformedTangents[i] = new float4(math.normalize(tangent.xyz), tangents[i].w);
  240. }
  241. }
  242. internal static void Deform(Sprite sprite, Matrix4x4 invRoot, Transform[] boneTransformsArray, NativeArray<byte> deformVertexData)
  243. {
  244. Debug.Assert(sprite != null);
  245. Debug.Assert(sprite.GetVertexCount() == (deformVertexData.Length / sprite.GetVertexStreamSize()));
  246. var vertices = sprite.GetVertexAttribute<Vector3>(UnityEngine.Rendering.VertexAttribute.Position);
  247. var tangents = sprite.GetVertexAttribute<Vector4>(UnityEngine.Rendering.VertexAttribute.Tangent);
  248. var boneWeights = sprite.GetVertexAttribute<BoneWeight>(UnityEngine.Rendering.VertexAttribute.BlendWeight);
  249. var bindPoses = sprite.GetBindPoses();
  250. Debug.Assert(bindPoses.Length == boneTransformsArray.Length);
  251. Debug.Assert(boneWeights.Length == sprite.GetVertexCount());
  252. var boneTransforms = new NativeArray<Matrix4x4>(boneTransformsArray.Length, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
  253. for (var i = 0; i < boneTransformsArray.Length; ++i)
  254. boneTransforms[i] = boneTransformsArray[i].localToWorldMatrix;
  255. Deform(sprite, invRoot, vertices, tangents, boneWeights, boneTransforms, bindPoses, deformVertexData);
  256. boneTransforms.Dispose();
  257. }
  258. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  259. static AtomicSafetyHandle CreateSafetyChecks<T>(ref NativeArray<T> array) where T : struct
  260. {
  261. var handle = AtomicSafetyHandle.Create();
  262. AtomicSafetyHandle.SetAllowSecondaryVersionWriting(handle, true);
  263. AtomicSafetyHandle.UseSecondaryVersion(ref handle);
  264. NativeArrayUnsafeUtility.SetAtomicSafetyHandle<T>(ref array, handle);
  265. return handle;
  266. }
  267. static AtomicSafetyHandle CreateSafetyChecks<T>(ref NativeSlice<T> array) where T : struct
  268. {
  269. var handle = AtomicSafetyHandle.Create();
  270. AtomicSafetyHandle.SetAllowSecondaryVersionWriting(handle, true);
  271. AtomicSafetyHandle.UseSecondaryVersion(ref handle);
  272. NativeSliceUnsafeUtility.SetAtomicSafetyHandle<T>(ref array, handle);
  273. return handle;
  274. }
  275. static void DisposeSafetyChecks(AtomicSafetyHandle handle)
  276. {
  277. AtomicSafetyHandle.Release(handle);
  278. }
  279. #endif
  280. internal static void Bake(this SpriteSkin spriteSkin, NativeArray<byte> deformVertexData)
  281. {
  282. if (!spriteSkin.isValid)
  283. throw new Exception("Bake error: invalid SpriteSkin");
  284. var sprite = spriteSkin.spriteRenderer.sprite;
  285. var boneTransformsArray = spriteSkin.boneTransforms;
  286. Deform(sprite, Matrix4x4.identity, boneTransformsArray, deformVertexData);
  287. }
  288. internal static unsafe void CalculateBounds(this SpriteSkin spriteSkin)
  289. {
  290. Debug.Assert(spriteSkin.isValid);
  291. var sprite = spriteSkin.sprite;
  292. var deformVertexData = new NativeArray<byte>(sprite.GetVertexStreamSize() * sprite.GetVertexCount(), Allocator.Temp, NativeArrayOptions.UninitializedMemory);
  293. var dataPtr = deformVertexData.GetUnsafePtr();
  294. var deformedPosSlice = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<Vector3>(dataPtr, sprite.GetVertexStreamSize(), sprite.GetVertexCount());
  295. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  296. NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref deformedPosSlice, NativeArrayUnsafeUtility.GetAtomicSafetyHandle(deformVertexData));
  297. #endif
  298. spriteSkin.Bake(deformVertexData);
  299. UpdateBounds(spriteSkin, deformVertexData);
  300. deformVertexData.Dispose();
  301. }
  302. internal static Bounds CalculateSpriteSkinBounds(NativeSlice<float3> deformablePositions)
  303. {
  304. var min = deformablePositions[0];
  305. var max = deformablePositions[0];
  306. for (int j = 1; j < deformablePositions.Length; ++j)
  307. {
  308. min = math.min(min, deformablePositions[j]);
  309. max = math.max(max, deformablePositions[j]);
  310. }
  311. var ext = (max - min) * 0.5F;
  312. var ctr = min + ext;
  313. var bounds = new Bounds();
  314. bounds.center = ctr;
  315. bounds.extents = ext;
  316. return bounds;
  317. }
  318. internal static unsafe void UpdateBounds(this SpriteSkin spriteSkin, NativeArray<byte> deformedVertices)
  319. {
  320. var deformedPosOffset = (byte*)NativeArrayUnsafeUtility.GetUnsafePtr(deformedVertices);
  321. var spriteVertexCount = spriteSkin.sprite.GetVertexCount();
  322. var spriteVertexStreamSize = spriteSkin.sprite.GetVertexStreamSize();
  323. var deformedPositions = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<float3>(deformedPosOffset, spriteVertexStreamSize, spriteVertexCount);
  324. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  325. var handle = CreateSafetyChecks<float3>(ref deformedPositions);
  326. #endif
  327. spriteSkin.bounds = CalculateSpriteSkinBounds(deformedPositions);
  328. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  329. DisposeSafetyChecks(handle);
  330. #endif
  331. InternalEngineBridge.SetLocalAABB(spriteSkin.spriteRenderer, spriteSkin.bounds);
  332. }
  333. }
  334. [BurstCompile]
  335. internal static class BurstedSpriteSkinUtilities
  336. {
  337. [BurstCompile]
  338. internal static bool ValidateBoneWeights(in NativeCustomSlice<BoneWeight> boneWeights, int bindPoseCount)
  339. {
  340. var boneWeightCount = boneWeights.Length;
  341. for (var i = 0; i < boneWeightCount; ++i)
  342. {
  343. var boneWeight = boneWeights[i];
  344. var idx0 = boneWeight.boneIndex0;
  345. var idx1 = boneWeight.boneIndex1;
  346. var idx2 = boneWeight.boneIndex2;
  347. var idx3 = boneWeight.boneIndex3;
  348. if ((idx0 < 0 || idx0 >= bindPoseCount) ||
  349. (idx1 < 0 || idx1 >= bindPoseCount) ||
  350. (idx2 < 0 || idx2 >= bindPoseCount) ||
  351. (idx3 < 0 || idx3 >= bindPoseCount))
  352. return false;
  353. }
  354. return true;
  355. }
  356. [BurstCompile]
  357. internal static void SetVertexPositionFromByteBuffer(in NativeArray<byte> buffer, in NativeArray<int> indices, ref NativeArray<Vector3> vertices, int stride)
  358. {
  359. unsafe
  360. {
  361. var bufferPtr = (byte*)buffer.GetUnsafeReadOnlyPtr();
  362. for (var i = 0; i < indices.Length; ++i)
  363. {
  364. var index = indices[i];
  365. var vertexPtr = (Vector3*)(bufferPtr + (index * stride));
  366. vertices[index] = *vertexPtr;
  367. }
  368. }
  369. }
  370. }
  371. }