Пример #1
0
        public FileResultModel ShowOpenFileDialog(OpenFileDialogConfigModel config)
        {
            var dialog = new OpenFileDialog
            {
                Title            = config.Title,
                InitialDirectory = config.InitialDirectory,
                FileName         = config.FileName,
                Multiselect      = config.Multiselect,
            };

            if (config.FileFilters != null)
            {
                foreach (var filter in config.FileFilters)
                {
                    dialog.FileFilters.Add(filter.ToFilter());
                }
            }

            var result = Application.Invoke(() => dialog.Show(parent));

            return(new FileResultModel
            {
                DialogResult = result,
                File = dialog.FileName,
                Files = dialog.SelectedFiles,
            });
        }
Пример #2
0
        private async void FileOpen_Click(object sender, MouseClickEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog
            {
                Title              = "Open a Text File...",
                Filter             = "All File(*.*)\0*.*\0Text(*.txt)\0*.txt\0",
                DefaultFilterIndex = 2
            };

            //Title of the Dialog

            //All Values have to be separated with \0

            //Shows Text(*.txt) as default

            //Show the Dialog modal to the current Form.
            if (ofd.Show(this))
            {
                this._TextBox.Enabled = false;
                //Read the selected Path
                string fileName = ofd.File;
                //File Actions.
                string text = await File.ReadAllTextAsync(fileName);

                this._CurrentFileName = fileName;
                this._TextBox.Text    = text;
                this._TextBox.Enabled = true;
                this.Text             = "Little Edit:" + fileName;
            }
        }
Пример #3
0
    public void ReadCSV()
    {
        Stream         filePath = null;
        OpenFileDialog openFile = new OpenFileDialog();

        openFile.Title  = "Select CSV File";
        openFile.Filter = "CSV File|*.csv";
        openFile.Show();
    }
Пример #4
0
        protected override void InitializeComponent()
        {
            Margins = true;
            Child   = hPanel;

            hPanel.Children.Add(vPanel);

            vPanel.Children.Add(datePicker);
            vPanel.Children.Add(timePicker);
            vPanel.Children.Add(dateTimePicker);
            vPanel.Children.Add(fontPicker);
            vPanel.Children.Add(colorPicker);

            hPanel.Children.Add(hSeparator);
            hPanel.Children.Add(vPanel2);

            vPanel2.Children.Add(grid);

            button.Click += (sender, args) =>
            {
                OpenFileDialog dialog = new OpenFileDialog();
                if (!dialog.Show())
                {
                    textBox.Text = "(cancelled)";
                    return;
                }
                ;
                textBox.Text = dialog.Path;
            };

            button2.Click += (sender, args) =>
            {
                SaveFileDialog dialog = new SaveFileDialog();
                if (!dialog.Show())
                {
                    textBox2.Text = "(cancelled)";
                    return;
                }
                ;
                textBox2.Text = dialog.Path;
            };

            button3.Click += (sender, args) => { MessageBox.Show("This is a normal message box.", "More detailed information can be shown here."); };
            button4.Click += (sender, args) => { MessageBox.Show("This message box describes an error.", "More detailed information can be shown here.", true); };

            grid.Children.Add(button, 0, 0, 1, 1, 0, 0, Alignment.Fill);
            grid.Children.Add(textBox, 1, 0, 1, 1, 1, 0, Alignment.Fill);
            grid.Children.Add(button2, 0, 1, 1, 1, 0, 0, Alignment.Fill);
            grid.Children.Add(textBox2, 1, 1, 1, 1, 1, 0, Alignment.Fill);
            grid.Children.Add(grid2, 0, 2, 2, 1, 0, 0, Alignment.TopCenter);
            grid2.Children.Add(button3, 0, 0, 1, 1, 0, 0, Alignment.Fill);
            grid2.Children.Add(button4, 1, 0, 1, 1, 0, 0, Alignment.Fill);
        }
Пример #5
0
 public static void PromptCards(Action <string[]> onAccept, string filter)
 {
     OpenFileDialog.Show(
         onAccept,
         Strings.SELECT_CARDS,
         Strings.CHARA_PATH,
         filter,
         Strings.CARD_EXTENSION,
         OpenFileDialog.OpenSaveFileDialgueFlags.OFN_ALLOWMULTISELECT |
         OpenFileDialog.OpenSaveFileDialgueFlags.OFN_FILEMUSTEXIST |
         OpenFileDialog.OpenSaveFileDialgueFlags.OFN_EXPLORER |
         OpenFileDialog.OpenSaveFileDialgueFlags.OFN_LONGNAMES
         );
 }
Пример #6
0
        public override bool OnKeyDown(KeyInfo key)
        {
            if (key.Key == ConsoleKey.F3)
            {
                MessageBox.Show(
                    "Thank you for letting me hax your system folder by putting 3 gb \nof pictures with Nicholas Cage",
                    " Test ",
                    MessageBoxButtons.OKCancel, res =>
                {
                });
            }
            if (key.Key == ConsoleKey.F4)
            {
                var ofd = new OpenFileDialog();
                ofd.Show(result =>
                {
                    if (result.GetValueOrDefault())
                    {
                        MessageBox.Show(
                            "So you want to open: " + ofd.SelectedFile + ", eh?",
                            " File to be opened ",
                            MessageBoxButtons.OK);
                    }
                    else
                    {
                        MessageBox.Show("Damn you're grumpy, son!", " No file? Fine! ", MessageBoxButtons.OK);
                    }
                });
            }

            if (key.Key == ConsoleKey.F1)
            {
                aboutWindow.Show();
            }

            if (key.Key == ConsoleKey.F2)
            {
                testWindow.Show(res =>
                {
                    var text = this.Controls.FindOfType <TextBlock>();
                    if (text)
                    {
                        text.Text = " " + res + " " + text.Text;
                    }
                });
            }

            return(base.OnKeyDown(key));
        }
Пример #7
0
        public bool ChooseContentFile(string initialDirectory, out List<string> files)
        {
            var dialog = new OpenFileDialog();
            dialog.Directory = new Uri(initialDirectory);
            dialog.MultiSelect = true;
            dialog.Filters.Add(_allFileFilter);
            dialog.CurrentFilter = _allFileFilter;

            var result = dialog.Show(this) == DialogResult.Ok;

            files = new List<string>();
            files.AddRange(dialog.Filenames);

            return result;
        }
Пример #8
0
        public bool AskImportProject(out string projectFilePath)
        {
            var dialog = new OpenFileDialog();
            dialog.Filters.Add(_xnaFileFilter);
            dialog.Filters.Add(_allFileFilter);
            dialog.CurrentFilter = _xnaFileFilter;

            if (dialog.Show(this) == DialogResult.Ok)
            {
                projectFilePath = dialog.FileName;
                return true;
            }

            projectFilePath = "";
            return false;
        }
Пример #9
0
        public bool AskOpenProject(out string projectFilePath)
        {
            var dialog = new OpenFileDialog();

            dialog.Filters.Add(_mgcbFileFilter);
            dialog.Filters.Add(_allFileFilter);
            dialog.CurrentFilter = _mgcbFileFilter;

            if (dialog.Show(this) == DialogResult.Ok)
            {
                projectFilePath = dialog.FileName;
                return(true);
            }

            projectFilePath = "";
            return(false);
        }
        private void SetupTexControls(RegisterCustomControlsEvent e, MakerCategory makerCategory, BaseUnityPlugin owner, TexType texType, string title)
        {
            e.AddControl(new MakerText(title, makerCategory, owner));

            var bi = e.AddControl(new MakerImage(null, makerCategory, owner)
            {
                Height = 150, Width = 150
            });

            _textureChanged.Subscribe(
                d =>
            {
                if (d.Key == texType)
                {
                    bi.Texture = d.Value;
                }
            });

            e.AddControl(new MakerButton("Load new texture", makerCategory, owner))
            .OnClick.AddListener(
                () => OpenFileDialog.Show(strings => OnFileAccept(strings, texType), "Open overlay image", GetDefaultLoadDir(), FileFilter, FileExt));

            e.AddControl(new MakerButton("Clear texture", makerCategory, owner))
            .OnClick.AddListener(() => SetTexAndUpdate(null, texType));

            e.AddControl(new MakerButton("Export current texture", makerCategory, owner))
            .OnClick.AddListener(
                () =>
            {
                try
                {
                    var ctrl = GetOverlayController();
                    var tex  = ctrl.Overlays.FirstOrDefault(x => x.Key == texType).Value;
                    if (tex == null)
                    {
                        return;
                    }
                    WriteAndOpenPng(tex.Data);
                }
                catch (Exception ex)
                {
                    Logger.Log(LogLevel.Error | LogLevel.Message, "[KSOX] Failed to export texture - " + ex.Message);
                }
            });
        }
