private void OnGUI_Buttons()
        {
            if (GUILayout.Button(TileLang.ParticularText("Action", "Reset"), ExtraEditorStyles.Instance.BigButton))
            {
                this.OnButton_Reset();
                GUIUtility.ExitGUI();
            }

            GUILayout.FlexibleSpace();

            if (GUILayout.Button(TileLang.ParticularText("Action", "Create"), ExtraEditorStyles.Instance.BigButtonPadded))
            {
                this.OnButton_Create();
                GUIUtility.ExitGUI();
            }

            GUILayout.Space(3);

            if (GUILayout.Button(TileLang.ParticularText("Action", "Cancel"), ExtraEditorStyles.Instance.BigButtonPadded))
            {
                this.Close();
                GUIUtility.ExitGUI();
            }
        }
Пример #2
0
        /// <summary>
        /// Draw standard options GUI using layout engine. This method should be called
        /// within a horizontally flowing layout.
        /// </summary>
        /// <example>
        /// <code language="csharp"><![CDATA[
        /// GUILayout.BeginHorizontal();
        /// {
        ///     DrawStandardOptionsGUI();
        /// }
        /// GUILayout.EndHorizontal();
        /// ]]></code>
        /// </example>
        protected void DrawStandardOptionsGUI()
        {
            Rect position = GUILayoutUtility.GetRect(77, 0);

            position.y -= 3;

            // Draw "Rotation" selector interface.
            EditorGUI.BeginChangeCheck();
            ToolUtility.Rotation = RotorzEditorGUI.RotationSelector(new Rect(position.x + 3, position.y, 39, 36), ToolUtility.Rotation);
            if (EditorGUI.EndChangeCheck())
            {
                SceneView.RepaintAll();
            }

            using (var content = ControlContent.Basic(
                       RotorzEditorStyles.Skin.GetActive(RotorzEditorStyles.Skin.Randomize, ToolUtility.RandomizeVariations),
                       TileLang.ParticularText("Property", "Randomize Variations")
                       )) {
                Rect togglePosition = position;
                togglePosition.x     += 3 + 39 + 5;
                togglePosition.y     += 1;
                togglePosition.width  = 32;
                togglePosition.height = 30;

                ToolUtility.RandomizeVariations = RotorzEditorGUI.HoverToggle(togglePosition, content, ToolUtility.RandomizeVariations);
            }

            if (this.EnableVariationShifting)
            {
                EditorGUI.BeginDisabledGroup(this.TemporarilyDisableVariationShifting);
                this.DrawVariationShifter();
                EditorGUI.EndDisabledGroup();
            }

            RotorzEditorGUI.VerticalSeparatorLight();
        }
Пример #3
0
        /// <summary>
        /// Remove material mapping from brush.
        /// </summary>
        /// <param name="index">
        /// Zero-based index of mapping to remove.
        /// </param>
        public void RemoveMaterialMapping(int index)
        {
            Undo.RecordObject(this.brush, TileLang.ParticularText("Action", "Remove Material Mapping"));

            Material[] from = this.mappings.MaterialMappingFrom;
            Material[] to   = this.mappings.MaterialMappingTo;

            if (index < 0 || index >= from.Length)
            {
                return;
            }

            // Remove material mapping.
            ArrayUtility.RemoveAt <Material>(ref from, index);
            ArrayUtility.RemoveAt <Material>(ref to, index);

            this.mappings.MaterialMappingFrom = from;
            this.mappings.MaterialMappingTo   = to;

            // Changes have been made!
            EditorUtility.SetDirty(this.brush);
            // Refresh brush preview.
            BrushUtility.RefreshPreviewIncludingDependencies(this.brush);
        }
Пример #4
0
        public static PlopInstance CyclePlop(TileSystem system, PlopInstance plop, Brush brush, int nextRotation, int nextVariation)
        {
            Undo.RecordObject(plop, TileLang.ParticularText("Action", "Cycle Plop"));

            var parentTransform = plop.transform.parent;

            var tileData = plop.ToTileData();

            nextVariation = Brush.WrapVariationIndexForCycle(Brush.GetSharedContext(brush, GetTempSystem(system), TileIndex.zero), tileData, nextVariation);

            var newPlop = PaintPlop(system, plop.PlopPoint, brush, nextRotation, nextVariation);

            ErasePlop(plop);

            // New plop should have same parent as original plop.
            var newPlopTransform = newPlop.transform;

            if (newPlopTransform.parent != parentTransform)
            {
                newPlopTransform.SetParent(parentTransform);
            }

            return(newPlop);
        }
        /// <inheritdoc/>
        protected override void DoEnable()
        {
            this.wantsMouseMove = true;

            this.titleContent = new GUIContent(TileLang.Text("Brushes"));
            this.minSize      = new Vector2(255, 200);

            // Set up brush list.
            this.brushList                        = new BrushListControl(this);
            this.brushList.Model                  = ToolUtility.SharedBrushListModel;
            this.brushList.CanShowHidden          = true;
            this.brushList.EnableDragAndDrop      = true;
            this.brushList.DragThreshold          = 16;
            this.brushList.EmptyLabel             = TileLang.ParticularText("Action", "(Erase)");
            this.brushList.VisibleViews           = BrushListView.Brushes | BrushListView.Tileset;
            this.brushList.ShowTilesetContextMenu = true;
            this.brushList.BrushMouseDown        += this._brushList_BrushMouseDown;
            this.brushList.BrushClicked          += this._brushList_BrushClicked;
            this.brushList.BrushContextMenu      += this._brushList_BrushContextMenu;

            this.brushList.Model.ViewChanged            += this.Model_ViewChanged;
            this.brushList.Model.SelectedBrushChanged   += this.Model_SelectedBrushChanged;
            this.brushList.Model.SelectedTilesetChanged += this.Model_SelectedTilesetChanged;
        }
Пример #6
0
        private void RecalculateMetrics()
        {
            if (this.autotileTextureUncompressed != null)
            {
                var autotileExpanderUtility = new AutotileExpanderUtility(s_SelectedAutotileLayout, this.autotileTextureUncompressed, this.tileWidth, this.tileHeight, s_InnerJoins, s_BorderSize, false);
                autotileExpanderUtility.CalculateMetrics(out this.metricAtlasWidth, out this.metricAtlasHeight, out this.metricAtlasUnused);

                this.metricAtlasUnusedPercentage = 100 * this.metricAtlasUnused / (this.metricAtlasWidth * this.metricAtlasHeight);

                this.metricSummary.text = string.Format(

                    /* 0: width of atlas texture in pixels
                     * 1: height of atlas texture in pixels
                     * 2: percentage of unused area of atlas texture */
                    TileLang.Text("Output Atlas: {0}x{1}   Unused: {2}%"),
                    this.metricAtlasWidth, this.metricAtlasHeight, this.metricAtlasUnusedPercentage
                    );
            }
            else
            {
                this.metricAtlasUnusedPercentage = this.metricAtlasUnused = this.metricAtlasHeight = this.metricAtlasWidth = 0;
                this.metricSummary.text          = string.Empty;
            }
        }
