SkeletonJson.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, 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
  13. * or 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
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #if (UNITY_5 || UNITY_5_3_OR_NEWER || UNITY_WSA || UNITY_WP8 || UNITY_WP8_1)
  30. #define IS_UNITY
  31. #endif
  32. using System;
  33. using System.IO;
  34. using System.Collections.Generic;
  35. #if WINDOWS_STOREAPP
  36. using System.Threading.Tasks;
  37. using Windows.Storage;
  38. #endif
  39. namespace Spine {
  40. public class SkeletonJson {
  41. public float Scale { get; set; }
  42. private AttachmentLoader attachmentLoader;
  43. private List<LinkedMesh> linkedMeshes = new List<LinkedMesh>();
  44. public SkeletonJson (params Atlas[] atlasArray)
  45. : this(new AtlasAttachmentLoader(atlasArray)) {
  46. }
  47. public SkeletonJson (AttachmentLoader attachmentLoader) {
  48. if (attachmentLoader == null) throw new ArgumentNullException("attachmentLoader", "attachmentLoader cannot be null.");
  49. this.attachmentLoader = attachmentLoader;
  50. Scale = 1;
  51. }
  52. #if !IS_UNITY && WINDOWS_STOREAPP
  53. private async Task<SkeletonData> ReadFile(string path) {
  54. var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
  55. var file = await folder.GetFileAsync(path).AsTask().ConfigureAwait(false);
  56. using (var reader = new StreamReader(await file.OpenStreamForReadAsync().ConfigureAwait(false))) {
  57. SkeletonData skeletonData = ReadSkeletonData(reader);
  58. skeletonData.Name = Path.GetFileNameWithoutExtension(path);
  59. return skeletonData;
  60. }
  61. }
  62. public SkeletonData ReadSkeletonData (string path) {
  63. return this.ReadFile(path).Result;
  64. }
  65. #else
  66. public SkeletonData ReadSkeletonData (string path) {
  67. #if WINDOWS_PHONE
  68. using (var reader = new StreamReader(Microsoft.Xna.Framework.TitleContainer.OpenStream(path))) {
  69. #else
  70. using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))) {
  71. #endif
  72. SkeletonData skeletonData = ReadSkeletonData(reader);
  73. skeletonData.name = Path.GetFileNameWithoutExtension(path);
  74. return skeletonData;
  75. }
  76. }
  77. #endif
  78. public SkeletonData ReadSkeletonData (TextReader reader) {
  79. if (reader == null) throw new ArgumentNullException("reader", "reader cannot be null.");
  80. float scale = this.Scale;
  81. var skeletonData = new SkeletonData();
  82. var root = Json.Deserialize(reader) as Dictionary<string, Object>;
  83. if (root == null) throw new Exception("Invalid JSON.");
  84. // Skeleton.
  85. if (root.ContainsKey("skeleton")) {
  86. var skeletonMap = (Dictionary<string, Object>)root["skeleton"];
  87. skeletonData.hash = (string)skeletonMap["hash"];
  88. skeletonData.version = (string)skeletonMap["spine"];
  89. if ("3.8.75" == skeletonData.version)
  90. throw new Exception("Unsupported skeleton data, please export with a newer version of Spine.");
  91. skeletonData.x = GetFloat(skeletonMap, "x", 0);
  92. skeletonData.y = GetFloat(skeletonMap, "y", 0);
  93. skeletonData.width = GetFloat(skeletonMap, "width", 0);
  94. skeletonData.height = GetFloat(skeletonMap, "height", 0);
  95. skeletonData.fps = GetFloat(skeletonMap, "fps", 30);
  96. skeletonData.imagesPath = GetString(skeletonMap, "images", null);
  97. skeletonData.audioPath = GetString(skeletonMap, "audio", null);
  98. }
  99. // Bones.
  100. if (root.ContainsKey("bones")) {
  101. foreach (Dictionary<string, Object> boneMap in (List<Object>)root["bones"]) {
  102. BoneData parent = null;
  103. if (boneMap.ContainsKey("parent")) {
  104. parent = skeletonData.FindBone((string)boneMap["parent"]);
  105. if (parent == null)
  106. throw new Exception("Parent bone not found: " + boneMap["parent"]);
  107. }
  108. var data = new BoneData(skeletonData.Bones.Count, (string)boneMap["name"], parent);
  109. data.length = GetFloat(boneMap, "length", 0) * scale;
  110. data.x = GetFloat(boneMap, "x", 0) * scale;
  111. data.y = GetFloat(boneMap, "y", 0) * scale;
  112. data.rotation = GetFloat(boneMap, "rotation", 0);
  113. data.scaleX = GetFloat(boneMap, "scaleX", 1);
  114. data.scaleY = GetFloat(boneMap, "scaleY", 1);
  115. data.shearX = GetFloat(boneMap, "shearX", 0);
  116. data.shearY = GetFloat(boneMap, "shearY", 0);
  117. string tm = GetString(boneMap, "transform", TransformMode.Normal.ToString());
  118. data.transformMode = (TransformMode)Enum.Parse(typeof(TransformMode), tm, true);
  119. data.skinRequired = GetBoolean(boneMap, "skin", false);
  120. skeletonData.bones.Add(data);
  121. }
  122. }
  123. // Slots.
  124. if (root.ContainsKey("slots")) {
  125. foreach (Dictionary<string, Object> slotMap in (List<Object>)root["slots"]) {
  126. var slotName = (string)slotMap["name"];
  127. var boneName = (string)slotMap["bone"];
  128. BoneData boneData = skeletonData.FindBone(boneName);
  129. if (boneData == null) throw new Exception("Slot bone not found: " + boneName);
  130. var data = new SlotData(skeletonData.Slots.Count, slotName, boneData);
  131. if (slotMap.ContainsKey("color")) {
  132. string color = (string)slotMap["color"];
  133. data.r = ToColor(color, 0);
  134. data.g = ToColor(color, 1);
  135. data.b = ToColor(color, 2);
  136. data.a = ToColor(color, 3);
  137. }
  138. if (slotMap.ContainsKey("dark")) {
  139. var color2 = (string)slotMap["dark"];
  140. data.r2 = ToColor(color2, 0, 6); // expectedLength = 6. ie. "RRGGBB"
  141. data.g2 = ToColor(color2, 1, 6);
  142. data.b2 = ToColor(color2, 2, 6);
  143. data.hasSecondColor = true;
  144. }
  145. data.attachmentName = GetString(slotMap, "attachment", null);
  146. if (slotMap.ContainsKey("blend"))
  147. data.blendMode = (BlendMode)Enum.Parse(typeof(BlendMode), (string)slotMap["blend"], true);
  148. else
  149. data.blendMode = BlendMode.Normal;
  150. skeletonData.slots.Add(data);
  151. }
  152. }
  153. // IK constraints.
  154. if (root.ContainsKey("ik")) {
  155. foreach (Dictionary<string, Object> constraintMap in (List<Object>)root["ik"]) {
  156. IkConstraintData data = new IkConstraintData((string)constraintMap["name"]);
  157. data.order = GetInt(constraintMap, "order", 0);
  158. data.skinRequired = GetBoolean(constraintMap,"skin", false);
  159. if (constraintMap.ContainsKey("bones")) {
  160. foreach (string boneName in (List<Object>)constraintMap["bones"]) {
  161. BoneData bone = skeletonData.FindBone(boneName);
  162. if (bone == null) throw new Exception("IK bone not found: " + boneName);
  163. data.bones.Add(bone);
  164. }
  165. }
  166. string targetName = (string)constraintMap["target"];
  167. data.target = skeletonData.FindBone(targetName);
  168. if (data.target == null) throw new Exception("IK target bone not found: " + targetName);
  169. data.mix = GetFloat(constraintMap, "mix", 1);
  170. data.softness = GetFloat(constraintMap, "softness", 0) * scale;
  171. data.bendDirection = GetBoolean(constraintMap, "bendPositive", true) ? 1 : -1;
  172. data.compress = GetBoolean(constraintMap, "compress", false);
  173. data.stretch = GetBoolean(constraintMap, "stretch", false);
  174. data.uniform = GetBoolean(constraintMap, "uniform", false);
  175. skeletonData.ikConstraints.Add(data);
  176. }
  177. }
  178. // Transform constraints.
  179. if (root.ContainsKey("transform")) {
  180. foreach (Dictionary<string, Object> constraintMap in (List<Object>)root["transform"]) {
  181. TransformConstraintData data = new TransformConstraintData((string)constraintMap["name"]);
  182. data.order = GetInt(constraintMap, "order", 0);
  183. data.skinRequired = GetBoolean(constraintMap,"skin", false);
  184. if (constraintMap.ContainsKey("bones")) {
  185. foreach (string boneName in (List<Object>)constraintMap["bones"]) {
  186. BoneData bone = skeletonData.FindBone(boneName);
  187. if (bone == null) throw new Exception("Transform constraint bone not found: " + boneName);
  188. data.bones.Add(bone);
  189. }
  190. }
  191. string targetName = (string)constraintMap["target"];
  192. data.target = skeletonData.FindBone(targetName);
  193. if (data.target == null) throw new Exception("Transform constraint target bone not found: " + targetName);
  194. data.local = GetBoolean(constraintMap, "local", false);
  195. data.relative = GetBoolean(constraintMap, "relative", false);
  196. data.offsetRotation = GetFloat(constraintMap, "rotation", 0);
  197. data.offsetX = GetFloat(constraintMap, "x", 0) * scale;
  198. data.offsetY = GetFloat(constraintMap, "y", 0) * scale;
  199. data.offsetScaleX = GetFloat(constraintMap, "scaleX", 0);
  200. data.offsetScaleY = GetFloat(constraintMap, "scaleY", 0);
  201. data.offsetShearY = GetFloat(constraintMap, "shearY", 0);
  202. data.rotateMix = GetFloat(constraintMap, "rotateMix", 1);
  203. data.translateMix = GetFloat(constraintMap, "translateMix", 1);
  204. data.scaleMix = GetFloat(constraintMap, "scaleMix", 1);
  205. data.shearMix = GetFloat(constraintMap, "shearMix", 1);
  206. skeletonData.transformConstraints.Add(data);
  207. }
  208. }
  209. // Path constraints.
  210. if(root.ContainsKey("path")) {
  211. foreach (Dictionary<string, Object> constraintMap in (List<Object>)root["path"]) {
  212. PathConstraintData data = new PathConstraintData((string)constraintMap["name"]);
  213. data.order = GetInt(constraintMap, "order", 0);
  214. data.skinRequired = GetBoolean(constraintMap,"skin", false);
  215. if (constraintMap.ContainsKey("bones")) {
  216. foreach (string boneName in (List<Object>)constraintMap["bones"]) {
  217. BoneData bone = skeletonData.FindBone(boneName);
  218. if (bone == null) throw new Exception("Path bone not found: " + boneName);
  219. data.bones.Add(bone);
  220. }
  221. }
  222. string targetName = (string)constraintMap["target"];
  223. data.target = skeletonData.FindSlot(targetName);
  224. if (data.target == null) throw new Exception("Path target slot not found: " + targetName);
  225. data.positionMode = (PositionMode)Enum.Parse(typeof(PositionMode), GetString(constraintMap, "positionMode", "percent"), true);
  226. data.spacingMode = (SpacingMode)Enum.Parse(typeof(SpacingMode), GetString(constraintMap, "spacingMode", "length"), true);
  227. data.rotateMode = (RotateMode)Enum.Parse(typeof(RotateMode), GetString(constraintMap, "rotateMode", "tangent"), true);
  228. data.offsetRotation = GetFloat(constraintMap, "rotation", 0);
  229. data.position = GetFloat(constraintMap, "position", 0);
  230. if (data.positionMode == PositionMode.Fixed) data.position *= scale;
  231. data.spacing = GetFloat(constraintMap, "spacing", 0);
  232. if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) data.spacing *= scale;
  233. data.rotateMix = GetFloat(constraintMap, "rotateMix", 1);
  234. data.translateMix = GetFloat(constraintMap, "translateMix", 1);
  235. skeletonData.pathConstraints.Add(data);
  236. }
  237. }
  238. // Skins.
  239. if (root.ContainsKey("skins")) {
  240. foreach (Dictionary<string, object> skinMap in (List<object>)root["skins"]) {
  241. Skin skin = new Skin((string)skinMap["name"]);
  242. if (skinMap.ContainsKey("bones")) {
  243. foreach (string entryName in (List<Object>)skinMap["bones"]) {
  244. BoneData bone = skeletonData.FindBone(entryName);
  245. if (bone == null) throw new Exception("Skin bone not found: " + entryName);
  246. skin.bones.Add(bone);
  247. }
  248. }
  249. if (skinMap.ContainsKey("ik")) {
  250. foreach (string entryName in (List<Object>)skinMap["ik"]) {
  251. IkConstraintData constraint = skeletonData.FindIkConstraint(entryName);
  252. if (constraint == null) throw new Exception("Skin IK constraint not found: " + entryName);
  253. skin.constraints.Add(constraint);
  254. }
  255. }
  256. if (skinMap.ContainsKey("transform")) {
  257. foreach (string entryName in (List<Object>)skinMap["transform"]) {
  258. TransformConstraintData constraint = skeletonData.FindTransformConstraint(entryName);
  259. if (constraint == null) throw new Exception("Skin transform constraint not found: " + entryName);
  260. skin.constraints.Add(constraint);
  261. }
  262. }
  263. if (skinMap.ContainsKey("path")) {
  264. foreach (string entryName in (List<Object>)skinMap["path"]) {
  265. PathConstraintData constraint = skeletonData.FindPathConstraint(entryName);
  266. if (constraint == null) throw new Exception("Skin path constraint not found: " + entryName);
  267. skin.constraints.Add(constraint);
  268. }
  269. }
  270. if (skinMap.ContainsKey("attachments")) {
  271. foreach (KeyValuePair<string, Object> slotEntry in (Dictionary<string, Object>)skinMap["attachments"]) {
  272. int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key);
  273. foreach (KeyValuePair<string, Object> entry in ((Dictionary<string, Object>)slotEntry.Value)) {
  274. try {
  275. Attachment attachment = ReadAttachment((Dictionary<string, Object>)entry.Value, skin, slotIndex, entry.Key, skeletonData);
  276. if (attachment != null) skin.SetAttachment(slotIndex, entry.Key, attachment);
  277. } catch (Exception e) {
  278. throw new Exception("Error reading attachment: " + entry.Key + ", skin: " + skin, e);
  279. }
  280. }
  281. }
  282. }
  283. skeletonData.skins.Add(skin);
  284. if (skin.name == "default") skeletonData.defaultSkin = skin;
  285. }
  286. }
  287. // Linked meshes.
  288. for (int i = 0, n = linkedMeshes.Count; i < n; i++) {
  289. LinkedMesh linkedMesh = linkedMeshes[i];
  290. Skin skin = linkedMesh.skin == null ? skeletonData.defaultSkin : skeletonData.FindSkin(linkedMesh.skin);
  291. if (skin == null) throw new Exception("Slot not found: " + linkedMesh.skin);
  292. Attachment parent = skin.GetAttachment(linkedMesh.slotIndex, linkedMesh.parent);
  293. if (parent == null) throw new Exception("Parent mesh not found: " + linkedMesh.parent);
  294. linkedMesh.mesh.DeformAttachment = linkedMesh.inheritDeform ? (VertexAttachment)parent : linkedMesh.mesh;
  295. linkedMesh.mesh.ParentMesh = (MeshAttachment)parent;
  296. linkedMesh.mesh.UpdateUVs();
  297. }
  298. linkedMeshes.Clear();
  299. // Events.
  300. if (root.ContainsKey("events")) {
  301. foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)root["events"]) {
  302. var entryMap = (Dictionary<string, Object>)entry.Value;
  303. var data = new EventData(entry.Key);
  304. data.Int = GetInt(entryMap, "int", 0);
  305. data.Float = GetFloat(entryMap, "float", 0);
  306. data.String = GetString(entryMap, "string", string.Empty);
  307. data.AudioPath = GetString(entryMap, "audio", null);
  308. if (data.AudioPath != null) {
  309. data.Volume = GetFloat(entryMap, "volume", 1);
  310. data.Balance = GetFloat(entryMap, "balance", 0);
  311. }
  312. skeletonData.events.Add(data);
  313. }
  314. }
  315. // Animations.
  316. if (root.ContainsKey("animations")) {
  317. foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)root["animations"]) {
  318. try {
  319. ReadAnimation((Dictionary<string, Object>)entry.Value, entry.Key, skeletonData);
  320. } catch (Exception e) {
  321. throw new Exception("Error reading animation: " + entry.Key, e);
  322. }
  323. }
  324. }
  325. skeletonData.bones.TrimExcess();
  326. skeletonData.slots.TrimExcess();
  327. skeletonData.skins.TrimExcess();
  328. skeletonData.events.TrimExcess();
  329. skeletonData.animations.TrimExcess();
  330. skeletonData.ikConstraints.TrimExcess();
  331. return skeletonData;
  332. }
  333. private Attachment ReadAttachment (Dictionary<string, Object> map, Skin skin, int slotIndex, string name, SkeletonData skeletonData) {
  334. float scale = this.Scale;
  335. name = GetString(map, "name", name);
  336. var typeName = GetString(map, "type", "region");
  337. var type = (AttachmentType)Enum.Parse(typeof(AttachmentType), typeName, true);
  338. string path = GetString(map, "path", name);
  339. switch (type) {
  340. case AttachmentType.Region:
  341. RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path);
  342. if (region == null) return null;
  343. region.Path = path;
  344. region.x = GetFloat(map, "x", 0) * scale;
  345. region.y = GetFloat(map, "y", 0) * scale;
  346. region.scaleX = GetFloat(map, "scaleX", 1);
  347. region.scaleY = GetFloat(map, "scaleY", 1);
  348. region.rotation = GetFloat(map, "rotation", 0);
  349. region.width = GetFloat(map, "width", 32) * scale;
  350. region.height = GetFloat(map, "height", 32) * scale;
  351. if (map.ContainsKey("color")) {
  352. var color = (string)map["color"];
  353. region.r = ToColor(color, 0);
  354. region.g = ToColor(color, 1);
  355. region.b = ToColor(color, 2);
  356. region.a = ToColor(color, 3);
  357. }
  358. region.UpdateOffset();
  359. return region;
  360. case AttachmentType.Boundingbox:
  361. BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name);
  362. if (box == null) return null;
  363. ReadVertices(map, box, GetInt(map, "vertexCount", 0) << 1);
  364. return box;
  365. case AttachmentType.Mesh:
  366. case AttachmentType.Linkedmesh: {
  367. MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path);
  368. if (mesh == null) return null;
  369. mesh.Path = path;
  370. if (map.ContainsKey("color")) {
  371. var color = (string)map["color"];
  372. mesh.r = ToColor(color, 0);
  373. mesh.g = ToColor(color, 1);
  374. mesh.b = ToColor(color, 2);
  375. mesh.a = ToColor(color, 3);
  376. }
  377. mesh.Width = GetFloat(map, "width", 0) * scale;
  378. mesh.Height = GetFloat(map, "height", 0) * scale;
  379. string parent = GetString(map, "parent", null);
  380. if (parent != null) {
  381. linkedMeshes.Add(new LinkedMesh(mesh, GetString(map, "skin", null), slotIndex, parent, GetBoolean(map, "deform", true)));
  382. return mesh;
  383. }
  384. float[] uvs = GetFloatArray(map, "uvs", 1);
  385. ReadVertices(map, mesh, uvs.Length);
  386. mesh.triangles = GetIntArray(map, "triangles");
  387. mesh.regionUVs = uvs;
  388. mesh.UpdateUVs();
  389. if (map.ContainsKey("hull")) mesh.HullLength = GetInt(map, "hull", 0) * 2;
  390. if (map.ContainsKey("edges")) mesh.Edges = GetIntArray(map, "edges");
  391. return mesh;
  392. }
  393. case AttachmentType.Path: {
  394. PathAttachment pathAttachment = attachmentLoader.NewPathAttachment(skin, name);
  395. if (pathAttachment == null) return null;
  396. pathAttachment.closed = GetBoolean(map, "closed", false);
  397. pathAttachment.constantSpeed = GetBoolean(map, "constantSpeed", true);
  398. int vertexCount = GetInt(map, "vertexCount", 0);
  399. ReadVertices(map, pathAttachment, vertexCount << 1);
  400. // potential BOZO see Java impl
  401. pathAttachment.lengths = GetFloatArray(map, "lengths", scale);
  402. return pathAttachment;
  403. }
  404. case AttachmentType.Point: {
  405. PointAttachment point = attachmentLoader.NewPointAttachment(skin, name);
  406. if (point == null) return null;
  407. point.x = GetFloat(map, "x", 0) * scale;
  408. point.y = GetFloat(map, "y", 0) * scale;
  409. point.rotation = GetFloat(map, "rotation", 0);
  410. //string color = GetString(map, "color", null);
  411. //if (color != null) point.color = color;
  412. return point;
  413. }
  414. case AttachmentType.Clipping: {
  415. ClippingAttachment clip = attachmentLoader.NewClippingAttachment(skin, name);
  416. if (clip == null) return null;
  417. string end = GetString(map, "end", null);
  418. if (end != null) {
  419. SlotData slot = skeletonData.FindSlot(end);
  420. if (slot == null) throw new Exception("Clipping end slot not found: " + end);
  421. clip.EndSlot = slot;
  422. }
  423. ReadVertices(map, clip, GetInt(map, "vertexCount", 0) << 1);
  424. //string color = GetString(map, "color", null);
  425. // if (color != null) clip.color = color;
  426. return clip;
  427. }
  428. }
  429. return null;
  430. }
  431. private void ReadVertices (Dictionary<string, Object> map, VertexAttachment attachment, int verticesLength) {
  432. attachment.WorldVerticesLength = verticesLength;
  433. float[] vertices = GetFloatArray(map, "vertices", 1);
  434. float scale = Scale;
  435. if (verticesLength == vertices.Length) {
  436. if (scale != 1) {
  437. for (int i = 0; i < vertices.Length; i++) {
  438. vertices[i] *= scale;
  439. }
  440. }
  441. attachment.vertices = vertices;
  442. return;
  443. }
  444. ExposedList<float> weights = new ExposedList<float>(verticesLength * 3 * 3);
  445. ExposedList<int> bones = new ExposedList<int>(verticesLength * 3);
  446. for (int i = 0, n = vertices.Length; i < n;) {
  447. int boneCount = (int)vertices[i++];
  448. bones.Add(boneCount);
  449. for (int nn = i + boneCount * 4; i < nn; i += 4) {
  450. bones.Add((int)vertices[i]);
  451. weights.Add(vertices[i + 1] * this.Scale);
  452. weights.Add(vertices[i + 2] * this.Scale);
  453. weights.Add(vertices[i + 3]);
  454. }
  455. }
  456. attachment.bones = bones.ToArray();
  457. attachment.vertices = weights.ToArray();
  458. }
  459. private void ReadAnimation (Dictionary<string, Object> map, string name, SkeletonData skeletonData) {
  460. var scale = this.Scale;
  461. var timelines = new ExposedList<Timeline>();
  462. float duration = 0;
  463. // Slot timelines.
  464. if (map.ContainsKey("slots")) {
  465. foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)map["slots"]) {
  466. string slotName = entry.Key;
  467. int slotIndex = skeletonData.FindSlotIndex(slotName);
  468. var timelineMap = (Dictionary<string, Object>)entry.Value;
  469. foreach (KeyValuePair<string, Object> timelineEntry in timelineMap) {
  470. var values = (List<Object>)timelineEntry.Value;
  471. var timelineName = (string)timelineEntry.Key;
  472. if (timelineName == "attachment") {
  473. var timeline = new AttachmentTimeline(values.Count);
  474. timeline.slotIndex = slotIndex;
  475. int frameIndex = 0;
  476. foreach (Dictionary<string, Object> valueMap in values) {
  477. float time = GetFloat(valueMap, "time", 0);
  478. timeline.SetFrame(frameIndex++, time, (string)valueMap["name"]);
  479. }
  480. timelines.Add(timeline);
  481. duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]);
  482. } else if (timelineName == "color") {
  483. var timeline = new ColorTimeline(values.Count);
  484. timeline.slotIndex = slotIndex;
  485. int frameIndex = 0;
  486. foreach (Dictionary<string, Object> valueMap in values) {
  487. float time = GetFloat(valueMap, "time", 0);
  488. string c = (string)valueMap["color"];
  489. timeline.SetFrame(frameIndex, time, ToColor(c, 0), ToColor(c, 1), ToColor(c, 2), ToColor(c, 3));
  490. ReadCurve(valueMap, timeline, frameIndex);
  491. frameIndex++;
  492. }
  493. timelines.Add(timeline);
  494. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * ColorTimeline.ENTRIES]);
  495. } else if (timelineName == "twoColor") {
  496. var timeline = new TwoColorTimeline(values.Count);
  497. timeline.slotIndex = slotIndex;
  498. int frameIndex = 0;
  499. foreach (Dictionary<string, Object> valueMap in values) {
  500. float time = GetFloat(valueMap, "time", 0);
  501. string light = (string)valueMap["light"];
  502. string dark = (string)valueMap["dark"];
  503. timeline.SetFrame(frameIndex, time, ToColor(light, 0), ToColor(light, 1), ToColor(light, 2), ToColor(light, 3),
  504. ToColor(dark, 0, 6), ToColor(dark, 1, 6), ToColor(dark, 2, 6));
  505. ReadCurve(valueMap, timeline, frameIndex);
  506. frameIndex++;
  507. }
  508. timelines.Add(timeline);
  509. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TwoColorTimeline.ENTRIES]);
  510. } else
  511. throw new Exception("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")");
  512. }
  513. }
  514. }
  515. // Bone timelines.
  516. if (map.ContainsKey("bones")) {
  517. foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)map["bones"]) {
  518. string boneName = entry.Key;
  519. int boneIndex = skeletonData.FindBoneIndex(boneName);
  520. if (boneIndex == -1) throw new Exception("Bone not found: " + boneName);
  521. var timelineMap = (Dictionary<string, Object>)entry.Value;
  522. foreach (KeyValuePair<string, Object> timelineEntry in timelineMap) {
  523. var values = (List<Object>)timelineEntry.Value;
  524. var timelineName = (string)timelineEntry.Key;
  525. if (timelineName == "rotate") {
  526. var timeline = new RotateTimeline(values.Count);
  527. timeline.boneIndex = boneIndex;
  528. int frameIndex = 0;
  529. foreach (Dictionary<string, Object> valueMap in values) {
  530. timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, "angle", 0));
  531. ReadCurve(valueMap, timeline, frameIndex);
  532. frameIndex++;
  533. }
  534. timelines.Add(timeline);
  535. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * RotateTimeline.ENTRIES]);
  536. } else if (timelineName == "translate" || timelineName == "scale" || timelineName == "shear") {
  537. TranslateTimeline timeline;
  538. float timelineScale = 1, defaultValue = 0;
  539. if (timelineName == "scale") {
  540. timeline = new ScaleTimeline(values.Count);
  541. defaultValue = 1;
  542. }
  543. else if (timelineName == "shear")
  544. timeline = new ShearTimeline(values.Count);
  545. else {
  546. timeline = new TranslateTimeline(values.Count);
  547. timelineScale = scale;
  548. }
  549. timeline.boneIndex = boneIndex;
  550. int frameIndex = 0;
  551. foreach (Dictionary<string, Object> valueMap in values) {
  552. float time = GetFloat(valueMap, "time", 0);
  553. float x = GetFloat(valueMap, "x", defaultValue);
  554. float y = GetFloat(valueMap, "y", defaultValue);
  555. timeline.SetFrame(frameIndex, time, x * timelineScale, y * timelineScale);
  556. ReadCurve(valueMap, timeline, frameIndex);
  557. frameIndex++;
  558. }
  559. timelines.Add(timeline);
  560. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TranslateTimeline.ENTRIES]);
  561. } else
  562. throw new Exception("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")");
  563. }
  564. }
  565. }
  566. // IK constraint timelines.
  567. if (map.ContainsKey("ik")) {
  568. foreach (KeyValuePair<string, Object> constraintMap in (Dictionary<string, Object>)map["ik"]) {
  569. IkConstraintData constraint = skeletonData.FindIkConstraint(constraintMap.Key);
  570. var values = (List<Object>)constraintMap.Value;
  571. var timeline = new IkConstraintTimeline(values.Count);
  572. timeline.ikConstraintIndex = skeletonData.ikConstraints.IndexOf(constraint);
  573. int frameIndex = 0;
  574. foreach (Dictionary<string, Object> valueMap in values) {
  575. timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, "mix", 1),
  576. GetFloat(valueMap, "softness", 0) * scale, GetBoolean(valueMap, "bendPositive", true) ? 1 : -1,
  577. GetBoolean(valueMap, "compress", false), GetBoolean(valueMap, "stretch", false));
  578. ReadCurve(valueMap, timeline, frameIndex);
  579. frameIndex++;
  580. }
  581. timelines.Add(timeline);
  582. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * IkConstraintTimeline.ENTRIES]);
  583. }
  584. }
  585. // Transform constraint timelines.
  586. if (map.ContainsKey("transform")) {
  587. foreach (KeyValuePair<string, Object> constraintMap in (Dictionary<string, Object>)map["transform"]) {
  588. TransformConstraintData constraint = skeletonData.FindTransformConstraint(constraintMap.Key);
  589. var values = (List<Object>)constraintMap.Value;
  590. var timeline = new TransformConstraintTimeline(values.Count);
  591. timeline.transformConstraintIndex = skeletonData.transformConstraints.IndexOf(constraint);
  592. int frameIndex = 0;
  593. foreach (Dictionary<string, Object> valueMap in values) {
  594. timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, "rotateMix", 1),
  595. GetFloat(valueMap, "translateMix", 1), GetFloat(valueMap, "scaleMix", 1), GetFloat(valueMap, "shearMix", 1));
  596. ReadCurve(valueMap, timeline, frameIndex);
  597. frameIndex++;
  598. }
  599. timelines.Add(timeline);
  600. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TransformConstraintTimeline.ENTRIES]);
  601. }
  602. }
  603. // Path constraint timelines.
  604. if (map.ContainsKey("path")) {
  605. foreach (KeyValuePair<string, Object> constraintMap in (Dictionary<string, Object>)map["path"]) {
  606. int index = skeletonData.FindPathConstraintIndex(constraintMap.Key);
  607. if (index == -1) throw new Exception("Path constraint not found: " + constraintMap.Key);
  608. PathConstraintData data = skeletonData.pathConstraints.Items[index];
  609. var timelineMap = (Dictionary<string, Object>)constraintMap.Value;
  610. foreach (KeyValuePair<string, Object> timelineEntry in timelineMap) {
  611. var values = (List<Object>)timelineEntry.Value;
  612. var timelineName = (string)timelineEntry.Key;
  613. if (timelineName == "position" || timelineName == "spacing") {
  614. PathConstraintPositionTimeline timeline;
  615. float timelineScale = 1;
  616. if (timelineName == "spacing") {
  617. timeline = new PathConstraintSpacingTimeline(values.Count);
  618. if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) timelineScale = scale;
  619. }
  620. else {
  621. timeline = new PathConstraintPositionTimeline(values.Count);
  622. if (data.positionMode == PositionMode.Fixed) timelineScale = scale;
  623. }
  624. timeline.pathConstraintIndex = index;
  625. int frameIndex = 0;
  626. foreach (Dictionary<string, Object> valueMap in values) {
  627. timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, timelineName, 0) * timelineScale);
  628. ReadCurve(valueMap, timeline, frameIndex);
  629. frameIndex++;
  630. }
  631. timelines.Add(timeline);
  632. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * PathConstraintPositionTimeline.ENTRIES]);
  633. }
  634. else if (timelineName == "mix") {
  635. PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(values.Count);
  636. timeline.pathConstraintIndex = index;
  637. int frameIndex = 0;
  638. foreach (Dictionary<string, Object> valueMap in values) {
  639. timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, "rotateMix", 1),
  640. GetFloat(valueMap, "translateMix", 1));
  641. ReadCurve(valueMap, timeline, frameIndex);
  642. frameIndex++;
  643. }
  644. timelines.Add(timeline);
  645. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * PathConstraintMixTimeline.ENTRIES]);
  646. }
  647. }
  648. }
  649. }
  650. // Deform timelines.
  651. if (map.ContainsKey("deform")) {
  652. foreach (KeyValuePair<string, Object> deformMap in (Dictionary<string, Object>)map["deform"]) {
  653. Skin skin = skeletonData.FindSkin(deformMap.Key);
  654. foreach (KeyValuePair<string, Object> slotMap in (Dictionary<string, Object>)deformMap.Value) {
  655. int slotIndex = skeletonData.FindSlotIndex(slotMap.Key);
  656. if (slotIndex == -1) throw new Exception("Slot not found: " + slotMap.Key);
  657. foreach (KeyValuePair<string, Object> timelineMap in (Dictionary<string, Object>)slotMap.Value) {
  658. var values = (List<Object>)timelineMap.Value;
  659. VertexAttachment attachment = (VertexAttachment)skin.GetAttachment(slotIndex, timelineMap.Key);
  660. if (attachment == null) throw new Exception("Deform attachment not found: " + timelineMap.Key);
  661. bool weighted = attachment.bones != null;
  662. float[] vertices = attachment.vertices;
  663. int deformLength = weighted ? vertices.Length / 3 * 2 : vertices.Length;
  664. var timeline = new DeformTimeline(values.Count);
  665. timeline.slotIndex = slotIndex;
  666. timeline.attachment = attachment;
  667. int frameIndex = 0;
  668. foreach (Dictionary<string, Object> valueMap in values) {
  669. float[] deform;
  670. if (!valueMap.ContainsKey("vertices")) {
  671. deform = weighted ? new float[deformLength] : vertices;
  672. } else {
  673. deform = new float[deformLength];
  674. int start = GetInt(valueMap, "offset", 0);
  675. float[] verticesValue = GetFloatArray(valueMap, "vertices", 1);
  676. Array.Copy(verticesValue, 0, deform, start, verticesValue.Length);
  677. if (scale != 1) {
  678. for (int i = start, n = i + verticesValue.Length; i < n; i++)
  679. deform[i] *= scale;
  680. }
  681. if (!weighted) {
  682. for (int i = 0; i < deformLength; i++)
  683. deform[i] += vertices[i];
  684. }
  685. }
  686. timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), deform);
  687. ReadCurve(valueMap, timeline, frameIndex);
  688. frameIndex++;
  689. }
  690. timelines.Add(timeline);
  691. duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]);
  692. }
  693. }
  694. }
  695. }
  696. // Draw order timeline.
  697. if (map.ContainsKey("drawOrder") || map.ContainsKey("draworder")) {
  698. var values = (List<Object>)map[map.ContainsKey("drawOrder") ? "drawOrder" : "draworder"];
  699. var timeline = new DrawOrderTimeline(values.Count);
  700. int slotCount = skeletonData.slots.Count;
  701. int frameIndex = 0;
  702. foreach (Dictionary<string, Object> drawOrderMap in values) {
  703. int[] drawOrder = null;
  704. if (drawOrderMap.ContainsKey("offsets")) {
  705. drawOrder = new int[slotCount];
  706. for (int i = slotCount - 1; i >= 0; i--)
  707. drawOrder[i] = -1;
  708. var offsets = (List<Object>)drawOrderMap["offsets"];
  709. int[] unchanged = new int[slotCount - offsets.Count];
  710. int originalIndex = 0, unchangedIndex = 0;
  711. foreach (Dictionary<string, Object> offsetMap in offsets) {
  712. int slotIndex = skeletonData.FindSlotIndex((string)offsetMap["slot"]);
  713. if (slotIndex == -1) throw new Exception("Slot not found: " + offsetMap["slot"]);
  714. // Collect unchanged items.
  715. while (originalIndex != slotIndex)
  716. unchanged[unchangedIndex++] = originalIndex++;
  717. // Set changed items.
  718. int index = originalIndex + (int)(float)offsetMap["offset"];
  719. drawOrder[index] = originalIndex++;
  720. }
  721. // Collect remaining unchanged items.
  722. while (originalIndex < slotCount)
  723. unchanged[unchangedIndex++] = originalIndex++;
  724. // Fill in unchanged items.
  725. for (int i = slotCount - 1; i >= 0; i--)
  726. if (drawOrder[i] == -1) drawOrder[i] = unchanged[--unchangedIndex];
  727. }
  728. timeline.SetFrame(frameIndex++, GetFloat(drawOrderMap, "time", 0), drawOrder);
  729. }
  730. timelines.Add(timeline);
  731. duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]);
  732. }
  733. // Event timeline.
  734. if (map.ContainsKey("events")) {
  735. var eventsMap = (List<Object>)map["events"];
  736. var timeline = new EventTimeline(eventsMap.Count);
  737. int frameIndex = 0;
  738. foreach (Dictionary<string, Object> eventMap in eventsMap) {
  739. EventData eventData = skeletonData.FindEvent((string)eventMap["name"]);
  740. if (eventData == null) throw new Exception("Event not found: " + eventMap["name"]);
  741. var e = new Event(GetFloat(eventMap, "time", 0), eventData) {
  742. intValue = GetInt(eventMap, "int", eventData.Int),
  743. floatValue = GetFloat(eventMap, "float", eventData.Float),
  744. stringValue = GetString(eventMap, "string", eventData.String)
  745. };
  746. if (e.data.AudioPath != null) {
  747. e.volume = GetFloat(eventMap, "volume", eventData.Volume);
  748. e.balance = GetFloat(eventMap, "balance", eventData.Balance);
  749. }
  750. timeline.SetFrame(frameIndex++, e);
  751. }
  752. timelines.Add(timeline);
  753. duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]);
  754. }
  755. timelines.TrimExcess();
  756. skeletonData.animations.Add(new Animation(name, timelines, duration));
  757. }
  758. static void ReadCurve (Dictionary<string, Object> valueMap, CurveTimeline timeline, int frameIndex) {
  759. if (!valueMap.ContainsKey("curve"))
  760. return;
  761. Object curveObject = valueMap["curve"];
  762. if (curveObject is string)
  763. timeline.SetStepped(frameIndex);
  764. else
  765. timeline.SetCurve(frameIndex, (float)curveObject, GetFloat(valueMap, "c2", 0), GetFloat(valueMap, "c3", 1), GetFloat(valueMap, "c4", 1));
  766. }
  767. internal class LinkedMesh {
  768. internal string parent, skin;
  769. internal int slotIndex;
  770. internal MeshAttachment mesh;
  771. internal bool inheritDeform;
  772. public LinkedMesh (MeshAttachment mesh, string skin, int slotIndex, string parent, bool inheritDeform) {
  773. this.mesh = mesh;
  774. this.skin = skin;
  775. this.slotIndex = slotIndex;
  776. this.parent = parent;
  777. this.inheritDeform = inheritDeform;
  778. }
  779. }
  780. static float[] GetFloatArray(Dictionary<string, Object> map, string name, float scale) {
  781. var list = (List<Object>)map[name];
  782. var values = new float[list.Count];
  783. if (scale == 1) {
  784. for (int i = 0, n = list.Count; i < n; i++)
  785. values[i] = (float)list[i];
  786. } else {
  787. for (int i = 0, n = list.Count; i < n; i++)
  788. values[i] = (float)list[i] * scale;
  789. }
  790. return values;
  791. }
  792. static int[] GetIntArray(Dictionary<string, Object> map, string name) {
  793. var list = (List<Object>)map[name];
  794. var values = new int[list.Count];
  795. for (int i = 0, n = list.Count; i < n; i++)
  796. values[i] = (int)(float)list[i];
  797. return values;
  798. }
  799. static float GetFloat(Dictionary<string, Object> map, string name, float defaultValue) {
  800. if (!map.ContainsKey(name))
  801. return defaultValue;
  802. return (float)map[name];
  803. }
  804. static int GetInt(Dictionary<string, Object> map, string name, int defaultValue) {
  805. if (!map.ContainsKey(name))
  806. return defaultValue;
  807. return (int)(float)map[name];
  808. }
  809. static bool GetBoolean(Dictionary<string, Object> map, string name, bool defaultValue) {
  810. if (!map.ContainsKey(name))
  811. return defaultValue;
  812. return (bool)map[name];
  813. }
  814. static string GetString(Dictionary<string, Object> map, string name, string defaultValue) {
  815. if (!map.ContainsKey(name))
  816. return defaultValue;
  817. return (string)map[name];
  818. }
  819. static float ToColor(string hexString, int colorIndex, int expectedLength = 8) {
  820. if (hexString.Length != expectedLength)
  821. throw new ArgumentException("Color hexidecimal length must be " + expectedLength + ", recieved: " + hexString, "hexString");
  822. return Convert.ToInt32(hexString.Substring(colorIndex * 2, 2), 16) / (float)255;
  823. }
  824. }
  825. }