Пример #11
0
        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();

            dialog.Directory   = new Uri(_controller.ProjectItem.Location);
            dialog.MultiSelect = true;
            dialog.Filters.Add(_dllFileFilter);
            dialog.Filters.Add(_allFileFilter);
            dialog.CurrentFilter = _dllFileFilter;

            if (dialog.Show(this) == DialogResult.Ok)
            {
                foreach (var fileName in dialog.Filenames)
                {
                    _dataStore.Add(new RefItem(Path.GetFileName(fileName), fileName));
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Allows the user to pick a project file.
        /// </summary>
        public static void OpenProject()
        {
            OpenFileDialog of = new OpenFileDialog();

            of.SetFilter(new FileFilter("MK Project File", "mkproj"));
            string lastfolder = "";

            if (GeneralSettings.RecentFiles.Count > 0)
            {
                string path = GeneralSettings.RecentFiles[0][1];
                while (path.Contains("/"))
                {
                    path = path.Replace("/", "\\");
                }
                List <string> folders = path.Split('\\').ToList();
                for (int i = 0; i < folders.Count - 1; i++)
                {
                    lastfolder += folders[i];
                    if (i != folders.Count - 2)
                    {
                        lastfolder += "\\";
                    }
                }
            }
            of.SetInitialDirectory(lastfolder);
            of.SetTitle("Choose a project file...");
            string result = of.Show() as string;

            if (!string.IsNullOrEmpty(result))
            {
                if (!result.EndsWith(".mkproj"))
                {
                    new MessageBox("Error", "Invalid project file.", ButtonType.OK, IconType.Error);
                }
                else
                {
                    CloseProject();
                    Data.SetProjectPath(result);
                    MainWindow.CreateEditor();
                    MakeRecentProject();
                }
            }
        }
Пример #13
0
            public void AddMaterialTextureProperty(int id, string materialName, string property, GameObject go)
            {
                OpenFileDialog.Show(strings => OnFileAccept(strings), "Open image", Application.dataPath, FileFilter, FileExt);

                void OnFileAccept(string[] strings)
                {
                    if (strings == null || strings.Length == 0)
                    {
                        return;
                    }

                    if (strings[0].IsNullOrEmpty())
                    {
                        return;
                    }

                    TexBytes        = File.ReadAllBytes(strings[0]);
                    PropertyToSet   = property;
                    MatToSet        = materialName;
                    GameObjectToSet = go;
                    IDToSet         = id;
                }
            }
Пример #14
0
        public static void ImportMaps()
        {
            Setup();
            OpenFileDialog of = new OpenFileDialog();

            of.SetFilter(new FileFilter("RPG Maker XP Map", "rxdata"));
            of.SetTitle("Pick map(s)");
            of.SetAllowMultiple(true);
            object        ret   = of.Show();
            List <string> Files = new List <string>();

            if (ret is string)
            {
                Files.Add(ret as string);
            }
            else if (ret is List <string> )
            {
                Files = ret as List <string>;
            }
            else
            {
                return;  // No files picked
            }
            for (int i = 0; i < Files.Count; i++)
            {
                while (Files[i].Contains('\\'))
                {
                    Files[i] = Files[i].Replace('\\', '/');
                }
            }
            string[] folders = Files[0].Split('/');
            string   parent  = "";
            string   root    = "";

            for (int i = 0; i < folders.Length - 1; i++)
            {
                parent += folders[i];
                if (i != folders.Length - 2)
                {
                    root += folders[i];
                }
                if (i != folders.Length - 2)
                {
                    parent += '/';
                }
                if (i != folders.Length - 3)
                {
                    root += '/';
                }
            }
            List <string> Names = new List <string>();

            foreach (string f in Files)
            {
                string[] l = f.Split('/').Last().Split('.');
                string   n = "";
                for (int i = 0; i < l.Length - 1; i++)
                {
                    n += l[i];
                    if (i != l.Length - 2)
                    {
                        n += '.';
                    }
                }
                Names.Add(n);
            }
            // Load MapInfos.rxdata
            IntPtr infofile = Ruby.Funcall(Ruby.GetConst(Ruby.Object.Class, "File"), "open", Ruby.String.ToPtr(parent + "/MapInfos.rxdata"), Ruby.String.ToPtr("rb"));
            IntPtr infos    = Ruby.Funcall(Ruby.GetConst(Ruby.Object.Class, "Marshal"), "load", infofile);

            Ruby.Pin(infos);
            IntPtr keys = Ruby.Funcall(infos, "keys");

            Ruby.Pin(keys);
            Ruby.Funcall(infofile, "close");
            // Load Tilesets.rxdata
            IntPtr tilesetfile = Ruby.Funcall(Ruby.GetConst(Ruby.Object.Class, "File"), "open", Ruby.String.ToPtr(parent + "/Tilesets.rxdata"), Ruby.String.ToPtr("rb"));
            IntPtr tilesets    = Ruby.Funcall(Ruby.GetConst(Ruby.Object.Class, "Marshal"), "load", tilesetfile);

            Ruby.Pin(tilesets);
            Ruby.Funcall(tilesetfile, "close");
            Action <int> ImportMap = null;

            ImportMap = delegate(int MapIndex)
            {
                // Convert rxdata (Ruby) to mkd (C#)
                string MapName = Names[MapIndex];
                string file    = Files[MapIndex];
                while (file.Contains('\\'))
                {
                    file = file.Replace('\\', '/');
                }
                // Load Map.rxdata
                IntPtr f   = Ruby.Funcall(Ruby.GetConst(Ruby.Object.Class, "File"), "open", Ruby.String.ToPtr(file), Ruby.String.ToPtr("rb"));
                IntPtr map = Ruby.Funcall(Ruby.GetConst(Ruby.Object.Class, "Marshal"), "load", f);
                Ruby.Pin(map);
                Ruby.Funcall(f, "close");
                int id = Convert.ToInt32(file.Substring(file.Length - 10, 3));
                // Link Map with its MapInfo
                IntPtr info = IntPtr.Zero;
                for (int i = 0; i < Ruby.Array.Length(keys); i++)
                {
                    if (Ruby.Array.Get(keys, i) == Ruby.Integer.ToPtr(id))
                    {
                        info = Ruby.Funcall(infos, "[]", Ruby.Array.Get(keys, i));
                    }
                }
                if (info == IntPtr.Zero)
                {
                    throw new Exception($"No MapInfo could be found for map ({MapName}).");
                }
                Game.Map data = new Game.Map();
                data.ID          = Editor.GetFreeMapID();
                data.DisplayName = MapInfo.Name(info);
                data.DevName     = data.DisplayName;
                data.Width       = Map.Width(map);
                data.Height      = Map.Height(map);
                IntPtr tileset = Ruby.Array.Get(tilesets, Map.TilesetID(map));
                Ruby.Pin(tileset);
                string       tilesetname = Tileset.Name(tileset);
                Action       cont        = null;
                Game.Tileset existing    = Data.Tilesets.Find(t => t != null && (t.Name == tilesetname || t.GraphicName == tilesetname));
                bool         exist       = existing != null;
                string       message     = $"Importing Map ({MapName})...\n\n";
                if (exist)
                {
                    message += "The tileset of the imported map has the same name as an already-defined tileset in " +
                               $"the database ({existing.Name}).\n" +
                               "Would you like to use this tileset, choose a different one, or import it?";
                }
                else
                {
                    message += $"No tilesets similar to the one used in the imported map ({Tileset.Name(tileset)}) could be found.\n" +
                               "Would you like to pick an existing tileset, or import it?";
                }
                List <string> Options = new List <string>();
                if (exist)
                {
                    Options.Add("Use this");
                }
                Options.Add("Pick other");
                Options.Add("Import it");
                MessageBox box = new MessageBox("Importing Map", message, Options);
                box.OnButtonPressed += delegate(BaseEventArgs e)
                {
                    if (Options[box.Result] == "Use this") // Use the matched tileset
                    {
                        data.TilesetIDs = new List <int>()
                        {
                            existing.ID
                        };
                        cont();
                    }
                    else if (Options[box.Result] == "Pick other") // Pick other tileset
                    {
                        TilesetPicker picker = new TilesetPicker(null);
                        picker.OnClosed += delegate(BaseEventArgs e)
                        {
                            if (picker.ChosenTilesetID > 0) // Chose tileset
                            {
                                data.TilesetIDs = new List <int>()
                                {
                                    picker.ChosenTilesetID
                                };
                                cont();
                            }
                            else // Didn't pick tileset; cancel importing
                            {
                                data = null;
                                Ruby.Unpin(tileset);
                                Ruby.Unpin(map);
                                MessageBox b = new MessageBox("Warning", $"Importing Map ({MapName})...\n\nAs no tileset was chosen, this map will not be imported.", IconType.Warning);
                                b.OnButtonPressed += delegate(BaseEventArgs e)
                                {
                                    if (MapIndex < Files.Count - 1)
                                    {
                                        ImportMap(MapIndex + 1);
                                    }
                                };
                            }
                        };
                    }
                    else if (Options[box.Result] == "Import it") // Import the tileset
                    {
                        string filename = root + "/Graphics/Tilesets/" + Tileset.TilesetName(tileset) + ".png";
                        if (!File.Exists(filename)) // Graphic doesn't exist
                        {
                            MessageBox b = new MessageBox("Error", $"Importing Map ({MapName})...\n\nThe tileset graphic could not be found. The tileset cannot be imported, and thus this map will not be imported.", IconType.Error);
                            b.OnButtonPressed += delegate(BaseEventArgs e)
                            {
                                if (MapIndex < Files.Count - 1)
                                {
                                    ImportMap(MapIndex + 1);
                                }
                            };
                        }
                        else // Graphic does exist
                        {
                            Bitmap bmp = new Bitmap(filename);
                            int    pw  = bmp.Width / 32 * 33;
                            int    ph  = bmp.Height / 32 * 33;
                            if (pw > Graphics.MaxTextureSize.Width || ph > Graphics.MaxTextureSize.Height)
                            {
                                MessageBox b = new MessageBox("Error",
                                                              $"Importing Map ({MapName})...\n\n" +
                                                              $"The formatted tileset will exceed the maximum texture size ({Graphics.MaxTextureSize.Width},{Graphics.MaxTextureSize.Height}).\n" +
                                                              "This map will not be imported."
                                                              );
                                b.OnButtonPressed += delegate(BaseEventArgs e)
                                {
                                    if (MapIndex < Files.Count - 1)
                                    {
                                        ImportMap(MapIndex + 1);
                                    }
                                };
                            }
                            else
                            {
                                string destination = Data.ProjectPath + "/gfx/tilesets/";
                                string name        = Tileset.TilesetName(tileset);
                                if (File.Exists(destination + Tileset.TilesetName(tileset) + ".png"))
                                {
                                    int i = 0;
                                    do
                                    {
                                        i++;
                                    } while (File.Exists(destination + Tileset.TilesetName(tileset) + " (" + i.ToString() + ").png"));
                                    destination += Tileset.TilesetName(tileset) + " (" + i.ToString() + ").png";
                                    name        += " (" + i.ToString() + ")";
                                }
                                else
                                {
                                    destination += Tileset.TilesetName(tileset) + ".png";
                                }
                                File.Copy(filename, destination);
                                Game.Tileset set = new Game.Tileset();
                                set.Name        = Tileset.Name(tileset);
                                set.GraphicName = name;
                                set.ID          = Editor.GetFreeTilesetID();
                                int tilecount = 8 * bmp.Height / 32;
                                set.Passabilities = new List <Passability>();
                                set.Priorities    = new List <int?>();
                                set.Tags          = new List <int?>();
                                for (int i = 0; i < tilecount; i++)
                                {
                                    set.Passabilities.Add(Passability.All);
                                    set.Priorities.Add(0);
                                    set.Tags.Add(null);
                                }
                                Data.Tilesets[set.ID] = set;
                                set.CreateBitmap();
                                if (Editor.MainWindow.DatabaseWidget != null)
                                {
                                    Editor.MainWindow.DatabaseWidget.DBDataList.RefreshList();
                                }
                                data.TilesetIDs = new List <int>()
                                {
                                    set.ID
                                };
                                cont();
                            }
                        }
                    }
                };
                // Called whenever a choice has been made for tileset importing.
                cont = new Action(delegate()
                {
                    if (data.TilesetIDs == null || data.TilesetIDs.Count == 0) // Should not be reachable
                    {
                        throw new Exception("Cannot continue without a tileset.");
                    }

                    data.Layers = new List <Layer>();

                    bool RemovedAutotiles = false;
                    bool RemovedEvents    = Ruby.Integer.FromPtr(Ruby.Funcall(Map.Events(map), "length")) > 0;

                    IntPtr Tiles    = Map.Data(map);
                    int XSize       = Table.XSize(Tiles);
                    int YSize       = Table.YSize(Tiles);
                    int ZSize       = Table.ZSize(Tiles);
                    IntPtr tiledata = Table.Data(Tiles);
                    for (int z = 0; z < ZSize; z++)
                    {
                        Layer layer = new Layer($"Layer {z + 1}");
                        for (int y = 0; y < YSize; y++)
                        {
                            for (int x = 0; x < XSize; x++)
                            {
                                int idx    = x + y * XSize + z * XSize * YSize;
                                int tileid = (int)Ruby.Integer.FromPtr(Ruby.Array.Get(tiledata, idx));
                                if (tileid < 384)
                                {
                                    RemovedAutotiles = true;
                                }
                                if (tileid == 0)
                                {
                                    layer.Tiles.Add(null);
                                }
                                else
                                {
                                    layer.Tiles.Add(new TileData()
                                    {
                                        TileType = TileType.Tileset, Index = 0, ID = tileid - 384
                                    });
                                }
                            }
                        }
                        data.Layers.Add(layer);
                    }

                    Ruby.Unpin(map);
                    Ruby.Unpin(tileset);

                    Editor.AddMap(data);

                    if (MapIndex < Files.Count - 1)
                    {
                        ImportMap(MapIndex + 1);
                    }
                    else
                    {
                        string Title = "Warning";
                        string Msg   = "";
                        if (Files.Count > 1)
                        {
                            Msg = "The maps were imported successfully";
                        }
                        else
                        {
                            Msg = "The map was imported successfully";
                        }
                        if (RemovedEvents && RemovedAutotiles)
                        {
                            Msg += ", but all events and autotiles have been deleted as these have not yet been implemented in RPG Studio MK.";
                        }
                        else if (RemovedEvents)
                        {
                            Msg += ", but all events have been deleted as these have not yet been implemented in RPG Studio MK.";
                        }
                        else if (RemovedAutotiles)
                        {
                            Msg += ", but all autotiles have been deleted as these have not yet been implemented in RPG Studio MK.";
                        }
                        else
                        {
                            Title = "Success";
                            Msg  += ".";
                        }
                        List <string> options = new List <string>();
                        if (Editor.ProjectSettings.LastMode != "MAPPING")
                        {
                            options.Add("Go to Map");
                        }
                        options.Add("OK");
                        MessageBox box       = new MessageBox(Title, Msg, options, IconType.Info);
                        box.OnButtonPressed += delegate(BaseEventArgs e)
                        {
                            if (options[box.Result] == "Go to Map") // Go to map
                            {
                                Editor.SetMode("MAPPING");
                                Editor.MainWindow.MapWidget.MapSelectPanel.SetMap(data);
                            }
                        };
                        Ruby.Unpin(keys);
                        Ruby.Unpin(infos);
                        Ruby.Unpin(tileset);
                        Cleanup();
                    }
                });
            };
            ImportMap(0);
        }
Пример #15
0
            private void DrawEditBlock()
            {
                Event _windowEvent = Event.current;

                if (!_pluginCtrl._cachedCoordinateGroupList.Any(x => x.Kind == _curEditGroupKind))
                {
                    _curEditGroupKind = -1;
                }

                _groupScrollPos = GUILayout.BeginScrollView(_groupScrollPos);
                {
                    foreach (TriggerGroup _group in _pluginCtrl._cachedCoordinateGroupList.ToList())
                    {
                        GUILayout.BeginHorizontal(GUI.skin.box);
                        {
                            if (_curRenameGroupKind == _group.Kind)
                            {
                                _curRenameGroupLabel = GUILayout.TextField(_curRenameGroupLabel, GUILayout.Width(65), GUILayout.ExpandWidth(false));
                                GUILayout.FlexibleSpace();
                                if (GUILayout.Button(new GUIContent("save", "Save group label"), _buttonSmall))
                                {
                                    if (_curRenameGroupLabel.Trim().IsNullOrEmpty() || _curRenameGroupLabel != _group.Label)
                                    {
                                        _pluginCtrl.RenameTriggerGroup(_curRenameGroupKind, _curRenameGroupLabel);
                                    }
                                    RefreshCache();
                                }
                                if (GUILayout.Button(new GUIContent("back", "Cancel renaming"), _buttonSmall))
                                {
                                    _curRenameGroupKind  = -1;
                                    _curRenameGroupLabel = "";
                                }
                            }
                            else
                            {
                                if (GUILayout.Button(new GUIContent(_group.Label, "Rename group label"), (_curEditGroupKind == _group.Kind ? _labelActive : _label), GUILayout.Width(70), GUILayout.ExpandWidth(false)))
                                {
                                    if (_curRenameGroupState > -1)
                                    {
                                        return;
                                    }
                                    _curRenameGroupKind  = _group.Kind;
                                    _curRenameGroupLabel = _group.Label;
                                }
                                GUILayout.FlexibleSpace();
                                if (_curEditGroupKind != _group.Kind)
                                {
                                    if (GUILayout.Button(new GUIContent("▼", "View the properties of this group"), _priorityElem))
                                    {
                                        _curEditGroupKind = _group.Kind;
                                    }
                                }
                                else
                                {
                                    if (GUILayout.Button(new GUIContent("▲", "Collapse the property view of this group"), _priorityElem))
                                    {
                                        _curEditGroupKind = -1;
                                    }
                                }
                                if (GUILayout.Button(new GUIContent("X", "Remove the group and accessory settings belong to this group"), _priorityElem))
                                {
                                    _pluginCtrl.RemoveTriggerGroup(_currentCoordinateIndex, _group.Kind);
                                    if (_curEditGroupKind == _group.Kind)
                                    {
                                        _curEditGroupKind = -1;
                                    }
                                    RefreshCache();
                                }
                            }
                        }
                        GUILayout.EndHorizontal();

                        if (_curEditGroupKind == _group.Kind)
                        {
                            List <int> _states = _group.States.OrderBy(x => x.Key).Select(x => x.Key).ToList();

                            GUILayout.BeginHorizontal(GUI.skin.box);
                            {
                                GUILayout.BeginVertical();
                                {
                                    foreach (int _state in _states)
                                    {
                                        GUILayout.BeginHorizontal();
                                        {
                                            if (_curRenameGroupState == _state)
                                            {
                                                _curRenameStateLabel = GUILayout.TextField(_curRenameStateLabel, GUILayout.Width(65), GUILayout.ExpandWidth(false));
                                                GUILayout.FlexibleSpace();
                                                if (GUILayout.Button(new GUIContent("save", "Save group state label"), _buttonSmall))
                                                {
                                                    if (_curRenameStateLabel.Trim().IsNullOrEmpty() || _curRenameStateLabel != _group.States[_state])
                                                    {
                                                        _pluginCtrl.RenameTriggerGroupState(_curEditGroupKind, _curRenameGroupState, _curRenameStateLabel);
                                                    }
                                                    RefreshCache();
                                                }
                                                if (GUILayout.Button(new GUIContent("back", "Cancel renaming"), _buttonSmall))
                                                {
                                                    _curRenameGroupState = -1;
                                                    _curRenameStateLabel = "";
                                                }
                                            }
                                            else
                                            {
                                                if (GUILayout.Button(new GUIContent(_group.States[_state], "Rename group label"), _label, GUILayout.Width(70), GUILayout.ExpandWidth(false)))
                                                {
                                                    if (_curRenameGroupKind > -1)
                                                    {
                                                        return;
                                                    }
                                                    _curRenameGroupState = _state;
                                                    _curRenameStateLabel = _group.States[_state];
                                                }

                                                GUILayout.FlexibleSpace();

                                                if (_state == _group.Startup)
                                                {
                                                    GUILayout.Button(new GUIContent("■", "This state is set as startup"), _buttonActive, _priorityElem);
                                                }
                                                else
                                                {
                                                    if (GUILayout.Button(new GUIContent(" ", "Set this state as startup"), _buttonActive, _priorityElem))
                                                    {
                                                        _group.Startup = _state;
                                                        RefreshCache();
                                                    }
                                                }

                                                if (_state == _group.Secondary)
                                                {
                                                    if (GUILayout.Button(new GUIContent("■", "Remove secondary setting for this group"), _buttonActive, _priorityElem))
                                                    {
                                                        _group.Secondary = -1;
                                                        RefreshCache();
                                                    }
                                                }
                                                else
                                                {
                                                    if (GUILayout.Button(new GUIContent(" ", "Set this state as secondary (assigned when H start)"), _buttonActive, _priorityElem))
                                                    {
                                                        _group.Secondary = _state;
                                                        RefreshCache();
                                                    }
                                                }

                                                if (GUILayout.Button(new GUIContent("=", "Clone the settings into a new state set"), _priorityElem))
                                                {
                                                    _pluginCtrl.CloneAsNewTriggerGroupState(_currentCoordinateIndex, _group.Kind, _state);
                                                    RefreshCache();
                                                }

                                                if (GUILayout.Button(new GUIContent("X", "Remove the state and accessory settings belong to this state"), _priorityElem))
                                                {
                                                    _pluginCtrl.RemoveTriggerGroupState(_currentCoordinateIndex, _group.Kind, _state);
                                                    RefreshCache();
                                                    if (_state == _group.State)
                                                    {
                                                        _pluginCtrl.ToggleByRefKind(_group.Kind);
                                                    }
                                                }
                                            }
                                        }
                                        GUILayout.EndHorizontal();
                                    }
                                }
                                GUILayout.EndVertical();
                            }
                            GUILayout.EndHorizontal();
                        }
                    }
                }
                GUILayout.EndScrollView();

                GUILayout.BeginHorizontal(GUI.skin.box);
                {
                    GUILayout.Label(new GUIContent("Integrity Check", "Run a full check on current coordinate"), _label);
                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button(new GUIContent("GO", "Check for missing or redundant triggers"), _buttonElem))
                    {
                        _pluginCtrl.MissingKindCheck(_currentCoordinateIndex);
                        _pluginCtrl.MissingPartCheck(_currentCoordinateIndex);
                        _pluginCtrl.MissingGroupCheck(_currentCoordinateIndex);
                        _pluginCtrl.MissingPropertyCheck(_currentCoordinateIndex);
                        RefreshCache();
                        _logger.LogMessage("Integrity check finished");
                    }
                }
                GUILayout.EndHorizontal();
#if DEBUG
                GUILayout.BeginHorizontal(GUI.skin.box);
                {
                    GUILayout.Label("Debug", _label);
                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button("Trigger", GUILayout.Width(65)))
                    {
                        List <TriggerProperty> _data = _pluginCtrl.TriggerPropertyList;
                        string _json = JSONSerializer.Serialize(_data.GetType(), _data, true);
                        _logger.LogInfo("[TriggerPropertyList]\n" + _json);
                    }
                    if (GUILayout.Button("Group", GUILayout.Width(65)))
                    {
                        List <TriggerGroup> _data = _pluginCtrl.TriggerGroupList;
                        string _json = JSONSerializer.Serialize(_data.GetType(), _data, true);
                        _logger.LogInfo("[TriggerGroupList]\n" + _json);
                    }
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal(GUI.skin.box);
                {
                    GUILayout.Label("Export", _label);
                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button("Trigger", GUILayout.Width(65)))
                    {
                        List <TriggerProperty> _data = _pluginCtrl.TriggerPropertyList.Where(x => x.Coordinate == _currentCoordinateIndex).ToList().JsonClone() as List <TriggerProperty>;
                        _data.ForEach(x => x.Coordinate = -1);
                        string _json     = JSONSerializer.Serialize(_data.GetType(), _data, true);
                        string _filePath = Path.Combine(_cfgExportPath.Value, $"ASS_Trigger_{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.json");
                        if (!Directory.Exists(_cfgExportPath.Value))
                        {
                            Directory.CreateDirectory(_cfgExportPath.Value);
                        }
                        File.WriteAllText(_filePath, _json);
                        _logger.LogMessage($"Trigger settings exported to {_filePath}");
                    }
                    if (GUILayout.Button("Group", GUILayout.Width(65)))
                    {
                        List <TriggerGroup> _data = _pluginCtrl.TriggerGroupList.Where(x => x.Coordinate == _currentCoordinateIndex).ToList().JsonClone() as List <TriggerGroup>;
                        _data.ForEach(x => x.Coordinate = -1);
                        string _json     = JSONSerializer.Serialize(_data.GetType(), _data, true);
                        string _filePath = Path.Combine(_cfgExportPath.Value, $"ASS_Group_{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.json");
                        if (!Directory.Exists(_cfgExportPath.Value))
                        {
                            Directory.CreateDirectory(_cfgExportPath.Value);
                        }
                        File.WriteAllText(_filePath, _json);
                        _logger.LogMessage($"Group settings exported to {_filePath}");
                    }
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal(GUI.skin.box);
                {
                    GUILayout.Label("Import", _label);
                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button("Trigger", GUILayout.Width(65)))
                    {
                        const string _fileExt    = ".json";
                        const string _fileFilter = "Exported Setting (*.json)|*.json|All files|*.*";
                        OpenFileDialog.Show(_string => OnFileAccept(_string, "Trigger"), "Open Exported Setting", CharaMaker._savePath, _fileFilter, _fileExt);
                    }
                    if (GUILayout.Button("Group", GUILayout.Width(65)))
                    {
                        const string _fileExt    = ".json";
                        const string _fileFilter = "Exported Setting (*.json)|*.json|All files|*.*";
                        OpenFileDialog.Show(_string => OnFileAccept(_string, "Group"), "Open Exported Setting", CharaMaker._savePath, _fileFilter, _fileExt);
                    }
                }
                GUILayout.EndHorizontal();
#endif
            }
        private void SetupTexControls(RegisterCustomControlsEvent e, MakerCategory makerCategory, BaseUnityPlugin owner, string clothesId, string title = "Overlay textures", bool addSeparator = false)
        {
            var texType = "overlay texture";

            var controlSeparator = addSeparator ? e.AddControl(new MakerSeparator(makerCategory, owner)) : null;

            var controlTitle = e.AddControl(new MakerText(title, makerCategory, owner));

            var controlGen = e.AddControl(new MakerButton("Dump original texture", makerCategory, owner));

            controlGen.OnClick.AddListener(() => GetOverlayController().DumpBaseTexture(clothesId, KoiSkinOverlayGui.WriteAndOpenPng));

            var controlImage = e.AddControl(new MakerImage(null, makerCategory, owner)
            {
                Height = 150, Width = 150
            });

            var controlOverride = e.AddControl(new MakerToggle(makerCategory, "Hide base texture", owner));

            controlOverride.ValueChanged.Subscribe(
                b =>
            {
                var c = GetOverlayController();
                if (c != null)
                {
                    var tex = c.GetOverlayTex(clothesId, true);
                    if (tex.Override != b)
                    {
                        tex.Override = b;
                        c.RefreshTexture(clothesId);
                    }
                }
            });

            var controlLoad = e.AddControl(new MakerButton("Load new " + texType, makerCategory, owner));

            controlLoad.OnClick.AddListener(
                () => OpenFileDialog.Show(
                    strings => OnFileAccept(strings, clothesId),
                    "Open overlay image",
                    KoiSkinOverlayGui.GetDefaultLoadDir(),
                    KoiSkinOverlayGui.FileFilter,
                    KoiSkinOverlayGui.FileExt));

            var controlClear = e.AddControl(new MakerButton("Clear " + texType, makerCategory, owner));

            controlClear.OnClick.AddListener(() => SetTexAndUpdate(null, clothesId));

            var controlExport = e.AddControl(new MakerButton("Export " + texType, makerCategory, owner));

            controlExport.OnClick.AddListener(
                () =>
            {
                try
                {
                    var tex = GetOverlayController().GetOverlayTex(clothesId, false)?.TextureBytes;
                    if (tex == null)
                    {
                        Logger.LogMessage("Nothing to export");
                        return;
                    }

                    KoiSkinOverlayGui.WriteAndOpenPng(tex);
                }
                catch (Exception ex)
                {
                    Logger.LogMessage("Failed to export texture - " + ex.Message);
                }
            });

            // Refresh logic -----------------------

            _textureChanged.Subscribe(
                d =>
            {
                if (Equals(clothesId, d.Key))
                {
                    controlImage.Texture = d.Value;
                    if (controlOverride != null)
                    {
                        controlOverride.Value = GetOverlayController().GetOverlayTex(d.Key, false)?.Override ?? false;
                    }
                }
            });

            _refreshInterface.Subscribe(
                cat =>
            {
                if (cat != null && cat != clothesId)
                {
                    return;
                }
                if (!controlImage.Exists)
                {
                    return;
                }

                var ctrl = GetOverlayController();

                var renderer = ctrl?.GetApplicableRenderers(clothesId)?.FirstOrDefault();
                var visible  = renderer?.material?.mainTexture != null;

                controlTitle.Visible.OnNext(visible);
                controlGen.Visible.OnNext(visible);
                controlImage.Visible.OnNext(visible);
                controlOverride?.Visible.OnNext(visible);
                controlLoad.Visible.OnNext(visible);
                controlClear.Visible.OnNext(visible);
                controlExport.Visible.OnNext(visible);
                controlSeparator?.Visible.OnNext(visible);

                _textureChanged.OnNext(new KeyValuePair <string, Texture2D>(clothesId, ctrl?.GetOverlayTex(clothesId, false)?.Texture));
            }
                );
        }
