Açıklama Yok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RuleTileEditor.cs 56KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Linq;
  5. using UnityEditorInternal;
  6. using UnityEngine;
  7. using UnityEngine.Tilemaps;
  8. using Object = UnityEngine.Object;
  9. namespace UnityEditor
  10. {
  11. /// <summary>
  12. /// The Editor for a RuleTile.
  13. /// </summary>
  14. [CustomEditor(typeof(RuleTile), true)]
  15. [CanEditMultipleObjects]
  16. public class RuleTileEditor : Editor
  17. {
  18. private const string s_XIconString = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAABoSURBVDhPnY3BDcAgDAOZhS14dP1O0x2C/LBEgiNSHvfwyZabmV0jZRUpq2zi6f0DJwdcQOEdwwDLypF0zHLMa9+NQRxkQ+ACOT2STVw/q8eY1346ZlE54sYAhVhSDrjwFymrSFnD2gTZpls2OvFUHAAAAABJRU5ErkJggg==";
  19. private const string s_Arrow0 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAACYSURBVDhPzZExDoQwDATzE4oU4QXXcgUFj+YxtETwgpMwXuFcwMFSRMVKKwzZcWzhiMg91jtg34XIntkre5EaT7yjjhI9pOD5Mw5k2X/DdUwFr3cQ7Pu23E/BiwXyWSOxrNqx+ewnsayam5OLBtbOGPUM/r93YZL4/dhpR/amwByGFBz170gNChA6w5bQQMqramBTgJ+Z3A58WuWejPCaHQAAAABJRU5ErkJggg==";
  20. private const string s_Arrow1 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAABqSURBVDhPxYzBDYAgEATpxYcd+PVr0fZ2siZrjmMhFz6STIiDs8XMlpEyi5RkO/d66TcgJUB43JfNBqRkSEYDnYjhbKD5GIUkDqRDwoH3+NgTAw+bL/aoOP4DOgH+iwECEt+IlFmkzGHlAYKAWF9R8zUnAAAAAElFTkSuQmCC";
  21. private const string s_Arrow2 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAC0SURBVDhPjVE5EsIwDMxPKFKYF9CagoJH8xhaMskLmEGsjOSRkBzYmU2s9a58TUQUmCH1BWEHweuKP+D8tphrWcAHuIGrjPnPNY8X2+DzEWE+FzrdrkNyg2YGNNfRGlyOaZDJOxBrDhgOowaYW8UW0Vau5ZkFmXbbDr+CzOHKmLinAXMEePyZ9dZkZR+s5QX2O8DY3zZ/sgYcdDqeEVp8516o0QQV1qeMwg6C91toYoLoo+kNt/tpKQEVvFQAAAAASUVORK5CYII=";
  22. private const string s_Arrow3 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAAB2SURBVDhPzY1LCoAwEEPnLi48gW5d6p31bH5SMhp0Cq0g+CCLxrzRPqMZ2pRqKG4IqzJc7JepTlbRZXYpWTg4RZE1XAso8VHFKNhQuTjKtZvHUNCEMogO4K3BhvMn9wP4EzoPZ3n0AGTW5fiBVzLAAYTP32C2Ay3agtu9V/9PAAAAAElFTkSuQmCC";
  23. private const string s_Arrow5 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAABqSURBVDhPnY3BCYBADASvFx924NevRdvbyoLBmNuDJQMDGjNxAFhK1DyUQ9fvobCdO+j7+sOKj/uSB+xYHZAxl7IR1wNTXJeVcaAVU+614uWfCT9mVUhknMlxDokd15BYsQrJFHeUQ0+MB5ErsPi/6hO1AAAAAElFTkSuQmCC";
  24. private const string s_Arrow6 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAACaSURBVDhPxZExEkAwEEVzE4UiTqClUDi0w2hlOIEZsV82xCZmQuPPfFn8t1mirLWf7S5flQOXjd64vCuEKWTKVt+6AayH3tIa7yLg6Qh2FcKFB72jBgJeziA1CMHzeaNHjkfwnAK86f3KUafU2ClHIJSzs/8HHLv09M3SaMCxS7ljw/IYJWzQABOQZ66x4h614ahTCL/WT7BSO51b5Z5hSx88AAAAAElFTkSuQmCC";
  25. private const string s_Arrow7 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAABQSURBVDhPYxh8QNle/T8U/4MKEQdAmsz2eICx6W530gygr2aQBmSMphkZYxqErAEXxusKfAYQ7XyyNMIAsgEkaYQBkAFkaYQBsjXSGDAwAAD193z4luKPrAAAAABJRU5ErkJggg==";
  26. private const string s_Arrow8 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAACYSURBVDhPxZE9DoAwCIW9iUOHegJXHRw8tIdx1egJTMSHAeMPaHSR5KVQ+KCkCRF91mdz4VDEWVzXTBgg5U1N5wahjHzXS3iFFVRxAygNVaZxJ6VHGIl2D6oUXP0ijlJuTp724FnID1Lq7uw2QM5+thoKth0N+GGyA7IA3+yM77Ag1e2zkey5gCdAg/h8csy+/89v7E+YkgUntOWeVt2SfAAAAABJRU5ErkJggg==";
  27. private const string s_MirrorX = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC41ZYUyZQAAAG1JREFUOE+lj9ENwCAIRB2IFdyRfRiuDSaXAF4MrR9P5eRhHGb2Gxp2oaEjIovTXSrAnPNx6hlgyCZ7o6omOdYOldGIZhAziEmOTSfigLV0RYAB9y9f/7kO8L3WUaQyhCgz0dmCL9CwCw172HgBeyG6oloC8fAAAAAASUVORK5CYII=";
  28. private const string s_MirrorY = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC41ZYUyZQAAAG9JREFUOE+djckNACEMAykoLdAjHbPyw1IOJ0L7mAejjFlm9hspyd77Kk+kBAjPOXcakJIh6QaKyOE0EB5dSPJAiUmOiL8PMVGxugsP/0OOib8vsY8yYwy6gRyC8CB5QIWgCMKBLgRSkikEUr5h6wOPWfMoCYILdgAAAABJRU5ErkJggg==";
  29. private const string s_MirrorXY = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAAABl0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC4yMfEgaZUAAAHkSURBVDhPrVJLSwJRFJ4cdXwjPlrVJly1kB62cpEguElXKgYKIpaC+EIEEfGxLqI/UES1KaJlEdGmRY9ltCsIWrUJatGm0eZO3xkHIsJdH3zce+ec75z5zr3cf2MMmLdYLA/BYFA2mUyPOPvwnR+GR4PXaDQLLpfrKpVKSb1eT6bV6XTeocAS4sIw7S804BzEZ4IgsGq1ykhcr9dlj8czwPdbxJdBMyX/As/zLiz74Ar2J9lsVulcKpUYut5DnEbsHFwEx8AhtFqtGViD6BOc1ul0B5lMRhGXy2Wm1+ufkBOE/2fsL1FsQpXCiCAcQiAlk0kJRZjf7+9TRxI3Gg0WCoW+IpGISHHERBS5UKUch8n2K5WK3O125VqtpqydTkdZie12W261WjIVo73b7RZVKccZDIZ1q9XaT6fTLB6PD9BFKhQKjITFYpGFw+FBNBpVOgcCARH516pUGZYZXk5R4B3efLBxDM9f1CkWi/WR3ICtGVh6Rd4NPE+p0iEgmkSRLRoMEjYhHpA4kUiIOO8iZRU8AmnadK2/QOOfhnjPZrO95fN5Zdq5XE5yOBwvuKoNxGfBkQ8FzXkPprnj9Xrfm82mDI8fsLON3x5H/Od+RwHdLfDds9vtn0aj8QoF6QH9JzjuG3acpxmu1RgPAAAAAElFTkSuQmCC";
  30. private const string s_Rotated = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC41ZYUyZQAAAHdJREFUOE+djssNwCAMQxmIFdgx+2S4Vj4YxWlQgcOT8nuG5u5C732Sd3lfLlmPMR4QhXgrTQaimUlA3EtD+CJlBuQ7aUAUMjEAv9gWCQNEPhHJUkYfZ1kEpcxDzioRzGIlr0Qwi0r+Q5rTgM+AAVcygHgt7+HtBZs/2QVWP8ahAAAAAElFTkSuQmCC";
  31. private const string s_RotatedMirror = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAApklEQVQoFY2SMRaAIAxDwefknVg8uIt3ckVSKdYSnjBAi/lprcaUUphZ+3WGY3u1yJcJMBdNtqAyM3BAFRgohBNmUzDEzIDCVQgGK2rL1gAxhatY3vXh+U7hIs2uOqUZ7EGfN6O1RU/wEf5VX4zgAzpTSessIhL5VDrJkrepitJtFtRHvm0YtA6MMfRSUUGcbGC+A0AdOIJx7w1w1y1WWX/FYUV1uQFvVjvOTYh+rAAAAABJRU5ErkJggg==";
  32. private const string s_Fixed = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMjHxIGmVAAAA50lEQVQ4T51Ruw6CQBCkwBYKWkIgQAs9gfgCvgb4BML/qWBM9Bdo9QPIuVOQ3JIzosVkc7Mzty9NCPE3lORaKMm1YA/LsnTXdbdhGJ6iKHoVRTEi+r4/OI6zN01Tl/XM7HneLsuyW13XU9u2ous6gYh3kiR327YPsp6ZgyDom6aZYFqiqqqJ8mdZz8xoca64BHjkZT0zY0aVcQbysp6Z4zj+Vvkp65mZttxjOSozdkEzD7KemekcxzRNHxDOHSDiQ/DIy3pmpjtuSJBThStGKMtyRKSOLnSm3DCMz3f+FUpyLZTkOgjtDSWORSDbpbmNAAAAAElFTkSuQmCC";
  33. private static readonly string k_UndoName = L10n.Tr("Change RuleTile");
  34. private static Texture2D[] s_Arrows;
  35. /// <summary>
  36. /// Array of arrow textures used for marking positions for Rule matches
  37. /// </summary>
  38. public static Texture2D[] arrows
  39. {
  40. get
  41. {
  42. if (s_Arrows == null)
  43. {
  44. s_Arrows = new Texture2D[10];
  45. s_Arrows[0] = Base64ToTexture(s_Arrow0);
  46. s_Arrows[1] = Base64ToTexture(s_Arrow1);
  47. s_Arrows[2] = Base64ToTexture(s_Arrow2);
  48. s_Arrows[3] = Base64ToTexture(s_Arrow3);
  49. s_Arrows[5] = Base64ToTexture(s_Arrow5);
  50. s_Arrows[6] = Base64ToTexture(s_Arrow6);
  51. s_Arrows[7] = Base64ToTexture(s_Arrow7);
  52. s_Arrows[8] = Base64ToTexture(s_Arrow8);
  53. s_Arrows[9] = Base64ToTexture(s_XIconString);
  54. }
  55. return s_Arrows;
  56. }
  57. }
  58. private static Texture2D[] s_AutoTransforms;
  59. /// <summary>
  60. /// Arrays of textures used for marking transform Rule matches
  61. /// </summary>
  62. public static Texture2D[] autoTransforms
  63. {
  64. get
  65. {
  66. if (s_AutoTransforms == null)
  67. {
  68. s_AutoTransforms = new Texture2D[6];
  69. s_AutoTransforms[0] = Base64ToTexture(s_Rotated);
  70. s_AutoTransforms[1] = Base64ToTexture(s_MirrorX);
  71. s_AutoTransforms[2] = Base64ToTexture(s_MirrorY);
  72. s_AutoTransforms[3] = Base64ToTexture(s_Fixed);
  73. s_AutoTransforms[4] = Base64ToTexture(s_MirrorXY);
  74. s_AutoTransforms[5] = Base64ToTexture(s_RotatedMirror);
  75. }
  76. return s_AutoTransforms;
  77. }
  78. }
  79. private static class Styles
  80. {
  81. public static readonly GUIContent defaultSprite = EditorGUIUtility.TrTextContent("Default Sprite"
  82. , "The default Sprite set when creating a new Rule.");
  83. public static readonly GUIContent defaultGameObject = EditorGUIUtility.TrTextContent("Default GameObject"
  84. , "The default GameObject set when creating a new Rule.");
  85. public static readonly GUIContent defaultCollider = EditorGUIUtility.TrTextContent("Default Collider"
  86. , "The default Collider Type set when creating a new Rule.");
  87. public static readonly GUIContent emptyRuleTileInfo =
  88. EditorGUIUtility.TrTextContent(
  89. "Drag Sprite or Sprite Texture assets \n" +
  90. " to start creating a Rule Tile.");
  91. public static readonly GUIContent extendNeighbor = EditorGUIUtility.TrTextContent("Extend Neighbor"
  92. , "Enabling this allows you to increase the range of neighbors beyond the 3x3 box.");
  93. public static readonly GUIContent numberOfTilingRules = EditorGUIUtility.TrTextContent(
  94. "Number of Tiling Rules"
  95. , "Change this to adjust of the number of tiling rules.");
  96. public static readonly GUIContent tilingRules = EditorGUIUtility.TrTextContent("Tiling Rules");
  97. public static readonly GUIContent tilingRulesGameObject = EditorGUIUtility.TrTextContent("GameObject"
  98. , "The GameObject for the Tile which fits this Rule.");
  99. public static readonly GUIContent tilingRulesCollider = EditorGUIUtility.TrTextContent("Collider"
  100. , "The Collider Type for the Tile which fits this Rule");
  101. public static readonly GUIContent tilingRulesOutput = EditorGUIUtility.TrTextContent("Output"
  102. , "The Output for the Tile which fits this Rule. Each Output type has its own properties.");
  103. public static readonly GUIContent tilingRulesNoise = EditorGUIUtility.TrTextContent("Noise"
  104. , "The Perlin noise factor when placing the Tile.");
  105. public static readonly GUIContent tilingRulesShuffle = EditorGUIUtility.TrTextContent("Shuffle"
  106. , "The randomized transform given to the Tile when placing it.");
  107. public static readonly GUIContent tilingRulesRandomSize = EditorGUIUtility.TrTextContent("Size"
  108. , "The number of Sprites to randomize from.");
  109. public static readonly GUIContent tilingRulesMinSpeed = EditorGUIUtility.TrTextContent("Min Speed"
  110. , "The minimum speed at which the animation is played.");
  111. public static readonly GUIContent tilingRulesMaxSpeed = EditorGUIUtility.TrTextContent("Max Speed"
  112. , "The maximum speed at which the animation is played.");
  113. public static readonly GUIContent tilingRulesAnimationSize = EditorGUIUtility.TrTextContent("Size"
  114. , "The number of Sprites in the animation.");
  115. public static readonly GUIStyle extendNeighborsLightStyle = new GUIStyle()
  116. {
  117. alignment = TextAnchor.MiddleLeft,
  118. fontStyle = FontStyle.Bold,
  119. fontSize = 10,
  120. normal = new GUIStyleState()
  121. {
  122. textColor = Color.black
  123. }
  124. };
  125. public static readonly GUIStyle extendNeighborsDarkStyle = new GUIStyle()
  126. {
  127. alignment = TextAnchor.MiddleLeft,
  128. fontStyle = FontStyle.Bold,
  129. fontSize = 10,
  130. normal = new GUIStyleState()
  131. {
  132. textColor = Color.white
  133. }
  134. };
  135. }
  136. /// <summary>
  137. /// The RuleTile being edited
  138. /// </summary>
  139. public RuleTile tile => target as RuleTile;
  140. /// <summary>
  141. /// List of Sprites for Drag and Drop
  142. /// </summary>
  143. private List<Sprite> dragAndDropSprites;
  144. /// <summary>
  145. /// Reorderable list for Rules
  146. /// </summary>
  147. private ReorderableList m_ReorderableList;
  148. /// <summary>
  149. /// Whether the RuleTile can extend its neighbors beyond directly adjacent ones
  150. /// </summary>
  151. public bool extendNeighbor;
  152. /// <summary>
  153. /// Preview Utility for rendering previews
  154. /// </summary>
  155. public PreviewRenderUtility m_PreviewUtility;
  156. /// <summary>
  157. /// Grid for rendering previews
  158. /// </summary>
  159. public Grid m_PreviewGrid;
  160. /// <summary>
  161. /// List of Tilemaps for rendering previews
  162. /// </summary>
  163. public List<Tilemap> m_PreviewTilemaps;
  164. /// <summary>
  165. /// List of TilemapRenderers for rendering previews
  166. /// </summary>
  167. public List<TilemapRenderer> m_PreviewTilemapRenderers;
  168. /// <summary>
  169. /// Default height for a Rule Element
  170. /// </summary>
  171. public const float k_DefaultElementHeight = 48f;
  172. /// <summary>
  173. /// Padding between Rule Elements
  174. /// </summary>
  175. public const float k_PaddingBetweenRules = 8f;
  176. /// <summary>
  177. /// Single line height
  178. /// </summary>
  179. public const float k_SingleLineHeight = 18f;
  180. /// <summary>
  181. /// Width for labels
  182. /// </summary>
  183. public const float k_LabelWidth = 80f;
  184. private SerializedProperty m_TilingRules;
  185. private MethodInfo m_ClearCacheMethod;
  186. /// <summary>
  187. /// OnEnable for the RuleTileEditor
  188. /// </summary>
  189. public virtual void OnEnable()
  190. {
  191. m_ReorderableList = new ReorderableList(tile != null ? tile.m_TilingRules : null, typeof(RuleTile.TilingRule), true, true, true, true);
  192. m_ReorderableList.drawHeaderCallback = OnDrawHeader;
  193. m_ReorderableList.drawElementCallback = OnDrawElement;
  194. m_ReorderableList.elementHeightCallback = GetElementHeight;
  195. m_ReorderableList.onChangedCallback = ListUpdated;
  196. m_ReorderableList.onAddDropdownCallback = OnAddDropdownElement;
  197. // Required to adjust element height changes
  198. var rolType = GetType("UnityEditorInternal.ReorderableList");
  199. if (rolType != null)
  200. {
  201. // ClearCache was changed to InvalidateCache in newer versions of Unity.
  202. // To maintain backwards compatibility, we will attempt to retrieve each method in order
  203. m_ClearCacheMethod = rolType.GetMethod("InvalidateCache", BindingFlags.Instance | BindingFlags.NonPublic);
  204. if (m_ClearCacheMethod == null)
  205. m_ClearCacheMethod = rolType.GetMethod("ClearCache", BindingFlags.Instance | BindingFlags.NonPublic);
  206. }
  207. m_TilingRules = serializedObject.FindProperty("m_TilingRules");
  208. }
  209. /// <summary>
  210. /// OnDisable for the RuleTileEditor
  211. /// </summary>
  212. public virtual void OnDisable()
  213. {
  214. DestroyPreview();
  215. }
  216. private void UpdateTilingRuleIds()
  217. {
  218. var existingIdSet = new HashSet<int>();
  219. var usedIdSet = new HashSet<int>();
  220. foreach (var rule in tile.m_TilingRules)
  221. {
  222. existingIdSet.Add(rule.m_Id);
  223. }
  224. foreach (var rule in tile.m_TilingRules)
  225. {
  226. if (usedIdSet.Contains(rule.m_Id))
  227. {
  228. while (existingIdSet.Contains(rule.m_Id))
  229. rule.m_Id++;
  230. existingIdSet.Add(rule.m_Id);
  231. }
  232. usedIdSet.Add(rule.m_Id);
  233. }
  234. }
  235. /// <summary>
  236. /// Get the GUI bounds for a Rule.
  237. /// </summary>
  238. /// <param name="bounds">Cell bounds of the Rule.</param>
  239. /// <param name="rule">Rule to get GUI bounds for.</param>
  240. /// <returns>The GUI bounds for a rule.</returns>
  241. public virtual BoundsInt GetRuleGUIBounds(BoundsInt bounds, RuleTile.TilingRule rule)
  242. {
  243. if (extendNeighbor)
  244. {
  245. bounds.xMin--;
  246. bounds.yMin--;
  247. bounds.xMax++;
  248. bounds.yMax++;
  249. }
  250. bounds.xMin = Mathf.Min(bounds.xMin, -1);
  251. bounds.yMin = Mathf.Min(bounds.yMin, -1);
  252. bounds.xMax = Mathf.Max(bounds.xMax, 2);
  253. bounds.yMax = Mathf.Max(bounds.yMax, 2);
  254. return bounds;
  255. }
  256. /// <summary>
  257. /// Callback when the Rule list is updated
  258. /// </summary>
  259. /// <param name="list">Reorderable list for Rules</param>
  260. public void ListUpdated(ReorderableList list)
  261. {
  262. UpdateTilingRuleIds();
  263. }
  264. private float GetElementHeight(int index)
  265. {
  266. RuleTile.TilingRule rule = tile.m_TilingRules[index];
  267. return GetElementHeight(rule);
  268. }
  269. /// <summary>
  270. /// Gets the GUI element height for a TilingRule
  271. /// </summary>
  272. /// <param name="rule">Rule to get height for</param>
  273. /// <returns>GUI element height for a TilingRule</returns>
  274. public float GetElementHeight(RuleTile.TilingRule rule)
  275. {
  276. BoundsInt bounds = GetRuleGUIBounds(rule.GetBounds(), rule);
  277. float inspectorHeight = GetElementHeight(rule as RuleTile.TilingRuleOutput);
  278. float matrixHeight = GetMatrixSize(bounds).y + 10f;
  279. return Mathf.Max(inspectorHeight, matrixHeight);
  280. }
  281. /// <summary>
  282. /// Gets the GUI element height for a TilingRuleOutput
  283. /// </summary>
  284. /// <param name="rule">Rule to get height for</param>
  285. /// <returns>GUI element height for a TilingRuleOutput </returns>
  286. public float GetElementHeight(RuleTile.TilingRuleOutput rule)
  287. {
  288. float inspectorHeight = k_DefaultElementHeight + k_PaddingBetweenRules;
  289. switch (rule.m_Output)
  290. {
  291. case RuleTile.TilingRuleOutput.OutputSprite.Random:
  292. case RuleTile.TilingRuleOutput.OutputSprite.Animation:
  293. inspectorHeight = k_DefaultElementHeight + k_SingleLineHeight * (rule.m_Sprites.Length + 3) + k_PaddingBetweenRules;
  294. break;
  295. }
  296. return inspectorHeight;
  297. }
  298. /// <summary>
  299. /// Gets the GUI matrix size for a Rule of a RuleTile
  300. /// </summary>
  301. /// <param name="bounds">Cell bounds of the Rule.</param>
  302. /// <returns>Returns the GUI matrix size for a Rule of a RuleTile.</returns>
  303. public virtual Vector2 GetMatrixSize(BoundsInt bounds)
  304. {
  305. return new Vector2(bounds.size.x * k_SingleLineHeight, bounds.size.y * k_SingleLineHeight);
  306. }
  307. /// <summary>
  308. /// Draws the Rule element for the Rule list
  309. /// </summary>
  310. /// <param name="rect">Rect to draw the Rule Element in</param>
  311. /// <param name="index">Index of the Rule Element to draw</param>
  312. /// <param name="isactive">Whether the Rule Element is active</param>
  313. /// <param name="isfocused">Whether the Rule Element is focused</param>
  314. protected virtual void OnDrawElement(Rect rect, int index, bool isactive, bool isfocused)
  315. {
  316. RuleTile.TilingRule rule = tile.m_TilingRules[index];
  317. BoundsInt bounds = GetRuleGUIBounds(rule.GetBounds(), rule);
  318. float yPos = rect.yMin + 2f;
  319. float height = rect.height - k_PaddingBetweenRules;
  320. Vector2 matrixSize = GetMatrixSize(bounds);
  321. Rect spriteRect = new Rect(rect.xMax - k_DefaultElementHeight - 5f, yPos, k_DefaultElementHeight, k_DefaultElementHeight);
  322. Rect matrixRect = new Rect(rect.xMax - matrixSize.x - spriteRect.width - 10f, yPos, matrixSize.x, matrixSize.y);
  323. Rect inspectorRect = new Rect(rect.xMin, yPos, rect.width - matrixSize.x - spriteRect.width - 20f, height);
  324. RuleInspectorOnGUI(inspectorRect, rule);
  325. RuleMatrixOnGUI(tile, matrixRect, bounds, rule);
  326. SpriteOnGUI(spriteRect, rule);
  327. }
  328. private void OnAddElement(object obj)
  329. {
  330. var list = obj as ReorderableList;
  331. RuleTile.TilingRule rule = new RuleTile.TilingRule();
  332. rule.m_Output = RuleTile.TilingRuleOutput.OutputSprite.Single;
  333. rule.m_Sprites[0] = tile.m_DefaultSprite;
  334. rule.m_GameObject = tile.m_DefaultGameObject;
  335. rule.m_ColliderType = tile.m_DefaultColliderType;
  336. var count = m_TilingRules.arraySize;
  337. ResizeRuleTileList(count + 1);
  338. if (list.index == -1 || list.index >= list.count)
  339. tile.m_TilingRules[count] = rule;
  340. else
  341. {
  342. tile.m_TilingRules.Insert(list.index + 1, rule);
  343. tile.m_TilingRules.RemoveAt(count + 1);
  344. if (list.IsSelected(list.index))
  345. list.index += 1;
  346. }
  347. UpdateTilingRuleIds();
  348. }
  349. private void OnDuplicateElement(object obj)
  350. {
  351. var list = obj as ReorderableList;
  352. if (list.index < 0 || list.index >= tile.m_TilingRules.Count)
  353. return;
  354. var copyRule = tile.m_TilingRules[list.index];
  355. var rule = copyRule.Clone();
  356. var count = m_TilingRules.arraySize;
  357. ResizeRuleTileList(count + 1);
  358. tile.m_TilingRules.Insert(list.index + 1, rule);
  359. tile.m_TilingRules.RemoveAt(count + 1);
  360. if (list.IsSelected(list.index))
  361. list.index += 1;
  362. UpdateTilingRuleIds();
  363. }
  364. private void OnAddDropdownElement(Rect rect, ReorderableList list)
  365. {
  366. if (0 <= list.index && list.index < tile.m_TilingRules.Count && list.IsSelected(list.index))
  367. {
  368. GenericMenu menu = new GenericMenu();
  369. menu.AddItem(EditorGUIUtility.TrTextContent("Add"), false, OnAddElement, list);
  370. menu.AddItem(EditorGUIUtility.TrTextContent("Duplicate"), false, OnDuplicateElement, list);
  371. menu.DropDown(rect);
  372. }
  373. else
  374. {
  375. OnAddElement(list);
  376. }
  377. }
  378. /// <summary>
  379. /// Saves any changes to the RuleTile
  380. /// </summary>
  381. public void SaveTile()
  382. {
  383. serializedObject.ApplyModifiedProperties();
  384. EditorUtility.SetDirty(target);
  385. SceneView.RepaintAll();
  386. UpdateAffectedOverrideTiles(tile);
  387. }
  388. /// <summary>
  389. /// Updates all RuleOverrideTiles which override the given RUleTile
  390. /// </summary>
  391. /// <param name="target">RuleTile which has been updated</param>
  392. public static void UpdateAffectedOverrideTiles(RuleTile target)
  393. {
  394. List<RuleOverrideTile> overrideTiles = FindAffectedOverrideTiles(target);
  395. if (overrideTiles != null)
  396. {
  397. foreach (var overrideTile in overrideTiles)
  398. {
  399. Undo.RegisterCompleteObjectUndo(overrideTile, k_UndoName);
  400. Undo.RecordObject(overrideTile.m_InstanceTile, k_UndoName);
  401. overrideTile.Override();
  402. UpdateAffectedOverrideTiles(overrideTile.m_InstanceTile);
  403. EditorUtility.SetDirty(overrideTile);
  404. }
  405. }
  406. }
  407. /// <summary>
  408. /// Gets all RuleOverrideTiles which override the given RuleTile
  409. /// </summary>
  410. /// <param name="target">RuleTile which has been updated</param>
  411. /// <returns>A list of RuleOverrideTiles which override the given RuleTile</returns>
  412. public static List<RuleOverrideTile> FindAffectedOverrideTiles(RuleTile target)
  413. {
  414. List<RuleOverrideTile> overrideTiles = new List<RuleOverrideTile>();
  415. string[] overrideTileGuids = AssetDatabase.FindAssets("t:" + typeof(RuleOverrideTile).Name);
  416. foreach (string overrideTileGuid in overrideTileGuids)
  417. {
  418. string overrideTilePath = AssetDatabase.GUIDToAssetPath(overrideTileGuid);
  419. RuleOverrideTile overrideTile = AssetDatabase.LoadAssetAtPath<RuleOverrideTile>(overrideTilePath);
  420. if (overrideTile.m_Tile == target)
  421. {
  422. overrideTiles.Add(overrideTile);
  423. }
  424. }
  425. return overrideTiles;
  426. }
  427. /// <summary>
  428. /// Draws the header for the Rule list
  429. /// </summary>
  430. /// <param name="rect">GUI Rect to draw the header at</param>
  431. public void OnDrawHeader(Rect rect)
  432. {
  433. GUI.Label(rect, Styles.tilingRules);
  434. var toggleRect = new Rect(rect.xMax - rect.height, rect.y, rect.height, rect.height);
  435. var style = EditorGUIUtility.isProSkin ? Styles.extendNeighborsDarkStyle : Styles.extendNeighborsLightStyle;
  436. var extendSize = style.CalcSize(Styles.extendNeighbor);
  437. var toggleWidth = toggleRect.width + extendSize.x + 5f;
  438. var toggleLabelRect = new Rect(rect.x + rect.width - toggleWidth, rect.y, toggleWidth, rect.height);
  439. EditorGUI.BeginChangeCheck();
  440. extendNeighbor = EditorGUI.Toggle(toggleRect, extendNeighbor);
  441. EditorGUI.LabelField(toggleLabelRect, Styles.extendNeighbor, style);
  442. if (EditorGUI.EndChangeCheck())
  443. {
  444. if (m_ClearCacheMethod != null)
  445. m_ClearCacheMethod.Invoke(m_ReorderableList, null);
  446. }
  447. }
  448. /// <summary>
  449. /// Draws the Inspector GUI for the RuleTileEditor
  450. /// </summary>
  451. public override void OnInspectorGUI()
  452. {
  453. serializedObject.Update();
  454. Undo.RecordObject(target, k_UndoName);
  455. EditorGUI.BeginChangeCheck();
  456. tile.m_DefaultSprite = EditorGUILayout.ObjectField(Styles.defaultSprite, tile.m_DefaultSprite, typeof(Sprite), false) as Sprite;
  457. tile.m_DefaultGameObject = EditorGUILayout.ObjectField(Styles.defaultGameObject, tile.m_DefaultGameObject, typeof(GameObject), false) as GameObject;
  458. tile.m_DefaultColliderType = (Tile.ColliderType)EditorGUILayout.EnumPopup(Styles.defaultCollider, tile.m_DefaultColliderType);
  459. DrawCustomFields(false);
  460. EditorGUILayout.Space();
  461. EditorGUI.BeginChangeCheck();
  462. int count = EditorGUILayout.DelayedIntField(Styles.numberOfTilingRules, tile.m_TilingRules?.Count ?? 0);
  463. if (count < 0)
  464. count = 0;
  465. if (EditorGUI.EndChangeCheck())
  466. ResizeRuleTileList(count);
  467. if (count == 0)
  468. {
  469. Rect rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * 5);
  470. HandleDragAndDrop(rect);
  471. EditorGUI.DrawRect(rect, dragAndDropActive && rect.Contains(Event.current.mousePosition) ? Color.white : Color.black);
  472. var innerRect = new Rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
  473. EditorGUI.DrawRect(innerRect, EditorGUIUtility.isProSkin
  474. ? (Color) new Color32 (56, 56, 56, 255)
  475. : (Color) new Color32 (194, 194, 194, 255));
  476. DisplayClipboardText(Styles.emptyRuleTileInfo, rect);
  477. GUILayout.Space(rect.height);
  478. EditorGUILayout.Space();
  479. }
  480. if (m_ReorderableList != null)
  481. m_ReorderableList.DoLayoutList();
  482. if (EditorGUI.EndChangeCheck())
  483. SaveTile();
  484. GUILayout.Space(k_DefaultElementHeight);
  485. }
  486. private void ResizeRuleTileList(int count)
  487. {
  488. if (m_TilingRules.arraySize == count)
  489. return;
  490. var isEmpty = m_TilingRules.arraySize == 0;
  491. m_TilingRules.arraySize = count;
  492. serializedObject.ApplyModifiedProperties();
  493. if (isEmpty)
  494. {
  495. for (int i = 0; i < count; ++i)
  496. tile.m_TilingRules[i] = new RuleTile.TilingRule();
  497. }
  498. UpdateTilingRuleIds();
  499. }
  500. /// <summary>
  501. /// Draw editor fields for custom properties for the RuleTile
  502. /// </summary>
  503. /// <param name="isOverrideInstance">Whether override fields are drawn</param>
  504. public void DrawCustomFields(bool isOverrideInstance)
  505. {
  506. var customFields = tile.GetCustomFields(isOverrideInstance);
  507. serializedObject.Update();
  508. EditorGUI.BeginChangeCheck();
  509. foreach (var field in customFields)
  510. {
  511. var property = serializedObject.FindProperty(field.Name);
  512. if (property != null)
  513. EditorGUILayout.PropertyField(property, true);
  514. }
  515. if (EditorGUI.EndChangeCheck())
  516. {
  517. serializedObject.ApplyModifiedProperties();
  518. DestroyPreview();
  519. CreatePreview();
  520. }
  521. }
  522. /// <summary>
  523. /// Gets the index for a Rule with the RuleTile to display an arrow.
  524. /// </summary>
  525. /// <param name="position">The relative position of the arrow from the center.</param>
  526. /// <returns>Returns the index for a Rule with the RuleTile to display an arrow.</returns>
  527. public virtual int GetArrowIndex(Vector3Int position)
  528. {
  529. if (Mathf.Abs(position.x) == Mathf.Abs(position.y))
  530. {
  531. if (position.x < 0 && position.y > 0)
  532. return 0;
  533. else if (position.x > 0 && position.y > 0)
  534. return 2;
  535. else if (position.x < 0 && position.y < 0)
  536. return 6;
  537. else if (position.x > 0 && position.y < 0)
  538. return 8;
  539. }
  540. else if (Mathf.Abs(position.x) > Mathf.Abs(position.y))
  541. {
  542. if (position.x > 0)
  543. return 5;
  544. else
  545. return 3;
  546. }
  547. else
  548. {
  549. if (position.y > 0)
  550. return 1;
  551. else
  552. return 7;
  553. }
  554. return -1;
  555. }
  556. /// <summary>
  557. /// Draws a neighbor matching rule
  558. /// </summary>
  559. /// <param name="rect">Rect to draw on</param>
  560. /// <param name="position">The relative position of the arrow from the center</param>
  561. /// <param name="neighbor">The index to the neighbor matching criteria</param>
  562. public virtual void RuleOnGUI(Rect rect, Vector3Int position, int neighbor)
  563. {
  564. switch (neighbor)
  565. {
  566. case RuleTile.TilingRuleOutput.Neighbor.This:
  567. GUI.DrawTexture(rect, arrows[GetArrowIndex(position)]);
  568. break;
  569. case RuleTile.TilingRuleOutput.Neighbor.NotThis:
  570. GUI.DrawTexture(rect, arrows[9]);
  571. break;
  572. default:
  573. var style = new GUIStyle();
  574. style.alignment = TextAnchor.MiddleCenter;
  575. style.fontSize = 10;
  576. GUI.Label(rect, neighbor.ToString(), style);
  577. break;
  578. }
  579. }
  580. /// <summary>
  581. /// Draws a tooltip for the neighbor matching rule
  582. /// </summary>
  583. /// <param name="rect">Rect to draw on</param>
  584. /// <param name="neighbor">The index to the neighbor matching criteria</param>
  585. public void RuleTooltipOnGUI(Rect rect, int neighbor)
  586. {
  587. var allConsts = tile.m_NeighborType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
  588. foreach (var c in allConsts)
  589. {
  590. if ((int)c.GetValue(null) == neighbor)
  591. {
  592. GUI.Label(rect, new GUIContent("", c.Name));
  593. break;
  594. }
  595. }
  596. }
  597. /// <summary>
  598. /// Draws a transform matching rule
  599. /// </summary>
  600. /// <param name="rect">Rect to draw on</param>
  601. /// <param name="ruleTransform">The transform matching criteria</param>
  602. public virtual void RuleTransformOnGUI(Rect rect, RuleTile.TilingRuleOutput.Transform ruleTransform)
  603. {
  604. switch (ruleTransform)
  605. {
  606. case RuleTile.TilingRuleOutput.Transform.Rotated:
  607. GUI.DrawTexture(rect, autoTransforms[0]);
  608. break;
  609. case RuleTile.TilingRuleOutput.Transform.MirrorX:
  610. GUI.DrawTexture(rect, autoTransforms[1]);
  611. break;
  612. case RuleTile.TilingRuleOutput.Transform.MirrorY:
  613. GUI.DrawTexture(rect, autoTransforms[2]);
  614. break;
  615. case RuleTile.TilingRuleOutput.Transform.Fixed:
  616. GUI.DrawTexture(rect, autoTransforms[3]);
  617. break;
  618. case RuleTile.TilingRuleOutput.Transform.MirrorXY:
  619. GUI.DrawTexture(rect, autoTransforms[4]);
  620. break;
  621. case RuleTile.TilingRuleOutput.Transform.RotatedMirror:
  622. GUI.DrawTexture(rect, autoTransforms[5]);
  623. break;
  624. }
  625. GUI.Label(rect, new GUIContent("", ruleTransform.ToString()));
  626. }
  627. /// <summary>
  628. /// Handles a neighbor matching Rule update from user mouse input
  629. /// </summary>
  630. /// <param name="rect">Rect containing neighbor matching Rule GUI</param>
  631. /// <param name="tilingRule">Tiling Rule to update neighbor matching rule</param>
  632. /// <param name="neighbors">A dictionary of neighbors</param>
  633. /// <param name="position">The relative position of the neighbor matching Rule</param>
  634. public void RuleNeighborUpdate(Rect rect, RuleTile.TilingRule tilingRule, Dictionary<Vector3Int, int> neighbors, Vector3Int position)
  635. {
  636. if (Event.current.type == EventType.MouseDown && ContainsMousePosition(rect))
  637. {
  638. var allConsts = tile.m_NeighborType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
  639. var neighborConsts = allConsts.Select(c => (int)c.GetValue(null)).ToList();
  640. neighborConsts.Sort();
  641. if (neighbors.ContainsKey(position))
  642. {
  643. int oldIndex = neighborConsts.IndexOf(neighbors[position]);
  644. int newIndex = oldIndex + GetMouseChange();
  645. if (newIndex >= 0 && newIndex < neighborConsts.Count)
  646. {
  647. newIndex = (int)Mathf.Repeat(newIndex, neighborConsts.Count);
  648. neighbors[position] = neighborConsts[newIndex];
  649. }
  650. else
  651. {
  652. neighbors.Remove(position);
  653. }
  654. }
  655. else
  656. {
  657. neighbors.Add(position, neighborConsts[GetMouseChange() == 1 ? 0 : (neighborConsts.Count - 1)]);
  658. }
  659. tilingRule.ApplyNeighbors(neighbors);
  660. GUI.changed = true;
  661. Event.current.Use();
  662. }
  663. }
  664. /// <summary>
  665. /// Handles a transform matching Rule update from user mouse input
  666. /// </summary>
  667. /// <param name="rect">Rect containing transform matching Rule GUI</param>
  668. /// <param name="tilingRule">Tiling Rule to update transform matching rule</param>
  669. public void RuleTransformUpdate(Rect rect, RuleTile.TilingRule tilingRule)
  670. {
  671. if (Event.current.type == EventType.MouseDown && ContainsMousePosition(rect))
  672. {
  673. tilingRule.m_RuleTransform = (RuleTile.TilingRuleOutput.Transform)(int)Mathf.Repeat((int)tilingRule.m_RuleTransform + GetMouseChange(), Enum.GetValues(typeof(RuleTile.TilingRule.Transform)).Length);
  674. GUI.changed = true;
  675. Event.current.Use();
  676. }
  677. }
  678. /// <summary>
  679. /// Determines the current mouse position is within the given Rect.
  680. /// </summary>
  681. /// <param name="rect">Rect to test mouse position for.</param>
  682. /// <returns>True if the current mouse position is within the given Rect. False otherwise.</returns>
  683. public virtual bool ContainsMousePosition(Rect rect)
  684. {
  685. return rect.Contains(Event.current.mousePosition);
  686. }
  687. /// <summary>
  688. /// Gets the offset change for a mouse click input
  689. /// </summary>
  690. /// <returns>The offset change for a mouse click input</returns>
  691. public static int GetMouseChange()
  692. {
  693. return Event.current.button == 1 ? -1 : 1;
  694. }
  695. /// <summary>
  696. /// Draws a Rule Matrix for the given Rule for a RuleTile.
  697. /// </summary>
  698. /// <param name="tile">Tile to draw rule for.</param>
  699. /// <param name="rect">GUI Rect to draw rule at.</param>
  700. /// <param name="bounds">Cell bounds of the Rule.</param>
  701. /// <param name="tilingRule">Rule to draw Rule Matrix for.</param>
  702. public virtual void RuleMatrixOnGUI(RuleTile tile, Rect rect, BoundsInt bounds, RuleTile.TilingRule tilingRule)
  703. {
  704. Handles.color = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.2f) : new Color(0f, 0f, 0f, 0.2f);
  705. float w = rect.width / bounds.size.x;
  706. float h = rect.height / bounds.size.y;
  707. for (int y = 0; y <= bounds.size.y; y++)
  708. {
  709. float top = rect.yMin + y * h;
  710. Handles.DrawLine(new Vector3(rect.xMin, top), new Vector3(rect.xMax, top));
  711. }
  712. for (int x = 0; x <= bounds.size.x; x++)
  713. {
  714. float left = rect.xMin + x * w;
  715. Handles.DrawLine(new Vector3(left, rect.yMin), new Vector3(left, rect.yMax));
  716. }
  717. Handles.color = Color.white;
  718. var neighbors = tilingRule.GetNeighbors();
  719. for (int y = bounds.yMin; y < bounds.yMax; y++)
  720. {
  721. for (int x = bounds.xMin; x < bounds.xMax; x++)
  722. {
  723. Vector3Int pos = new Vector3Int(x, y, 0);
  724. Rect r = new Rect(rect.xMin + (x - bounds.xMin) * w, rect.yMin + (-y + bounds.yMax - 1) * h, w - 1, h - 1);
  725. RuleMatrixIconOnGUI(tilingRule, neighbors, pos, r);
  726. }
  727. }
  728. }
  729. /// <summary>
  730. /// Draws a Rule Matrix Icon for the given matching Rule for a RuleTile with the given position
  731. /// </summary>
  732. /// <param name="tilingRule">Tile to draw rule for.</param>
  733. /// <param name="neighbors">A dictionary of neighbors</param>
  734. /// <param name="position">The relative position of the neighbor matching Rule</param>
  735. /// <param name="rect">GUI Rect to draw icon at</param>
  736. public void RuleMatrixIconOnGUI(RuleTile.TilingRule tilingRule, Dictionary<Vector3Int, int> neighbors, Vector3Int position, Rect rect)
  737. {
  738. using (var check = new EditorGUI.ChangeCheckScope())
  739. {
  740. if (position.x != 0 || position.y != 0)
  741. {
  742. if (neighbors.ContainsKey(position))
  743. {
  744. RuleOnGUI(rect, position, neighbors[position]);
  745. RuleTooltipOnGUI(rect, neighbors[position]);
  746. }
  747. RuleNeighborUpdate(rect, tilingRule, neighbors, position);
  748. }
  749. else
  750. {
  751. RuleTransformOnGUI(rect, tilingRule.m_RuleTransform);
  752. RuleTransformUpdate(rect, tilingRule);
  753. }
  754. if (check.changed)
  755. {
  756. tile.UpdateNeighborPositions();
  757. }
  758. }
  759. }
  760. /// <summary>
  761. /// Draws a Sprite field for the Rule
  762. /// </summary>
  763. /// <param name="rect">Rect to draw Sprite Inspector in</param>
  764. /// <param name="tilingRule">Rule to draw Sprite Inspector for</param>
  765. public virtual void SpriteOnGUI(Rect rect, RuleTile.TilingRuleOutput tilingRule)
  766. {
  767. tilingRule.m_Sprites[0] = EditorGUI.ObjectField(rect, tilingRule.m_Sprites[0], typeof(Sprite), false) as Sprite;
  768. }
  769. /// <summary>
  770. /// Draws an Inspector for the Rule
  771. /// </summary>
  772. /// <param name="rect">Rect to draw Inspector in</param>
  773. /// <param name="tilingRule">Rule to draw Inspector for</param>
  774. public void RuleInspectorOnGUI(Rect rect, RuleTile.TilingRuleOutput tilingRule)
  775. {
  776. float y = rect.yMin;
  777. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesGameObject);
  778. tilingRule.m_GameObject = (GameObject)EditorGUI.ObjectField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), "", tilingRule.m_GameObject, typeof(GameObject), false);
  779. y += k_SingleLineHeight;
  780. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesCollider);
  781. tilingRule.m_ColliderType = (Tile.ColliderType)EditorGUI.EnumPopup(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_ColliderType);
  782. y += k_SingleLineHeight;
  783. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesOutput);
  784. tilingRule.m_Output = (RuleTile.TilingRuleOutput.OutputSprite)EditorGUI.EnumPopup(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_Output);
  785. y += k_SingleLineHeight;
  786. if (tilingRule.m_Output == RuleTile.TilingRuleOutput.OutputSprite.Animation)
  787. {
  788. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesMinSpeed);
  789. tilingRule.m_MinAnimationSpeed = EditorGUI.FloatField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_MinAnimationSpeed);
  790. y += k_SingleLineHeight;
  791. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesMaxSpeed);
  792. tilingRule.m_MaxAnimationSpeed = EditorGUI.FloatField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_MaxAnimationSpeed);
  793. y += k_SingleLineHeight;
  794. }
  795. if (tilingRule.m_Output == RuleTile.TilingRuleOutput.OutputSprite.Random)
  796. {
  797. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesNoise);
  798. tilingRule.m_PerlinScale = EditorGUI.Slider(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_PerlinScale, 0.001f, 0.999f);
  799. y += k_SingleLineHeight;
  800. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight), Styles.tilingRulesShuffle);
  801. tilingRule.m_RandomTransform = (RuleTile.TilingRuleOutput.Transform)EditorGUI.EnumPopup(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_RandomTransform);
  802. y += k_SingleLineHeight;
  803. }
  804. if (tilingRule.m_Output != RuleTile.TilingRuleOutput.OutputSprite.Single)
  805. {
  806. GUI.Label(new Rect(rect.xMin, y, k_LabelWidth, k_SingleLineHeight)
  807. , tilingRule.m_Output == RuleTile.TilingRuleOutput.OutputSprite.Animation ? Styles.tilingRulesAnimationSize : Styles.tilingRulesRandomSize);
  808. EditorGUI.BeginChangeCheck();
  809. int newLength = EditorGUI.DelayedIntField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_Sprites.Length);
  810. if (EditorGUI.EndChangeCheck())
  811. Array.Resize(ref tilingRule.m_Sprites, Math.Max(newLength, 1));
  812. y += k_SingleLineHeight;
  813. for (int i = 0; i < tilingRule.m_Sprites.Length; i++)
  814. {
  815. tilingRule.m_Sprites[i] = EditorGUI.ObjectField(new Rect(rect.xMin + k_LabelWidth, y, rect.width - k_LabelWidth, k_SingleLineHeight), tilingRule.m_Sprites[i], typeof(Sprite), false) as Sprite;
  816. y += k_SingleLineHeight;
  817. }
  818. }
  819. }
  820. private void DisplayClipboardText(GUIContent clipboardText, Rect position)
  821. {
  822. Color old = GUI.color;
  823. GUI.color = Color.gray;
  824. var infoSize = GUI.skin.label.CalcSize(clipboardText);
  825. Rect rect = new Rect(position.center.x - infoSize.x * .5f
  826. , position.center.y - infoSize.y * .5f
  827. , infoSize.x
  828. , infoSize.y);
  829. GUI.Label(rect, clipboardText);
  830. GUI.color = old;
  831. }
  832. private bool dragAndDropActive
  833. {
  834. get
  835. {
  836. return dragAndDropSprites != null
  837. && dragAndDropSprites.Count > 0;
  838. }
  839. }
  840. private static List<Sprite> GetSpritesFromTexture(Texture2D texture)
  841. {
  842. string path = AssetDatabase.GetAssetPath(texture);
  843. Object[] assets = AssetDatabase.LoadAllAssetsAtPath(path);
  844. List<Sprite> sprites = new List<Sprite>();
  845. foreach (Object asset in assets)
  846. {
  847. if (asset is Sprite)
  848. {
  849. sprites.Add(asset as Sprite);
  850. }
  851. }
  852. return sprites;
  853. }
  854. private static List<Sprite> GetValidSingleSprites(Object[] objects)
  855. {
  856. List<Sprite> result = new List<Sprite>();
  857. foreach (Object obj in objects)
  858. {
  859. if (obj is Sprite sprite)
  860. {
  861. result.Add(sprite);
  862. }
  863. else if (obj is Texture2D texture2D)
  864. {
  865. List<Sprite> sprites = GetSpritesFromTexture(texture2D);
  866. if (sprites.Count > 0)
  867. {
  868. result.AddRange(sprites);
  869. }
  870. }
  871. }
  872. return result;
  873. }
  874. private void HandleDragAndDrop(Rect guiRect)
  875. {
  876. if (DragAndDrop.objectReferences.Length == 0 || !guiRect.Contains(Event.current.mousePosition))
  877. return;
  878. switch (Event.current.type)
  879. {
  880. case EventType.DragUpdated:
  881. {
  882. dragAndDropSprites = GetValidSingleSprites(DragAndDrop.objectReferences);
  883. if (dragAndDropActive)
  884. {
  885. DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
  886. Event.current.Use();
  887. GUI.changed = true;
  888. }
  889. }
  890. break;
  891. case EventType.DragPerform:
  892. {
  893. if (!dragAndDropActive)
  894. return;
  895. Undo.RegisterCompleteObjectUndo(tile, "Drag and Drop to Rule Tile");
  896. ResizeRuleTileList(dragAndDropSprites.Count);
  897. for (int i = 0; i < dragAndDropSprites.Count; ++i)
  898. {
  899. tile.m_TilingRules[i].m_Sprites[0] = dragAndDropSprites[i];
  900. }
  901. DragAndDropClear();
  902. GUI.changed = true;
  903. EditorUtility.SetDirty(tile);
  904. GUIUtility.ExitGUI();
  905. }
  906. break;
  907. case EventType.Repaint:
  908. // Handled in Render()
  909. break;
  910. }
  911. if (Event.current.type == EventType.DragExited ||
  912. Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)
  913. {
  914. DragAndDropClear();
  915. }
  916. }
  917. private void DragAndDropClear()
  918. {
  919. dragAndDropSprites = null;
  920. DragAndDrop.visualMode = DragAndDropVisualMode.None;
  921. Event.current.Use();
  922. }
  923. /// <summary>
  924. /// Whether the RuleTile has a preview GUI
  925. /// </summary>
  926. /// <returns>True</returns>
  927. public override bool HasPreviewGUI()
  928. {
  929. return true;
  930. }
  931. /// <summary>
  932. /// Draws the preview GUI for the RuleTile
  933. /// </summary>
  934. /// <param name="rect">Rect to draw the preview GUI</param>
  935. /// <param name="background">The GUIStyle of the background for the preview</param>
  936. public override void OnPreviewGUI(Rect rect, GUIStyle background)
  937. {
  938. if (m_PreviewUtility == null)
  939. CreatePreview();
  940. if (Event.current.type != EventType.Repaint)
  941. return;
  942. m_PreviewUtility.BeginPreview(rect, background);
  943. m_PreviewUtility.camera.orthographicSize = 2;
  944. if (rect.height > rect.width)
  945. m_PreviewUtility.camera.orthographicSize *= rect.height / rect.width;
  946. m_PreviewUtility.camera.Render();
  947. m_PreviewUtility.EndAndDrawPreview(rect);
  948. }
  949. /// <summary>
  950. /// Creates a Preview for the RuleTile.
  951. /// </summary>
  952. protected virtual void CreatePreview()
  953. {
  954. m_PreviewUtility = new PreviewRenderUtility(true);
  955. m_PreviewUtility.camera.orthographic = true;
  956. m_PreviewUtility.camera.orthographicSize = 2;
  957. m_PreviewUtility.camera.transform.position = new Vector3(0, 0, -10);
  958. var previewInstance = new GameObject();
  959. m_PreviewGrid = previewInstance.AddComponent<Grid>();
  960. m_PreviewUtility.AddSingleGO(previewInstance);
  961. m_PreviewTilemaps = new List<Tilemap>();
  962. m_PreviewTilemapRenderers = new List<TilemapRenderer>();
  963. for (int i = 0; i < 4; i++)
  964. {
  965. var previewTilemapGo = new GameObject();
  966. m_PreviewTilemaps.Add(previewTilemapGo.AddComponent<Tilemap>());
  967. m_PreviewTilemapRenderers.Add(previewTilemapGo.AddComponent<TilemapRenderer>());
  968. previewTilemapGo.transform.SetParent(previewInstance.transform, false);
  969. }
  970. for (int x = -2; x <= 0; x++)
  971. for (int y = -1; y <= 1; y++)
  972. m_PreviewTilemaps[0].SetTile(new Vector3Int(x, y, 0), tile);
  973. for (int y = -1; y <= 1; y++)
  974. m_PreviewTilemaps[1].SetTile(new Vector3Int(1, y, 0), tile);
  975. for (int x = -2; x <= 0; x++)
  976. m_PreviewTilemaps[2].SetTile(new Vector3Int(x, -2, 0), tile);
  977. m_PreviewTilemaps[3].SetTile(new Vector3Int(1, -2, 0), tile);
  978. }
  979. /// <summary>
  980. /// Handles cleanup for the Preview GUI
  981. /// </summary>
  982. protected virtual void DestroyPreview()
  983. {
  984. if (m_PreviewUtility != null)
  985. {
  986. m_PreviewUtility.Cleanup();
  987. m_PreviewUtility = null;
  988. m_PreviewGrid = null;
  989. m_PreviewTilemaps = null;
  990. m_PreviewTilemapRenderers = null;
  991. }
  992. }
  993. /// <summary>
  994. /// Renders a static preview Texture2D for a RuleTile asset
  995. /// </summary>
  996. /// <param name="assetPath">Asset path of the RuleTile</param>
  997. /// <param name="subAssets">Arrays of assets from the given Asset path</param>
  998. /// <param name="width">Width of the static preview</param>
  999. /// <param name="height">Height of the static preview </param>
  1000. /// <returns>Texture2D containing static preview for the RuleTile asset</returns>
  1001. public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
  1002. {
  1003. if (tile.m_DefaultSprite != null)
  1004. {
  1005. Type t = GetType("UnityEditor.SpriteUtility");
  1006. if (t != null)
  1007. {
  1008. MethodInfo method = t.GetMethod("RenderStaticPreview", new[] { typeof(Sprite), typeof(Color), typeof(int), typeof(int) });
  1009. if (method != null)
  1010. {
  1011. object ret = method.Invoke("RenderStaticPreview", new object[] { tile.m_DefaultSprite, Color.white, width, height });
  1012. if (ret is Texture2D)
  1013. return ret as Texture2D;
  1014. }
  1015. }
  1016. }
  1017. return base.RenderStaticPreview(assetPath, subAssets, width, height);
  1018. }
  1019. private static Type GetType(string typeName)
  1020. {
  1021. var type = Type.GetType(typeName);
  1022. if (type != null)
  1023. return type;
  1024. var currentAssembly = Assembly.GetExecutingAssembly();
  1025. var referencedAssemblies = currentAssembly.GetReferencedAssemblies();
  1026. foreach (var assemblyName in referencedAssemblies)
  1027. {
  1028. var assembly = Assembly.Load(assemblyName);
  1029. if (assembly != null)
  1030. {
  1031. type = assembly.GetType(typeName);
  1032. if (type != null)
  1033. return type;
  1034. }
  1035. }
  1036. return null;
  1037. }
  1038. /// <summary>
  1039. /// Converts a Base64 string to a Texture2D
  1040. /// </summary>
  1041. /// <param name="base64">Base64 string containing image data</param>
  1042. /// <returns>Texture2D containing an image from the given Base64 string</returns>
  1043. public static Texture2D Base64ToTexture(string base64)
  1044. {
  1045. Texture2D t = new Texture2D(1, 1);
  1046. t.hideFlags = HideFlags.HideAndDontSave;
  1047. t.LoadImage(Convert.FromBase64String(base64));
  1048. return t;
  1049. }
  1050. /// <summary>
  1051. /// Wrapper for serializing a list of Rules
  1052. /// </summary>
  1053. [Serializable]
  1054. class RuleTileRuleWrapper
  1055. {
  1056. /// <summary>
  1057. /// List of Rules to serialize
  1058. /// </summary>
  1059. [SerializeField]
  1060. public List<RuleTile.TilingRule> rules = new List<RuleTile.TilingRule>();
  1061. }
  1062. /// <summary>
  1063. /// Copies all Rules from a RuleTile to the clipboard
  1064. /// </summary>
  1065. /// <param name="item">MenuCommand storing the RuleTile to copy from</param>
  1066. [MenuItem("CONTEXT/RuleTile/Copy All Rules")]
  1067. public static void CopyAllRules(MenuCommand item)
  1068. {
  1069. RuleTile tile = item.context as RuleTile;
  1070. if (tile == null)
  1071. return;
  1072. RuleTileRuleWrapper rulesWrapper = new RuleTileRuleWrapper();
  1073. rulesWrapper.rules = tile.m_TilingRules;
  1074. var rulesJson = EditorJsonUtility.ToJson(rulesWrapper);
  1075. EditorGUIUtility.systemCopyBuffer = rulesJson;
  1076. }
  1077. /// <summary>
  1078. /// Pastes all Rules from the clipboard to a RuleTile
  1079. /// </summary>
  1080. /// <param name="item">MenuCommand storing the RuleTile to paste to</param>
  1081. [MenuItem("CONTEXT/RuleTile/Paste Rules")]
  1082. public static void PasteRules(MenuCommand item)
  1083. {
  1084. RuleTile tile = item.context as RuleTile;
  1085. if (tile == null)
  1086. return;
  1087. try
  1088. {
  1089. RuleTileRuleWrapper rulesWrapper = new RuleTileRuleWrapper();
  1090. EditorJsonUtility.FromJsonOverwrite(EditorGUIUtility.systemCopyBuffer, rulesWrapper);
  1091. tile.m_TilingRules.AddRange(rulesWrapper.rules);
  1092. }
  1093. catch (Exception)
  1094. {
  1095. Debug.LogError("Unable to paste rules from system copy buffer");
  1096. }
  1097. }
  1098. }
  1099. }