Пример #7
0
        private void DrawModifyGridSection()
        {
            if (this.targets.Length > 1)
            {
                EditorGUILayout.HelpBox(TileLang.Text("Cannot modify structure of multiple tile systems at the same time."), MessageType.Info);
                return;
            }

            var tileSystem = this.target as TileSystem;

            if (PrefabUtility.GetPrefabType(tileSystem) == PrefabType.Prefab)
            {
                EditorGUILayout.HelpBox(TileLang.Text("Prefab must be instantiated in order to modify tile system structure."), MessageType.Info);
                return;
            }

            float restoreLabelWidth = EditorGUIUtility.labelWidth;

            bool hasGridSizeChanged;
            bool hasOffsetChanged;

            if (s_ModifyGridGroupStyle == null)
            {
                s_ModifyGridGroupStyle = new GUIStyle();
                s_ModifyGridGroupStyle.margin.right = 55;
            }

            Rect modifyGroupRect = EditorGUILayout.BeginVertical(s_ModifyGridGroupStyle);

            {
                ExtraEditorGUI.MultiPartPrefixLabel(TileLang.ParticularText("Property", "Grid Size (in tiles)"));
                GUILayout.BeginHorizontal();
                {
                    GUILayout.Space(18);
                    EditorGUIUtility.labelWidth = 65;

                    EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Rows"));
                    this.inputNewRows = Mathf.Max(1, EditorGUILayout.IntField(this.inputNewRows));
                    EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Columns"));
                    this.inputNewColumns = Mathf.Max(1, EditorGUILayout.IntField(this.inputNewColumns));

                    EditorGUIUtility.labelWidth = restoreLabelWidth;
                }
                GUILayout.EndHorizontal();

                ExtraEditorGUI.MultiPartPrefixLabel(TileLang.ParticularText("Property", "Offset Amount (in tiles)"));
                GUILayout.BeginHorizontal();
                {
                    GUILayout.Space(18);
                    EditorGUIUtility.labelWidth = 65;

                    EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Rows"));
                    this.inputRowOffset = EditorGUILayout.IntField(this.inputRowOffset);
                    EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Columns"));
                    this.inputColumnOffset = EditorGUILayout.IntField(this.inputColumnOffset);

                    EditorGUIUtility.labelWidth = restoreLabelWidth;
                }
                GUILayout.EndHorizontal();

                hasGridSizeChanged = (this.inputNewRows != tileSystem.RowCount || this.inputNewColumns != tileSystem.ColumnCount);
                hasOffsetChanged   = (this.inputRowOffset != 0 || this.inputColumnOffset != 0);

                if (hasGridSizeChanged)
                {
                    this.DrawMaintainTilePositionsInWorld(ref this.inputMaintainTilePositionsInWorldResize);
                }
                else if (hasOffsetChanged)
                {
                    this.DrawMaintainTilePositionsInWorld(ref this.inputMaintainTilePositionsInWorldOffset);
                }

                EditorGUIUtility.labelWidth = restoreLabelWidth;

                ExtraEditorGUI.MultiPartPrefixLabel(TileLang.ParticularText("Property", "Chunk Size (in tiles)"));
                GUILayout.BeginHorizontal();
                {
                    GUILayout.Space(18);
                    EditorGUIUtility.labelWidth = 65;

                    EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Height"));
                    this.inputNewChunkHeight = Mathf.Max(1, EditorGUILayout.IntField(this.inputNewChunkHeight));
                    EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Width"));
                    this.inputNewChunkWidth = Mathf.Max(1, EditorGUILayout.IntField(this.inputNewChunkWidth));

                    EditorGUIUtility.labelWidth = restoreLabelWidth;
                }
                GUILayout.EndHorizontal();
            }
            EditorGUILayout.EndVertical();


            Rect buttonRect = new Rect(modifyGroupRect.xMax + 5, modifyGroupRect.y + 3, 45, 35);

            using (var content = ControlContent.Basic(
                       RotorzEditorStyles.Skin.Trim,
                       TileLang.ParticularText("Action", "Trim")
                       )) {
                if (GUI.Button(buttonRect, content))
                {
                    this.OnTrimTileSystem();
                    GUIUtility.ExitGUI();
                }
            }

            buttonRect.y = buttonRect.yMax + 3;

            EditorGUI.BeginDisabledGroup(!hasGridSizeChanged);
            {
                using (var content = ControlContent.Basic(
                           RotorzEditorStyles.Skin.CentralizeUsed,
                           TileLang.ParticularText("Action", "Centralize Tile Bounds")
                           )) {
                    if (GUI.Button(buttonRect, content))
                    {
                        this.OnCentralizeUsedTileSystem();
                        GUIUtility.ExitGUI();
                    }
                }

                buttonRect.y = buttonRect.yMax + 3;

                using (var content = ControlContent.Basic(
                           RotorzEditorStyles.Skin.Centralize,
                           TileLang.ParticularText("Action", "Centralize")
                           )) {
                    if (GUI.Button(buttonRect, content))
                    {
                        this.OnCentralizeTileSystem();
                        GUIUtility.ExitGUI();
                    }
                }
            }
            EditorGUI.EndDisabledGroup();


            bool hasChunkSizeChanged = (this.inputNewChunkWidth != tileSystem.ChunkWidth || this.inputNewChunkHeight != tileSystem.ChunkHeight);

            // Display "Rebuild" button?
            if (hasGridSizeChanged || hasOffsetChanged || hasChunkSizeChanged)
            {
                GUILayout.Space(6);
                GUILayout.BeginHorizontal();
                {
                    EditorGUILayout.HelpBox(TileLang.Text("Tile system must be reconstructed, some tiles may be force refreshed."), MessageType.Warning);

                    if (GUILayout.Button(TileLang.ParticularText("Action", "Rebuild"), GUILayout.Width(75), GUILayout.Height(40)))
                    {
                        GUIUtility.keyboardControl = 0;
                        this.OnResizeTileSystem();
                        GUIUtility.ExitGUI();
                    }
                    if (GUILayout.Button(TileLang.ParticularText("Action", "Cancel"), GUILayout.Width(75), GUILayout.Height(40)))
                    {
                        GUIUtility.keyboardControl = 0;
                        this.RefreshModifyGridParamsFromTileSystem();
                        GUIUtility.ExitGUI();
                    }
                }
                GUILayout.EndHorizontal();
                GUILayout.Space(2);
            }

            ExtraEditorGUI.SeparatorLight();

            using (var content = ControlContent.Basic(
                       TileLang.ParticularText("Property", "Cell Size"),
                       TileLang.Text("Span of an individual tile.")
                       )) {
                Vector3 newCellSize = Vector3.Max(new Vector3(0.0001f, 0.0001f, 0.0001f), EditorGUILayout.Vector3Field(content, tileSystem.CellSize));
                if (tileSystem.CellSize != newCellSize)
                {
                    this.propertyCellSize.vector3Value      = newCellSize;
                    this.propertyHintForceRefresh.boolValue = true;
                }
            }

            GUILayout.Space(5);

            using (var content = ControlContent.Basic(
                       TileLang.ParticularText("Property", "Tiles Facing"),
                       TileLang.Text("Direction that tiles will face when painted. 'Sideways' is good for platform and 2D games. 'Upwards' is good for top-down.")
                       )) {
                TileFacing newTilesFacing = (TileFacing)EditorGUILayout.EnumPopup(content, tileSystem.TilesFacing);
                if (tileSystem.TilesFacing != newTilesFacing)
                {
                    this.propertyTilesFacing.intValue       = (int)newTilesFacing;
                    this.propertyHintForceRefresh.boolValue = true;
                }
            }

            GUILayout.Space(5);

            // Display suitable warning message when force refresh is required.
            if (this.propertyHintForceRefresh.boolValue)
            {
                if (!RotorzEditorGUI.InfoBoxClosable(TileLang.Text("Changes may not take effect until tile system is force refreshed without preserving manual offsets, or cleared."), MessageType.Warning))
                {
                    this.propertyHintForceRefresh.boolValue = false;
                    this.serializedObject.ApplyModifiedProperties();
                    GUIUtility.ExitGUI();
                }
            }
            else
            {
                ExtraEditorGUI.SeparatorLight(marginTop: 0, marginBottom: 0, thickness: 1);
            }

            GUILayout.Space(5);

            GUILayout.BeginHorizontal();
            {
                // Display extra padding to right of buttons to avoid accidental click when
                // clicking close button of warning message.
                GUILayoutOption columnWidth = GUILayout.Width((EditorGUIUtility.currentViewWidth - 30) / 3 - GUI.skin.button.margin.horizontal);

                GUILayout.BeginVertical(columnWidth);
                if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Refresh"))))
                {
                    TileSystemCommands.Command_Refresh(this.target);
                    GUIUtility.ExitGUI();
                }
                GUILayout.Space(2);
                if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Refresh Plops"))))
                {
                    TileSystemCommands.Command_RefreshPlops(this.target);
                    GUIUtility.ExitGUI();
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical(columnWidth);
                if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Repair"))))
                {
                    TileSystemCommands.Command_Repair(this.target);
                    GUIUtility.ExitGUI();
                }
                GUILayout.Space(2);
                if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Clear Plops"))))
                {
                    TileSystemCommands.Command_ClearPlops(this.target);
                    GUIUtility.ExitGUI();
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical(columnWidth);
                if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Clear"))))
                {
                    TileSystemCommands.Command_Clear(this.target);
                    GUIUtility.ExitGUI();
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(5);
        }
        //!TODO: The following should be refactored so that the tile system is passed in
        //       as the context object rather than using a closure.
        private EditorMenu BuildContextMenu(TileSystem system)
        {
            var contextMenu = new EditorMenu();

            contextMenu.AddCommand(TileLang.ParticularText("Action", "Inspect"))
            .Action(() => {
                EditorInternalUtility.FocusInspectorWindow();
            });

            contextMenu.AddSeparator();

            contextMenu.AddCommand(TileLang.ParticularText("Action", "Rename"))
            .Action(() => {
                this.BeginEditingName(system);
            });

            contextMenu.AddCommand(TileLang.ParticularText("Action", "Lock"))
            .Checked(system.Locked)
            .Action(() => {
                Undo.RecordObject(system, system.Locked
                        ? TileLang.ParticularText("Action", "Unlock Tile System")
                        : TileLang.ParticularText("Action", "Lock Tile System"));
                system.Locked = !system.Locked;
                EditorUtility.SetDirty(system);
                ToolUtility.RepaintScenePalette();
            });

            contextMenu.AddSeparator();

            contextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Refresh Tiles")))
            .Enabled(!system.Locked)
            .Action(() => {
                TileSystemCommands.Command_Refresh(system);
            });

            contextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Repair Tiles")))
            .Enabled(!system.Locked)
            .Action(() => {
                TileSystemCommands.Command_Repair(system);
            });

            contextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Clear Tiles")))
            .Enabled(!system.Locked)
            .Action(() => {
                TileSystemCommands.Command_Clear(system);
            });

            //contextMenu.AddSeparator();

            //contextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Refresh Plops")))
            //    .Enabled(!system.Locked)
            //    .Action(() => {
            //        TileSystemCommands.Command_RefreshPlops(system);
            //    });

            //contextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Clear Plops")))
            //    .Enabled(!system.Locked)
            //    .Action(() => {
            //        TileSystemCommands.Command_ClearPlops(system);
            //    });

            contextMenu.AddSeparator();

            contextMenu.AddCommand(TileLang.ParticularText("Action", "Delete"))
            .Enabled(!system.Locked)
            .Action(() => {
                Undo.DestroyObjectImmediate(system.gameObject);
            });

            contextMenu.AddSeparator();

            contextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Build Prefab")))
            .Action(() => {
                TileSystemCommands.Command_BuildPrefab(system);
            });

            return(contextMenu);
        }
Пример #9
0
 /// <summary>
 /// Display orientation selection window.
 /// </summary>
 /// <param name="callback">Invoked when orientation is defined.</param>
 /// <returns>
 /// The window.
 /// </returns>
 public static DefineOrientationWindow ShowWindow(DefineOrientationDelegate2 callback)
 {
     return(ShowWindow(TileLang.ParticularText("Action", "Select Orientation"), callback));
 }
        private void _brushList_BrushContextMenu(Brush brush)
        {
            // Do not attempt to display context menu for "(Erase)" item.
            if (brush == null)
            {
                return;
            }

            var brushRecord = BrushDatabase.Instance.FindRecord(brush);

            var brushContextMenu = new EditorMenu();

            brushContextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Show in Designer")))
            .Enabled(!brushRecord.IsMaster)     // Cannot edit a master brush :)
            .Action(() => {
                ToolUtility.ShowBrushInDesigner(brush);
            });

            var selectedTilesetBrush = brush as TilesetBrush;

            if (selectedTilesetBrush != null)
            {
                brushContextMenu.AddCommand(TileLang.ParticularText("Action", "Goto Tileset"))
                .Action(() => {
                    this.brushList.Model.View            = BrushListView.Tileset;
                    this.brushList.Model.SelectedTileset = selectedTilesetBrush.Tileset;

                    var designerWindow = RotorzWindow.GetInstance <DesignerWindow>();
                    if (designerWindow != null && !designerWindow.IsLocked)
                    {
                        designerWindow.SelectedObject = selectedTilesetBrush.Tileset;
                    }

                    this.Repaint();
                });
            }

            brushContextMenu.AddCommand(TileLang.ParticularText("Action", "Reveal Asset"))
            .Action(() => {
                EditorGUIUtility.PingObject(brush);
            });

            brushContextMenu.AddSeparator();

            brushContextMenu.AddCommand(TileLang.ParticularText("Action", "Refresh Preview"))
            .Action(() => {
                BrushUtility.RefreshPreviewIncludingDependencies(brush);
            });

            brushContextMenu.AddSeparator();

            brushContextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Create Duplicate")))
            .Action(() => {
                var window = CreateBrushWindow.ShowWindow <DuplicateBrushCreator>();
                window.SharedProperties["targetBrush"] = brush;
            });

            var brushDescriptor = BrushUtility.GetDescriptor(brush.GetType());

            brushContextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Create Alias")))
            .Enabled(brushDescriptor.SupportsAliases)
            .Action(() => {
                var window = CreateBrushWindow.ShowWindow <AliasBrushCreator>();
                window.SharedProperties["targetBrush"] = brush;
            });

            brushContextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Delete Brush")))
            .Action(() => {
                TileSystemCommands.DeleteBrush(brush, ToolUtility.SharedBrushListModel.View == BrushListView.Tileset);
            });

            brushContextMenu.ShowAsContext();
        }
        private void OnGUI_Presets()
        {
            GUILayout.Space(10);

            EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Preset"));
            EditorGUI.BeginChangeCheck();
            using (var valueContent = ControlContent.Basic(this.currentPreset.name)) {
                s_SelectedPresetGuid.Value = CustomPopupGUI.Popup(GUIContent.none, s_SelectedPresetGuid.Value, valueContent, this.PopulatePresetMenu);
            }
            if (EditorGUI.EndChangeCheck())
            {
                this.SetSelectedPreset(s_SelectedPresetGuid.Value);
            }

            EditorGUILayout.Space();

            EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Preset Name"));
            this.newPresetName = EditorGUILayout.TextField(this.newPresetName);

            if (GUILayout.Button(TileLang.ParticularText("Action", "Save Preset")))
            {
                this.OnButton_SavePreset();
                GUIUtility.ExitGUI();
            }

            // Do not allow deletion of factory default preset.
            EditorGUI.BeginDisabledGroup(this.selectedPreset == null);
            if (GUILayout.Button(TileLang.ParticularText("Action", "Delete Preset")))
            {
                this.OnButton_DeletePreset();
                GUIUtility.ExitGUI();
            }
            EditorGUI.EndDisabledGroup();

            GUILayout.FlexibleSpace();

            ControlContent.TrailingTipsVisible = GUILayout.Toggle(ControlContent.TrailingTipsVisible, TileLang.ParticularText("Action", "Show Tips"));

            GUILayout.Space(10);
        }
Пример #12
0
 public override void OnInspectorGUI()
 {
     GUILayout.Label(TileLang.Text("Please use designer to edit brush."));
 }
Пример #13
0
        protected override void OnHeaderGUI()
        {
            if (!this.hasInitialized)
            {
                this.hasInitialized = true;

                // Find out whether brush asset is accessible via brush database.
                var record = BrushDatabase.Instance.FindRecord(target as Brush);
                this.hasRecord = (record != null);
            }

            if (this.hasRecord)
            {
                var brush = target as Brush;

                GUILayout.BeginHorizontal(RotorzEditorStyles.Instance.InspectorBigTitle);

                Rect previewPosition = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.Width(64), GUILayout.Height(65));
                if (Event.current.type == EventType.Repaint)
                {
                    RotorzEditorStyles.Instance.Box.Draw(new Rect(previewPosition.x - 2, previewPosition.y - 2, 68, 68), GUIContent.none, false, false, false, false);
                    previewPosition = new Rect(previewPosition.x, previewPosition.y, 64, 64);
                    RotorzEditorGUI.DrawBrushPreview(previewPosition, brush);
                }

                GUILayout.BeginVertical();
                {
                    GUILayout.Label(brush.name, EditorStyles.largeLabel);

                    GUILayout.BeginHorizontal();
                    {
                        GUILayout.FlexibleSpace();

                        var tilesetBrush = brush as TilesetBrush;
                        if (tilesetBrush != null)
                        {
                            EditorGUI.BeginDisabledGroup(tilesetBrush.Tileset == null);
                            if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Goto Tileset")), EditorStyles.miniButton))
                            {
                                ToolUtility.ShowTilesetInDesigner(tilesetBrush.Tileset);
                                GUIUtility.ExitGUI();
                            }
                            EditorGUI.EndDisabledGroup();
                        }

                        if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Show in Designer")), EditorStyles.miniButton))
                        {
                            ToolUtility.ShowBrushInDesigner(brush);
                            GUIUtility.ExitGUI();
                        }
                    }
                    GUILayout.EndHorizontal();
                }
                GUILayout.EndVertical();

                GUILayout.EndHorizontal();
            }
            else
            {
                // Nope, assume default header!
                base.OnHeaderGUI();
            }
        }
Пример #14
0
        private void DrawStandardStatusGUI()
        {
            var       activeTileSystem = ToolUtility.ActiveTileSystem;
            TileIndex activeTileIndex  = ToolUtility.ActiveTileIndex;
            TileData  activeTile       = ToolUtility.ActiveTile;

            string statusLabel = string.Format(

                /* 0: zero-based index of row
                 * 1: zero-based index of column */
                TileLang.Text("Row: {0,5}    Column: {1,5}"),
                activeTileIndex.row, activeTileIndex.column
                );

            Rect outRect = new Rect(5, 20, 205, 17);

            GUI.Label(outRect, statusLabel, EditorStyles.whiteLabel);

            outRect.x     = 203;
            outRect.width = 190;

            statusLabel = "-";
            if (activeTile != null)
            {
                if (activeTile.brush != null)
                {
                    if (activeTile.tileset != null)
                    {
                        statusLabel = string.Format(

                            /* 0: name of brush
                             * 1: zero-based index of associated tile in tileset */
                            TileLang.Text("{0} : {1}"),
                            activeTile.brush.name, activeTile.tilesetIndex
                            );
                    }
                    else
                    {
                        statusLabel = activeTile.brush.name;
                    }
                }
                else if (activeTile.tileset != null)
                {
                    statusLabel = string.Format(

                        /* 0: name of tileset
                         * 1: zero-based index of tile in tileset */
                        TileLang.Text("{1} from {0}"),
                        activeTile.tileset.name, activeTile.tilesetIndex
                        );
                }
            }
            GUI.Label(outRect, statusLabel, EditorStyles.whiteLabel);

            if (activeTile != null && Event.current.type == EventType.Repaint)
            {
                int actualOrientation = activeTile.orientationMask;

                // Get oriented brush component of tile.
                var orientedBrush = activeTile.OrientedBrush;
                if (activeTile.brush is AliasBrush)
                {
                    orientedBrush = activeTile.AliasBrush.target as OrientedBrush;
                }
                // Determine actual orientation of active tile.
                if (orientedBrush != null)
                {
                    actualOrientation = OrientationUtility.DetermineTileOrientation(activeTileSystem, activeTileIndex, activeTile.brush, activeTile.PaintedRotation);
                }

                Color restoreBackground = GUI.backgroundColor;
                Color activeColor       = activeTile.PaintedRotation != 0 ? new Color(0, 40, 255) : Color.green;

                outRect.x      = 180;
                outRect.y      = 19;
                outRect.width  = 5;
                outRect.height = 5;

                int bit = 1;
                for (int i = 0; i < 9; ++i)
                {
                    if (i == 4)
                    {
                        // Draw center box!
                        GUI.backgroundColor = Color.black;
                        RotorzEditorStyles.Instance.TransparentBox.Draw(outRect, GUIContent.none, false, false, false, false);

                        if (activeTile.PaintedRotation != 0)
                        {
                            GUI.backgroundColor = activeColor;
                            RotorzEditorStyles.Instance.TransparentBox.Draw(new Rect(outRect.x + 1, outRect.y + 1, 3, 3), GUIContent.none, false, false, false, false);
                        }
                    }
                    else
                    {
                        // Green  : Matching part of orientation
                        // Cyan   : Matching part of orientation with rotation applied
                        // Red    : Surplus part of orientation
                        // Gray   : Missing part of orientation

                        if ((actualOrientation & bit) != (activeTile.orientationMask & bit))
                        {
                            // Orientation of tile is invalid.
                            GUI.backgroundColor = (activeTile.orientationMask & bit) != 0 ? Color.red : Color.gray;
                        }
                        else
                        {
                            // Orientation of tile is valid.
                            GUI.backgroundColor = (activeTile.orientationMask & bit) != 0 ? activeColor : Color.white;
                        }

                        RotorzEditorStyles.Instance.TransparentBox.Draw(outRect, GUIContent.none, false, false, false, false);

                        bit <<= 1;
                    }

                    if (i % 3 == 2)
                    {
                        outRect.x  = 180;
                        outRect.y += 6;
                    }
                    else
                    {
                        outRect.x += 6;
                    }
                }

                GUI.backgroundColor = restoreBackground;
            }
        }
Пример #15
0
        /// <summary>
        /// Build optimized prefab from a tile system.
        /// </summary>
        /// <remarks>
        /// <para>Presents various user interfaces.</para>
        /// </remarks>
        /// <param name="system">Tile system.</param>
        /// <param name="dataPath">Output path for generated data asset.</param>
        /// <param name="prefabPath">Output path for generated prefab asset.</param>
        public static void BuildPrefab(TileSystem system, string dataPath, string prefabPath)
        {
            // Destroy mesh if it already exists.
            AssetDatabase.DeleteAsset(dataPath);
            // Destroy prefab if it already exists.
            AssetDatabase.DeleteAsset(prefabPath);

            // Duplicate tile system for processing.
            var duplicateTileSystemGO = GameObject.Instantiate(system.gameObject);
            var duplicateTileSystem   = duplicateTileSystemGO.GetComponent <TileSystem>();

            InternalUtility.EnableProgressHandler = true;

            // Raise event for start of building prefab.
            if (BuildPrefabStart != null)
            {
                BuildPrefabStart(duplicateTileSystem);
            }

            try {
                string tileSystemName = duplicateTileSystem.name;

                var tileSystemBuilder = BuildTileSystemHelper(duplicateTileSystem, InternalUtility.CancelableProgressHandler);

                // Save generated meshes to asset.
                TileSystemPrefabAsset assetData = ScriptableObject.CreateInstance <TileSystemPrefabAsset>();
                AssetDatabase.CreateAsset(assetData, dataPath);
                foreach (var mesh in tileSystemBuilder.GeneratedMeshes)
                {
                    AssetDatabase.AddObjectToAsset(mesh, assetData);
                }
                AssetDatabase.ImportAsset(dataPath);

                EditorUtility.DisplayProgressBar(
                    string.Format(
                        /* 0: name of tile system */
                        TileLang.Text("Building tile system '{0}'..."),
                        tileSystemName
                        ),
                    TileLang.Text("Saving prefab and data asset..."),
                    progress: 1f
                    );

                // Create prefab output.
                var newPrefab = PrefabUtility.CreatePrefab(prefabPath, duplicateTileSystemGO, ReplacePrefabOptions.ConnectToPrefab);

                // Raise event for end of building prefab.
                if (BuildPrefabComplete != null)
                {
                    BuildPrefabComplete(newPrefab);
                }
            }
            catch {
                throw;
            }
            finally {
                // Destroy duplicate tile system.
                Object.DestroyImmediate(duplicateTileSystemGO);
                // Finished with progress bar!
                EditorUtility.ClearProgressBar();
            }
        }
Пример #16
0
        /// <summary>
        /// Build all tile systems in scene.
        /// </summary>
        /// <remarks>
        /// <para>Each tile system in scene is built in sequence and then the built
        /// version of the scene is saved. Various user interfaces will appear during
        /// the build process.</para>
        /// </remarks>
        public static void BuildScene()
        {
            if (!EditorUtility.DisplayDialog(
                    TileLang.ParticularText("Action", "Build Scene"),
                    TileLang.Text("Scene must be saved before tile systems can be built.\n\nWould you like to save the scene now?"),
                    TileLang.ParticularText("Action", "Save and Proceed"),
                    TileLang.ParticularText("Action", "Cancel")
                    ))
            {
                //EditorUtility.DisplayDialog(ProductInfo.name, "Could not build scene because it was not saved.", "Close");
                return;
            }

            // Force user to save scene
            if (!EditorSceneManager.SaveOpenScenes())
            {
                //EditorUtility.DisplayDialog(ProductInfo.name, "Could not build scene because it was not saved.", "Close");
                return;
            }

            string originalScenePath = EditorApplication.currentScene;

            if (!EditorUtility.DisplayDialog(
                    string.Format(
                        /* 0: path of scene */
                        TileLang.Text("Building Scene '{0}'"),
                        originalScenePath
                        ),
                    TileLang.Text("Open scene was saved successfully.\n\nProceed to save built variation of scene."),
                    TileLang.ParticularText("Action", "Proceed"),
                    TileLang.ParticularText("Action", "Cancel")
                    ))
            {
                Debug.Log(TileLang.Text("Building of tile systems was cancelled."));
                return;
            }

            // Prompt user to save built scene.
            string outputPath = SaveBuildSceneAs();

            if (outputPath == null)
            {
                return;
            }

            // Save output scene straight away!
            if (!EditorApplication.SaveScene(outputPath))
            {
                EditorUtility.DisplayDialog(
                    TileLang.Text("Error"),
                    string.Format(
                        /* 0: path to output asset */
                        TileLang.ParticularText("Error", "Was unable to save output scene '{0}'"),
                        outputPath
                        ),
                    TileLang.ParticularText("Action", "Close")
                    );
                return;
            }

            if (BuildSceneStart != null)
            {
                BuildSceneStart();
            }

            bool hasErrors = false;

            // Fetch all tile systems in scene.
            TileSystem[] systems = GameObject.FindObjectsOfType <TileSystem>();

            float overallTaskCount  = 1f;
            float overallTaskOffset = 0f;
            float overallTaskRatio  = 0f;

            TileSystemBuilder builder = new TileSystemBuilder();

            builder.progressHandler = delegate(string title, string status, float percentage) {
                float progress = (builder.Task + overallTaskOffset) * overallTaskRatio;
                return(EditorUtility.DisplayCancelableProgressBar(title, status, progress));
            };

            // Count tasks in advance.
            foreach (TileSystem system in systems)
            {
                // Skip non-editable tile systems and output warning message to console.
                if (!system.IsEditable)
                {
                    Debug.LogWarning(string.Format(
                                         /* 0: name of tile system */
                                         TileLang.Text("Skipping non-editable tile system '{0}'."),
                                         system.name
                                         ), system);
                    continue;
                }

                overallTaskCount += builder.CountTasks(system);
            }

            overallTaskRatio = 1f / overallTaskCount;

            try {
                // Build each tile system in turn.
                foreach (TileSystem system in systems)
                {
                    // Skip non-editable tile systems.
                    if (!system.IsEditable)
                    {
                        continue;
                    }

                    BuildTileSystemHelper(builder, system);

                    // Adjust overall task offset.
                    overallTaskOffset += builder.TaskCount;
                }

                builder.progressHandler(
                    TileLang.Text("Building tile systems"),
                    TileLang.Text("Cleaning up..."),
                    progress: (overallTaskCount - 1f) * overallTaskRatio
                    );
                builder = null;

                UnityEngine.Resources.UnloadUnusedAssets();
                GC.Collect();
            }
            catch (Exception ex) {
                Debug.LogError(ex.ToString());
                hasErrors = true;
            }
            finally {
                // Finished with progress bar!
                EditorUtility.ClearProgressBar();
            }

            // Save output scene.
            if (!EditorApplication.SaveScene(outputPath))
            {
                Debug.LogError(string.Format(
                                   /* 0: scene file path */
                                   TileLang.ParticularText("Error", "Was unable to save output scene '{0}'"),
                                   outputPath
                                   ));
            }

            // Raise event for end of build process.
            if (BuildSceneComplete != null)
            {
                BuildSceneComplete();
            }

            // Rollback changes.
            EditorApplication.OpenScene(originalScenePath);

            if (hasErrors)
            {
                EditorUtility.DisplayDialog(
                    TileLang.Text("Warning"),
                    TileLang.Text("Errors were encountered whilst building scene. Please check console for any additional information."),
                    TileLang.ParticularText("Action", "Close")
                    );
            }
        }
        private void OnToolSelectorGUI()
        {
            GUILayout.Space(6);

            this.FilterRegisteredTools();

            // Calculate metrics.
            int buttonColumns = Screen.width / 46;

            if (buttonColumns > this.filteredToolList.Count + 1)
            {
                buttonColumns = this.filteredToolList.Count + 1;
            }

            // Prepare style for tool button.
            if (s_ToolButtonStyle == null)
            {
                s_ToolButtonStyle = new GUIStyle(RotorzEditorStyles.Instance.ToolButton);
            }
            s_ToolButtonStyle.fixedWidth = Mathf.FloorToInt((float)Screen.width / (float)buttonColumns) - 3;

            // Display tool items.
            GUILayout.BeginHorizontal();
            GUILayout.Space(4);

            using (var content = ControlContent.Basic(
                       RotorzEditorStyles.Skin.MenuButton,
                       TileLang.ParticularText("Action", "Main Menu")
                       )) {
                if (EditorInternalUtility.DropdownMenu(content, s_ToolButtonStyle))
                {
                    EditorUtility.DisplayPopupMenu(this.menuPosition, "CONTEXT/_RTS_TOOLS_", new MenuCommand(this, 0));
                }
                if (Event.current.type == EventType.Repaint)
                {
                    this.menuPosition = GUILayoutUtility.GetLastRect();
                }
            }

            int currentColumn = 1;

            for (int i = 0; i < this.filteredToolList.Count; ++i)
            {
                var tool = this.filteredToolList[i];

                // Place tool button at start of new row upon overflowing width of palette.
                if (currentColumn++ >= buttonColumns)
                {
                    currentColumn = 0;
                    GUILayout.EndHorizontal();
                    GUILayout.BeginHorizontal();
                    GUILayout.Space(4);
                }

                bool selected = ToolManager.Instance.CurrentTool == tool;

                // Get label for tool button and select icon based upon tool selection.
                var toolIconTexture = selected ? tool.IconActive : tool.IconNormal;
                using (var buttonContent = ControlContent.Basic(tool.Label, toolIconTexture)) {
                    // Fallback to 'normal' icon if 'active' icon is not specified.
                    if (selected && toolIconTexture == null)
                    {
                        buttonContent.LabelContent.image = tool.IconNormal;
                    }

                    if (this.ToolButton(buttonContent, selected))
                    {
                        ToolManager.Instance.CurrentTool = !selected ? tool : null;
                    }
                }
            }
            GUILayout.EndHorizontal();

            ExtraEditorGUI.SeparatorLight(marginBottom: 0);

            this.scrolling = GUILayout.BeginScrollView(this.scrolling);

            if (ToolManager.Instance.CurrentTool != null)
            {
                GUILayout.Space(6);

                float restoreLabelWidth = EditorGUIUtility.labelWidth;
                EditorGUIUtility.labelWidth = 130;
                {
                    var tool = ToolManager.Instance.CurrentTool;
                    tool.OnToolOptionsGUI();

                    if (tool.HasAdvancedToolOptionsGUI)
                    {
                        GUILayout.Space(-2);

                        tool.ShowAdvancedOptionsGUI = GUILayout.Toggle(tool.ShowAdvancedOptionsGUI, TileLang.ParticularText("Section", "Advanced"), RotorzEditorStyles.Instance.FlatToggle);
                        if (tool.ShowAdvancedOptionsGUI)
                        {
                            tool.OnAdvancedToolOptionsGUI();
                        }
                    }
                }
                EditorGUIUtility.labelWidth = restoreLabelWidth;
            }
            else
            {
                GUILayout.Space(6 + 2);
                GUILayout.Label(TileLang.Text("No tool selected"), EditorStyles.miniLabel);
            }

            GUILayout.Space(3);
            GUILayout.FlexibleSpace();

            GUILayout.EndScrollView();
        }
Пример #18
0
        private void DrawRuntimeOptionsSection()
        {
            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Erase Empty Chunks"),
                       TileLang.Text("Hints that empty chunks should be erased when they become empty at runtime.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyHintEraseEmptyChunks, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Apply Basic Stripping"),
                       TileLang.Text("Applies a basic degree of stripping at runtime upon awakening.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyApplyRuntimeStripping, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            ExtraEditorGUI.SeparatorLight();

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Update Procedural at Start"),
                       TileLang.Text("Automatically updates procedural meshes at runtime upon awakening.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyUpdateProceduralAtStart, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Mark Procedural Dynamic"),
                       TileLang.Text("Helps to improve performance when procedural tiles are updated frequently at runtime. Unset if only updated at start of level.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyMarkProceduralDynamic, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Add Procedural Normals"),
                       TileLang.Text("Adds normals to procedural meshes.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyAddProceduralNormals, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            ExtraEditorGUI.SeparatorLight();

            EditorGUI.BeginChangeCheck();

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Procedural Sorting Layer"),
                       TileLang.Text("Sorting layer for procedural tileset meshes.")
                       )) {
                RotorzEditorGUI.SortingLayerField(this.propertySortingLayerID, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Procedural Order in Layer"),
                       TileLang.Text("Order in sorting layer.")
                       )) {
                EditorGUILayout.PropertyField(this.propertySortingOrder, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            if (EditorGUI.EndChangeCheck())
            {
                int sortingLayerID = this.propertySortingLayerID.intValue;
                int sortingOrder   = this.propertySortingOrder.intValue;

                // Update existing procedurally generated tileset meshes immediately.
                foreach (var target in this.targets)
                {
                    ((TileSystem)target).ApplySortingPropertiesToExistingProceduralMeshes(sortingLayerID, sortingOrder);
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Handles GUI events for inspector.
        /// </summary>
        public void OnGUI()
        {
            float initialLabelWidth = EditorGUIUtility.labelWidth;

            RotorzEditorGUI.UseExtendedLabelWidthForLocalization();

            bool formerAddNormals = this.target.addProceduralNormals;

            this.serializedObject.Update();

            GUILayout.Space(6);
            this.DrawToolbar();
            GUILayout.Space(6);

            if (!this.target.IsEditable)
            {
                EditorGUILayout.HelpBox(TileLang.Text("Tile system has been built and can no longer be edited."), MessageType.Info, true);
                return;
            }

            // Display message if any of the target tile systems are locked.
            foreach (TileSystem tileSystem in this.targets)
            {
                if (tileSystem.Locked)
                {
                    string message = this.targets.Length == 1
                        ? TileLang.Text("Tile system is locked. Select 'Toggle Lock' from context menu to unlock inspector.")
                        : TileLang.Text("One or more selected tile systems are locked. Unlock tile systems to unlock inspector.");
                    EditorGUILayout.HelpBox(message, MessageType.Info, true);
                    return;
                }
            }

            s_setting_ToggleModifyGrid.Value = RotorzEditorGUI.FoldoutSection(s_setting_ToggleModifyGrid,
                                                                              label: TileLang.ParticularText("Section", "Modify Grid"),
                                                                              callback: this.DrawModifyGridSection,
                                                                              paddedStyle: RotorzEditorStyles.Instance.InspectorSectionPadded
                                                                              );

            s_setting_ToggleStripping.Value = RotorzEditorGUI.FoldoutSection(s_setting_ToggleStripping,
                                                                             label: TileLang.ParticularText("Section", "Stripping"),
                                                                             callback: this.DrawStrippingSection,
                                                                             paddedStyle: RotorzEditorStyles.Instance.InspectorSectionPadded
                                                                             );

            s_setting_ToggleBuildOptions.Value = RotorzEditorGUI.FoldoutSection(s_setting_ToggleBuildOptions,
                                                                                label: TileLang.ParticularText("Section", "Build Options"),
                                                                                callback: this.DrawBuildOptionsSection,
                                                                                paddedStyle: RotorzEditorStyles.Instance.InspectorSectionPadded
                                                                                );

            s_setting_ToggleRuntimeOptions.Value = RotorzEditorGUI.FoldoutSection(s_setting_ToggleRuntimeOptions,
                                                                                  label: TileLang.ParticularText("Section", "Runtime Options"),
                                                                                  callback: this.DrawRuntimeOptionsSection,
                                                                                  paddedStyle: RotorzEditorStyles.Instance.InspectorSectionPadded
                                                                                  );

            // Ensure that changes are saved.
            if (GUI.changed)
            {
                EditorUtility.SetDirty(this.target);
                this.serializedObject.ApplyModifiedProperties();

                if (formerAddNormals != this.target.addProceduralNormals)
                {
                    this.target.UpdateProceduralTiles(true);
                }
            }

            EditorGUIUtility.labelWidth = initialLabelWidth;
        }
        private void DrawCategoryListToolbar()
        {
            GUILayout.BeginHorizontal(EditorStyles.toolbar);

            this.propertyShowCategoryIds.boolValue = GUILayout.Toggle(this.propertyShowCategoryIds.boolValue, TileLang.ParticularText("Action", "Show Id"), EditorStyles.toolbarButton);

            GUILayout.FlexibleSpace();

            if (GUILayout.Button(RotorzEditorStyles.Skin.SortAsc, EditorStyles.toolbarButton))
            {
                ProjectSettings.Instance.SortCategoriesByLabel(true);
            }
            if (GUILayout.Button(RotorzEditorStyles.Skin.SortDesc, EditorStyles.toolbarButton))
            {
                ProjectSettings.Instance.SortCategoriesByLabel(false);
            }

            GUILayout.EndHorizontal();
        }
Пример #21
0
 /// <inheritdoc/>
 protected override void DoEnable()
 {
     this.titleContent = new GUIContent(TileLang.ParticularText("Action", "Select Brush Categories"));
     this.InitialSize  = new Vector2(400, 320);
     this.minSize      = new Vector2(360, 230);
 }
        private void OnSection_BuildOptions()
        {
            float initialLabelWidth = EditorGUIUtility.labelWidth;

            GUILayout.Space(3);

            using (var content = ControlContent.Basic(
                       TileLang.ParticularText("Property", "Combine Method")
                       )) {
                EditorGUILayout.PropertyField(this.propertyCombineMethod, content);
            }

            if (!this.propertyCombineMethod.hasMultipleDifferentValues)
            {
                if ((BuildCombineMethod)this.propertyCombineMethod.intValue == BuildCombineMethod.CustomChunkInTiles)
                {
                    GUILayout.BeginHorizontal();
                    ++EditorGUI.indentLevel;
                    {
                        EditorGUIUtility.labelWidth = 65;

                        EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Height"));
                        EditorGUI.BeginChangeCheck();
                        EditorGUILayout.PropertyField(this.propertyCombineChunkHeight, GUIContent.none);
                        if (EditorGUI.EndChangeCheck())
                        {
                            this.propertyCombineChunkHeight.intValue = Mathf.Max(1, this.propertyCombineChunkHeight.intValue);
                        }

                        EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Width"));
                        EditorGUI.BeginChangeCheck();
                        EditorGUILayout.PropertyField(this.propertyCombineChunkWidth, GUIContent.none);
                        if (EditorGUI.EndChangeCheck())
                        {
                            this.propertyCombineChunkWidth.intValue = Mathf.Max(1, this.propertyCombineChunkWidth.intValue);
                        }

                        EditorGUIUtility.labelWidth = initialLabelWidth;
                    }
                    --EditorGUI.indentLevel;
                    GUILayout.EndHorizontal();
                }

                if ((BuildCombineMethod)this.propertyCombineMethod.intValue != BuildCombineMethod.None)
                {
                    ++EditorGUI.indentLevel;
                    {
                        this.propertyCombineIntoSubmeshes.boolValue = EditorGUILayout.ToggleLeft(TileLang.ParticularText("Property", "Combine into submeshes"), this.propertyCombineIntoSubmeshes.boolValue);
                        if (ControlContent.TrailingTipsVisible)
                        {
                            ExtraEditorGUI.TrailingTip(TileLang.Text("Determines whether to use submeshes, or an individual mesh for each material."));
                        }
                    }
                    --EditorGUI.indentLevel;

                    RotorzEditorGUI.InfoBox(TileLang.Text("Avoid generation of meshes with vertices in excess of 64k."), MessageType.Warning);
                }
            }

            EditorGUILayout.Space();

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Vertex Snap Threshold"),
                       TileLang.Text("Increase threshold to snap vertices that are more widely spread.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyVertexSnapThreshold, content);
                if (!this.propertyVertexSnapThreshold.hasMultipleDifferentValues)
                {
                    if (this.propertyVertexSnapThreshold.floatValue == 0f)
                    {
                        EditorGUILayout.HelpBox(TileLang.Text("No snapping occurs when threshold is 0."), MessageType.Warning, true);
                    }
                }
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Static Snapping"),
                       TileLang.Text("Applies vertex snapping to static tiles to avoid tiny gaps due to numerical inaccuracies. Vertex snapping is always applied to 'smooth' tiles.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyStaticVertexSnapping, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.Basic(
                       TileLang.ParticularText("Property", "Generate Lightmap UVs")
                       )) {
                EditorGUILayout.PropertyField(this.propertyGenerateSecondUVs, content);
                if (this.propertyGenerateSecondUVs.boolValue)
                {
                    ++EditorGUI.indentLevel;

                    s_ToggleBuildOptions_AdvancedUV2 = EditorGUILayout.Foldout(s_ToggleBuildOptions_AdvancedUV2, TileLang.ParticularText("Section", "Advanced"));
                    if (s_ToggleBuildOptions_AdvancedUV2)
                    {
                        float hardAngle  = this.propertySecondUVsHardAngle.floatValue;
                        float packMargin = this.propertySecondUVsPackMargin.floatValue * 1024f;
                        float angleError = this.propertySecondUVsAngleError.floatValue * 100f;
                        float areaError  = this.propertySecondUVsAreaError.floatValue * 100f;

                        using (var content2 = ControlContent.WithTrailableTip(
                                   TileLang.ParticularText("Property", "Hard Angle"),
                                   TileLang.Text("Angle between neighbor triangles that will generate seam.")
                                   )) {
                            EditorGUI.BeginChangeCheck();
                            EditorGUI.showMixedValue = this.propertySecondUVsHardAngle.hasMultipleDifferentValues;
                            hardAngle = EditorGUILayout.Slider(content, hardAngle, 0f, 180f);
                            if (EditorGUI.EndChangeCheck())
                            {
                                this.propertySecondUVsHardAngle.floatValue = Mathf.Ceil(hardAngle);
                            }
                            ExtraEditorGUI.TrailingTip(content2);
                        }

                        using (var content2 = ControlContent.WithTrailableTip(
                                   TileLang.ParticularText("Property", "Pack Margin"),
                                   TileLang.Text("Measured in pixels, assuming mesh will cover an entire 1024x1024 lightmap.")
                                   )) {
                            EditorGUI.BeginChangeCheck();
                            EditorGUI.showMixedValue = this.propertySecondUVsPackMargin.hasMultipleDifferentValues;
                            packMargin = EditorGUILayout.Slider(content, packMargin, 1f, 64f);
                            if (EditorGUI.EndChangeCheck())
                            {
                                this.propertySecondUVsPackMargin.floatValue = Mathf.Ceil(packMargin) / 1024f;
                            }
                            ExtraEditorGUI.TrailingTip(content2);
                        }

                        using (var content2 = ControlContent.WithTrailableTip(
                                   TileLang.ParticularText("Property", "Angle Error"),
                                   TileLang.Text("Measured in percents. Angle error measures deviation of UV angles from geometry angles. Area error measure deviation of UV triangles area from geometry triangles if they were uniformly scaled.")
                                   )) {
                            EditorGUI.BeginChangeCheck();
                            EditorGUI.showMixedValue = this.propertySecondUVsAngleError.hasMultipleDifferentValues;
                            angleError = EditorGUILayout.Slider(content, angleError, 1f, 75f);
                            if (EditorGUI.EndChangeCheck())
                            {
                                this.propertySecondUVsAngleError.floatValue = Mathf.Ceil(angleError) / 100f;
                            }
                            ExtraEditorGUI.TrailingTip(content2);
                        }

                        using (var content2 = ControlContent.Basic(
                                   TileLang.ParticularText("Property", "Area Error")
                                   )) {
                            EditorGUI.BeginChangeCheck();
                            EditorGUI.showMixedValue = this.propertySecondUVsAreaError.hasMultipleDifferentValues;
                            areaError = EditorGUILayout.Slider(content2, areaError, 1f, 75f);
                            if (EditorGUI.EndChangeCheck())
                            {
                                this.propertySecondUVsAreaError.floatValue = Mathf.Ceil(areaError) / 100f;
                            }
                        }

                        EditorGUI.showMixedValue = false;
                    }

                    --EditorGUI.indentLevel;
                }
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Pre-generate Procedural"),
                       TileLang.Text("Increases size of scene but allows brushes to be stripped from builds.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyPregenerateProcedural, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            RotorzEditorGUI.InfoBox(TileLang.Text("Stripping capabilities are reduced when procedural tiles are present but are not pre-generated since they are otherwise generated at runtime."), MessageType.Info);
            GUILayout.Space(5);

            using (var content = ControlContent.Basic(
                       TileLang.ParticularText("Property", "Reduce Box Colliders"),
                       TileLang.Text("Reduces count of box colliders by coalescing adjacent colliders.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyReduceColliders, content);
            }
        }
Пример #23
0
        public bool DrawTilePreviews(Texture2D tileset, ITilesetMetrics metrics, int tileCount = 0)
        {
            if (tileset == null || metrics == null || metrics.TileWidth == 0 || metrics.TileHeight == 0)
            {
                return(false);
            }

            int  tilesetCount       = metrics.Rows * metrics.Columns;
            bool tilesetCountCapped = false;

            // Limit number of tiles that are displayed.
            // Note: Do not exceed 2500 because that starts to become slow!
            if (tileCount > 0)
            {
                tilesetCount = Mathf.Min(tileCount, tilesetCount);
            }
            if (tilesetCount > 2500)
            {
                tilesetCount       = 2500;
                tilesetCountCapped = true;
            }

            int previewSpacing = 5;
            int previewOffsetX = metrics.TileWidth + previewSpacing + 2;
            int previewOffsetY = metrics.TileHeight + previewSpacing + 2;

            Rect r = EditorGUILayout.BeginVertical();

            if (r.width > 0)
            {
                this.previewColumnCount = (int)r.width / previewOffsetX;
                this.previewRowCount    = Mathf.CeilToInt((float)tilesetCount / (float)this.previewColumnCount);
            }

            if (this.previewColumnCount == 0)
            {
                GUILayout.Space(1);
                EditorGUILayout.EndVertical();
                return(false);
            }

            // Repaint window if preview area has changed.
            float previewAreaHeight = this.previewRowCount * previewOffsetY;

            if (previewAreaHeight != this.previewAreaHeight)
            {
                this.previewAreaHeight = previewAreaHeight;
                this.repaintableUI.Repaint();
            }
            GUILayout.Space(this.previewAreaHeight);

            // Get rectangle for outputting previews.
            Rect output = new Rect(r.x, r.y, metrics.TileWidth + 2, metrics.TileHeight + 2);

            float texX = metrics.BorderU;

            Rect texCoords = new Rect(
                texX,
                1f - (metrics.BorderV + metrics.TileHeightUV),
                metrics.TileWidthUV,
                metrics.TileHeightUV
                );

            GUIStyle boxStyle = GUI.skin.box;

            for (int i = 0; i < tilesetCount; ++i)
            {
                if (i != 0)
                {
                    if (i % this.previewColumnCount == 0)
                    {
                        output.x  = r.x;
                        output.y += previewOffsetY;
                    }

                    if (i % metrics.Columns == 0)
                    {
                        texCoords.x  = texX;
                        texCoords.y -= metrics.TileIncrementV;
                    }
                }

                if (Event.current.type == EventType.Repaint)
                {
                    boxStyle.Draw(output, false, false, false, false);

                    GUI.DrawTextureWithTexCoords(
                        new Rect(output.x + 1, output.y + 1, output.width - 2, output.height - 2),
                        tileset,
                        texCoords
                        );
                }

                output.x    += previewOffsetX;
                texCoords.x += metrics.TileIncrementU;
            }

            // Display warning message?
            if (tilesetCountCapped)
            {
                EditorGUILayout.HelpBox(TileLang.Text("Not all tile previews have been displayed to avoid poor performance."), MessageType.Info);
            }

            EditorGUILayout.EndVertical();
            return(true);
        }
Пример #24
0
        private static string SaveBuildSceneAs()
        {
            string currentScenePath = EditorSceneManager.GetActiveScene().path.Replace("Assets/", Application.dataPath + "/");
            //string currentScenePath = EditorApplication.currentScene.Replace("Assets/", Application.dataPath + "/");
            int fileNameIndex = currentScenePath.LastIndexOf('/');

            // Prompt user to save built scene.
            string outputPath;

            while (true)
            {
                // Prompt user to save scene.
                outputPath = EditorUtility.SaveFilePanel(
                    title: TileLang.ParticularText("Action", "Save Built Scene"),
                    directory: currentScenePath.Substring(0, fileNameIndex),
                    defaultName: currentScenePath.Substring(fileNameIndex + 1).Replace(".unity", "_build.unity"),
                    extension: "unity"
                    );
                // Make output path relative to project.
                outputPath = outputPath.Replace(Application.dataPath, "Assets");

                // Attempt to save scene.
                if (!string.IsNullOrEmpty(outputPath))
                {
                    if (outputPath == EditorSceneManager.GetActiveScene().path)
                    {
                        //if (outputPath == EditorApplication.currentScene) {
                        if (EditorUtility.DisplayDialog(
                                TileLang.Text("Error"),
                                TileLang.ParticularText("Error", "Cannot overwrite current scene with built scene."),
                                TileLang.ParticularText("Action", "Choose Other"),
                                TileLang.ParticularText("Action", "Cancel")
                                ))
                        {
                            continue;
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    // Ensure that built scene will be placed within "Assets" directory.
                    else if (outputPath.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }
                }

                // Allow user to retry!
                if (!EditorUtility.DisplayDialog(
                        TileLang.Text("Error"),
                        TileLang.ParticularText("Error", "Was unable to save built scene.\n\nWould you like to specify an alternative filename?"),
                        TileLang.ParticularText("Action", "Yes"),
                        TileLang.ParticularText("Action", "No")
                        ))
                {
                    return(null);
                }
            }

            return(outputPath);
        }
        private void OnSection_TileSystem()
        {
            float initialLabelWidth = EditorGUIUtility.labelWidth;

            BeginMultiPartField(TileLang.ParticularText("Property", "Grid Size (in tiles)"));
            {
                EditorGUIUtility.labelWidth = 65;

                EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Rows"));
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(this.propertyRows, GUIContent.none);
                if (EditorGUI.EndChangeCheck())
                {
                    this.propertyRows.intValue = Mathf.Max(1, this.propertyRows.intValue);
                }

                EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Columns"));
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(this.propertyColumns, GUIContent.none);
                if (EditorGUI.EndChangeCheck())
                {
                    this.propertyColumns.intValue = Mathf.Max(1, this.propertyColumns.intValue);
                }

                EditorGUIUtility.labelWidth = initialLabelWidth;
            }
            EndMultiPartField();

            BeginMultiPartField(TileLang.ParticularText("Property", "Chunk Size (in tiles)"));
            {
                EditorGUIUtility.labelWidth = 65;

                EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Height"));
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(this.propertyChunkHeight, GUIContent.none);
                if (EditorGUI.EndChangeCheck())
                {
                    this.propertyChunkHeight.intValue = Mathf.Max(1, this.propertyChunkHeight.intValue);
                }

                EditorGUILayout.PrefixLabel(TileLang.ParticularText("Property", "Width"));
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(this.propertyChunkWidth, GUIContent.none);
                if (EditorGUI.EndChangeCheck())
                {
                    this.propertyChunkWidth.intValue = Mathf.Max(1, this.propertyChunkWidth.intValue);
                }

                EditorGUIUtility.labelWidth = initialLabelWidth;
            }
            EndMultiPartField();

            if (!this.propertyChunkHeight.hasMultipleDifferentValues && !this.propertyChunkWidth.hasMultipleDifferentValues)
            {
                if (this.propertyChunkHeight.intValue * this.propertyChunkWidth.intValue > 10000)
                {
                    RotorzEditorGUI.InfoBox(TileLang.Text("Do not exceed an area of 100x100 tiles per chunk when using procedural tilesets."), MessageType.Warning);
                }
            }

            if (ControlContent.TrailingTipsVisible)
            {
                ExtraEditorGUI.TrailingTip(TileLang.Text("Number of tiles that contribute to a chunk."));
            }

            ExtraEditorGUI.SeparatorLight();

            BeginMultiPartField(TileLang.ParticularText("Property", "Cell Size"));
            {
                EditorGUI.showMixedValue = this.propertyTileWidth.hasMultipleDifferentValues || this.propertyTileHeight.hasMultipleDifferentValues || this.propertyTileDepth.hasMultipleDifferentValues;

                Vector3 cellSize = new Vector3(this.propertyTileWidth.floatValue, this.propertyTileHeight.floatValue, this.propertyTileDepth.floatValue);
                EditorGUI.BeginChangeCheck();
                cellSize = EditorGUILayout.Vector3Field(GUIContent.none, cellSize);
                if (EditorGUI.EndChangeCheck())
                {
                    this.propertyTileWidth.floatValue  = Mathf.Max(0.0001f, cellSize.x);
                    this.propertyTileHeight.floatValue = Mathf.Max(0.0001f, cellSize.y);
                    this.propertyTileDepth.floatValue  = Mathf.Max(0.0001f, cellSize.z);
                }

                EditorGUI.showMixedValue = false;
            }
            EndMultiPartField();
            if (ControlContent.TrailingTipsVisible)
            {
                ExtraEditorGUI.TrailingTip(TileLang.Text("Span of an individual tile."));
            }

            GUILayout.Space(10);

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Tiles Facing"),
                       TileLang.Text("Direction that tiles will face when painted. 'Sideways' is good for platform and 2D games. 'Upwards' is good for top-down.")
                       )) {
                EditorGUI.BeginChangeCheck();

                EditorGUILayout.PropertyField(this.propertyTilesFacing, content);
                ExtraEditorGUI.TrailingTip(content);

                if (EditorGUI.EndChangeCheck() && this.propertyAutoAdjustDirection.boolValue)
                {
                    switch ((TileFacing)this.propertyTilesFacing.intValue)
                    {
                    case TileFacing.Sideways:
                        this.propertyDirection.intValue = (int)WorldDirection.Forward;
                        break;

                    case TileFacing.Upwards:
                        this.propertyDirection.intValue = (int)WorldDirection.Up;
                        break;
                    }
                }
            }

            GUILayout.Space(3);

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Initial Direction"),
                       TileLang.Text("Initial direction of tile system upon creation. If in doubt assume default and rotate afterwards.")
                       )) {
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(this.propertyDirection, content);
                ExtraEditorGUI.TrailingTip(content);

                if (EditorGUI.EndChangeCheck())
                {
                    this.propertyAutoAdjustDirection.boolValue = false;
                }
            }

            GUILayout.Space(5);
        }
Пример #26
0
        private void DrawProceduralField(TilesetBrush brush, Tileset tileset)
        {
            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Procedural"),
                       TileLang.Text("Allows individual atlas brushes to override property of tileset.")
                       )) {
                // Need to make width of "Procedural" popup shorter.
                GUILayout.BeginHorizontal(GUILayout.Width(200));
                InheritYesNo newProcedural = (InheritYesNo)EditorGUILayout.EnumPopup(content, brush.procedural);
                if (newProcedural != brush.procedural)
                {
                    brush.procedural = newProcedural;

                    if (!brush.IsProcedural)
                    {
                        // Ensure that required procedural mesh exists!
                        if (BrushUtility.EnsureTilesetMeshExists(tileset, brush.tileIndex))
                        {
                            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tileset.tileMeshAsset));
                        }
                    }
                }

                Rect position = GUILayoutUtility.GetLastRect();
                GUI.Label(new Rect(position.x + position.width, position.y, 100, position.height), "= " + (brush.IsProcedural ? TileLang.Text("Procedural") : TileLang.Text("Non-Procedural")), EditorStyles.miniLabel);

                GUILayout.EndHorizontal();

                ExtraEditorGUI.TrailingTip(content);
            }
        }
        private void OnSection_RuntimeOptions()
        {
            GUILayout.Space(3);

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Erase Empty Chunks"),
                       TileLang.Text("Hints that empty chunks should be erased when they become empty at runtime.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyHintEraseEmptyChunks, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Apply Basic Stripping"),
                       TileLang.Text("Applies a basic degree of stripping at runtime upon awakening.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyApplyRuntimeStripping, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            ExtraEditorGUI.SeparatorLight();

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Update Procedural at Start"),
                       TileLang.Text("Automatically updates procedural meshes at runtime upon awakening.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyUpdateProceduralAtStart, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Mark Procedural Dynamic"),
                       TileLang.Text("Helps to improve performance when procedural tiles are updated frequently at runtime. Unset if only updated at start of level.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyMarkProceduralDynamic, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Add Procedural Normals"),
                       TileLang.Text("Adds normals to procedural meshes.")
                       )) {
                EditorGUILayout.PropertyField(this.propertyAddProceduralNormals, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            ExtraEditorGUI.SeparatorLight();

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Procedural Sorting Layer"),
                       TileLang.Text("Sorting layer for procedural tileset meshes.")
                       )) {
                RotorzEditorGUI.SortingLayerField(this.propertySortingLayerID, content);
                ExtraEditorGUI.TrailingTip(content);
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Procedural Order in Layer"),
                       TileLang.Text("Order in sorting layer.")
                       )) {
                EditorGUILayout.PropertyField(this.propertySortingOrder, content);
                ExtraEditorGUI.TrailingTip(content);
            }
        }
Пример #28
0
        /// <inheritdoc/>
        public override void OnExtendedPropertiesGUI()
        {
            bool autoInitCollider;

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Add Collider"),
                       TileLang.Text("Automatically adds box collider to painted tile.")
                       )) {
                EditorGUI.BeginChangeCheck();
                this.TilesetBrush.addCollider = EditorGUILayout.ToggleLeft(content, this.TilesetBrush.addCollider);
                autoInitCollider = (EditorGUI.EndChangeCheck() && this.TilesetBrush.addCollider);
                if (this.TilesetBrush.addCollider)
                {
                    ++EditorGUI.indentLevel;
                    this.TilesetBrush.colliderType = (ColliderType)EditorGUILayout.EnumPopup(this.TilesetBrush.colliderType);
                    --EditorGUI.indentLevel;
                }
                ExtraEditorGUI.TrailingTip(content);
            }

            if (autoInitCollider)
            {
                this.TilesetBrush.colliderType = BrushUtility.AutomaticColliderType;
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Always Add Container"),
                       TileLang.Text("Add tile container object even when not needed by brush.")
                       )) {
                if (this.TilesetBrush.IsProcedural)
                {
                    this.TilesetBrush.alwaysAddContainer = EditorGUILayout.ToggleLeft(content, this.TilesetBrush.alwaysAddContainer);
                    ExtraEditorGUI.TrailingTip(content);
                }
            }

            if (this.brushAttachPrefabTick)
            {
                ExtraEditorGUI.SeparatorLight();
            }

            using (var content = ControlContent.WithTrailableTip(
                       TileLang.ParticularText("Property", "Attach Prefab"),
                       TileLang.Text("Additional game objects can be painted by attaching a prefab.")
                       )) {
                bool newAttachPrefabTick = EditorGUILayout.ToggleLeft(content, this.brushAttachPrefabTick);
                if (!newAttachPrefabTick)
                {
                    ExtraEditorGUI.TrailingTip(content);
                }

                // Has state of prefab tick changed?
                if (newAttachPrefabTick != this.brushAttachPrefabTick)
                {
                    this.brushAttachPrefabTick = newAttachPrefabTick;
                    // Should attachment be cleared?
                    if (!this.brushAttachPrefabTick)
                    {
                        this.TilesetBrush.attachPrefab = null;
                    }
                }

                if (this.brushAttachPrefabTick)
                {
                    ++EditorGUI.indentLevel;

                    this.TilesetBrush.attachPrefab = EditorGUILayout.ObjectField(this.TilesetBrush.attachPrefab, typeof(GameObject), false) as GameObject;
                    GUILayout.Space(2);
                    this.OnExtendedGUI_ScaleMode();

                    --EditorGUI.indentLevel;
                }
            }
        }
Пример #29
0
 /// <inheritdoc/>
 public override void OnAdvancedToolOptionsGUI()
 {
     this.MaximumFillCount = EditorGUILayout.IntField(TileLang.ParticularText("Property", "Fill Limit"), this.MaximumFillCount);
     ExtraEditorGUI.TrailingTip(TileLang.Text("Filling too many tiles may cause Unity to crash. Avoid setting this preference too high."));
 }
        private void DrawItem_TileSystem(Rect position, int index, TileSystem system)
        {
            bool isActiveSystem = system == ToolUtility.ActiveTileSystem;

            int itemControlID = GUIUtility.GetControlID(FocusType.Passive);

            Rect totalPosition = ReorderableListGUI.CurrentItemTotalPosition;

            if (this.itemPositions == null || this.itemPositions.Length != this.entries.Count)
            {
                this.itemPositions = new Rect[this.entries.Count];
            }
            this.itemPositions[index] = ReorderableListGUI.CurrentItemTotalPosition;

            Rect eyeButtonPosition  = new Rect(position.x, totalPosition.y + (totalPosition.height - 18) / 2f, 21, 18);
            int  eyeButtonControlID = GUIUtility.GetControlID(FocusType.Passive);

            Rect totalLabelPosition = new Rect(position.x, totalPosition.y, totalPosition.xMax - position.x, totalPosition.height);

            totalLabelPosition.x     += eyeButtonPosition.width + 3;
            totalLabelPosition.width -= eyeButtonPosition.width + 3;

            Rect labelPosition = totalLabelPosition;

            labelPosition.height -= 1;

            var eventType = Event.current.GetTypeForControl(itemControlID);

            if (eventType == EventType.Repaint)
            {
                GUI.DrawTexture(eyeButtonPosition, system.gameObject.activeInHierarchy ? RotorzEditorStyles.Skin.EyeOpen : RotorzEditorStyles.Skin.EyeShut);

                string systemName = this.IsEditingName && this.renameIndex == index ? "" : system.name;
                RotorzEditorStyles.Instance.ListLargeElement.Draw(labelPosition, systemName, false, false, isActiveSystem, false);

                if (system.Locked)
                {
                    Rect lockIconPosition = new Rect(labelPosition.xMax - 28, labelPosition.y + 5, 12, 15);
                    GUI.DrawTexture(lockIconPosition, isActiveSystem ? RotorzEditorStyles.Skin.LockActive : RotorzEditorStyles.Skin.Lock);
                }
            }

            if (isActiveSystem)
            {
                this.RenameField(labelPosition, system);
            }

            if (this.IsEditingName)
            {
                return;
            }

            switch (eventType)
            {
            case EventType.MouseDown:
                if (Event.current.button == 0)
                {
                    if (eyeButtonPosition.Contains(Event.current.mousePosition))
                    {
                        this._wantsToBeginEditingName = false;

                        Undo.RecordObject(system.gameObject, TileLang.ParticularText("Action", "Toggle Visibility"));
                        system.gameObject.SetActive(!system.gameObject.activeSelf);
                        Event.current.Use();
                        break;
                    }

                    bool wasTileSystemAlreadySelected = isActiveSystem || (Selection.activeGameObject == system.gameObject && Selection.objects.Length == 1);
                    if (!wasTileSystemAlreadySelected)
                    {
                        if (Event.current.clickCount == 1 && totalPosition.Contains(Event.current.mousePosition))
                        {
                            // Ensure that tile system is selected.
                            ToolUtility.SelectTileSystem(system);
                        }
                    }

                    if (totalLabelPosition.Contains(Event.current.mousePosition))
                    {
                        this._wantsToBeginEditingName = false;

                        if (Event.current.clickCount == 2)
                        {
                            Selection.objects = new Object[] { system.gameObject };
                            SceneView.lastActiveSceneView.FrameSelected();
                        }
                        else
                        {
                            this.mouseDownPosition = Event.current.mousePosition;

                            // Should game object of tile system be selected?
                            if (wasTileSystemAlreadySelected)
                            {
                                this._wantsToBeginEditingName = this.CanBeginEditingNameOnMouseUp;
                            }

                            GUIUtility.hotControl      = itemControlID;
                            GUIUtility.keyboardControl = 0;
                        }

                        Event.current.Use();
                    }
                }
                else if (Event.current.button == 1)
                {
                    if (totalPosition.Contains(Event.current.mousePosition))
                    {
                        ToolUtility.SelectTileSystem(system);
                        Event.current.Use();

                        GUIUtility.hotControl      = itemControlID;
                        GUIUtility.keyboardControl = 0;
                    }
                }
                break;

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == itemControlID && Event.current.button == 0)
                {
                    if (Vector2.Distance(this.mouseDownPosition, Event.current.mousePosition) >= DragThresholdInPixels)
                    {
                        GUIUtility.hotControl = 0;
                        this.StartDrag(system);
                    }
                    Event.current.Use();
                }
                break;

            case EventType.MouseUp:
                if (GUIUtility.hotControl == itemControlID || GUIUtility.hotControl == eyeButtonControlID)
                {
                    if (totalPosition.Contains(Event.current.mousePosition))
                    {
                        if (Event.current.button == 0 && GUIUtility.hotControl == itemControlID)
                        {
                            // Consider entering rename mode?
                            if (isActiveSystem && this._wantsToBeginEditingName)
                            {
                                CallbackSchedulerUtility.SetTimeout(() => {
                                    if (this._wantsToBeginEditingName)
                                    {
                                        this.BeginEditingName(system);
                                    }
                                }, 0.5);
                            }
                        }
                        else if (Event.current.button == 1)
                        {
                            this.ShowContextMenu(system);
                        }
                    }

                    GUIUtility.hotControl = 0;
                    Event.current.Use();
                }
                break;
            }
        }