Пример #17
0
        /// <summary>
        /// Populate the MaterialEditor UI
        /// </summary>
        /// <param name="go">GameObject for which to read the renderers and materials</param>
        /// <param name="slot">Slot of the clothing (0=tops, 1=bottoms, etc.), the hair (0=back, 1=front, etc.), or of the accessory, or ID of the Studio item. Ignored for other object types.</param>
        /// <param name="filter">Comma separated list of text to filter the results</param>
        protected void PopulateList(GameObject go, int slot = 0, string filter = "")
        {
            MaterialEditorWindow.gameObject.SetActive(true);
            MaterialEditorWindow.GetComponent <CanvasScaler>().referenceResolution = new Vector2(1920f / UIScale.Value, 1080f / UIScale.Value);
            MaterialEditorMainPanel.transform.SetRect(0.05f, 0.05f, UIWidth.Value * UIScale.Value, UIHeight.Value * UIScale.Value);
            FilterInputField.Set(filter);

            CurrentGameObject = go;
            CurrentSlot       = slot;
            CurrentFilter     = filter;

            if (go == null)
            {
                return;
            }

            List <Renderer> rendList              = new List <Renderer>();
            List <Renderer> rendListFull          = GetRendererList(go);
            List <string>   filterList            = new List <string>();
            List <ItemInfo> items                 = new List <ItemInfo>();
            Dictionary <string, Material> matList = new Dictionary <string, Material>();

            if (!filter.IsNullOrEmpty())
            {
                filterList = filter.Split(',').ToList();
            }
            filterList.RemoveAll(x => x.IsNullOrWhiteSpace());

            //Get all renderers and materials matching the filter
            if (filterList.Count == 0)
            {
                rendList = rendListFull;
            }
            else
            {
                for (var i = 0; i < rendListFull.Count; i++)
                {
                    var rend = rendListFull[i];
                    for (var j = 0; j < filterList.Count; j++)
                    {
                        var filterWord = filterList[j];
                        if (rend.NameFormatted().ToLower().Contains(filterWord.Trim().ToLower()) && !rendList.Contains(rend))
                        {
                            rendList.Add(rend);
                        }
                    }

                    var mats = GetMaterials(rend);
                    for (var j = 0; j < mats.Count; j++)
                    {
                        var mat = mats[j];
                        for (var k = 0; k < filterList.Count; k++)
                        {
                            var filterWord = filterList[k];
                            if (mat.NameFormatted().ToLower().Contains(filterWord.Trim().ToLower()))
                            {
                                matList[mat.NameFormatted()] = mat;
                            }
                        }
                    }
                }
            }

            for (var i = 0; i < rendList.Count; i++)
            {
                var rend = rendList[i];
                //Get materials if materials list wasn't previously built by the filter
                if (filterList.Count == 0)
                {
                    foreach (var mat in GetMaterials(rend))
                    {
                        matList[mat.NameFormatted()] = mat;
                    }
                }

                var rendererItem = new ItemInfo(ItemInfo.RowItemType.Renderer, "Renderer");
                rendererItem.RendererName     = rend.NameFormatted();
                rendererItem.ExportUVOnClick  = () => Export.ExportUVMaps(rend);
                rendererItem.ExportObjOnClick = () => Export.ExportObj(rend);
                items.Add(rendererItem);

                //Renderer Enabled
                bool valueEnabledOriginal = rend.enabled;
                var  temp = GetRendererPropertyValueOriginal(slot, rend, RendererProperties.Enabled, go);
                if (!temp.IsNullOrEmpty())
                {
                    valueEnabledOriginal = temp == "1";
                }
                var rendererEnabledItem = new ItemInfo(ItemInfo.RowItemType.RendererEnabled, "Enabled");
                rendererEnabledItem.RendererEnabled         = rend.enabled ? 1 : 0;
                rendererEnabledItem.RendererEnabledOriginal = valueEnabledOriginal ? 1 : 0;
                rendererEnabledItem.RendererEnabledOnChange = value => SetRendererProperty(slot, rend, RendererProperties.Enabled, value.ToString(), go);
                rendererEnabledItem.RendererEnabledOnReset  = () => RemoveRendererProperty(slot, rend, RendererProperties.Enabled, go);
                items.Add(rendererEnabledItem);

                //Renderer ShadowCastingMode
                var valueShadowCastingModeOriginal = rend.shadowCastingMode;
                temp = GetRendererPropertyValueOriginal(slot, rend, RendererProperties.ShadowCastingMode, go);
                if (!temp.IsNullOrEmpty())
                {
                    valueShadowCastingModeOriginal = (UnityEngine.Rendering.ShadowCastingMode) int.Parse(temp);
                }
                var rendererShadowCastingModeItem = new ItemInfo(ItemInfo.RowItemType.RendererShadowCastingMode, "Shadow Casting Mode");
                rendererShadowCastingModeItem.RendererShadowCastingMode         = (int)rend.shadowCastingMode;
                rendererShadowCastingModeItem.RendererShadowCastingModeOriginal = (int)valueShadowCastingModeOriginal;
                rendererShadowCastingModeItem.RendererShadowCastingModeOnChange = value => SetRendererProperty(slot, rend, RendererProperties.ShadowCastingMode, value.ToString(), go);
                rendererShadowCastingModeItem.RendererShadowCastingModeOnReset  = () => RemoveRendererProperty(slot, rend, RendererProperties.ShadowCastingMode, go);
                items.Add(rendererShadowCastingModeItem);

                //Renderer ReceiveShadows
                bool valueReceiveShadowsOriginal = rend.receiveShadows;
                temp = GetRendererPropertyValueOriginal(slot, rend, RendererProperties.ShadowCastingMode, go);
                if (!temp.IsNullOrEmpty())
                {
                    valueReceiveShadowsOriginal = temp == "1";
                }
                var rendererReceiveShadowsItem = new ItemInfo(ItemInfo.RowItemType.RendererReceiveShadows, "Receive Shadows");
                rendererReceiveShadowsItem.RendererReceiveShadows         = rend.receiveShadows ? 1 : 0;
                rendererReceiveShadowsItem.RendererReceiveShadowsOriginal = valueReceiveShadowsOriginal ? 1 : 0;
                rendererReceiveShadowsItem.RendererReceiveShadowsOnChange = value => SetRendererProperty(slot, rend, RendererProperties.ReceiveShadows, value.ToString(), go);
                rendererReceiveShadowsItem.RendererReceiveShadowsOnReset  = () => RemoveRendererProperty(slot, rend, RendererProperties.ReceiveShadows, go);
                items.Add(rendererReceiveShadowsItem);
            }

            foreach (var mat in matList.Values)
            {
                string materialName = mat.NameFormatted();
                string shaderName   = mat.shader.NameFormatted();

                var materialItem = new ItemInfo(ItemInfo.RowItemType.Material, "Material");
                materialItem.MaterialName    = materialName;
                materialItem.MaterialOnCopy  = () => MaterialCopyEdits(slot, mat, go);
                materialItem.MaterialOnPaste = () =>
                {
                    MaterialPasteEdits(slot, mat, go);
                    PopulateList(go, slot, filter);
                };
                //materialItem.MaterialOnCopyRemove = () =>
                //{
                //    CopyMaterial(gameObject, materialName);
                //    PopulateList(gameObject, slot, filter);
                //};
                items.Add(materialItem);

                //Shader
                string shaderNameOriginal = shaderName;
                var    temp = GetMaterialShaderNameOriginal(slot, mat, go);
                if (!temp.IsNullOrEmpty())
                {
                    shaderNameOriginal = temp;
                }
                var shaderItem = new ItemInfo(ItemInfo.RowItemType.Shader, "Shader");
                shaderItem.ShaderName         = shaderName;
                shaderItem.ShaderNameOriginal = shaderNameOriginal;
                shaderItem.ShaderNameOnChange = value =>
                {
                    SetMaterialShaderName(slot, mat, value, go);
                    StartCoroutine(PopulateListCoroutine(go, slot, filter));
                };
                shaderItem.ShaderNameOnReset = () =>
                {
                    RemoveMaterialShaderName(slot, mat, go);
                    StartCoroutine(PopulateListCoroutine(go, slot, filter));
                };
                items.Add(shaderItem);

                //Shader RenderQueue
                int renderQueueOriginal     = mat.renderQueue;
                int?renderQueueOriginalTemp = GetMaterialShaderRenderQueueOriginal(slot, mat, go);
                renderQueueOriginal = renderQueueOriginalTemp ?? renderQueueOriginal;
                var shaderRenderQueueItem = new ItemInfo(ItemInfo.RowItemType.ShaderRenderQueue, "Render Queue");
                shaderRenderQueueItem.ShaderRenderQueue         = mat.renderQueue;
                shaderRenderQueueItem.ShaderRenderQueueOriginal = renderQueueOriginal;
                shaderRenderQueueItem.ShaderRenderQueueOnChange = value => SetMaterialShaderRenderQueue(slot, mat, value, go);
                shaderRenderQueueItem.ShaderRenderQueueOnReset  = () => RemoveMaterialShaderRenderQueue(slot, mat, go);
                items.Add(shaderRenderQueueItem);

                foreach (var property in XMLShaderProperties[XMLShaderProperties.ContainsKey(shaderName) ? shaderName : "default"].OrderBy(x => x.Value.Type).ThenBy(x => x.Key))
                {
                    string propertyName = property.Key;
                    if (CheckBlacklist(materialName, propertyName))
                    {
                        continue;
                    }

                    if (property.Value.Type == ShaderPropertyType.Texture)
                    {
                        if (mat.HasProperty($"_{propertyName}"))
                        {
                            var textureItem = new ItemInfo(ItemInfo.RowItemType.TextureProperty, propertyName);
                            textureItem.TextureChanged  = !GetMaterialTextureValueOriginal(slot, mat, propertyName, go);
                            textureItem.TextureExists   = mat.GetTexture($"_{propertyName}") != null;
                            textureItem.TextureOnExport = () => ExportTexture(mat, propertyName);
                            textureItem.TextureOnImport = () =>
                            {
                                OpenFileDialog.Show(OnFileAccept, "Open image", Application.dataPath, FileFilter, FileExt);

                                void OnFileAccept(string[] strings)
                                {
                                    if (strings == null || strings.Length == 0 || strings[0].IsNullOrEmpty())
                                    {
                                        textureItem.TextureChanged = !GetMaterialTextureValueOriginal(slot, mat, propertyName, go);
                                        textureItem.TextureExists  = mat.GetTexture($"_{propertyName}") != null;
                                        return;
                                    }
                                    string filePath = strings[0];

                                    SetMaterialTexture(slot, mat, propertyName, filePath, go);

                                    TexChangeWatcher?.Dispose();
                                    if (WatchTexChanges.Value)
                                    {
                                        var directory = Path.GetDirectoryName(filePath);
                                        if (directory != null)
                                        {
                                            TexChangeWatcher          = new FileSystemWatcher(directory, Path.GetFileName(filePath));
                                            TexChangeWatcher.Changed += (sender, args) =>
                                            {
                                                if (WatchTexChanges.Value && File.Exists(filePath))
                                                {
                                                    SetMaterialTexture(slot, mat, propertyName, filePath, go);
                                                }
                                            };
                                            TexChangeWatcher.Deleted            += (sender, args) => TexChangeWatcher?.Dispose();
                                            TexChangeWatcher.Error              += (sender, args) => TexChangeWatcher?.Dispose();
                                            TexChangeWatcher.EnableRaisingEvents = true;
                                        }
                                    }
                                }
                            };
                            textureItem.TextureOnReset = () => RemoveMaterialTexture(slot, mat, propertyName, go);
                            items.Add(textureItem);

                            Vector2 textureOffset             = mat.GetTextureOffset($"_{propertyName}");
                            Vector2 textureOffsetOriginal     = textureOffset;
                            Vector2?textureOffsetOriginalTemp = GetMaterialTextureOffsetOriginal(slot, mat, propertyName, go);
                            if (textureOffsetOriginalTemp != null)
                            {
                                textureOffsetOriginal = (Vector2)textureOffsetOriginalTemp;
                            }

                            Vector2 textureScale             = mat.GetTextureScale($"_{propertyName}");
                            Vector2 textureScaleOriginal     = textureScale;
                            Vector2?textureScaleOriginalTemp = GetMaterialTextureScaleOriginal(slot, mat, propertyName, go);
                            if (textureScaleOriginalTemp != null)
                            {
                                textureScaleOriginal = (Vector2)textureScaleOriginalTemp;
                            }

                            var textureItemOffsetScale = new ItemInfo(ItemInfo.RowItemType.TextureOffsetScale);
                            textureItemOffsetScale.Offset         = textureOffset;
                            textureItemOffsetScale.OffsetOriginal = textureOffsetOriginal;
                            textureItemOffsetScale.OffsetOnChange = value => SetMaterialTextureOffset(slot, mat, propertyName, value, go);
                            textureItemOffsetScale.OffsetOnReset  = () => RemoveMaterialTextureOffset(slot, mat, propertyName, go);
                            textureItemOffsetScale.Scale          = textureScale;
                            textureItemOffsetScale.ScaleOriginal  = textureScaleOriginal;
                            textureItemOffsetScale.ScaleOnChange  = value => SetMaterialTextureScale(slot, mat, propertyName, value, go);
                            textureItemOffsetScale.ScaleOnReset   = () => RemoveMaterialTextureScale(slot, mat, propertyName, go);
                            items.Add(textureItemOffsetScale);
                        }
                    }
                    else if (property.Value.Type == ShaderPropertyType.Color)
                    {
                        if (mat.HasProperty($"_{propertyName}"))
                        {
                            Color valueColor         = mat.GetColor($"_{propertyName}");
                            Color valueColorOriginal = valueColor;
                            Color?c = GetMaterialColorPropertyValueOriginal(slot, mat, propertyName, go);
                            if (c != null)
                            {
                                valueColorOriginal = (Color)c;
                            }
                            var contentItem = new ItemInfo(ItemInfo.RowItemType.ColorProperty, propertyName);
                            contentItem.ColorValue         = valueColor;
                            contentItem.ColorValueOriginal = valueColorOriginal;
                            contentItem.ColorValueOnChange = value => SetMaterialColorProperty(slot, mat, propertyName, value, go);
                            contentItem.ColorValueOnReset  = () => RemoveMaterialColorProperty(slot, mat, propertyName, go);
                            items.Add(contentItem);
                        }
                    }
                    else if (property.Value.Type == ShaderPropertyType.Float)
                    {
                        if (mat.HasProperty($"_{propertyName}"))
                        {
                            float valueFloat             = mat.GetFloat($"_{propertyName}");
                            float valueFloatOriginal     = valueFloat;
                            float?valueFloatOriginalTemp = GetMaterialFloatPropertyValueOriginal(slot, mat, propertyName, go);
                            if (valueFloatOriginalTemp != null)
                            {
                                valueFloatOriginal = (float)valueFloatOriginalTemp;
                            }
                            var contentItem = new ItemInfo(ItemInfo.RowItemType.FloatProperty, propertyName);
                            contentItem.FloatValue         = valueFloat;
                            contentItem.FloatValueOriginal = valueFloatOriginal;
                            if (property.Value.MinValue != null)
                            {
                                contentItem.FloatValueSliderMin = (float)property.Value.MinValue;
                            }
                            if (property.Value.MaxValue != null)
                            {
                                contentItem.FloatValueSliderMax = (float)property.Value.MaxValue;
                            }
                            contentItem.FloatValueOnChange = value => SetMaterialFloatProperty(slot, mat, propertyName, value, go);
                            contentItem.FloatValueOnReset  = () => RemoveMaterialFloatProperty(slot, mat, propertyName, go);
                            items.Add(contentItem);
                        }
                    }
                }
            }

            virtualList.SetList(items);
        }
