暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

GridPaintingState.cs 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using UnityEditor.EditorTools;
  6. using UnityEditor.ShortcutManagement;
  7. using UnityEngine;
  8. using Cursor = UnityEngine.Cursor;
  9. namespace UnityEditor.Tilemaps
  10. {
  11. /// <summary>
  12. /// GridPaintingState controls the state of objects for painting with a Tile Palette.
  13. /// </summary>
  14. /// <remarks>
  15. /// Utilize this class to get and set the current painting target and brush for painting
  16. /// with the Tile Palette.
  17. /// </remarks>
  18. public class GridPaintingState : ScriptableSingleton<GridPaintingState>
  19. {
  20. [SerializeField] private GameObject m_EditModeScenePaintTarget; // Which GameObject in scene was the last painting target in EditMode
  21. [SerializeField] private GameObject m_ScenePaintTarget; // Which GameObject in scene is considered as painting target
  22. [SerializeField] private EditorTool[] m_BrushTools;
  23. [SerializeField] private GridBrushBase m_Brush; // Which brush will handle painting callbacks
  24. [SerializeField] private GridBrushPickStore m_BrushPickStore; // Stores prior brush selection settings
  25. [SerializeField] private HashSet<PaintableGrid> m_ActiveGridsSet = new HashSet<PaintableGrid>();
  26. [SerializeField] private PaintableGrid m_ActiveGrid; // Grid that has painting focus (can be palette, too)
  27. [SerializeField] private PaintableGrid m_LastActiveGrid; // Grid that last had painting focus (can be palette, too)
  28. [SerializeField] private HashSet<System.Object> m_InterestedPainters = new HashSet<System.Object>(); // A list of objects that can paint using the GridPaintingState
  29. [SerializeField] private GameObject m_Palette;
  30. private bool m_HasActivePick;
  31. [SerializeField] private BoundsInt m_ActivePick;
  32. [SerializeField] private Vector3Int m_ActivePivot;
  33. [SerializeField] private GameObject m_ActivePickPalette;
  34. [SerializeField] private bool m_DrawGridGizmo = true;
  35. [SerializeField] private bool m_DrawGizmos;
  36. [SerializeField] private bool m_IsEditing;
  37. private GameObject[] m_CachedPaintTargets;
  38. private bool m_FlushPaintTargetCache;
  39. private Editor m_CachedEditor;
  40. private bool m_SavingPalette;
  41. private float m_BrushToolbarSize;
  42. private GridBrushEditorBase m_PreviousToolActivatedEditor;
  43. private GridBrushBase.Tool m_PreviousToolActivated;
  44. private PaintableSceneViewGrid m_PaintableSceneViewGrid;
  45. /// <summary>
  46. /// Callback when the Tile Palette's active target has changed
  47. /// </summary>
  48. public static event Action<GameObject> scenePaintTargetChanged;
  49. /// <summary>
  50. /// Callback when the Tile Palette's active target has been edited
  51. /// </summary>
  52. public static event Action<GameObject> scenePaintTargetEdited;
  53. /// <summary>
  54. /// Callback when the Tile Palette's active brush has changed.
  55. /// </summary>
  56. public static event Action<GridBrushBase> brushChanged;
  57. /// <summary>
  58. /// Callback when the Tile Palette's active brush's selection has changed.
  59. /// </summary>
  60. public static event Action brushPickChanged;
  61. /// <summary>
  62. /// Callback when the Tile Palette's brush selection store has changed.
  63. /// </summary>
  64. public static event Action brushPickStoreChanged;
  65. /// <summary>
  66. /// Callback when the Tile Palette's active brush tools have changed.
  67. /// </summary>
  68. public static event Action brushToolsChanged;
  69. /// <summary>
  70. /// Callback before the Tile Palette's active palette GameObject has changed.
  71. /// </summary>
  72. public static event Action beforePaletteChanged;
  73. /// <summary>
  74. /// Callback when the Tile Palette's active palette GameObject has changed.
  75. /// </summary>
  76. public static event Action<GameObject> paletteChanged;
  77. /// <summary>
  78. /// Callback when the Tile Palette's list of palettes has changed
  79. /// </summary>
  80. public static event Action palettesChanged;
  81. /// <summary>
  82. /// Callback when the Tile Palette's valid targets has changed.
  83. /// </summary>
  84. public static event Action validTargetsChanged;
  85. /// <summary>
  86. /// Callback when Tile Palette edit mode has changed.
  87. /// </summary>
  88. public static event Action editModeChanged;
  89. private static readonly string k_TilemapLastPaletteEditorPref = "TilemapLastPalette";
  90. private string lastTilemapPalette
  91. {
  92. get => EditorPrefs.GetString(k_TilemapLastPaletteEditorPref, "");
  93. set => EditorPrefs.SetString(k_TilemapLastPaletteEditorPref, value);
  94. }
  95. private static readonly string k_GridBrushMousePositionAtZ = "TilemapGridBrushMousePositionAtZ";
  96. private static bool? m_CachedGridBrushMousePositionAtZ;
  97. internal static bool gridBrushMousePositionAtZ
  98. {
  99. get
  100. {
  101. m_CachedGridBrushMousePositionAtZ ??= EditorPrefs.GetBool(k_GridBrushMousePositionAtZ, false);
  102. return m_CachedGridBrushMousePositionAtZ.Value;
  103. }
  104. set
  105. {
  106. m_CachedGridBrushMousePositionAtZ = value;
  107. EditorPrefs.SetBool(k_GridBrushMousePositionAtZ, value);
  108. }
  109. }
  110. readonly TilemapEditorTool.ShortcutContext m_ShortcutContext = new TilemapEditorTool.ShortcutContext { active = true };
  111. private void OnEnable()
  112. {
  113. EditorApplication.hierarchyChanged += HierarchyChanged;
  114. EditorApplication.playModeStateChanged += PlayModeStateChanged;
  115. Selection.selectionChanged += OnSelectionChange;
  116. Undo.selectionUndoRedoPerformed += OnSelectionUndoRedoPerformed;
  117. m_FlushPaintTargetCache = true;
  118. }
  119. private void OnDisable()
  120. {
  121. m_InterestedPainters.Clear();
  122. EditorApplication.hierarchyChanged -= HierarchyChanged;
  123. EditorApplication.playModeStateChanged -= PlayModeStateChanged;
  124. Selection.selectionChanged -= OnSelectionChange;
  125. Undo.selectionUndoRedoPerformed -= OnSelectionUndoRedoPerformed;
  126. FlushCache();
  127. }
  128. private void OnEditEnable()
  129. {
  130. isEditing = true;
  131. if (palette == null && !String.IsNullOrEmpty(lastTilemapPalette))
  132. {
  133. var lastPalette = GridPalettes.palettes
  134. .Where((paletteInList, _) => (AssetDatabase.GetAssetPath(paletteInList) == lastTilemapPalette))
  135. .FirstOrDefault();
  136. if (lastPalette != null)
  137. palette = lastPalette;
  138. }
  139. if (palette == null && GridPalettes.palettes.Count > 0)
  140. {
  141. palette = GridPalettes.palettes[0];
  142. }
  143. if (m_PaintableSceneViewGrid == null)
  144. {
  145. m_PaintableSceneViewGrid = CreateInstance<PaintableSceneViewGrid>();
  146. m_PaintableSceneViewGrid.hideFlags = HideFlags.HideAndDontSave;
  147. m_PaintableSceneViewGrid.onEdited += OnEdited;
  148. }
  149. m_FlushPaintTargetCache = true;
  150. GridPaletteBrushes.FlushCache();
  151. GridPaletteBrushes.RefreshCache();
  152. if (gridBrush != null)
  153. GetValidTargets();
  154. GridPalettes.palettesChanged += PalettesChanged;
  155. ShortcutIntegration.instance.profileManager.shortcutBindingChanged += UpdateTooltips;
  156. scenePaintTargetChanged += TilemapFocusModeUtility.OnScenePaintTargetChanged;
  157. brushChanged += TilemapFocusModeUtility.OnBrushChanged;
  158. paletteChanged += PaletteChanged;
  159. SceneView.duringSceneGui += TilemapFocusModeUtility.OnSceneViewGUI;
  160. ToolManager.activeToolChanged += ActiveToolChanged;
  161. ToolManager.activeToolChanging += ActiveToolChanging;
  162. ShortcutIntegration.instance.contextManager.RegisterToolContext(m_ShortcutContext);
  163. }
  164. private void OnEdited(GameObject obj)
  165. {
  166. scenePaintTargetEdited?.Invoke(obj);
  167. }
  168. private void PaletteChanged(GameObject obj)
  169. {
  170. lastTilemapPalette = AssetDatabase.GetAssetPath(palette);
  171. }
  172. private void PalettesChanged()
  173. {
  174. palettesChanged?.Invoke();
  175. }
  176. private void OnEditDisable()
  177. {
  178. TilemapFocusModeUtility.SetFocusMode(TilemapFocusModeUtility.TilemapFocusMode.None);
  179. CallOnToolDeactivated();
  180. gridBrush = null;
  181. GridPaletteBrushes.FlushCache();
  182. DestroyImmediate(m_BrushPickStore);
  183. DestroyImmediate(m_PaintableSceneViewGrid);
  184. if (PaintableGrid.InGridEditMode())
  185. {
  186. // Set Editor Tool to an always available Tool, as Tile Palette Tools are not available any more
  187. ToolManager.SetActiveTool<ViewModeTool>();
  188. }
  189. ShortcutIntegration.instance.profileManager.shortcutBindingChanged -= UpdateTooltips;
  190. ToolManager.activeToolChanged -= ActiveToolChanged;
  191. ToolManager.activeToolChanging -= ActiveToolChanging;
  192. SceneView.duringSceneGui -= TilemapFocusModeUtility.OnSceneViewGUI;
  193. brushChanged -= TilemapFocusModeUtility.OnBrushChanged;
  194. paletteChanged -= PaletteChanged;
  195. GridPalettes.palettesChanged -= PalettesChanged;
  196. ShortcutIntegration.instance.contextManager.DeregisterToolContext(m_ShortcutContext);
  197. isEditing = false;
  198. }
  199. private void ActiveToolChanged()
  200. {
  201. if (gridBrush != null && PaintableGrid.InGridEditMode() && activeBrushEditor != null)
  202. {
  203. GridBrushBase.Tool tool = PaintableGrid.EditTypeToBrushTool(ToolManager.activeToolType);
  204. activeBrushEditor.OnToolActivated(tool);
  205. m_PreviousToolActivatedEditor = activeBrushEditor;
  206. m_PreviousToolActivated = tool;
  207. for (int i = 0; i < TilePaletteMouseCursorUtility.MouseStyles.sceneViewEditModes.Length; ++i)
  208. {
  209. if (TilePaletteMouseCursorUtility.MouseStyles.sceneViewEditModes[i] == tool)
  210. {
  211. Cursor.SetCursor(TilePaletteMouseCursorUtility.MouseStyles.mouseCursorTextures[i],
  212. TilePaletteMouseCursorUtility.MouseStyles.mouseCursorTextures[i] != null ? TilePaletteMouseCursorUtility.MouseStyles.mouseCursorOSHotspot[(int)SystemInfo.operatingSystemFamily] : Vector2.zero,
  213. CursorMode.Auto);
  214. break;
  215. }
  216. }
  217. }
  218. else
  219. {
  220. Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
  221. }
  222. if (GridSelection.active
  223. && !TilemapEditorTool.IsActive(typeof(MoveTool))
  224. && !TilemapEditorTool.IsActive(typeof(SelectTool))
  225. && !ToolManager.activeToolType.IsSubclassOf(typeof(GridSelectionTool)))
  226. {
  227. GridSelection.Clear();
  228. }
  229. }
  230. private void ActiveToolChanging()
  231. {
  232. CallOnToolDeactivated();
  233. }
  234. private void CallOnToolDeactivated()
  235. {
  236. if (gridBrush != null && m_PreviousToolActivatedEditor != null)
  237. {
  238. m_PreviousToolActivatedEditor.OnToolDeactivated(m_PreviousToolActivated);
  239. m_PreviousToolActivatedEditor = null;
  240. if (!PaintableGrid.InGridEditMode())
  241. Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
  242. }
  243. }
  244. private void OnSelectionChange()
  245. {
  246. if (!hasInterestedPainters)
  247. return;
  248. var selectedObject = Selection.activeGameObject;
  249. if (ValidatePaintTarget(selectedObject))
  250. {
  251. scenePaintTarget = selectedObject;
  252. }
  253. if (selectedObject != null)
  254. {
  255. var isPrefab = EditorUtility.IsPersistent(selectedObject) || (selectedObject.hideFlags & HideFlags.NotEditable) != 0;
  256. if (isPrefab)
  257. {
  258. var assetPath = AssetDatabase.GetAssetPath(selectedObject);
  259. var allAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetPath);
  260. foreach (var asset in allAssets)
  261. {
  262. if (asset != null && asset.GetType() == typeof(GridPalette))
  263. {
  264. var targetPalette = (GameObject)AssetDatabase.LoadMainAssetAtPath(assetPath);
  265. if (targetPalette != palette)
  266. palette = targetPalette;
  267. break;
  268. }
  269. }
  270. }
  271. }
  272. }
  273. private void OnSelectionUndoRedoPerformed(Undo.UndoRedoType undo)
  274. {
  275. if (GridSelection.active && !TilemapEditorTool.IsActive(typeof(SelectTool)))
  276. TilemapEditorTool.ToggleActiveEditorTool(typeof(SelectTool));
  277. }
  278. private void PlayModeStateChanged(PlayModeStateChange state)
  279. {
  280. if (state == PlayModeStateChange.ExitingEditMode)
  281. {
  282. m_EditModeScenePaintTarget = scenePaintTarget;
  283. }
  284. else if (state == PlayModeStateChange.EnteredEditMode)
  285. {
  286. if (GridPaintActiveTargetsPreferences.restoreEditModeSelection && m_EditModeScenePaintTarget != null)
  287. {
  288. scenePaintTarget = m_EditModeScenePaintTarget;
  289. }
  290. }
  291. }
  292. private void HierarchyChanged()
  293. {
  294. if (hasInterestedPainters)
  295. {
  296. m_FlushPaintTargetCache = true;
  297. if (validTargets == null || validTargets.Length == 0 || !validTargets.Contains(scenePaintTarget))
  298. {
  299. // case 1102618: Try to use current Selection as scene paint target if possible
  300. if (Selection.activeGameObject != null && hasInterestedPainters && ValidatePaintTarget(Selection.activeGameObject))
  301. {
  302. scenePaintTarget = Selection.activeGameObject;
  303. }
  304. else
  305. {
  306. AutoSelectPaintTarget();
  307. }
  308. }
  309. }
  310. }
  311. private GameObject[] GetValidTargets()
  312. {
  313. if (m_FlushPaintTargetCache)
  314. {
  315. m_CachedPaintTargets = null;
  316. if (activeBrushEditor != null)
  317. m_CachedPaintTargets = activeBrushEditor.validTargets;
  318. if (m_CachedPaintTargets == null || m_CachedPaintTargets.Length == 0)
  319. scenePaintTarget = null;
  320. else
  321. {
  322. var comparer = GridPaintActiveTargetsPreferences.GetTargetComparer();
  323. if (comparer != null)
  324. Array.Sort(m_CachedPaintTargets, comparer);
  325. }
  326. m_FlushPaintTargetCache = false;
  327. validTargetsChanged?.Invoke();
  328. }
  329. return m_CachedPaintTargets;
  330. }
  331. private static void UpdateTooltips(IShortcutProfileManager obj, Identifier identifier, ShortcutBinding oldBinding, ShortcutBinding newBinding)
  332. {
  333. TilemapEditorTool.UpdateTooltips();
  334. }
  335. internal static void RegisterShortcutContext()
  336. {
  337. // ShortcutIntegration instance is recreated after LoadLayout which wipes the OnEnable registration
  338. ShortcutIntegration.instance.contextManager.RegisterToolContext(instance.m_ShortcutContext);
  339. }
  340. internal static void AutoSelectPaintTarget()
  341. {
  342. if (activeBrushEditor != null)
  343. {
  344. if (validTargets != null && validTargets.Length > 0)
  345. {
  346. scenePaintTarget = validTargets[0];
  347. }
  348. }
  349. }
  350. /// <summary>
  351. /// The currently active target for the Tile Palette
  352. /// </summary>
  353. public static GameObject scenePaintTarget
  354. {
  355. get => instance.m_ScenePaintTarget;
  356. set
  357. {
  358. if (value != instance.m_ScenePaintTarget)
  359. {
  360. instance.m_ScenePaintTarget = value;
  361. if (scenePaintTargetChanged != null)
  362. scenePaintTargetChanged(instance.m_ScenePaintTarget);
  363. RepaintGridPaintPaletteWindow();
  364. }
  365. }
  366. }
  367. /// <summary>
  368. /// The currently active brush for the Tile Palette
  369. /// </summary>
  370. public static GridBrushBase gridBrush
  371. {
  372. get
  373. {
  374. if (instance.m_Brush == null)
  375. {
  376. instance.m_Brush = GridPaletteBrushes.instance.GetLastUsedBrush();
  377. if (instance.m_BrushPickStore == null)
  378. instance.m_BrushPickStore = GridBrushPickStore.LoadOrCreateLibraryGridBrushPickAsset();
  379. UpdateBrushToolbar();
  380. }
  381. return instance.m_Brush;
  382. }
  383. set
  384. {
  385. if (instance.m_Brush != value)
  386. {
  387. instance.m_Brush = value;
  388. instance.m_FlushPaintTargetCache = true;
  389. if (value != null)
  390. {
  391. GridPaletteBrushes.instance.StoreLastUsedBrush(value);
  392. UpdateBrushToolbar();
  393. }
  394. // Ensure that current scenePaintTarget is still a valid target after a brush change
  395. if (scenePaintTarget != null && !ValidatePaintTarget(scenePaintTarget))
  396. scenePaintTarget = null;
  397. // Use Selection if previous scenePaintTarget was not valid
  398. if (scenePaintTarget == null)
  399. scenePaintTarget = ValidatePaintTarget(Selection.activeGameObject) ? Selection.activeGameObject : null;
  400. // Auto select a valid target if there is still no scenePaintTarget
  401. if (scenePaintTarget == null)
  402. AutoSelectPaintTarget();
  403. if (null != brushChanged)
  404. brushChanged(value);
  405. RepaintGridPaintPaletteWindow();
  406. }
  407. }
  408. }
  409. /// <summary>
  410. /// Returns a store of brush selection data for the current gridBrush
  411. /// </summary>
  412. public static GridBrushPickStore brushPickStore
  413. {
  414. get
  415. {
  416. if (gridBrush != null && (instance.m_BrushPickStore == null
  417. || !instance.m_BrushPickStore.IsValid()))
  418. {
  419. instance.m_BrushPickStore = GridBrushPickStore.LoadOrCreateLibraryGridBrushPickAsset();
  420. }
  421. return instance.m_BrushPickStore;
  422. }
  423. internal set
  424. {
  425. if (instance.m_BrushPickStore == value)
  426. return;
  427. var store = value;
  428. if (store == null)
  429. store = GridBrushPickStore.LoadOrCreateLibraryGridBrushPickAsset();
  430. if (instance.m_BrushPickStore != null)
  431. DestroyImmediate(instance.m_BrushPickStore);
  432. instance.m_BrushPickStore = store;
  433. InvokeBrushPickStoreChanged();
  434. }
  435. }
  436. /// <summary>
  437. /// Returns all available brushes for the Tile Palette
  438. /// </summary>
  439. public static IList<GridBrushBase> brushes => GridPaletteBrushes.brushes;
  440. internal static GridBrush defaultBrush
  441. {
  442. get => gridBrush as GridBrush;
  443. set => gridBrush = value;
  444. }
  445. /// <summary>
  446. /// The currently active palette GameObject for the Tile Palette
  447. /// </summary>
  448. public static GameObject palette
  449. {
  450. get => instance.m_Palette;
  451. set
  452. {
  453. if (value == null || !GridPalettes.palettes.Contains(value))
  454. throw new ArgumentException(L10n.Tr("Unable to set invalid palette"));
  455. if (instance.m_Palette != value)
  456. {
  457. OnBeforePaletteChanged();
  458. instance.m_Palette = value;
  459. OnPaletteChanged(instance.m_Palette);
  460. }
  461. }
  462. }
  463. /// <summary>
  464. /// Checks if target GameObject is part of the active Palette.
  465. /// </summary>
  466. /// <param name="target">GameObject to check.</param>
  467. /// <returns>True if the target GameObject is part of the active palette. False if not.</returns>
  468. public static bool IsPartOfActivePalette(GameObject target)
  469. {
  470. foreach (var clipboard in GridPaintPaletteClipboard.instances)
  471. {
  472. if (target == clipboard.paletteInstance)
  473. return true;
  474. }
  475. if (target == palette)
  476. return true;
  477. var parent = target.transform.parent;
  478. return parent != null && IsPartOfActivePalette(parent.gameObject);
  479. }
  480. /// <summary>
  481. /// Returns all available Palette GameObjects for the Tile Palette
  482. /// </summary>
  483. public static IList<GameObject> palettes => GridPalettes.palettes;
  484. /// <summary>
  485. /// The currently active editor for the active brush for the Tile Palette
  486. /// </summary>
  487. public static GridBrushEditorBase activeBrushEditor
  488. {
  489. get
  490. {
  491. Editor.CreateCachedEditor(instance.m_Brush, null, ref instance.m_CachedEditor);
  492. GridBrushEditorBase baseEditor = instance.m_CachedEditor as GridBrushEditorBase;
  493. return baseEditor;
  494. }
  495. }
  496. internal static Editor fallbackEditor
  497. {
  498. get
  499. {
  500. Editor.CreateCachedEditor(gridBrush, null, ref instance.m_CachedEditor);
  501. return instance.m_CachedEditor;
  502. }
  503. }
  504. internal static PaintableGrid activeGrid => instance.m_ActiveGrid;
  505. internal static PaintableGrid lastActiveGrid => instance.m_LastActiveGrid;
  506. internal static void AddActiveGrid(PaintableGrid grid)
  507. {
  508. if (grid == null)
  509. return;
  510. var added = instance.m_ActiveGridsSet.Add(grid);
  511. if (!added)
  512. return;
  513. if (activeGrid != null && activeGrid.windowRoot == grid.windowRoot)
  514. {
  515. if (activeGrid.rectPosition.Contains(new Vector2(grid.rectPosition.xMin, grid.rectPosition.yMin))
  516. && activeGrid.rectPosition.Contains(new Vector2(grid.rectPosition.xMin, grid.rectPosition.yMax))
  517. && activeGrid.rectPosition.Contains(new Vector2(grid.rectPosition.xMax, grid.rectPosition.yMin))
  518. && activeGrid.rectPosition.Contains(new Vector2(grid.rectPosition.xMax, grid.rectPosition.yMax)))
  519. {
  520. instance.m_ActiveGrid = grid;
  521. if (instance.m_ActiveGrid != null)
  522. instance.m_LastActiveGrid = grid;
  523. }
  524. }
  525. else
  526. {
  527. // Remove all other grids
  528. if (activeGrid != null && instance.m_ActiveGridsSet.Count > 1)
  529. {
  530. instance.m_ActiveGridsSet.Clear();
  531. instance.m_ActiveGridsSet.Add(grid);
  532. }
  533. instance.m_ActiveGrid = grid;
  534. if (instance.m_ActiveGrid != null)
  535. instance.m_LastActiveGrid = grid;
  536. }
  537. }
  538. internal static void RemoveActiveGrid(PaintableGrid grid)
  539. {
  540. if (grid == null)
  541. return;
  542. var removed = instance.m_ActiveGridsSet.Remove(grid);
  543. if (!removed)
  544. return;
  545. if (instance.m_ActiveGrid == grid)
  546. instance.m_ActiveGrid = null;
  547. if (instance.m_ActiveGridsSet.Count > 0)
  548. {
  549. foreach (var oldGrid in instance.m_ActiveGridsSet)
  550. {
  551. instance.m_ActiveGrid = oldGrid;
  552. if (instance.m_ActiveGrid != null)
  553. instance.m_LastActiveGrid = oldGrid;
  554. break;
  555. }
  556. }
  557. }
  558. internal static PaintableSceneViewGrid paintableSceneViewGrid => instance.m_PaintableSceneViewGrid;
  559. /// <summary>
  560. /// The last active mouse position on the `SceneView`
  561. /// when the `GridPaintingState` is active.
  562. /// </summary>
  563. public static Vector2 lastSceneViewMousePosition => paintableSceneViewGrid.mousePosition;
  564. /// <summary>
  565. /// The last active grid position on the `SceneView`
  566. /// when the `GridPaintingState` is active.
  567. /// </summary>
  568. public static Vector3Int lastSceneViewGridPosition =>
  569. new Vector3Int(paintableSceneViewGrid.mouseGridPosition.x
  570. , paintableSceneViewGrid.mouseGridPosition.y
  571. , paintableSceneViewGrid.zPosition);
  572. internal static EditorTool[] activeBrushTools
  573. {
  574. get => instance.m_BrushTools;
  575. set
  576. {
  577. instance.m_BrushTools = value;
  578. brushToolsChanged?.Invoke();
  579. }
  580. }
  581. internal static float activeBrushToolbarSize
  582. {
  583. get
  584. {
  585. if (instance.m_BrushToolbarSize == 0.0f)
  586. CalculateToolbarSize();
  587. return instance.m_BrushToolbarSize;
  588. }
  589. set => instance.m_BrushToolbarSize = value;
  590. }
  591. internal static bool drawGridGizmo
  592. {
  593. get => instance.m_DrawGridGizmo;
  594. set => instance.m_DrawGridGizmo = value;
  595. }
  596. internal static bool drawGizmos
  597. {
  598. get => instance.m_DrawGizmos;
  599. set => instance.m_DrawGizmos = value;
  600. }
  601. /// <summary>
  602. /// Returns whether GridPaintingState is active for editing.
  603. /// </summary>
  604. public static bool isEditing
  605. {
  606. get => instance.m_IsEditing;
  607. internal set
  608. {
  609. if (value != instance.m_IsEditing)
  610. {
  611. instance.m_IsEditing = value;
  612. editModeChanged?.Invoke();
  613. }
  614. }
  615. }
  616. internal static bool hasActivePick
  617. {
  618. get => instance.m_HasActivePick && activePickPalette == palette;
  619. set => instance.m_HasActivePick = value;
  620. }
  621. internal static BoundsInt activePick
  622. {
  623. get => instance.m_ActivePick;
  624. set => instance.m_ActivePick = value;
  625. }
  626. internal static Vector3Int activePivot
  627. {
  628. get => instance.m_ActivePivot;
  629. set => instance.m_ActivePivot = value;
  630. }
  631. internal static GameObject activePickPalette
  632. {
  633. get => instance.m_ActivePickPalette;
  634. set => instance.m_ActivePickPalette = value;
  635. }
  636. /// <summary>
  637. /// Retrieves a stored selection from the current Active GridBrushPickStore
  638. /// and copies it into the Active GridBrush.
  639. /// </summary>
  640. /// <param name="user">Use user selection or last selection.</param>
  641. /// <param name="index">Index of selection from store to use.</param>
  642. public static void SetPickOnActiveGridBrush(bool user, int index)
  643. {
  644. if (gridBrush == null || brushPickStore == null)
  645. return;
  646. GridBrushBase selection = null;
  647. if (user)
  648. {
  649. if (0 <= index && index < brushPickStore.userSavedBrushes.Count)
  650. selection = brushPickStore.userSavedBrushes[index];
  651. }
  652. else
  653. {
  654. if (0 <= index && index < brushPickStore.lastSavedBrushes.Count)
  655. selection = brushPickStore.lastSavedBrushes[index];
  656. }
  657. if (selection == null)
  658. return;
  659. var selectedBrushType = selection.GetType();
  660. if (!GridPaletteBrushes.IsDefaultInstanceVisibleGridBrushType(selectedBrushType)
  661. && selectedBrushType != GridPaletteBrushes.GetDefaultBrushType())
  662. return;
  663. if (gridBrush.GetType() != selectedBrushType)
  664. {
  665. foreach (var brush in GridPaletteBrushes.brushes)
  666. {
  667. if (brush.GetType() == selectedBrushType)
  668. {
  669. gridBrush = brush;
  670. break;
  671. }
  672. }
  673. }
  674. var originalName = gridBrush.name;
  675. var originalFlags = gridBrush.hideFlags;
  676. EditorUtility.CopySerialized(selection, gridBrush);
  677. gridBrush.name = originalName;
  678. gridBrush.hideFlags = originalFlags;
  679. GridPaletteBrushes.GridBrushAssetChanged(gridBrush);
  680. }
  681. private static void CalculateToolbarSize()
  682. {
  683. GUIStyle toolbarStyle = "Command";
  684. activeBrushToolbarSize = activeBrushTools.Sum(x => toolbarStyle.CalcSize(x.toolbarIcon).x);
  685. }
  686. internal static void SetBrushTools(EditorTool[] editorTools)
  687. {
  688. activeBrushTools = editorTools;
  689. activeBrushToolbarSize = 0.0f;
  690. }
  691. private static bool ValidatePaintTarget(GameObject candidate)
  692. {
  693. if (candidate == null)
  694. return false;
  695. // Case 1327021: Do not allow disabled GameObjects as a paint target
  696. if (!candidate.activeInHierarchy)
  697. return false;
  698. if (candidate.GetComponentInParent<Grid>() == null && candidate.GetComponent<Grid>() == null)
  699. return false;
  700. if (validTargets != null && validTargets.Length > 0 && !validTargets.Contains(candidate))
  701. return false;
  702. if (PrefabUtility.IsPartOfPrefabAsset(candidate))
  703. return false;
  704. return true;
  705. }
  706. internal static void FlushCache()
  707. {
  708. if (instance.m_CachedEditor != null)
  709. {
  710. DestroyImmediate(instance.m_CachedEditor);
  711. instance.m_CachedEditor = null;
  712. }
  713. instance.m_FlushPaintTargetCache = true;
  714. }
  715. /// <summary>
  716. /// A list of all valid targets that can be set as an active target for the Tile Palette
  717. /// </summary>
  718. public static GameObject[] validTargets => instance.GetValidTargets();
  719. internal static bool savingPalette
  720. {
  721. get => instance.m_SavingPalette;
  722. set => instance.m_SavingPalette = value;
  723. }
  724. internal static void OnBeforePaletteChanged()
  725. {
  726. if (null != beforePaletteChanged)
  727. beforePaletteChanged();
  728. }
  729. internal static void OnPaletteChanged(GameObject changedPalette)
  730. {
  731. if (null != paletteChanged)
  732. paletteChanged(changedPalette);
  733. }
  734. internal static void UpdateBrushToolbar()
  735. {
  736. BrushToolsAttribute toolAttribute = null;
  737. if (instance.m_Brush != null)
  738. toolAttribute = (BrushToolsAttribute)instance.m_Brush.GetType().GetCustomAttribute(typeof(BrushToolsAttribute), false);
  739. TilemapEditorTool.UpdateEditorTools(toolAttribute);
  740. }
  741. internal static void ActiveGridBrushAssetChanged()
  742. {
  743. if (gridBrush == null)
  744. return;
  745. GridPaletteBrushes.GridBrushAssetChanged(gridBrush);
  746. if (activeBrushEditor != null && activeBrushEditor.shouldSaveBrushForSelection)
  747. brushPickStore.AddNewLastSavedBrush(gridBrush);
  748. brushPickChanged?.Invoke();
  749. }
  750. internal static void UpdateActiveGridPalette()
  751. {
  752. foreach (var clipboard in GridPaintPaletteClipboard.instances)
  753. {
  754. clipboard.DelayedResetPreviewInstance();
  755. }
  756. }
  757. internal static void RepaintGridPaintPaletteWindow()
  758. {
  759. foreach (var clipboard in GridPaintPaletteClipboard.instances)
  760. {
  761. clipboard.Repaint();
  762. }
  763. }
  764. internal static void InvokeBrushPickStoreChanged()
  765. {
  766. brushPickStoreChanged?.Invoke();
  767. }
  768. internal static void UnlockGridPaintPaletteClipboardForEditing()
  769. {
  770. foreach (var clipboard in GridPaintPaletteClipboard.instances)
  771. {
  772. clipboard.UnlockAndEdit();
  773. }
  774. }
  775. internal static void RegisterPainterInterest(System.Object painter)
  776. {
  777. var added = instance.m_InterestedPainters.Add(painter);
  778. if (added && instance.m_InterestedPainters.Count == 1)
  779. instance.OnEditEnable();
  780. }
  781. internal static void UnregisterPainterInterest(System.Object painter)
  782. {
  783. var removed = instance.m_InterestedPainters.Remove(painter);
  784. if (removed && instance.m_InterestedPainters.Count == 0)
  785. instance.OnEditDisable();
  786. }
  787. internal static bool hasInterestedPainters => instance != null && instance.m_InterestedPainters.Count > 0;
  788. }
  789. }