Пример #18
0
 public static void Main()
 {
     OpenFileDialog.Show();
     Console.WriteLine("MainFile");
     SomeFile someFile = new SomeFile();
 }
        private void SetupTexControls(RegisterCustomControlsEvent e, MakerCategory makerCategory, BaseUnityPlugin owner, TexType texType, string title)
        {
            var radButtons = texType == TexType.EyeOver || texType == TexType.EyeUnder ?
                             e.AddControl(new MakerRadioButtons(makerCategory, owner, "Eye to edit", "Both", "Left", "Right")) :
                             null;

            TexType GetTexType(bool cantBeBoth)
            {
                if (radButtons != null)
                {
                    if (radButtons.Value == 0)
                    {
                        return(cantBeBoth ? texType + 2 : texType); // left or both
                    }
                    if (radButtons.Value == 1)
                    {
                        return(texType + 2); // left
                    }
                    if (radButtons.Value == 2)
                    {
                        return(texType + 4); // right
                    }
                }
                return(texType);
            }

            e.AddControl(new MakerText(title, makerCategory, owner));

            var forceAllowBoth = false;
            var bi             = e.AddControl(new MakerImage(null, makerCategory, owner)
            {
                Height = 150, Width = 150
            });

            _textureChanged.Subscribe(
                d =>
            {
                var incomingType = d.Key;
                if (!forceAllowBoth)
                {
                    // If left and right images are different, and we have Both selected, change selection to Left instead
                    var currentType = GetTexType(false);
                    if (radButtons != null && (currentType == TexType.EyeOver && incomingType == TexType.EyeOverR || currentType == TexType.EyeUnder && incomingType == TexType.EyeUnderR))
                    {
                        var leftTex = GetTex(GetTexType(true));
                        if (d.Value != leftTex)
                        {
                            radButtons.Value = 1;
                        }
                        else
                        {
                            radButtons.Value = 0;
                        }
                    }
                }

                if (incomingType == GetTexType(true) || incomingType == GetTexType(false))
                {
                    bi.Texture = d.Value;
                }
            });

            e.AddControl(new MakerButton("Load new texture", makerCategory, owner))
            .OnClick.AddListener(
                () => OpenFileDialog.Show(strings => OnFileAccept(strings, GetTexType(false)), "Open overlay image", GetDefaultLoadDir(), FileFilter, FileExt));

            e.AddControl(new MakerButton("Clear texture", makerCategory, owner))
            .OnClick.AddListener(() => SetTexAndUpdate(null, GetTexType(false)));

            e.AddControl(new MakerButton("Export current texture", makerCategory, owner))
            .OnClick.AddListener(
                () =>
            {
                try
                {
                    var tex = GetTex(GetTexType(true));
                    if (tex == null)
                    {
                        return;
                    }
                    WriteAndOpenPng(tex.EncodeToPNG(), GetTexType(false).ToString());
                }
                catch (Exception ex)
                {
                    Logger.LogMessage("Failed to export texture - " + ex.Message);
                }
            });

            radButtons?.ValueChanged.Subscribe(i =>
            {
                forceAllowBoth = true;
                var safeType   = GetTexType(true);
                _textureChanged.OnNext(new KeyValuePair <TexType, Texture2D>(safeType, GetTex(safeType)));
                forceAllowBoth = false;
            });

            Texture2D GetTex(TexType type)
            {
                var ctrl           = GetOverlayController();
                var overlayTexture = ctrl.OverlayStorage.GetTexture(type);

                return(overlayTexture);
            }
        }
Пример #20
0
        public TilesetEditor(IContainer Parent) : base(Parent)
        {
            Submodes = new SubmodeView(this);
            Submodes.SetHeaderHeight(31);
            Submodes.SetHeaderWidth(96);
            Submodes.SetHeaderSelHeight(1);
            Submodes.SetTextY(6);

            PassageContainer = Submodes.CreateTab("Passage");
            VignetteFade PassageFade = new VignetteFade(PassageContainer);

            PassageContainer.OnSizeChanged += delegate(BaseEventArgs e) { PassageFade.SetSize(PassageContainer.Size); };

            FourDirContainer = Submodes.CreateTab("4-Dir");
            VignetteFade FourDirFade = new VignetteFade(FourDirContainer);

            FourDirContainer.OnSizeChanged += delegate(BaseEventArgs e) { FourDirFade.SetSize(FourDirContainer.Size); };

            //PriorityContainer = Submodes.CreateTab("Priority");
            //VignetteFade PriorityFade = new VignetteFade(PriorityContainer);
            //PriorityContainer.OnSizeChanged += delegate (BaseEventArgs e) { PriorityFade.SetSize(PriorityContainer.Size); };

            //Submodes.CreateTab("Terrain Tag");
            //Submodes.CreateTab("Bush Flag");
            //Submodes.CreateTab("Counter Flag");

            Container PassageSubContainer = new Container(PassageContainer);

            PassageList = new TilesetDisplay(PassageSubContainer);
            PassageList.OnTilesetLoaded += delegate(BaseEventArgs e) { PassageDrawAll(); };
            PassageList.OnTileClicked   += delegate(MouseEventArgs e) { PassageInput(e); };

            Container FourDirSubContainer = new Container(FourDirContainer);

            FourDirList = new TilesetDisplay(FourDirSubContainer);
            FourDirList.OnTilesetLoaded += delegate(BaseEventArgs e) { FourDirDrawAll(); };
            FourDirList.OnTileClicked   += delegate(MouseEventArgs e) { FourDirInput(e); };

            PassageContainer.SetBackgroundColor(28, 50, 73);
            FourDirContainer.SetBackgroundColor(28, 50, 73);
            //PriorityContainer.SetBackgroundColor(28, 50, 73);

            SharedContainer = new Container(this);
            SharedContainer.SetPosition(22, 41);
            SharedContainer.Sprites["bg"] = new Sprite(SharedContainer.Viewport);
            SimpleFade fade = new SimpleFade(SharedContainer);

            fade.SetPosition(4, 4);
            NameLabel = new Label(SharedContainer);
            NameLabel.SetText("Name");
            NameLabel.SetFont(Font.Get("Fonts/Ubuntu-B", 14));
            NameLabel.SetPosition(19, 16);
            NameBox = new TextBox(SharedContainer);
            NameBox.SetPosition(19, 40);
            NameBox.SetSize(156, 21);
            NameBox.SetSkin(1);
            // Updates tileset list
            NameBox.OnTextChanged += delegate(BaseEventArgs e)
            {
                if (this.Tileset == null)
                {
                    return;
                }
                this.Tileset.Name = NameBox.Text;
                ListItem item = DBDataList.DataList.Items[TilesetID - 1];
                item.Name = item.Name.Split(':')[0] + ": " + this.Tileset.Name;
                DBDataList.DataList.Redraw();
            };

            GraphicLabel = new Label(SharedContainer);
            GraphicLabel.SetFont(Font.Get("Fonts/Ubuntu-B", 14));
            GraphicLabel.SetPosition(19, 79);
            GraphicLabel.SetText("Tileset Graphic");

            GraphicBox = new BrowserBox(SharedContainer);
            GraphicBox.SetPosition(19, 103);
            GraphicBox.SetSize(156, 21);
            GraphicBox.OnDropDownClicked += delegate(BaseEventArgs e)
            {
                OpenFileDialog of = new OpenFileDialog();
                of.SetFilter(new FileFilter("PNG Image", "png"));
                of.SetInitialDirectory(Game.Data.ProjectPath + "/gfx/tilesets");
                of.SetTitle("Pick a tileset...");
                object result = of.Show();
                if (result != null)
                {
                    // Converts path (C:/.../.../tileset_image.png) to filename (tileset_image)
                    string path = result as string;
                    while (path.Contains('\\'))
                    {
                        path = path.Replace('\\', '/');
                    }
                    string[] folders  = path.Split('/');
                    string   file_ext = folders[folders.Length - 1];
                    string[] dots     = file_ext.Split('.');
                    string   file     = "";
                    for (int i = 0; i < dots.Length - 1; i++)
                    {
                        file += dots[i];
                        if (i != dots.Length - 2)
                        {
                            file += '.';
                        }
                    }
                    string tilesetsfolder = Game.Data.ProjectPath + "/gfx/tilesets";
                    // Selected file not in the tilesets folder
                    // Copies source to tilesets folder
                    string chosenparent = System.IO.Directory.GetParent(path).FullName;
                    while (chosenparent.Contains('\\'))
                    {
                        chosenparent = chosenparent.Replace('\\', '/');
                    }
                    if (chosenparent != tilesetsfolder)
                    {
                        MessageBox box = new MessageBox("Error",
                                                        "The selected file doesn't exist in the gfx/tilesets folder. Would you like to copy it in?", ButtonType.YesNo);
                        box.OnButtonPressed += delegate(BaseEventArgs e)
                        {
                            if (box.Result == 0) // Yes
                            {
                                string newfilename = null;
                                if (System.IO.File.Exists(tilesetsfolder + "/" + file_ext))
                                {
                                    int iterator = 1;
                                    while (string.IsNullOrEmpty(newfilename))
                                    {
                                        if (!System.IO.File.Exists(tilesetsfolder + "/" + file + " (" + iterator.ToString() + ")." + dots[dots.Length - 1]))
                                        {
                                            newfilename = tilesetsfolder + "/" + file + " (" + iterator.ToString() + ")." + dots[dots.Length - 1];
                                            file        = file + " (" + iterator.ToString() + ")";
                                        }
                                        iterator++;
                                    }
                                }
                                else
                                {
                                    newfilename = tilesetsfolder + "/" + file_ext;
                                }
                                System.IO.File.Copy(path, newfilename);
                                SetTilesetGraphic(file);
                            }
                        };
                    }
                    // File is in tilesets folder
                    else
                    {
                        SetTilesetGraphic(file);
                    }
                }
            };
            // Updates graphic if typed
            GraphicBox.TextArea.OnWidgetDeselected += delegate(BaseEventArgs e)
            {
                string file = GraphicBox.Text;
                if (!System.IO.File.Exists(Game.Data.ProjectPath + "/gfx/tilesets/" + file + ".png"))
                {
                    new MessageBox("Error", "No tileset with the name '" + file + "' exists in gfx/tilesets.", IconType.Error);
                }
                else
                {
                    SetTilesetGraphic(file);
                }
            };

            ClearTilesetButton = new Button(SharedContainer);
            ClearTilesetButton.SetPosition(25, 150);
            ClearTilesetButton.SetSize(140, 44);
            ClearTilesetButton.SetFont(Font.Get("Fonts/Ubuntu-B", 16));
            ClearTilesetButton.SetText("Clear Tileset");
            ClearTilesetButton.OnClicked += delegate(BaseEventArgs e)
            {
                ConfirmClearTileset();
            };

            Submodes.SelectTab(1);
        }
Пример #21
0
 private void GetCard(string key) => OpenFileDialog.Show(path => OnCardAccept(key, path), "Select replacement card", GetDir(), Filter, FileExtension, OpenFileDialog.OpenSaveFileDialgueFlags.OFN_FILEMUSTEXIST);
Пример #22
0
        protected void PopulateList(GameObject gameObject, ObjectType objectType, int coordinateIndex = 0, int slot = 0, FilterType filterType = FilterType.All)
        {
            MaterialEditorWindow.gameObject.SetActive(true);
            MaterialEditorWindow.GetComponent <CanvasScaler>().referenceResolution = new Vector2(1920f / UIScale.Value, 1080f / UIScale.Value);
            MaterialEditorMainPanel.transform.SetRect(0.05f, 0.05f, UIWidth.Value * UIScale.Value, UIHeight.Value * UIScale.Value);

            if (gameObject == null)
            {
                return;
            }
            if (objectType == ObjectType.Hair || objectType == ObjectType.Character)
            {
                coordinateIndex = 0;
            }

            List <Renderer> rendList = new List <Renderer>();
            List <string>   mats     = new List <string>();

            Dictionary <string, Material> matList = new Dictionary <string, Material>();

            var chaControl = gameObject.GetComponent <ChaControl>();

            if (chaControl == null)
            {
                rendList   = GetRendererList(gameObject);
                filterType = FilterType.All;
            }
            else
            {
                if (filterType == FilterType.Body)
                {
                    matList[chaControl.customMatBody.NameFormatted()] = chaControl.customMatBody;
                    rendList.Add(chaControl.rendBody);
                }
                else if (filterType == FilterType.Face)
                {
                    matList[chaControl.customMatFace.NameFormatted()] = chaControl.customMatFace;
                    rendList.Add(chaControl.rendFace);
                }
                else
                {
                    rendList = GetRendererList(gameObject);
                }
            }
            List <ItemInfo> items = new List <ItemInfo>();

            foreach (var rend in rendList)
            {
                foreach (var mat in rend.sharedMaterials)
                {
                    matList[mat.NameFormatted()] = mat;
                }

                var rendererItem = new ItemInfo(ItemInfo.RowItemType.Renderer, "Renderer");
                rendererItem.RendererName = rend.NameFormatted();
                items.Add(rendererItem);

                //Renderer Enabled
                bool valueEnabledOriginal = rend.enabled;
                var  temp = GetRendererPropertyValueOriginal(objectType, coordinateIndex, slot, rend.NameFormatted(), RendererProperties.Enabled);
                if (!temp.IsNullOrEmpty())
                {
                    valueEnabledOriginal = temp == "1";
                }
                var rendererEnabledItem = new ItemInfo(ItemInfo.RowItemType.RendererEnabled, "Enabled");
                rendererEnabledItem.RendererEnabled         = rend.enabled ? 1 : 0;
                rendererEnabledItem.RendererEnabledOriginal = valueEnabledOriginal ? 1 : 0;
                rendererEnabledItem.RendererEnabledOnChange = delegate(int value) { AddRendererProperty(objectType, coordinateIndex, slot, rend.NameFormatted(), RendererProperties.Enabled, value.ToString(), valueEnabledOriginal ? "1" : "0", gameObject); };
                rendererEnabledItem.RendererEnabledOnReset  = delegate { RemoveRendererProperty(objectType, coordinateIndex, slot, rend.NameFormatted(), RendererProperties.Enabled, gameObject); };
                items.Add(rendererEnabledItem);

                //Renderer ShadowCastingMode
                var valueShadowCastingModeOriginal = rend.shadowCastingMode;
                temp = GetRendererPropertyValueOriginal(objectType, coordinateIndex, slot, rend.NameFormatted(), RendererProperties.ShadowCastingMode);
                if (!temp.IsNullOrEmpty())
                {
                    valueShadowCastingModeOriginal = (UnityEngine.Rendering.ShadowCastingMode) int.Parse(temp);
                }
                var rendererShadowCastingModeItem = new ItemInfo(ItemInfo.RowItemType.RendererShadowCastingMode, "Shadow Casting Mode");
                rendererShadowCastingModeItem.RendererShadowCastingMode         = (int)rend.shadowCastingMode;
                rendererShadowCastingModeItem.RendererShadowCastingModeOriginal = (int)valueShadowCastingModeOriginal;
                rendererShadowCastingModeItem.RendererShadowCastingModeOnChange = delegate(int value) { AddRendererProperty(objectType, coordinateIndex, slot, rend.NameFormatted(), RendererProperties.ShadowCastingMode, value.ToString(), ((int)valueShadowCastingModeOriginal).ToString(), gameObject); };
                rendererShadowCastingModeItem.RendererShadowCastingModeOnReset  = delegate { RemoveRendererProperty(objectType, coordinateIndex, slot, rend.NameFormatted(), RendererProperties.ShadowCastingMode, gameObject); };
                items.Add(rendererShadowCastingModeItem);

                //Renderer ReceiveShadows
                bool valueReceiveShadowsOriginal = rend.receiveShadows;
                temp = GetRendererPropertyValueOriginal(objectType, coordinateIndex, slot, rend.NameFormatted(), RendererProperties.ShadowCastingMode);
                if (!temp.IsNullOrEmpty())
                {
                    valueReceiveShadowsOriginal = temp == "1";
                }
                var rendererReceiveShadowsItem = new ItemInfo(ItemInfo.RowItemType.RendererReceiveShadows, "Receive Shadows");
                rendererReceiveShadowsItem.RendererReceiveShadows         = rend.receiveShadows ? 1 : 0;
                rendererReceiveShadowsItem.RendererReceiveShadowsOriginal = valueReceiveShadowsOriginal ? 1 : 0;
                rendererReceiveShadowsItem.RendererReceiveShadowsOnChange = delegate(int value) { AddRendererProperty(objectType, coordinateIndex, slot, rend.NameFormatted(), RendererProperties.ReceiveShadows, value.ToString(), valueReceiveShadowsOriginal ? "1" : "0", gameObject); };
                rendererReceiveShadowsItem.RendererReceiveShadowsOnReset  = delegate { RemoveRendererProperty(objectType, coordinateIndex, slot, rend.NameFormatted(), RendererProperties.ReceiveShadows, gameObject); };
                items.Add(rendererReceiveShadowsItem);
            }

            foreach (var mat in matList.Values)
            {
                string materialName = mat.NameFormatted();
                string shaderName   = mat.shader.NameFormatted();

                var materialItem = new ItemInfo(ItemInfo.RowItemType.Material, "Material");
                materialItem.MaterialName = materialName;
                items.Add(materialItem);

                //Shader
                string shaderNameOriginal = shaderName;
                var    temp = GetMaterialShaderNameOriginal(objectType, coordinateIndex, slot, materialName);
                if (!temp.IsNullOrEmpty())
                {
                    shaderNameOriginal = temp;
                }
                var shaderItem = new ItemInfo(ItemInfo.RowItemType.Shader, "Shader");
                shaderItem.ShaderName         = shaderName;
                shaderItem.ShaderNameOriginal = shaderNameOriginal;
                shaderItem.ShaderNameOnChange = delegate(string value)
                {
                    AddMaterialShaderName(objectType, coordinateIndex, slot, materialName, value, shaderNameOriginal, gameObject);
                    StartCoroutine(PopulateListCoroutine(gameObject, objectType, coordinateIndex, slot, filterType: filterType));
                };
                shaderItem.ShaderNameOnReset = delegate
                {
                    RemoveMaterialShaderName(objectType, coordinateIndex, slot, materialName, gameObject);
                    StartCoroutine(PopulateListCoroutine(gameObject, objectType, coordinateIndex, slot, filterType: filterType));
                };
                items.Add(shaderItem);

                //Shader RenderQueue
                int renderQueueOriginal     = mat.renderQueue;
                int?renderQueueOriginalTemp = GetMaterialShaderRenderQueueOriginal(objectType, coordinateIndex, slot, materialName);
                renderQueueOriginal = renderQueueOriginalTemp == null ? mat.renderQueue : (int)renderQueueOriginalTemp;
                var shaderRenderQueueItem = new ItemInfo(ItemInfo.RowItemType.ShaderRenderQueue, "Render Queue");
                shaderRenderQueueItem.ShaderRenderQueue         = mat.renderQueue;
                shaderRenderQueueItem.ShaderRenderQueueOriginal = renderQueueOriginal;
                shaderRenderQueueItem.ShaderRenderQueueOnChange = delegate(int value) { AddMaterialShaderRenderQueue(objectType, coordinateIndex, slot, materialName, mat.renderQueue, renderQueueOriginal, gameObject); };
                shaderRenderQueueItem.ShaderRenderQueueOnReset  = delegate { RemoveMaterialShaderRenderQueue(objectType, coordinateIndex, slot, materialName, gameObject); };
                items.Add(shaderRenderQueueItem);

                foreach (var property in XMLShaderProperties[XMLShaderProperties.ContainsKey(shaderName) ? shaderName : "default"].OrderBy(x => x.Value.Type).ThenBy(x => x.Key))
                {
                    string propertyName = property.Key;
                    if (CheckBlacklist(objectType, propertyName))
                    {
                        continue;
                    }

                    if (property.Value.Type == ShaderPropertyType.Texture)
                    {
                        if (mat.HasProperty($"_{propertyName}"))
                        {
                            var textureItem = new ItemInfo(ItemInfo.RowItemType.TextureProperty, propertyName);
                            textureItem.TextureChanged  = !GetMaterialTextureValueOriginal(objectType, coordinateIndex, slot, materialName, propertyName);
                            textureItem.TextureExists   = mat.GetTexture($"_{propertyName}") != null;
                            textureItem.TextureOnExport = delegate { ExportTexture(mat, propertyName); };
                            textureItem.TextureOnImport = delegate
                            {
                                OpenFileDialog.Show(strings => OnFileAccept(strings), "Open image", Application.dataPath, FileFilter, FileExt);

                                void OnFileAccept(string[] strings)
                                {
                                    if (strings == null || strings.Length == 0 || strings[0].IsNullOrEmpty())
                                    {
                                        textureItem.TextureChanged = !GetMaterialTextureValueOriginal(objectType, coordinateIndex, slot, materialName, propertyName);
                                        textureItem.TextureExists  = mat.GetTexture($"_{propertyName}") != null;
                                        return;
                                    }
                                    string filePath = strings[0];

                                    AddMaterialTexture(objectType, coordinateIndex, slot, materialName, propertyName, filePath, gameObject);

                                    TexChangeWatcher?.Dispose();
                                    if (WatchTexChanges.Value)
                                    {
                                        var directory = Path.GetDirectoryName(filePath);
                                        if (directory != null)
                                        {
                                            TexChangeWatcher          = new FileSystemWatcher(directory, Path.GetFileName(filePath));
                                            TexChangeWatcher.Changed += (sender, args) =>
                                            {
                                                if (WatchTexChanges.Value && File.Exists(filePath))
                                                {
                                                    AddMaterialTexture(objectType, coordinateIndex, slot, materialName, propertyName, filePath, gameObject);
                                                }
                                            };
                                            TexChangeWatcher.Deleted            += (sender, args) => TexChangeWatcher?.Dispose();
                                            TexChangeWatcher.Error              += (sender, args) => TexChangeWatcher?.Dispose();
                                            TexChangeWatcher.EnableRaisingEvents = true;
                                        }
                                    }
                                }
                            };
                            textureItem.TextureOnReset = delegate { RemoveMaterialTexture(objectType, coordinateIndex, slot, materialName, propertyName); };
                            items.Add(textureItem);

                            Vector2 textureOffset             = mat.GetTextureOffset($"_{propertyName}");
                            Vector2 textureOffsetOriginal     = textureOffset;
                            Vector2?textureOffsetOriginalTemp = GetMaterialTextureOffsetOriginal(objectType, coordinateIndex, slot, materialName, propertyName);
                            if (textureOffsetOriginalTemp != null)
                            {
                                textureOffsetOriginal = (Vector2)textureOffsetOriginalTemp;
                            }

                            Vector2 textureScale             = mat.GetTextureScale($"_{propertyName}");
                            Vector2 textureScaleOriginal     = textureScale;
                            Vector2?textureScaleOriginalTemp = GetMaterialTextureScaleOriginal(objectType, coordinateIndex, slot, materialName, propertyName);
                            if (textureScaleOriginalTemp != null)
                            {
                                textureScaleOriginal = (Vector2)textureScaleOriginalTemp;
                            }

                            var textureItemOffsetScale = new ItemInfo(ItemInfo.RowItemType.TextureOffsetScale);
                            textureItemOffsetScale.Offset         = textureOffset;
                            textureItemOffsetScale.OffsetOriginal = textureOffsetOriginal;
                            textureItemOffsetScale.OffsetOnChange = delegate(Vector2 value) { AddMaterialTextureOffset(objectType, coordinateIndex, slot, materialName, propertyName, value, textureOffsetOriginal, gameObject); };
                            textureItemOffsetScale.OffsetOnReset  = delegate { RemoveMaterialTextureOffset(objectType, coordinateIndex, slot, materialName, propertyName, gameObject); };
                            textureItemOffsetScale.Scale          = textureScale;
                            textureItemOffsetScale.ScaleOriginal  = textureScaleOriginal;
                            textureItemOffsetScale.ScaleOnChange  = delegate(Vector2 value) { AddMaterialTextureScale(objectType, coordinateIndex, slot, materialName, propertyName, value, textureScaleOriginal, gameObject); };
                            textureItemOffsetScale.ScaleOnReset   = delegate { RemoveMaterialTextureScale(objectType, coordinateIndex, slot, materialName, propertyName, gameObject); };
                            items.Add(textureItemOffsetScale);
                        }
                    }
                    else if (property.Value.Type == ShaderPropertyType.Color)
                    {
                        if (mat.HasProperty($"_{propertyName}"))
                        {
                            Color valueColor         = mat.GetColor($"_{propertyName}");
                            Color valueColorOriginal = valueColor;
                            Color?c = GetMaterialColorPropertyValueOriginal(objectType, coordinateIndex, slot, materialName, propertyName);
                            if (c != null)
                            {
                                valueColorOriginal = (Color)c;
                            }
                            var contentItem = new ItemInfo(ItemInfo.RowItemType.ColorProperty, propertyName);
                            contentItem.ColorValue         = valueColor;
                            contentItem.ColorValueOriginal = valueColorOriginal;
                            contentItem.ColorValueOnChange = delegate(Color value) { AddMaterialColorProperty(objectType, coordinateIndex, slot, materialName, propertyName, value, valueColorOriginal, gameObject); };
                            contentItem.ColorValueOnReset  = delegate { RemoveMaterialColorProperty(objectType, coordinateIndex, slot, materialName, propertyName, gameObject); };
                            items.Add(contentItem);
                        }
                    }
                    else if (property.Value.Type == ShaderPropertyType.Float)
                    {
                        if (mat.HasProperty($"_{propertyName}"))
                        {
                            float  valueFloat             = mat.GetFloat($"_{propertyName}");
                            float  valueFloatOriginal     = valueFloat;
                            string valueFloatOriginalTemp = GetMaterialFloatPropertyValueOriginal(objectType, coordinateIndex, slot, materialName, propertyName);
                            if (!valueFloatOriginalTemp.IsNullOrEmpty() && float.TryParse(valueFloatOriginalTemp, out float valueFloatOriginalTempF))
                            {
                                valueFloatOriginal = valueFloatOriginalTempF;
                            }
                            var contentItem = new ItemInfo(ItemInfo.RowItemType.FloatProperty, propertyName);
                            contentItem.FloatValue         = valueFloat;
                            contentItem.FloatValueOriginal = valueFloatOriginal;
                            if (property.Value.MinValue != null)
                            {
                                contentItem.FloatValueSliderMin = (float)property.Value.MinValue;
                            }
                            if (property.Value.MaxValue != null)
                            {
                                contentItem.FloatValueSliderMax = (float)property.Value.MaxValue;
                            }
                            contentItem.FloatValueOnChange = delegate(float value) { AddMaterialFloatProperty(objectType, coordinateIndex, slot, materialName, propertyName, value, valueFloatOriginal, gameObject); };
                            contentItem.FloatValueOnReset  = delegate { RemoveMaterialFloatProperty(objectType, coordinateIndex, slot, materialName, propertyName, gameObject); };
                            items.Add(contentItem);
                        }
                    }
                }
            }

            virtualList.SetList(items);
        }
Пример #23
0
            private void InitializeComponent()
            {
                _hBox = new HorizontalBox()
                {
                    AllowPadding = true
                };
                this.Child = _hBox;

                _vBox = new VerticalBox()
                {
                    AllowPadding = true
                };
                _hBox.Children.Add(_vBox);

                _vBox.Children.Add(new DatePicker());
                _vBox.Children.Add(new TimePicker());
                _vBox.Children.Add(new DateTimePicker());
                _vBox.Children.Add(new FontPicker());
                _vBox.Children.Add(new ColorPicker());

                _hBox.Children.Add(new Separator(Orientation.Vertical));

                _vBox = new VerticalBox()
                {
                    AllowPadding = true
                };
                _hBox.Children.Add(_vBox);

                _grid = new Grid()
                {
                    AllowPadding = true
                };
                _vBox.Children.Add(_grid);

                _button = new Button("Open File");
                _entry  = new Entry()
                {
                    IsReadOnly = true
                };

                _button.Click += (sender, args) =>
                {
                    var dialog = new OpenFileDialog();
                    if (!dialog.Show())
                    {
                        _entry.Text = "(cancelled)";
                        return;
                    }
                    ;
                    _entry.Text = dialog.Path;
                };

                _grid.Children.Add(_button, 0, 0, 1, 1, 0, HorizontalAlignment.Stretch, 0, VerticalAlignment.Stretch);
                _grid.Children.Add(_entry, 1, 0, 1, 1, 1, HorizontalAlignment.Stretch, 0, VerticalAlignment.Stretch);

                _button = new Button("Save File");
                _entry2 = new Entry()
                {
                    IsReadOnly = true
                };

                _button.Click += (sender, args) =>
                {
                    var dialog = new SaveFileDialog();
                    if (!dialog.Show())
                    {
                        _entry2.Text = "(cancelled)";
                        return;
                    }
                    ;
                    _entry2.Text = dialog.Path;
                };

                _grid.Children.Add(_button, 0, 1, 1, 1, 0, HorizontalAlignment.Stretch, 0, VerticalAlignment.Stretch);
                _grid.Children.Add(_entry2, 1, 1, 1, 1, 1, HorizontalAlignment.Stretch, 0, VerticalAlignment.Stretch);

                _msgGrid = new Grid()
                {
                    AllowPadding = true
                };
                _grid.Children.Add(_msgGrid, 0, 2, 2, 1, 0, HorizontalAlignment.Center, 0, VerticalAlignment.Top);

                _button        = new Button("Message Box");
                _button.Click += (sender, args) =>
                {
                    MessageBox.Show("This is a normal message box.", "More detailed information can be shown here.");
                };
                _msgGrid.Children.Add(_button, 0, 0, 1, 1, 0, HorizontalAlignment.Stretch, 0, VerticalAlignment.Stretch);

                _button        = new Button("Error Box");
                _button.Click += (sender, args) =>
                {
                    MessageBox.Show("This message box describes an error.", "More detailed information can be shown here.", MessageBoxTypes.Error);
                };
                _msgGrid.Children.Add(_button, 1, 0, 1, 1, 0, HorizontalAlignment.Stretch, 0, VerticalAlignment.Stretch);
            }