From 4ae138a8c28452d1fc79dde64ee357e3882227d2 Mon Sep 17 00:00:00 2001 From: mrbusysky <58412572+mrbusysky@users.noreply.github.com> Date: Wed, 11 Oct 2023 00:25:21 -0700 Subject: [PATCH 1/2] fix: namespace and version (#80) * namespace and version updates to changes version # and to fix namespace issues * name space and ignore * fixed missing dependency added it back into the files * Update package.json --- .gitignore | 4 +- .../CompositionEditor/CompositionEditor.cs | 297 ++-- Scenario/Editor/DataBuilder/DataBuilder.cs | 594 ++++---- Scenario/Editor/ImageEditor/ImageEditor.cs | 51 +- Scenario/Editor/ImageEditor/ImageEditorUI.cs | 1237 ++++++++-------- Scenario/Editor/Images/ImageDataClasses.cs | 55 +- Scenario/Editor/Images/Images.cs | 195 +-- Scenario/Editor/Images/ImagesUI.cs | 357 ++--- .../InpaintingEditor/InpaintingEditor.cs | 51 +- .../InpaintingEditor/InpaintingEditorUI.cs | 1283 +++++++++-------- .../Editor/LayerEditor/ContextMenuActions.cs | 367 ++--- Scenario/Editor/LayerEditor/LayerEditor.cs | 885 ++++++------ .../LayerEditor/LayerEditorRightPanel.cs | 80 +- Scenario/Editor/Models/Models.cs | 466 +++--- Scenario/Editor/Models/ModelsUI.cs | 329 ++--- Scenario/Editor/PackageExport.cs | 192 +-- Scenario/Editor/PixelEditor/PixelEditor.cs | 55 +- Scenario/Editor/PixelEditor/PixelEditorUI.cs | 413 +++--- Scenario/Editor/PromptImages/PromptImages.cs | 328 ++--- .../Editor/PromptImages/PromptImagesUI.cs | 355 ++--- .../PromptWindow/PromptBuilderWindow.cs | 837 +++++------ Scenario/Editor/PromptWindow/PromptWindow.cs | 671 ++++----- .../Editor/PromptWindow/PromptWindowUI.cs | 619 ++++---- .../PromptWindow/Views/ControlNetView.cs | 122 +- .../PromptWindow/Views/ImageSettingsView.cs | 143 +- .../PromptWindow/Views/NegativePromptView.cs | 211 +-- .../Editor/PromptWindow/Views/PromptView.cs | 191 +-- .../Editor/UpscaleEditor/UpscaleEditor.cs | 47 +- .../Editor/UpscaleEditor/UpscaleEditorUI.cs | 435 +++--- Scenario/Editor/_CustomStyle/CustomStyle.cs | 225 +-- Scenario/EditorGUI/CustomStyle.cs | 243 ++-- Scenario/Plugins/APIPricing.cs | 149 +- Scenario/Plugins/ApiClient.cs | 201 +-- Scenario/Plugins/CommonUtils.cs | 168 +-- Scenario/Plugins/PluginSettings.cs | 167 +-- Scenario/com.scenario.editor.asmdef | 2 +- 36 files changed, 6053 insertions(+), 5972 deletions(-) diff --git a/.gitignore b/.gitignore index bd7a852..fec5a7a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ *.meta -node_modules/ \ No newline at end of file +node_modules/ +./idea* +Scenario/.idea/* diff --git a/Scenario/Editor/CompositionEditor/CompositionEditor.cs b/Scenario/Editor/CompositionEditor/CompositionEditor.cs index b0a65a9..f1dee22 100644 --- a/Scenario/Editor/CompositionEditor/CompositionEditor.cs +++ b/Scenario/Editor/CompositionEditor/CompositionEditor.cs @@ -1,191 +1,194 @@ +using System; using UnityEditor; using UnityEngine; -using System; -public class CompositionEditor : EditorWindow +namespace Scenario { - private static readonly int[] AllowedWidthValues = { 512, 576, 640, 688, 704, 768, 912, 1024 }; - private static readonly int[] AllowedHeightValues = { 512, 576, 640, 688, 704, 768, 912, 1024 }; - private static readonly float MinimumWidth = 800f; - private static readonly float MinimumHeight = 750f; - - private int widthSliderValue = 512; - private int heightSliderValue = 512; - private float distanceOffset = 1f; - private GameObject compositionCamera = null; - internal RenderTexture renderTexture; - private Texture2D screenshot; - - [MenuItem("Window/Scenario/Composition Editor")] - public static void ShowWindow() + public class CompositionEditor : EditorWindow { - var window = GetWindow("Composition Editor"); - window.minSize = new Vector2(MinimumWidth, MinimumHeight); - } + private static readonly int[] AllowedWidthValues = { 512, 576, 640, 688, 704, 768, 912, 1024 }; + private static readonly int[] AllowedHeightValues = { 512, 576, 640, 688, 704, 768, 912, 1024 }; + private static readonly float MinimumWidth = 800f; + private static readonly float MinimumHeight = 750f; + + private int widthSliderValue = 512; + private int heightSliderValue = 512; + private float distanceOffset = 1f; + private GameObject compositionCamera = null; + internal RenderTexture renderTexture; + private Texture2D screenshot; + + [MenuItem("Window/Scenario/Composition Editor")] + public static void ShowWindow() + { + var window = GetWindow("Composition Editor"); + window.minSize = new Vector2(MinimumWidth, MinimumHeight); + } - private void OnGUI() - { - DrawBackground(); - DrawScreenshotIfAvailable(); - DrawControlButtons(); - DrawControls(); - DrawUseImageButton(); - } + private void OnGUI() + { + DrawBackground(); + DrawScreenshotIfAvailable(); + DrawControlButtons(); + DrawControls(); + DrawUseImageButton(); + } - private void DrawBackground() - { - Color backgroundColor = CustomStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } + private void DrawBackground() + { + Color backgroundColor = CustomStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); + } - private void DrawScreenshotIfAvailable() - { - if (screenshot == null) return; + private void DrawScreenshotIfAvailable() + { + if (screenshot == null) return; - Rect textureRect = GUILayoutUtility.GetRect(screenshot.width, screenshot.height, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); - GUI.DrawTexture(textureRect, screenshot, ScaleMode.ScaleToFit); - } + Rect textureRect = GUILayoutUtility.GetRect(screenshot.width, screenshot.height, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); + GUI.DrawTexture(textureRect, screenshot, ScaleMode.ScaleToFit); + } - private void DrawControlButtons() - { - EditorGUILayout.BeginHorizontal(); + private void DrawControlButtons() { - CustomStyle.ButtonSecondary("Place Camera", 25, PlaceCamera); - CustomStyle.ButtonSecondary("Remove Camera", 25, RemoveCamera); - CustomStyle.ButtonSecondary("Take Screenshot", 25, CaptureScreenshot); + EditorGUILayout.BeginHorizontal(); + { + CustomStyle.ButtonSecondary("Place Camera", 25, PlaceCamera); + CustomStyle.ButtonSecondary("Remove Camera", 25, RemoveCamera); + CustomStyle.ButtonSecondary("Take Screenshot", 25, CaptureScreenshot); + } + EditorGUILayout.EndHorizontal(); } - EditorGUILayout.EndHorizontal(); - } - - private void DrawControls() - { - CustomStyle.Space(); - distanceOffset = EditorGUILayout.Slider("Distance Offset: ", distanceOffset, 0.1f, 100.0f); - widthSliderValue = DrawDimensionControl("Width: ", widthSliderValue, AllowedWidthValues); - heightSliderValue = DrawDimensionControl("Height: ", heightSliderValue, AllowedHeightValues); - CustomStyle.Space(20f); - } - private int DrawDimensionControl(string label, int currentValue, int[] allowedValues) - { - int index = 0; - - EditorGUILayout.BeginVertical(); + private void DrawControls() { - EditorGUILayout.LabelField(label, EditorStyles.label, GUILayout.Width(55), GUILayout.Height(20)); - index = NearestValueIndex(currentValue, allowedValues); - index = GUILayout.SelectionGrid(index, Array.ConvertAll(allowedValues, x => x.ToString()), - allowedValues.Length); + CustomStyle.Space(); + distanceOffset = EditorGUILayout.Slider("Distance Offset: ", distanceOffset, 0.1f, 100.0f); + widthSliderValue = DrawDimensionControl("Width: ", widthSliderValue, AllowedWidthValues); + heightSliderValue = DrawDimensionControl("Height: ", heightSliderValue, AllowedHeightValues); + CustomStyle.Space(20f); } - EditorGUILayout.EndVertical(); - - return allowedValues[index]; - } - private void DrawUseImageButton() - { - EditorGUILayout.BeginVertical(); + private int DrawDimensionControl(string label, int currentValue, int[] allowedValues) { - GUIStyle generateButtonStyle = new GUIStyle(GUI.skin.button) + int index = 0; + + EditorGUILayout.BeginVertical(); { - normal = - { - background = CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)), - textColor = Color.white - }, - active = - { - background = CreateColorTexture(new Color(0, 0.3f, 0.6f, 1)), - textColor = Color.white - } - }; + EditorGUILayout.LabelField(label, EditorStyles.label, GUILayout.Width(55), GUILayout.Height(20)); + index = NearestValueIndex(currentValue, allowedValues); + index = GUILayout.SelectionGrid(index, Array.ConvertAll(allowedValues, x => x.ToString()), + allowedValues.Length); + } + EditorGUILayout.EndVertical(); + + return allowedValues[index]; + } - if (GUILayout.Button("Use Image", generateButtonStyle, GUILayout.Height(40))) + private void DrawUseImageButton() + { + EditorGUILayout.BeginVertical(); { - if (screenshot == null) + GUIStyle generateButtonStyle = new GUIStyle(GUI.skin.button) { - Debug.LogError("Screenshot must be taken before using the image"); - } - else + normal = + { + background = CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)), + textColor = Color.white + }, + active = + { + background = CreateColorTexture(new Color(0, 0.3f, 0.6f, 1)), + textColor = Color.white + } + }; + + if (GUILayout.Button("Use Image", generateButtonStyle, GUILayout.Height(40))) { - PromptWindowUI.imageUpload = screenshot; + if (screenshot == null) + { + Debug.LogError("Screenshot must be taken before using the image"); + } + else + { + PromptWindowUI.imageUpload = screenshot; + } } } + EditorGUILayout.EndVertical(); + CustomStyle.Space(10f); } - EditorGUILayout.EndVertical(); - CustomStyle.Space(10f); - } - private void PlaceCamera() - { - compositionCamera = new GameObject("CompositionCamera"); - Camera camera = compositionCamera.AddComponent(); - SceneView sceneView = SceneView.lastActiveSceneView; + private void PlaceCamera() + { + compositionCamera = new GameObject("CompositionCamera"); + Camera camera = compositionCamera.AddComponent(); + SceneView sceneView = SceneView.lastActiveSceneView; - if (sceneView == null) return; + if (sceneView == null) return; - Vector3 cameraPosition = sceneView.pivot + sceneView.rotation * Vector3.forward * distanceOffset; - compositionCamera.transform.position = cameraPosition; - compositionCamera.transform.rotation = sceneView.rotation; - } + Vector3 cameraPosition = sceneView.pivot + sceneView.rotation * Vector3.forward * distanceOffset; + compositionCamera.transform.position = cameraPosition; + compositionCamera.transform.rotation = sceneView.rotation; + } - private void RemoveCamera() - { - if (compositionCamera == null) return; + private void RemoveCamera() + { + if (compositionCamera == null) return; - DestroyImmediate(compositionCamera); - compositionCamera = null; - } - - private int NearestValueIndex(int currentValue, int[] allowedValues) - { - int nearestIndex = 0; - int minDifference = int.MaxValue; + DestroyImmediate(compositionCamera); + compositionCamera = null; + } - for (int i = 0; i < allowedValues.Length; i++) + private int NearestValueIndex(int currentValue, int[] allowedValues) { - int difference = Mathf.Abs(currentValue - allowedValues[i]); - if (difference < minDifference) + int nearestIndex = 0; + int minDifference = int.MaxValue; + + for (int i = 0; i < allowedValues.Length; i++) { - minDifference = difference; - nearestIndex = i; + int difference = Mathf.Abs(currentValue - allowedValues[i]); + if (difference < minDifference) + { + minDifference = difference; + nearestIndex = i; + } } - } - return nearestIndex; - } + return nearestIndex; + } - private void CaptureScreenshot() - { - if (compositionCamera == null) return; + private void CaptureScreenshot() + { + if (compositionCamera == null) return; - Camera camera = compositionCamera.GetComponent(); - RenderTexture rt = new RenderTexture(widthSliderValue, heightSliderValue, 24); - camera.targetTexture = rt; - camera.Render(); + Camera camera = compositionCamera.GetComponent(); + RenderTexture rt = new RenderTexture(widthSliderValue, heightSliderValue, 24); + camera.targetTexture = rt; + camera.Render(); - Texture2D tempTexture = new Texture2D(widthSliderValue, heightSliderValue, TextureFormat.RGB24, false); - RenderTexture.active = rt; - tempTexture.ReadPixels(new Rect(0, 0, widthSliderValue, heightSliderValue), 0, 0); - tempTexture.Apply(); + Texture2D tempTexture = new Texture2D(widthSliderValue, heightSliderValue, TextureFormat.RGB24, false); + RenderTexture.active = rt; + tempTexture.ReadPixels(new Rect(0, 0, widthSliderValue, heightSliderValue), 0, 0); + tempTexture.Apply(); - screenshot = new Texture2D(widthSliderValue, heightSliderValue, TextureFormat.RGB24, false); - screenshot.SetPixels(tempTexture.GetPixels()); - screenshot.Apply(); + screenshot = new Texture2D(widthSliderValue, heightSliderValue, TextureFormat.RGB24, false); + screenshot.SetPixels(tempTexture.GetPixels()); + screenshot.Apply(); - camera.targetTexture = null; - RenderTexture.active = null; - DestroyImmediate(rt); - DestroyImmediate(tempTexture); + camera.targetTexture = null; + RenderTexture.active = null; + DestroyImmediate(rt); + DestroyImmediate(tempTexture); - Repaint(); - } + Repaint(); + } - private Texture2D CreateColorTexture(Color color) - { - Texture2D texture = new Texture2D(1, 1); - texture.SetPixel(0, 0, color); - texture.Apply(); - return texture; + private Texture2D CreateColorTexture(Color color) + { + Texture2D texture = new Texture2D(1, 1); + texture.SetPixel(0, 0, color); + texture.Apply(); + return texture; + } } } \ No newline at end of file diff --git a/Scenario/Editor/DataBuilder/DataBuilder.cs b/Scenario/Editor/DataBuilder/DataBuilder.cs index 3b8f40a..6cb9c3d 100644 --- a/Scenario/Editor/DataBuilder/DataBuilder.cs +++ b/Scenario/Editor/DataBuilder/DataBuilder.cs @@ -1,392 +1,394 @@ +using System.IO; using UnityEditor; using UnityEngine; -using System; -using System.IO; -public class DataBuilder : EditorWindow +namespace Scenario { - private enum ScreenshotType + public class DataBuilder : EditorWindow { - Normal, - Depth - } + private enum ScreenshotType + { + Normal, + Depth + } - private GameObject selectedObject; - private GameObject instantiatedObject; - private GameObject[] cameras; - private GameObject[] lights = new GameObject[8]; - private Texture2D combinedScreenshot; - private ScreenshotType screenshotType = ScreenshotType.Normal; - private ScreenshotType previousScreenshotType; - private static float minimumWidth = 800f; - private static float minimumHeight = 750f; - private const int ScreenshotSize = 1024; - private float cameraDistance = 2f; - private float lightDistance = 2f; - - [MenuItem("Window/Scenario/3d Data Builder")] - public static void ShowWindow() - { - GetWindow("3d Data Builder"); - DataBuilder window = GetWindow("3d Data Builder"); - window.minSize = new Vector2(minimumWidth, window.minSize.y); - window.minSize = new Vector2(window.minSize.x, minimumHeight); - } + private GameObject selectedObject; + private GameObject instantiatedObject; + private GameObject[] cameras; + private GameObject[] lights = new GameObject[8]; + private Texture2D combinedScreenshot; + private ScreenshotType screenshotType = ScreenshotType.Normal; + private ScreenshotType previousScreenshotType; + private static float minimumWidth = 800f; + private static float minimumHeight = 750f; + private const int ScreenshotSize = 1024; + private float cameraDistance = 2f; + private float lightDistance = 2f; + + [MenuItem("Window/Scenario/3d Data Builder")] + public static void ShowWindow() + { + GetWindow("3d Data Builder"); + DataBuilder window = GetWindow("3d Data Builder"); + window.minSize = new Vector2(minimumWidth, window.minSize.y); + window.minSize = new Vector2(window.minSize.x, minimumHeight); + } - private void Update() - { - if (previousScreenshotType == screenshotType || cameras == null) return; - - foreach (GameObject cameraObject in cameras) + private void Update() { - Camera cameraComponent = cameraObject.GetComponent(); - if (screenshotType == ScreenshotType.Normal) - { - cameraComponent.backgroundColor = Color.white; - } - else if (screenshotType == ScreenshotType.Depth) + if (previousScreenshotType == screenshotType || cameras == null) return; + + foreach (GameObject cameraObject in cameras) { - cameraComponent.backgroundColor = Color.black; + Camera cameraComponent = cameraObject.GetComponent(); + if (screenshotType == ScreenshotType.Normal) + { + cameraComponent.backgroundColor = Color.white; + } + else if (screenshotType == ScreenshotType.Depth) + { + cameraComponent.backgroundColor = Color.black; + } } - } - previousScreenshotType = screenshotType; - } - - private void OnDestroy() - { - RemoveCamerasAndLights(); + previousScreenshotType = screenshotType; + } - if (instantiatedObject != null) + private void OnDestroy() { - DestroyImmediate(instantiatedObject); - instantiatedObject = null; - } - } + RemoveCamerasAndLights(); - private void OnGUI() - { - DrawBackground(); + if (instantiatedObject != null) + { + DestroyImmediate(instantiatedObject); + instantiatedObject = null; + } + } - if (combinedScreenshot != null) + private void OnGUI() { - float maxWidth = 768f; - float maxHeight = 768f; + DrawBackground(); - float aspectRatio = (float)combinedScreenshot.width / combinedScreenshot.height; - float width = Mathf.Min(maxWidth, maxHeight * aspectRatio); - float height = width / aspectRatio; + if (combinedScreenshot != null) + { + float maxWidth = 768f; + float maxHeight = 768f; - Rect rect = GUILayoutUtility.GetRect(width, height); - GUI.DrawTexture(rect, combinedScreenshot, ScaleMode.ScaleToFit); - } + float aspectRatio = (float)combinedScreenshot.width / combinedScreenshot.height; + float width = Mathf.Min(maxWidth, maxHeight * aspectRatio); + float height = width / aspectRatio; - GUILayout.Label("Select Object", EditorStyles.boldLabel); - selectedObject = EditorGUILayout.ObjectField("Object", selectedObject, typeof(GameObject), true) as GameObject; + Rect rect = GUILayoutUtility.GetRect(width, height); + GUI.DrawTexture(rect, combinedScreenshot, ScaleMode.ScaleToFit); + } - float previousCameraDistance = cameraDistance; - cameraDistance = EditorGUILayout.Slider("Camera Distance", cameraDistance, 0.1f, 100.0f); + GUILayout.Label("Select Object", EditorStyles.boldLabel); + selectedObject = EditorGUILayout.ObjectField("Object", selectedObject, typeof(GameObject), true) as GameObject; - float previousLightDistance = lightDistance; - lightDistance = EditorGUILayout.Slider("Light Distance", lightDistance, 0.1f, 100.0f); + float previousCameraDistance = cameraDistance; + cameraDistance = EditorGUILayout.Slider("Camera Distance", cameraDistance, 0.1f, 100.0f); - screenshotType = (ScreenshotType)EditorGUILayout.EnumPopup("Screenshot Type", screenshotType); + float previousLightDistance = lightDistance; + lightDistance = EditorGUILayout.Slider("Light Distance", lightDistance, 0.1f, 100.0f); - DrawControlButtons(); + screenshotType = (ScreenshotType)EditorGUILayout.EnumPopup("Screenshot Type", screenshotType); - if (Mathf.Approximately(previousCameraDistance, cameraDistance) == false && instantiatedObject != null) - { - UpdateCameraPositions(); - } + DrawControlButtons(); - if (Mathf.Approximately(previousLightDistance, lightDistance) == false && instantiatedObject != null) - { - UpdateLightPositions(); - } + if (Mathf.Approximately(previousCameraDistance, cameraDistance) == false && instantiatedObject != null) + { + UpdateCameraPositions(); + } - CustomStyle.Space(20f); + if (Mathf.Approximately(previousLightDistance, lightDistance) == false && instantiatedObject != null) + { + UpdateLightPositions(); + } - GUIStyle generateButtonStyle = new GUIStyle(GUI.skin.button); - generateButtonStyle.normal.background = CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)); - generateButtonStyle.normal.textColor = Color.white; - generateButtonStyle.active.background = CreateColorTexture(new Color(0, 0.3f, 0.6f, 1)); - generateButtonStyle.active.textColor = Color.white; + CustomStyle.Space(20f); - if (GUILayout.Button("Use Image", generateButtonStyle, GUILayout.Height(40))) - { - if (combinedScreenshot == null) + GUIStyle generateButtonStyle = new GUIStyle(GUI.skin.button); + generateButtonStyle.normal.background = CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)); + generateButtonStyle.normal.textColor = Color.white; + generateButtonStyle.active.background = CreateColorTexture(new Color(0, 0.3f, 0.6f, 1)); + generateButtonStyle.active.textColor = Color.white; + + if (GUILayout.Button("Use Image", generateButtonStyle, GUILayout.Height(40))) { - Debug.Log("MUST HAVE A 3D IMAGE VIEW"); + if (combinedScreenshot == null) + { + Debug.Log("MUST HAVE A 3D IMAGE VIEW"); + } + else + { + PromptWindowUI.imageUpload = combinedScreenshot; + } } - else + } + + private void DrawControlButtons() + { + EditorGUILayout.BeginHorizontal(); { - PromptWindowUI.imageUpload = combinedScreenshot; + EditorStyle.Button("Place Object", PlaceObject); + EditorStyle.Button("Place Cameras/Lights", PlaceCamerasAndLights); + EditorStyle.Button("Remove Cameras/Lights", RemoveCamerasAndLights); + EditorStyle.Button("Take Screenshot", CaptureScreenshots); } + EditorGUILayout.EndHorizontal(); } - } - private void DrawControlButtons() - { - EditorGUILayout.BeginHorizontal(); + private void DrawBackground() { - EditorStyle.Button("Place Object", PlaceObject); - EditorStyle.Button("Place Cameras/Lights", PlaceCamerasAndLights); - EditorStyle.Button("Remove Cameras/Lights", RemoveCamerasAndLights); - EditorStyle.Button("Take Screenshot", CaptureScreenshots); + Color backgroundColor = EditorStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); } - EditorGUILayout.EndHorizontal(); - } - private void DrawBackground() - { - Color backgroundColor = EditorStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } + private void PlaceObject() + { + if (selectedObject == null) return; - private void PlaceObject() - { - if (selectedObject == null) return; + Camera sceneCamera = SceneView.lastActiveSceneView.camera; + Vector3 screenCenter = new Vector3(0.5f, 0.5f, 0.01f); + Vector3 worldCenter = sceneCamera.ViewportToWorldPoint(screenCenter); - Camera sceneCamera = SceneView.lastActiveSceneView.camera; - Vector3 screenCenter = new Vector3(0.5f, 0.5f, 0.01f); - Vector3 worldCenter = sceneCamera.ViewportToWorldPoint(screenCenter); + instantiatedObject = Instantiate(selectedObject, worldCenter, Quaternion.identity); + } - instantiatedObject = Instantiate(selectedObject, worldCenter, Quaternion.identity); - } + private void PlaceCamerasAndLights() + { + if (instantiatedObject == null) return; - private void PlaceCamerasAndLights() - { - if (instantiatedObject == null) return; + cameras = new GameObject[9]; - cameras = new GameObject[9]; + for (int i = 0; i < 9; i++) + { + cameras[i] = CreateCamera("Camera " + (i + 1)); + Camera cameraComponent = cameras[i].GetComponent(); - for (int i = 0; i < 9; i++) - { - cameras[i] = CreateCamera("Camera " + (i + 1)); - Camera cameraComponent = cameras[i].GetComponent(); + cameraComponent.clearFlags = CameraClearFlags.SolidColor; - cameraComponent.clearFlags = CameraClearFlags.SolidColor; + if (screenshotType == ScreenshotType.Normal) + { + cameraComponent.backgroundColor = Color.white; + } + else if (screenshotType == ScreenshotType.Depth) + { + cameraComponent.backgroundColor = Color.black; + } - if (screenshotType == ScreenshotType.Normal) - { - cameraComponent.backgroundColor = Color.white; - } - else if (screenshotType == ScreenshotType.Depth) - { - cameraComponent.backgroundColor = Color.black; + cameraComponent.fieldOfView = 54f; } - cameraComponent.fieldOfView = 54f; + UpdateCameraPositions(); + CreateLights(); } - UpdateCameraPositions(); - CreateLights(); - } - - private void UpdateCameraPositions() - { - Vector3 objectCenter = GetObjectCenter(instantiatedObject); - - (float latitude, float longitude)[] sphericalCoords = new (float, float)[] + private void UpdateCameraPositions() { - (Mathf.PI / 3, 0), - (Mathf.PI / 3, 2 * Mathf.PI / 3), - (Mathf.PI / 3, 4 * Mathf.PI / 3), + Vector3 objectCenter = GetObjectCenter(instantiatedObject); + + (float latitude, float longitude)[] sphericalCoords = new (float, float)[] + { + (Mathf.PI / 3, 0), + (Mathf.PI / 3, 2 * Mathf.PI / 3), + (Mathf.PI / 3, 4 * Mathf.PI / 3), - (Mathf.PI / 2, Mathf.PI / 3), - (Mathf.PI / 2, Mathf.PI), - (Mathf.PI / 2, 5 * Mathf.PI / 3), + (Mathf.PI / 2, Mathf.PI / 3), + (Mathf.PI / 2, Mathf.PI), + (Mathf.PI / 2, 5 * Mathf.PI / 3), - (2 * Mathf.PI / 3, 0), - (2 * Mathf.PI / 3, 2 * Mathf.PI / 3), - (2 * Mathf.PI / 3, 4 * Mathf.PI / 3) - }; + (2 * Mathf.PI / 3, 0), + (2 * Mathf.PI / 3, 2 * Mathf.PI / 3), + (2 * Mathf.PI / 3, 4 * Mathf.PI / 3) + }; - for (int i = 0; i < 9; i++) - { - float latitude = sphericalCoords[i].latitude; - float longitude = sphericalCoords[i].longitude; + for (int i = 0; i < 9; i++) + { + float latitude = sphericalCoords[i].latitude; + float longitude = sphericalCoords[i].longitude; - Vector3 direction = new Vector3( - Mathf.Sin(latitude) * Mathf.Cos(longitude), - Mathf.Cos(latitude), - Mathf.Sin(latitude) * Mathf.Sin(longitude) - ); + Vector3 direction = new Vector3( + Mathf.Sin(latitude) * Mathf.Cos(longitude), + Mathf.Cos(latitude), + Mathf.Sin(latitude) * Mathf.Sin(longitude) + ); - cameras[i].transform.position = objectCenter + direction * cameraDistance; - cameras[i].transform.LookAt(objectCenter); + cameras[i].transform.position = objectCenter + direction * cameraDistance; + cameras[i].transform.LookAt(objectCenter); + } } - } - private void RemoveCamerasAndLights() - { - if (cameras != null) + private void RemoveCamerasAndLights() { - foreach (GameObject camera in cameras) + if (cameras != null) { - DestroyImmediate(camera); + foreach (GameObject camera in cameras) + { + DestroyImmediate(camera); + } } - } - cameras = null; + cameras = null; - if (lights != null) - { - foreach (GameObject light in lights) + if (lights != null) { - DestroyImmediate(light); + foreach (GameObject light in lights) + { + DestroyImmediate(light); + } } - } - lights = null; + lights = null; - if (instantiatedObject != null) - { - DestroyImmediate(instantiatedObject); - instantiatedObject = null; + if (instantiatedObject != null) + { + DestroyImmediate(instantiatedObject); + instantiatedObject = null; + } } - } - - private GameObject CreateCamera(string cameraName) - { - GameObject cameraObject = new GameObject(cameraName); - Camera camera = cameraObject.AddComponent(); - return cameraObject; - } - private Vector3 GetObjectCenter(GameObject obj) - { - Renderer renderer = obj.GetComponent(); - if (renderer != null && renderer.bounds.size != Vector3.zero) + private GameObject CreateCamera(string cameraName) { - return renderer.bounds.center; + GameObject cameraObject = new GameObject(cameraName); + Camera camera = cameraObject.AddComponent(); + return cameraObject; } - Collider collider = obj.GetComponent(); - if (collider != null && collider.bounds.size != Vector3.zero) + private Vector3 GetObjectCenter(GameObject obj) { - return collider.bounds.center; - } - - return obj.transform.position; - } - - private void CaptureScreenshots() - { - if (cameras == null || cameras.Length <= 0) return; - - int gridRows = 3; - int gridCols = 3; - int totalCameras = gridRows * gridCols; - - int screenshotSize = ScreenshotSize; - int combinedWidth = screenshotSize * gridCols; - int combinedHeight = screenshotSize * gridRows; + Renderer renderer = obj.GetComponent(); + if (renderer != null && renderer.bounds.size != Vector3.zero) + { + return renderer.bounds.center; + } - combinedScreenshot = new Texture2D(combinedWidth, combinedHeight, TextureFormat.RGB24, false); + Collider collider = obj.GetComponent(); + if (collider != null && collider.bounds.size != Vector3.zero) + { + return collider.bounds.center; + } - string saveFolder = EditorPrefs.GetString("SaveFolder", "Assets"); - if (!Directory.Exists(saveFolder)) - { - Directory.CreateDirectory(saveFolder); + return obj.transform.position; } - for (int i = 0; i < totalCameras; i++) + private void CaptureScreenshots() { - if (i >= cameras.Length) - { - continue; - } + if (cameras == null || cameras.Length <= 0) return; + + int gridRows = 3; + int gridCols = 3; + int totalCameras = gridRows * gridCols; - Camera camera = cameras[i].GetComponent(); - RenderTexture renderTexture = new RenderTexture(screenshotSize, screenshotSize, 24); - camera.targetTexture = renderTexture; + int screenshotSize = ScreenshotSize; + int combinedWidth = screenshotSize * gridCols; + int combinedHeight = screenshotSize * gridRows; - if (screenshotType == ScreenshotType.Depth) + combinedScreenshot = new Texture2D(combinedWidth, combinedHeight, TextureFormat.RGB24, false); + + string saveFolder = EditorPrefs.GetString("SaveFolder", "Assets"); + if (!Directory.Exists(saveFolder)) { - camera.depthTextureMode = DepthTextureMode.Depth; - camera.RenderWithShader(Shader.Find("Custom/DepthMap"), ""); + Directory.CreateDirectory(saveFolder); } - else + + for (int i = 0; i < totalCameras; i++) { - camera.Render(); + if (i >= cameras.Length) + { + continue; + } + + Camera camera = cameras[i].GetComponent(); + RenderTexture renderTexture = new RenderTexture(screenshotSize, screenshotSize, 24); + camera.targetTexture = renderTexture; + + if (screenshotType == ScreenshotType.Depth) + { + camera.depthTextureMode = DepthTextureMode.Depth; + camera.RenderWithShader(Shader.Find("Custom/DepthMap"), ""); + } + else + { + camera.Render(); + } + + RenderTexture.active = renderTexture; + Texture2D screenshot = new Texture2D(screenshotSize, screenshotSize, TextureFormat.RGB24, false); + screenshot.ReadPixels(new Rect(0, 0, screenshotSize, screenshotSize), 0, 0); + screenshot.Apply(); + + byte[] screenshotBytes = screenshot.EncodeToPNG(); + string screenshotPath = Path.Combine(saveFolder, + camera.name + "_" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"); + File.WriteAllBytes(screenshotPath, screenshotBytes); + Debug.Log("Saved Screenshot: " + screenshotPath); + + int row = i / gridCols; + int col = i % gridCols; + int x = col * screenshotSize; + int y = (gridRows - row - 1) * screenshotSize; + + combinedScreenshot.SetPixels(x, y, screenshotSize, screenshotSize, screenshot.GetPixels()); + + RenderTexture.active = null; + camera.targetTexture = null; + GameObject.DestroyImmediate(renderTexture); + GameObject.DestroyImmediate(screenshot); } - RenderTexture.active = renderTexture; - Texture2D screenshot = new Texture2D(screenshotSize, screenshotSize, TextureFormat.RGB24, false); - screenshot.ReadPixels(new Rect(0, 0, screenshotSize, screenshotSize), 0, 0); - screenshot.Apply(); + combinedScreenshot.Apply(); - byte[] screenshotBytes = screenshot.EncodeToPNG(); - string screenshotPath = Path.Combine(saveFolder, - camera.name + "_" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"); - File.WriteAllBytes(screenshotPath, screenshotBytes); - Debug.Log("Saved Screenshot: " + screenshotPath); - - int row = i / gridCols; - int col = i % gridCols; - int x = col * screenshotSize; - int y = (gridRows - row - 1) * screenshotSize; - - combinedScreenshot.SetPixels(x, y, screenshotSize, screenshotSize, screenshot.GetPixels()); - - RenderTexture.active = null; - camera.targetTexture = null; - GameObject.DestroyImmediate(renderTexture); - GameObject.DestroyImmediate(screenshot); + byte[] combinedBytes = combinedScreenshot.EncodeToPNG(); + string combinedPath = Path.Combine(saveFolder, + "CombinedScreenshot_" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"); + File.WriteAllBytes(combinedPath, combinedBytes); + Debug.Log("Saved Combined Screenshot: " + combinedPath); } - combinedScreenshot.Apply(); - - byte[] combinedBytes = combinedScreenshot.EncodeToPNG(); - string combinedPath = Path.Combine(saveFolder, - "CombinedScreenshot_" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"); - File.WriteAllBytes(combinedPath, combinedBytes); - Debug.Log("Saved Combined Screenshot: " + combinedPath); - } - - private Texture2D CreateColorTexture(Color color) - { - Texture2D texture = new Texture2D(1, 1); - texture.SetPixel(0, 0, color); - texture.Apply(); - return texture; - } - - private void CreateLights() - { - lights = new GameObject[8]; - for (int i = 0; i < 8; i++) + private Texture2D CreateColorTexture(Color color) { - lights[i] = new GameObject("Light " + (i + 1)); - Light lightComponent = lights[i].AddComponent(); - lightComponent.type = LightType.Directional; + Texture2D texture = new Texture2D(1, 1); + texture.SetPixel(0, 0, color); + texture.Apply(); + return texture; } - UpdateLightPositions(); - } - private void UpdateLightPositions() - { - Vector3 objectCenter = GetObjectCenter(instantiatedObject); - - Vector3[] directions = new Vector3[] + private void CreateLights() { - new Vector3(1, 1, 1), - new Vector3(-1, 1, 1), - new Vector3(1, -1, 1), - new Vector3(-1, -1, 1), - new Vector3(1, 1, -1), - new Vector3(-1, 1, -1), - new Vector3(1, -1, -1), - new Vector3(-1, -1, -1) - }; - - for (int i = 0; i < lights.Length; i++) + lights = new GameObject[8]; + for (int i = 0; i < 8; i++) + { + lights[i] = new GameObject("Light " + (i + 1)); + Light lightComponent = lights[i].AddComponent(); + lightComponent.type = LightType.Directional; + } + UpdateLightPositions(); + } + + private void UpdateLightPositions() { - Vector3 direction = directions[i].normalized; - lights[i].transform.position = objectCenter + direction * lightDistance; - lights[i].transform.LookAt(objectCenter); + Vector3 objectCenter = GetObjectCenter(instantiatedObject); + + Vector3[] directions = new Vector3[] + { + new Vector3(1, 1, 1), + new Vector3(-1, 1, 1), + new Vector3(1, -1, 1), + new Vector3(-1, -1, 1), + new Vector3(1, 1, -1), + new Vector3(-1, 1, -1), + new Vector3(1, -1, -1), + new Vector3(-1, -1, -1) + }; + + for (int i = 0; i < lights.Length; i++) + { + Vector3 direction = directions[i].normalized; + lights[i].transform.position = objectCenter + direction * lightDistance; + lights[i].transform.LookAt(objectCenter); + } } } } \ No newline at end of file diff --git a/Scenario/Editor/ImageEditor/ImageEditor.cs b/Scenario/Editor/ImageEditor/ImageEditor.cs index dd34be2..fb336f7 100644 --- a/Scenario/Editor/ImageEditor/ImageEditor.cs +++ b/Scenario/Editor/ImageEditor/ImageEditor.cs @@ -1,37 +1,40 @@ using UnityEditor; using UnityEngine; -public class ImageEditor : EditorWindow +namespace Scenario { - private static ImageEditorUI imageEditorUI; - private static Texture2D imageTexture; + public class ImageEditor : EditorWindow + { + private static ImageEditorUI imageEditorUI; + private static Texture2D imageTexture; - private static float minimumWidth = 1775f; + private static float minimumWidth = 1775f; - [MenuItem("Window/Scenario/Image Editor")] - public static void ShowWindow() - { - ImageEditor window = GetWindow("Image Editor"); - window.minSize = new Vector2(minimumWidth, window.minSize.y); - } + [MenuItem("Window/Scenario/Image Editor")] + public static void ShowWindow() + { + ImageEditor window = GetWindow("Image Editor"); + window.minSize = new Vector2(minimumWidth, window.minSize.y); + } - public static void ShowWindow(Texture2D texture2D) - { - EditorWindow.GetWindow(typeof(ImageEditor), false, "Image Editor"); - imageTexture = texture2D; - if (imageTexture != null) + public static void ShowWindow(Texture2D texture2D) { - imageEditorUI.SetImage(imageTexture); + EditorWindow.GetWindow(typeof(ImageEditor), false, "Image Editor"); + imageTexture = texture2D; + if (imageTexture != null) + { + imageEditorUI.SetImage(imageTexture); + } } - } - private void OnEnable() - { - imageEditorUI = new ImageEditorUI(this); - } + private void OnEnable() + { + imageEditorUI = new ImageEditorUI(this); + } - private void OnGUI() - { - imageEditorUI.DrawUI(this.position); + private void OnGUI() + { + imageEditorUI.DrawUI(this.position); + } } } \ No newline at end of file diff --git a/Scenario/Editor/ImageEditor/ImageEditorUI.cs b/Scenario/Editor/ImageEditor/ImageEditorUI.cs index 39ca2ea..e1fba9c 100644 --- a/Scenario/Editor/ImageEditor/ImageEditorUI.cs +++ b/Scenario/Editor/ImageEditor/ImageEditorUI.cs @@ -1,826 +1,829 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; -using System.Collections.Generic; using UnityEditor; using UnityEngine; -public class ImageEditorUI +namespace Scenario { - private Texture2D uploadedImage; - private Texture2D brushCursor; - private Color selectedColor = Color.white; - private Texture2D canvasImage; - private Texture2D transparentImage; - private int selectedBrushSize; - private List canvasHistory; - private List redoHistory; - private int canvasHistoryIndex; - private bool newStroke = true; - public string uploadedImagePath; - - internal ImageEditor imageEditor; - private float selectedOpacity = 1.0f; - - private enum DrawingMode { Draw, Erase,/* Fill, Picker,*/ Expand, Crop } - private DrawingMode currentDrawingMode = DrawingMode.Draw; - private int[] allowedSizes = { 256, 384, 512, 570, 640, 704, 768, 912, 1024 }; - - private struct ToolButton + public class ImageEditorUI { - public string Text; - public string Tooltip; - public DrawingMode Mode; - public Action OnClick; - } + private Texture2D uploadedImage; + private Texture2D brushCursor; + private Color selectedColor = Color.white; + private Texture2D canvasImage; + private Texture2D transparentImage; + private int selectedBrushSize; + private List canvasHistory; + private List redoHistory; + private int canvasHistoryIndex; + private bool newStroke = true; + public string uploadedImagePath; + + internal ImageEditor imageEditor; + private float selectedOpacity = 1.0f; + + private enum DrawingMode { Draw, Erase,/* Fill, Picker,*/ Expand, Crop } + private DrawingMode currentDrawingMode = DrawingMode.Draw; + private int[] allowedSizes = { 256, 384, 512, 570, 640, 704, 768, 912, 1024 }; + + private struct ToolButton + { + public string Text; + public string Tooltip; + public DrawingMode Mode; + public Action OnClick; + } - private ToolButton[] toolButtons; + private ToolButton[] toolButtons; - private struct ActionButton - { - public string Text; - public string Tooltip; - public Action OnClick; - } + private struct ActionButton + { + public string Text; + public string Tooltip; + public Action OnClick; + } - private ActionButton[] actionButtons; + private ActionButton[] actionButtons; - public ImageEditorUI(ImageEditor imageEditor) - { - this.imageEditor = imageEditor; + public ImageEditorUI(ImageEditor imageEditor) + { + this.imageEditor = imageEditor; - transparentImage = new Texture2D(1, 1); - selectedBrushSize = 6; - canvasHistory = new List(); - canvasHistoryIndex = -1; - redoHistory = new List(); + transparentImage = new Texture2D(1, 1); + selectedBrushSize = 6; + canvasHistory = new List(); + canvasHistoryIndex = -1; + redoHistory = new List(); - toolButtons = new ToolButton[] - { - new ToolButton { Text = "✎", Tooltip = "Draw tool", Mode = DrawingMode.Draw }, - new ToolButton { Text = "✐", Tooltip = "Erase tool", Mode = DrawingMode.Erase }, - /*new ToolButton { Text = "◉", Tooltip = "Fill tool", Mode = DrawingMode.Fill }, + toolButtons = new ToolButton[] + { + new ToolButton { Text = "✎", Tooltip = "Draw tool", Mode = DrawingMode.Draw }, + new ToolButton { Text = "✐", Tooltip = "Erase tool", Mode = DrawingMode.Erase }, + /*new ToolButton { Text = "◉", Tooltip = "Fill tool", Mode = DrawingMode.Fill }, new ToolButton { Text = "✚", Tooltip = "Picker tool", Mode = DrawingMode.Picker },*/ - new ToolButton { Text = "[]", Tooltip = "To expand the image", Mode = DrawingMode.Expand }, - new ToolButton { Text = "-", Tooltip = "To crop the image", Mode = DrawingMode.Crop } - }; + new ToolButton { Text = "[]", Tooltip = "To expand the image", Mode = DrawingMode.Expand }, + new ToolButton { Text = "-", Tooltip = "To crop the image", Mode = DrawingMode.Crop } + }; - actionButtons = new ActionButton[] - { - /*new ActionButton { Text = "Load mask from file", Tooltip = "Load mask from file", OnClick = LoadMaskFromFile }, + actionButtons = new ActionButton[] + { + /*new ActionButton { Text = "Load mask from file", Tooltip = "Load mask from file", OnClick = LoadMaskFromFile }, new ActionButton { Text = "Save mask to file", Tooltip = "Save mask to file", OnClick = SaveMaskToFile }, new ActionButton { Text = "Fill all", Tooltip = "Fill all", OnClick = FillAll },*/ - new ActionButton { Text = "Create Image", Tooltip = "Create a new image", OnClick = CreateImage }, - new ActionButton { Text = "Clear", Tooltip = "Clear", OnClick = Clear }, - new ActionButton { Text = "Undo", Tooltip = "Undo", OnClick = UndoCanvas }, - new ActionButton { Text = "Redo", Tooltip = "Redo", OnClick = RedoCanvas }, - new ActionButton { Text = "Cancel", Tooltip = "Cancel", OnClick = Cancel }, - new ActionButton { Text = "Use", Tooltip = "Use", OnClick = Use } - }; - } - - internal void SetImage(Texture2D imageData) - { - uploadedImage = imageData; - uploadedImage.alphaIsTransparency = true; - - canvasImage = new Texture2D(uploadedImage.width, uploadedImage.height, TextureFormat.RGBA32, false, true); - canvasImage.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height).ToArray()); - canvasImage.Apply(); + new ActionButton { Text = "Create Image", Tooltip = "Create a new image", OnClick = CreateImage }, + new ActionButton { Text = "Clear", Tooltip = "Clear", OnClick = Clear }, + new ActionButton { Text = "Undo", Tooltip = "Undo", OnClick = UndoCanvas }, + new ActionButton { Text = "Redo", Tooltip = "Redo", OnClick = RedoCanvas }, + new ActionButton { Text = "Cancel", Tooltip = "Cancel", OnClick = Cancel }, + new ActionButton { Text = "Use", Tooltip = "Use", OnClick = Use } + }; + } - canvasHistory.Clear(); - canvasHistoryIndex = -1; - AddToCanvasHistory(); - } + internal void SetImage(Texture2D imageData) + { + uploadedImage = imageData; + uploadedImage.alphaIsTransparency = true; - public void DrawUI(Rect position) - { - DrawBackground(position); + canvasImage = new Texture2D(uploadedImage.width, uploadedImage.height, TextureFormat.RGBA32, false, true); + canvasImage.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height).ToArray()); + canvasImage.Apply(); - EditorGUILayout.BeginHorizontal(); + canvasHistory.Clear(); + canvasHistoryIndex = -1; + AddToCanvasHistory(); + } - position = DrawLeftSection(position); + public void DrawUI(Rect position) + { + DrawBackground(position); - // Flexible space between left and middle section - GUILayout.FlexibleSpace(); + EditorGUILayout.BeginHorizontal(); - DrawMiddleSection(position); + position = DrawLeftSection(position); - GUILayout.FlexibleSpace(); + // Flexible space between left and middle section + GUILayout.FlexibleSpace(); - DrawRightSection(position); + DrawMiddleSection(position); - EditorGUILayout.EndHorizontal(); - } + GUILayout.FlexibleSpace(); - private static void DrawBackground(Rect position) - { - Color backgroundColor = EditorStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } + DrawRightSection(position); - private void DrawRightSection(Rect position) - { - // Right Section - float rightSectionWidth = position.width * 0.1f; - EditorGUILayout.BeginVertical(GUILayout.Width(rightSectionWidth)); - CustomStyle.Space(18); - GUILayout.Label("Actions", EditorStyles.boldLabel); + EditorGUILayout.EndHorizontal(); + } - for (int i = 0; i < actionButtons.Length; i++) + private static void DrawBackground(Rect position) { - ActionButton button = actionButtons[i]; - if (GUILayout.Button(new GUIContent(button.Text, button.Tooltip), GUILayout.Width(140), GUILayout.Height(40))) - { - button.OnClick?.Invoke(); - } + Color backgroundColor = EditorStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); } - EditorGUILayout.EndVertical(); - } - - private void DrawMiddleSection(Rect position) - { - // Middle Section - float middleSectionWidth = position.width * 0.8f; - EditorGUILayout.BeginVertical(GUILayout.Width(middleSectionWidth)); + private void DrawRightSection(Rect position) { + // Right Section + float rightSectionWidth = position.width * 0.1f; + EditorGUILayout.BeginVertical(GUILayout.Width(rightSectionWidth)); CustomStyle.Space(18); + GUILayout.Label("Actions", EditorStyles.boldLabel); - if (uploadedImage != null) + for (int i = 0; i < actionButtons.Length; i++) { - switch (currentDrawingMode) + ActionButton button = actionButtons[i]; + if (GUILayout.Button(new GUIContent(button.Text, button.Tooltip), GUILayout.Width(140), GUILayout.Height(40))) { - case DrawingMode.Draw: - case DrawingMode.Erase: - DrawCanvasWithImage(); - break; - case DrawingMode.Expand: - DrawExpandSection(position); - break; - case DrawingMode.Crop: - DrawCropSection(position); - break; + button.OnClick?.Invoke(); } } - else - { - DrawUploadSection(); - } - } - EditorGUILayout.EndVertical(); - } - private void DrawUploadSection() - { - GUILayout.BeginHorizontal(); - { - GUILayout.FlexibleSpace(); - GUILayout.BeginVertical(); - { - HandleImageUpload(); - } - GUILayout.EndVertical(); - GUILayout.FlexibleSpace(); + EditorGUILayout.EndVertical(); } - GUILayout.EndHorizontal(); - } - private void HandleImageUpload() - { - Rect dropArea = GUILayoutUtility.GetRect(512f, 256f, GUILayout.ExpandWidth(false)); - GUI.Box(dropArea, "Drop image here or"); - - Event currentEvent = Event.current; - if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) + private void DrawMiddleSection(Rect position) { - if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) + // Middle Section + float middleSectionWidth = position.width * 0.8f; + EditorGUILayout.BeginVertical(GUILayout.Width(middleSectionWidth)); { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + CustomStyle.Space(18); - if (currentEvent.type == EventType.DragPerform) + if (uploadedImage != null) { - DragAndDrop.AcceptDrag(); - string path = DragAndDrop.paths[0]; - if (System.IO.File.Exists(path) && (System.IO.Path.GetExtension(path).ToLower() == ".png" || - System.IO.Path.GetExtension(path).ToLower() == ".jpg" || - System.IO.Path.GetExtension(path).ToLower() == ".jpeg")) + switch (currentDrawingMode) { - Texture2D tex = new Texture2D(2, 2); - byte[] imageData = File.ReadAllBytes(path); - tex.LoadImage(imageData); - SetImage(tex); + case DrawingMode.Draw: + case DrawingMode.Erase: + DrawCanvasWithImage(); + break; + case DrawingMode.Expand: + DrawExpandSection(position); + break; + case DrawingMode.Crop: + DrawCropSection(position); + break; } } - - currentEvent.Use(); + else + { + DrawUploadSection(); + } } + EditorGUILayout.EndVertical(); } - Rect buttonRect = new Rect(dropArea.center.x - 75f, dropArea.center.y - 20f, 150f, 40f); - if (GUI.Button(buttonRect, "Upload")) + private void DrawUploadSection() { - uploadedImagePath = EditorUtility.OpenFilePanel("Upload image", "", "png,jpeg,jpg"); - if (!string.IsNullOrEmpty(uploadedImagePath)) + GUILayout.BeginHorizontal(); { - Texture2D tex = new Texture2D(1, 1); - tex.LoadImage(File.ReadAllBytes(uploadedImagePath)); - SetImage(tex); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(); + { + HandleImageUpload(); + } + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); } + GUILayout.EndHorizontal(); } - } - private void DrawCropSection(Rect position) - { - EditorGUILayout.BeginHorizontal(); + private void HandleImageUpload() { - CustomStyle.Space(); - EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); + Rect dropArea = GUILayoutUtility.GetRect(512f, 256f, GUILayout.ExpandWidth(false)); + GUI.Box(dropArea, "Drop image here or"); + + Event currentEvent = Event.current; + if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) { - float centerX = position.width * 0.5f; - float centerY = position.height / 2f; - float imageWidth = uploadedImage.width; - float imageHeight = uploadedImage.height; - float buttonSize = 50f; - - var rect = new Rect(centerX - imageWidth / 2, centerY - imageHeight / 2, imageWidth, imageHeight); - GUI.DrawTexture(rect, uploadedImage); - - rect = new Rect(centerX - imageWidth / 2 - buttonSize - 5, centerY - buttonSize / 2, buttonSize, - buttonSize); - if (GUI.Button(rect, "-")) + if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) { - int newWidth = FindPreviousSize((int)imageWidth); - uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight, addLeft: true); - } + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - // Right button - rect = new Rect(centerX + imageWidth / 2 + 5, centerY - buttonSize / 2, buttonSize, buttonSize); - if (GUI.Button(rect, "-")) - { - int newWidth = FindPreviousSize((int)imageWidth); - uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight); - } + if (currentEvent.type == EventType.DragPerform) + { + DragAndDrop.AcceptDrag(); + string path = DragAndDrop.paths[0]; + if (System.IO.File.Exists(path) && (System.IO.Path.GetExtension(path).ToLower() == ".png" || + System.IO.Path.GetExtension(path).ToLower() == ".jpg" || + System.IO.Path.GetExtension(path).ToLower() == ".jpeg")) + { + Texture2D tex = new Texture2D(2, 2); + byte[] imageData = File.ReadAllBytes(path); + tex.LoadImage(imageData); + SetImage(tex); + } + } - // Top button - rect = new Rect(centerX - buttonSize / 2, centerY - imageHeight / 2 - buttonSize - 5, buttonSize, - buttonSize); - if (GUI.Button(rect, "-")) - { - int newHeight = FindPreviousSize((int)imageHeight); - uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight); + currentEvent.Use(); } + } - // Bottom button - rect = new Rect(centerX - buttonSize / 2, centerY + imageHeight / 2 + 5, buttonSize, buttonSize); - if (GUI.Button(rect, "-")) + Rect buttonRect = new Rect(dropArea.center.x - 75f, dropArea.center.y - 20f, 150f, 40f); + if (GUI.Button(buttonRect, "Upload")) + { + uploadedImagePath = EditorUtility.OpenFilePanel("Upload image", "", "png,jpeg,jpg"); + if (!string.IsNullOrEmpty(uploadedImagePath)) { - int newHeight = FindPreviousSize((int)imageHeight); - uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight, addBottom: true); + Texture2D tex = new Texture2D(1, 1); + tex.LoadImage(File.ReadAllBytes(uploadedImagePath)); + SetImage(tex); } } - EditorGUILayout.EndVertical(); } - EditorGUILayout.EndHorizontal(); - } - private void DrawExpandSection(Rect position) - { - EditorGUILayout.BeginHorizontal(); + private void DrawCropSection(Rect position) { - CustomStyle.Space(); - EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); + EditorGUILayout.BeginHorizontal(); { - float centerX = position.width * 0.5f; - float centerY = position.height / 2f; - float imageWidth = uploadedImage.width; - float imageHeight = uploadedImage.height; - float buttonSize = 50f; - - var rect = new Rect(centerX - imageWidth / 2, centerY - imageHeight / 2, imageWidth, imageHeight); - GUI.DrawTexture(rect, uploadedImage); - - rect = new Rect(centerX - imageWidth / 2 - buttonSize - 5, centerY - buttonSize / 2, buttonSize, - buttonSize); - if (GUI.Button(rect, "+")) + CustomStyle.Space(); + EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); { - int newWidth = FindNextSize((int)imageWidth); - uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight, addLeft: true); - } + float centerX = position.width * 0.5f; + float centerY = position.height / 2f; + float imageWidth = uploadedImage.width; + float imageHeight = uploadedImage.height; + float buttonSize = 50f; + + var rect = new Rect(centerX - imageWidth / 2, centerY - imageHeight / 2, imageWidth, imageHeight); + GUI.DrawTexture(rect, uploadedImage); + + rect = new Rect(centerX - imageWidth / 2 - buttonSize - 5, centerY - buttonSize / 2, buttonSize, + buttonSize); + if (GUI.Button(rect, "-")) + { + int newWidth = FindPreviousSize((int)imageWidth); + uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight, addLeft: true); + } - // Right button - rect = new Rect(centerX + imageWidth / 2 + 5, centerY - buttonSize / 2, buttonSize, buttonSize); - if (GUI.Button(rect, "+")) - { - int newWidth = FindNextSize((int)imageWidth); - uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight); - } + // Right button + rect = new Rect(centerX + imageWidth / 2 + 5, centerY - buttonSize / 2, buttonSize, buttonSize); + if (GUI.Button(rect, "-")) + { + int newWidth = FindPreviousSize((int)imageWidth); + uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight); + } - // Top button - rect = new Rect(centerX - buttonSize / 2, centerY - imageHeight / 2 - buttonSize - 5, buttonSize, - buttonSize); - if (GUI.Button(rect, "+")) - { - int newHeight = FindNextSize((int)imageHeight); - uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight); - } + // Top button + rect = new Rect(centerX - buttonSize / 2, centerY - imageHeight / 2 - buttonSize - 5, buttonSize, + buttonSize); + if (GUI.Button(rect, "-")) + { + int newHeight = FindPreviousSize((int)imageHeight); + uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight); + } - // Bottom button - rect = new Rect(centerX - buttonSize / 2, centerY + imageHeight / 2 + 5, buttonSize, buttonSize); - if (GUI.Button(rect, "+")) - { - int newHeight = FindNextSize((int)imageHeight); - uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight, addBottom: true); + // Bottom button + rect = new Rect(centerX - buttonSize / 2, centerY + imageHeight / 2 + 5, buttonSize, buttonSize); + if (GUI.Button(rect, "-")) + { + int newHeight = FindPreviousSize((int)imageHeight); + uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight, addBottom: true); + } } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); + EditorGUILayout.EndHorizontal(); } - EditorGUILayout.EndHorizontal(); - } - private void DrawCanvasWithImage() - { - EditorGUILayout.BeginHorizontal(); + private void DrawExpandSection(Rect position) { - CustomStyle.Space(); - EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); + EditorGUILayout.BeginHorizontal(); { - float maxSize = 1024f; - float aspectRatio = (float)uploadedImage.width / (float)uploadedImage.height; - float width = Mathf.Min(uploadedImage.width, maxSize); - float height = width / aspectRatio; - - Rect rect = GUILayoutUtility.GetRect(width, height, GUILayout.ExpandWidth(false), - GUILayout.ExpandHeight(false)); + CustomStyle.Space(); + EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); + { + float centerX = position.width * 0.5f; + float centerY = position.height / 2f; + float imageWidth = uploadedImage.width; + float imageHeight = uploadedImage.height; + float buttonSize = 50f; + + var rect = new Rect(centerX - imageWidth / 2, centerY - imageHeight / 2, imageWidth, imageHeight); + GUI.DrawTexture(rect, uploadedImage); + + rect = new Rect(centerX - imageWidth / 2 - buttonSize - 5, centerY - buttonSize / 2, buttonSize, + buttonSize); + if (GUI.Button(rect, "+")) + { + int newWidth = FindNextSize((int)imageWidth); + uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight, addLeft: true); + } - GUI.DrawTexture(rect, uploadedImage, ScaleMode.ScaleToFit); + // Right button + rect = new Rect(centerX + imageWidth / 2 + 5, centerY - buttonSize / 2, buttonSize, buttonSize); + if (GUI.Button(rect, "+")) + { + int newWidth = FindNextSize((int)imageWidth); + uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight); + } - if (canvasImage == null || canvasImage.width != uploadedImage.width || - canvasImage.height != uploadedImage.height) - { - int canvasWidth = Mathf.Min(uploadedImage.width, 1024); - int canvasHeight = Mathf.Min(uploadedImage.height, 1024); - canvasImage = new Texture2D(canvasWidth, canvasHeight, TextureFormat.RGBA32, false, true); - canvasImage.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height) - .ToArray()); - canvasImage.Apply(); - } + // Top button + rect = new Rect(centerX - buttonSize / 2, centerY - imageHeight / 2 - buttonSize - 5, buttonSize, + buttonSize); + if (GUI.Button(rect, "+")) + { + int newHeight = FindNextSize((int)imageHeight); + uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight); + } - GUI.DrawTexture(rect, canvasImage, ScaleMode.ScaleToFit); + // Bottom button + rect = new Rect(centerX - buttonSize / 2, centerY + imageHeight / 2 + 5, buttonSize, buttonSize); + if (GUI.Button(rect, "+")) + { + int newHeight = FindNextSize((int)imageHeight); + uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight, addBottom: true); + } + } + EditorGUILayout.EndVertical(); + } + EditorGUILayout.EndHorizontal(); + } - Rect lastRect = GUILayoutUtility.GetLastRect(); - if (lastRect.Contains(Event.current.mousePosition)) + private void DrawCanvasWithImage() + { + EditorGUILayout.BeginHorizontal(); + { + CustomStyle.Space(); + EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); { - if (brushCursor == null || brushCursor.width != selectedBrushSize) + float maxSize = 1024f; + float aspectRatio = (float)uploadedImage.width / (float)uploadedImage.height; + float width = Mathf.Min(uploadedImage.width, maxSize); + float height = width / aspectRatio; + + Rect rect = GUILayoutUtility.GetRect(width, height, GUILayout.ExpandWidth(false), + GUILayout.ExpandHeight(false)); + + GUI.DrawTexture(rect, uploadedImage, ScaleMode.ScaleToFit); + + if (canvasImage == null || canvasImage.width != uploadedImage.width || + canvasImage.height != uploadedImage.height) { - brushCursor = MakeCircularTex(selectedBrushSize, selectedColor); + int canvasWidth = Mathf.Min(uploadedImage.width, 1024); + int canvasHeight = Mathf.Min(uploadedImage.height, 1024); + canvasImage = new Texture2D(canvasWidth, canvasHeight, TextureFormat.RGBA32, false, true); + canvasImage.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height) + .ToArray()); + canvasImage.Apply(); } - EditorGUIUtility.AddCursorRect(lastRect, MouseCursor.CustomCursor); - Cursor.SetCursor(brushCursor, new Vector2(brushCursor.width / 2, brushCursor.height / 2), - CursorMode.Auto); + GUI.DrawTexture(rect, canvasImage, ScaleMode.ScaleToFit); - if (Event.current.type == EventType.MouseDrag || Event.current.type == EventType.MouseDown) + Rect lastRect = GUILayoutUtility.GetLastRect(); + if (lastRect.Contains(Event.current.mousePosition)) { - Vector2 localMousePosition = Event.current.mousePosition - new Vector2(rect.x, rect.y); - Vector2 textureCoords = new Vector2(localMousePosition.x / rect.width, - localMousePosition.y / rect.height); + if (brushCursor == null || brushCursor.width != selectedBrushSize) + { + brushCursor = MakeCircularTex(selectedBrushSize, selectedColor); + } - int x = (int)(textureCoords.x * uploadedImage.width); - int y = (int)((1 - textureCoords.y) * uploadedImage.height); + EditorGUIUtility.AddCursorRect(lastRect, MouseCursor.CustomCursor); + Cursor.SetCursor(brushCursor, new Vector2(brushCursor.width / 2, brushCursor.height / 2), + CursorMode.Auto); - if (currentDrawingMode == DrawingMode.Draw) + if (Event.current.type == EventType.MouseDrag || Event.current.type == EventType.MouseDown) { - DrawOnTexture(canvasImage, new Vector2(x, y), selectedBrushSize, selectedColor, - selectedOpacity); + Vector2 localMousePosition = Event.current.mousePosition - new Vector2(rect.x, rect.y); + Vector2 textureCoords = new Vector2(localMousePosition.x / rect.width, + localMousePosition.y / rect.height); + + int x = (int)(textureCoords.x * uploadedImage.width); + int y = (int)((1 - textureCoords.y) * uploadedImage.height); + + if (currentDrawingMode == DrawingMode.Draw) + { + DrawOnTexture(canvasImage, new Vector2(x, y), selectedBrushSize, selectedColor, + selectedOpacity); + } + else if (currentDrawingMode == DrawingMode.Erase) + { + DrawOnTexture(canvasImage, new Vector2(x, y), selectedBrushSize, new Color(0, 0, 0, 0), + selectedOpacity); + } + + Event.current.Use(); } - else if (currentDrawingMode == DrawingMode.Erase) + + else if (Event.current.type == EventType.MouseUp) { - DrawOnTexture(canvasImage, new Vector2(x, y), selectedBrushSize, new Color(0, 0, 0, 0), - selectedOpacity); + newStroke = true; } - - Event.current.Use(); - } - - else if (Event.current.type == EventType.MouseUp) - { - newStroke = true; } } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); + EditorGUILayout.EndHorizontal(); } - EditorGUILayout.EndHorizontal(); - } - private Rect DrawLeftSection(Rect position) - { - // Left Section - float leftSectionWidth = position.width * 0.1f; - EditorGUILayout.BeginVertical(GUILayout.Width(leftSectionWidth)); + private Rect DrawLeftSection(Rect position) { - CustomStyle.Space(18); - GUILayout.Label("Tools", EditorStyles.boldLabel); - - for (int i = 0; i < toolButtons.Length; i++) + // Left Section + float leftSectionWidth = position.width * 0.1f; + EditorGUILayout.BeginVertical(GUILayout.Width(leftSectionWidth)); { - ToolButton button = toolButtons[i]; - if (i % 4 == 0) - { - EditorGUILayout.BeginHorizontal(); - } + CustomStyle.Space(18); + GUILayout.Label("Tools", EditorStyles.boldLabel); - GUIStyle buttonStyle = new GUIStyle(GUI.skin.button); - buttonStyle.fontSize = 25; - if (GUILayout.Button(new GUIContent(button.Text, button.Tooltip), buttonStyle, GUILayout.Width(45), - GUILayout.Height(45))) + for (int i = 0; i < toolButtons.Length; i++) { - currentDrawingMode = button.Mode; - button.OnClick?.Invoke(); - } + ToolButton button = toolButtons[i]; + if (i % 4 == 0) + { + EditorGUILayout.BeginHorizontal(); + } - if (i % 4 == 3 || i == toolButtons.Length - 1) - { - EditorGUILayout.EndHorizontal(); + GUIStyle buttonStyle = new GUIStyle(GUI.skin.button); + buttonStyle.fontSize = 25; + if (GUILayout.Button(new GUIContent(button.Text, button.Tooltip), buttonStyle, GUILayout.Width(45), + GUILayout.Height(45))) + { + currentDrawingMode = button.Mode; + button.OnClick?.Invoke(); + } + + if (i % 4 == 3 || i == toolButtons.Length - 1) + { + EditorGUILayout.EndHorizontal(); + } } - } - CustomStyle.Space(10); + CustomStyle.Space(10); - GUILayout.Label("Color", EditorStyles.boldLabel); + GUILayout.Label("Color", EditorStyles.boldLabel); - int colorButtonSize = 40; - int numColumns = Mathf.FloorToInt((leftSectionWidth - 0) / colorButtonSize); - - for (int i = 0; i < 35; i++) - { - if (i % numColumns == 0) EditorGUILayout.BeginHorizontal(); - - GUIStyle colorButtonStyle = new GUIStyle(GUI.skin.button); - Color color = Color.HSVToRGB((float)i / 35, 1, 1); - colorButtonStyle.normal.background = MakeTex(2, 2, color); + int colorButtonSize = 40; + int numColumns = Mathf.FloorToInt((leftSectionWidth - 0) / colorButtonSize); - if (GUILayout.Button("", colorButtonStyle, GUILayout.Width(colorButtonSize), - GUILayout.Height(colorButtonSize))) + for (int i = 0; i < 35; i++) { - selectedColor = color; - } + if (i % numColumns == 0) EditorGUILayout.BeginHorizontal(); - if (i % numColumns == numColumns - 1 || i == 34) EditorGUILayout.EndHorizontal(); - } + GUIStyle colorButtonStyle = new GUIStyle(GUI.skin.button); + Color color = Color.HSVToRGB((float)i / 35, 1, 1); + colorButtonStyle.normal.background = MakeTex(2, 2, color); - CustomStyle.Space(10); + if (GUILayout.Button("", colorButtonStyle, GUILayout.Width(colorButtonSize), + GUILayout.Height(colorButtonSize))) + { + selectedColor = color; + } - int[] brushSizes = new[] { 6, 12, 16, 24, 30, 40, 48, 64 }; + if (i % numColumns == numColumns - 1 || i == 34) EditorGUILayout.EndHorizontal(); + } - GUILayout.BeginHorizontal(); - { - GUILayout.Label("Brush Size", EditorStyles.boldLabel, GUILayout.Width(80)); - GUILayout.Label(selectedBrushSize.ToString(), GUILayout.Width(40)); - } - GUILayout.EndHorizontal(); + CustomStyle.Space(10); - GUILayout.BeginHorizontal(); - { - selectedBrushSize = (int)GUILayout.HorizontalSlider(selectedBrushSize, brushSizes[0], - brushSizes[brushSizes.Length - 1], GUILayout.Width(200)); - } - GUILayout.EndHorizontal(); + int[] brushSizes = new[] { 6, 12, 16, 24, 30, 40, 48, 64 }; - CustomStyle.Space(20); + GUILayout.BeginHorizontal(); + { + GUILayout.Label("Brush Size", EditorStyles.boldLabel, GUILayout.Width(80)); + GUILayout.Label(selectedBrushSize.ToString(), GUILayout.Width(40)); + } + GUILayout.EndHorizontal(); - float[] opacities = new float[] { 0.0f, 0.2f, 0.4f, 0.6f, 0.8f, 1.0f }; - int selectedOpacityIndex = 5; + GUILayout.BeginHorizontal(); + { + selectedBrushSize = (int)GUILayout.HorizontalSlider(selectedBrushSize, brushSizes[0], + brushSizes[brushSizes.Length - 1], GUILayout.Width(200)); + } + GUILayout.EndHorizontal(); - GUILayout.BeginHorizontal(); - { - GUILayout.Label("Opacity", EditorStyles.boldLabel); - } - GUILayout.EndHorizontal(); + CustomStyle.Space(20); - GUILayout.BeginHorizontal(); - { - for (int i = 0; i < opacities.Length; i++) + float[] opacities = new float[] { 0.0f, 0.2f, 0.4f, 0.6f, 0.8f, 1.0f }; + int selectedOpacityIndex = 5; + + GUILayout.BeginHorizontal(); { - float opacity = opacities[i]; - GUIStyle opacityButtonStyle = new GUIStyle(GUI.skin.button); - opacityButtonStyle.normal.background = MakeOpacityTex(10, 10, opacity); + GUILayout.Label("Opacity", EditorStyles.boldLabel); + } + GUILayout.EndHorizontal(); - if (GUILayout.Button("", opacityButtonStyle, GUILayout.Width(14), GUILayout.Height(14))) + GUILayout.BeginHorizontal(); + { + for (int i = 0; i < opacities.Length; i++) { - selectedOpacityIndex = i; - selectedOpacity = opacities[selectedOpacityIndex]; + float opacity = opacities[i]; + GUIStyle opacityButtonStyle = new GUIStyle(GUI.skin.button); + opacityButtonStyle.normal.background = MakeOpacityTex(10, 10, opacity); + + if (GUILayout.Button("", opacityButtonStyle, GUILayout.Width(14), GUILayout.Height(14))) + { + selectedOpacityIndex = i; + selectedOpacity = opacities[selectedOpacityIndex]; + } } } + GUILayout.EndHorizontal(); } - GUILayout.EndHorizontal(); - } - EditorGUILayout.EndVertical(); + EditorGUILayout.EndVertical(); - return position; - } + return position; + } - private Texture2D MakeTex(int width, int height, Color col) - { - Color[] pix = new Color[width * height]; - for (int i = 0; i < pix.Length; i++) + private Texture2D MakeTex(int width, int height, Color col) { - pix[i] = col; + Color[] pix = new Color[width * height]; + for (int i = 0; i < pix.Length; i++) + { + pix[i] = col; + } + Texture2D result = new Texture2D(width, height); + result.SetPixels(pix); + result.Apply(); + return result; } - Texture2D result = new Texture2D(width, height); - result.SetPixels(pix); - result.Apply(); - return result; - } - private Texture2D MakeOpacityTex(int width, int height, float opacity) - { - Color[] pix = new Color[width * height]; - for (int i = 0; i < pix.Length; i++) + private Texture2D MakeOpacityTex(int width, int height, float opacity) { - pix[i] = new Color(1, 1, 1, opacity); + Color[] pix = new Color[width * height]; + for (int i = 0; i < pix.Length; i++) + { + pix[i] = new Color(1, 1, 1, opacity); + } + Texture2D result = new Texture2D(width, height); + result.SetPixels(pix); + result.Apply(); + return result; } - Texture2D result = new Texture2D(width, height); - result.SetPixels(pix); - result.Apply(); - return result; - } - - private Texture2D MakeCircularTex(int diameter, Color col) - { - if (diameter <= 0) return null; - int radius = diameter / 2; - Color[] pix = new Color[diameter * diameter]; - for (int y = 0; y < diameter; y++) + private Texture2D MakeCircularTex(int diameter, Color col) { - for (int x = 0; x < diameter; x++) + if (diameter <= 0) return null; + + int radius = diameter / 2; + Color[] pix = new Color[diameter * diameter]; + for (int y = 0; y < diameter; y++) { - int dx = x - radius; - int dy = y - radius; - if (dx * dx + dy * dy < radius * radius) + for (int x = 0; x < diameter; x++) { - pix[y * diameter + x] = col; - } - else - { - pix[y * diameter + x] = Color.clear; + int dx = x - radius; + int dy = y - radius; + if (dx * dx + dy * dy < radius * radius) + { + pix[y * diameter + x] = col; + } + else + { + pix[y * diameter + x] = Color.clear; + } } } + Texture2D result = new Texture2D(diameter, diameter, TextureFormat.RGBA32, false, true); + result.SetPixels(pix); + result.Apply(); + return result; } - Texture2D result = new Texture2D(diameter, diameter, TextureFormat.RGBA32, false, true); - result.SetPixels(pix); - result.Apply(); - return result; - } - private Texture2D MakeCursorTex(int diameter, Color col) - { - if (diameter <= 0) return null; - - int radius = diameter / 2; - Color[] pix = new Color[diameter * diameter]; - for (int y = 0; y < diameter; y++) + private Texture2D MakeCursorTex(int diameter, Color col) { - for (int x = 0; x < diameter; x++) + if (diameter <= 0) return null; + + int radius = diameter / 2; + Color[] pix = new Color[diameter * diameter]; + for (int y = 0; y < diameter; y++) { - int dx = x - radius; - int dy = y - radius; - if (dx * dx + dy * dy < radius * radius) - { - pix[y * diameter + x] = col; - } - else + for (int x = 0; x < diameter; x++) { - pix[y * diameter + x] = Color.clear; + int dx = x - radius; + int dy = y - radius; + if (dx * dx + dy * dy < radius * radius) + { + pix[y * diameter + x] = col; + } + else + { + pix[y * diameter + x] = Color.clear; + } } } + Texture2D result = new Texture2D(diameter, diameter, TextureFormat.RGBA32, false, true); + result.SetPixels(pix); + result.Apply(); + return result; } - Texture2D result = new Texture2D(diameter, diameter, TextureFormat.RGBA32, false, true); - result.SetPixels(pix); - result.Apply(); - return result; - } - private void DrawOnTexture(Texture2D tex, Vector2 position, int brushSize, Color color, float opacity) - { - if (newStroke && (currentDrawingMode == DrawingMode.Draw || currentDrawingMode == DrawingMode.Erase)) + private void DrawOnTexture(Texture2D tex, Vector2 position, int brushSize, Color color, float opacity) { - // Clear the redo history - if (canvasHistoryIndex < canvasHistory.Count - 1) + if (newStroke && (currentDrawingMode == DrawingMode.Draw || currentDrawingMode == DrawingMode.Erase)) { - canvasHistory.RemoveRange(canvasHistoryIndex + 1, canvasHistory.Count - canvasHistoryIndex - 1); - } + // Clear the redo history + if (canvasHistoryIndex < canvasHistory.Count - 1) + { + canvasHistory.RemoveRange(canvasHistoryIndex + 1, canvasHistory.Count - canvasHistoryIndex - 1); + } - AddToCanvasHistory(); - newStroke = false; - } + AddToCanvasHistory(); + newStroke = false; + } - int xStart = Mathf.Clamp((int)position.x - brushSize / 2, 0, tex.width); - int xEnd = Mathf.Clamp((int)position.x + brushSize / 2, 0, tex.width); - int yStart = Mathf.Clamp((int)position.y - brushSize / 2, 0, tex.height); - int yEnd = Mathf.Clamp((int)position.y + brushSize / 2, 0, tex.height); + int xStart = Mathf.Clamp((int)position.x - brushSize / 2, 0, tex.width); + int xEnd = Mathf.Clamp((int)position.x + brushSize / 2, 0, tex.width); + int yStart = Mathf.Clamp((int)position.y - brushSize / 2, 0, tex.height); + int yEnd = Mathf.Clamp((int)position.y + brushSize / 2, 0, tex.height); - Color colorWithOpacity = new Color(color.r, color.g, color.b, opacity); + Color colorWithOpacity = new Color(color.r, color.g, color.b, opacity); - for (int x = xStart; x < xEnd; x++) - { - for (int y = yStart; y < yEnd; y++) + for (int x = xStart; x < xEnd; x++) { - if (Vector2.Distance(new Vector2(x, y), position) <= brushSize / 2) + for (int y = yStart; y < yEnd; y++) { - Color currentColor = tex.GetPixel(x, y); - Color blendedColor; - - if (currentDrawingMode == DrawingMode.Erase) - { - blendedColor = new Color(currentColor.r, currentColor.g, currentColor.b, 0); - } - else + if (Vector2.Distance(new Vector2(x, y), position) <= brushSize / 2) { - blendedColor = Color.Lerp(currentColor, colorWithOpacity, colorWithOpacity.a); - } + Color currentColor = tex.GetPixel(x, y); + Color blendedColor; + + if (currentDrawingMode == DrawingMode.Erase) + { + blendedColor = new Color(currentColor.r, currentColor.g, currentColor.b, 0); + } + else + { + blendedColor = Color.Lerp(currentColor, colorWithOpacity, colorWithOpacity.a); + } - tex.SetPixel(x, y, blendedColor); + tex.SetPixel(x, y, blendedColor); + } } } - } - tex.Apply(); - } + tex.Apply(); + } - private int FindNextSize(int currentSize) - { - foreach (int size in allowedSizes) + private int FindNextSize(int currentSize) { - if (size > currentSize) - return size; + foreach (int size in allowedSizes) + { + if (size > currentSize) + return size; + } + return currentSize; } - return currentSize; - } - private int FindPreviousSize(int currentSize) - { - for (int i = allowedSizes.Length - 1; i >= 0; i--) + private int FindPreviousSize(int currentSize) { - if (allowedSizes[i] < currentSize) - return allowedSizes[i]; + for (int i = allowedSizes.Length - 1; i >= 0; i--) + { + if (allowedSizes[i] < currentSize) + return allowedSizes[i]; + } + return currentSize; } - return currentSize; - } - private Texture2D ResizeImage(Texture2D original, int newWidth, int newHeight, bool addBottom = false, bool addLeft = false) - { - Texture2D resizedImage = new Texture2D(newWidth, newHeight); - Color[] originalPixels = original.GetPixels(); - Color[] newPixels = new Color[newWidth * newHeight]; - int xOffset = addLeft ? newWidth - original.width : 0; - int yOffset = addBottom ? newHeight - original.height : 0; - for (int y = 0; y < newHeight; y++) + private Texture2D ResizeImage(Texture2D original, int newWidth, int newHeight, bool addBottom = false, bool addLeft = false) { - for (int x = 0; x < newWidth; x++) + Texture2D resizedImage = new Texture2D(newWidth, newHeight); + Color[] originalPixels = original.GetPixels(); + Color[] newPixels = new Color[newWidth * newHeight]; + int xOffset = addLeft ? newWidth - original.width : 0; + int yOffset = addBottom ? newHeight - original.height : 0; + for (int y = 0; y < newHeight; y++) { - if (x >= xOffset && x < xOffset + original.width && y >= yOffset && y < yOffset + original.height) + for (int x = 0; x < newWidth; x++) { - newPixels[y * newWidth + x] = originalPixels[(y - yOffset) * original.width + (x - xOffset)]; - } - else - { - newPixels[y * newWidth + x] = Color.white; + if (x >= xOffset && x < xOffset + original.width && y >= yOffset && y < yOffset + original.height) + { + newPixels[y * newWidth + x] = originalPixels[(y - yOffset) * original.width + (x - xOffset)]; + } + else + { + newPixels[y * newWidth + x] = Color.white; + } } } + resizedImage.SetPixels(newPixels); + resizedImage.Apply(); + return resizedImage; } - resizedImage.SetPixels(newPixels); - resizedImage.Apply(); - return resizedImage; - } - - private void CreateTransparentImage(int width, int height) - { - transparentImage = new Texture2D(width, height, TextureFormat.ARGB32, false); - Color32[] pixels = new Color32[width * height]; - for (int i = 0; i < pixels.Length; i++) + private void CreateTransparentImage(int width, int height) { - pixels[i] = new Color32(0, 0, 0, 0); + transparentImage = new Texture2D(width, height, TextureFormat.ARGB32, false); + Color32[] pixels = new Color32[width * height]; + + for (int i = 0; i < pixels.Length; i++) + { + pixels[i] = new Color32(0, 0, 0, 0); + } + + transparentImage.SetPixels32(pixels); + transparentImage.Apply(); } - transparentImage.SetPixels32(pixels); - transparentImage.Apply(); - } + private void AddToCanvasHistory() + { + canvasHistory.RemoveRange(canvasHistoryIndex + 1, canvasHistory.Count - canvasHistoryIndex - 1); - private void AddToCanvasHistory() - { - canvasHistory.RemoveRange(canvasHistoryIndex + 1, canvasHistory.Count - canvasHistoryIndex - 1); + Texture2D newHistoryImage = new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); + newHistoryImage.SetPixels(canvasImage.GetPixels()); + newHistoryImage.Apply(); + canvasHistory.Add(newHistoryImage); + canvasHistoryIndex++; - Texture2D newHistoryImage = new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); - newHistoryImage.SetPixels(canvasImage.GetPixels()); - newHistoryImage.Apply(); - canvasHistory.Add(newHistoryImage); - canvasHistoryIndex++; + const int maxHistorySize = 10; + if (canvasHistory.Count > maxHistorySize) + { + canvasHistory.RemoveAt(0); + canvasHistoryIndex--; + } + } - const int maxHistorySize = 10; - if (canvasHistory.Count > maxHistorySize) + private void UndoCanvas() { - canvasHistory.RemoveAt(0); + if (canvasHistoryIndex <= 0) return; + + // Save the current state to the redo stack + Texture2D redoImage = new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); + redoImage.SetPixels(canvasImage.GetPixels()); + redoImage.Apply(); + redoHistory.Add(redoImage); + + // Revert to the previous state canvasHistoryIndex--; + canvasImage.SetPixels(canvasHistory[canvasHistoryIndex].GetPixels()); + canvasImage.Apply(); } - } - private void UndoCanvas() - { - if (canvasHistoryIndex <= 0) return; + private void RedoCanvas() + { + if (redoHistory.Count <= 0) return; - // Save the current state to the redo stack - Texture2D redoImage = new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); - redoImage.SetPixels(canvasImage.GetPixels()); - redoImage.Apply(); - redoHistory.Add(redoImage); - - // Revert to the previous state - canvasHistoryIndex--; - canvasImage.SetPixels(canvasHistory[canvasHistoryIndex].GetPixels()); - canvasImage.Apply(); - } + // Save the current state to the undo stack + Texture2D undoImage = new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); + undoImage.SetPixels(canvasImage.GetPixels()); + undoImage.Apply(); + canvasHistory.Add(undoImage); + canvasHistoryIndex++; + + // Update to the next state + Texture2D redoImage = redoHistory[redoHistory.Count - 1]; + redoHistory.RemoveAt(redoHistory.Count - 1); + canvasImage.SetPixels(redoImage.GetPixels()); + canvasImage.Apply(); + } - private void RedoCanvas() - { - if (redoHistory.Count <= 0) return; - - // Save the current state to the undo stack - Texture2D undoImage = new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); - undoImage.SetPixels(canvasImage.GetPixels()); - undoImage.Apply(); - canvasHistory.Add(undoImage); - canvasHistoryIndex++; - - // Update to the next state - Texture2D redoImage = redoHistory[redoHistory.Count - 1]; - redoHistory.RemoveAt(redoHistory.Count - 1); - canvasImage.SetPixels(redoImage.GetPixels()); - canvasImage.Apply(); - } + // Add the corresponding methods for the action buttons + private void CreateImage() + { + int width = 512; + int height = 512; + uploadedImage = new Texture2D(width, height, TextureFormat.RGBA32, false); + Color[] pixels = new Color[width * height]; - // Add the corresponding methods for the action buttons - private void CreateImage() - { - int width = 512; - int height = 512; - uploadedImage = new Texture2D(width, height, TextureFormat.RGBA32, false); - Color[] pixels = new Color[width * height]; + for (int i = 0; i < pixels.Length; i++) + { + pixels[i] = Color.white; + } - for (int i = 0; i < pixels.Length; i++) - { - pixels[i] = Color.white; + uploadedImage.SetPixels(pixels); + uploadedImage.Apply(); } - uploadedImage.SetPixels(pixels); - uploadedImage.Apply(); - } - - /*private void FillAll() + /*private void FillAll() { // Add logic to fill all }*/ - private void Clear() - { - uploadedImage = null; - canvasImage = null; - canvasHistory.Clear(); - canvasHistoryIndex = -1; - } - - private void Cancel() - { - imageEditor.Close(); - } + private void Clear() + { + uploadedImage = null; + canvasImage = null; + canvasHistory.Clear(); + canvasHistoryIndex = -1; + } - private void Use() - { - if (uploadedImage == null || canvasImage == null) + private void Cancel() { - Debug.Log("MUST HAVE AN UPLOADED IMAGE AND A CANVAS IMAGE FOR MASKING"); - return; + imageEditor.Close(); } - // Create a new texture that combines the uploaded image and the canvas image - Texture2D combinedImage = new Texture2D(uploadedImage.width, uploadedImage.height, TextureFormat.RGBA32, false); - for (int y = 0; y < combinedImage.height; y++) + private void Use() { - for (int x = 0; x < combinedImage.width; x++) + if (uploadedImage == null || canvasImage == null) { - Color backgroundColor = uploadedImage.GetPixel(x, y); - Color foregroundColor = canvasImage.GetPixel(x, y); - Color combinedColor = Color.Lerp(backgroundColor, foregroundColor, foregroundColor.a); - combinedImage.SetPixel(x, y, combinedColor); + Debug.Log("MUST HAVE AN UPLOADED IMAGE AND A CANVAS IMAGE FOR MASKING"); + return; } + + // Create a new texture that combines the uploaded image and the canvas image + Texture2D combinedImage = new Texture2D(uploadedImage.width, uploadedImage.height, TextureFormat.RGBA32, false); + for (int y = 0; y < combinedImage.height; y++) + { + for (int x = 0; x < combinedImage.width; x++) + { + Color backgroundColor = uploadedImage.GetPixel(x, y); + Color foregroundColor = canvasImage.GetPixel(x, y); + Color combinedColor = Color.Lerp(backgroundColor, foregroundColor, foregroundColor.a); + combinedImage.SetPixel(x, y, combinedColor); + } + } + combinedImage.Apply(); + + PromptWindowUI.imageUpload = combinedImage; + imageEditor.Close(); } - combinedImage.Apply(); - PromptWindowUI.imageUpload = combinedImage; - imageEditor.Close(); } - } \ No newline at end of file diff --git a/Scenario/Editor/Images/ImageDataClasses.cs b/Scenario/Editor/Images/ImageDataClasses.cs index b3c3352..2b4c1e9 100644 --- a/Scenario/Editor/Images/ImageDataClasses.cs +++ b/Scenario/Editor/Images/ImageDataClasses.cs @@ -1,36 +1,39 @@ using System.Collections.Generic; -public static class ImageDataStorage +namespace Scenario { - public static List imageDataList = new List(); - - public class ImageData + public static class ImageDataStorage { - public string Id { get; set; } - public string Url { get; set; } - public string InferenceId { get; set; } + public static List imageDataList = new List(); + + public class ImageData + { + public string Id { get; set; } + public string Url { get; set; } + public string InferenceId { get; set; } + } } -} -public class InferencesResponse -{ - public List inferences { get; set; } - public string nextPaginationToken { get; set; } -} + public class InferencesResponse + { + public List inferences { get; set; } + public string nextPaginationToken { get; set; } + } -public class Inference -{ - public string id { get; set; } - public List images { get; set; } -} + public class Inference + { + public string id { get; set; } + public List images { get; set; } + } -public class Image -{ - public string id { get; set; } - public string url { get; set; } -} + public class Image + { + public string id { get; set; } + public string url { get; set; } + } -public class TokenResponse -{ - public string nextPaginationToken { get; set; } + public class TokenResponse + { + public string nextPaginationToken { get; set; } + } } \ No newline at end of file diff --git a/Scenario/Editor/Images/Images.cs b/Scenario/Editor/Images/Images.cs index 573f59f..8c6155a 100644 --- a/Scenario/Editor/Images/Images.cs +++ b/Scenario/Editor/Images/Images.cs @@ -1,134 +1,137 @@ +using System; +using System.Collections.Generic; using UnityEditor; using UnityEngine; using Newtonsoft.Json; -using System.Collections.Generic; -using System; -public class Images : EditorWindow +namespace Scenario { - private static readonly string PaginationTokenKey = "paginationToken"; - private static readonly float MinimumWidth = 1000f; - private static readonly float MinimumHeight = 700f; - private static readonly ImagesUI ImagesUI = new(); + public class Images : EditorWindow + { + private static readonly string PaginationTokenKey = "paginationToken"; + private static readonly float MinimumWidth = 1000f; + private static readonly float MinimumHeight = 700f; + private static readonly ImagesUI ImagesUI = new(); - private static string _paginationToken = ""; - private static List _imageDataList = ImageDataStorage.imageDataList; + private static string _paginationToken = ""; + private static List _imageDataList = ImageDataStorage.imageDataList; - [MenuItem("Window/Scenario/Images")] - public static void ShowWindow() - { - Images window = GetWindow("Images"); + [MenuItem("Window/Scenario/Images")] + public static void ShowWindow() + { + Images window = GetWindow("Images"); - GetInferencesData(); + GetInferencesData(); - var images = EditorWindow.GetWindow(typeof(Images)); - ImagesUI.Init((Images)images); + var images = EditorWindow.GetWindow(typeof(Images)); + ImagesUI.Init((Images)images); - window.minSize = new Vector2(MinimumWidth, window.minSize.y); - window.minSize = new Vector2(window.minSize.x, MinimumHeight); - } + window.minSize = new Vector2(MinimumWidth, window.minSize.y); + window.minSize = new Vector2(window.minSize.x, MinimumHeight); + } - private void OnGUI() - { - ImagesUI.OnGUI(this.position); - } - - private void OnDestroy() - { - ImagesUI.ClearSelectedTexture(); - } - - private static void GetInferencesData() - { - string selectedModelId = EditorPrefs.GetString("SelectedModelId"); - if (selectedModelId.Length < 2) + private void OnGUI() { - Debug.LogError("Please select a model first."); - return; + ImagesUI.OnGUI(this.position); } - - string paginationTokenString = EditorPrefs.GetString(PaginationTokenKey,""); - if (paginationTokenString != "") + + private void OnDestroy() { - paginationTokenString = "&paginationToken=" + paginationTokenString; + ImagesUI.ClearSelectedTexture(); } - - ApiClient.RestGet($"inferences?nextPaginationToken={_paginationToken}", response => + + private static void GetInferencesData() { - var inferencesResponse = JsonConvert.DeserializeObject(response.Content); - _paginationToken = inferencesResponse.nextPaginationToken; + string selectedModelId = EditorPrefs.GetString("SelectedModelId"); + if (selectedModelId.Length < 2) + { + Debug.LogError("Please select a model first."); + return; + } + + string paginationTokenString = EditorPrefs.GetString(PaginationTokenKey,""); + if (paginationTokenString != "") + { + paginationTokenString = "&paginationToken=" + paginationTokenString; + } + + ApiClient.RestGet($"inferences?nextPaginationToken={_paginationToken}", response => + { + var inferencesResponse = JsonConvert.DeserializeObject(response.Content); + _paginationToken = inferencesResponse.nextPaginationToken; - ImageDataStorage.imageDataList.Clear(); - ImagesUI.textures.Clear(); + ImageDataStorage.imageDataList.Clear(); + ImagesUI.textures.Clear(); - foreach (var inference in inferencesResponse.inferences) - { - foreach (var image in inference.images) + foreach (var inference in inferencesResponse.inferences) { - ImageDataStorage.imageDataList.Add(new ImageDataStorage.ImageData + foreach (var image in inference.images) { - Id = image.id, - Url = image.url, - InferenceId = inference.id - }); + ImageDataStorage.imageDataList.Add(new ImageDataStorage.ImageData + { + Id = image.id, + Url = image.url, + InferenceId = inference.id + }); + } } - } - ImagesUI.SetFirstPage(); - ImagesUI.UpdatePage(); - }); - } + ImagesUI.SetFirstPage(); + ImagesUI.UpdatePage(); + }); + } - public void DeleteImageAtIndex(int selectedTextureIndex) - { - ImagesUI.textures.RemoveAt(selectedTextureIndex); + public void DeleteImageAtIndex(int selectedTextureIndex) + { + ImagesUI.textures.RemoveAt(selectedTextureIndex); - string imageId = _imageDataList[selectedTextureIndex].Id; - string modelId = EditorPrefs.GetString("SelectedModelId", ""); - string inferenceId = _imageDataList[selectedTextureIndex].InferenceId; + string imageId = _imageDataList[selectedTextureIndex].Id; + string modelId = EditorPrefs.GetString("SelectedModelId", ""); + string inferenceId = _imageDataList[selectedTextureIndex].InferenceId; - Debug.Log("Requesting image deletion please wait.."); + Debug.Log("Requesting image deletion please wait.."); - string url = $"models/{modelId}/inferences/{inferenceId}/images/{imageId}"; + string url = $"models/{modelId}/inferences/{inferenceId}/images/{imageId}"; - ApiClient.RestDelete(url,null); + ApiClient.RestDelete(url,null); - Repaint(); - } + Repaint(); + } - internal void RemoveBackgroundForImageAtIndex(int selectedTextureIndex) - { - string dataUrl = CommonUtils.Texture2DToDataURL(ImagesUI.textures[selectedTextureIndex]); - string fileName =CommonUtils.GetRandomImageFileName(); - string param = $"{{\"image\":\"{dataUrl}\",\"name\":\"{fileName}\",\"format\":\"png\",\"returnImage\":\"false\"}}"; + internal void RemoveBackgroundForImageAtIndex(int selectedTextureIndex) + { + string dataUrl = CommonUtils.Texture2DToDataURL(ImagesUI.textures[selectedTextureIndex]); + string fileName =CommonUtils.GetRandomImageFileName(); + string param = $"{{\"image\":\"{dataUrl}\",\"name\":\"{fileName}\",\"format\":\"png\",\"returnImage\":\"false\"}}"; - Debug.Log($"Requesting background removal, please wait.."); + Debug.Log($"Requesting background removal, please wait.."); - ApiClient.RestPut("images/erase-background",param, response => - { - if (response.ErrorException != null) - { - Debug.LogError($"Error: {response.ErrorException.Message}"); - } - else + ApiClient.RestPut("images/erase-background",param, response => { - Debug.Log($"Response: {response.Content}"); - - try + if (response.ErrorException != null) { - dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content); - string imageUrl = jsonResponse.asset.url; - - CommonUtils.FetchTextureFromURL(imageUrl, texture => - { - CommonUtils.SaveTextureAsPNG(texture); - }); + Debug.LogError($"Error: {response.ErrorException.Message}"); } - catch (Exception ex) + else { - Debug.LogError("An error occurred while processing the response: " + ex.Message); + Debug.Log($"Response: {response.Content}"); + + try + { + dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content); + string imageUrl = jsonResponse.asset.url; + + CommonUtils.FetchTextureFromURL(imageUrl, texture => + { + CommonUtils.SaveTextureAsPNG(texture); + }); + } + catch (Exception ex) + { + Debug.LogError("An error occurred while processing the response: " + ex.Message); + } } - } - }); + }); + } } } diff --git a/Scenario/Editor/Images/ImagesUI.cs b/Scenario/Editor/Images/ImagesUI.cs index 22c8907..d55c691 100644 --- a/Scenario/Editor/Images/ImagesUI.cs +++ b/Scenario/Editor/Images/ImagesUI.cs @@ -1,252 +1,255 @@ -using UnityEngine; -using UnityEditor; using System.Collections.Generic; -using static ImageDataStorage; +using UnityEditor; +using UnityEngine; +using static Scenario.ImageDataStorage; -public class ImagesUI +namespace Scenario { - public List textures = new(); - - private int itemsPerRow = 5; - private float padding = 10f; - - private Vector2 scrollPosition = Vector2.zero; - private Texture2D selectedTexture = null; + public class ImagesUI + { + public List textures = new(); - private Images images; - private int selectedTextureIndex = 0; + private int itemsPerRow = 5; + private float padding = 10f; - private int firstImageIndex = 0; - private int pageImageCount = 15; - private List pageList; + private Vector2 scrollPosition = Vector2.zero; + private Texture2D selectedTexture = null; - public void Init(Images img) - { - images = img; - } + private Images images; + private int selectedTextureIndex = 0; - public void SetFirstPage() - { - firstImageIndex = 0; - pageImageCount = 15; - } + private int firstImageIndex = 0; + private int pageImageCount = 15; + private List pageList; - public void SetNextPage() - { - firstImageIndex += pageImageCount; - if (firstImageIndex >= ImageDataStorage.imageDataList.Count - pageImageCount) + public void Init(Images img) { - firstImageIndex -= pageImageCount; + images = img; } - } - public void SetPreviousPage() - { - firstImageIndex -= pageImageCount; - if (firstImageIndex <= 0) + public void SetFirstPage() { firstImageIndex = 0; + pageImageCount = 15; } - } - public void UpdatePage() - { - pageList = ImageDataStorage.imageDataList.GetRange(firstImageIndex, pageImageCount); - FetchPageTextures(); - } + public void SetNextPage() + { + firstImageIndex += pageImageCount; + if (firstImageIndex >= ImageDataStorage.imageDataList.Count - pageImageCount) + { + firstImageIndex -= pageImageCount; + } + } - private void FetchPageTextures() - { - textures.Clear(); - foreach (var item in pageList) + public void SetPreviousPage() { - CommonUtils.FetchTextureFromURL(item.Url, texture => + firstImageIndex -= pageImageCount; + if (firstImageIndex <= 0) { - textures.Add(texture); - }); + firstImageIndex = 0; + } } - } - public void ClearSelectedTexture() - { - selectedTexture = null; - } + public void UpdatePage() + { + pageList = ImageDataStorage.imageDataList.GetRange(firstImageIndex, pageImageCount); + FetchPageTextures(); + } - public void OnGUI(Rect position) - { - DrawBackground(position); + private void FetchPageTextures() + { + textures.Clear(); + foreach (var item in pageList) + { + CommonUtils.FetchTextureFromURL(item.Url, texture => + { + textures.Add(texture); + }); + } + } - float previewWidth = 309f; - float scrollViewWidth = selectedTexture != null ? position.width - previewWidth : position.width; - float boxWidth = (scrollViewWidth - padding * (itemsPerRow - 1)) / itemsPerRow; - float boxHeight = boxWidth; + public void ClearSelectedTexture() + { + selectedTexture = null; + } - int numRows = Mathf.CeilToInt((float)textures.Count / itemsPerRow); + public void OnGUI(Rect position) + { + DrawBackground(position); - float scrollViewHeight = (boxHeight + padding) * numRows; + float previewWidth = 309f; + float scrollViewWidth = selectedTexture != null ? position.width - previewWidth : position.width; + float boxWidth = (scrollViewWidth - padding * (itemsPerRow - 1)) / itemsPerRow; + float boxHeight = boxWidth; - scrollPosition = GUI.BeginScrollView(new Rect(0, 20, scrollViewWidth, position.height - 70), scrollPosition, - new Rect(0, 0, scrollViewWidth - 20, scrollViewHeight)); + int numRows = Mathf.CeilToInt((float)textures.Count / itemsPerRow); - for (int i = 0; i < textures.Count; i++) - { - DrawTextureButton(boxWidth, boxHeight, i); - } + float scrollViewHeight = (boxHeight + padding) * numRows; - GUI.EndScrollView(); + scrollPosition = GUI.BeginScrollView(new Rect(0, 20, scrollViewWidth, position.height - 70), scrollPosition, + new Rect(0, 0, scrollViewWidth - 20, scrollViewHeight)); - GUILayout.BeginArea(new Rect(0, position.height - 50, scrollViewWidth, 50)); - { - GUILayout.BeginHorizontal(); - if (firstImageIndex > 0 && GUILayout.Button("Previous Page")) + for (int i = 0; i < textures.Count; i++) { - SetPreviousPage(); - UpdatePage(); + DrawTextureButton(boxWidth, boxHeight, i); } - if (firstImageIndex < imageDataList.Count - pageImageCount && GUILayout.Button("Next Page")) + + GUI.EndScrollView(); + + GUILayout.BeginArea(new Rect(0, position.height - 50, scrollViewWidth, 50)); { - SetNextPage(); - UpdatePage(); + GUILayout.BeginHorizontal(); + if (firstImageIndex > 0 && GUILayout.Button("Previous Page")) + { + SetPreviousPage(); + UpdatePage(); + } + if (firstImageIndex < imageDataList.Count - pageImageCount && GUILayout.Button("Next Page")) + { + SetNextPage(); + UpdatePage(); + } + GUILayout.EndHorizontal(); } - GUILayout.EndHorizontal(); - } - GUILayout.EndArea(); + GUILayout.EndArea(); - GUILayout.FlexibleSpace(); + GUILayout.FlexibleSpace(); - DrawSelectedTextureSection(position, previewWidth, scrollViewWidth); - } - - private static void DrawBackground(Rect position) - { - Color backgroundColor = EditorStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } + DrawSelectedTextureSection(position, previewWidth, scrollViewWidth); + } - private void DrawSelectedTextureSection(Rect position, float previewWidth, float scrollViewWidth) - { - if (selectedTexture == null) + private static void DrawBackground(Rect position) { - return; + Color backgroundColor = EditorStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); } - GUILayout.BeginArea(new Rect(scrollViewWidth, 20, previewWidth, position.height - 20)); + private void DrawSelectedTextureSection(Rect position, float previewWidth, float scrollViewWidth) { - DrawScrollableArea(previewWidth); + if (selectedTexture == null) + { + return; + } + + GUILayout.BeginArea(new Rect(scrollViewWidth, 20, previewWidth, position.height - 20)); + { + DrawScrollableArea(previewWidth); + } + GUILayout.EndArea(); } - GUILayout.EndArea(); - } - private void DrawScrollableArea(float previewWidth) - { - DrawSelectedImage(previewWidth); - CustomStyle.Space(10); - GUILayout.BeginVertical(); + private void DrawScrollableArea(float previewWidth) { - DrawFirstButtons(); + DrawSelectedImage(previewWidth); CustomStyle.Space(10); - DrawSecondButtons(); + GUILayout.BeginVertical(); + { + DrawFirstButtons(); + CustomStyle.Space(10); + DrawSecondButtons(); + CustomStyle.Space(10); + } + GUILayout.EndVertical(); CustomStyle.Space(10); } - GUILayout.EndVertical(); - CustomStyle.Space(10); - } - private void DrawSecondButtons() - { - string[] buttonNames = { "Remove Background", "Pixelate Image", "Upscale Image" /*, "Generate More Images"*/ }; - System.Action[] buttonCallbacks = + private void DrawSecondButtons() { - () => images.RemoveBackgroundForImageAtIndex(selectedTextureIndex + firstImageIndex), - () => PixelEditor.ShowWindow(selectedTexture, ImageDataStorage.imageDataList[selectedTextureIndex + firstImageIndex]), - () => UpscaleEditor.ShowWindow(selectedTexture, ImageDataStorage.imageDataList[selectedTextureIndex + firstImageIndex]) /*, + string[] buttonNames = { "Remove Background", "Pixelate Image", "Upscale Image" /*, "Generate More Images"*/ }; + System.Action[] buttonCallbacks = + { + () => images.RemoveBackgroundForImageAtIndex(selectedTextureIndex + firstImageIndex), + () => PixelEditor.ShowWindow(selectedTexture, ImageDataStorage.imageDataList[selectedTextureIndex + firstImageIndex]), + () => UpscaleEditor.ShowWindow(selectedTexture, ImageDataStorage.imageDataList[selectedTextureIndex + firstImageIndex]) /*, () => { // TODO: Implement generate more images functionality }*/ - }; + }; - for (int i = 0; i < buttonNames.Length; i++) - { - if (GUILayout.Button(buttonNames[i], GUILayout.Height(40))) + for (int i = 0; i < buttonNames.Length; i++) { - buttonCallbacks[i](); + if (GUILayout.Button(buttonNames[i], GUILayout.Height(40))) + { + buttonCallbacks[i](); + } + CustomStyle.Space(10); } - CustomStyle.Space(10); } - } - - private void DrawFirstButtons() - { - string[] buttonNames = { "Refine Image", "Download", "Delete" }; - System.Action[] buttonCallbacks = - { - () => PromptWindowUI.imageUpload = selectedTexture, - () => CommonUtils.SaveTextureAsPNG(selectedTexture), - () => - { - images.DeleteImageAtIndex(selectedTextureIndex + firstImageIndex); - selectedTexture = null; - } - }; - GUILayout.BeginHorizontal(); - for (int i = 0; i < buttonNames.Length; i++) + private void DrawFirstButtons() { - if (GUILayout.Button(buttonNames[i], GUILayout.Height(40))) + string[] buttonNames = { "Refine Image", "Download", "Delete" }; + System.Action[] buttonCallbacks = { - buttonCallbacks[i](); - } + () => PromptWindowUI.imageUpload = selectedTexture, + () => CommonUtils.SaveTextureAsPNG(selectedTexture), + () => + { + images.DeleteImageAtIndex(selectedTextureIndex + firstImageIndex); + selectedTexture = null; + } + }; - // Add spacing between buttons but not after the last button - if (i < buttonNames.Length - 1) + GUILayout.BeginHorizontal(); + for (int i = 0; i < buttonNames.Length; i++) { - CustomStyle.Space(5); + if (GUILayout.Button(buttonNames[i], GUILayout.Height(40))) + { + buttonCallbacks[i](); + } + + // Add spacing between buttons but not after the last button + if (i < buttonNames.Length - 1) + { + CustomStyle.Space(5); + } } + GUILayout.EndHorizontal(); } - GUILayout.EndHorizontal(); - } - private void DrawSelectedImage(float previewWidth) - { - GUILayout.Label("Selected Image", EditorStyles.boldLabel); + private void DrawSelectedImage(float previewWidth) + { + GUILayout.Label("Selected Image", EditorStyles.boldLabel); - CustomStyle.Space(10); + CustomStyle.Space(10); - float aspectRatio = (float)selectedTexture.width / selectedTexture.height; - float paddedPreviewWidth = previewWidth - 2 * padding; - float paddedPreviewHeight = paddedPreviewWidth / aspectRatio; + float aspectRatio = (float)selectedTexture.width / selectedTexture.height; + float paddedPreviewWidth = previewWidth - 2 * padding; + float paddedPreviewHeight = paddedPreviewWidth / aspectRatio; - GUILayout.BeginHorizontal(); - { - CustomStyle.Space(padding); - GUILayout.Label(selectedTexture, GUILayout.Width(paddedPreviewWidth), - GUILayout.Height(paddedPreviewHeight)); - CustomStyle.Space(padding); + GUILayout.BeginHorizontal(); + { + CustomStyle.Space(padding); + GUILayout.Label(selectedTexture, GUILayout.Width(paddedPreviewWidth), + GUILayout.Height(paddedPreviewHeight)); + CustomStyle.Space(padding); + } + GUILayout.EndHorizontal(); } - GUILayout.EndHorizontal(); - } - private void DrawTextureButton(float boxWidth, float boxHeight, int i) - { - int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); - int colIndex = i % itemsPerRow; + private void DrawTextureButton(float boxWidth, float boxHeight, int i) + { + int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); + int colIndex = i % itemsPerRow; - Rect boxRect = new Rect(colIndex * (boxWidth + padding), rowIndex * (boxHeight + padding), boxWidth, boxHeight); - Texture2D texture = textures[i]; + Rect boxRect = new Rect(colIndex * (boxWidth + padding), rowIndex * (boxHeight + padding), boxWidth, boxHeight); + Texture2D texture = textures[i]; - if (texture == null) - { - GUI.Box(boxRect, "Loading..."); - } - else - { - if (GUI.Button(boxRect, "")) + if (texture == null) { - selectedTexture = texture; - selectedTextureIndex = i; + GUI.Box(boxRect, "Loading..."); } + else + { + if (GUI.Button(boxRect, "")) + { + selectedTexture = texture; + selectedTextureIndex = i; + } - GUI.DrawTexture(boxRect, texture, ScaleMode.ScaleToFit); + GUI.DrawTexture(boxRect, texture, ScaleMode.ScaleToFit); + } } } } \ No newline at end of file diff --git a/Scenario/Editor/InpaintingEditor/InpaintingEditor.cs b/Scenario/Editor/InpaintingEditor/InpaintingEditor.cs index 3628727..0fc017b 100644 --- a/Scenario/Editor/InpaintingEditor/InpaintingEditor.cs +++ b/Scenario/Editor/InpaintingEditor/InpaintingEditor.cs @@ -1,36 +1,39 @@ using UnityEditor; using UnityEngine; -public class InpaintingEditor : EditorWindow +namespace Scenario { - private static readonly float MinimumWidth = 1775f; - private static InpaintingEditorUI inpaintingEditorUI; - private static Texture2D inpaintingTexture; - - [MenuItem("Window/Scenario/Inpainting Editor")] - public static void ShowWindow() + public class InpaintingEditor : EditorWindow { - InpaintingEditor window = GetWindow("Inpainting Editor"); - window.minSize = new Vector2(MinimumWidth, window.minSize.y); - } + private static readonly float MinimumWidth = 1775f; + private static InpaintingEditorUI inpaintingEditorUI; + private static Texture2D inpaintingTexture; - public static void ShowWindow(Texture2D texture2D) - { - InpaintingEditor window = GetWindow("Inpainting Editor"); - inpaintingTexture = texture2D; - if (inpaintingTexture != null) + [MenuItem("Window/Scenario/Inpainting Editor")] + public static void ShowWindow() { - inpaintingEditorUI.SetImage(inpaintingTexture); + InpaintingEditor window = GetWindow("Inpainting Editor"); + window.minSize = new Vector2(MinimumWidth, window.minSize.y); } - } - private void OnEnable() - { - inpaintingEditorUI = new InpaintingEditorUI(this); - } + public static void ShowWindow(Texture2D texture2D) + { + InpaintingEditor window = GetWindow("Inpainting Editor"); + inpaintingTexture = texture2D; + if (inpaintingTexture != null) + { + inpaintingEditorUI.SetImage(inpaintingTexture); + } + } - private void OnGUI() - { - inpaintingEditorUI.DrawUI(this.position); + private void OnEnable() + { + inpaintingEditorUI = new InpaintingEditorUI(this); + } + + private void OnGUI() + { + inpaintingEditorUI.DrawUI(this.position); + } } } \ No newline at end of file diff --git a/Scenario/Editor/InpaintingEditor/InpaintingEditorUI.cs b/Scenario/Editor/InpaintingEditor/InpaintingEditorUI.cs index 694fc4e..1e69c32 100644 --- a/Scenario/Editor/InpaintingEditor/InpaintingEditorUI.cs +++ b/Scenario/Editor/InpaintingEditor/InpaintingEditorUI.cs @@ -1,846 +1,849 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; -using System.Collections.Generic; using UnityEditor; using UnityEngine; -public class InpaintingEditorUI +namespace Scenario { - private int selectedBrushSize; - private int canvasHistoryIndex; - private bool newStroke = true; - private float selectedOpacity = 1.0f; - private string uploadedImagePath; - private Texture2D uploadedImage; - private Texture2D brushCursor; - private Texture2D canvasImage; - private Texture2D maskBuffer; - private Texture2D transparentImage; - private List canvasHistory; - private List redoHistory; - private Color selectedColor = Color.white; - - private InpaintingEditor inpaintingEditor; - - private enum DrawingMode - { - Draw, - Erase, - Fill, - Picker, - Expand, - Crop - } - - private DrawingMode currentDrawingMode = DrawingMode.Draw; - private int[] allowedSizes = { 256, 384, 512, 570, 640, 704, 768, 912, 1024 }; - - private struct ToolButton - { - public string text; - public string tooltip; - public DrawingMode mode; - public Action onClick; - } - - private ToolButton[] toolButtons; - - private struct ActionButton - { - public string text; - public string tooltip; - public Action onClick; - } - - private ActionButton[] actionButtons; - - public InpaintingEditorUI(InpaintingEditor inpaintingEditor) - { - this.inpaintingEditor = inpaintingEditor; + public class InpaintingEditorUI + { + private int selectedBrushSize; + private int canvasHistoryIndex; + private bool newStroke = true; + private float selectedOpacity = 1.0f; + private string uploadedImagePath; + private Texture2D uploadedImage; + private Texture2D brushCursor; + private Texture2D canvasImage; + private Texture2D maskBuffer; + private Texture2D transparentImage; + private List canvasHistory; + private List redoHistory; + private Color selectedColor = Color.white; + + private InpaintingEditor inpaintingEditor; + + private enum DrawingMode + { + Draw, + Erase, + Fill, + Picker, + Expand, + Crop + } - transparentImage = new Texture2D(1, 1); - selectedBrushSize = 6; - canvasHistory = new List(); - canvasHistoryIndex = -1; - redoHistory = new List(); + private DrawingMode currentDrawingMode = DrawingMode.Draw; + private int[] allowedSizes = { 256, 384, 512, 570, 640, 704, 768, 912, 1024 }; - toolButtons = new[] + private struct ToolButton { - new ToolButton { text = "✎", tooltip = "To draw the mask", mode = DrawingMode.Draw }, - new ToolButton { text = "✐", tooltip = "To erase mask marks.", mode = DrawingMode.Erase }, - new ToolButton { text = "[]", tooltip = "To expand the image", mode = DrawingMode.Expand }, - new ToolButton { text = "-", tooltip = "To crop the image", mode = DrawingMode.Crop } - }; + public string text; + public string tooltip; + public DrawingMode mode; + public Action onClick; + } - actionButtons = new[] + private ToolButton[] toolButtons; + + private struct ActionButton { - new ActionButton - { text = "Load mask from file", tooltip = "Load mask from file", onClick = LoadMaskFromFile }, - new ActionButton { text = "Save mask to file", tooltip = "Save mask to file", onClick = SaveMaskToFile }, - new ActionButton { text = "Clear", tooltip = "Clear", onClick = Clear }, - new ActionButton { text = "Undo", tooltip = "Undo", onClick = UndoCanvas }, - new ActionButton { text = "Redo", tooltip = "Redo", onClick = RedoCanvas }, - new ActionButton { text = "Cancel", tooltip = "Cancel", onClick = Cancel }, - new ActionButton { text = "Use", tooltip = "Use", onClick = Use } - }; - } + public string text; + public string tooltip; + public Action onClick; + } - internal void SetImage(Texture2D imageData) - { - uploadedImage = imageData; - uploadedImage.alphaIsTransparency = true; + private ActionButton[] actionButtons; - canvasImage = new Texture2D(uploadedImage.width, uploadedImage.height, TextureFormat.RGBA32, false, true); - canvasImage.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height).ToArray()); - canvasImage.Apply(); + public InpaintingEditorUI(InpaintingEditor inpaintingEditor) + { + this.inpaintingEditor = inpaintingEditor; - maskBuffer = new Texture2D(uploadedImage.width, uploadedImage.height, TextureFormat.RGBA32, false, true); - maskBuffer.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height).ToArray()); - maskBuffer.Apply(); + transparentImage = new Texture2D(1, 1); + selectedBrushSize = 6; + canvasHistory = new List(); + canvasHistoryIndex = -1; + redoHistory = new List(); - canvasHistory.Clear(); - canvasHistoryIndex = -1; - AddToCanvasHistory(); - } + toolButtons = new[] + { + new ToolButton { text = "✎", tooltip = "To draw the mask", mode = DrawingMode.Draw }, + new ToolButton { text = "✐", tooltip = "To erase mask marks.", mode = DrawingMode.Erase }, + new ToolButton { text = "[]", tooltip = "To expand the image", mode = DrawingMode.Expand }, + new ToolButton { text = "-", tooltip = "To crop the image", mode = DrawingMode.Crop } + }; - public void DrawUI(Rect position) - { - DrawBackground(position); + actionButtons = new[] + { + new ActionButton + { text = "Load mask from file", tooltip = "Load mask from file", onClick = LoadMaskFromFile }, + new ActionButton { text = "Save mask to file", tooltip = "Save mask to file", onClick = SaveMaskToFile }, + new ActionButton { text = "Clear", tooltip = "Clear", onClick = Clear }, + new ActionButton { text = "Undo", tooltip = "Undo", onClick = UndoCanvas }, + new ActionButton { text = "Redo", tooltip = "Redo", onClick = RedoCanvas }, + new ActionButton { text = "Cancel", tooltip = "Cancel", onClick = Cancel }, + new ActionButton { text = "Use", tooltip = "Use", onClick = Use } + }; + } - float leftSectionWidth = position.width * 0.1f; - float middleSectionWidth = position.width * 0.8f; - float rightSectionWidth = position.width * 0.1f; - EditorGUILayout.BeginHorizontal(); + internal void SetImage(Texture2D imageData) { - DrawLeftSection(leftSectionWidth); + uploadedImage = imageData; + uploadedImage.alphaIsTransparency = true; - // Flexible space between left and middle section - GUILayout.FlexibleSpace(); - DrawMiddleSection(position, middleSectionWidth); + canvasImage = new Texture2D(uploadedImage.width, uploadedImage.height, TextureFormat.RGBA32, false, true); + canvasImage.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height).ToArray()); + canvasImage.Apply(); - GUILayout.FlexibleSpace(); - DrawRightSection(rightSectionWidth); - } - EditorGUILayout.EndHorizontal(); - } + maskBuffer = new Texture2D(uploadedImage.width, uploadedImage.height, TextureFormat.RGBA32, false, true); + maskBuffer.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height).ToArray()); + maskBuffer.Apply(); - private static void DrawBackground(Rect position) - { - Color backgroundColor = EditorStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } - - private void DrawRightSection(float rightSectionWidth) - { - // Right Section - EditorGUILayout.BeginVertical(GUILayout.Width(rightSectionWidth)); - CustomStyle.Space(18); - EditorStyle.Label("Actions", bold: true); + canvasHistory.Clear(); + canvasHistoryIndex = -1; + AddToCanvasHistory(); + } - for (int i = 0; i < actionButtons.Length; i++) + public void DrawUI(Rect position) { - ActionButton button = actionButtons[i]; - if (GUILayout.Button(new GUIContent(button.text, button.tooltip), GUILayout.Width(140), - GUILayout.Height(40))) + DrawBackground(position); + + float leftSectionWidth = position.width * 0.1f; + float middleSectionWidth = position.width * 0.8f; + float rightSectionWidth = position.width * 0.1f; + EditorGUILayout.BeginHorizontal(); { - button.onClick?.Invoke(); + DrawLeftSection(leftSectionWidth); + + // Flexible space between left and middle section + GUILayout.FlexibleSpace(); + DrawMiddleSection(position, middleSectionWidth); + + GUILayout.FlexibleSpace(); + DrawRightSection(rightSectionWidth); } + EditorGUILayout.EndHorizontal(); } - EditorGUILayout.EndVertical(); - } + private static void DrawBackground(Rect position) + { + Color backgroundColor = EditorStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); + } - private void DrawMiddleSection(Rect position, float middleSectionWidth) - { - // Middle Section - EditorGUILayout.BeginVertical(GUILayout.Width(middleSectionWidth)); + private void DrawRightSection(float rightSectionWidth) { + // Right Section + EditorGUILayout.BeginVertical(GUILayout.Width(rightSectionWidth)); CustomStyle.Space(18); + EditorStyle.Label("Actions", bold: true); - if (uploadedImage != null) + for (int i = 0; i < actionButtons.Length; i++) { - switch (currentDrawingMode) + ActionButton button = actionButtons[i]; + if (GUILayout.Button(new GUIContent(button.text, button.tooltip), GUILayout.Width(140), + GUILayout.Height(40))) { - case DrawingMode.Draw: - case DrawingMode.Erase: - DrawDrawingModeSection(); - break; - case DrawingMode.Expand: - DrawExpandModeSection(position); - break; - case DrawingMode.Crop: - DrawCropModeSection(position); - break; + button.onClick?.Invoke(); } } - else + + EditorGUILayout.EndVertical(); + } + + private void DrawMiddleSection(Rect position, float middleSectionWidth) + { + // Middle Section + EditorGUILayout.BeginVertical(GUILayout.Width(middleSectionWidth)); { - GUILayout.BeginHorizontal(); + CustomStyle.Space(18); + + if (uploadedImage != null) { - GUILayout.FlexibleSpace(); - GUILayout.BeginVertical(); + switch (currentDrawingMode) { - HandleImageUpload(); + case DrawingMode.Draw: + case DrawingMode.Erase: + DrawDrawingModeSection(); + break; + case DrawingMode.Expand: + DrawExpandModeSection(position); + break; + case DrawingMode.Crop: + DrawCropModeSection(position); + break; } - GUILayout.EndVertical(); - GUILayout.FlexibleSpace(); } - GUILayout.EndHorizontal(); + else + { + GUILayout.BeginHorizontal(); + { + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(); + { + HandleImageUpload(); + } + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + } + GUILayout.EndHorizontal(); + } } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); - } - - private void HandleImageUpload() - { - Rect dropArea = GUILayoutUtility.GetRect(512f, 256f, GUILayout.ExpandWidth(false)); - GUI.Box(dropArea, "Drop image here or"); - Event currentEvent = Event.current; - if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) + private void HandleImageUpload() { - if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) - { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + Rect dropArea = GUILayoutUtility.GetRect(512f, 256f, GUILayout.ExpandWidth(false)); + GUI.Box(dropArea, "Drop image here or"); - if (currentEvent.type == EventType.DragPerform) + Event currentEvent = Event.current; + if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) + { + if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) { - DragAndDrop.AcceptDrag(); - string path = DragAndDrop.paths[0]; - if (System.IO.File.Exists(path) && - (System.IO.Path.GetExtension(path).ToLower() == ".png" || - System.IO.Path.GetExtension(path).ToLower() == ".jpg" || - System.IO.Path.GetExtension(path).ToLower() == ".jpeg")) + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + + if (currentEvent.type == EventType.DragPerform) { - Texture2D tex = new Texture2D(2, 2); - byte[] imageData = File.ReadAllBytes(path); - tex.LoadImage(imageData); - SetImage(tex); + DragAndDrop.AcceptDrag(); + string path = DragAndDrop.paths[0]; + if (System.IO.File.Exists(path) && + (System.IO.Path.GetExtension(path).ToLower() == ".png" || + System.IO.Path.GetExtension(path).ToLower() == ".jpg" || + System.IO.Path.GetExtension(path).ToLower() == ".jpeg")) + { + Texture2D tex = new Texture2D(2, 2); + byte[] imageData = File.ReadAllBytes(path); + tex.LoadImage(imageData); + SetImage(tex); + } } - } - currentEvent.Use(); + currentEvent.Use(); + } } - } - Rect buttonRect = new Rect(dropArea.center.x - 75f, dropArea.center.y - 20f, 150f, 40f); - if (GUI.Button(buttonRect, "Upload")) - { - uploadedImagePath = EditorUtility.OpenFilePanel("Upload image", "", "png,jpeg,jpg"); - if (!string.IsNullOrEmpty(uploadedImagePath)) + Rect buttonRect = new Rect(dropArea.center.x - 75f, dropArea.center.y - 20f, 150f, 40f); + if (GUI.Button(buttonRect, "Upload")) { - Texture2D tex = new Texture2D(1, 1); - tex.LoadImage(File.ReadAllBytes(uploadedImagePath)); - SetImage(tex); + uploadedImagePath = EditorUtility.OpenFilePanel("Upload image", "", "png,jpeg,jpg"); + if (!string.IsNullOrEmpty(uploadedImagePath)) + { + Texture2D tex = new Texture2D(1, 1); + tex.LoadImage(File.ReadAllBytes(uploadedImagePath)); + SetImage(tex); + } } } - } - private void DrawCropModeSection(Rect position) - { - EditorGUILayout.BeginHorizontal(); + private void DrawCropModeSection(Rect position) { - CustomStyle.Space(); - EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); + EditorGUILayout.BeginHorizontal(); { - float centerX = position.width * 0.5f; - float centerY = position.height / 2f; - float imageWidth = uploadedImage.width; - float imageHeight = uploadedImage.height; - float buttonSize = 50f; - - var rect = new Rect(centerX - imageWidth / 2, centerY - imageHeight / 2, imageWidth, imageHeight); - GUI.DrawTexture(rect, uploadedImage); - - rect = new Rect(centerX - imageWidth / 2 - buttonSize - 5, centerY - buttonSize / 2, buttonSize, - buttonSize); - if (GUI.Button(rect, "-")) + CustomStyle.Space(); + EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); { - int newWidth = FindPreviousSize((int)imageWidth); - uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight, addLeft: true); - maskBuffer = ResizeImage(maskBuffer, newWidth, (int)imageHeight, addLeft: true); - } + float centerX = position.width * 0.5f; + float centerY = position.height / 2f; + float imageWidth = uploadedImage.width; + float imageHeight = uploadedImage.height; + float buttonSize = 50f; + + var rect = new Rect(centerX - imageWidth / 2, centerY - imageHeight / 2, imageWidth, imageHeight); + GUI.DrawTexture(rect, uploadedImage); + + rect = new Rect(centerX - imageWidth / 2 - buttonSize - 5, centerY - buttonSize / 2, buttonSize, + buttonSize); + if (GUI.Button(rect, "-")) + { + int newWidth = FindPreviousSize((int)imageWidth); + uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight, addLeft: true); + maskBuffer = ResizeImage(maskBuffer, newWidth, (int)imageHeight, addLeft: true); + } - // Right button - rect = new Rect(centerX + imageWidth / 2 + 5, centerY - buttonSize / 2, buttonSize, buttonSize); - if (GUI.Button(rect, "-")) - { - int newWidth = FindPreviousSize((int)imageWidth); - uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight); - maskBuffer = ResizeImage(maskBuffer, newWidth, (int)imageHeight); - } + // Right button + rect = new Rect(centerX + imageWidth / 2 + 5, centerY - buttonSize / 2, buttonSize, buttonSize); + if (GUI.Button(rect, "-")) + { + int newWidth = FindPreviousSize((int)imageWidth); + uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight); + maskBuffer = ResizeImage(maskBuffer, newWidth, (int)imageHeight); + } - // Top button - rect = new Rect(centerX - buttonSize / 2, centerY - imageHeight / 2 - buttonSize - 5, buttonSize, - buttonSize); - if (GUI.Button(rect, "-")) - { - int newHeight = FindPreviousSize((int)imageHeight); - uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight); - maskBuffer = ResizeImage(maskBuffer, (int)imageWidth, newHeight); - } + // Top button + rect = new Rect(centerX - buttonSize / 2, centerY - imageHeight / 2 - buttonSize - 5, buttonSize, + buttonSize); + if (GUI.Button(rect, "-")) + { + int newHeight = FindPreviousSize((int)imageHeight); + uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight); + maskBuffer = ResizeImage(maskBuffer, (int)imageWidth, newHeight); + } - // Bottom button - rect = new Rect(centerX - buttonSize / 2, centerY + imageHeight / 2 + 5, buttonSize, buttonSize); - if (GUI.Button(rect, "-")) - { - int newHeight = FindPreviousSize((int)imageHeight); - uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight, addBottom: true); - maskBuffer = ResizeImage(maskBuffer, (int)imageWidth, newHeight, addBottom: true); + // Bottom button + rect = new Rect(centerX - buttonSize / 2, centerY + imageHeight / 2 + 5, buttonSize, buttonSize); + if (GUI.Button(rect, "-")) + { + int newHeight = FindPreviousSize((int)imageHeight); + uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight, addBottom: true); + maskBuffer = ResizeImage(maskBuffer, (int)imageWidth, newHeight, addBottom: true); + } } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); + EditorGUILayout.EndHorizontal(); } - EditorGUILayout.EndHorizontal(); - } - private void DrawExpandModeSection(Rect position) - { - EditorGUILayout.BeginHorizontal(); + private void DrawExpandModeSection(Rect position) { - CustomStyle.Space(); - EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); + EditorGUILayout.BeginHorizontal(); { - float centerX = position.width * 0.5f; - float centerY = position.height / 2f; - float imageWidth = uploadedImage.width; - float imageHeight = uploadedImage.height; - float buttonSize = 50f; - - var rect = new Rect(centerX - imageWidth / 2, centerY - imageHeight / 2, imageWidth, imageHeight); - GUI.DrawTexture(rect, uploadedImage); - - rect = new Rect(centerX - imageWidth / 2 - buttonSize - 5, centerY - buttonSize / 2, buttonSize, - buttonSize); - if (GUI.Button(rect, "+")) + CustomStyle.Space(); + EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); { - int newWidth = FindNextSize((int)imageWidth); - uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight, addLeft: true); - maskBuffer = ResizeImage(maskBuffer, newWidth, (int)imageHeight, addLeft: true); - } + float centerX = position.width * 0.5f; + float centerY = position.height / 2f; + float imageWidth = uploadedImage.width; + float imageHeight = uploadedImage.height; + float buttonSize = 50f; + + var rect = new Rect(centerX - imageWidth / 2, centerY - imageHeight / 2, imageWidth, imageHeight); + GUI.DrawTexture(rect, uploadedImage); + + rect = new Rect(centerX - imageWidth / 2 - buttonSize - 5, centerY - buttonSize / 2, buttonSize, + buttonSize); + if (GUI.Button(rect, "+")) + { + int newWidth = FindNextSize((int)imageWidth); + uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight, addLeft: true); + maskBuffer = ResizeImage(maskBuffer, newWidth, (int)imageHeight, addLeft: true); + } - // Right button - rect = new Rect(centerX + imageWidth / 2 + 5, centerY - buttonSize / 2, buttonSize, buttonSize); - if (GUI.Button(rect, "+")) - { - int newWidth = FindNextSize((int)imageWidth); - uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight); - maskBuffer = ResizeImage(maskBuffer, newWidth, (int)imageHeight); - } + // Right button + rect = new Rect(centerX + imageWidth / 2 + 5, centerY - buttonSize / 2, buttonSize, buttonSize); + if (GUI.Button(rect, "+")) + { + int newWidth = FindNextSize((int)imageWidth); + uploadedImage = ResizeImage(uploadedImage, newWidth, (int)imageHeight); + maskBuffer = ResizeImage(maskBuffer, newWidth, (int)imageHeight); + } - // Top button - rect = new Rect(centerX - buttonSize / 2, centerY - imageHeight / 2 - buttonSize - 5, buttonSize, - buttonSize); - if (GUI.Button(rect, "+")) - { - int newHeight = FindNextSize((int)imageHeight); - uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight); - maskBuffer = ResizeImage(maskBuffer, (int)imageWidth, newHeight); - } + // Top button + rect = new Rect(centerX - buttonSize / 2, centerY - imageHeight / 2 - buttonSize - 5, buttonSize, + buttonSize); + if (GUI.Button(rect, "+")) + { + int newHeight = FindNextSize((int)imageHeight); + uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight); + maskBuffer = ResizeImage(maskBuffer, (int)imageWidth, newHeight); + } - // Bottom button - rect = new Rect(centerX - buttonSize / 2, centerY + imageHeight / 2 + 5, buttonSize, buttonSize); - if (GUI.Button(rect, "+")) - { - int newHeight = FindNextSize((int)imageHeight); - uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight, addBottom: true); - maskBuffer = ResizeImage(maskBuffer, (int)imageWidth, newHeight, addBottom: true); + // Bottom button + rect = new Rect(centerX - buttonSize / 2, centerY + imageHeight / 2 + 5, buttonSize, buttonSize); + if (GUI.Button(rect, "+")) + { + int newHeight = FindNextSize((int)imageHeight); + uploadedImage = ResizeImage(uploadedImage, (int)imageWidth, newHeight, addBottom: true); + maskBuffer = ResizeImage(maskBuffer, (int)imageWidth, newHeight, addBottom: true); + } } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); + EditorGUILayout.EndHorizontal(); } - EditorGUILayout.EndHorizontal(); - } - private void DrawDrawingModeSection() - { - EditorGUILayout.BeginHorizontal(); + private void DrawDrawingModeSection() { - CustomStyle.Space(); - EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); + EditorGUILayout.BeginHorizontal(); { - float maxSize = 1024f; - float aspectRatio = (float)uploadedImage.width / (float)uploadedImage.height; - float width = Mathf.Min(uploadedImage.width, maxSize); - float height = width / aspectRatio; - Rect rect = GUILayoutUtility.GetRect(width, height, GUILayout.ExpandWidth(false), - GUILayout.ExpandHeight(false)); - - GUI.DrawTexture(rect, uploadedImage, ScaleMode.ScaleToFit); - - if (canvasImage == null || canvasImage.width != uploadedImage.width || canvasImage.height != uploadedImage.height) + CustomStyle.Space(); + EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); { - int canvasWidth = Mathf.Min(uploadedImage.width, 1024); - int canvasHeight = Mathf.Min(uploadedImage.height, 1024); - canvasImage = new Texture2D(canvasWidth, canvasHeight, TextureFormat.RGBA32, false, true); - canvasImage.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height) - .ToArray()); - canvasImage.Apply(); - - maskBuffer = new Texture2D(canvasWidth, canvasHeight, TextureFormat.RGBA32, false, true); - maskBuffer.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height) - .ToArray()); - maskBuffer.Apply(); - } + float maxSize = 1024f; + float aspectRatio = (float)uploadedImage.width / (float)uploadedImage.height; + float width = Mathf.Min(uploadedImage.width, maxSize); + float height = width / aspectRatio; + Rect rect = GUILayoutUtility.GetRect(width, height, GUILayout.ExpandWidth(false), + GUILayout.ExpandHeight(false)); - GUI.DrawTexture(rect, canvasImage, ScaleMode.ScaleToFit); + GUI.DrawTexture(rect, uploadedImage, ScaleMode.ScaleToFit); - Rect lastRect = GUILayoutUtility.GetLastRect(); - if (lastRect.Contains(Event.current.mousePosition)) - { - if (brushCursor == null || brushCursor.width != selectedBrushSize) + if (canvasImage == null || canvasImage.width != uploadedImage.width || canvasImage.height != uploadedImage.height) { - brushCursor = MakeCircularTex(selectedBrushSize, selectedColor); + int canvasWidth = Mathf.Min(uploadedImage.width, 1024); + int canvasHeight = Mathf.Min(uploadedImage.height, 1024); + canvasImage = new Texture2D(canvasWidth, canvasHeight, TextureFormat.RGBA32, false, true); + canvasImage.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height) + .ToArray()); + canvasImage.Apply(); + + maskBuffer = new Texture2D(canvasWidth, canvasHeight, TextureFormat.RGBA32, false, true); + maskBuffer.SetPixels(Enumerable.Repeat(Color.clear, canvasImage.width * canvasImage.height) + .ToArray()); + maskBuffer.Apply(); } - EditorGUIUtility.AddCursorRect(lastRect, MouseCursor.CustomCursor); - Cursor.SetCursor(brushCursor, new Vector2(brushCursor.width / 2, brushCursor.height / 2), - CursorMode.Auto); + GUI.DrawTexture(rect, canvasImage, ScaleMode.ScaleToFit); - if (Event.current.type == EventType.MouseDrag || Event.current.type == EventType.MouseDown) + Rect lastRect = GUILayoutUtility.GetLastRect(); + if (lastRect.Contains(Event.current.mousePosition)) { - Vector2 localMousePosition = Event.current.mousePosition - new Vector2(rect.x, rect.y); - Vector2 textureCoords = - new Vector2(localMousePosition.x / rect.width, localMousePosition.y / rect.height); + if (brushCursor == null || brushCursor.width != selectedBrushSize) + { + brushCursor = MakeCircularTex(selectedBrushSize, selectedColor); + } - int x = (int)(textureCoords.x * uploadedImage.width); - int y = (int)((1 - textureCoords.y) * uploadedImage.height); + EditorGUIUtility.AddCursorRect(lastRect, MouseCursor.CustomCursor); + Cursor.SetCursor(brushCursor, new Vector2(brushCursor.width / 2, brushCursor.height / 2), + CursorMode.Auto); - if (currentDrawingMode == DrawingMode.Draw) + if (Event.current.type == EventType.MouseDrag || Event.current.type == EventType.MouseDown) { - DrawOnTexture(canvasImage, new Vector2(x, y), selectedBrushSize, selectedColor, - selectedOpacity); - DrawOnTexture(maskBuffer, new Vector2(x, y), selectedBrushSize, selectedColor, - selectedOpacity); + Vector2 localMousePosition = Event.current.mousePosition - new Vector2(rect.x, rect.y); + Vector2 textureCoords = + new Vector2(localMousePosition.x / rect.width, localMousePosition.y / rect.height); + + int x = (int)(textureCoords.x * uploadedImage.width); + int y = (int)((1 - textureCoords.y) * uploadedImage.height); + + if (currentDrawingMode == DrawingMode.Draw) + { + DrawOnTexture(canvasImage, new Vector2(x, y), selectedBrushSize, selectedColor, + selectedOpacity); + DrawOnTexture(maskBuffer, new Vector2(x, y), selectedBrushSize, selectedColor, + selectedOpacity); + } + else if (currentDrawingMode == DrawingMode.Erase) + { + DrawOnTexture(canvasImage, new Vector2(x, y), selectedBrushSize, new Color(0, 0, 0, 0), + selectedOpacity); + DrawOnTexture(maskBuffer, new Vector2(x, y), selectedBrushSize, new Color(0, 0, 0, 0), + selectedOpacity); + } + + Event.current.Use(); } - else if (currentDrawingMode == DrawingMode.Erase) + + else if (Event.current.type == EventType.MouseUp) { - DrawOnTexture(canvasImage, new Vector2(x, y), selectedBrushSize, new Color(0, 0, 0, 0), - selectedOpacity); - DrawOnTexture(maskBuffer, new Vector2(x, y), selectedBrushSize, new Color(0, 0, 0, 0), - selectedOpacity); + newStroke = true; } - - Event.current.Use(); - } - - else if (Event.current.type == EventType.MouseUp) - { - newStroke = true; } } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); + EditorGUILayout.EndHorizontal(); } - EditorGUILayout.EndHorizontal(); - } - private void DrawLeftSection(float leftSectionWidth) - { - // Left Section - EditorGUILayout.BeginVertical(GUILayout.Width(leftSectionWidth)); + private void DrawLeftSection(float leftSectionWidth) { - CustomStyle.Space(18); - GUILayout.Label("Tools", EditorStyles.boldLabel); - - for (int i = 0; i < toolButtons.Length; i++) + // Left Section + EditorGUILayout.BeginVertical(GUILayout.Width(leftSectionWidth)); { - ToolButton button = toolButtons[i]; - if (i % 4 == 0) + CustomStyle.Space(18); + GUILayout.Label("Tools", EditorStyles.boldLabel); + + for (int i = 0; i < toolButtons.Length; i++) { - EditorGUILayout.BeginHorizontal(); + ToolButton button = toolButtons[i]; + if (i % 4 == 0) + { + EditorGUILayout.BeginHorizontal(); + } + + GUIStyle buttonStyle = new GUIStyle(GUI.skin.button); + buttonStyle.fontSize = 25; + + if (GUILayout.Button(new GUIContent(button.text, button.tooltip), buttonStyle, GUILayout.Width(45), + GUILayout.Height(45))) + { + currentDrawingMode = button.mode; + button.onClick?.Invoke(); + } + + if (i % 4 == 3 || i == toolButtons.Length - 1) + { + EditorGUILayout.EndHorizontal(); + } } - GUIStyle buttonStyle = new GUIStyle(GUI.skin.button); - buttonStyle.fontSize = 25; + CustomStyle.Space(10); - if (GUILayout.Button(new GUIContent(button.text, button.tooltip), buttonStyle, GUILayout.Width(45), - GUILayout.Height(45))) + int[] brushSizes = new int[] { 6, 12, 16, 24, 30, 40, 48, 64 }; + + GUILayout.BeginHorizontal(); { - currentDrawingMode = button.mode; - button.onClick?.Invoke(); + GUILayout.Label("Brush Size", EditorStyles.boldLabel, GUILayout.Width(80)); + GUILayout.Label(selectedBrushSize.ToString(), GUILayout.Width(40)); } + GUILayout.EndHorizontal(); - if (i % 4 == 3 || i == toolButtons.Length - 1) + GUILayout.BeginHorizontal(); { - EditorGUILayout.EndHorizontal(); + selectedBrushSize = (int)GUILayout.HorizontalSlider(selectedBrushSize, brushSizes[0], + brushSizes[brushSizes.Length - 1], GUILayout.Width(200)); } - } + GUILayout.EndHorizontal(); - CustomStyle.Space(10); + CustomStyle.Space(20); - int[] brushSizes = new int[] { 6, 12, 16, 24, 30, 40, 48, 64 }; + float[] opacities = new[] { 0.0f, 0.2f, 0.4f, 0.6f, 0.8f, 1.0f }; + int selectedOpacityIndex = 5; - GUILayout.BeginHorizontal(); - { - GUILayout.Label("Brush Size", EditorStyles.boldLabel, GUILayout.Width(80)); - GUILayout.Label(selectedBrushSize.ToString(), GUILayout.Width(40)); + GUILayout.BeginHorizontal(); + { + GUILayout.Label("Opacity", EditorStyles.boldLabel); + } + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + { + for (int i = 0; i < opacities.Length; i++) + { + float opacity = opacities[i]; + GUIStyle opacityButtonStyle = new GUIStyle(GUI.skin.button) + { + normal = + { + background = MakeOpacityTex(10, 10, opacity) + } + }; + + if (GUILayout.Button("", opacityButtonStyle, GUILayout.Width(14), GUILayout.Height(14))) + { + selectedOpacityIndex = i; + selectedOpacity = opacities[selectedOpacityIndex]; + } + } + } + GUILayout.EndHorizontal(); } - GUILayout.EndHorizontal(); + EditorGUILayout.EndVertical(); + } - GUILayout.BeginHorizontal(); + private Texture2D MakeTex(int width, int height, Color col) + { + Color[] pix = new Color[width * height]; + for (int i = 0; i < pix.Length; i++) { - selectedBrushSize = (int)GUILayout.HorizontalSlider(selectedBrushSize, brushSizes[0], - brushSizes[brushSizes.Length - 1], GUILayout.Width(200)); + pix[i] = col; } - GUILayout.EndHorizontal(); - - CustomStyle.Space(20); - float[] opacities = new[] { 0.0f, 0.2f, 0.4f, 0.6f, 0.8f, 1.0f }; - int selectedOpacityIndex = 5; + Texture2D result = new Texture2D(width, height); + result.SetPixels(pix); + result.Apply(); + return result; + } - GUILayout.BeginHorizontal(); + private Texture2D MakeOpacityTex(int width, int height, float opacity) + { + Color[] pix = new Color[width * height]; + for (int i = 0; i < pix.Length; i++) { - GUILayout.Label("Opacity", EditorStyles.boldLabel); + pix[i] = new Color(1, 1, 1, opacity); } - GUILayout.EndHorizontal(); - GUILayout.BeginHorizontal(); + Texture2D result = new Texture2D(width, height); + result.SetPixels(pix); + result.Apply(); + return result; + } + + private Texture2D MakeCircularTex(int diameter, Color col) + { + if (diameter <= 0) return null; + + int radius = diameter / 2; + Color[] pix = new Color[diameter * diameter]; + for (int y = 0; y < diameter; y++) { - for (int i = 0; i < opacities.Length; i++) + for (int x = 0; x < diameter; x++) { - float opacity = opacities[i]; - GUIStyle opacityButtonStyle = new GUIStyle(GUI.skin.button) + int dx = x - radius; + int dy = y - radius; + if (dx * dx + dy * dy < radius * radius) { - normal = - { - background = MakeOpacityTex(10, 10, opacity) - } - }; - - if (GUILayout.Button("", opacityButtonStyle, GUILayout.Width(14), GUILayout.Height(14))) + pix[y * diameter + x] = col; + } + else { - selectedOpacityIndex = i; - selectedOpacity = opacities[selectedOpacityIndex]; + pix[y * diameter + x] = Color.clear; } } } - GUILayout.EndHorizontal(); - } - EditorGUILayout.EndVertical(); - } - private Texture2D MakeTex(int width, int height, Color col) - { - Color[] pix = new Color[width * height]; - for (int i = 0; i < pix.Length; i++) - { - pix[i] = col; + Texture2D result = new Texture2D(diameter, diameter, TextureFormat.RGBA32, false, true); + result.SetPixels(pix); + result.Apply(); + return result; } - Texture2D result = new Texture2D(width, height); - result.SetPixels(pix); - result.Apply(); - return result; - } - - private Texture2D MakeOpacityTex(int width, int height, float opacity) - { - Color[] pix = new Color[width * height]; - for (int i = 0; i < pix.Length; i++) + private Texture2D MakeCursorTex(int diameter, Color col) { - pix[i] = new Color(1, 1, 1, opacity); - } + if (diameter <= 0) return null; - Texture2D result = new Texture2D(width, height); - result.SetPixels(pix); - result.Apply(); - return result; - } + int radius = diameter / 2; + Color[] pix = new Color[diameter * diameter]; + for (int y = 0; y < diameter; y++) + { + for (int x = 0; x < diameter; x++) + { + int dx = x - radius; + int dy = y - radius; + if (dx * dx + dy * dy < radius * radius) + { + pix[y * diameter + x] = col; + } + else + { + pix[y * diameter + x] = Color.clear; + } + } + } - private Texture2D MakeCircularTex(int diameter, Color col) - { - if (diameter <= 0) return null; + Texture2D result = new Texture2D(diameter, diameter, TextureFormat.RGBA32, false, true); + result.SetPixels(pix); + result.Apply(); + return result; + } - int radius = diameter / 2; - Color[] pix = new Color[diameter * diameter]; - for (int y = 0; y < diameter; y++) + private void DrawOnTexture(Texture2D tex, Vector2 position, int brushSize, Color color, float opacity) { - for (int x = 0; x < diameter; x++) + if (newStroke && (currentDrawingMode == DrawingMode.Draw || currentDrawingMode == DrawingMode.Erase)) { - int dx = x - radius; - int dy = y - radius; - if (dx * dx + dy * dy < radius * radius) + if (canvasHistoryIndex < canvasHistory.Count - 1) { - pix[y * diameter + x] = col; - } - else - { - pix[y * diameter + x] = Color.clear; + canvasHistory.RemoveRange(canvasHistoryIndex + 1, canvasHistory.Count - canvasHistoryIndex - 1); } + + AddToCanvasHistory(); + newStroke = false; } - } - Texture2D result = new Texture2D(diameter, diameter, TextureFormat.RGBA32, false, true); - result.SetPixels(pix); - result.Apply(); - return result; - } + int xStart = Mathf.Clamp((int)position.x - brushSize / 2, 0, tex.width); + int xEnd = Mathf.Clamp((int)position.x + brushSize / 2, 0, tex.width); + int yStart = Mathf.Clamp((int)position.y - brushSize / 2, 0, tex.height); + int yEnd = Mathf.Clamp((int)position.y + brushSize / 2, 0, tex.height); - private Texture2D MakeCursorTex(int diameter, Color col) - { - if (diameter <= 0) return null; + Color colorWithOpacity = new Color(color.r, color.g, color.b, opacity); - int radius = diameter / 2; - Color[] pix = new Color[diameter * diameter]; - for (int y = 0; y < diameter; y++) - { - for (int x = 0; x < diameter; x++) + for (int x = xStart; x < xEnd; x++) { - int dx = x - radius; - int dy = y - radius; - if (dx * dx + dy * dy < radius * radius) + for (int y = yStart; y < yEnd; y++) { - pix[y * diameter + x] = col; - } - else - { - pix[y * diameter + x] = Color.clear; + if (Vector2.Distance(new Vector2(x, y), position) <= brushSize / 2) + { + Color currentColor = tex.GetPixel(x, y); + Color blendedColor; + + if (currentDrawingMode == DrawingMode.Erase) + { + blendedColor = new Color(currentColor.r, currentColor.g, currentColor.b, 0); + } + else + { + blendedColor = Color.Lerp(currentColor, colorWithOpacity, colorWithOpacity.a); + } + + tex.SetPixel(x, y, blendedColor); + } } } - } - Texture2D result = new Texture2D(diameter, diameter, TextureFormat.RGBA32, false, true); - result.SetPixels(pix); - result.Apply(); - return result; - } + tex.Apply(); + } - private void DrawOnTexture(Texture2D tex, Vector2 position, int brushSize, Color color, float opacity) - { - if (newStroke && (currentDrawingMode == DrawingMode.Draw || currentDrawingMode == DrawingMode.Erase)) + private int FindNextSize(int currentSize) { - if (canvasHistoryIndex < canvasHistory.Count - 1) + foreach (int size in allowedSizes) { - canvasHistory.RemoveRange(canvasHistoryIndex + 1, canvasHistory.Count - canvasHistoryIndex - 1); + if (size > currentSize) + return size; } - AddToCanvasHistory(); - newStroke = false; + return currentSize; } - int xStart = Mathf.Clamp((int)position.x - brushSize / 2, 0, tex.width); - int xEnd = Mathf.Clamp((int)position.x + brushSize / 2, 0, tex.width); - int yStart = Mathf.Clamp((int)position.y - brushSize / 2, 0, tex.height); - int yEnd = Mathf.Clamp((int)position.y + brushSize / 2, 0, tex.height); + private int FindPreviousSize(int currentSize) + { + for (int i = allowedSizes.Length - 1; i >= 0; i--) + { + if (allowedSizes[i] < currentSize) + return allowedSizes[i]; + } - Color colorWithOpacity = new Color(color.r, color.g, color.b, opacity); + return currentSize; + } - for (int x = xStart; x < xEnd; x++) + private Texture2D ResizeImage(Texture2D original, int newWidth, int newHeight, bool addBottom = false, + bool addLeft = false) { - for (int y = yStart; y < yEnd; y++) + Texture2D resizedImage = new Texture2D(newWidth, newHeight); + Color[] originalPixels = original.GetPixels(); + Color[] newPixels = new Color[newWidth * newHeight]; + + int xOffset = addLeft ? newWidth - original.width : 0; + int yOffset = addBottom ? newHeight - original.height : 0; + + for (int y = 0; y < newHeight; y++) { - if (Vector2.Distance(new Vector2(x, y), position) <= brushSize / 2) + for (int x = 0; x < newWidth; x++) { - Color currentColor = tex.GetPixel(x, y); - Color blendedColor; - - if (currentDrawingMode == DrawingMode.Erase) + if (x >= xOffset && x < xOffset + original.width && y >= yOffset && y < yOffset + original.height) { - blendedColor = new Color(currentColor.r, currentColor.g, currentColor.b, 0); + newPixels[y * newWidth + x] = originalPixels[(y - yOffset) * original.width + (x - xOffset)]; } else { - blendedColor = Color.Lerp(currentColor, colorWithOpacity, colorWithOpacity.a); + newPixels[y * newWidth + x] = Color.white; } - - tex.SetPixel(x, y, blendedColor); } } - } - tex.Apply(); - } + resizedImage.SetPixels(newPixels); + resizedImage.Apply(); - private int FindNextSize(int currentSize) - { - foreach (int size in allowedSizes) - { - if (size > currentSize) - return size; + return resizedImage; } - return currentSize; - } - - private int FindPreviousSize(int currentSize) - { - for (int i = allowedSizes.Length - 1; i >= 0; i--) + private void CreateTransparentImage(int width, int height) { - if (allowedSizes[i] < currentSize) - return allowedSizes[i]; - } + transparentImage = new Texture2D(width, height, TextureFormat.ARGB32, false); + Color32[] pixels = new Color32[width * height]; - return currentSize; - } - - private Texture2D ResizeImage(Texture2D original, int newWidth, int newHeight, bool addBottom = false, - bool addLeft = false) - { - Texture2D resizedImage = new Texture2D(newWidth, newHeight); - Color[] originalPixels = original.GetPixels(); - Color[] newPixels = new Color[newWidth * newHeight]; - - int xOffset = addLeft ? newWidth - original.width : 0; - int yOffset = addBottom ? newHeight - original.height : 0; - - for (int y = 0; y < newHeight; y++) - { - for (int x = 0; x < newWidth; x++) + for (int i = 0; i < pixels.Length; i++) { - if (x >= xOffset && x < xOffset + original.width && y >= yOffset && y < yOffset + original.height) - { - newPixels[y * newWidth + x] = originalPixels[(y - yOffset) * original.width + (x - xOffset)]; - } - else - { - newPixels[y * newWidth + x] = Color.white; - } + pixels[i] = new Color32(0, 0, 0, 0); } - } - - resizedImage.SetPixels(newPixels); - resizedImage.Apply(); - - return resizedImage; - } - private void CreateTransparentImage(int width, int height) - { - transparentImage = new Texture2D(width, height, TextureFormat.ARGB32, false); - Color32[] pixels = new Color32[width * height]; + transparentImage.SetPixels32(pixels); + transparentImage.Apply(); + } - for (int i = 0; i < pixels.Length; i++) + private void AddToCanvasHistory() { - pixels[i] = new Color32(0, 0, 0, 0); - } + canvasHistory.RemoveRange(canvasHistoryIndex + 1, canvasHistory.Count - canvasHistoryIndex - 1); - transparentImage.SetPixels32(pixels); - transparentImage.Apply(); - } + Texture2D newHistoryImage = + new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); + newHistoryImage.SetPixels(canvasImage.GetPixels()); + newHistoryImage.Apply(); + canvasHistory.Add(newHistoryImage); + canvasHistoryIndex++; - private void AddToCanvasHistory() - { - canvasHistory.RemoveRange(canvasHistoryIndex + 1, canvasHistory.Count - canvasHistoryIndex - 1); - - Texture2D newHistoryImage = - new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); - newHistoryImage.SetPixels(canvasImage.GetPixels()); - newHistoryImage.Apply(); - canvasHistory.Add(newHistoryImage); - canvasHistoryIndex++; + const int maxHistorySize = 10; + if (canvasHistory.Count > maxHistorySize) + { + canvasHistory.RemoveAt(0); + canvasHistoryIndex--; + } + } - const int maxHistorySize = 10; - if (canvasHistory.Count > maxHistorySize) + private void UndoCanvas() { - canvasHistory.RemoveAt(0); + if (canvasHistoryIndex <= 0) return; + + Texture2D redoImage = + new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); + redoImage.SetPixels(canvasImage.GetPixels()); + redoImage.Apply(); + redoHistory.Add(redoImage); + canvasHistoryIndex--; - } - } + canvasImage.SetPixels(canvasHistory[canvasHistoryIndex].GetPixels()); + canvasImage.Apply(); - private void UndoCanvas() - { - if (canvasHistoryIndex <= 0) return; - - Texture2D redoImage = - new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); - redoImage.SetPixels(canvasImage.GetPixels()); - redoImage.Apply(); - redoHistory.Add(redoImage); - - canvasHistoryIndex--; - canvasImage.SetPixels(canvasHistory[canvasHistoryIndex].GetPixels()); - canvasImage.Apply(); - - maskBuffer.SetPixels(canvasHistory[canvasHistoryIndex].GetPixels()); - maskBuffer.Apply(); - } + maskBuffer.SetPixels(canvasHistory[canvasHistoryIndex].GetPixels()); + maskBuffer.Apply(); + } - private void RedoCanvas() - { - if (redoHistory.Count <= 0) return; + private void RedoCanvas() + { + if (redoHistory.Count <= 0) return; - Texture2D undoImage = - new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); - undoImage.SetPixels(canvasImage.GetPixels()); - undoImage.Apply(); - canvasHistory.Add(undoImage); - canvasHistoryIndex++; - - Texture2D redoImage = redoHistory[redoHistory.Count - 1]; - redoHistory.RemoveAt(redoHistory.Count - 1); - canvasImage.SetPixels(redoImage.GetPixels()); - canvasImage.Apply(); - - maskBuffer.SetPixels(redoImage.GetPixels()); - maskBuffer.Apply(); - } + Texture2D undoImage = + new Texture2D(canvasImage.width, canvasImage.height, TextureFormat.RGBA32, false, true); + undoImage.SetPixels(canvasImage.GetPixels()); + undoImage.Apply(); + canvasHistory.Add(undoImage); + canvasHistoryIndex++; + + Texture2D redoImage = redoHistory[redoHistory.Count - 1]; + redoHistory.RemoveAt(redoHistory.Count - 1); + canvasImage.SetPixels(redoImage.GetPixels()); + canvasImage.Apply(); + + maskBuffer.SetPixels(redoImage.GetPixels()); + maskBuffer.Apply(); + } - private void LoadMaskFromFile() - { - string filePath = EditorUtility.OpenFilePanel("Load mask image", "", "png,jpg,jpeg"); - if (!string.IsNullOrEmpty(filePath)) + private void LoadMaskFromFile() { - byte[] fileData = File.ReadAllBytes(filePath); - Texture2D loadedMask = new Texture2D(2, 2); - loadedMask.LoadImage(fileData); - - if (loadedMask.width == canvasImage.width && loadedMask.height == canvasImage.height) + string filePath = EditorUtility.OpenFilePanel("Load mask image", "", "png,jpg,jpeg"); + if (!string.IsNullOrEmpty(filePath)) { - canvasImage.SetPixels(loadedMask.GetPixels()); - canvasImage.Apply(); + byte[] fileData = File.ReadAllBytes(filePath); + Texture2D loadedMask = new Texture2D(2, 2); + loadedMask.LoadImage(fileData); - maskBuffer.SetPixels(loadedMask.GetPixels()); - maskBuffer.Apply(); + if (loadedMask.width == canvasImage.width && loadedMask.height == canvasImage.height) + { + canvasImage.SetPixels(loadedMask.GetPixels()); + canvasImage.Apply(); - AddToCanvasHistory(); - } - else - { - Debug.LogWarning("Loaded mask dimensions do not match canvas dimensions."); + maskBuffer.SetPixels(loadedMask.GetPixels()); + maskBuffer.Apply(); + + AddToCanvasHistory(); + } + else + { + Debug.LogWarning("Loaded mask dimensions do not match canvas dimensions."); + } } } - } - private void SaveMaskToFile() - { - var savePath = EditorUtility.SaveFilePanel("Save image", "", "", "png"); - if (savePath.Length > 0) + private void SaveMaskToFile() { - File.WriteAllBytes(savePath, maskBuffer.EncodeToPNG()); + var savePath = EditorUtility.SaveFilePanel("Save image", "", "", "png"); + if (savePath.Length > 0) + { + File.WriteAllBytes(savePath, maskBuffer.EncodeToPNG()); + } } - } - /*private void FillAll() + /*private void FillAll() { // Add logic to fill all }*/ - private void Clear() - { - uploadedImage = null; - canvasImage = null; - canvasHistory.Clear(); - canvasHistoryIndex = -1; - } - - private void Cancel() - { - inpaintingEditor.Close(); - } + private void Clear() + { + uploadedImage = null; + canvasImage = null; + canvasHistory.Clear(); + canvasHistoryIndex = -1; + } - private void Use() - { - if (uploadedImage == null) + private void Cancel() { - Debug.Log("MUST HAVE AN UPLOADED IMAGE FOR MASKING"); - return; + inpaintingEditor.Close(); } - PromptWindowUI.imageUpload = uploadedImage; - PromptWindowUI.imageMask = maskBuffer; - inpaintingEditor.Close(); + private void Use() + { + if (uploadedImage == null) + { + Debug.Log("MUST HAVE AN UPLOADED IMAGE FOR MASKING"); + return; + } + + PromptWindowUI.imageUpload = uploadedImage; + PromptWindowUI.imageMask = maskBuffer; + inpaintingEditor.Close(); + } } } \ No newline at end of file diff --git a/Scenario/Editor/LayerEditor/ContextMenuActions.cs b/Scenario/Editor/LayerEditor/ContextMenuActions.cs index 5f1c941..8db59f2 100644 --- a/Scenario/Editor/LayerEditor/ContextMenuActions.cs +++ b/Scenario/Editor/LayerEditor/ContextMenuActions.cs @@ -1,241 +1,244 @@ using System; -using UnityEngine; using UnityEditor; +using UnityEngine; using Newtonsoft.Json; -public class ContextMenuActions +namespace Scenario { - private LayerEditor layerEditor; - - public ContextMenuActions(LayerEditor layerEditor) + public class ContextMenuActions { - this.layerEditor = layerEditor; - } + private LayerEditor layerEditor; - public void CreateContextMenu(int index) - { - GenericMenu menu = new GenericMenu(); - - menu.AddItem(new GUIContent("Move Up"), false, () => MoveLayerUp(index)); - menu.AddItem(new GUIContent("Move Down"), false, () => MoveLayerDown(index)); - menu.AddItem(new GUIContent("Clone"), false, () => CloneLayer(index)); - menu.AddItem(new GUIContent("Delete"), false, () => DeleteLayer(index)); - menu.AddSeparator(""); - menu.AddItem(new GUIContent("Flip/Horizontal"), false, () => FlipHorizontal(index)); - menu.AddItem(new GUIContent("Flip/Vertical"), false, () => FlipVertical(index)); - menu.AddItem(new GUIContent("Remove/Background"), false, () => RemoveBackground(index)); - menu.AddItem(new GUIContent("Set As Background"), false, () => SetAsBackground(index)); - - menu.ShowAsContext(); - } + public ContextMenuActions(LayerEditor layerEditor) + { + this.layerEditor = layerEditor; + } - private void MoveLayer(int fromIndex, int toIndex) - { - if (fromIndex >= 0 && fromIndex < layerEditor.uploadedImages.Count && - toIndex >= 0 && toIndex < layerEditor.uploadedImages.Count) + public void CreateContextMenu(int index) { - Texture2D image = layerEditor.uploadedImages[fromIndex]; - Vector2 position = layerEditor.imagePositions[fromIndex]; - bool isDragging = layerEditor.isDraggingList[fromIndex]; - Vector2 size = layerEditor.imageSizes[fromIndex]; - - layerEditor.uploadedImages.RemoveAt(fromIndex); - layerEditor.imagePositions.RemoveAt(fromIndex); - layerEditor.isDraggingList.RemoveAt(fromIndex); - layerEditor.imageSizes.RemoveAt(fromIndex); - - layerEditor.uploadedImages.Insert(toIndex, image); - layerEditor.imagePositions.Insert(toIndex, position); - layerEditor.isDraggingList.Insert(toIndex, isDragging); - layerEditor.imageSizes.Insert(toIndex, size); - - GameObject spriteObj = layerEditor.spriteObjects[fromIndex]; - layerEditor.spriteObjects.RemoveAt(fromIndex); - layerEditor.spriteObjects.Insert(toIndex, spriteObj); - - for (int i = 0; i < layerEditor.spriteObjects.Count; i++) + GenericMenu menu = new GenericMenu(); + + menu.AddItem(new GUIContent("Move Up"), false, () => MoveLayerUp(index)); + menu.AddItem(new GUIContent("Move Down"), false, () => MoveLayerDown(index)); + menu.AddItem(new GUIContent("Clone"), false, () => CloneLayer(index)); + menu.AddItem(new GUIContent("Delete"), false, () => DeleteLayer(index)); + menu.AddSeparator(""); + menu.AddItem(new GUIContent("Flip/Horizontal"), false, () => FlipHorizontal(index)); + menu.AddItem(new GUIContent("Flip/Vertical"), false, () => FlipVertical(index)); + menu.AddItem(new GUIContent("Remove/Background"), false, () => RemoveBackground(index)); + menu.AddItem(new GUIContent("Set As Background"), false, () => SetAsBackground(index)); + + menu.ShowAsContext(); + } + + private void MoveLayer(int fromIndex, int toIndex) + { + if (fromIndex >= 0 && fromIndex < layerEditor.uploadedImages.Count && + toIndex >= 0 && toIndex < layerEditor.uploadedImages.Count) { - GameObject obj = layerEditor.spriteObjects[i]; - SpriteRenderer spriteRenderer = obj.GetComponent(); - spriteRenderer.sortingOrder = i; - } + Texture2D image = layerEditor.uploadedImages[fromIndex]; + Vector2 position = layerEditor.imagePositions[fromIndex]; + bool isDragging = layerEditor.isDraggingList[fromIndex]; + Vector2 size = layerEditor.imageSizes[fromIndex]; + + layerEditor.uploadedImages.RemoveAt(fromIndex); + layerEditor.imagePositions.RemoveAt(fromIndex); + layerEditor.isDraggingList.RemoveAt(fromIndex); + layerEditor.imageSizes.RemoveAt(fromIndex); + + layerEditor.uploadedImages.Insert(toIndex, image); + layerEditor.imagePositions.Insert(toIndex, position); + layerEditor.isDraggingList.Insert(toIndex, isDragging); + layerEditor.imageSizes.Insert(toIndex, size); + + GameObject spriteObj = layerEditor.spriteObjects[fromIndex]; + layerEditor.spriteObjects.RemoveAt(fromIndex); + layerEditor.spriteObjects.Insert(toIndex, spriteObj); + + for (int i = 0; i < layerEditor.spriteObjects.Count; i++) + { + GameObject obj = layerEditor.spriteObjects[i]; + SpriteRenderer spriteRenderer = obj.GetComponent(); + spriteRenderer.sortingOrder = i; + } - layerEditor.selectedLayerIndex = toIndex; + layerEditor.selectedLayerIndex = toIndex; - layerEditor.Repaint(); + layerEditor.Repaint(); + } } - } - private void SetAsBackground(int index) - { - if (index >= 0 && index < layerEditor.uploadedImages.Count) + private void SetAsBackground(int index) { - Texture2D selectedImage = layerEditor.uploadedImages[index]; - layerEditor.backgroundImage = selectedImage; + if (index >= 0 && index < layerEditor.uploadedImages.Count) + { + Texture2D selectedImage = layerEditor.uploadedImages[index]; + layerEditor.backgroundImage = selectedImage; + } } - } - private void MoveLayerUp(int index) - { - MoveLayer(index, index + 1); - } + private void MoveLayerUp(int index) + { + MoveLayer(index, index + 1); + } - private void MoveLayerDown(int index) - { - MoveLayer(index, index - 1); - } + private void MoveLayerDown(int index) + { + MoveLayer(index, index - 1); + } - private void CloneLayer(int index) - { - if (index >= 0 && index < layerEditor.uploadedImages.Count) + private void CloneLayer(int index) { - Texture2D originalImage = layerEditor.uploadedImages[index]; - Texture2D clonedImage = new Texture2D(originalImage.width, originalImage.height); - clonedImage.SetPixels(originalImage.GetPixels()); - clonedImage.Apply(); + if (index >= 0 && index < layerEditor.uploadedImages.Count) + { + Texture2D originalImage = layerEditor.uploadedImages[index]; + Texture2D clonedImage = new Texture2D(originalImage.width, originalImage.height); + clonedImage.SetPixels(originalImage.GetPixels()); + clonedImage.Apply(); - layerEditor.uploadedImages.Insert(index + 1, clonedImage); - layerEditor.imagePositions.Insert(index + 1, layerEditor.imagePositions[index]); - layerEditor.isDraggingList.Insert(index + 1, false); - layerEditor.imageSizes.Insert(index + 1, layerEditor.imageSizes[index]); + layerEditor.uploadedImages.Insert(index + 1, clonedImage); + layerEditor.imagePositions.Insert(index + 1, layerEditor.imagePositions[index]); + layerEditor.isDraggingList.Insert(index + 1, false); + layerEditor.imageSizes.Insert(index + 1, layerEditor.imageSizes[index]); - Rect rect = new Rect(0, 0, clonedImage.width, clonedImage.height); - Vector2 pivot = new Vector2(0.5f, 0.5f); - Sprite sprite = Sprite.Create(clonedImage, rect, pivot); + Rect rect = new Rect(0, 0, clonedImage.width, clonedImage.height); + Vector2 pivot = new Vector2(0.5f, 0.5f); + Sprite sprite = Sprite.Create(clonedImage, rect, pivot); - string originalName = layerEditor.spriteObjects[index].name; - GameObject spriteObj = new GameObject(originalName + "-clone"); - SpriteRenderer renderer = spriteObj.AddComponent(); - renderer.sprite = sprite; + string originalName = layerEditor.spriteObjects[index].name; + GameObject spriteObj = new GameObject(originalName + "-clone"); + SpriteRenderer renderer = spriteObj.AddComponent(); + renderer.sprite = sprite; - spriteObj.transform.position = new Vector3(layerEditor.spriteObjects[index].transform.position.x, - layerEditor.spriteObjects[index].transform.position.y, - 0); + spriteObj.transform.position = new Vector3(layerEditor.spriteObjects[index].transform.position.x, + layerEditor.spriteObjects[index].transform.position.y, + 0); - layerEditor.spriteObjects.Insert(index + 1, spriteObj); + layerEditor.spriteObjects.Insert(index + 1, spriteObj); - for (int i = 0; i < layerEditor.spriteObjects.Count; i++) - { - GameObject obj = layerEditor.spriteObjects[i]; - SpriteRenderer spriteRenderer = obj.GetComponent(); - spriteRenderer.sortingOrder = i; + for (int i = 0; i < layerEditor.spriteObjects.Count; i++) + { + GameObject obj = layerEditor.spriteObjects[i]; + SpriteRenderer spriteRenderer = obj.GetComponent(); + spriteRenderer.sortingOrder = i; + } } } - } - private void DeleteLayer(int index) - { - if (index >= 0 && index < layerEditor.uploadedImages.Count) + private void DeleteLayer(int index) { - try + if (index >= 0 && index < layerEditor.uploadedImages.Count) { - layerEditor.uploadedImages.RemoveAt(index); - layerEditor.imagePositions.RemoveAt(index); - layerEditor.isDraggingList.RemoveAt(index); - layerEditor.imageSizes.RemoveAt(index); - - GameObject spriteObj = layerEditor.spriteObjects[index]; - GameObject.DestroyImmediate(spriteObj); - layerEditor.spriteObjects.RemoveAt(index); - } - catch (Exception ex) - { - Debug.LogError("Error deleting layer: " + ex.Message); - return; - } + try + { + layerEditor.uploadedImages.RemoveAt(index); + layerEditor.imagePositions.RemoveAt(index); + layerEditor.isDraggingList.RemoveAt(index); + layerEditor.imageSizes.RemoveAt(index); - if (layerEditor.selectedLayerIndex == index) - { - layerEditor.selectedLayerIndex = -1; - } - else if (layerEditor.selectedLayerIndex > index) - { - layerEditor.selectedLayerIndex--; + GameObject spriteObj = layerEditor.spriteObjects[index]; + GameObject.DestroyImmediate(spriteObj); + layerEditor.spriteObjects.RemoveAt(index); + } + catch (Exception ex) + { + Debug.LogError("Error deleting layer: " + ex.Message); + return; + } + + if (layerEditor.selectedLayerIndex == index) + { + layerEditor.selectedLayerIndex = -1; + } + else if (layerEditor.selectedLayerIndex > index) + { + layerEditor.selectedLayerIndex--; + } } } - } - private void FlipHorizontal(int index) - { - Texture2D texture = layerEditor.uploadedImages[index]; + private void FlipHorizontal(int index) + { + Texture2D texture = layerEditor.uploadedImages[index]; - Texture2D flipped = new Texture2D(texture.width, texture.height); + Texture2D flipped = new Texture2D(texture.width, texture.height); - for (int y = 0; y < texture.height; y++) - { - for (int x = 0; x < texture.width; x++) + for (int y = 0; y < texture.height; y++) { - flipped.SetPixel(x, y, texture.GetPixel(texture.width - x - 1, y)); + for (int x = 0; x < texture.width; x++) + { + flipped.SetPixel(x, y, texture.GetPixel(texture.width - x - 1, y)); + } } - } - flipped.Apply(); - layerEditor.uploadedImages[index] = flipped; + flipped.Apply(); + layerEditor.uploadedImages[index] = flipped; - Rect spriteRect = new Rect(0, 0, flipped.width, flipped.height); - Vector2 pivot = new Vector2(0.5f, 0.5f); - Sprite newSprite = Sprite.Create(flipped, spriteRect, pivot); + Rect spriteRect = new Rect(0, 0, flipped.width, flipped.height); + Vector2 pivot = new Vector2(0.5f, 0.5f); + Sprite newSprite = Sprite.Create(flipped, spriteRect, pivot); - GameObject spriteObj = layerEditor.spriteObjects[index]; - SpriteRenderer renderer = spriteObj.GetComponent(); - renderer.sprite = newSprite; - } + GameObject spriteObj = layerEditor.spriteObjects[index]; + SpriteRenderer renderer = spriteObj.GetComponent(); + renderer.sprite = newSprite; + } - private void FlipVertical(int index) - { - Texture2D texture = layerEditor.uploadedImages[index]; + private void FlipVertical(int index) + { + Texture2D texture = layerEditor.uploadedImages[index]; - Texture2D flipped = new Texture2D(texture.width, texture.height); + Texture2D flipped = new Texture2D(texture.width, texture.height); - for (int y = 0; y < texture.height; y++) - { - for (int x = 0; x < texture.width; x++) + for (int y = 0; y < texture.height; y++) { - flipped.SetPixel(x, y, texture.GetPixel(x, texture.height - y - 1)); + for (int x = 0; x < texture.width; x++) + { + flipped.SetPixel(x, y, texture.GetPixel(x, texture.height - y - 1)); + } } - } - flipped.Apply(); - layerEditor.uploadedImages[index] = flipped; + flipped.Apply(); + layerEditor.uploadedImages[index] = flipped; - Rect spriteRect = new Rect(0, 0, flipped.width, flipped.height); - Vector2 pivot = new Vector2(0.5f, 0.5f); - Sprite newSprite = Sprite.Create(flipped, spriteRect, pivot); + Rect spriteRect = new Rect(0, 0, flipped.width, flipped.height); + Vector2 pivot = new Vector2(0.5f, 0.5f); + Sprite newSprite = Sprite.Create(flipped, spriteRect, pivot); - GameObject spriteObj = layerEditor.spriteObjects[index]; - SpriteRenderer renderer = spriteObj.GetComponent(); - renderer.sprite = newSprite; - } + GameObject spriteObj = layerEditor.spriteObjects[index]; + SpriteRenderer renderer = spriteObj.GetComponent(); + renderer.sprite = newSprite; + } - private void RemoveBackground(int index) - { - if (index >= 0 && index < layerEditor.uploadedImages.Count) + private void RemoveBackground(int index) { - Texture2D texture2D = layerEditor.uploadedImages[index]; - string dataUrl = CommonUtils.Texture2DToDataURL(texture2D); - string name = CommonUtils.GetRandomImageFileName(); - string param = $"{{\"image\":\"{dataUrl}\",\"name\":\"{name}\",\"format\":\"png\",\"returnImage\":\"false\"}}"; - Debug.Log(param); - - ApiClient.RestPut("images/erase-background",param,response => + if (index >= 0 && index < layerEditor.uploadedImages.Count) { - dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content); - string imageUrl = jsonResponse.asset.url; - CommonUtils.FetchTextureFromURL(imageUrl, texture => - { - layerEditor.uploadedImages[index] = texture; + Texture2D texture2D = layerEditor.uploadedImages[index]; + string dataUrl = CommonUtils.Texture2DToDataURL(texture2D); + string name = CommonUtils.GetRandomImageFileName(); + string param = $"{{\"image\":\"{dataUrl}\",\"name\":\"{name}\",\"format\":\"png\",\"returnImage\":\"false\"}}"; + Debug.Log(param); - // Update the sprite - Rect spriteRect = new Rect(0, 0, texture.width, texture.height); - Vector2 pivot = new Vector2(0.5f, 0.5f); - Sprite newSprite = Sprite.Create(texture, spriteRect, pivot); - - GameObject spriteObj = layerEditor.spriteObjects[index]; - SpriteRenderer renderer = spriteObj.GetComponent(); - renderer.sprite = newSprite; + ApiClient.RestPut("images/erase-background",param,response => + { + dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content); + string imageUrl = jsonResponse.asset.url; + CommonUtils.FetchTextureFromURL(imageUrl, texture => + { + layerEditor.uploadedImages[index] = texture; + + // Update the sprite + Rect spriteRect = new Rect(0, 0, texture.width, texture.height); + Vector2 pivot = new Vector2(0.5f, 0.5f); + Sprite newSprite = Sprite.Create(texture, spriteRect, pivot); + + GameObject spriteObj = layerEditor.spriteObjects[index]; + SpriteRenderer renderer = spriteObj.GetComponent(); + renderer.sprite = newSprite; + }); }); - }); + } } } } diff --git a/Scenario/Editor/LayerEditor/LayerEditor.cs b/Scenario/Editor/LayerEditor/LayerEditor.cs index fc41172..6f81ba1 100644 --- a/Scenario/Editor/LayerEditor/LayerEditor.cs +++ b/Scenario/Editor/LayerEditor/LayerEditor.cs @@ -1,589 +1,590 @@ -using System; -using System.IO; -using System.Collections; using System.Collections.Generic; +using System.IO; using UnityEditor; using UnityEngine; -public class LayerEditor : EditorWindow +namespace Scenario { - [SerializeField] private float rightWidthRatio = 0.1f; - [SerializeField] private float leftWidthRatio = 0.9f; + public class LayerEditor : EditorWindow + { + [SerializeField] private float rightWidthRatio = 0.1f; + [SerializeField] private float leftWidthRatio = 0.9f; - public List uploadedImages = new(); - public List imagePositions = new(); - public List isDraggingList = new(); - public List imageSizes = new(); - public List spriteObjects = new(); + public List uploadedImages = new(); + public List imagePositions = new(); + public List isDraggingList = new(); + public List imageSizes = new(); + public List spriteObjects = new(); - private GUIStyle imageStyle; + private GUIStyle imageStyle; - public int selectedLayerIndex = -1; - private int selectedImageIndex = -1; - private const float HandleSize = 5f; + public int selectedLayerIndex = -1; + private int selectedImageIndex = -1; + private const float HandleSize = 5f; - private bool isRightPanelOpen = true; - private bool showPixelAlignment = true; - private bool showHorizontalAlignment = true; - private Vector2 canvasScrollPosition; - private bool isCropping = false; - private Rect cropRect; - private bool isCroppingActive = false; + private bool isRightPanelOpen = true; + private bool showPixelAlignment = true; + private bool showHorizontalAlignment = true; + private Vector2 canvasScrollPosition; + private bool isCropping = false; + private Rect cropRect; + private bool isCroppingActive = false; - private double lastClickTime = 0; - private const double DoubleClickTimeThreshold = 0.3; + private double lastClickTime = 0; + private const double DoubleClickTimeThreshold = 0.3; - public Texture2D backgroundImage; + public Texture2D backgroundImage; - private float zoomFactor = 1f; + private float zoomFactor = 1f; - private LayerEditorRightPanel rightPanel; - private ContextMenuActions contextMenuActions; + private LayerEditorRightPanel rightPanel; + private ContextMenuActions contextMenuActions; - [MenuItem("Window/Layer Editor")] - public static void ShowWindow() - { - GetWindow("Layer Editor"); - } - - private void OnEnable() - { - imageStyle = new GUIStyle + [MenuItem("Window/Layer Editor")] + public static void ShowWindow() { - alignment = TextAnchor.MiddleCenter - }; + GetWindow("Layer Editor"); + } - uploadedImages = new List(); - imagePositions = new List(); - isDraggingList = new List(); - imageSizes = new List(); - spriteObjects = new List(); + private void OnEnable() + { + imageStyle = new GUIStyle + { + alignment = TextAnchor.MiddleCenter + }; - rightPanel = new LayerEditorRightPanel(this); - contextMenuActions = new ContextMenuActions(this); - } + uploadedImages = new List(); + imagePositions = new List(); + isDraggingList = new List(); + imageSizes = new List(); + spriteObjects = new List(); - private void OnDestroy() - { - uploadedImages.Clear(); - imagePositions.Clear(); - isDraggingList.Clear(); - imageSizes.Clear(); - spriteObjects.Clear(); - } + rightPanel = new LayerEditorRightPanel(this); + contextMenuActions = new ContextMenuActions(this); + } - private void OnGUI() - { - float totalWidth = position.width; - float leftWidth = isRightPanelOpen ? totalWidth * leftWidthRatio : totalWidth; - float rightWidth = isRightPanelOpen ? totalWidth * rightWidthRatio : 0f; + private void OnDestroy() + { + uploadedImages.Clear(); + imagePositions.Clear(); + isDraggingList.Clear(); + imageSizes.Clear(); + spriteObjects.Clear(); + } - EditorGUILayout.BeginHorizontal(); + private void OnGUI() { - EditorGUILayout.BeginVertical(GUILayout.Width(leftWidth)); + float totalWidth = position.width; + float leftWidth = isRightPanelOpen ? totalWidth * leftWidthRatio : totalWidth; + float rightWidth = isRightPanelOpen ? totalWidth * rightWidthRatio : 0f; + + EditorGUILayout.BeginHorizontal(); { - DrawCanvas(leftWidth); + EditorGUILayout.BeginVertical(GUILayout.Width(leftWidth)); + { + DrawCanvas(leftWidth); + } + EditorGUILayout.EndVertical(); + + if (isRightPanelOpen) + { + rightPanel.DrawRightPanel(rightWidth); + } } - EditorGUILayout.EndVertical(); + EditorGUILayout.EndHorizontal(); - if (isRightPanelOpen) + var buttonStyle = new GUIStyle(GUI.skin.button) { - rightPanel.DrawRightPanel(rightWidth); + fontSize = 30 + }; + + float buttonSize = 50; + float buttonX = isRightPanelOpen ? position.width - buttonSize - rightWidth : position.width - buttonSize; + if (GUI.Button(new Rect(buttonX, 0, buttonSize, buttonSize), "≡", buttonStyle)) + { + isRightPanelOpen = !isRightPanelOpen; + Repaint(); } } - EditorGUILayout.EndHorizontal(); - var buttonStyle = new GUIStyle(GUI.skin.button) - { - fontSize = 30 - }; - float buttonSize = 50; - float buttonX = isRightPanelOpen ? position.width - buttonSize - rightWidth : position.width - buttonSize; - if (GUI.Button(new Rect(buttonX, 0, buttonSize, buttonSize), "≡", buttonStyle)) + private void DrawCanvas(float canvasWidth) { - isRightPanelOpen = !isRightPanelOpen; - Repaint(); - } - } + Color backgroundColor = new Color32(18, 18, 18, 255); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); + Rect canvasRect = GUILayoutUtility.GetRect(canvasWidth, position.height); + GUI.Box(canvasRect, GUIContent.none); - private void DrawCanvas(float canvasWidth) - { - Color backgroundColor = new Color32(18, 18, 18, 255); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - - Rect canvasRect = GUILayoutUtility.GetRect(canvasWidth, position.height); - GUI.Box(canvasRect, GUIContent.none); + Vector2 canvasContentSize = new Vector2(canvasWidth * zoomFactor, position.height * zoomFactor); - Vector2 canvasContentSize = new Vector2(canvasWidth * zoomFactor, position.height * zoomFactor); - - canvasScrollPosition = GUI.BeginScrollView(canvasRect, canvasScrollPosition, new Rect(Vector2.zero, canvasContentSize)); - { - canvasRect = DrawImageList(canvasWidth, canvasRect, canvasContentSize); - DrawImageView(canvasRect); + canvasScrollPosition = GUI.BeginScrollView(canvasRect, canvasScrollPosition, new Rect(Vector2.zero, canvasContentSize)); + { + canvasRect = DrawImageList(canvasWidth, canvasRect, canvasContentSize); + DrawImageView(canvasRect); + } + GUI.EndScrollView(); } - GUI.EndScrollView(); - } - private Rect DrawImageList(float canvasWidth, Rect canvasRect, Vector2 canvasContentSize) - { - GUI.BeginGroup(new Rect(Vector2.zero, canvasContentSize)); + private Rect DrawImageList(float canvasWidth, Rect canvasRect, Vector2 canvasContentSize) { - DrawBackgroundImage(canvasWidth); - - if (Event.current.type == EventType.DragUpdated && canvasRect.Contains(Event.current.mousePosition)) + GUI.BeginGroup(new Rect(Vector2.zero, canvasContentSize)); { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - Event.current.Use(); - } - else if (Event.current.type == EventType.DragPerform && canvasRect.Contains(Event.current.mousePosition)) - { - DragAndDrop.AcceptDrag(); - DragAndDrop.paths = FilterImagePaths(DragAndDrop.paths); + DrawBackgroundImage(canvasWidth); - foreach (string imagePath in DragAndDrop.paths) + if (Event.current.type == EventType.DragUpdated && canvasRect.Contains(Event.current.mousePosition)) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + Event.current.Use(); + } + else if (Event.current.type == EventType.DragPerform && canvasRect.Contains(Event.current.mousePosition)) { - Texture2D uploadedImage = LoadImageFromPath(imagePath); - if (uploadedImage == null) continue; + DragAndDrop.AcceptDrag(); + DragAndDrop.paths = FilterImagePaths(DragAndDrop.paths); + + foreach (string imagePath in DragAndDrop.paths) + { + Texture2D uploadedImage = LoadImageFromPath(imagePath); + if (uploadedImage == null) continue; - uploadedImages.Add(uploadedImage); + uploadedImages.Add(uploadedImage); - // Drop the image at mouse position - Vector2 imageCenter = new Vector2(uploadedImage.width / 2f, uploadedImage.height / 2f); - Vector2 imagePosition = new Vector2( - Event.current.mousePosition.x - canvasRect.x, - Event.current.mousePosition.y - canvasRect.y - ); + // Drop the image at mouse position + Vector2 imageCenter = new Vector2(uploadedImage.width / 2f, uploadedImage.height / 2f); + Vector2 imagePosition = new Vector2( + Event.current.mousePosition.x - canvasRect.x, + Event.current.mousePosition.y - canvasRect.y + ); - imagePositions.Add( imagePosition - imageCenter); - isDraggingList.Add(false); - imageSizes.Add(new Vector2(uploadedImage.width, uploadedImage.height)); + imagePositions.Add( imagePosition - imageCenter); + isDraggingList.Add(false); + imageSizes.Add(new Vector2(uploadedImage.width, uploadedImage.height)); - Rect rect = new Rect(0, 0, uploadedImage.width, uploadedImage.height); - Vector2 pivot = new Vector2(0.5f, 0.5f); - Sprite sprite = Sprite.Create(uploadedImage, rect, pivot); + Rect rect = new Rect(0, 0, uploadedImage.width, uploadedImage.height); + Vector2 pivot = new Vector2(0.5f, 0.5f); + Sprite sprite = Sprite.Create(uploadedImage, rect, pivot); - GameObject spriteObj = new GameObject("SpriteObj"); - SpriteRenderer renderer = spriteObj.AddComponent(); - renderer.sprite = sprite; + GameObject spriteObj = new GameObject("SpriteObj"); + SpriteRenderer renderer = spriteObj.AddComponent(); + renderer.sprite = sprite; - spriteObj.transform.position = new Vector3(0, 0, 0); - spriteObjects.Add(spriteObj); - } + spriteObj.transform.position = new Vector3(0, 0, 0); + spriteObjects.Add(spriteObj); + } - Event.current.Use(); + Event.current.Use(); + } } + GUI.EndGroup(); + return canvasRect; } - GUI.EndGroup(); - return canvasRect; - } - private void DrawBackgroundImage(float canvasWidth) - { - if (backgroundImage == null) return; + private void DrawBackgroundImage(float canvasWidth) + { + if (backgroundImage == null) return; - GUI.DrawTexture(new Rect(Vector2.zero, new Vector2(canvasWidth, position.height) * zoomFactor), - backgroundImage, ScaleMode.ScaleToFit, true); - } - - private void DrawImageView(Rect canvasRect) - { - GUI.BeginGroup(canvasRect); - - // Calculate the center of the canvas - Vector2 canvasCenter = canvasRect.center; + GUI.DrawTexture(new Rect(Vector2.zero, new Vector2(canvasWidth, position.height) * zoomFactor), + backgroundImage, ScaleMode.ScaleToFit, true); + } - for (int i = 0; i < uploadedImages.Count; i++) + private void DrawImageView(Rect canvasRect) { - DrawImage(canvasCenter, i); - } + GUI.BeginGroup(canvasRect); - GUI.EndGroup(); - } + // Calculate the center of the canvas + Vector2 canvasCenter = canvasRect.center; - private void DrawImage(Vector2 canvasCenter, int i) - { - int index = i; + for (int i = 0; i < uploadedImages.Count; i++) + { + DrawImage(canvasCenter, i); + } - Texture2D uploadedImage = uploadedImages[i]; - Vector2 imagePosition = imagePositions[i]; - Vector2 imageSize = imageSizes[i]; - bool isDragging = isDraggingList[i]; + GUI.EndGroup(); + } - float imageSizeXHalf = (imageSize.x / 2.0f); - float imageSizeYHalf = (imageSize.y / 2.0f); - var halfSize = new Vector2(imageSizeXHalf, imageSizeYHalf); + private void DrawImage(Vector2 canvasCenter, int i) + { + int index = i; - // Calculate the transformed position with the center as anchor - Vector2 transformedPosition = canvasCenter + (imagePosition - halfSize) * zoomFactor; - Vector2 transformedSize = imageSize * zoomFactor; + Texture2D uploadedImage = uploadedImages[i]; + Vector2 imagePosition = imagePositions[i]; + Vector2 imageSize = imageSizes[i]; + bool isDragging = isDraggingList[i]; - Rect imageRect = new Rect(transformedPosition, transformedSize); - GUI.DrawTexture(imageRect, uploadedImage); + float imageSizeXHalf = (imageSize.x / 2.0f); + float imageSizeYHalf = (imageSize.y / 2.0f); + var halfSize = new Vector2(imageSizeXHalf, imageSizeYHalf); - HandleImageEvents(i, index, ref imagePosition, ref imageSize, ref isDragging, imageRect); - } + // Calculate the transformed position with the center as anchor + Vector2 transformedPosition = canvasCenter + (imagePosition - halfSize) * zoomFactor; + Vector2 transformedSize = imageSize * zoomFactor; - private void HandleImageEvents(int i, int index, ref Vector2 imagePosition, ref Vector2 imageSize, ref bool isDragging, Rect imageRect) - { - Vector2 transformedMousePosition = Event.current.mousePosition / zoomFactor; + Rect imageRect = new Rect(transformedPosition, transformedSize); + GUI.DrawTexture(imageRect, uploadedImage); - if (Event.current.type == EventType.ScrollWheel) - { - HandleScrollWheel(i, ref imageSize, ref imageRect); + HandleImageEvents(i, index, ref imagePosition, ref imageSize, ref isDragging, imageRect); } - if (Event.current.type == EventType.MouseDown && imageRect.Contains(Event.current.mousePosition)) + private void HandleImageEvents(int i, int index, ref Vector2 imagePosition, ref Vector2 imageSize, ref bool isDragging, Rect imageRect) { - switch (Event.current.button) + Vector2 transformedMousePosition = Event.current.mousePosition / zoomFactor; + + if (Event.current.type == EventType.ScrollWheel) + { + HandleScrollWheel(i, ref imageSize, ref imageRect); + } + + if (Event.current.type == EventType.MouseDown && imageRect.Contains(Event.current.mousePosition)) { - case 0: + switch (Event.current.button) { - double clickTime = EditorApplication.timeSinceStartup; - if (clickTime - lastClickTime < DoubleClickTimeThreshold) + case 0: { - if (selectedImageIndex == i && isCropping && isCroppingActive) + double clickTime = EditorApplication.timeSinceStartup; + if (clickTime - lastClickTime < DoubleClickTimeThreshold) { - CropImage(i, cropRect); - isCroppingActive = false; + if (selectedImageIndex == i && isCropping && isCroppingActive) + { + CropImage(i, cropRect); + isCroppingActive = false; + } + else + { + selectedImageIndex = i; + isDragging = false; + isCropping = true; + isCroppingActive = true; + cropRect = imageRect; + } } else { selectedImageIndex = i; - isDragging = false; - isCropping = true; - isCroppingActive = true; - cropRect = imageRect; + isDragging = true; + isCropping = false; + isCroppingActive = false; + cropRect = Rect.zero; } - } - else - { - selectedImageIndex = i; - isDragging = true; - isCropping = false; - isCroppingActive = false; - cropRect = Rect.zero; - } - lastClickTime = clickTime; - Event.current.Use(); - break; + lastClickTime = clickTime; + Event.current.Use(); + break; + } + case 1: + CreateContextMenu(index); + break; } - case 1: - CreateContextMenu(index); - break; } - } - else if (Event.current.type == EventType.MouseDrag && isDragging && !isCropping) - { - Vector2 oldPosition = imagePosition; - Vector2 transformedDelta = Event.current.delta / zoomFactor; - Vector2 newPosition = imagePosition + transformedDelta; + else if (Event.current.type == EventType.MouseDrag && isDragging && !isCropping) + { + Vector2 oldPosition = imagePosition; + Vector2 transformedDelta = Event.current.delta / zoomFactor; + Vector2 newPosition = imagePosition + transformedDelta; - imagePosition = newPosition; - Vector2 delta = newPosition - oldPosition; - - float scaleFactor = 0.01f; - Vector3 sceneDelta = new Vector3(delta.x, -delta.y, 0) * scaleFactor; + imagePosition = newPosition; + Vector2 delta = newPosition - oldPosition; - GameObject spriteObj = spriteObjects[i]; - spriteObj.transform.position += sceneDelta; + float scaleFactor = 0.01f; + Vector3 sceneDelta = new Vector3(delta.x, -delta.y, 0) * scaleFactor; - Event.current.Use(); - } - else if (Event.current.type == EventType.MouseDrag && isCropping) - { - OnMouseClickDrag_Crop(index, imageRect, transformedMousePosition); - } - else if (Event.current.type == EventType.MouseUp && isDragging) - { - isDragging = false; - selectedImageIndex = -1; - Event.current.Use(); - } - else if (Event.current.type == EventType.MouseUp && isCropping) - { - CropImage(i, cropRect); - Event.current.Use(); - } - - imagePositions[i] = imagePosition; - isDraggingList[i] = isDragging; - - HandleIsDragging(i, isDragging, imageRect); - HandleIsCropping(); - } - - private void OnMouseClickDrag_Crop(int index, Rect imageRect, Vector2 transformedMousePosition) - { - if (Event.current.button == 0) - { - bool croppingRight = Mathf.Abs(transformedMousePosition.x - cropRect.xMax) < HandleSize; - bool croppingLeft = Mathf.Abs(transformedMousePosition.x - cropRect.xMin) < HandleSize; - bool croppingBottom = Mathf.Abs(transformedMousePosition.y - cropRect.yMax) < HandleSize; - bool croppingTop = Mathf.Abs(transformedMousePosition.y - cropRect.yMin) < HandleSize; + GameObject spriteObj = spriteObjects[i]; + spriteObj.transform.position += sceneDelta; - if (croppingRight) - { - int prevWidth = Mathf.RoundToInt(cropRect.width); - cropRect.width += Event.current.delta.x; - cropRect.width = Mathf.Max(cropRect.width, 10f); - int newWidth = Mathf.RoundToInt(cropRect.width); - DeletePixelsHorizontal(index, prevWidth, newWidth); + Event.current.Use(); } - else if (croppingLeft) + else if (Event.current.type == EventType.MouseDrag && isCropping) { - int prevWidth = Mathf.RoundToInt(cropRect.width); - cropRect.x += Event.current.delta.x; - cropRect.width -= Event.current.delta.x; - cropRect.width = Mathf.Max(cropRect.width, 10f); - int newWidth = Mathf.RoundToInt(cropRect.width); - DeletePixelsHorizontal(index, newWidth, prevWidth); + OnMouseClickDrag_Crop(index, imageRect, transformedMousePosition); } - - if (croppingBottom) + else if (Event.current.type == EventType.MouseUp && isDragging) { - int prevHeight = Mathf.RoundToInt(cropRect.height); - cropRect.height += Event.current.delta.y; - cropRect.height = Mathf.Max(cropRect.height, 10f); - int newHeight = Mathf.RoundToInt(cropRect.height); - DeletePixelsVertical(index, prevHeight, newHeight); + isDragging = false; + selectedImageIndex = -1; + Event.current.Use(); } - else if (croppingTop) + else if (Event.current.type == EventType.MouseUp && isCropping) { - int prevHeight = Mathf.RoundToInt(cropRect.height); - cropRect.y += Event.current.delta.y; - cropRect.height -= Event.current.delta.y; - cropRect.height = Mathf.Max(cropRect.height, 10f); - int newHeight = Mathf.RoundToInt(cropRect.height); - DeletePixelsVertical(index, newHeight, prevHeight); + CropImage(i, cropRect); + Event.current.Use(); } - } - cropRect.width = Mathf.Clamp(cropRect.width, 0f, imageRect.width); - cropRect.height = Mathf.Clamp(cropRect.height, 0f, imageRect.height); - cropRect.x = Mathf.Clamp(cropRect.x, imageRect.x, imageRect.xMax - cropRect.width); - cropRect.y = Mathf.Clamp(cropRect.y, imageRect.y, imageRect.yMax - cropRect.height); + imagePositions[i] = imagePosition; + isDraggingList[i] = isDragging; - Event.current.Use(); - } + HandleIsDragging(i, isDragging, imageRect); + HandleIsCropping(); + } - private void HandleIsCropping() - { - if (!isCropping) return; - - float borderThickness = 1f; - Color borderColor = Color.white; + private void OnMouseClickDrag_Crop(int index, Rect imageRect, Vector2 transformedMousePosition) + { + if (Event.current.button == 0) + { + bool croppingRight = Mathf.Abs(transformedMousePosition.x - cropRect.xMax) < HandleSize; + bool croppingLeft = Mathf.Abs(transformedMousePosition.x - cropRect.xMin) < HandleSize; + bool croppingBottom = Mathf.Abs(transformedMousePosition.y - cropRect.yMax) < HandleSize; + bool croppingTop = Mathf.Abs(transformedMousePosition.y - cropRect.yMin) < HandleSize; + + if (croppingRight) + { + int prevWidth = Mathf.RoundToInt(cropRect.width); + cropRect.width += Event.current.delta.x; + cropRect.width = Mathf.Max(cropRect.width, 10f); + int newWidth = Mathf.RoundToInt(cropRect.width); + DeletePixelsHorizontal(index, prevWidth, newWidth); + } + else if (croppingLeft) + { + int prevWidth = Mathf.RoundToInt(cropRect.width); + cropRect.x += Event.current.delta.x; + cropRect.width -= Event.current.delta.x; + cropRect.width = Mathf.Max(cropRect.width, 10f); + int newWidth = Mathf.RoundToInt(cropRect.width); + DeletePixelsHorizontal(index, newWidth, prevWidth); + } - EditorGUI.DrawRect(cropRect, new Color(1, 1, 1, 0.1f)); + if (croppingBottom) + { + int prevHeight = Mathf.RoundToInt(cropRect.height); + cropRect.height += Event.current.delta.y; + cropRect.height = Mathf.Max(cropRect.height, 10f); + int newHeight = Mathf.RoundToInt(cropRect.height); + DeletePixelsVertical(index, prevHeight, newHeight); + } + else if (croppingTop) + { + int prevHeight = Mathf.RoundToInt(cropRect.height); + cropRect.y += Event.current.delta.y; + cropRect.height -= Event.current.delta.y; + cropRect.height = Mathf.Max(cropRect.height, 10f); + int newHeight = Mathf.RoundToInt(cropRect.height); + DeletePixelsVertical(index, newHeight, prevHeight); + } + } - float lineHeight = cropRect.height / 3f; - float columnWidth = cropRect.width / 3f; + cropRect.width = Mathf.Clamp(cropRect.width, 0f, imageRect.width); + cropRect.height = Mathf.Clamp(cropRect.height, 0f, imageRect.height); + cropRect.x = Mathf.Clamp(cropRect.x, imageRect.x, imageRect.xMax - cropRect.width); + cropRect.y = Mathf.Clamp(cropRect.y, imageRect.y, imageRect.yMax - cropRect.height); - for (int lineIndex = 1; lineIndex <= 2; lineIndex++) - { - float lineY = cropRect.y + lineIndex * lineHeight; - Rect lineRect = new Rect(cropRect.x, lineY, cropRect.width, borderThickness); - EditorGUI.DrawRect(lineRect, borderColor); + Event.current.Use(); } - for (int columnIndex = 1; columnIndex <= 2; columnIndex++) + private void HandleIsCropping() { - float lineX = cropRect.x + columnIndex * columnWidth; - Rect lineRect = new Rect(lineX, cropRect.y, borderThickness, cropRect.height); - EditorGUI.DrawRect(lineRect, borderColor); - } + if (!isCropping) return; + + float borderThickness = 1f; + Color borderColor = Color.white; - EditorGUI.DrawRect(new Rect(cropRect.x - borderThickness, cropRect.y - borderThickness, cropRect.width + 2 * borderThickness, borderThickness), borderColor); - EditorGUI.DrawRect(new Rect(cropRect.x - borderThickness, cropRect.y + cropRect.height, cropRect.width + 2 * borderThickness, borderThickness), borderColor); - EditorGUI.DrawRect(new Rect(cropRect.x - borderThickness, cropRect.y, borderThickness, cropRect.height), borderColor); - EditorGUI.DrawRect(new Rect(cropRect.x + cropRect.width, cropRect.y, borderThickness, cropRect.height), borderColor); - } + EditorGUI.DrawRect(cropRect, new Color(1, 1, 1, 0.1f)); - private void HandleIsDragging(int i, bool isDragging, Rect imageRect) - { - if (!isDragging) return; - - if (showPixelAlignment && i < uploadedImages.Count - 1) - { - Rect nextImageRect = new Rect(imagePositions[i + 1] * zoomFactor, imageSizes[i + 1] * zoomFactor); - Rect lineRect = new Rect(imageRect.xMax, imageRect.y, nextImageRect.xMin - imageRect.xMax, imageRect.height); - if (lineRect.width > 0 && lineRect.height > 0) + float lineHeight = cropRect.height / 3f; + float columnWidth = cropRect.width / 3f; + + for (int lineIndex = 1; lineIndex <= 2; lineIndex++) + { + float lineY = cropRect.y + lineIndex * lineHeight; + Rect lineRect = new Rect(cropRect.x, lineY, cropRect.width, borderThickness); + EditorGUI.DrawRect(lineRect, borderColor); + } + + for (int columnIndex = 1; columnIndex <= 2; columnIndex++) { - EditorGUI.DrawRect(lineRect, Color.red); + float lineX = cropRect.x + columnIndex * columnWidth; + Rect lineRect = new Rect(lineX, cropRect.y, borderThickness, cropRect.height); + EditorGUI.DrawRect(lineRect, borderColor); } + + EditorGUI.DrawRect(new Rect(cropRect.x - borderThickness, cropRect.y - borderThickness, cropRect.width + 2 * borderThickness, borderThickness), borderColor); + EditorGUI.DrawRect(new Rect(cropRect.x - borderThickness, cropRect.y + cropRect.height, cropRect.width + 2 * borderThickness, borderThickness), borderColor); + EditorGUI.DrawRect(new Rect(cropRect.x - borderThickness, cropRect.y, borderThickness, cropRect.height), borderColor); + EditorGUI.DrawRect(new Rect(cropRect.x + cropRect.width, cropRect.y, borderThickness, cropRect.height), borderColor); } - if (showHorizontalAlignment && i < uploadedImages.Count - 1 && Mathf.Approximately(imagePositions[i].y, imagePositions[i + 1].y)) + private void HandleIsDragging(int i, bool isDragging, Rect imageRect) { - Rect nextImageRect = new Rect(imagePositions[i + 1] * zoomFactor, imageSizes[i + 1] * zoomFactor); - Rect lineRect = new Rect(imageRect.xMin, imageRect.y, Mathf.Max(imageRect.width, nextImageRect.width), 1f); - if (lineRect.width > 0 && lineRect.height > 0) + if (!isDragging) return; + + if (showPixelAlignment && i < uploadedImages.Count - 1) { - EditorGUI.DrawRect(lineRect, Color.red); + Rect nextImageRect = new Rect(imagePositions[i + 1] * zoomFactor, imageSizes[i + 1] * zoomFactor); + Rect lineRect = new Rect(imageRect.xMax, imageRect.y, nextImageRect.xMin - imageRect.xMax, imageRect.height); + if (lineRect.width > 0 && lineRect.height > 0) + { + EditorGUI.DrawRect(lineRect, Color.red); + } + } + + if (showHorizontalAlignment && i < uploadedImages.Count - 1 && Mathf.Approximately(imagePositions[i].y, imagePositions[i + 1].y)) + { + Rect nextImageRect = new Rect(imagePositions[i + 1] * zoomFactor, imageSizes[i + 1] * zoomFactor); + Rect lineRect = new Rect(imageRect.xMin, imageRect.y, Mathf.Max(imageRect.width, nextImageRect.width), 1f); + if (lineRect.width > 0 && lineRect.height > 0) + { + EditorGUI.DrawRect(lineRect, Color.red); + } } } - } - private void HandleScrollWheel(int i, ref Vector2 imageSize, ref Rect imageRect) - { - if (Event.current.control) + private void HandleScrollWheel(int i, ref Vector2 imageSize, ref Rect imageRect) { - if (imageRect.Contains(Event.current.mousePosition)) + if (Event.current.control) { - float scaleFactor = ScaleImage(ref imageSize); - imageSizes[i] = imageSize; + if (imageRect.Contains(Event.current.mousePosition)) + { + float scaleFactor = ScaleImage(ref imageSize); + imageSizes[i] = imageSize; - // Scale the corresponding GameObject as well - GameObject spriteObj = spriteObjects[i]; - spriteObj.transform.localScale *= scaleFactor; + // Scale the corresponding GameObject as well + GameObject spriteObj = spriteObjects[i]; + spriteObj.transform.localScale *= scaleFactor; + } + Event.current.Use(); + } + else + { + Vector2 mousePositionBeforeZoom = (Event.current.mousePosition + canvasScrollPosition) / zoomFactor; + zoomFactor -= Event.current.delta.y * 0.01f; + zoomFactor = Mathf.Clamp(zoomFactor, 0.1f, 1f); + Vector2 mousePositionAfterZoom = (Event.current.mousePosition + canvasScrollPosition) / zoomFactor; + canvasScrollPosition += (mousePositionAfterZoom - mousePositionBeforeZoom) * zoomFactor; + Event.current.Use(); } - Event.current.Use(); } - else + + private static float ScaleImage(ref Vector2 imageSize) { - Vector2 mousePositionBeforeZoom = (Event.current.mousePosition + canvasScrollPosition) / zoomFactor; - zoomFactor -= Event.current.delta.y * 0.01f; - zoomFactor = Mathf.Clamp(zoomFactor, 0.1f, 1f); - Vector2 mousePositionAfterZoom = (Event.current.mousePosition + canvasScrollPosition) / zoomFactor; - canvasScrollPosition += (mousePositionAfterZoom - mousePositionBeforeZoom) * zoomFactor; - Event.current.Use(); + float scaleFactor = Event.current.delta.y > 0 ? 0.9f : 1.1f; + imageSize *= scaleFactor; + imageSize = Vector2.Max(imageSize, new Vector2(10, 10)); + imageSize = Vector2.Min(imageSize, new Vector2(1000, 1000)); + return scaleFactor; } - } - - private static float ScaleImage(ref Vector2 imageSize) - { - float scaleFactor = Event.current.delta.y > 0 ? 0.9f : 1.1f; - imageSize *= scaleFactor; - imageSize = Vector2.Max(imageSize, new Vector2(10, 10)); - imageSize = Vector2.Min(imageSize, new Vector2(1000, 1000)); - return scaleFactor; - } - private void CreateContextMenu(int index) - { - contextMenuActions.CreateContextMenu(index); - } + private void CreateContextMenu(int index) + { + contextMenuActions.CreateContextMenu(index); + } - private Texture2D LoadImageFromPath(string path) - { - Texture2D texture = new Texture2D(2, 2, TextureFormat.RGBA32, false); - byte[] imageData = File.ReadAllBytes(path); - texture.LoadImage(imageData); - return texture; - } + private Texture2D LoadImageFromPath(string path) + { + Texture2D texture = new Texture2D(2, 2, TextureFormat.RGBA32, false); + byte[] imageData = File.ReadAllBytes(path); + texture.LoadImage(imageData); + return texture; + } - private string[] FilterImagePaths(string[] paths) - { - List filteredPaths = new List(); - foreach (string path in paths) + private string[] FilterImagePaths(string[] paths) { - if (IsImagePath(path)) + List filteredPaths = new List(); + foreach (string path in paths) { - filteredPaths.Add(path); + if (IsImagePath(path)) + { + filteredPaths.Add(path); + } } + return filteredPaths.ToArray(); } - return filteredPaths.ToArray(); - } - private bool IsImagePath(string path) - { - string extension = Path.GetExtension(path).ToLower(); - return extension is ".png" or ".jpg" or ".jpeg" or ".gif" or ".bmp"; - } - - private void DeletePixelsHorizontal(int index, int prevWidth, int newWidth) - { - Texture2D image = uploadedImages[index]; - int startX = Mathf.Min(prevWidth, newWidth); - int endX = Mathf.Max(prevWidth, newWidth); + private bool IsImagePath(string path) + { + string extension = Path.GetExtension(path).ToLower(); + return extension is ".png" or ".jpg" or ".jpeg" or ".gif" or ".bmp"; + } - if (newWidth < prevWidth) + private void DeletePixelsHorizontal(int index, int prevWidth, int newWidth) { - for (int x = startX; x < endX; x++) + Texture2D image = uploadedImages[index]; + int startX = Mathf.Min(prevWidth, newWidth); + int endX = Mathf.Max(prevWidth, newWidth); + + if (newWidth < prevWidth) { - for (int y = 0; y < image.height; y++) + for (int x = startX; x < endX; x++) { - image.SetPixel(x, y, Color.clear); + for (int y = 0; y < image.height; y++) + { + image.SetPixel(x, y, Color.clear); + } } } - } - else - { - for (int x = startX; x < endX; x++) + else { - for (int y = 0; y < image.height; y++) + for (int x = startX; x < endX; x++) { - int reversedX = image.width - 1 - x; - image.SetPixel(reversedX, y, Color.clear); + for (int y = 0; y < image.height; y++) + { + int reversedX = image.width - 1 - x; + image.SetPixel(reversedX, y, Color.clear); + } } } - } - - image.Apply(); - } - private void DeletePixelsVertical(int index, int prevHeight, int newHeight) - { - Texture2D image = uploadedImages[index]; - int startY = Mathf.Min(prevHeight, newHeight); - int endY = Mathf.Max(prevHeight, newHeight); + image.Apply(); + } - if (newHeight < prevHeight) + private void DeletePixelsVertical(int index, int prevHeight, int newHeight) { - for (int y = startY; y < endY; y++) + Texture2D image = uploadedImages[index]; + int startY = Mathf.Min(prevHeight, newHeight); + int endY = Mathf.Max(prevHeight, newHeight); + + if (newHeight < prevHeight) { - for (int x = 0; x < image.width; x++) + for (int y = startY; y < endY; y++) { - int reversedY = image.height - 1 - y; - image.SetPixel(x, reversedY, Color.clear); + for (int x = 0; x < image.width; x++) + { + int reversedY = image.height - 1 - y; + image.SetPixel(x, reversedY, Color.clear); + } } } - } - else - { - for (int y = startY; y < endY; y++) + else { - for (int x = 0; x < image.width; x++) + for (int y = startY; y < endY; y++) { - image.SetPixel(x, y, Color.clear); + for (int x = 0; x < image.width; x++) + { + image.SetPixel(x, y, Color.clear); + } } } - } - image.Apply(); - } + image.Apply(); + } - private void CropImage(int index, Rect rectCrop) - { - Texture2D originalImage = uploadedImages[index]; - - int x = Mathf.RoundToInt(rectCrop.x - imagePositions[index].x); - int y = Mathf.RoundToInt((imagePositions[index].y + imageSizes[index].y) - (rectCrop.y + rectCrop.height)); - int width = Mathf.RoundToInt(rectCrop.width); - int height = Mathf.RoundToInt(rectCrop.height); - - x = Mathf.Clamp(x, 0, originalImage.width); - y = Mathf.Clamp(y, 0, originalImage.height); - width = Mathf.Clamp(width, 0, originalImage.width - x); - height = Mathf.Clamp(height, 0, originalImage.height - y); - - Texture2D croppedImage = new Texture2D(width, height); - Color[] pixels = originalImage.GetPixels(x, y, width, height); - croppedImage.SetPixels(pixels); - croppedImage.Apply(); - - uploadedImages[index] = croppedImage; - imagePositions[index] = new Vector2(imagePositions[index].x + x, imagePositions[index].y + imageSizes[index].y - (y + height)); - imageSizes[index] = new Vector2(width, height); - - Rect spriteRect = new Rect(0, 0, croppedImage.width, croppedImage.height); - Vector2 pivot = new Vector2(0.5f, 0.5f); - Sprite newSprite = Sprite.Create(croppedImage, spriteRect, pivot); - - GameObject spriteObj = spriteObjects[index]; - SpriteRenderer renderer = spriteObj.GetComponent(); - renderer.sprite = newSprite; + private void CropImage(int index, Rect rectCrop) + { + Texture2D originalImage = uploadedImages[index]; + + int x = Mathf.RoundToInt(rectCrop.x - imagePositions[index].x); + int y = Mathf.RoundToInt((imagePositions[index].y + imageSizes[index].y) - (rectCrop.y + rectCrop.height)); + int width = Mathf.RoundToInt(rectCrop.width); + int height = Mathf.RoundToInt(rectCrop.height); + + x = Mathf.Clamp(x, 0, originalImage.width); + y = Mathf.Clamp(y, 0, originalImage.height); + width = Mathf.Clamp(width, 0, originalImage.width - x); + height = Mathf.Clamp(height, 0, originalImage.height - y); + + Texture2D croppedImage = new Texture2D(width, height); + Color[] pixels = originalImage.GetPixels(x, y, width, height); + croppedImage.SetPixels(pixels); + croppedImage.Apply(); + + uploadedImages[index] = croppedImage; + imagePositions[index] = new Vector2(imagePositions[index].x + x, imagePositions[index].y + imageSizes[index].y - (y + height)); + imageSizes[index] = new Vector2(width, height); + + Rect spriteRect = new Rect(0, 0, croppedImage.width, croppedImage.height); + Vector2 pivot = new Vector2(0.5f, 0.5f); + Sprite newSprite = Sprite.Create(croppedImage, spriteRect, pivot); + + GameObject spriteObj = spriteObjects[index]; + SpriteRenderer renderer = spriteObj.GetComponent(); + renderer.sprite = newSprite; + } } } \ No newline at end of file diff --git a/Scenario/Editor/LayerEditor/LayerEditorRightPanel.cs b/Scenario/Editor/LayerEditor/LayerEditorRightPanel.cs index 6657f81..79c820a 100644 --- a/Scenario/Editor/LayerEditor/LayerEditorRightPanel.cs +++ b/Scenario/Editor/LayerEditor/LayerEditorRightPanel.cs @@ -1,56 +1,58 @@ -using System.Collections.Generic; using UnityEditor; using UnityEngine; -public class LayerEditorRightPanel +namespace Scenario { - private LayerEditor editor; - - public LayerEditorRightPanel(LayerEditor editor) + public class LayerEditorRightPanel { - this.editor = editor; - } + private LayerEditor editor; + + public LayerEditorRightPanel(LayerEditor editor) + { + this.editor = editor; + } - public void DrawRightPanel(float rightWidth) - { - EditorGUILayout.BeginVertical(GUILayout.Width(rightWidth)); - - for (int i = 0; i < editor.uploadedImages.Count; i++) + public void DrawRightPanel(float rightWidth) { - Texture2D uploadedImage = editor.uploadedImages[i]; - EditorGUILayout.BeginHorizontal(); + EditorGUILayout.BeginVertical(GUILayout.Width(rightWidth)); + + for (int i = 0; i < editor.uploadedImages.Count; i++) { - // Display Thumbnail Image - GUILayout.Label(uploadedImage, GUILayout.Width(50), GUILayout.Height(50)); - - EditorGUILayout.BeginVertical(); + Texture2D uploadedImage = editor.uploadedImages[i]; + EditorGUILayout.BeginHorizontal(); { - // Display Image Name as Label - GUILayout.Label($"Layer {i + 1}"); + // Display Thumbnail Image + GUILayout.Label(uploadedImage, GUILayout.Width(50), GUILayout.Height(50)); - // Add any additional information or options related to the image layer here - // For example: - // GUILayout.Label($"Width: {uploadedImage.width}"); - // GUILayout.Label($"Height: {uploadedImage.height}"); - // ... additional properties ... - } - EditorGUILayout.EndVertical(); + EditorGUILayout.BeginVertical(); + { + // Display Image Name as Label + GUILayout.Label($"Layer {i + 1}"); - if (editor.selectedLayerIndex == i) - { - GUI.backgroundColor = Color.yellow; - } + // Add any additional information or options related to the image layer here + // For example: + // GUILayout.Label($"Width: {uploadedImage.width}"); + // GUILayout.Label($"Height: {uploadedImage.height}"); + // ... additional properties ... + } + EditorGUILayout.EndVertical(); - if (GUILayout.Button($"Select", GUILayout.MinWidth(80))) - { - editor.selectedLayerIndex = i; - } + if (editor.selectedLayerIndex == i) + { + GUI.backgroundColor = Color.yellow; + } - GUI.backgroundColor = Color.white; + if (GUILayout.Button($"Select", GUILayout.MinWidth(80))) + { + editor.selectedLayerIndex = i; + } + + GUI.backgroundColor = Color.white; + } + EditorGUILayout.EndHorizontal(); } - EditorGUILayout.EndHorizontal(); - } - EditorGUILayout.EndVertical(); + EditorGUILayout.EndVertical(); + } } } diff --git a/Scenario/Editor/Models/Models.cs b/Scenario/Editor/Models/Models.cs index c7e9341..6f6bad0 100644 --- a/Scenario/Editor/Models/Models.cs +++ b/Scenario/Editor/Models/Models.cs @@ -1,304 +1,306 @@ +using System.Collections.Generic; +using System.Threading.Tasks; using UnityEditor; using UnityEngine; using Newtonsoft.Json; -using System.Collections.Generic; -using System; -using System.Threading.Tasks; -public class Models : EditorWindow +namespace Scenario { - private static readonly float MinimumWidth = 1000f; + public class Models : EditorWindow + { + private static readonly float MinimumWidth = 1000f; - public static List modelsPrivate = new(); - public static List modelsPublic = new(); + public static List modelsPrivate = new(); + public static List modelsPublic = new(); - public static List texturesPrivate = new(); - public static List texturesPublic = new(); + public static List texturesPrivate = new(); + public static List texturesPublic = new(); - public static string privacyPrivate = "private"; - public static string privacyPublic = "public"; + public static string privacyPrivate = "private"; + public static string privacyPublic = "public"; - private static ModelsUI modelsUI = new(); - private static Models window; + private static ModelsUI modelsUI = new(); + private static Models window; - public static bool IsPrivateTab() - { - return CurrentPrivacy == privacyPrivate; - } + public static bool IsPrivateTab() + { + return CurrentPrivacy == privacyPrivate; + } - public static List GetModels() - { - return (IsPrivateTab()) ? modelsPrivate : modelsPublic; - } - - public static List GetTextures() - { - return (IsPrivateTab()) ? texturesPrivate : texturesPublic; - } + public static List GetModels() + { + return (IsPrivateTab()) ? modelsPrivate : modelsPublic; + } - [MenuItem("Window/Scenario/Models")] - public static void ShowWindow() - { - SetTab(CurrentPrivacy); - - window = GetWindow("Models"); - window.minSize = new Vector2(MinimumWidth, window.minSize.y); - } - - public static void SetTab(string privacySetting) - { - CurrentPrivacy = privacySetting; - - if (privacySetting == privacyPrivate) + public static List GetTextures() { - PopulatePrivateModels(); + return (IsPrivateTab()) ? texturesPrivate : texturesPublic; } - else + + [MenuItem("Window/Scenario/Models")] + public static void ShowWindow() { - PopulatePublicModels(); + SetTab(CurrentPrivacy); + + window = GetWindow("Models"); + window.minSize = new Vector2(MinimumWidth, window.minSize.y); } - } - private static async void PopulatePublicModels() - { - modelsPublic.Clear(); - await FetchAllPublicModels(); - FetchAllPublicTextures(); - modelsUI.RedrawPage(0); - } - - private static async void PopulatePrivateModels() - { - modelsPrivate.Clear(); - await FetchAllPrivateModels(); - FetchAllPrivateTextures(); - modelsUI.RedrawPage(0); - } - - private static void FetchAllPrivateTextures() - { - Debug.Log("Fetch Private Textures"); - foreach (var item in modelsPrivate) + public static void SetTab(string privacySetting) { - string downloadUrl = null; - - if (item.thumbnail != null && !string.IsNullOrEmpty(item.thumbnail.url)) + CurrentPrivacy = privacySetting; + + if (privacySetting == privacyPrivate) { - downloadUrl = item.thumbnail.url; + PopulatePrivateModels(); } - else if (item.trainingImages != null && item.trainingImages.Count > 0) + else { - downloadUrl = item.trainingImages[0].downloadUrl; + PopulatePublicModels(); } + } + + private static async void PopulatePublicModels() + { + modelsPublic.Clear(); + await FetchAllPublicModels(); + FetchAllPublicTextures(); + modelsUI.RedrawPage(0); + } - if (string.IsNullOrEmpty(downloadUrl)) continue; + private static async void PopulatePrivateModels() + { + modelsPrivate.Clear(); + await FetchAllPrivateModels(); + FetchAllPrivateTextures(); + modelsUI.RedrawPage(0); + } - var texturePair = new TexturePair() + private static void FetchAllPrivateTextures() + { + Debug.Log("Fetch Private Textures"); + foreach (var item in modelsPrivate) { - name = item.name, - texture = null, - }; + string downloadUrl = null; - texturesPrivate.Add(texturePair); + if (item.thumbnail != null && !string.IsNullOrEmpty(item.thumbnail.url)) + { + downloadUrl = item.thumbnail.url; + } + else if (item.trainingImages != null && item.trainingImages.Count > 0) + { + downloadUrl = item.trainingImages[0].downloadUrl; + } + + if (string.IsNullOrEmpty(downloadUrl)) continue; + + var texturePair = new TexturePair() + { + name = item.name, + texture = null, + }; - CommonUtils.FetchTextureFromURL(downloadUrl, texture => - { - texturePair.texture = texture; - }); + texturesPrivate.Add(texturePair); + + CommonUtils.FetchTextureFromURL(downloadUrl, texture => + { + texturePair.texture = texture; + }); - if (window != null) { window.Repaint(); } + if (window != null) { window.Repaint(); } - Debug.Log($"downloaded {item.name}"); + Debug.Log($"downloaded {item.name}"); + } } - } - private static void FetchAllPublicTextures() - { - Debug.Log("Fetch Public Textures"); - - foreach (var item in modelsPublic) + private static void FetchAllPublicTextures() { - string downloadUrl = null; - - if (item.thumbnail != null && !string.IsNullOrEmpty(item.thumbnail.url)) - { - downloadUrl = item.thumbnail.url; - } - else if (item.trainingImages != null && item.trainingImages.Count > 0) - { - downloadUrl = item.trainingImages[0].downloadUrl; - } + Debug.Log("Fetch Public Textures"); - if (string.IsNullOrEmpty(downloadUrl)) continue; - - var texturePair = new TexturePair() + foreach (var item in modelsPublic) { - name = item.name, - texture = null, - }; + string downloadUrl = null; - texturesPublic.Add(texturePair); + if (item.thumbnail != null && !string.IsNullOrEmpty(item.thumbnail.url)) + { + downloadUrl = item.thumbnail.url; + } + else if (item.trainingImages != null && item.trainingImages.Count > 0) + { + downloadUrl = item.trainingImages[0].downloadUrl; + } + + if (string.IsNullOrEmpty(downloadUrl)) continue; - CommonUtils.FetchTextureFromURL(downloadUrl, texture => - { - texturePair.texture = texture; - }); + var texturePair = new TexturePair() + { + name = item.name, + texture = null, + }; + + texturesPublic.Add(texturePair); + + CommonUtils.FetchTextureFromURL(downloadUrl, texture => + { + texturePair.texture = texture; + }); - if (window != null) { window.Repaint(); } + if (window != null) { window.Repaint(); } - //* Debug.Log($"downloaded {item.name}"); + //* Debug.Log($"downloaded {item.name}"); + } } - } - private static async Task FetchAllPrivateModels() - { - //* Debug.Log("Fetch Private Models"); - - while (true) + private static async Task FetchAllPrivateModels() { - string endpoint = $"models?pageSize=15&status=trained&privacy={privacyPrivate}"; + //* Debug.Log("Fetch Private Models"); - if (!string.IsNullOrEmpty(PagniationTokenPrivate)) + while (true) { - endpoint += $"&paginationToken={PagniationTokenPrivate}"; - } + string endpoint = $"models?pageSize=15&status=trained&privacy={privacyPrivate}"; - string response = await ApiClient.RestGetAsync(endpoint); - if (response is null) { return; } + if (!string.IsNullOrEmpty(PagniationTokenPrivate)) + { + endpoint += $"&paginationToken={PagniationTokenPrivate}"; + } - var modelsResponse = JsonConvert.DeserializeObject(response); - if (modelsResponse is null) { return; } - - modelsPrivate.AddRange(modelsResponse.models); + string response = await ApiClient.RestGetAsync(endpoint); + if (response is null) { return; } - if (modelsResponse.nextPaginationToken is null || - PagniationTokenPrivate == modelsResponse.nextPaginationToken) - { - PagniationTokenPrivate = ""; - Debug.Log("no next page to fetch."); - } - else - { - PagniationTokenPrivate = modelsResponse.nextPaginationToken; - Debug.Log("fetching next page data..."); - continue; + var modelsResponse = JsonConvert.DeserializeObject(response); + if (modelsResponse is null) { return; } + + modelsPrivate.AddRange(modelsResponse.models); + + if (modelsResponse.nextPaginationToken is null || + PagniationTokenPrivate == modelsResponse.nextPaginationToken) + { + PagniationTokenPrivate = ""; + Debug.Log("no next page to fetch."); + } + else + { + PagniationTokenPrivate = modelsResponse.nextPaginationToken; + Debug.Log("fetching next page data..."); + continue; + } + + break; } - - break; } - } - private static async Task FetchAllPublicModels() - { - Debug.Log("Fetch Public Models"); - - while (true) + private static async Task FetchAllPublicModels() { - string endpoint = $"models?pageSize=15&status=trained&privacy={privacyPublic}"; + Debug.Log("Fetch Public Models"); - if (!string.IsNullOrEmpty(PagniationTokenPublic)) + while (true) { - endpoint += $"&paginationToken={PagniationTokenPublic}"; - } + string endpoint = $"models?pageSize=15&status=trained&privacy={privacyPublic}"; - string response = await ApiClient.RestGetAsync(endpoint); - if (response is null) { return; } + if (!string.IsNullOrEmpty(PagniationTokenPublic)) + { + endpoint += $"&paginationToken={PagniationTokenPublic}"; + } - var modelsResponse = JsonConvert.DeserializeObject(response); - if (modelsResponse is null) { return; } - - modelsPublic.AddRange(modelsResponse.models); + string response = await ApiClient.RestGetAsync(endpoint); + if (response is null) { return; } - if (modelsResponse.nextPaginationToken is null || - PagniationTokenPublic == modelsResponse.nextPaginationToken) - { - PagniationTokenPublic = ""; - Debug.Log("no next page to fetch."); - } - else - { - PagniationTokenPublic = modelsResponse.nextPaginationToken; - Debug.Log("fetching next page data..."); - continue; + var modelsResponse = JsonConvert.DeserializeObject(response); + if (modelsResponse is null) { return; } + + modelsPublic.AddRange(modelsResponse.models); + + if (modelsResponse.nextPaginationToken is null || + PagniationTokenPublic == modelsResponse.nextPaginationToken) + { + PagniationTokenPublic = ""; + Debug.Log("no next page to fetch."); + } + else + { + PagniationTokenPublic = modelsResponse.nextPaginationToken; + Debug.Log("fetching next page data..."); + continue; + } + + break; } - - break; } - } - private void OnGUI() - { - modelsUI.OnGUI(this.position); - } + private void OnGUI() + { + modelsUI.OnGUI(this.position); + } - public static string CurrentPrivacy - { - get => EditorPrefs.GetString("privacy", privacyPrivate); - set => EditorPrefs.SetString("privacy", value); - } + public static string CurrentPrivacy + { + get => EditorPrefs.GetString("privacy", privacyPrivate); + set => EditorPrefs.SetString("privacy", value); + } - public static string PagniationTokenPrivate - { - get => EditorPrefs.GetString("paginationTokenPrivate", ""); - set => EditorPrefs.SetString("paginationTokenPrivate", value); - } + public static string PagniationTokenPrivate + { + get => EditorPrefs.GetString("paginationTokenPrivate", ""); + set => EditorPrefs.SetString("paginationTokenPrivate", value); + } - public static string PagniationTokenPublic - { - get => EditorPrefs.GetString("paginationTokenPublic", ""); - set => EditorPrefs.SetString("paginationTokenPublic", value); - } + public static string PagniationTokenPublic + { + get => EditorPrefs.GetString("paginationTokenPublic", ""); + set => EditorPrefs.SetString("paginationTokenPublic", value); + } - public class TexturePair - { - public Texture2D texture; - public string name; - } + public class TexturePair + { + public Texture2D texture; + public string name; + } - #region API_DTO + #region API_DTO - private class ImageData - { - public string Id { get; set; } - public string Url { get; set; } - } + private class ImageData + { + public string Id { get; set; } + public string Url { get; set; } + } - private class ModelsResponse - { - public List models { get; set; } - public string nextPaginationToken { get; set; } - } + private class ModelsResponse + { + public List models { get; set; } + public string nextPaginationToken { get; set; } + } - public class ModelData - { - public string id { get; set; } - public string name { get; set; } - public ClassData classData { get; set; } - public string privacy { get; set; } - public string status { get; set; } - public List trainingImages { get; set; } - public ThumbnailData thumbnail { get; set; } // Assuming you have a ThumbnailData class. - } + public class ModelData + { + public string id { get; set; } + public string name { get; set; } + public ClassData classData { get; set; } + public string privacy { get; set; } + public string status { get; set; } + public List trainingImages { get; set; } + public ThumbnailData thumbnail { get; set; } // Assuming you have a ThumbnailData class. + } - public class ClassData - { - public string modelId { get; set; } - } + public class ClassData + { + public string modelId { get; set; } + } - public class TrainingImageData - { - public string downloadUrl { get; set; } - } + public class TrainingImageData + { + public string downloadUrl { get; set; } + } - public class ThumbnailData - { - public string url { get; set; } - } + public class ThumbnailData + { + public string url { get; set; } + } - private class TokenResponse - { - public string nextPaginationToken { get; set; } - } + private class TokenResponse + { + public string nextPaginationToken { get; set; } + } - #endregion + #endregion + } } \ No newline at end of file diff --git a/Scenario/Editor/Models/ModelsUI.cs b/Scenario/Editor/Models/ModelsUI.cs index 55e0b7c..4299bd7 100644 --- a/Scenario/Editor/Models/ModelsUI.cs +++ b/Scenario/Editor/Models/ModelsUI.cs @@ -1,221 +1,224 @@ -using UnityEngine; -using UnityEditor; using System.Collections.Generic; using System.Linq; -using static Models; +using UnityEditor; +using UnityEngine; +using static Scenario.Models; -public class ModelsUI +namespace Scenario { - public List pageModels = new(); - private float padding = 10f; - private int itemsPerRow = 5; - private int firstImageIndex; - private int maxModelsPerPage; - private int selectedTab = 0; - private bool showNextButton = false; - private bool showPreviousButton = false; - private bool drawTabs = false; - private Vector2 scrollPosition = Vector2.zero; - - private void SetFirstPage() + public class ModelsUI { - selectedTab = (Models.IsPrivateTab()) ? 0 : 1; + public List pageModels = new(); + private float padding = 10f; + private int itemsPerRow = 5; + private int firstImageIndex; + private int maxModelsPerPage; + private int selectedTab = 0; + private bool showNextButton = false; + private bool showPreviousButton = false; + private bool drawTabs = false; + private Vector2 scrollPosition = Vector2.zero; + + private void SetFirstPage() + { + selectedTab = (Models.IsPrivateTab()) ? 0 : 1; - firstImageIndex = 0; - maxModelsPerPage = 15; + firstImageIndex = 0; + maxModelsPerPage = 15; - showPreviousButton = false; - showNextButton = false; + showPreviousButton = false; + showNextButton = false; - UpdatePage(); - } + UpdatePage(); + } - private void SetNextPage() - { - firstImageIndex += maxModelsPerPage; + private void SetNextPage() + { + firstImageIndex += maxModelsPerPage; - var models = Models.GetModels(); + var models = Models.GetModels(); - if (firstImageIndex > models.Count - maxModelsPerPage) - { - firstImageIndex = models.Count - maxModelsPerPage; - showNextButton = false; - } - showPreviousButton = true; + if (firstImageIndex > models.Count - maxModelsPerPage) + { + firstImageIndex = models.Count - maxModelsPerPage; + showNextButton = false; + } + showPreviousButton = true; - UpdatePage(); - } + UpdatePage(); + } - private void SetPreviousPage() - { - firstImageIndex -= maxModelsPerPage; - showPreviousButton = firstImageIndex > maxModelsPerPage; + private void SetPreviousPage() + { + firstImageIndex -= maxModelsPerPage; + showPreviousButton = firstImageIndex > maxModelsPerPage; - UpdatePage(); - } + UpdatePage(); + } - private void UpdatePage() - { - // clear page - pageModels.Clear(); + private void UpdatePage() + { + // clear page + pageModels.Clear(); - var models = Models.GetModels(); + var models = Models.GetModels(); - // Populate Page with models - for (int i = firstImageIndex; i < firstImageIndex + maxModelsPerPage; i++) - { - if (i > models.Count - 1) + // Populate Page with models + for (int i = firstImageIndex; i < firstImageIndex + maxModelsPerPage; i++) { - continue; - } + if (i > models.Count - 1) + { + continue; + } - pageModels.Add(models[i]); - } + pageModels.Add(models[i]); + } - if (models.Count > maxModelsPerPage && firstImageIndex != models.Count - maxModelsPerPage) - { - showNextButton = true; - } + if (models.Count > maxModelsPerPage && firstImageIndex != models.Count - maxModelsPerPage) + { + showNextButton = true; + } - if (pageModels.Count > maxModelsPerPage) - { - showNextButton = true; - } + if (pageModels.Count > maxModelsPerPage) + { + showNextButton = true; + } - drawTabs = true; - } + drawTabs = true; + } - public void OnGUI(Rect position) - { - DrawBackground(position); - - if (drawTabs) + public void OnGUI(Rect position) { - string[] tabs = { "Private Models", "Public Models" }; - HandleTabSelection(tabs); - } + DrawBackground(position); - DrawModelsGrid(position); + if (drawTabs) + { + string[] tabs = { "Private Models", "Public Models" }; + HandleTabSelection(tabs); + } - GUILayout.BeginArea(new Rect(0, position.height - 50, position.width, 50)); - GUILayout.BeginHorizontal(); + DrawModelsGrid(position); - if (showPreviousButton) - { - EditorStyle.Button("Previous Page", () => { RedrawPage(-1); }); + GUILayout.BeginArea(new Rect(0, position.height - 50, position.width, 50)); + GUILayout.BeginHorizontal(); + + if (showPreviousButton) + { + EditorStyle.Button("Previous Page", () => { RedrawPage(-1); }); + } + + if (showNextButton) + { + EditorStyle.Button("Next Page", () => { RedrawPage(1); }); + } + + GUILayout.EndHorizontal(); + GUILayout.EndArea(); } - if (showNextButton) + private static void DrawBackground(Rect position) { - EditorStyle.Button("Next Page", () => { RedrawPage(1); }); + Color backgroundColor = EditorStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); } - GUILayout.EndHorizontal(); - GUILayout.EndArea(); - } - - private static void DrawBackground(Rect position) - { - Color backgroundColor = EditorStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } - - private void DrawModelsGrid(Rect position) - { - float boxWidth = (position.width - padding * (itemsPerRow - 1)) / itemsPerRow; - float boxHeight = boxWidth; + private void DrawModelsGrid(Rect position) + { + float boxWidth = (position.width - padding * (itemsPerRow - 1)) / itemsPerRow; + float boxHeight = boxWidth; - var textures = Models.GetTextures(); + var textures = Models.GetTextures(); - int numRows = Mathf.CeilToInt((float)maxModelsPerPage / itemsPerRow); - float rowPadding = 10f; - float scrollViewHeight = (boxHeight + padding + rowPadding) * numRows - rowPadding; + int numRows = Mathf.CeilToInt((float)maxModelsPerPage / itemsPerRow); + float rowPadding = 10f; + float scrollViewHeight = (boxHeight + padding + rowPadding) * numRows - rowPadding; - scrollPosition = GUI.BeginScrollView(new Rect(0, 70, position.width, position.height - 20), scrollPosition, new Rect(0, 0, position.width - 20, scrollViewHeight)); - { - DrawTextureBox(boxWidth, boxHeight, rowPadding, textures); + scrollPosition = GUI.BeginScrollView(new Rect(0, 70, position.width, position.height - 20), scrollPosition, new Rect(0, 0, position.width - 20, scrollViewHeight)); + { + DrawTextureBox(boxWidth, boxHeight, rowPadding, textures); + } + GUI.EndScrollView(); } - GUI.EndScrollView(); - } - private void DrawTextureBox(float boxWidth, float boxHeight, float rowPadding, List textures) - { - var models = Models.GetModels(); - - for (int i = 0; i < pageModels.Count; i++) + private void DrawTextureBox(float boxWidth, float boxHeight, float rowPadding, List textures) { - int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); - int colIndex = i % itemsPerRow; + var models = Models.GetModels(); + + for (int i = 0; i < pageModels.Count; i++) + { + int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); + int colIndex = i % itemsPerRow; - var i1 = i; - var item = textures.FirstOrDefault(x => x.name == pageModels[i1].name); - if (item == null) { return; } + var i1 = i; + var item = textures.FirstOrDefault(x => x.name == pageModels[i1].name); + if (item == null) { return; } - Rect boxRect = new Rect(colIndex * (boxWidth + padding), rowIndex * (boxHeight + padding + rowPadding), boxWidth, boxHeight); - Texture2D texture = item.texture; - string name = item.name; + Rect boxRect = new Rect(colIndex * (boxWidth + padding), rowIndex * (boxHeight + padding + rowPadding), boxWidth, boxHeight); + Texture2D texture = item.texture; + string name = item.name; - GUIStyle style = new GUIStyle(GUI.skin.label) - { - alignment = TextAnchor.MiddleCenter - }; + GUIStyle style = new GUIStyle(GUI.skin.label) + { + alignment = TextAnchor.MiddleCenter + }; - if (texture != null) - { - if (GUI.Button(boxRect, texture)) + if (texture != null) { - if (i >= 0 && i < models.Count) + if (GUI.Button(boxRect, texture)) { - EditorPrefs.SetString("SelectedModelId", models[i].id); - EditorPrefs.SetString("SelectedModelName", name); + if (i >= 0 && i < models.Count) + { + EditorPrefs.SetString("SelectedModelId", models[i].id); + EditorPrefs.SetString("SelectedModelName", name); + } + + EditorWindow window = EditorWindow.GetWindow(typeof(Models)); + window.Close(); } - - EditorWindow window = EditorWindow.GetWindow(typeof(Models)); - window.Close(); - } - GUI.Label(new Rect(boxRect.x, boxRect.y + boxHeight, boxWidth, 20), name, style); - } - else - { - GUI.Label(new Rect(boxRect.x, boxRect.y + boxHeight, boxWidth, 20), "Loading..", style); + GUI.Label(new Rect(boxRect.x, boxRect.y + boxHeight, boxWidth, 20), name, style); + } + else + { + GUI.Label(new Rect(boxRect.x, boxRect.y + boxHeight, boxWidth, 20), "Loading..", style); + } } } - } - - private void HandleTabSelection(string[] tabs) - { - int previousTab = selectedTab; - selectedTab = GUILayout.Toolbar(selectedTab, tabs); - if (previousTab != selectedTab) + private void HandleTabSelection(string[] tabs) { - if (selectedTab == 0) - { - Models.SetTab(Models.privacyPrivate); - drawTabs = false; - } - else if (selectedTab == 1) + int previousTab = selectedTab; + selectedTab = GUILayout.Toolbar(selectedTab, tabs); + + if (previousTab != selectedTab) { - Models.SetTab(Models.privacyPublic); - drawTabs = false; + if (selectedTab == 0) + { + Models.SetTab(Models.privacyPrivate); + drawTabs = false; + } + else if (selectedTab == 1) + { + Models.SetTab(Models.privacyPublic); + drawTabs = false; + } } } - } - public void RedrawPage(int _updateType) - { - switch (_updateType) + public void RedrawPage(int _updateType) { - case 0: - SetFirstPage(); - break; - case 1: - SetNextPage(); - break; - case -1: - SetPreviousPage(); - break; + switch (_updateType) + { + case 0: + SetFirstPage(); + break; + case 1: + SetNextPage(); + break; + case -1: + SetPreviousPage(); + break; + } } } } diff --git a/Scenario/Editor/PackageExport.cs b/Scenario/Editor/PackageExport.cs index c218361..75c9c33 100644 --- a/Scenario/Editor/PackageExport.cs +++ b/Scenario/Editor/PackageExport.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using UnityEditor; @@ -8,128 +7,131 @@ using UnityEngine; using PackageInfo = UnityEditor.PackageManager.PackageInfo; -/// -/// Displays a Unity Editor window where you can select the package to export. -/// -public class PackageExport : EditorWindow +namespace Scenario { - [SerializeField] private static string _sourceFolder = string.Empty; - [SerializeField] private string _info = string.Empty; - private PackageInfo _selection; - private PackRequest _packRequest; - private string _destinationFolder = string.Empty; - private bool _isWorking = false; - - [MenuItem("Tools/Export Package", false, -100)] - private static void MenuItem_Export() + /// + /// Displays a Unity Editor window where you can select the package to export. + /// + public class PackageExport : EditorWindow { - GetWindow(false, "Package Export", true); + [SerializeField] private static string _sourceFolder = string.Empty; + [SerializeField] private string _info = string.Empty; + private PackageInfo _selection; + private PackRequest _packRequest; + private string _destinationFolder = string.Empty; + private bool _isWorking = false; + + [MenuItem("Tools/Export Package", false, -100)] + private static void MenuItem_Export() + { + GetWindow(false, "Package Export", true); - _sourceFolder = EditorUtility.OpenFolderPanel - ( - "Select folder of the package", - Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), - string.Empty - ); - } + _sourceFolder = EditorUtility.OpenFolderPanel + ( + "Select folder of the package", + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + string.Empty + ); + } - private void Awake() - { - EditorApplication.update += OnEditorUpdate; - } + private void Awake() + { + EditorApplication.update += OnEditorUpdate; + } - private void OnDestroy() - { - _isWorking = false; - EditorApplication.update -= OnEditorUpdate; - } + private void OnDestroy() + { + _isWorking = false; + EditorApplication.update -= OnEditorUpdate; + } - private void OnInspectorUpdate() - { - Repaint(); - } + private void OnInspectorUpdate() + { + Repaint(); + } - private void OnGUI() - { - EditorGUILayout.LabelField("Package path"); + private void OnGUI() + { + EditorGUILayout.LabelField("Package path"); - EditorGUILayout.TextField(_sourceFolder); + EditorGUILayout.TextField(_sourceFolder); - if (GUILayout.Button("Export", GUILayout.Height(30.0f))) - { - if (!_isWorking) + if (GUILayout.Button("Export", GUILayout.Height(30.0f))) { - _destinationFolder = EditorUtility.OpenFolderPanel - ( - "Select where to export the package", - Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), - string.Empty - ); + if (!_isWorking) + { + _destinationFolder = EditorUtility.OpenFolderPanel + ( + "Select where to export the package", + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + string.Empty + ); + + _isWorking = true; + _info = "Exporting package..."; + + Export(); + } + } - _isWorking = true; - _info = "Exporting package..."; + EditorGUILayout.LabelField(_info); + } - Export(); + private void Export() + { + if (string.IsNullOrWhiteSpace(_sourceFolder)) + { + _info = "Package path is empty"; + return; } - } - EditorGUILayout.LabelField(_info); - } + if (string.IsNullOrWhiteSpace(_destinationFolder)) + { + _info = "Destination folder is empty"; + return; + } - private void Export() - { - if (string.IsNullOrWhiteSpace(_sourceFolder)) - { - _info = "Package path is empty"; - return; - } + if (!Directory.Exists(_sourceFolder)) + { + _info = "Package folder does not exist"; + return; + } - if (string.IsNullOrWhiteSpace(_destinationFolder)) - { - _info = "Destination folder is empty"; - return; - } + if (!Directory.Exists(_destinationFolder)) + { + _info = "Destination folder does not exist"; + return; + } - if (!Directory.Exists(_sourceFolder)) - { - _info = "Package folder does not exist"; - return; + _packRequest = Client.Pack(_sourceFolder, _destinationFolder); } - if (!Directory.Exists(_destinationFolder)) + private void OnEditorUpdate() { - _info = "Destination folder does not exist"; - return; + PackPackage(); } - _packRequest = Client.Pack(_sourceFolder, _destinationFolder); - } - - private void OnEditorUpdate() - { - PackPackage(); - } - - private async void PackPackage() - { - if (_packRequest != null && _packRequest.IsCompleted) + private async void PackPackage() { - if (_packRequest.Status == StatusCode.Success) + if (_packRequest != null && _packRequest.IsCompleted) { - _info = "Package exported!"; + if (_packRequest.Status == StatusCode.Success) + { + _info = "Package exported!"; - await Task.Delay(300); + await Task.Delay(300); - System.Diagnostics.Process.Start(_destinationFolder); + System.Diagnostics.Process.Start(_destinationFolder); - _isWorking = false; - } - else - { - _info = "There was an error exporting the package."; - } + _isWorking = false; + } + else + { + _info = "There was an error exporting the package."; + } - _packRequest = null; + _packRequest = null; + } } } } \ No newline at end of file diff --git a/Scenario/Editor/PixelEditor/PixelEditor.cs b/Scenario/Editor/PixelEditor/PixelEditor.cs index 76890a3..6c98192 100644 --- a/Scenario/Editor/PixelEditor/PixelEditor.cs +++ b/Scenario/Editor/PixelEditor/PixelEditor.cs @@ -1,38 +1,41 @@ using UnityEditor; using UnityEngine; -public class PixelEditor : EditorWindow +namespace Scenario { - private static readonly float MinimumWidth = 1650f; - private PixelEditorUI pixelEditorUI = new(); - - [MenuItem("Window/Scenario/Pixel Editor")] - public static void ShowWindow() + public class PixelEditor : EditorWindow { - var window = EditorWindow.GetWindow(typeof(PixelEditor), false, "Pixel Editor") as PixelEditor; - if (window.pixelEditorUI != null) + private static readonly float MinimumWidth = 1650f; + private PixelEditorUI pixelEditorUI = new(); + + [MenuItem("Window/Scenario/Pixel Editor")] + public static void ShowWindow() { - window.pixelEditorUI.removeNoise = false; - window.pixelEditorUI.removeBackground = false; - } + var window = EditorWindow.GetWindow(typeof(PixelEditor), false, "Pixel Editor") as PixelEditor; + if (window.pixelEditorUI != null) + { + window.pixelEditorUI.removeNoise = false; + window.pixelEditorUI.removeBackground = false; + } - window.minSize = new Vector2(MinimumWidth, window.minSize.y); - } + window.minSize = new Vector2(MinimumWidth, window.minSize.y); + } - public static void ShowWindow(Texture2D selectedTexture, ImageDataStorage.ImageData imageData) - { - PixelEditorUI.currentImage = selectedTexture; - PixelEditorUI.imageData = imageData; - ShowWindow(); - } + public static void ShowWindow(Texture2D selectedTexture, ImageDataStorage.ImageData imageData) + { + PixelEditorUI.currentImage = selectedTexture; + PixelEditorUI.imageData = imageData; + ShowWindow(); + } - private void OnGUI() - { - pixelEditorUI.OnGUI(this.position); - } + private void OnGUI() + { + pixelEditorUI.OnGUI(this.position); + } - private void OnDestroy() - { - PixelEditorUI.currentImage = null; + private void OnDestroy() + { + PixelEditorUI.currentImage = null; + } } } \ No newline at end of file diff --git a/Scenario/Editor/PixelEditor/PixelEditorUI.cs b/Scenario/Editor/PixelEditor/PixelEditorUI.cs index a9f78e0..895a1bc 100644 --- a/Scenario/Editor/PixelEditor/PixelEditorUI.cs +++ b/Scenario/Editor/PixelEditor/PixelEditorUI.cs @@ -1,266 +1,269 @@ -using UnityEngine; -using UnityEditor; using System; +using System.Collections.Generic; using System.IO; +using UnityEditor; +using UnityEngine; using Newtonsoft.Json; -using System.Collections.Generic; -public class PixelEditorUI +namespace Scenario { - public static Texture2D currentImage = null; - public static ImageDataStorage.ImageData imageData = null; + public class PixelEditorUI + { + public static Texture2D currentImage = null; + public static ImageDataStorage.ImageData imageData = null; - private static List imageDataList = new(); + private static List imageDataList = new(); - public bool removeNoise = false; - public bool removeBackground = false; - private bool returnImage = true; - private int itemsPerRow = 1; - private string imageDataUrl = ""; - private string assetId = ""; - private float pixelGridSize = 32f; - private float padding = 10f; - private Vector2 scrollPosition = Vector2.zero; - private Texture2D selectedTexture = null; - private List pixelatedImages = new(); + public bool removeNoise = false; + public bool removeBackground = false; + private bool returnImage = true; + private int itemsPerRow = 1; + private string imageDataUrl = ""; + private string assetId = ""; + private float pixelGridSize = 32f; + private float padding = 10f; + private Vector2 scrollPosition = Vector2.zero; + private Texture2D selectedTexture = null; + private List pixelatedImages = new(); - private float leftSectionWidth = 150; - private int selectedGridSizeIndex = 0; - private readonly int[] allowedPixelGridSizes = { 32, 64, 128, 256 }; + private float leftSectionWidth = 150; + private int selectedGridSizeIndex = 0; + private readonly int[] allowedPixelGridSizes = { 32, 64, 128, 256 }; - public void OnGUI(Rect position) - { - DrawBackground(position); - - GUILayout.BeginHorizontal(); + public void OnGUI(Rect position) + { + DrawBackground(position); - position = DrawLeftSection(position); + GUILayout.BeginHorizontal(); - GUILayout.FlexibleSpace(); + position = DrawLeftSection(position); - DrawRightSection(position); + GUILayout.FlexibleSpace(); - GUILayout.EndHorizontal(); - } + DrawRightSection(position); - private static void DrawBackground(Rect position) - { - Color backgroundColor = EditorStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } + GUILayout.EndHorizontal(); + } - private void DrawRightSection(Rect position) - { - // Right section - GUILayout.BeginVertical(GUILayout.Width(position.width * 0.15f)); + private static void DrawBackground(Rect position) + { + Color backgroundColor = EditorStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); + } - EditorStyle.Label("Pixelate Image", bold: true); - if (currentImage == null) + private void DrawRightSection(Rect position) { - Rect dropArea = GUILayoutUtility.GetRect(0f, 150f, GUILayout.ExpandWidth(true)); - GUI.Box(dropArea, "Drag & Drop an image here"); + // Right section + GUILayout.BeginVertical(GUILayout.Width(position.width * 0.15f)); - Rect buttonRect = new Rect(dropArea.center.x - 50f, dropArea.center.y - 15f, 100f, 30f); - if (GUI.Button(buttonRect, "Choose Image")) + EditorStyle.Label("Pixelate Image", bold: true); + if (currentImage == null) { - HandleChooseImageClick(); - } + Rect dropArea = GUILayoutUtility.GetRect(0f, 150f, GUILayout.ExpandWidth(true)); + GUI.Box(dropArea, "Drag & Drop an image here"); - HandleDrag(); - } - else - { - Rect rect = GUILayoutUtility.GetRect(leftSectionWidth, leftSectionWidth, GUILayout.Width(300), GUILayout.Height(300)); - GUI.DrawTexture(rect, currentImage, ScaleMode.ScaleToFit); + Rect buttonRect = new Rect(dropArea.center.x - 50f, dropArea.center.y - 15f, 100f, 30f); + if (GUI.Button(buttonRect, "Choose Image")) + { + HandleChooseImageClick(); + } - EditorStyle.Button("Clear Image", ()=> currentImage = null); - } + HandleDrag(); + } + else + { + Rect rect = GUILayoutUtility.GetRect(leftSectionWidth, leftSectionWidth, GUILayout.Width(300), GUILayout.Height(300)); + GUI.DrawTexture(rect, currentImage, ScaleMode.ScaleToFit); + + EditorStyle.Button("Clear Image", ()=> currentImage = null); + } - EditorStyle.Label("Pixel Grid Size:"); - int pixelGridSizeIndex = Array.IndexOf(allowedPixelGridSizes, (int)pixelGridSize); - if (pixelGridSizeIndex == -1) { pixelGridSizeIndex = 0; } + EditorStyle.Label("Pixel Grid Size:"); + int pixelGridSizeIndex = Array.IndexOf(allowedPixelGridSizes, (int)pixelGridSize); + if (pixelGridSizeIndex == -1) { pixelGridSizeIndex = 0; } - selectedGridSizeIndex = GUILayout.SelectionGrid(selectedGridSizeIndex, Array.ConvertAll(allowedPixelGridSizes, x => x.ToString()), allowedPixelGridSizes.Length); - pixelGridSize = allowedPixelGridSizes[selectedGridSizeIndex]; - removeNoise = EditorGUILayout.Toggle("Remove Noise", removeNoise); - removeBackground = EditorGUILayout.Toggle("Remove Background", removeBackground); + selectedGridSizeIndex = GUILayout.SelectionGrid(selectedGridSizeIndex, Array.ConvertAll(allowedPixelGridSizes, x => x.ToString()), allowedPixelGridSizes.Length); + pixelGridSize = allowedPixelGridSizes[selectedGridSizeIndex]; + removeNoise = EditorGUILayout.Toggle("Remove Noise", removeNoise); + removeBackground = EditorGUILayout.Toggle("Remove Background", removeBackground); - EditorStyle.Button("Pixelate Image", () => - { - if (currentImage == null) return; + EditorStyle.Button("Pixelate Image", () => + { + if (currentImage == null) return; - imageDataUrl = CommonUtils.Texture2DToDataURL(currentImage); - assetId = imageData.Id; - FetchPixelatedImage(imageDataUrl); - }); + imageDataUrl = CommonUtils.Texture2DToDataURL(currentImage); + assetId = imageData.Id; + FetchPixelatedImage(imageDataUrl); + }); - if (selectedTexture != null) - { - EditorStyle.Button("Download", () => CommonUtils.SaveTextureAsPNG(selectedTexture)); - } + if (selectedTexture != null) + { + EditorStyle.Button("Download", () => CommonUtils.SaveTextureAsPNG(selectedTexture)); + } - GUILayout.EndVertical(); - } + GUILayout.EndVertical(); + } - private static void HandleDrag() - { - Event currentEvent = Event.current; - if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) + private static void HandleDrag() { - if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) + Event currentEvent = Event.current; + if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - if (currentEvent.type == EventType.DragPerform) + if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) { - DragAndDrop.AcceptDrag(); - string path = DragAndDrop.paths[0]; - if (System.IO.File.Exists(path) && - (System.IO.Path.GetExtension(path).ToLower() == ".png" || - System.IO.Path.GetExtension(path).ToLower() == ".jpg" || - System.IO.Path.GetExtension(path).ToLower() == ".jpeg")) + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + if (currentEvent.type == EventType.DragPerform) { - currentImage = new Texture2D(2, 2); - byte[] imgBytes = File.ReadAllBytes(path); - currentImage.LoadImage(imgBytes); + DragAndDrop.AcceptDrag(); + string path = DragAndDrop.paths[0]; + if (System.IO.File.Exists(path) && + (System.IO.Path.GetExtension(path).ToLower() == ".png" || + System.IO.Path.GetExtension(path).ToLower() == ".jpg" || + System.IO.Path.GetExtension(path).ToLower() == ".jpeg")) + { + currentImage = new Texture2D(2, 2); + byte[] imgBytes = File.ReadAllBytes(path); + currentImage.LoadImage(imgBytes); + } } + currentEvent.Use(); } - currentEvent.Use(); } } - } - private static void HandleChooseImageClick() - { - string imagePath = EditorUtility.OpenFilePanel("Choose Image", "", "png,jpg,jpeg"); - if (!string.IsNullOrEmpty(imagePath)) + private static void HandleChooseImageClick() { - currentImage = new Texture2D(2, 2); - byte[] imgBytes = File.ReadAllBytes(imagePath); - currentImage.LoadImage(imgBytes); + string imagePath = EditorUtility.OpenFilePanel("Choose Image", "", "png,jpg,jpeg"); + if (!string.IsNullOrEmpty(imagePath)) + { + currentImage = new Texture2D(2, 2); + byte[] imgBytes = File.ReadAllBytes(imagePath); + currentImage.LoadImage(imgBytes); - PixelEditorUI.imageData = new ImageDataStorage.ImageData(); + PixelEditorUI.imageData = new ImageDataStorage.ImageData(); + } } - } - - private Rect DrawLeftSection(Rect position) - { - // Left section - GUILayout.BeginVertical(GUILayout.Width(position.width * 0.85f)); - float requiredWidth = itemsPerRow * (256 + padding) + padding; - scrollPosition = GUI.BeginScrollView(new Rect(0, 20, requiredWidth, position.height - 20), scrollPosition, new Rect(0, 0, requiredWidth, position.height - 20)); - itemsPerRow = 5; - for (int i = 0; i < pixelatedImages.Count; i++) + private Rect DrawLeftSection(Rect position) { - int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); - int colIndex = i % itemsPerRow; + // Left section + GUILayout.BeginVertical(GUILayout.Width(position.width * 0.85f)); + float requiredWidth = itemsPerRow * (256 + padding) + padding; + scrollPosition = GUI.BeginScrollView(new Rect(0, 20, requiredWidth, position.height - 20), scrollPosition, new Rect(0, 0, requiredWidth, position.height - 20)); + itemsPerRow = 5; - Rect boxRect = new Rect(colIndex * (256 + padding), rowIndex * (256 + padding), 256, 256); - Texture2D texture = pixelatedImages[i]; - - if (texture != null) + for (int i = 0; i < pixelatedImages.Count; i++) { - if (GUI.Button(boxRect, "")) + int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); + int colIndex = i % itemsPerRow; + + Rect boxRect = new Rect(colIndex * (256 + padding), rowIndex * (256 + padding), 256, 256); + Texture2D texture = pixelatedImages[i]; + + if (texture != null) + { + if (GUI.Button(boxRect, "")) + { + selectedTexture = texture; + } + GUI.DrawTexture(boxRect, texture, ScaleMode.ScaleToFit); + } + else { - selectedTexture = texture; + GUI.Box(boxRect, "Loading..."); } - GUI.DrawTexture(boxRect, texture, ScaleMode.ScaleToFit); - } - else - { - GUI.Box(boxRect, "Loading..."); } + GUI.EndScrollView(); + GUILayout.EndVertical(); + return position; } - GUI.EndScrollView(); - GUILayout.EndVertical(); - return position; - } - private void FetchPixelatedImage(string imgUrl) - { - string json = ""; - - if (assetId == "") + private void FetchPixelatedImage(string imgUrl) { - var payload = new + string json = ""; + + if (assetId == "") { - image = imgUrl, - pixelGridSize = pixelGridSize, - removeNoise = removeNoise, - removeBackground = removeBackground, - returnImage = returnImage, - name = "", - colorPalette = "" - }; - json = JsonConvert.SerializeObject(payload); - } - else - { - var payload = new + var payload = new + { + image = imgUrl, + pixelGridSize = pixelGridSize, + removeNoise = removeNoise, + removeBackground = removeBackground, + returnImage = returnImage, + name = "", + colorPalette = "" + }; + json = JsonConvert.SerializeObject(payload); + } + else { - image = imgUrl, - assetId = assetId, - pixelGridSize = pixelGridSize, - removeNoise = removeNoise, - removeBackground = removeBackground, - returnImage = returnImage, - name = CommonUtils.GetRandomImageFileName(), - colorPalette = "" - }; - json = JsonConvert.SerializeObject(payload); - } + var payload = new + { + image = imgUrl, + assetId = assetId, + pixelGridSize = pixelGridSize, + removeNoise = removeNoise, + removeBackground = removeBackground, + returnImage = returnImage, + name = CommonUtils.GetRandomImageFileName(), + colorPalette = "" + }; + json = JsonConvert.SerializeObject(payload); + } - ApiClient.RestPut("images/pixelate", json, response => - { - var pixelatedResponse = JsonConvert.DeserializeObject(response.Content); - var texture = CommonUtils.DataURLToTexture2D(pixelatedResponse.image); - var newImageData = new ImageDataStorage.ImageData + ApiClient.RestPut("images/pixelate", json, response => { - Id = pixelatedResponse.asset.id, - Url = pixelatedResponse.image, - InferenceId = pixelatedResponse.asset.ownerId, - }; - pixelatedImages.Insert(0, texture); - imageDataList.Insert(0, newImageData); - }); + var pixelatedResponse = JsonConvert.DeserializeObject(response.Content); + var texture = CommonUtils.DataURLToTexture2D(pixelatedResponse.image); + var newImageData = new ImageDataStorage.ImageData + { + Id = pixelatedResponse.asset.id, + Url = pixelatedResponse.image, + InferenceId = pixelatedResponse.asset.ownerId, + }; + pixelatedImages.Insert(0, texture); + imageDataList.Insert(0, newImageData); + }); + } } -} -#region API_DTOS + #region API_DTOS -[Serializable] -public class Asset -{ - public string id { get; set; } - public string mimeType { get; set; } - public Type type { get; set; } - public string ownerId { get; set; } - public string authorId { get; set; } - public DateTime createdAt { get; set; } - public DateTime updatedAt { get; set; } - public string privacy { get; set; } - public List tags { get; set; } - public List collectionIds { get; set; } -} + [Serializable] + public class Asset + { + public string id { get; set; } + public string mimeType { get; set; } + public Type type { get; set; } + public string ownerId { get; set; } + public string authorId { get; set; } + public DateTime createdAt { get; set; } + public DateTime updatedAt { get; set; } + public string privacy { get; set; } + public List tags { get; set; } + public List collectionIds { get; set; } + } -[Serializable] -public class Root -{ - public Asset asset { get; set; } - public string image { get; set; } -} + [Serializable] + public class Root + { + public Asset asset { get; set; } + public string image { get; set; } + } -[Serializable] -public class Type -{ - public string source { get; set; } - public string parentId { get; set; } - public string rootParentId { get; set; } - public string kind { get; set; } - public int pixelGridSize { get; set; } - public bool removeNoise { get; set; } - public bool removeBackground { get; set; } -} + [Serializable] + public class Type + { + public string source { get; set; } + public string parentId { get; set; } + public string rootParentId { get; set; } + public string kind { get; set; } + public int pixelGridSize { get; set; } + public bool removeNoise { get; set; } + public bool removeBackground { get; set; } + } -#endregion + #endregion +} \ No newline at end of file diff --git a/Scenario/Editor/PromptImages/PromptImages.cs b/Scenario/Editor/PromptImages/PromptImages.cs index c7b67ce..f9ba5d6 100644 --- a/Scenario/Editor/PromptImages/PromptImages.cs +++ b/Scenario/Editor/PromptImages/PromptImages.cs @@ -1,225 +1,225 @@ -using UnityEditor; -using UnityEngine; -using System.Threading.Tasks; +using System; +using System.Collections; using System.Collections.Generic; -using UnityEngine.Networking; +using System.IO; +using System.Threading.Tasks; using RestSharp; -using System.Collections; using Unity.EditorCoroutines.Editor; -using UnityEditor.TerrainTools; -using System; -using UnityEditor.PackageManager.Requests; -using System.IO; +using UnityEditor; +using UnityEngine; +using UnityEngine.Networking; using Newtonsoft.Json; -using System.Text; -public class PromptImages : EditorWindow +namespace Scenario { - public static List imageDataList = ImageDataStorage.imageDataList; - public static PromptImagesUI promptImagesUI = new PromptImagesUI(); + public class PromptImages : EditorWindow + { + public static List imageDataList = ImageDataStorage.imageDataList; + public static PromptImagesUI promptImagesUI = new PromptImagesUI(); - public static string downloadPath; + public static string downloadPath; - [MenuItem("Window/Scenario/Prompt Images")] - public static void ShowWindow() - { - FetchGeneratedImages(); + [MenuItem("Window/Scenario/Prompt Images")] + public static void ShowWindow() + { + FetchGeneratedImages(); - var promptImages = (PromptImages) EditorWindow.GetWindow(typeof(PromptImages)); - - promptImagesUI.Init(promptImages); + var promptImages = (PromptImages) EditorWindow.GetWindow(typeof(PromptImages)); - downloadPath = EditorPrefs.GetString("SaveFolder", "Assets"); - } + promptImagesUI.Init(promptImages); - public void DeleteImageAtIndex(int selectedTextureIndex) - { - promptImagesUI.textures.RemoveAt(selectedTextureIndex); + downloadPath = EditorPrefs.GetString("SaveFolder", "Assets"); + } - string imageId = imageDataList[selectedTextureIndex].Id; - string modelId = EditorPrefs.GetString("SelectedModelId", ""); - string inferenceId = imageDataList[selectedTextureIndex].InferenceId; - EditorCoroutineUtility.StartCoroutineOwnerless(DeleteImageRequest(inferenceId, modelId, imageId)); + public void DeleteImageAtIndex(int selectedTextureIndex) + { + promptImagesUI.textures.RemoveAt(selectedTextureIndex); - Repaint(); - } + string imageId = imageDataList[selectedTextureIndex].Id; + string modelId = EditorPrefs.GetString("SelectedModelId", ""); + string inferenceId = imageDataList[selectedTextureIndex].InferenceId; + EditorCoroutineUtility.StartCoroutineOwnerless(DeleteImageRequest(inferenceId, modelId, imageId)); - public void DownloadImage(string fileName, byte[] pngBytes) - { - string filePath = downloadPath + "/" + fileName; - File.WriteAllBytes(filePath, pngBytes); - EditorCoroutineUtility.StartCoroutineOwnerless(RefreshDatabase()); - Debug.Log("Downloaded image to: " + filePath); - } - - IEnumerator RefreshDatabase() - { - yield return null; - AssetDatabase.Refresh(); - } + Repaint(); + } - private static async Task LoadTexture(string url) - { - using UnityWebRequest www = UnityWebRequestTexture.GetTexture(url); - www.SendWebRequest(); - while (!www.isDone) + public void DownloadImage(string fileName, byte[] pngBytes) { - await Task.Delay(10); + string filePath = downloadPath + "/" + fileName; + File.WriteAllBytes(filePath, pngBytes); + EditorCoroutineUtility.StartCoroutineOwnerless(RefreshDatabase()); + Debug.Log("Downloaded image to: " + filePath); } - if (www.result != UnityWebRequest.Result.Success) + IEnumerator RefreshDatabase() { - Debug.LogError(www.error); - return null; + yield return null; + AssetDatabase.Refresh(); } - return DownloadHandlerTexture.GetContent(www); - } + private static async Task LoadTexture(string url) + { + using UnityWebRequest www = UnityWebRequestTexture.GetTexture(url); + www.SendWebRequest(); + while (!www.isDone) + { + await Task.Delay(10); + } - private void OnGUI() - { - promptImagesUI.OnGUI(this.position); - } + if (www.result != UnityWebRequest.Result.Success) + { + Debug.LogError(www.error); + return null; + } - private static async void FetchGeneratedImages() - { - Debug.Log("Fetching new images, please wait.."); + return DownloadHandlerTexture.GetContent(www); + } - int oldImageCount = PromptWindow.generatedImagesData.Count; - int newImageCount = 0; + private void OnGUI() + { + promptImagesUI.OnGUI(this.position); + } - foreach (var image in PromptWindow.generatedImagesData) + private static async void FetchGeneratedImages() { - if (!imageDataList.Exists(x => x.Id == image.Id)) + Debug.Log("Fetching new images, please wait.."); + + int oldImageCount = PromptWindow.generatedImagesData.Count; + int newImageCount = 0; + + foreach (var image in PromptWindow.generatedImagesData) { - ImageDataStorage.ImageData newImageData = new ImageDataStorage.ImageData { Id = image.Id, Url = image.Url, InferenceId = image.InferenceId }; - imageDataList.Insert(0, newImageData); + if (!imageDataList.Exists(x => x.Id == image.Id)) + { + ImageDataStorage.ImageData newImageData = new ImageDataStorage.ImageData { Id = image.Id, Url = image.Url, InferenceId = image.InferenceId }; + imageDataList.Insert(0, newImageData); - Texture2D texture = await LoadTexture(image.Url); - promptImagesUI.textures.Insert(0, texture); + Texture2D texture = await LoadTexture(image.Url); + promptImagesUI.textures.Insert(0, texture); - newImageCount++; + newImageCount++; + } } - } - Debug.Log("Retrieved " + newImageCount + " new images. Total images: " + imageDataList.Count + "."); + Debug.Log("Retrieved " + newImageCount + " new images. Total images: " + imageDataList.Count + "."); - promptImagesUI?.promptImages?.Repaint(); - } + promptImagesUI?.promptImages?.Repaint(); + } - IEnumerator DeleteImageRequest(string inferenceId, string modelId, string imageId) - { - Debug.Log("Requesting image deletion please wait.."); + IEnumerator DeleteImageRequest(string inferenceId, string modelId, string imageId) + { + Debug.Log("Requesting image deletion please wait.."); - string url = $"{PluginSettings.ApiUrl}/models/{modelId}/inferences/{inferenceId}/images/{imageId}"; - Debug.Log(url); + string url = $"{PluginSettings.ApiUrl}/models/{modelId}/inferences/{inferenceId}/images/{imageId}"; + Debug.Log(url); - RestClient client = new RestClient(url); - RestRequest request = new RestRequest(Method.DELETE); - request.AddHeader("accept", "application/json"); - request.AddHeader("Authorization", $"Basic {PluginSettings.EncodedAuth}"); + RestClient client = new RestClient(url); + RestRequest request = new RestRequest(Method.DELETE); + request.AddHeader("accept", "application/json"); + request.AddHeader("Authorization", $"Basic {PluginSettings.EncodedAuth}"); - yield return client.ExecuteAsync(request, response => - { - if (response.ErrorException != null) - { - Debug.Log($"Error: {response.ErrorException.Message}"); - } - else + yield return client.ExecuteAsync(request, response => { - Debug.Log($"Response: {response.Content}"); - } - }); - } + if (response.ErrorException != null) + { + Debug.Log($"Error: {response.ErrorException.Message}"); + } + else + { + Debug.Log($"Response: {response.Content}"); + } + }); + } - private void OnDestroy() - { - ClearData(); - promptImagesUI.selectedTexture = null; - promptImagesUI.selectedImageId = null; - } + private void OnDestroy() + { + ClearData(); + promptImagesUI.selectedTexture = null; + promptImagesUI.selectedImageId = null; + } - private void OnLostFocus() - { - promptImagesUI.selectedTexture = null; - promptImagesUI.selectedImageId = null; - } + private void OnLostFocus() + { + promptImagesUI.selectedTexture = null; + promptImagesUI.selectedImageId = null; + } - private void ClearData() - { - imageDataList.Clear(); - promptImagesUI.textures.Clear(); - } + private void ClearData() + { + imageDataList.Clear(); + promptImagesUI.textures.Clear(); + } - internal void RemoveBackground(int selectedTextureIndex) - { - string dataUrl = CommonUtils.Texture2DToDataURL(promptImagesUI.textures[selectedTextureIndex]); - EditorCoroutineUtility.StartCoroutineOwnerless(PutRemoveBackground(dataUrl)); - } + internal void RemoveBackground(int selectedTextureIndex) + { + string dataUrl = CommonUtils.Texture2DToDataURL(promptImagesUI.textures[selectedTextureIndex]); + EditorCoroutineUtility.StartCoroutineOwnerless(PutRemoveBackground(dataUrl)); + } - IEnumerator PutRemoveBackground(string dataUrl) - { - string name = CommonUtils.GetRandomImageFileName(); + IEnumerator PutRemoveBackground(string dataUrl) + { + string name = CommonUtils.GetRandomImageFileName(); - Debug.Log("Requesting background removal, please wait.."); + Debug.Log("Requesting background removal, please wait.."); - string url = $"{PluginSettings.ApiUrl}/images/erase-background"; - Debug.Log(url); + string url = $"{PluginSettings.ApiUrl}/images/erase-background"; + Debug.Log(url); - RestClient client = new RestClient(url); - RestRequest request = new RestRequest(Method.PUT); + RestClient client = new RestClient(url); + RestRequest request = new RestRequest(Method.PUT); - string param = $"{{\"image\":\"{dataUrl}\",\"name\":\"{name}\",\"backgroundColor\":\"\",\"format\":\"png\",\"returnImage\":\"false\"}}"; - Debug.Log(param); + string param = $"{{\"image\":\"{dataUrl}\",\"name\":\"{name}\",\"backgroundColor\":\"\",\"format\":\"png\",\"returnImage\":\"false\"}}"; + Debug.Log(param); - request.AddHeader("accept", "application/json"); - request.AddHeader("content-type", "application/json"); - request.AddHeader("Authorization", $"Basic {PluginSettings.EncodedAuth}"); - request.AddParameter("application/json", - param, ParameterType.RequestBody); + request.AddHeader("accept", "application/json"); + request.AddHeader("content-type", "application/json"); + request.AddHeader("Authorization", $"Basic {PluginSettings.EncodedAuth}"); + request.AddParameter("application/json", + param, ParameterType.RequestBody); - yield return client.ExecuteAsync(request, response => - { - if (response.ErrorException != null) - { - Debug.LogError($"Error: {response.ErrorException.Message}"); - } - else + yield return client.ExecuteAsync(request, response => { - Debug.Log($"Response: {response.Content}"); - - try + if (response.ErrorException != null) { - dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content); - string imageUrl = jsonResponse.asset.url; - - EditorCoroutineUtility.StartCoroutineOwnerless(DownloadImageFromUrl(imageUrl)); + Debug.LogError($"Error: {response.ErrorException.Message}"); } - catch (Exception ex) + else { - Debug.LogError("An error occurred while processing the response: " + ex.Message); + Debug.Log($"Response: {response.Content}"); + + try + { + dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content); + string imageUrl = jsonResponse.asset.url; + + EditorCoroutineUtility.StartCoroutineOwnerless(DownloadImageFromUrl(imageUrl)); + } + catch (Exception ex) + { + Debug.LogError("An error occurred while processing the response: " + ex.Message); + } } - } - }); - } + }); + } - IEnumerator DownloadImageFromUrl(string imageUrl) - { - using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl)) + IEnumerator DownloadImageFromUrl(string imageUrl) { - yield return www.SendWebRequest(); - if (www.result != UnityWebRequest.Result.Success) - { - Debug.LogError(www.error); - } - else + using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl)) { - Texture2D texture = DownloadHandlerTexture.GetContent(www); - byte[] pngBytes = texture.EncodeToPNG(); + yield return www.SendWebRequest(); + if (www.result != UnityWebRequest.Result.Success) + { + Debug.LogError(www.error); + } + else + { + Texture2D texture = DownloadHandlerTexture.GetContent(www); + byte[] pngBytes = texture.EncodeToPNG(); - string fileName = "image" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"; - DownloadImage(fileName, pngBytes); + string fileName = "image" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"; + DownloadImage(fileName, pngBytes); + } } } } diff --git a/Scenario/Editor/PromptImages/PromptImagesUI.cs b/Scenario/Editor/PromptImages/PromptImagesUI.cs index 9001949..2110c32 100644 --- a/Scenario/Editor/PromptImages/PromptImagesUI.cs +++ b/Scenario/Editor/PromptImages/PromptImagesUI.cs @@ -1,242 +1,243 @@ -using UnityEngine; -using UnityEditor; using System.Collections.Generic; -using System.IO; -using System; +using UnityEditor; +using UnityEngine; -public class PromptImagesUI +namespace Scenario { - public List textures = new List(); - public int itemsPerRow = 5; - public float padding = 10f; - public Vector2 scrollPosition = Vector2.zero; - public Texture2D selectedTexture = null; - public string selectedImageId = null; - internal PromptImages promptImages; - private int selectedTextureIndex = 0; - private bool isModalOpen = false; - public void Init(PromptImages promptImg) + public class PromptImagesUI { - promptImages = promptImg; - } + public List textures = new List(); + public int itemsPerRow = 5; + public float padding = 10f; + public Vector2 scrollPosition = Vector2.zero; + public Texture2D selectedTexture = null; + public string selectedImageId = null; + internal PromptImages promptImages; + private int selectedTextureIndex = 0; + private bool isModalOpen = false; + public void Init(PromptImages promptImg) + { + promptImages = promptImg; + } - private static void DrawBackground(Rect position) - { - Color backgroundColor = EditorStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } + private static void DrawBackground(Rect position) + { + Color backgroundColor = EditorStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); + } - public void OnGUI(Rect position) - { - DrawBackground(position); + public void OnGUI(Rect position) + { + DrawBackground(position); - float previewWidth = 309f; - float scrollViewWidth = selectedTexture != null ? position.width - previewWidth : position.width; - float boxWidth = (scrollViewWidth - padding * (itemsPerRow - 1)) / itemsPerRow; - float boxHeight = boxWidth; + float previewWidth = 309f; + float scrollViewWidth = selectedTexture != null ? position.width - previewWidth : position.width; + float boxWidth = (scrollViewWidth - padding * (itemsPerRow - 1)) / itemsPerRow; + float boxHeight = boxWidth; - int numRows = Mathf.CeilToInt((float)textures.Count / itemsPerRow); + int numRows = Mathf.CeilToInt((float)textures.Count / itemsPerRow); - float scrollViewHeight = (boxHeight + padding) * numRows; + float scrollViewHeight = (boxHeight + padding) * numRows; - scrollPosition = GUI.BeginScrollView(new Rect(0, 20, scrollViewWidth, position.height - 70), scrollPosition, - new Rect(0, 0, scrollViewWidth - 20, scrollViewHeight)); + scrollPosition = GUI.BeginScrollView(new Rect(0, 20, scrollViewWidth, position.height - 70), scrollPosition, + new Rect(0, 0, scrollViewWidth - 20, scrollViewHeight)); - DrawTextureBoxes(boxWidth, boxHeight); + DrawTextureBoxes(boxWidth, boxHeight); - GUI.EndScrollView(); + GUI.EndScrollView(); - GUILayout.FlexibleSpace(); + GUILayout.FlexibleSpace(); - if (isModalOpen) - { - DrawImageModal(new Rect(0, 0, position.width, position.height)); - } + if (isModalOpen) + { + DrawImageModal(new Rect(0, 0, position.width, position.height)); + } - DrawSelectedTextureSection(position, previewWidth, scrollViewWidth); - } + DrawSelectedTextureSection(position, previewWidth, scrollViewWidth); + } - private void DrawSelectedTextureSection(Rect position, float previewWidth, float scrollViewWidth) - { - if (selectedTexture == null) + private void DrawSelectedTextureSection(Rect position, float previewWidth, float scrollViewWidth) { - return; - } + if (selectedTexture == null) + { + return; + } - float paddedPreviewWidth = previewWidth - 2 * padding; - float aspectRatio = (float)selectedTexture.width / selectedTexture.height; - float paddedPreviewHeight = paddedPreviewWidth / aspectRatio; + float paddedPreviewWidth = previewWidth - 2 * padding; + float aspectRatio = (float)selectedTexture.width / selectedTexture.height; + float paddedPreviewHeight = paddedPreviewWidth / aspectRatio; - GUILayout.BeginArea(new Rect(scrollViewWidth, 20, previewWidth, position.height - 20)); - { - DrawScrollableArea(previewWidth); + GUILayout.BeginArea(new Rect(scrollViewWidth, 20, previewWidth, position.height - 20)); + { + DrawScrollableArea(previewWidth); + } + GUILayout.EndArea(); } - GUILayout.EndArea(); - } - private void DrawScrollableArea(float previewWidth) - { - DrawSelectedImage(previewWidth); - CustomStyle.Space(10); - GUILayout.BeginVertical(); + private void DrawScrollableArea(float previewWidth) { - DrawFirstButtons(); + DrawSelectedImage(previewWidth); CustomStyle.Space(10); - DrawSecondButtons(); + GUILayout.BeginVertical(); + { + DrawFirstButtons(); + CustomStyle.Space(10); + DrawSecondButtons(); + CustomStyle.Space(10); + } + GUILayout.EndVertical(); CustomStyle.Space(10); } - GUILayout.EndVertical(); - CustomStyle.Space(10); - } - private void DrawSelectedImage(float previewWidth) - { - GUILayout.Label("Selected Image", EditorStyles.boldLabel); + private void DrawSelectedImage(float previewWidth) + { + GUILayout.Label("Selected Image", EditorStyles.boldLabel); - CustomStyle.Space(10); + CustomStyle.Space(10); - float aspectRatio = (float)selectedTexture.width / selectedTexture.height; - float paddedPreviewWidth = previewWidth - 2 * padding; - float paddedPreviewHeight = paddedPreviewWidth / aspectRatio; + float aspectRatio = (float)selectedTexture.width / selectedTexture.height; + float paddedPreviewWidth = previewWidth - 2 * padding; + float paddedPreviewHeight = paddedPreviewWidth / aspectRatio; - GUILayout.BeginHorizontal(); - { - CustomStyle.Space(padding); - GUILayout.Label(selectedTexture, GUILayout.Width(paddedPreviewWidth), - GUILayout.Height(paddedPreviewHeight)); - CustomStyle.Space(padding); + GUILayout.BeginHorizontal(); + { + CustomStyle.Space(padding); + GUILayout.Label(selectedTexture, GUILayout.Width(paddedPreviewWidth), + GUILayout.Height(paddedPreviewHeight)); + CustomStyle.Space(padding); + } + GUILayout.EndHorizontal(); } - GUILayout.EndHorizontal(); - } - private void DrawFirstButtons() - { - string[] buttonNames = { "Refine Image", "Download", "Delete" }; - System.Action[] buttonCallbacks = + private void DrawFirstButtons() { - () => PromptWindowUI.imageUpload = selectedTexture, - () => CommonUtils.SaveTextureAsPNG(selectedTexture), - () => + string[] buttonNames = { "Refine Image", "Download", "Delete" }; + System.Action[] buttonCallbacks = { - promptImages.DeleteImageAtIndex(selectedTextureIndex); - selectedTexture = null; - } - }; + () => PromptWindowUI.imageUpload = selectedTexture, + () => CommonUtils.SaveTextureAsPNG(selectedTexture), + () => + { + promptImages.DeleteImageAtIndex(selectedTextureIndex); + selectedTexture = null; + } + }; - GUILayout.BeginHorizontal(); - for (int i = 0; i < buttonNames.Length; i++) - { - if (GUILayout.Button(buttonNames[i], GUILayout.Height(40))) + GUILayout.BeginHorizontal(); + for (int i = 0; i < buttonNames.Length; i++) { - buttonCallbacks[i](); - } + if (GUILayout.Button(buttonNames[i], GUILayout.Height(40))) + { + buttonCallbacks[i](); + } - // Add spacing between buttons but not after the last button - if (i < buttonNames.Length - 1) - { - CustomStyle.Space(10); + // Add spacing between buttons but not after the last button + if (i < buttonNames.Length - 1) + { + CustomStyle.Space(10); + } } + GUILayout.EndHorizontal(); } - GUILayout.EndHorizontal(); - } - private void DrawSecondButtons() - { - string[] buttonNames = { "Remove Background", "Pixelate Image", "Upscale Image" /*, "Generate More Images"*/ }; - System.Action[] buttonCallbacks = + private void DrawSecondButtons() { - () => promptImages.RemoveBackground(selectedTextureIndex), - () => PixelEditor.ShowWindow(selectedTexture, PromptImages.imageDataList[selectedTextureIndex]), - () => UpscaleEditor.ShowWindow(selectedTexture, PromptImages.imageDataList[selectedTextureIndex]) /*, + string[] buttonNames = { "Remove Background", "Pixelate Image", "Upscale Image" /*, "Generate More Images"*/ }; + System.Action[] buttonCallbacks = + { + () => promptImages.RemoveBackground(selectedTextureIndex), + () => PixelEditor.ShowWindow(selectedTexture, PromptImages.imageDataList[selectedTextureIndex]), + () => UpscaleEditor.ShowWindow(selectedTexture, PromptImages.imageDataList[selectedTextureIndex]) /*, () => { // TODO: Implement generate more images functionality }*/ - }; + }; - for (int i = 0; i < buttonNames.Length; i++) - { - GUILayout.BeginHorizontal(); - if (GUILayout.Button(buttonNames[i], GUILayout.Height(40))) - { - buttonCallbacks[i](); - } - GUILayout.EndHorizontal(); - if (i < buttonNames.Length - 1) + for (int i = 0; i < buttonNames.Length; i++) { - CustomStyle.Space(10); + GUILayout.BeginHorizontal(); + if (GUILayout.Button(buttonNames[i], GUILayout.Height(40))) + { + buttonCallbacks[i](); + } + GUILayout.EndHorizontal(); + if (i < buttonNames.Length - 1) + { + CustomStyle.Space(10); + } } } - } - private void DrawImageModal(Rect position) - { - // Determine image dimensions at 2x scale - float imageWidth = selectedTexture.width * 2; - float imageHeight = selectedTexture.height * 2; - - // If the scaled image exceeds the window dimensions, adjust it - if (imageWidth > position.width) + private void DrawImageModal(Rect position) { - float ratio = position.width / imageWidth; - imageWidth = position.width; - imageHeight *= ratio; - } + // Determine image dimensions at 2x scale + float imageWidth = selectedTexture.width * 2; + float imageHeight = selectedTexture.height * 2; - if (imageHeight > position.height) - { - float ratio = position.height / imageHeight; - imageHeight = position.height; - imageWidth *= ratio; - } + // If the scaled image exceeds the window dimensions, adjust it + if (imageWidth > position.width) + { + float ratio = position.width / imageWidth; + imageWidth = position.width; + imageHeight *= ratio; + } + + if (imageHeight > position.height) + { + float ratio = position.height / imageHeight; + imageHeight = position.height; + imageWidth *= ratio; + } - // Compute the position to center the image in the window - float imageX = (position.width - imageWidth) / 2; - float imageY = (position.height - imageHeight) / 2; + // Compute the position to center the image in the window + float imageX = (position.width - imageWidth) / 2; + float imageY = (position.height - imageHeight) / 2; - // Draw the image - GUI.DrawTexture(new Rect(imageX, imageY, imageWidth, imageHeight), selectedTexture, ScaleMode.ScaleToFit); + // Draw the image + GUI.DrawTexture(new Rect(imageX, imageY, imageWidth, imageHeight), selectedTexture, ScaleMode.ScaleToFit); - // Close the modal if clicked outside the image - if (Event.current.type == EventType.MouseDown && - !new Rect(imageX, imageY, imageWidth, imageHeight).Contains(Event.current.mousePosition)) - { - isModalOpen = false; - Event.current.Use(); + // Close the modal if clicked outside the image + if (Event.current.type == EventType.MouseDown && + !new Rect(imageX, imageY, imageWidth, imageHeight).Contains(Event.current.mousePosition)) + { + isModalOpen = false; + Event.current.Use(); + } } - } - private void DrawTextureBoxes(float boxWidth, float boxHeight) - { - for (int i = 0; i < textures.Count; i++) + private void DrawTextureBoxes(float boxWidth, float boxHeight) { - int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); - int colIndex = i % itemsPerRow; + for (int i = 0; i < textures.Count; i++) + { + int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); + int colIndex = i % itemsPerRow; - Rect boxRect = new Rect(colIndex * (boxWidth + padding), rowIndex * (boxHeight + padding), boxWidth, boxHeight); - Texture2D texture = textures[i]; + Rect boxRect = new Rect(colIndex * (boxWidth + padding), rowIndex * (boxHeight + padding), boxWidth, boxHeight); + Texture2D texture = textures[i]; - if (texture != null) - { - // Detect double click - if (Event.current.type == EventType.MouseDown && Event.current.clickCount == 2 && boxRect.Contains(Event.current.mousePosition)) + if (texture != null) { - selectedTexture = texture; - isModalOpen = true; - Event.current.Use(); - return; // Exit early since we've handled the double-click - } + // Detect double click + if (Event.current.type == EventType.MouseDown && Event.current.clickCount == 2 && boxRect.Contains(Event.current.mousePosition)) + { + selectedTexture = texture; + isModalOpen = true; + Event.current.Use(); + return; // Exit early since we've handled the double-click + } - if (GUI.Button(boxRect, "")) + if (GUI.Button(boxRect, "")) + { + selectedTexture = texture; + selectedTextureIndex = i; + } + + GUI.DrawTexture(boxRect, texture, ScaleMode.ScaleToFit); + } + else { - selectedTexture = texture; - selectedTextureIndex = i; + GUI.Box(boxRect, "Loading..."); } - - GUI.DrawTexture(boxRect, texture, ScaleMode.ScaleToFit); - } - else - { - GUI.Box(boxRect, "Loading..."); } } } diff --git a/Scenario/Editor/PromptWindow/PromptBuilderWindow.cs b/Scenario/Editor/PromptWindow/PromptBuilderWindow.cs index 3ec502d..3033f81 100644 --- a/Scenario/Editor/PromptWindow/PromptBuilderWindow.cs +++ b/Scenario/Editor/PromptWindow/PromptBuilderWindow.cs @@ -1,523 +1,526 @@ -using UnityEngine; -using UnityEditor; -using System.Linq; -using System.Collections.Generic; using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; -public class PromptBuilderWindow : EditorWindow +namespace Scenario { - public static bool isFromNegativePrompt = false; - - private string activeCategory = ""; - private string inputText = ""; - private int pageIndex = 0; - private int itemsPerPage = 25; - private int dragFromIndex = -1; - private Vector2 scrollPosition; - private Vector2 dragStartPos; + public class PromptBuilderWindow : EditorWindow + { + public static bool isFromNegativePrompt = false; + + private string activeCategory = ""; + private string inputText = ""; + private int pageIndex = 0; + private int itemsPerPage = 25; + private int dragFromIndex = -1; + private Vector2 scrollPosition; + private Vector2 dragStartPos; - private string[] currentDescriptors = {}; - private List tags = new(); - private List tagRects = new(); - - public static Action onReturn; - public static PromptBuilderWindow Instance; + private string[] currentDescriptors = {}; + private List tags = new(); + private List tagRects = new(); - [MenuItem("Window/Scenario/Prompt Builder")] - public static void ShowWindow() - { - Instance = GetWindow("Prompt Builder"); - } + public static Action onReturn; + public static PromptBuilderWindow Instance; - void OnGUI() - { - DrawBackground(); - tagRects.Clear(); - DrawPromptWithTags(); + [MenuItem("Window/Scenario/Prompt Builder")] + public static void ShowWindow() + { + Instance = GetWindow("Prompt Builder"); + } - CustomStyle.Space(20f); + void OnGUI() + { + DrawBackground(); + tagRects.Clear(); + DrawPromptWithTags(); - GUILayout.Label("Enhance your prompts with additional tokens from these categories:"); - DisplayCategoryButtons(); + CustomStyle.Space(20f); - CustomStyle.Space(20f); + GUILayout.Label("Enhance your prompts with additional tokens from these categories:"); + DisplayCategoryButtons(); - GUILayout.Label("Choose a descriptor to add to your prompt"); - DisplayDescriptorButtons(currentDescriptors.Skip(pageIndex * itemsPerPage).Take(itemsPerPage).ToArray()); + CustomStyle.Space(20f); - CustomStyle.Space(20f); + GUILayout.Label("Choose a descriptor to add to your prompt"); + DisplayDescriptorButtons(currentDescriptors.Skip(pageIndex * itemsPerPage).Take(itemsPerPage).ToArray()); - DisplayNavigationButtons(); - DrawUpdateButton(); - } + CustomStyle.Space(20f); - private void DrawBackground() - { - Color backgroundColor = EditorStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } + DisplayNavigationButtons(); + DrawUpdateButton(); + } - private void DrawUpdateButton() - { - Rect bottomAreaRect = new Rect(0, Screen.height - 60, Screen.width, 60); + private void DrawBackground() + { + Color backgroundColor = EditorStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); + } - GUILayout.BeginArea(bottomAreaRect); + private void DrawUpdateButton() { - if (onReturn != null) + Rect bottomAreaRect = new Rect(0, Screen.height - 60, Screen.width, 60); + + GUILayout.BeginArea(bottomAreaRect); { - EditorStyle.ButtonPrimary("Update Tags", 40, () => + if (onReturn != null) { - Close(); - onReturn?.Invoke(SerializeTags()); - onReturn = null; - }); + EditorStyle.ButtonPrimary("Update Tags", 40, () => + { + Close(); + onReturn?.Invoke(SerializeTags()); + onReturn = null; + }); + } } + GUILayout.EndArea(); } - GUILayout.EndArea(); - } - private void DrawPromptWithTags() - { - EditorGUILayout.LabelField("Prompt with tags"); - EditorGUILayout.BeginVertical(GUI.skin.box, GUILayout.Height(100)); + private void DrawPromptWithTags() { - EditorGUILayout.BeginVertical(EditorStyles.helpBox); + EditorGUILayout.LabelField("Prompt with tags"); + EditorGUILayout.BeginVertical(GUI.skin.box, GUILayout.Height(100)); { - GUIStyle customTagStyle = new GUIStyle(EditorStyles.label) + EditorGUILayout.BeginVertical(EditorStyles.helpBox); { - fixedHeight = 25, - margin = new RectOffset(0, 5, 0, 5) - }; - - float availableWidth = EditorGUIUtility.currentViewWidth - 20; - int tagsPerRow = Mathf.FloorToInt(availableWidth / 100); - int currentTagIndex = 0; + GUIStyle customTagStyle = new GUIStyle(EditorStyles.label) + { + fixedHeight = 25, + margin = new RectOffset(0, 5, 0, 5) + }; - while (currentTagIndex < tags.Count) - { - EditorGUILayout.BeginHorizontal(); + float availableWidth = EditorGUIUtility.currentViewWidth - 20; + int tagsPerRow = Mathf.FloorToInt(availableWidth / 100); + int currentTagIndex = 0; - for (int i = 0; i < tagsPerRow && currentTagIndex < tags.Count; i++) + while (currentTagIndex < tags.Count) { - Rect tagRect = GUILayoutUtility.GetRect(new GUIContent(tags[currentTagIndex]), customTagStyle); + EditorGUILayout.BeginHorizontal(); - bool isActiveTag = currentTagIndex == dragFromIndex; - GUIStyle tagStyle = isActiveTag ? new GUIStyle(customTagStyle) { normal = { background = MakeTex(2, 2, isActiveTag ? new Color(0.5f, 0.5f, 0.5f) : new Color(0.8f, 0.8f, 0.8f)) } } : customTagStyle; + for (int i = 0; i < tagsPerRow && currentTagIndex < tags.Count; i++) + { + Rect tagRect = GUILayoutUtility.GetRect(new GUIContent(tags[currentTagIndex]), customTagStyle); - Rect xRect = new Rect(tagRect.xMax - 20, tagRect.y, 20, tagRect.height); + bool isActiveTag = currentTagIndex == dragFromIndex; + GUIStyle tagStyle = isActiveTag ? new GUIStyle(customTagStyle) { normal = { background = MakeTex(2, 2, isActiveTag ? new Color(0.5f, 0.5f, 0.5f) : new Color(0.8f, 0.8f, 0.8f)) } } : customTagStyle; - if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && tagRect.Contains(Event.current.mousePosition)) - { - if (!xRect.Contains(Event.current.mousePosition)) + Rect xRect = new Rect(tagRect.xMax - 20, tagRect.y, 20, tagRect.height); + + if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && tagRect.Contains(Event.current.mousePosition)) { - dragFromIndex = currentTagIndex; - dragStartPos = Event.current.mousePosition; - Event.current.Use(); + if (!xRect.Contains(Event.current.mousePosition)) + { + dragFromIndex = currentTagIndex; + dragStartPos = Event.current.mousePosition; + Event.current.Use(); + } } - } - if (dragFromIndex >= 0 && Event.current.type == EventType.MouseDrag) - { - int newIndex = GetNewIndex(Event.current.mousePosition); - if (newIndex != -1 && newIndex != dragFromIndex) + if (dragFromIndex >= 0 && Event.current.type == EventType.MouseDrag) { - string tempTag = tags[dragFromIndex]; - tags.RemoveAt(dragFromIndex); - tags.Insert(newIndex, tempTag); - dragFromIndex = newIndex; + int newIndex = GetNewIndex(Event.current.mousePosition); + if (newIndex != -1 && newIndex != dragFromIndex) + { + string tempTag = tags[dragFromIndex]; + tags.RemoveAt(dragFromIndex); + tags.Insert(newIndex, tempTag); + dragFromIndex = newIndex; + } } - } - if (Event.current.type == EventType.MouseUp) - { - dragFromIndex = -1; - } + if (Event.current.type == EventType.MouseUp) + { + dragFromIndex = -1; + } - EditorGUI.LabelField(tagRect, tags[currentTagIndex], tagStyle); + EditorGUI.LabelField(tagRect, tags[currentTagIndex], tagStyle); - if (GUI.Button(xRect, "x")) - { - tags.RemoveAt(currentTagIndex); - } - else - { - currentTagIndex++; + if (GUI.Button(xRect, "x")) + { + tags.RemoveAt(currentTagIndex); + } + else + { + currentTagIndex++; + } + + tagRects.Add(tagRect); } - tagRects.Add(tagRect); + EditorGUILayout.EndHorizontal(); } - - EditorGUILayout.EndHorizontal(); } - } - EditorGUILayout.EndVertical(); + EditorGUILayout.EndVertical(); - EditorGUILayout.BeginVertical(); - { - GUI.SetNextControlName("inputTextField"); - inputText = EditorGUILayout.TextField(inputText, GUILayout.ExpandWidth(true), GUILayout.Height(25)); - - if (Event.current.isKey && Event.current.keyCode == KeyCode.Return) + EditorGUILayout.BeginVertical(); { - if (GUI.GetNameOfFocusedControl() == "inputTextField") + GUI.SetNextControlName("inputTextField"); + inputText = EditorGUILayout.TextField(inputText, GUILayout.ExpandWidth(true), GUILayout.Height(25)); + + if (Event.current.isKey && Event.current.keyCode == KeyCode.Return) { - if (!string.IsNullOrWhiteSpace(inputText)) + if (GUI.GetNameOfFocusedControl() == "inputTextField") { - string descriptorName = inputText.Trim(); - tags.Add(descriptorName); - inputText = ""; + if (!string.IsNullOrWhiteSpace(inputText)) + { + string descriptorName = inputText.Trim(); + tags.Add(descriptorName); + inputText = ""; + Event.current.Use(); + } + } + else + { + EditorGUI.FocusTextInControl("inputTextField"); Event.current.Use(); } } - else - { - EditorGUI.FocusTextInControl("inputTextField"); - Event.current.Use(); - } } + EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); - } - - private string SerializeTags() - { - string str = ""; - foreach (var tag in tags) - { - str += tag + ", "; - } - return str; - } - private int GetNewIndex(Vector2 currentPos) - { - for (int i = 0; i < tagRects.Count; i++) + private string SerializeTags() { - if (tagRects[i].Contains(currentPos)) + string str = ""; + foreach (var tag in tags) { - return i; + str += tag + ", "; } + return str; } - return -1; - } - - private void DisplayCategoryButtons() - { - string[] categories = PromptData.GetCategories(); - float buttonWidth = 100; - int buttonsPerRow = Mathf.FloorToInt(position.width / buttonWidth); - int currentButton = 0; - GUIStyle activeButtonStyle = new GUIStyle(GUI.skin.button) + private int GetNewIndex(Vector2 currentPos) { - normal = + for (int i = 0; i < tagRects.Count; i++) { - textColor = Color.blue + if (tagRects[i].Contains(currentPos)) + { + return i; + } } - }; - for (int i = 0; i < categories.Length; i++) + return -1; + } + + private void DisplayCategoryButtons() { - if (currentButton % buttonsPerRow == 0) + string[] categories = PromptData.GetCategories(); + float buttonWidth = 100; + int buttonsPerRow = Mathf.FloorToInt(position.width / buttonWidth); + int currentButton = 0; + GUIStyle activeButtonStyle = new GUIStyle(GUI.skin.button) { - EditorGUILayout.BeginHorizontal(); - } + normal = + { + textColor = Color.blue + } + }; - bool isActiveCategory = categories[i] == activeCategory; - GUIStyle buttonStyle = isActiveCategory ? activeButtonStyle : GUI.skin.button; - if (GUILayout.Toggle(isActiveCategory, categories[i], buttonStyle, GUILayout.Width(100), GUILayout.Height(25))) + for (int i = 0; i < categories.Length; i++) { - if (!isActiveCategory) + if (currentButton % buttonsPerRow == 0) { - activeCategory = categories[i]; - currentDescriptors = PromptData.GetDescriptorsForCategory(activeCategory); - scrollPosition = Vector2.zero; + EditorGUILayout.BeginHorizontal(); + } + + bool isActiveCategory = categories[i] == activeCategory; + GUIStyle buttonStyle = isActiveCategory ? activeButtonStyle : GUI.skin.button; + if (GUILayout.Toggle(isActiveCategory, categories[i], buttonStyle, GUILayout.Width(100), GUILayout.Height(25))) + { + if (!isActiveCategory) + { + activeCategory = categories[i]; + currentDescriptors = PromptData.GetDescriptorsForCategory(activeCategory); + scrollPosition = Vector2.zero; + } } - } - currentButton++; + currentButton++; - if (currentButton % buttonsPerRow == 0 || i == categories.Length - 1) - { - EditorGUILayout.EndHorizontal(); + if (currentButton % buttonsPerRow == 0 || i == categories.Length - 1) + { + EditorGUILayout.EndHorizontal(); + } } } - } - private void DisplayDescriptorButtons(string[] descriptors) - { - if (descriptors.Count() <= 0) + private void DisplayDescriptorButtons(string[] descriptors) { - return; - } + if (descriptors.Count() <= 0) + { + return; + } - int maxCharsPerLine = 20; - int buttonWidthPerChar = 8; + int maxCharsPerLine = 20; + int buttonWidthPerChar = 8; - float maxButtonWidth = descriptors.Max(d => Mathf.Min(d.Length, maxCharsPerLine) * buttonWidthPerChar); + float maxButtonWidth = descriptors.Max(d => Mathf.Min(d.Length, maxCharsPerLine) * buttonWidthPerChar); - int buttonsPerRow = Mathf.FloorToInt(position.width / maxButtonWidth); - int currentButton = 0; + int buttonsPerRow = Mathf.FloorToInt(position.width / maxButtonWidth); + int currentButton = 0; - EditorGUILayout.BeginVertical(); - for (int i = 0; i < descriptors.Length; i++) - { - if (currentButton % buttonsPerRow == 0) + EditorGUILayout.BeginVertical(); + for (int i = 0; i < descriptors.Length; i++) { - EditorGUILayout.BeginHorizontal(); - } + if (currentButton % buttonsPerRow == 0) + { + EditorGUILayout.BeginHorizontal(); + } - DisplayDescriptorButton(descriptors[i], Mathf.FloorToInt(position.width / buttonsPerRow)); + DisplayDescriptorButton(descriptors[i], Mathf.FloorToInt(position.width / buttonsPerRow)); - currentButton++; + currentButton++; - if (currentButton % buttonsPerRow == 0 || i == descriptors.Length - 1) - { - EditorGUILayout.EndHorizontal(); + if (currentButton % buttonsPerRow == 0 || i == descriptors.Length - 1) + { + EditorGUILayout.EndHorizontal(); + } } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); - } - void DisplayDescriptorButton(string descriptorName, int maxWidth) - { - if (GUILayout.Button(descriptorName, GUILayout.Width(maxWidth), GUILayout.Height(25))) + void DisplayDescriptorButton(string descriptorName, int maxWidth) { - tags.Add(descriptorName); + if (GUILayout.Button(descriptorName, GUILayout.Width(maxWidth), GUILayout.Height(25))) + { + tags.Add(descriptorName); + } } - } - void DisplayNavigationButtons() - { - EditorGUILayout.BeginHorizontal(); - EditorGUI.BeginDisabledGroup(pageIndex == 0); - if (GUILayout.Button("Previous", GUILayout.Width(100), GUILayout.Height(25))) + void DisplayNavigationButtons() { - pageIndex--; + EditorGUILayout.BeginHorizontal(); + EditorGUI.BeginDisabledGroup(pageIndex == 0); + if (GUILayout.Button("Previous", GUILayout.Width(100), GUILayout.Height(25))) + { + pageIndex--; + } + EditorGUI.EndDisabledGroup(); + + EditorGUI.BeginDisabledGroup(pageIndex >= Mathf.CeilToInt((float)currentDescriptors.Length / itemsPerPage) - 1); + if (GUILayout.Button("Next", GUILayout.Width(100), GUILayout.Height(25))) + { + pageIndex++; + } + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndHorizontal(); } - EditorGUI.EndDisabledGroup(); - EditorGUI.BeginDisabledGroup(pageIndex >= Mathf.CeilToInt((float)currentDescriptors.Length / itemsPerPage) - 1); - if (GUILayout.Button("Next", GUILayout.Width(100), GUILayout.Height(25))) + private Texture2D MakeTex(int width, int height, Color color) { - pageIndex++; + Color[] pix = new Color[width * height]; + for (int i = 0; i < pix.Length; i++) + { + pix[i] = color; + } + Texture2D result = new Texture2D(width, height); + result.SetPixels(pix); + result.Apply(); + return result; } - EditorGUI.EndDisabledGroup(); - EditorGUILayout.EndHorizontal(); - } - private Texture2D MakeTex(int width, int height, Color color) - { - Color[] pix = new Color[width * height]; - for (int i = 0; i < pix.Length; i++) + internal static void ShowWindow(Action onPromptBuilderReturn, List tagList) { - pix[i] = color; + ShowWindow(); + Instance.tags = tagList; + onReturn += onPromptBuilderReturn; } - Texture2D result = new Texture2D(width, height); - result.SetPixels(pix); - result.Apply(); - return result; - } - - internal static void ShowWindow(Action onPromptBuilderReturn, List tagList) - { - ShowWindow(); - Instance.tags = tagList; - onReturn += onPromptBuilderReturn; } -} -public static class PromptData -{ - public static string[] GetCategories() + public static class PromptData { - return new[] { "Art Style", "Art Medium", "Describers", "Colors", "Materials", "Lighting", "Framing", "Render", "Details", "Epoch", "Weather", "Aesthetics", "Others" }; - } + public static string[] GetCategories() + { + return new[] { "Art Style", "Art Medium", "Describers", "Colors", "Materials", "Lighting", "Framing", "Render", "Details", "Epoch", "Weather", "Aesthetics", "Others" }; + } - public static string[] GetDescriptorsForCategory(string category) - { - return category switch + public static string[] GetDescriptorsForCategory(string category) { - "Art Style" => new[] - { - "abstract", "anime", "art deco", "bauhaus", "brutalism", "comic book style", "contemporary", - "cubism", "cyberpunk", "fantasy", "fine lining", "futurism", "impressionism", "isometric", "kawaii", - "low-poly", "manga", "pixel art", "pop art", "retro", "sci-fi", "sharp lines", "steampunk", - "surrealism", "vector", "voxel art" - }, - "Art Medium" => new[] - { - "acrylic paint", "amigurumi", "cartoon", "chalk art", "character design", "concept art", - "concept design", "digital art", "diorama", "drawing", "fine art", "gouache", "graffiti", - "illustration", "Japanese print", "oil", "painting", "paper model", "paper-marbling", - "papercutting", "sculpture", "sketch", "street art", "watercolor" - }, - "Describers" => new[] - { - "apocalyptic", "beautiful", "big", "centered", "chaotic", "delicate", "distorted", "geometric", - "gloomy", "intricate", "kaleidoscopic", "magical", "minimalist", "monumental", "organic", "ornate", - "psychedelic", "sad", "scary", "small", "somber", "symmetric", "tall", "trending on Artstation", - "trending on Pixiv" - }, - "Colors" => new[] - { - "aquamarine", "azure", "black", "blue", "brown", "charcoal", "color sharding", "colorful", - "contrasted", "coral", "cyan", "desaturated", "fuchsia", "gray", "green", "hot pink magenta", - "hue colors", "ivory", "khaki", "lime", "maroon", "multicolor", "navy blue", "olive", "orange", - "plum", "purple", "rainbow", "red", "saturated", "silver", "teal", "vivid", "white", "yellow" - }, - "Materials" => new[] - { - "aluminum", "bronze", "clay", "concrete", "copper", "dirt", "epoxy resin", "fabric", "foam", - "glass", "gold", "iron", "lead", "marble", "metal", "nickel", "paper", "plastic", "plasticine", - "rubber", "sand", "silver", "stainless steel", "stone", "titanium", "wood", "zinc" - }, - "Lighting" => new[] + return category switch { - "Christmas light", "Xray", "backlight", "blacklight", "blue lighting", "bright", "candlelight", - "cinematic lighting", "colorful lighting", "concert lighting", "contre-jour", "crepuscular rays", - "dark", "dark lighting", "dawn", "daylight", "dim lighting", "direct sunlight", "dramatic lighting", - "fairy lights", "glowing", "glowing radioactively", "golden hour", "incandescent light", - "moonlight", "neon", "nightclub lighting", "nuclear waste glow", "quantum dot display", - "realistic lighting", "soft lighting", "spotlight", "strobe", "studio lighting", "sunlight", - "sunrise", "sunset", "twilight", "ultraviolet", "ultraviolet light", "volumetric lighting" - }, - "Framing" => new[] - { - "GoPro view", "aerial view", "body shot", "close-up", "close-up portrait", "cow-boy shot", - "face shot", "fisheye", "full body shot", "landscape", "long shot", "low angle", "lower body shot", - "massive scale", "panoramic", "portrait", "side view", "street level view", "top-down", - "ultra wide-angle", "upper body shot", "wide shot", "wide-angle" - }, - "Render" => new[] - { - "2d platformer", "3D rendering", "Blender rendering", "CGsociety", "Cinema4D rendering", - "Houdini rendering", "Octane rendering", "Photoshop", "Redshift rendering", "Sketchfab", - "Substance 3D", "Unreal Engine rendering", "Zbrush rendering", "cgi", "highly detailed" - }, - "Details" => new[] - { - "100mm", "16-bit", "4k", "500px", "64-bit", "8-bit", "8k", "DSLR", "HDR", "analog photography", - "bokeh", "depth of field", "detailed", "film photography", "hi-fi", "high quality", - "highly detailed", "hyper-realistic", "lo-fi", "polaroid", "studio quality", "uhd", - "ultra realistic" - }, - "Epoch" => new[] - { - "1100s", "Assyrian Empire", "Aztec", "Babylonian Empire", "Benin Kingdom", "Bronze Age", - "Byzantine Empire", "Carolingian", "Dark Ages", "Edwardian", "Elizabethan", "Georgian", - "Gilded Age", "Great Depression", "Heian Period", "Incan", "Industrial Revolution", "Iron Age", - "Maori", "Mayan", "Meiji Period", "Middle Ages", "Ming Dynasty", "Minoan", "Moorish", "Mughal Era", - "Nasrid", "Navajo", "Neolithic", "Olmec", "Ottoman Empire", "Paleolithic", "Persian Empire", - "Primitive society", "Qing Dynasty", "Regency", "Renaissance", "Shang Dynasty", "Songhai", - "Stone Age", "Sumerian", "Tokugawa Shogunate", "Tudor", "Victorian", "Viking", "World War I", - "World War II", "Zhou Dynasty", "Zuni-Pueblo", "ancient Egypt", "ancient Greece", "ancient Rome", - "antique", "antiquity", "aztec", "bronze age", "contemporary", "future", "medieval", "mid-century", - "middle ages", "modern", "modern world", "pre-Columbian", "prehistoric", "renaissance", "retro", - "sci-fi", "space age", "victorian", "viking" - }, - "Weather" => new[] - { - "cloudy", "foggy", "frosty", "humid", "icy", "rainy", "snowy", "stormy", "sunny", "windy" - }, - "Aesthetics" => new[] - { - "Abstract Tech", "Acid Pixie", "Acidwave", "Acubi", "Adventure Pulp", "Adventurecore", "Aetherpunk", - "Afro-Victorian", "Afrofuturism", "After Hours", "Agropeople", "Alien", "Alternative", - "American Pioneers", "American Revolution", "American Thanksgiving", "American Tourist Traps", - "Americana", "Analog Horror", "Ancient Egypt", "Androgynous", "Anemoiacore", "Angelcore", - "Anglo Gothic", "Angura Kei", "Animecore", "Anti-Fashion", "Antique Grunge", "Arcade", "Arcadecore", - "Art Academia", "Art Deco", "Art Hoe", "Art Nouveau", "Arts and Crafts Movement", "Athlete", - "Atompunk", "Auroracore", "Autumn", "Autumn Academia", "Avant Apocalypse", "Avant-garde", - "Back-to-School", "Baddie", "Ballet Academia", "Baltic Violence Tumblr", "Barbiecore", "Bardcore", - "Baroque", "Bastardcore", "Bauhaus", "Beach Day", "Beatnik", "Biker", "Bimbocore", "Biohazard", - "Biopunk", "Bizarro Fiction", "Black-Holed Meme", "Bodikon", "Bohemian", "Bronzepunk", "C-Pop", - "Camp", "Campcore", "Candycore", "Cargopunk", "Carnivalcore", "Cartoon", "Cartooncore", "Casino", - "Cassette Futurism", "Celtic", "Changelingcore", "Chaotic Academia", "Chav", "Cheiron Crush", - "Cholo", "Christmas", "Chunyu", "City Pop", "Classic Academia", "Classic Lolita", "Classicism", - "Cleancore", "Clockpunk", "Cloudcore", "Clowncore", "Club", "Club Kids", "Coastal Grandmother", - "Coffee House/Cafe", "Coffinwood", "Colourful Black", "Comfy/Cozy", "Concore", "Constructivism", - "Coquette", "Coquette Academia", "Corporate", "Corporate Memphis", "Corporate Punk", "Cottagecore", - "Cottagegore", "Country", "Cozy Childhood Hideaway", "Craftcore", "Cripplepunk", "Crowcore", - "Crustpunk", "Cryptid Academia", "Cryptidcore", "Cubism", "Cuddle Party", "Cult Party Kei", - "Cultcore", "Cutecore", "Cyber Fairy Grunge", "Cyberdelic", "Cyberghetto", "Cybergoth", - "Cybergrunge", "CyberneticPunk", "Cyberparadism", "Cyberpop", "Cyberprep", "Cyberpunk", - "Danish Pastel", "Dark Academia", "Dark Fantasy", "Dark Naturalism", "Dark Nautical", - "Dark Nymphet", "Dark Paradise", "DarkErrorcore", "Darkcore", "Darkest Academia", "Daydreampunk", - "Dazecore", "De Stijl", "Deathcore", "Deathrock", "Decopunk", "Decora", "Delicate Sweet", - "Desertwave", "Desi Romantic Academia", "Dethereal", "Devilcore", "Dieselpunk", "Diner", - "Dionysism", "Dolly Kei", "Dracopunk", "Dragoncore", "Drain", "Dreamcore", "Dreamy", "Drugcore", - "Dual Kawaii", "Duckcore", "Dullcore", "Dungeon Synth", "Earthcore", "Electro Swing", - "ElectroPop 08", "Emo", "English Major", "Equestrian", "Erokawa", "Ethereal", "Europunk", - "Expressionism", "Fairy Academia", "Fairy Grunge", "Fairy Kei", "Fairy Tale", "Fairycore", - "Fanfare", "Fantasy", "Fantasy Astronomy", "Farmer's Daughter", "Fashwave", "Fauvism", "Fawncore", - "Femme Fatale", "Feralcore", "Film Noir", "Flapper", "Flat Design", "Folk Punk", "Foodie", - "Forestpunk", "French", "Frogcore", "Frutiger Aero", "Funky Seasons", "Furry", "Futago", "Futurism", - "Gadgetpunk", "Game Night", "Gamercore", "Gamine", "Geek", "Gen X Soft Club", "Ghostcore", - "Glam Rock", "Glitchcore", "Gloomcore", "Glowwave", "Goblin Academia", "Goblincore", - "Golden Age of Detective Fiction", "Golden Hour", "Gopnik", "Gorecore", "Gorpcore", "Goth", - "Gothcore", "Gothic", "Gothic Lolita", "Grandmillenial", "Grandparentcore", "Greaser", - "Green Academia", "Grifes", "Grindhouse", "Groundcore", "Grunge", "Gurokawa", "Gyaru", "Hackercore", - "Halloween", "Hallyu", "Happycore", "Hatecore", "Hauntology", "Haussmann Paris", "Health Goth", - "Heatwave", "Heistcore", "Hellenic", "Hermaphroditus", "Hermitpunk", "Hexatron", "Hi-NRG", - "High School Dream", "Hikecore", "Hime Lolita", "Hip-Hop", "Hipness Purgatory", "Hippie", "Hipster", - "Hispanicore", "Historical Americana", "Holosexual", "Honeycore", "Horror", "Horror Academia", - "Hot Topic", "Hustlewave", "Hydrogen", "Hyperpop", "Icepunk", "Imaginarium", "Impressionism", - "Indicolite", "Indie", "Indie Kid", "Indie Sleaze", "Internet Academia", "Italian Mafia", - "Italian Renaissance", "Italo Disco", "Jamcore", "Japanese High School", "Jersey Shore", "Joyride", - "Juggalo", "Jungle Grunge", "Junglecore", "Karasu Zoku", "Kawaii", "Kawaii Gamer", - "Key West Kitten", "Kid Science", "Kidcore", "Kimoicore", "Kinderwhore", "King Gas", "Kingcore", - "Knightcore", "Kogal", "Kuromicore", "La Sape", "Labcore", "Laborwave", "Lagenlook", "Larme Kei", - "Larme Kei", "Late 2000s Elementary School", "Libertywave", "Light Academia", "Lightcore", - "Lightningwave", "Liminal Space", "Lit Kid", "Lo-Fi", "Long Island", "Lounge", "Lovecore", - "Lunarpunk", "MTV Green Sky", "Macaute", "Mad Scientist", "Magewave", "Magical", "Maidcore", - "Mall Ninja", "Mallgoth", "Maximalism", "McBling", "Meatcore", "Medicalcore", "Medieval", "Memphis", - "Mermaid", "Metal", "Metalcore", "Metalheart", "Metrosexual", "Miami Metro", "Midwest Emo", - "Midwest Gothic", "Military", "Milk", "Miniaturecore", "Minimalism", "Minivan Rock", - "Miscellaneous Academia", "Mizuiro Kaiwai", "Mod", "Modern Brazil", "Modernism", "Mori Kei", - "Morute", "Mosscore", "Mote Kei", "Ms Paint", "Mulchcore", "Mushroomcore", "Musical Academia", - "Mythpunk", "Nanopunk", "Naturecore", "Nautical", "Neko", "Neo-Romanism", "Neo-Tokyo", "Nerd", - "Nerdcore", "New Age", "New England Gothic", "New Money", "New Romantic", "New Wave", "Nihilcore", - "Nintencore", "Normcore", "Northerness", "Nostalgiacore", "Nu-Goth", "Nuclear", "Nymphet", - "Ocean Academia", "Ocean Grunge", "Old Hollywood", "Old Memecore", "Old Money", "Old Web", - "Onii Kei", "Oshare Kei", "Otaku", "Otherkin", "PC Music", "Pachuco", "Pale Grunge", "Paleocore", - "Palewave", "Paramilitary", "Party Animal", "Party Kei", "Pastel", "Pastel Academia", "Pastel Goth", - "Pastel Punk", "Peach", "Pearly", "Peoplehood", "Photorealism", "Pin-up", "Pink Parisian", - "Pink Pilates Princess", "Pink Princess", "Pinterest Coquette", "Pirate", "Pixel Cutie", - "Pixiecore", "Plaguecore", "Plant Mom", "Pop", "Pop Art", "Pop Kei", "Post-Apocalyptic", - "Post-Impressionism", "Post-Punk", "Post-rock", "Powwow Step", "Prairiecore", "Pre-Raphaelite", - "Prehistoricore", "Pride flags", "Princecore", "Princesscore", "Printcore", "Progressive Academia", - "Psychedelica", "Punk", "Purism", "Quality Tumblr", "Queencore", "Queer Academia", "Queercore", - "R&B", "Racaille", "Ragecore", "Rainbowcore", "Rainy Day", "Randumb", "Rangercore", "Ratcore", - "Ravencore", "Raver", "Real Life Super Hero", "Realism", "Reefwave", "Regency", "Regional Gothic", - "Retro-Futurism", "Rivethead", "Roaring 20s", "Robotics Kid", "Rock", "Rockabilly", "Rococo", - "Roguecore", "Rollerwave", "Roma", "Romantic Academia", "Romantic Goth", "Romantic Italian", - "Romanticism", "Rotcore", "Royalcore", "Rusticcore", "Sad people", "Salon Kei", "Salvagepunk", - "Sandalpunk", "Sanriocore", "Scene", "Schizowave", "Science Academia", "Scoutcore", "Scrapbook", - "Scrapper", "Seapunk", "Selkiecore", "Shanzhai", "Sharpies", "Shibuya Punk", "Shironuri", - "Shoegaze", "Shā mǎ tè", "Shamate", "Sigilkore", "Sizz", "Skater", "Sleepycore", "Slimepunk", - "Sloanies", "Snow Bunny", "Snowdrop", "Soft Apocalypse", "Soft Grunge", "Soft Macabre", - "Soft indie", "Softie", "Soggy", "Solarpunk", "Southern Belle", "Southern Gothic", "Space Cowboy", - "Spacecore", "Sparklecore", "Spiritcore", "Tacticool", "Takenokozoku", "Tanbi Kei", - "Technical Scene", "Technocore", "Technozen", "Techwear", "Teddies", "Teenqueen", "Teethcore", - "Terrorwave", "Teslapunk", "Theatre Academia", "Theatre Kids", "Thrasher", "Thriftcore", "Tiki", - "Tinkercore", "Tinycore", "Trad Goth", "Traditional Korean", "Trailer Park Princess", "Trenchcore", - "Trendercore", "Trillwave", "Tropical", "Tumblewave", "Tupinipunk", "Twee", "Tweencore", "Ukiyo-e", - "Unicorncore", "Urban Fantasy", "Urbancore", "Utopian Scholastic", "VSCO", "Vampire", "Vaporwave", - "Vectorbloom", "Vectorheart", "Vibrant Academia", "Victorian", "Victorian Goth", "Viking", - "Villagecore", "Villaincore", "Vintage British Sportsman", "Vintage Parisian", "Virgo's Tears", - "Visual Kei", "Voidcore", "Voidpunk", "Vorticism", "Vulture Culture", "Wabi-Sabi", "Waif", - "Waldorf", "Wanderlust", "Warmcore", "Weathercore", "Web Creep", "Weeaboo", "Weirdcore", "Werewolf", - "Western", "Wetcore", "Wild Child", "Winter", "Winter Fairy Coquette", "Witch House", "Witchcore", - "Witchy Academia", "Wizardcore", "Wonderland", "Woodland Goth", "Wormcore", "Writer Academia", - "Wuxia", "XO", "Y2K", "Yakuza", "Yami Kawaii", "Yandere", "Yankeecore", "Yanki", "Youthquake", - "Yume Kawaii", "Zombie Apocalypse" - }, - "Others" => new[] { " " }, - _ => new[] { " " } - }; + "Art Style" => new[] + { + "abstract", "anime", "art deco", "bauhaus", "brutalism", "comic book style", "contemporary", + "cubism", "cyberpunk", "fantasy", "fine lining", "futurism", "impressionism", "isometric", "kawaii", + "low-poly", "manga", "pixel art", "pop art", "retro", "sci-fi", "sharp lines", "steampunk", + "surrealism", "vector", "voxel art" + }, + "Art Medium" => new[] + { + "acrylic paint", "amigurumi", "cartoon", "chalk art", "character design", "concept art", + "concept design", "digital art", "diorama", "drawing", "fine art", "gouache", "graffiti", + "illustration", "Japanese print", "oil", "painting", "paper model", "paper-marbling", + "papercutting", "sculpture", "sketch", "street art", "watercolor" + }, + "Describers" => new[] + { + "apocalyptic", "beautiful", "big", "centered", "chaotic", "delicate", "distorted", "geometric", + "gloomy", "intricate", "kaleidoscopic", "magical", "minimalist", "monumental", "organic", "ornate", + "psychedelic", "sad", "scary", "small", "somber", "symmetric", "tall", "trending on Artstation", + "trending on Pixiv" + }, + "Colors" => new[] + { + "aquamarine", "azure", "black", "blue", "brown", "charcoal", "color sharding", "colorful", + "contrasted", "coral", "cyan", "desaturated", "fuchsia", "gray", "green", "hot pink magenta", + "hue colors", "ivory", "khaki", "lime", "maroon", "multicolor", "navy blue", "olive", "orange", + "plum", "purple", "rainbow", "red", "saturated", "silver", "teal", "vivid", "white", "yellow" + }, + "Materials" => new[] + { + "aluminum", "bronze", "clay", "concrete", "copper", "dirt", "epoxy resin", "fabric", "foam", + "glass", "gold", "iron", "lead", "marble", "metal", "nickel", "paper", "plastic", "plasticine", + "rubber", "sand", "silver", "stainless steel", "stone", "titanium", "wood", "zinc" + }, + "Lighting" => new[] + { + "Christmas light", "Xray", "backlight", "blacklight", "blue lighting", "bright", "candlelight", + "cinematic lighting", "colorful lighting", "concert lighting", "contre-jour", "crepuscular rays", + "dark", "dark lighting", "dawn", "daylight", "dim lighting", "direct sunlight", "dramatic lighting", + "fairy lights", "glowing", "glowing radioactively", "golden hour", "incandescent light", + "moonlight", "neon", "nightclub lighting", "nuclear waste glow", "quantum dot display", + "realistic lighting", "soft lighting", "spotlight", "strobe", "studio lighting", "sunlight", + "sunrise", "sunset", "twilight", "ultraviolet", "ultraviolet light", "volumetric lighting" + }, + "Framing" => new[] + { + "GoPro view", "aerial view", "body shot", "close-up", "close-up portrait", "cow-boy shot", + "face shot", "fisheye", "full body shot", "landscape", "long shot", "low angle", "lower body shot", + "massive scale", "panoramic", "portrait", "side view", "street level view", "top-down", + "ultra wide-angle", "upper body shot", "wide shot", "wide-angle" + }, + "Render" => new[] + { + "2d platformer", "3D rendering", "Blender rendering", "CGsociety", "Cinema4D rendering", + "Houdini rendering", "Octane rendering", "Photoshop", "Redshift rendering", "Sketchfab", + "Substance 3D", "Unreal Engine rendering", "Zbrush rendering", "cgi", "highly detailed" + }, + "Details" => new[] + { + "100mm", "16-bit", "4k", "500px", "64-bit", "8-bit", "8k", "DSLR", "HDR", "analog photography", + "bokeh", "depth of field", "detailed", "film photography", "hi-fi", "high quality", + "highly detailed", "hyper-realistic", "lo-fi", "polaroid", "studio quality", "uhd", + "ultra realistic" + }, + "Epoch" => new[] + { + "1100s", "Assyrian Empire", "Aztec", "Babylonian Empire", "Benin Kingdom", "Bronze Age", + "Byzantine Empire", "Carolingian", "Dark Ages", "Edwardian", "Elizabethan", "Georgian", + "Gilded Age", "Great Depression", "Heian Period", "Incan", "Industrial Revolution", "Iron Age", + "Maori", "Mayan", "Meiji Period", "Middle Ages", "Ming Dynasty", "Minoan", "Moorish", "Mughal Era", + "Nasrid", "Navajo", "Neolithic", "Olmec", "Ottoman Empire", "Paleolithic", "Persian Empire", + "Primitive society", "Qing Dynasty", "Regency", "Renaissance", "Shang Dynasty", "Songhai", + "Stone Age", "Sumerian", "Tokugawa Shogunate", "Tudor", "Victorian", "Viking", "World War I", + "World War II", "Zhou Dynasty", "Zuni-Pueblo", "ancient Egypt", "ancient Greece", "ancient Rome", + "antique", "antiquity", "aztec", "bronze age", "contemporary", "future", "medieval", "mid-century", + "middle ages", "modern", "modern world", "pre-Columbian", "prehistoric", "renaissance", "retro", + "sci-fi", "space age", "victorian", "viking" + }, + "Weather" => new[] + { + "cloudy", "foggy", "frosty", "humid", "icy", "rainy", "snowy", "stormy", "sunny", "windy" + }, + "Aesthetics" => new[] + { + "Abstract Tech", "Acid Pixie", "Acidwave", "Acubi", "Adventure Pulp", "Adventurecore", "Aetherpunk", + "Afro-Victorian", "Afrofuturism", "After Hours", "Agropeople", "Alien", "Alternative", + "American Pioneers", "American Revolution", "American Thanksgiving", "American Tourist Traps", + "Americana", "Analog Horror", "Ancient Egypt", "Androgynous", "Anemoiacore", "Angelcore", + "Anglo Gothic", "Angura Kei", "Animecore", "Anti-Fashion", "Antique Grunge", "Arcade", "Arcadecore", + "Art Academia", "Art Deco", "Art Hoe", "Art Nouveau", "Arts and Crafts Movement", "Athlete", + "Atompunk", "Auroracore", "Autumn", "Autumn Academia", "Avant Apocalypse", "Avant-garde", + "Back-to-School", "Baddie", "Ballet Academia", "Baltic Violence Tumblr", "Barbiecore", "Bardcore", + "Baroque", "Bastardcore", "Bauhaus", "Beach Day", "Beatnik", "Biker", "Bimbocore", "Biohazard", + "Biopunk", "Bizarro Fiction", "Black-Holed Meme", "Bodikon", "Bohemian", "Bronzepunk", "C-Pop", + "Camp", "Campcore", "Candycore", "Cargopunk", "Carnivalcore", "Cartoon", "Cartooncore", "Casino", + "Cassette Futurism", "Celtic", "Changelingcore", "Chaotic Academia", "Chav", "Cheiron Crush", + "Cholo", "Christmas", "Chunyu", "City Pop", "Classic Academia", "Classic Lolita", "Classicism", + "Cleancore", "Clockpunk", "Cloudcore", "Clowncore", "Club", "Club Kids", "Coastal Grandmother", + "Coffee House/Cafe", "Coffinwood", "Colourful Black", "Comfy/Cozy", "Concore", "Constructivism", + "Coquette", "Coquette Academia", "Corporate", "Corporate Memphis", "Corporate Punk", "Cottagecore", + "Cottagegore", "Country", "Cozy Childhood Hideaway", "Craftcore", "Cripplepunk", "Crowcore", + "Crustpunk", "Cryptid Academia", "Cryptidcore", "Cubism", "Cuddle Party", "Cult Party Kei", + "Cultcore", "Cutecore", "Cyber Fairy Grunge", "Cyberdelic", "Cyberghetto", "Cybergoth", + "Cybergrunge", "CyberneticPunk", "Cyberparadism", "Cyberpop", "Cyberprep", "Cyberpunk", + "Danish Pastel", "Dark Academia", "Dark Fantasy", "Dark Naturalism", "Dark Nautical", + "Dark Nymphet", "Dark Paradise", "DarkErrorcore", "Darkcore", "Darkest Academia", "Daydreampunk", + "Dazecore", "De Stijl", "Deathcore", "Deathrock", "Decopunk", "Decora", "Delicate Sweet", + "Desertwave", "Desi Romantic Academia", "Dethereal", "Devilcore", "Dieselpunk", "Diner", + "Dionysism", "Dolly Kei", "Dracopunk", "Dragoncore", "Drain", "Dreamcore", "Dreamy", "Drugcore", + "Dual Kawaii", "Duckcore", "Dullcore", "Dungeon Synth", "Earthcore", "Electro Swing", + "ElectroPop 08", "Emo", "English Major", "Equestrian", "Erokawa", "Ethereal", "Europunk", + "Expressionism", "Fairy Academia", "Fairy Grunge", "Fairy Kei", "Fairy Tale", "Fairycore", + "Fanfare", "Fantasy", "Fantasy Astronomy", "Farmer's Daughter", "Fashwave", "Fauvism", "Fawncore", + "Femme Fatale", "Feralcore", "Film Noir", "Flapper", "Flat Design", "Folk Punk", "Foodie", + "Forestpunk", "French", "Frogcore", "Frutiger Aero", "Funky Seasons", "Furry", "Futago", "Futurism", + "Gadgetpunk", "Game Night", "Gamercore", "Gamine", "Geek", "Gen X Soft Club", "Ghostcore", + "Glam Rock", "Glitchcore", "Gloomcore", "Glowwave", "Goblin Academia", "Goblincore", + "Golden Age of Detective Fiction", "Golden Hour", "Gopnik", "Gorecore", "Gorpcore", "Goth", + "Gothcore", "Gothic", "Gothic Lolita", "Grandmillenial", "Grandparentcore", "Greaser", + "Green Academia", "Grifes", "Grindhouse", "Groundcore", "Grunge", "Gurokawa", "Gyaru", "Hackercore", + "Halloween", "Hallyu", "Happycore", "Hatecore", "Hauntology", "Haussmann Paris", "Health Goth", + "Heatwave", "Heistcore", "Hellenic", "Hermaphroditus", "Hermitpunk", "Hexatron", "Hi-NRG", + "High School Dream", "Hikecore", "Hime Lolita", "Hip-Hop", "Hipness Purgatory", "Hippie", "Hipster", + "Hispanicore", "Historical Americana", "Holosexual", "Honeycore", "Horror", "Horror Academia", + "Hot Topic", "Hustlewave", "Hydrogen", "Hyperpop", "Icepunk", "Imaginarium", "Impressionism", + "Indicolite", "Indie", "Indie Kid", "Indie Sleaze", "Internet Academia", "Italian Mafia", + "Italian Renaissance", "Italo Disco", "Jamcore", "Japanese High School", "Jersey Shore", "Joyride", + "Juggalo", "Jungle Grunge", "Junglecore", "Karasu Zoku", "Kawaii", "Kawaii Gamer", + "Key West Kitten", "Kid Science", "Kidcore", "Kimoicore", "Kinderwhore", "King Gas", "Kingcore", + "Knightcore", "Kogal", "Kuromicore", "La Sape", "Labcore", "Laborwave", "Lagenlook", "Larme Kei", + "Larme Kei", "Late 2000s Elementary School", "Libertywave", "Light Academia", "Lightcore", + "Lightningwave", "Liminal Space", "Lit Kid", "Lo-Fi", "Long Island", "Lounge", "Lovecore", + "Lunarpunk", "MTV Green Sky", "Macaute", "Mad Scientist", "Magewave", "Magical", "Maidcore", + "Mall Ninja", "Mallgoth", "Maximalism", "McBling", "Meatcore", "Medicalcore", "Medieval", "Memphis", + "Mermaid", "Metal", "Metalcore", "Metalheart", "Metrosexual", "Miami Metro", "Midwest Emo", + "Midwest Gothic", "Military", "Milk", "Miniaturecore", "Minimalism", "Minivan Rock", + "Miscellaneous Academia", "Mizuiro Kaiwai", "Mod", "Modern Brazil", "Modernism", "Mori Kei", + "Morute", "Mosscore", "Mote Kei", "Ms Paint", "Mulchcore", "Mushroomcore", "Musical Academia", + "Mythpunk", "Nanopunk", "Naturecore", "Nautical", "Neko", "Neo-Romanism", "Neo-Tokyo", "Nerd", + "Nerdcore", "New Age", "New England Gothic", "New Money", "New Romantic", "New Wave", "Nihilcore", + "Nintencore", "Normcore", "Northerness", "Nostalgiacore", "Nu-Goth", "Nuclear", "Nymphet", + "Ocean Academia", "Ocean Grunge", "Old Hollywood", "Old Memecore", "Old Money", "Old Web", + "Onii Kei", "Oshare Kei", "Otaku", "Otherkin", "PC Music", "Pachuco", "Pale Grunge", "Paleocore", + "Palewave", "Paramilitary", "Party Animal", "Party Kei", "Pastel", "Pastel Academia", "Pastel Goth", + "Pastel Punk", "Peach", "Pearly", "Peoplehood", "Photorealism", "Pin-up", "Pink Parisian", + "Pink Pilates Princess", "Pink Princess", "Pinterest Coquette", "Pirate", "Pixel Cutie", + "Pixiecore", "Plaguecore", "Plant Mom", "Pop", "Pop Art", "Pop Kei", "Post-Apocalyptic", + "Post-Impressionism", "Post-Punk", "Post-rock", "Powwow Step", "Prairiecore", "Pre-Raphaelite", + "Prehistoricore", "Pride flags", "Princecore", "Princesscore", "Printcore", "Progressive Academia", + "Psychedelica", "Punk", "Purism", "Quality Tumblr", "Queencore", "Queer Academia", "Queercore", + "R&B", "Racaille", "Ragecore", "Rainbowcore", "Rainy Day", "Randumb", "Rangercore", "Ratcore", + "Ravencore", "Raver", "Real Life Super Hero", "Realism", "Reefwave", "Regency", "Regional Gothic", + "Retro-Futurism", "Rivethead", "Roaring 20s", "Robotics Kid", "Rock", "Rockabilly", "Rococo", + "Roguecore", "Rollerwave", "Roma", "Romantic Academia", "Romantic Goth", "Romantic Italian", + "Romanticism", "Rotcore", "Royalcore", "Rusticcore", "Sad people", "Salon Kei", "Salvagepunk", + "Sandalpunk", "Sanriocore", "Scene", "Schizowave", "Science Academia", "Scoutcore", "Scrapbook", + "Scrapper", "Seapunk", "Selkiecore", "Shanzhai", "Sharpies", "Shibuya Punk", "Shironuri", + "Shoegaze", "Shā mǎ tè", "Shamate", "Sigilkore", "Sizz", "Skater", "Sleepycore", "Slimepunk", + "Sloanies", "Snow Bunny", "Snowdrop", "Soft Apocalypse", "Soft Grunge", "Soft Macabre", + "Soft indie", "Softie", "Soggy", "Solarpunk", "Southern Belle", "Southern Gothic", "Space Cowboy", + "Spacecore", "Sparklecore", "Spiritcore", "Tacticool", "Takenokozoku", "Tanbi Kei", + "Technical Scene", "Technocore", "Technozen", "Techwear", "Teddies", "Teenqueen", "Teethcore", + "Terrorwave", "Teslapunk", "Theatre Academia", "Theatre Kids", "Thrasher", "Thriftcore", "Tiki", + "Tinkercore", "Tinycore", "Trad Goth", "Traditional Korean", "Trailer Park Princess", "Trenchcore", + "Trendercore", "Trillwave", "Tropical", "Tumblewave", "Tupinipunk", "Twee", "Tweencore", "Ukiyo-e", + "Unicorncore", "Urban Fantasy", "Urbancore", "Utopian Scholastic", "VSCO", "Vampire", "Vaporwave", + "Vectorbloom", "Vectorheart", "Vibrant Academia", "Victorian", "Victorian Goth", "Viking", + "Villagecore", "Villaincore", "Vintage British Sportsman", "Vintage Parisian", "Virgo's Tears", + "Visual Kei", "Voidcore", "Voidpunk", "Vorticism", "Vulture Culture", "Wabi-Sabi", "Waif", + "Waldorf", "Wanderlust", "Warmcore", "Weathercore", "Web Creep", "Weeaboo", "Weirdcore", "Werewolf", + "Western", "Wetcore", "Wild Child", "Winter", "Winter Fairy Coquette", "Witch House", "Witchcore", + "Witchy Academia", "Wizardcore", "Wonderland", "Woodland Goth", "Wormcore", "Writer Academia", + "Wuxia", "XO", "Y2K", "Yakuza", "Yami Kawaii", "Yandere", "Yankeecore", "Yanki", "Youthquake", + "Yume Kawaii", "Zombie Apocalypse" + }, + "Others" => new[] { " " }, + _ => new[] { " " } + }; + } } } \ No newline at end of file diff --git a/Scenario/Editor/PromptWindow/PromptWindow.cs b/Scenario/Editor/PromptWindow/PromptWindow.cs index 1732f4b..aa89178 100644 --- a/Scenario/Editor/PromptWindow/PromptWindow.cs +++ b/Scenario/Editor/PromptWindow/PromptWindow.cs @@ -1,232 +1,234 @@ -using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; +using System.Globalization; +using System.Linq; using Unity.EditorCoroutines.Editor; using UnityEditor; using UnityEngine; -using System.Globalization; -using System.Linq; +using Newtonsoft.Json; -public class PromptWindow : EditorWindow +namespace Scenario { - internal static List generatedImagesData = new(); + public class PromptWindow : EditorWindow + { + internal static List generatedImagesData = new(); - private PromptWindowUI promptWindowUI; + private PromptWindowUI promptWindowUI; - private string inferenceId = ""; - private EditorCoroutine inferenceStatusCoroutine; - private bool processReceivedUploadImage = false; // for main thread receiving callback - private byte[] pngBytesUploadImage = null; - private string fileName; + private string inferenceId = ""; + private EditorCoroutine inferenceStatusCoroutine; + private bool processReceivedUploadImage = false; // for main thread receiving callback + private byte[] pngBytesUploadImage = null; + private string fileName; - [MenuItem("Window/Scenario/Prompt Window")] - public static void ShowWindow() - { - GetWindow("Prompt Window"); - } + [MenuItem("Window/Scenario/Prompt Window")] + public static void ShowWindow() + { + GetWindow("Prompt Window"); + } - private void OnEnable() - { - promptWindowUI = new PromptWindowUI(this); - UpdateSelectedModel(); - } - - private void OnFocus() - { - if (promptWindowUI != null) + private void OnEnable() { + promptWindowUI = new PromptWindowUI(this); UpdateSelectedModel(); } - } - internal void RemoveBackground(Texture2D texture2D) - { - string dataUrl = CommonUtils.Texture2DToDataURL(texture2D); - fileName = CommonUtils.GetRandomImageFileName(); - string url = $"images/erase-background"; - string param = $"{{\"image\":\"{dataUrl}\",\"name\":\"{fileName}\",\"backgroundColor\":\"\",\"format\":\"png\",\"returnImage\":\"false\"}}"; - - Debug.Log("Requesting background removal, please wait.."); - - ApiClient.RestPut(url,param,response => + private void OnFocus() { - try + if (promptWindowUI != null) { - dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content); - string imageUrl = jsonResponse.asset.url; - CommonUtils.FetchTextureFromURL(imageUrl, texture => - { - byte[] textureBytes = texture.EncodeToPNG(); - Callback_BackgroundRemoved(textureBytes); - }); - } - catch (Exception ex) - { - Debug.LogError("An error occurred while processing the response: " + ex.Message); + UpdateSelectedModel(); } - }); - } + } - private void Callback_BackgroundRemoved(byte[] textureBytes) - { - PromptWindowUI.imageUpload.LoadImage(textureBytes); - } - - private void Update() - { - if (!processReceivedUploadImage) return; - - processReceivedUploadImage = false; - Callback_BackgroundRemoved(pngBytesUploadImage); - } + internal void RemoveBackground(Texture2D texture2D) + { + string dataUrl = CommonUtils.Texture2DToDataURL(texture2D); + fileName = CommonUtils.GetRandomImageFileName(); + string url = $"images/erase-background"; + string param = $"{{\"image\":\"{dataUrl}\",\"name\":\"{fileName}\",\"backgroundColor\":\"\",\"format\":\"png\",\"returnImage\":\"false\"}}"; - private void UpdateSelectedModel() - { - string selectedModelId = EditorPrefs.GetString("SelectedModelId"); - string selectedModelName = EditorPrefs.GetString("SelectedModelName"); + Debug.Log("Requesting background removal, please wait.."); - if (!string.IsNullOrEmpty(selectedModelId) && !string.IsNullOrEmpty(selectedModelName)) - { - promptWindowUI.selectedModelName = selectedModelName; + ApiClient.RestPut(url,param,response => + { + try + { + dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content); + string imageUrl = jsonResponse.asset.url; + CommonUtils.FetchTextureFromURL(imageUrl, texture => + { + byte[] textureBytes = texture.EncodeToPNG(); + Callback_BackgroundRemoved(textureBytes); + }); + } + catch (Exception ex) + { + Debug.LogError("An error occurred while processing the response: " + ex.Message); + } + }); } - else + + private void Callback_BackgroundRemoved(byte[] textureBytes) { - promptWindowUI.selectedModelName = "Choose Model"; + PromptWindowUI.imageUpload.LoadImage(textureBytes); } - } - - private void OnGUI() - { - promptWindowUI.Render(this.position); - } - - public void GenerateImage(string seed) - { - Debug.Log("Generate Image button clicked. Model: " + promptWindowUI.selectedModelName + ", Seed: " + seed); - - string modelId = EditorPrefs.GetString("SelectedModelId"); - - EditorCoroutineUtility.StartCoroutineOwnerless(PostInferenceRequest(modelId)); - } - private IEnumerator PostInferenceRequest(string modelId) - { - Debug.Log("Requesting image generation please wait.."); + private void Update() + { + if (!processReceivedUploadImage) return; - string modality = ""; - string operationType = "txt2img"; - string dataUrl = "\"\""; - string maskDataUrl = "\"\""; + processReceivedUploadImage = false; + Callback_BackgroundRemoved(pngBytesUploadImage); + } - if (promptWindowUI.isImageToImage) + private void UpdateSelectedModel() { - operationType = "img2img"; + string selectedModelId = EditorPrefs.GetString("SelectedModelId"); + string selectedModelName = EditorPrefs.GetString("SelectedModelName"); - if (PromptWindowUI.imageUpload == null) + if (!string.IsNullOrEmpty(selectedModelId) && !string.IsNullOrEmpty(selectedModelName)) { - Debug.LogError("Img2Img Must have a image uploaded."); - yield break; + promptWindowUI.selectedModelName = selectedModelName; } - - dataUrl = CommonUtils.Texture2DToDataURL(PromptWindowUI.imageUpload); - } - else if (promptWindowUI.isControlNet) - { - operationType = "controlnet"; - - if (PromptWindowUI.imageUpload == null) + else { - Debug.LogError("ControlNet Must have a image uploaded."); - yield break; + promptWindowUI.selectedModelName = "Choose Model"; } - - dataUrl = CommonUtils.Texture2DToDataURL(PromptWindowUI.imageUpload); } - if (promptWindowUI.isImageToImage && promptWindowUI.isControlNet) + private void OnGUI() { - operationType = "controlnet"; + promptWindowUI.Render(this.position); } - Dictionary modalitySettings = PrepareModalitySettings(ref modality, ref operationType); + public void GenerateImage(string seed) + { + Debug.Log("Generate Image button clicked. Model: " + promptWindowUI.selectedModelName + ", Seed: " + seed); - modality = PrepareModality(modalitySettings); + string modelId = EditorPrefs.GetString("SelectedModelId"); - if (promptWindowUI.isInpainting) + EditorCoroutineUtility.StartCoroutineOwnerless(PostInferenceRequest(modelId)); + } + + private IEnumerator PostInferenceRequest(string modelId) { - operationType = "inpaint"; + Debug.Log("Requesting image generation please wait.."); + + string modality = ""; + string operationType = "txt2img"; + string dataUrl = "\"\""; + string maskDataUrl = "\"\""; - if (PromptWindowUI.imageUpload == null) + if (promptWindowUI.isImageToImage) { - Debug.LogError("Inpainting Must have an image uploaded."); - yield break; + operationType = "img2img"; + + if (PromptWindowUI.imageUpload == null) + { + Debug.LogError("Img2Img Must have a image uploaded."); + yield break; + } + + dataUrl = CommonUtils.Texture2DToDataURL(PromptWindowUI.imageUpload); } - else + else if (promptWindowUI.isControlNet) { + operationType = "controlnet"; + + if (PromptWindowUI.imageUpload == null) + { + Debug.LogError("ControlNet Must have a image uploaded."); + yield break; + } + dataUrl = CommonUtils.Texture2DToDataURL(PromptWindowUI.imageUpload); } - if (PromptWindowUI.imageMask == null) + if (promptWindowUI.isImageToImage && promptWindowUI.isControlNet) { - Debug.LogError("Inpainting Must have a mask uploaded."); - yield break; + operationType = "controlnet"; } - else + + Dictionary modalitySettings = PrepareModalitySettings(ref modality, ref operationType); + + modality = PrepareModality(modalitySettings); + + if (promptWindowUI.isInpainting) { - maskDataUrl = ProcessMask(); - } - } + operationType = "inpaint"; - string inputData = PrepareInputData(modality, operationType, dataUrl, maskDataUrl); + if (PromptWindowUI.imageUpload == null) + { + Debug.LogError("Inpainting Must have an image uploaded."); + yield break; + } + else + { + dataUrl = CommonUtils.Texture2DToDataURL(PromptWindowUI.imageUpload); + } - Debug.Log("Input Data: " + inputData); + if (PromptWindowUI.imageMask == null) + { + Debug.LogError("Inpainting Must have a mask uploaded."); + yield break; + } + else + { + maskDataUrl = ProcessMask(); + } + } - ApiClient.RestPost($"models/{modelId}/inferences", inputData,response => - { - InferenceRoot inferenceRoot = JsonConvert.DeserializeObject(response.Content); - inferenceId = inferenceRoot.inference.id; - inferenceStatusCoroutine = EditorCoroutineUtility.StartCoroutineOwnerless(GetInferenceStatus()); - }); - } + string inputData = PrepareInputData(modality, operationType, dataUrl, maskDataUrl); - private static string ProcessMask() - { - Texture2D processedMask = Texture2D.Instantiate(PromptWindowUI.imageMask); + Debug.Log("Input Data: " + inputData); - Color[] pixels = processedMask.GetPixels(); + ApiClient.RestPost($"models/{modelId}/inferences", inputData,response => + { + InferenceRoot inferenceRoot = JsonConvert.DeserializeObject(response.Content); + inferenceId = inferenceRoot.inference.id; + inferenceStatusCoroutine = EditorCoroutineUtility.StartCoroutineOwnerless(GetInferenceStatus()); + }); + } - for (int i = 0; i < pixels.Length; i++) + private static string ProcessMask() { - if (pixels[i].a == 0) + Texture2D processedMask = Texture2D.Instantiate(PromptWindowUI.imageMask); + + Color[] pixels = processedMask.GetPixels(); + + for (int i = 0; i < pixels.Length; i++) { - pixels[i] = Color.black; + if (pixels[i].a == 0) + { + pixels[i] = Color.black; + } } - } - processedMask.SetPixels(pixels); - processedMask.Apply(); + processedMask.SetPixels(pixels); + processedMask.Apply(); - return CommonUtils.Texture2DToDataURL(processedMask); - } + return CommonUtils.Texture2DToDataURL(processedMask); + } - private string PrepareInputData(string modality, string operationType, string dataUrl, string maskDataUrl) - { - bool hideResults = false; - string type = operationType; - string image = $"\"{dataUrl}\""; - string mask = $"\"{maskDataUrl}\""; - string prompt = promptWindowUI.promptinputText; - int seed = int.Parse(promptWindowUI.seedinputText); - string negativePrompt = promptWindowUI.negativepromptinputText; - float strength = (float)Math.Round(promptWindowUI.influncesliderValue, 2); - float guidance = promptWindowUI.guidancesliderValue; - int width = (int)promptWindowUI.widthSliderValue; - int height = (int)promptWindowUI.heightSliderValue; - int numInferenceSteps = (int)promptWindowUI.samplesliderValue; - int numSamples = (int)promptWindowUI.imagesliderValue; - - string inputData = $@"{{ + private string PrepareInputData(string modality, string operationType, string dataUrl, string maskDataUrl) + { + bool hideResults = false; + string type = operationType; + string image = $"\"{dataUrl}\""; + string mask = $"\"{maskDataUrl}\""; + string prompt = promptWindowUI.promptinputText; + int seed = int.Parse(promptWindowUI.seedinputText); + string negativePrompt = promptWindowUI.negativepromptinputText; + float strength = (float)Math.Round(promptWindowUI.influncesliderValue, 2); + float guidance = promptWindowUI.guidancesliderValue; + int width = (int)promptWindowUI.widthSliderValue; + int height = (int)promptWindowUI.heightSliderValue; + int numInferenceSteps = (int)promptWindowUI.samplesliderValue; + int numSamples = (int)promptWindowUI.imagesliderValue; + + string inputData = $@"{{ ""parameters"": {{ ""hideResults"": {hideResults.ToString().ToLower()}, ""type"": ""{type}"", @@ -244,208 +246,209 @@ private string PrepareInputData(string modality, string operationType, string da ""numSamples"": {numSamples} }} }}"; - return inputData; - } + return inputData; + } - private string PrepareModality(Dictionary modalitySettings) - { - string modality; - if (promptWindowUI.isControlNet && promptWindowUI.isAdvancedSettings) + private string PrepareModality(Dictionary modalitySettings) { - modality = string.Join(",", modalitySettings.Select(kv => $"{kv.Key}:{float.Parse(kv.Value).ToString(CultureInfo.InvariantCulture)}")); + string modality; + if (promptWindowUI.isControlNet && promptWindowUI.isAdvancedSettings) + { + modality = string.Join(",", modalitySettings.Select(kv => $"{kv.Key}:{float.Parse(kv.Value).ToString(CultureInfo.InvariantCulture)}")); + } + else + { + modality = promptWindowUI.selectedPreset; + } + + return modality; } - else + + private Dictionary PrepareModalitySettings(ref string modality, ref string operationType) { - modality = promptWindowUI.selectedPreset; - } + Dictionary modalitySettings = new(); - return modality; - } + if (promptWindowUI.isAdvancedSettings) + { + PrepareAdvancedModalitySettings(out modality, out operationType, modalitySettings); + } - private Dictionary PrepareModalitySettings(ref string modality, ref string operationType) - { - Dictionary modalitySettings = new(); + return modalitySettings; + } - if (promptWindowUI.isAdvancedSettings) + private void PrepareAdvancedModalitySettings(out string modality, out string operationType, Dictionary modalitySettings) { - PrepareAdvancedModalitySettings(out modality, out operationType, modalitySettings); - } + operationType = "controlnet"; - return modalitySettings; - } + if (promptWindowUI.selectedOption1Index > 0) + { + string option1Name = promptWindowUI.dropdownOptions[promptWindowUI.selectedOption1Index - 1]; + if (!modalitySettings.ContainsKey(option1Name)) + modalitySettings.Add(option1Name, $"{promptWindowUI.sliderValue1:0.00}"); + } - private void PrepareAdvancedModalitySettings(out string modality, out string operationType, Dictionary modalitySettings) - { - operationType = "controlnet"; + if (promptWindowUI.selectedOption2Index > 0) + { + string option2Name = promptWindowUI.dropdownOptions[promptWindowUI.selectedOption2Index - 1]; + if (!modalitySettings.ContainsKey(option2Name)) + modalitySettings.Add(option2Name, $"{promptWindowUI.sliderValue2:0.00}"); + } - if (promptWindowUI.selectedOption1Index > 0) - { - string option1Name = promptWindowUI.dropdownOptions[promptWindowUI.selectedOption1Index - 1]; - if (!modalitySettings.ContainsKey(option1Name)) - modalitySettings.Add(option1Name, $"{promptWindowUI.sliderValue1:0.00}"); - } + if (promptWindowUI.selectedOption3Index > 0) + { + string option3Name = promptWindowUI.dropdownOptions[promptWindowUI.selectedOption3Index - 1]; + if (!modalitySettings.ContainsKey(option3Name)) + modalitySettings.Add(option3Name, $"{promptWindowUI.sliderValue3:0.00}"); + } - if (promptWindowUI.selectedOption2Index > 0) - { - string option2Name = promptWindowUI.dropdownOptions[promptWindowUI.selectedOption2Index - 1]; - if (!modalitySettings.ContainsKey(option2Name)) - modalitySettings.Add(option2Name, $"{promptWindowUI.sliderValue2:0.00}"); + modality = string.Join(",", modalitySettings.Select(kv => $"{kv.Key}:{float.Parse(kv.Value).ToString(CultureInfo.InvariantCulture)}")); } - if (promptWindowUI.selectedOption3Index > 0) + private IEnumerator GetInferenceStatus() { - string option3Name = promptWindowUI.dropdownOptions[promptWindowUI.selectedOption3Index - 1]; - if (!modalitySettings.ContainsKey(option3Name)) - modalitySettings.Add(option3Name, $"{promptWindowUI.sliderValue3:0.00}"); - } + Debug.Log("Requesting status please wait.."); - modality = string.Join(",", modalitySettings.Select(kv => $"{kv.Key}:{float.Parse(kv.Value).ToString(CultureInfo.InvariantCulture)}")); - } + yield return new WaitForSecondsRealtime(1.0f); - private IEnumerator GetInferenceStatus() - { - Debug.Log("Requesting status please wait.."); - - yield return new WaitForSecondsRealtime(1.0f); - - string modelId = UnityEditor.EditorPrefs.GetString("postedModelName"); + string modelId = UnityEditor.EditorPrefs.GetString("postedModelName"); - ApiClient.RestGet($"models/{modelId}/inferences/{inferenceId}",response => - { - InferenceStatusRoot inferenceStatusRoot = JsonConvert.DeserializeObject(response.Content); - - if (inferenceStatusRoot.inference.status != "succeeded" && inferenceStatusRoot.inference.status != "failed" ) - { - Debug.Log("Commission in process, please wait.."); - EditorCoroutineUtility.StopCoroutine(inferenceStatusCoroutine); - inferenceStatusCoroutine = EditorCoroutineUtility.StartCoroutineOwnerless(PeriodicStatusCheck()); - } - else + ApiClient.RestGet($"models/{modelId}/inferences/{inferenceId}",response => { - generatedImagesData.Clear(); - foreach (var item in inferenceStatusRoot.inference.images) + InferenceStatusRoot inferenceStatusRoot = JsonConvert.DeserializeObject(response.Content); + + if (inferenceStatusRoot.inference.status != "succeeded" && inferenceStatusRoot.inference.status != "failed" ) { - /*Debug.Log("Image URL: " + item);*/ - var img = JsonConvert.DeserializeObject(item.ToString()); - generatedImagesData.Add(new ImageDataStorage.ImageData() + Debug.Log("Commission in process, please wait.."); + EditorCoroutineUtility.StopCoroutine(inferenceStatusCoroutine); + inferenceStatusCoroutine = EditorCoroutineUtility.StartCoroutineOwnerless(PeriodicStatusCheck()); + } + else + { + generatedImagesData.Clear(); + foreach (var item in inferenceStatusRoot.inference.images) { - Id = img.Id, - Url = img.Url, - InferenceId = this.inferenceId - }); + /*Debug.Log("Image URL: " + item);*/ + var img = JsonConvert.DeserializeObject(item.ToString()); + generatedImagesData.Add(new ImageDataStorage.ImageData() + { + Id = img.Id, + Url = img.Url, + InferenceId = this.inferenceId + }); + } + EditorCoroutineUtility.StopCoroutine(inferenceStatusCoroutine); + EditorCoroutineUtility.StartCoroutineOwnerless(ShowPromptImagesWindow()); } - EditorCoroutineUtility.StopCoroutine(inferenceStatusCoroutine); - EditorCoroutineUtility.StartCoroutineOwnerless(ShowPromptImagesWindow()); - } - }); - } + }); + } - public class ImageDataAPI - { - public string Id { get; set; } - public string Url { get; set; } - } + public class ImageDataAPI + { + public string Id { get; set; } + public string Url { get; set; } + } - private IEnumerator ShowPromptImagesWindow() - { - yield return null; - PromptImages.ShowWindow(); - } + private IEnumerator ShowPromptImagesWindow() + { + yield return null; + PromptImages.ShowWindow(); + } - private IEnumerator PeriodicStatusCheck() - { - yield return new WaitForSecondsRealtime(4.0f); - EditorCoroutineUtility.StopCoroutine(inferenceStatusCoroutine); - inferenceStatusCoroutine = EditorCoroutineUtility.StartCoroutineOwnerless(GetInferenceStatus()); - } + private IEnumerator PeriodicStatusCheck() + { + yield return new WaitForSecondsRealtime(4.0f); + EditorCoroutineUtility.StopCoroutine(inferenceStatusCoroutine); + inferenceStatusCoroutine = EditorCoroutineUtility.StartCoroutineOwnerless(GetInferenceStatus()); + } - public void SetSeed(string seed) - { - // Set the seed value here - } + public void SetSeed(string seed) + { + // Set the seed value here + } - #region API_DTO + #region API_DTO - [Serializable] - public class InferenceRoot - { - public Inference inference { get; set; } - } + [Serializable] + public class InferenceRoot + { + public Inference inference { get; set; } + } - [Serializable] - public class Inference - { - public string id { get; set; } - public string userId { get; set; } - public string ownerId { get; set; } - public string authorId { get; set; } - public string modelId { get; set; } - public DateTime createdAt { get; set; } - public Parameters parameters { get; set; } - public string status { get; set; } - public List images { get; set; } - public int imagesNumber { get; set; } - public string displayPrompt { get; set; } - } + [Serializable] + public class Inference + { + public string id { get; set; } + public string userId { get; set; } + public string ownerId { get; set; } + public string authorId { get; set; } + public string modelId { get; set; } + public DateTime createdAt { get; set; } + public Parameters parameters { get; set; } + public string status { get; set; } + public List images { get; set; } + public int imagesNumber { get; set; } + public string displayPrompt { get; set; } + } - [Serializable] - public class Parameters - { - public string negativePrompt { get; set; } - public int numSamples { get; set; } - public double guidance { get; set; } - public int numInferenceSteps { get; set; } - public bool enableSafetyCheck { get; set; } - public int seed { get; set; } - public int width { get; set; } - public int height { get; set; } - public string type { get; set; } - public string image { get; set; } - public string prompt { get; set; } - public string mask { get; set; } - } + [Serializable] + public class Parameters + { + public string negativePrompt { get; set; } + public int numSamples { get; set; } + public double guidance { get; set; } + public int numInferenceSteps { get; set; } + public bool enableSafetyCheck { get; set; } + public int seed { get; set; } + public int width { get; set; } + public int height { get; set; } + public string type { get; set; } + public string image { get; set; } + public string prompt { get; set; } + public string mask { get; set; } + } - [Serializable] - public class InferenceStatusRoot - { - public Inference inference { get; set; } - } + [Serializable] + public class InferenceStatusRoot + { + public Inference inference { get; set; } + } - [Serializable] - public class InferenceStatus - { - public string id { get; set; } - public string userId { get; set; } - public string ownerId { get; set; } - public string authorId { get; set; } - public string modelId { get; set; } - public DateTime createdAt { get; set; } - public ParametersStatus parameters { get; set; } - public string status { get; set; } - public List images { get; set; } - } + [Serializable] + public class InferenceStatus + { + public string id { get; set; } + public string userId { get; set; } + public string ownerId { get; set; } + public string authorId { get; set; } + public string modelId { get; set; } + public DateTime createdAt { get; set; } + public ParametersStatus parameters { get; set; } + public string status { get; set; } + public List images { get; set; } + } - [Serializable] - public class ParametersStatus - { - public string image { get; set; } - public double guidance { get; set; } - public int numInferenceSteps { get; set; } - public int numSamples { get; set; } - public int width { get; set; } - public string type { get; set; } - public string prompt { get; set; } - public bool enableSafetyCheck { get; set; } - public int height { get; set; } - public string mask { get; set; } - } + [Serializable] + public class ParametersStatus + { + public string image { get; set; } + public double guidance { get; set; } + public int numInferenceSteps { get; set; } + public int numSamples { get; set; } + public int width { get; set; } + public string type { get; set; } + public string prompt { get; set; } + public bool enableSafetyCheck { get; set; } + public int height { get; set; } + public string mask { get; set; } + } - [Serializable] - public class Image - { - public string id { get; set; } - public string url { get; set; } - } + [Serializable] + public class Image + { + public string id { get; set; } + public string url { get; set; } + } - #endregion + #endregion + } } diff --git a/Scenario/Editor/PromptWindow/PromptWindowUI.cs b/Scenario/Editor/PromptWindow/PromptWindowUI.cs index 1a40009..0669627 100644 --- a/Scenario/Editor/PromptWindow/PromptWindowUI.cs +++ b/Scenario/Editor/PromptWindow/PromptWindowUI.cs @@ -1,409 +1,412 @@ -using UnityEditor; -using UnityEngine; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Text; +using UnityEditor; +using UnityEngine; -public partial class PromptWindowUI +namespace Scenario { - public static Texture2D imageMask; + public partial class PromptWindowUI + { + public static Texture2D imageMask; - internal static Texture2D imageUpload; + internal static Texture2D imageUpload; - public readonly string[] dropdownOptions = - { - "", - "canny", - "pose", - "depth", - "lines", - "seg", - "scribble", - "lineart", - "normal-map", - "shuffle" - }; - public string selectedPreset = ""; - public int selectedOption1Index = 0; - public int selectedOption2Index = 0; - public int selectedOption3Index = 0; - public float sliderValue1 = 0.1f; - public float sliderValue2 = 0.1f; - public float sliderValue3 = 0.1f; + public readonly string[] dropdownOptions = + { + "", + "canny", + "pose", + "depth", + "lines", + "seg", + "scribble", + "lineart", + "normal-map", + "shuffle" + }; + public string selectedPreset = ""; + public int selectedOption1Index = 0; + public int selectedOption2Index = 0; + public int selectedOption3Index = 0; + public float sliderValue1 = 0.1f; + public float sliderValue2 = 0.1f; + public float sliderValue3 = 0.1f; - internal bool isImageToImage = false; - internal bool isControlNet = false; - internal bool isAdvancedSettings = false; - internal int controlNetModeIndex = 0; - internal bool isInpainting = false; - internal string promptinputText = ""; - internal string negativepromptinputText = ""; - internal int widthSliderValue = 512; - internal int heightSliderValue = 512; - internal float imagesliderValue = 4; - internal float samplesliderValue = 30; - internal float influncesliderValue = 0.25f; - internal float guidancesliderValue = 7; - internal string postedModelName = "Choose Model"; - internal string seedinputText = ""; + internal bool isImageToImage = false; + internal bool isControlNet = false; + internal bool isAdvancedSettings = false; + internal int controlNetModeIndex = 0; + internal bool isInpainting = false; + internal string promptinputText = ""; + internal string negativepromptinputText = ""; + internal int widthSliderValue = 512; + internal int heightSliderValue = 512; + internal float imagesliderValue = 4; + internal float samplesliderValue = 30; + internal float influncesliderValue = 0.25f; + internal float guidancesliderValue = 7; + internal string postedModelName = "Choose Model"; + internal string seedinputText = ""; - private int dragFromIndex = -1; - private int negativeDragFromIndex = -1; - private string inputText = ""; - private string negativeInputText = ""; - private bool isTextToImage = true; - private bool showSettings = true; - private bool controlNetFoldout = false; - private Vector2 scrollPosition; - private Vector2 scrollPosition1 = Vector2.zero; - private Vector2 scrollPosition2 = Vector2.zero; - private Vector2 dragStartPos; - private Vector2 negativeDragStartPos; - - private readonly int[] allowedWidthValues = { 512, 576, 640, 688, 704, 768, 912, 1024 }; - private readonly int[] allowedHeightValues = { 512, 576, 640, 688, 704, 768, 912, 1024 }; - - private List tags = new(); - private List tagRects = new(); - private List negativeTags = new(); - private List negativeTagRects = new(); - - private PromptWindow promptWindow; - - public string selectedModelName { get; set; } = "Choose Model"; - - public PromptWindowUI(PromptWindow promptWindow) - { - this.promptWindow = promptWindow; - } + private int dragFromIndex = -1; + private int negativeDragFromIndex = -1; + private string inputText = ""; + private string negativeInputText = ""; + private bool isTextToImage = true; + private bool showSettings = true; + private bool controlNetFoldout = false; + private Vector2 scrollPosition; + private Vector2 scrollPosition1 = Vector2.zero; + private Vector2 scrollPosition2 = Vector2.zero; + private Vector2 dragStartPos; + private Vector2 negativeDragStartPos; + + private readonly int[] allowedWidthValues = { 512, 576, 640, 688, 704, 768, 912, 1024 }; + private readonly int[] allowedHeightValues = { 512, 576, 640, 688, 704, 768, 912, 1024 }; + + private List tags = new(); + private List tagRects = new(); + private List negativeTags = new(); + private List negativeTagRects = new(); + + private PromptWindow promptWindow; + + public string selectedModelName { get; set; } = "Choose Model"; + + public PromptWindowUI(PromptWindow promptWindow) + { + this.promptWindow = promptWindow; + } - private void PromptRecv(string str) - { - //promptinputText = str; - } + private void PromptRecv(string str) + { + //promptinputText = str; + } - private void NegativePromptRecv(string str) - { - //negativeInputText = str; - } + private void NegativePromptRecv(string str) + { + //negativeInputText = str; + } - public void Render(Rect position) - { - DrawBackground(position); + public void Render(Rect position) + { + DrawBackground(position); - tagRects.Clear(); + tagRects.Clear(); - Event e = Event.current; - if (e.type == EventType.MouseDown) - { - GUI.FocusControl(null); - } + Event e = Event.current; + if (e.type == EventType.MouseDown) + { + GUI.FocusControl(null); + } - scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUIStyle.none); + scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUIStyle.none); - CustomStyle.ButtonSecondary(selectedModelName, 30 , Models.ShowWindow); - CustomStyle.Separator(); - RenderPromptSection(); - CustomStyle.Space(); - RenderNegativePromptSection(); - CustomStyle.Separator(); + CustomStyle.ButtonSecondary(selectedModelName, 30 , Models.ShowWindow); + CustomStyle.Separator(); + RenderPromptSection(); + CustomStyle.Space(); + RenderNegativePromptSection(); + CustomStyle.Separator(); - bool shouldAutoGenerateSeed = imagesliderValue > 1; - if (shouldAutoGenerateSeed) { seedinputText = "-1"; } + bool shouldAutoGenerateSeed = imagesliderValue > 1; + if (shouldAutoGenerateSeed) { seedinputText = "-1"; } - CustomStyle.ButtonPrimary("Generate Image", 40, () => - { - promptinputText = SerializeTags(tags); - negativepromptinputText = SerializeTags(negativeTags); + CustomStyle.ButtonPrimary("Generate Image", 40, () => + { + promptinputText = SerializeTags(tags); + negativepromptinputText = SerializeTags(negativeTags); - EditorPrefs.SetString("postedModelName", EditorPrefs.GetString("SelectedModelId")); + EditorPrefs.SetString("postedModelName", EditorPrefs.GetString("SelectedModelId")); - if (shouldAutoGenerateSeed) - { - promptWindow.GenerateImage(null); - } - else - { - string seed = seedinputText; - if (seed == "-1") { seed = null; } - promptWindow.GenerateImage(seed); - } - }); + if (shouldAutoGenerateSeed) + { + promptWindow.GenerateImage(null); + } + else + { + string seed = seedinputText; + if (seed == "-1") { seed = null; } + promptWindow.GenerateImage(seed); + } + }); - CustomStyle.Space(); + CustomStyle.Space(); - RenderImageSettingsSection(shouldAutoGenerateSeed); + RenderImageSettingsSection(shouldAutoGenerateSeed); - GUI.enabled = true; + GUI.enabled = true; - CustomStyle.Space(); + CustomStyle.Space(); - int selectedTab = isTextToImage ? 0 : (isImageToImage ? 1 : 2); - string[] tabLabels = { "Text to Image", "Image to Image", "Inpainting" }; - selectedTab = GUILayout.Toolbar(selectedTab, tabLabels, CustomStyle.GetTertiaryButtonStyle()); + int selectedTab = isTextToImage ? 0 : (isImageToImage ? 1 : 2); + string[] tabLabels = { "Text to Image", "Image to Image", "Inpainting" }; + selectedTab = GUILayout.Toolbar(selectedTab, tabLabels, CustomStyle.GetTertiaryButtonStyle()); - switch (selectedTab) - { - case 0: - isTextToImage = true; - isImageToImage = false; - controlNetFoldout = false; - isControlNet = false; - isAdvancedSettings = false; - isInpainting = false; - break; + switch (selectedTab) + { + case 0: + isTextToImage = true; + isImageToImage = false; + controlNetFoldout = false; + isControlNet = false; + isAdvancedSettings = false; + isInpainting = false; + break; - case 1: - isTextToImage = false; - isImageToImage = true; - isInpainting = false; - break; + case 1: + isTextToImage = false; + isImageToImage = true; + isInpainting = false; + break; - case 2: - isTextToImage = false; - isImageToImage = false; - controlNetFoldout = false; - isControlNet = false; - isAdvancedSettings = false; - isInpainting = true; - break; - } + case 2: + isTextToImage = false; + isImageToImage = false; + controlNetFoldout = false; + isControlNet = false; + isAdvancedSettings = false; + isInpainting = true; + break; + } - if (isImageToImage || isInpainting) - { - CustomStyle.Space(); + if (isImageToImage || isInpainting) + { + CustomStyle.Space(); - Rect dropArea = RenderImageUploadArea(); + Rect dropArea = RenderImageUploadArea(); - if (imageUpload != null) - { - dropArea = DrawUploadedImage(dropArea); - } + if (imageUpload != null) + { + dropArea = DrawUploadedImage(dropArea); + } - if (imageMask != null) - { - GUI.DrawTexture(dropArea, imageMask, ScaleMode.ScaleToFit, true); - } + if (imageMask != null) + { + GUI.DrawTexture(dropArea, imageMask, ScaleMode.ScaleToFit, true); + } - HandleDrag(); + HandleDrag(); - GUILayout.BeginHorizontal(); + GUILayout.BeginHorizontal(); - if (isControlNet || isImageToImage) - { - if (GUILayout.Button("Create Image")) + if (isControlNet || isImageToImage) { - ImageEditor.ShowWindow(imageUpload); + if (GUILayout.Button("Create Image")) + { + ImageEditor.ShowWindow(imageUpload); + } } - } - if (isControlNet) - { - if (GUILayout.Button("Add Control")) + if (isControlNet) { - CompositionEditor.ShowWindow(); + if (GUILayout.Button("Add Control")) + { + CompositionEditor.ShowWindow(); + } } - } - if (isInpainting) - { - if (GUILayout.Button("Add Mask")) + if (isInpainting) { - InpaintingEditor.ShowWindow(imageUpload); + if (GUILayout.Button("Add Mask")) + { + InpaintingEditor.ShowWindow(imageUpload); + } } - } - GUILayout.EndHorizontal(); + GUILayout.EndHorizontal(); - if (isImageToImage) - { - CustomStyle.Space(); + if (isImageToImage) + { + CustomStyle.Space(); - controlNetFoldout = EditorGUILayout.Foldout(controlNetFoldout, "ControlNet Options"); + controlNetFoldout = EditorGUILayout.Foldout(controlNetFoldout, "ControlNet Options"); - RenderControlNetFoldout(); + RenderControlNetFoldout(); + } } - } - GUILayout.EndScrollView(); - } + GUILayout.EndScrollView(); + } - private static void DrawBackground(Rect position) - { - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), CustomStyle.GetBackgroundColor()); - } + private static void DrawBackground(Rect position) + { + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), CustomStyle.GetBackgroundColor()); + } - private static void HandleDrag() - { - Event currentEvent = Event.current; - if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) + private static void HandleDrag() { - if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) + Event currentEvent = Event.current; + if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - - if (currentEvent.type == EventType.DragPerform) + if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) { - DragAndDrop.AcceptDrag(); - string path = DragAndDrop.paths[0]; - imageUpload = new Texture2D(2, 2); - byte[] imageData = File.ReadAllBytes(path); - imageUpload.LoadImage(imageData); + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + + if (currentEvent.type == EventType.DragPerform) + { + DragAndDrop.AcceptDrag(); + string path = DragAndDrop.paths[0]; + imageUpload = new Texture2D(2, 2); + byte[] imageData = File.ReadAllBytes(path); + imageUpload.LoadImage(imageData); + } + + currentEvent.Use(); } - - currentEvent.Use(); } } - } - - private Rect DrawUploadedImage(Rect dropArea) - { - GUI.DrawTexture(dropArea, imageUpload, ScaleMode.ScaleToFit); - Rect dropdownButtonRect = new Rect(dropArea.xMax - 90, dropArea.yMax - 25, 30, 30); - if (imageUpload != null && GUI.Button(dropdownButtonRect, "...")) + private Rect DrawUploadedImage(Rect dropArea) { - GenericMenu toolsMenu = new GenericMenu(); - toolsMenu.AddItem(new GUIContent("Remove bg"), false, () => + GUI.DrawTexture(dropArea, imageUpload, ScaleMode.ScaleToFit); + + Rect dropdownButtonRect = new Rect(dropArea.xMax - 90, dropArea.yMax - 25, 30, 30); + if (imageUpload != null && GUI.Button(dropdownButtonRect, "...")) { - Debug.Log("Remove bg button pressed"); - promptWindow.RemoveBackground(imageUpload); - }); + GenericMenu toolsMenu = new GenericMenu(); + toolsMenu.AddItem(new GUIContent("Remove bg"), false, () => + { + Debug.Log("Remove bg button pressed"); + promptWindow.RemoveBackground(imageUpload); + }); - toolsMenu.AddItem(new GUIContent("Adjust aspect ratio"), false, () => - { - if (imageUpload == null) return; + toolsMenu.AddItem(new GUIContent("Adjust aspect ratio"), false, () => + { + if (imageUpload == null) return; - int currentWidth = imageUpload.width; - int currentHeight = imageUpload.height; + int currentWidth = imageUpload.width; + int currentHeight = imageUpload.height; - int matchingWidth = GetMatchingValue(currentWidth, allowedWidthValues); - int matchingHeight = GetMatchingValue(currentHeight, allowedHeightValues); + int matchingWidth = GetMatchingValue(currentWidth, allowedWidthValues); + int matchingHeight = GetMatchingValue(currentHeight, allowedHeightValues); - widthSliderValue = matchingWidth != -1 ? matchingWidth : currentWidth; - heightSliderValue = matchingHeight != -1 ? matchingHeight : currentHeight; + widthSliderValue = matchingWidth != -1 ? matchingWidth : currentWidth; + heightSliderValue = matchingHeight != -1 ? matchingHeight : currentHeight; - selectedOption1Index = NearestValueIndex(widthSliderValue, allowedWidthValues); - selectedOption2Index = NearestValueIndex(heightSliderValue, allowedHeightValues); - }); + selectedOption1Index = NearestValueIndex(widthSliderValue, allowedWidthValues); + selectedOption2Index = NearestValueIndex(heightSliderValue, allowedHeightValues); + }); - toolsMenu.DropDown(dropdownButtonRect); - } - - Rect clearImageButtonRect = new Rect(dropArea.xMax - 50, dropArea.yMax - 25, 30, 30); - if (imageUpload != null && GUI.Button(clearImageButtonRect, "X")) - { - imageUpload = null; - imageMask = null; - } + toolsMenu.DropDown(dropdownButtonRect); + } - return dropArea; - } + Rect clearImageButtonRect = new Rect(dropArea.xMax - 50, dropArea.yMax - 25, 30, 30); + if (imageUpload != null && GUI.Button(clearImageButtonRect, "X")) + { + imageUpload = null; + imageMask = null; + } - private static Rect RenderImageUploadArea() - { - CustomStyle.Label("Upload Image"); + return dropArea; + } - Rect dropArea = GUILayoutUtility.GetRect(0f, 150f, GUILayout.ExpandWidth(true)); - if (imageUpload == null) + private static Rect RenderImageUploadArea() { - GUI.Box(dropArea, "Drag & Drop an image here"); + CustomStyle.Label("Upload Image"); - Rect buttonRect = new Rect(dropArea.center.x - 50f, dropArea.center.y - 15f, 100f, 30f); - if (GUI.Button(buttonRect, "Choose Image")) + Rect dropArea = GUILayoutUtility.GetRect(0f, 150f, GUILayout.ExpandWidth(true)); + if (imageUpload == null) { - string imagePath = EditorUtility.OpenFilePanel("Choose Image", "", "png,jpg,jpeg"); - if (!string.IsNullOrEmpty(imagePath)) + GUI.Box(dropArea, "Drag & Drop an image here"); + + Rect buttonRect = new Rect(dropArea.center.x - 50f, dropArea.center.y - 15f, 100f, 30f); + if (GUI.Button(buttonRect, "Choose Image")) { - imageUpload = new Texture2D(2, 2); - byte[] imageData = File.ReadAllBytes(imagePath); - imageUpload.LoadImage(imageData); + string imagePath = EditorUtility.OpenFilePanel("Choose Image", "", "png,jpg,jpeg"); + if (!string.IsNullOrEmpty(imagePath)) + { + imageUpload = new Texture2D(2, 2); + byte[] imageData = File.ReadAllBytes(imagePath); + imageUpload.LoadImage(imageData); + } } } - } - return dropArea; - } + return dropArea; + } - private string SerializeTags(List tags) - { - if (tags == null || tags.Count == 0) - return ""; - - StringBuilder serializedTags = new StringBuilder(tags[0]); - for (int i = 1; i < tags.Count; i++) + private string SerializeTags(List tags) { - serializedTags.Append(", "); - serializedTags.Append(tags[i]); + if (tags == null || tags.Count == 0) + return ""; + + StringBuilder serializedTags = new StringBuilder(tags[0]); + for (int i = 1; i < tags.Count; i++) + { + serializedTags.Append(", "); + serializedTags.Append(tags[i]); + } + return serializedTags.ToString(); } - return serializedTags.ToString(); - } - private string TruncateTag(string tag) - { - if (tag.Length <= 30) + private string TruncateTag(string tag) { - return tag; - } + if (tag.Length <= 30) + { + return tag; + } - int lastSpaceIndex = tag.LastIndexOf(' ', 30); - return lastSpaceIndex == -1 ? tag[..30] : tag[..lastSpaceIndex]; - } - - private int NearestValueIndex(int currentValue, int[] allowedValues) - { - int nearestIndex = 0; - int minDifference = int.MaxValue; + int lastSpaceIndex = tag.LastIndexOf(' ', 30); + return lastSpaceIndex == -1 ? tag[..30] : tag[..lastSpaceIndex]; + } - for (int i = 0; i < allowedValues.Length; i++) + private int NearestValueIndex(int currentValue, int[] allowedValues) { - int difference = Mathf.Abs(currentValue - allowedValues[i]); - if (difference < minDifference) + int nearestIndex = 0; + int minDifference = int.MaxValue; + + for (int i = 0; i < allowedValues.Length; i++) { - minDifference = difference; - nearestIndex = i; + int difference = Mathf.Abs(currentValue - allowedValues[i]); + if (difference < minDifference) + { + minDifference = difference; + nearestIndex = i; + } } - } - return nearestIndex; - } + return nearestIndex; + } - private int GetNewIndex(Vector2 currentPos) - { - for (int i = 0; i < tagRects.Count; i++) + private int GetNewIndex(Vector2 currentPos) { - if (tagRects[i].Contains(currentPos)) + for (int i = 0; i < tagRects.Count; i++) { - return i; + if (tagRects[i].Contains(currentPos)) + { + return i; + } } - } - return -1; - } + return -1; + } - private Texture2D MakeTex(int width, int height, Color color) - { - Color[] pix = new Color[width * height]; - for (int i = 0; i < pix.Length; i++) + private Texture2D MakeTex(int width, int height, Color color) { - pix[i] = color; + Color[] pix = new Color[width * height]; + for (int i = 0; i < pix.Length; i++) + { + pix[i] = color; + } + Texture2D result = new Texture2D(width, height); + result.SetPixels(pix); + result.Apply(); + return result; } - Texture2D result = new Texture2D(width, height); - result.SetPixels(pix); - result.Apply(); - return result; - } - private int GetMatchingValue(int targetValue, int[] values) - { - foreach (int value in values) + private int GetMatchingValue(int targetValue, int[] values) { - if (value == targetValue) + foreach (int value in values) { - return value; + if (value == targetValue) + { + return value; + } } - } - return -1; + return -1; + } } } \ No newline at end of file diff --git a/Scenario/Editor/PromptWindow/Views/ControlNetView.cs b/Scenario/Editor/PromptWindow/Views/ControlNetView.cs index 94ac9f9..84b7628 100644 --- a/Scenario/Editor/PromptWindow/Views/ControlNetView.cs +++ b/Scenario/Editor/PromptWindow/Views/ControlNetView.cs @@ -1,90 +1,92 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Globalization; using UnityEditor; using UnityEngine; -public partial class PromptWindowUI +namespace Scenario { - private void RenderControlNetFoldout() + public partial class PromptWindowUI { - if (!controlNetFoldout) return; - - GUILayout.BeginHorizontal(); - GUILayout.Label("Enable ControlNet", EditorStyles.label); - isControlNet = GUILayout.Toggle(isControlNet, ""); - - if (isControlNet) + private void RenderControlNetFoldout() { - GUILayout.Label("Advanced Settings", EditorStyles.label); - isAdvancedSettings = GUILayout.Toggle(isAdvancedSettings, ""); - } - - GUILayout.EndHorizontal(); - - if (!isControlNet) return; + if (!controlNetFoldout) return; - CustomStyle.Space(20); - - if (isAdvancedSettings) - { GUILayout.BeginHorizontal(); - GUILayout.Label("Model 1", EditorStyles.label); + GUILayout.Label("Enable ControlNet", EditorStyles.label); + isControlNet = GUILayout.Toggle(isControlNet, ""); - List availableOptions1 = new List { "None" }; - availableOptions1.AddRange(dropdownOptions); - selectedOption1Index = EditorGUILayout.Popup(selectedOption1Index, availableOptions1.ToArray()); + if (isControlNet) + { + GUILayout.Label("Advanced Settings", EditorStyles.label); + isAdvancedSettings = GUILayout.Toggle(isAdvancedSettings, ""); + } - GUILayout.Label("Slider 1", EditorStyles.label); - sliderValue1 = Mathf.Round(EditorGUILayout.Slider(Mathf.Clamp(sliderValue1, 0.1f, 1.0f), 0.1f, 1.0f) * 100) / 100; GUILayout.EndHorizontal(); - if (selectedOption1Index > 0) + if (!isControlNet) return; + + CustomStyle.Space(20); + + if (isAdvancedSettings) { GUILayout.BeginHorizontal(); - GUILayout.Label("Model 2", EditorStyles.label); + GUILayout.Label("Model 1", EditorStyles.label); - List availableOptions2 = new List { "None" }; - availableOptions2.AddRange(dropdownOptions); - availableOptions2.RemoveAt(selectedOption1Index); - selectedOption2Index = EditorGUILayout.Popup(selectedOption2Index, availableOptions2.ToArray()); + List availableOptions1 = new List { "None" }; + availableOptions1.AddRange(dropdownOptions); + selectedOption1Index = EditorGUILayout.Popup(selectedOption1Index, availableOptions1.ToArray()); - GUILayout.Label("Slider 2", EditorStyles.label); - sliderValue2 = Mathf.Round(EditorGUILayout.Slider(Mathf.Clamp(sliderValue2, 0.1f, 1.0f), 0.1f, 1.0f) * 100) / 100; + GUILayout.Label("Slider 1", EditorStyles.label); + sliderValue1 = Mathf.Round(EditorGUILayout.Slider(Mathf.Clamp(sliderValue1, 0.1f, 1.0f), 0.1f, 1.0f) * 100) / 100; GUILayout.EndHorizontal(); - } - if (selectedOption2Index > 0) - { - GUILayout.BeginHorizontal(); - GUILayout.Label("Model 3", EditorStyles.label); + if (selectedOption1Index > 0) + { + GUILayout.BeginHorizontal(); + GUILayout.Label("Model 2", EditorStyles.label); - List availableOptions3 = new List { "None" }; - availableOptions3.AddRange(dropdownOptions); - int option1Index = Array.IndexOf(dropdownOptions, availableOptions1[selectedOption1Index]); - int option2Index = Array.IndexOf(dropdownOptions, dropdownOptions[selectedOption2Index]); + List availableOptions2 = new List { "None" }; + availableOptions2.AddRange(dropdownOptions); + availableOptions2.RemoveAt(selectedOption1Index); + selectedOption2Index = EditorGUILayout.Popup(selectedOption2Index, availableOptions2.ToArray()); - availableOptions3.RemoveAt(option1Index + 1); - availableOptions3.RemoveAt(option2Index); + GUILayout.Label("Slider 2", EditorStyles.label); + sliderValue2 = Mathf.Round(EditorGUILayout.Slider(Mathf.Clamp(sliderValue2, 0.1f, 1.0f), 0.1f, 1.0f) * 100) / 100; + GUILayout.EndHorizontal(); + } - selectedOption3Index = EditorGUILayout.Popup(selectedOption3Index, availableOptions3.ToArray()); + if (selectedOption2Index > 0) + { + GUILayout.BeginHorizontal(); + GUILayout.Label("Model 3", EditorStyles.label); - GUILayout.Label("Slider 3", EditorStyles.label); - sliderValue3 = Mathf.Round(EditorGUILayout.Slider(Mathf.Clamp(sliderValue3, 0.1f, 1.0f), 0.1f, 1.0f) * 100) / 100; - GUILayout.EndHorizontal(); - } - } - else - { - GUILayout.Label("Presets:", EditorStyles.boldLabel); - string[] presets = { "Character", "Landscape", "City", "Interior" }; + List availableOptions3 = new List { "None" }; + availableOptions3.AddRange(dropdownOptions); + int option1Index = Array.IndexOf(dropdownOptions, availableOptions1[selectedOption1Index]); + int option2Index = Array.IndexOf(dropdownOptions, dropdownOptions[selectedOption2Index]); + + availableOptions3.RemoveAt(option1Index + 1); + availableOptions3.RemoveAt(option2Index); - int selectedIndex = Array.IndexOf(presets, CultureInfo.CurrentCulture.TextInfo.ToTitleCase(selectedPreset)); - selectedIndex = GUILayout.SelectionGrid(selectedIndex, presets, presets.Length); - if (selectedIndex >= 0 && selectedIndex < presets.Length) + selectedOption3Index = EditorGUILayout.Popup(selectedOption3Index, availableOptions3.ToArray()); + + GUILayout.Label("Slider 3", EditorStyles.label); + sliderValue3 = Mathf.Round(EditorGUILayout.Slider(Mathf.Clamp(sliderValue3, 0.1f, 1.0f), 0.1f, 1.0f) * 100) / 100; + GUILayout.EndHorizontal(); + } + } + else { - selectedPreset = presets[selectedIndex].ToLower(); + GUILayout.Label("Presets:", EditorStyles.boldLabel); + string[] presets = { "Character", "Landscape", "City", "Interior" }; + + int selectedIndex = Array.IndexOf(presets, CultureInfo.CurrentCulture.TextInfo.ToTitleCase(selectedPreset)); + selectedIndex = GUILayout.SelectionGrid(selectedIndex, presets, presets.Length); + if (selectedIndex >= 0 && selectedIndex < presets.Length) + { + selectedPreset = presets[selectedIndex].ToLower(); + } } } } diff --git a/Scenario/Editor/PromptWindow/Views/ImageSettingsView.cs b/Scenario/Editor/PromptWindow/Views/ImageSettingsView.cs index c88af0e..71b5ca1 100644 --- a/Scenario/Editor/PromptWindow/Views/ImageSettingsView.cs +++ b/Scenario/Editor/PromptWindow/Views/ImageSettingsView.cs @@ -1,98 +1,99 @@ using System; -using System.Collections; -using System.Collections.Generic; using UnityEditor; using UnityEngine; -public partial class PromptWindowUI +namespace Scenario { - private void RenderImageSettingsSection(bool shouldAutoGenerateSeed) + public partial class PromptWindowUI { - showSettings = EditorGUILayout.BeginFoldoutHeaderGroup(showSettings, "Image Settings"); + private void RenderImageSettingsSection(bool shouldAutoGenerateSeed) + { + showSettings = EditorGUILayout.BeginFoldoutHeaderGroup(showSettings, "Image Settings"); - if (!showSettings) return; + if (!showSettings) return; - EditorGUILayout.BeginHorizontal(); - { - CustomStyle.Label("Width: ", width: 45, height: 20); - int widthIndex = NearestValueIndex(widthSliderValue, allowedWidthValues); - widthIndex = GUILayout.SelectionGrid(widthIndex, Array.ConvertAll(allowedWidthValues, x => x.ToString()), - allowedWidthValues.Length, CustomStyle.GetNormalButtonStyle()); - widthSliderValue = allowedWidthValues[widthIndex]; - } - EditorGUILayout.EndHorizontal(); + EditorGUILayout.BeginHorizontal(); + { + CustomStyle.Label("Width: ", width: 45, height: 20); + int widthIndex = NearestValueIndex(widthSliderValue, allowedWidthValues); + widthIndex = GUILayout.SelectionGrid(widthIndex, Array.ConvertAll(allowedWidthValues, x => x.ToString()), + allowedWidthValues.Length, CustomStyle.GetNormalButtonStyle()); + widthSliderValue = allowedWidthValues[widthIndex]; + } + EditorGUILayout.EndHorizontal(); - EditorGUILayout.BeginHorizontal(); - { - CustomStyle.Label("Height: ", width: 45, height: 20); - int heightIndex = NearestValueIndex(heightSliderValue, allowedHeightValues); - heightIndex = GUILayout.SelectionGrid(heightIndex, Array.ConvertAll(allowedHeightValues, x => x.ToString()), - allowedHeightValues.Length, CustomStyle.GetNormalButtonStyle()); - heightSliderValue = allowedHeightValues[heightIndex]; - } - EditorGUILayout.EndHorizontal(); + EditorGUILayout.BeginHorizontal(); + { + CustomStyle.Label("Height: ", width: 45, height: 20); + int heightIndex = NearestValueIndex(heightSliderValue, allowedHeightValues); + heightIndex = GUILayout.SelectionGrid(heightIndex, Array.ConvertAll(allowedHeightValues, x => x.ToString()), + allowedHeightValues.Length, CustomStyle.GetNormalButtonStyle()); + heightSliderValue = allowedHeightValues[heightIndex]; + } + EditorGUILayout.EndHorizontal(); - CustomStyle.Space(); + CustomStyle.Space(); - float labelWidthPercentage = 0.2f; - float sliderWidthPercentage = 0.78f; + float labelWidthPercentage = 0.2f; + float sliderWidthPercentage = 0.78f; - int labelWidth = Mathf.RoundToInt(EditorGUIUtility.currentViewWidth * labelWidthPercentage); - int sliderWidth = Mathf.RoundToInt(EditorGUIUtility.currentViewWidth * sliderWidthPercentage); + int labelWidth = Mathf.RoundToInt(EditorGUIUtility.currentViewWidth * labelWidthPercentage); + int sliderWidth = Mathf.RoundToInt(EditorGUIUtility.currentViewWidth * sliderWidthPercentage); - int imagesliderIntValue = Mathf.RoundToInt(imagesliderValue); - EditorGUILayout.BeginHorizontal(); - { - GUILayout.Label("Images: " + imagesliderIntValue, GUILayout.Width(labelWidth)); - imagesliderValue = GUILayout.HorizontalSlider(imagesliderValue, 1, 16, GUILayout.Width(sliderWidth)); - } - EditorGUILayout.EndHorizontal(); - - int samplesliderIntValue = Mathf.RoundToInt(samplesliderValue); - EditorGUILayout.BeginHorizontal(); - { - GUILayout.Label("Sampling steps: " + samplesliderIntValue, GUILayout.Width(labelWidth)); - samplesliderValue = GUILayout.HorizontalSlider(samplesliderValue, 10, 150, GUILayout.Width(sliderWidth)); - } - EditorGUILayout.EndHorizontal(); + int imagesliderIntValue = Mathf.RoundToInt(imagesliderValue); + EditorGUILayout.BeginHorizontal(); + { + GUILayout.Label("Images: " + imagesliderIntValue, GUILayout.Width(labelWidth)); + imagesliderValue = GUILayout.HorizontalSlider(imagesliderValue, 1, 16, GUILayout.Width(sliderWidth)); + } + EditorGUILayout.EndHorizontal(); - EditorGUILayout.BeginHorizontal(); - { - GUILayout.Label("Guidance: " + guidancesliderValue.ToString("0.0"), GUILayout.Width(labelWidth)); - guidancesliderValue = - Mathf.Round(GUILayout.HorizontalSlider(guidancesliderValue, 0f, 20f, GUILayout.Width(sliderWidth)) * - 10) / 10f; - } - EditorGUILayout.EndHorizontal(); + int samplesliderIntValue = Mathf.RoundToInt(samplesliderValue); + EditorGUILayout.BeginHorizontal(); + { + GUILayout.Label("Sampling steps: " + samplesliderIntValue, GUILayout.Width(labelWidth)); + samplesliderValue = GUILayout.HorizontalSlider(samplesliderValue, 10, 150, GUILayout.Width(sliderWidth)); + } + EditorGUILayout.EndHorizontal(); - if (isImageToImage || isControlNet) - { EditorGUILayout.BeginHorizontal(); { - GUILayout.Label("Influence: " + influncesliderValue.ToString("0.00"), GUILayout.Width(labelWidth)); - influncesliderValue = - GUILayout.HorizontalSlider(influncesliderValue, 0f, 1f, GUILayout.Width(sliderWidth)); + GUILayout.Label("Guidance: " + guidancesliderValue.ToString("0.0"), GUILayout.Width(labelWidth)); + guidancesliderValue = + Mathf.Round(GUILayout.HorizontalSlider(guidancesliderValue, 0f, 20f, GUILayout.Width(sliderWidth)) * + 10) / 10f; } EditorGUILayout.EndHorizontal(); - } - EditorGUILayout.BeginHorizontal(); - { - GUILayout.Label("Seed", GUILayout.Width(labelWidth)); - if (shouldAutoGenerateSeed) + if (isImageToImage || isControlNet) { - GUI.enabled = false; - GUILayout.TextArea("-1", GUILayout.Height(20), GUILayout.Width(sliderWidth)); + EditorGUILayout.BeginHorizontal(); + { + GUILayout.Label("Influence: " + influncesliderValue.ToString("0.00"), GUILayout.Width(labelWidth)); + influncesliderValue = + GUILayout.HorizontalSlider(influncesliderValue, 0f, 1f, GUILayout.Width(sliderWidth)); + } + EditorGUILayout.EndHorizontal(); } - else + + EditorGUILayout.BeginHorizontal(); { - GUI.enabled = true; - seedinputText = GUILayout.TextField(seedinputText, GUILayout.Height(20), GUILayout.Width(sliderWidth)); - promptWindow.SetSeed(seedinputText == "-1" ? null : seedinputText); + GUILayout.Label("Seed", GUILayout.Width(labelWidth)); + if (shouldAutoGenerateSeed) + { + GUI.enabled = false; + GUILayout.TextArea("-1", GUILayout.Height(20), GUILayout.Width(sliderWidth)); + } + else + { + GUI.enabled = true; + seedinputText = GUILayout.TextField(seedinputText, GUILayout.Height(20), GUILayout.Width(sliderWidth)); + promptWindow.SetSeed(seedinputText == "-1" ? null : seedinputText); + } } - } - EditorGUILayout.EndHorizontal(); + EditorGUILayout.EndHorizontal(); - EditorGUILayout.EndFoldoutHeaderGroup(); + EditorGUILayout.EndFoldoutHeaderGroup(); + } } } \ No newline at end of file diff --git a/Scenario/Editor/PromptWindow/Views/NegativePromptView.cs b/Scenario/Editor/PromptWindow/Views/NegativePromptView.cs index 702bc3a..5284773 100644 --- a/Scenario/Editor/PromptWindow/Views/NegativePromptView.cs +++ b/Scenario/Editor/PromptWindow/Views/NegativePromptView.cs @@ -1,155 +1,156 @@ -using System.Collections; -using System.Collections.Generic; using UnityEditor; using UnityEngine; -public partial class PromptWindowUI +namespace Scenario { - private void RenderNegativePromptSection() + public partial class PromptWindowUI { - GUILayout.BeginHorizontal(); + private void RenderNegativePromptSection() { - CustomStyle.Label("- Prompt", width: 64, alignment: TextAnchor.MiddleCenter); - HandleNegativeInputField(); - GUIContent plusNegativePrompt = new GUIContent(EditorGUIUtility.IconContent("d_Toolbar Plus").image); - if (GUILayout.Button(plusNegativePrompt, GUILayout.Width(25), GUILayout.Height(25))) + GUILayout.BeginHorizontal(); { - PromptBuilderWindow.isFromNegativePrompt = true; - PromptBuilderWindow.ShowWindow(NegativePromptRecv, negativeTags); + CustomStyle.Label("- Prompt", width: 64, alignment: TextAnchor.MiddleCenter); + HandleNegativeInputField(); + GUIContent plusNegativePrompt = new GUIContent(EditorGUIUtility.IconContent("d_Toolbar Plus").image); + if (GUILayout.Button(plusNegativePrompt, GUILayout.Width(25), GUILayout.Height(25))) + { + PromptBuilderWindow.isFromNegativePrompt = true; + PromptBuilderWindow.ShowWindow(NegativePromptRecv, negativeTags); + } } - } - GUILayout.EndHorizontal(); + GUILayout.EndHorizontal(); - EditorGUILayout.BeginVertical(GUI.skin.box, GUILayout.Height(50)); - { - EditorGUILayout.BeginVertical(EditorStyles.helpBox); + EditorGUILayout.BeginVertical(GUI.skin.box, GUILayout.Height(50)); { - GUIStyle customTagStyle = new GUIStyle(EditorStyles.label) + EditorGUILayout.BeginVertical(EditorStyles.helpBox); { - fixedHeight = 25, - margin = new RectOffset(0, 5, 0, 5) - }; + GUIStyle customTagStyle = new GUIStyle(EditorStyles.label) + { + fixedHeight = 25, + margin = new RectOffset(0, 5, 0, 5) + }; - float availableWidth = EditorGUIUtility.currentViewWidth - 20; - int tagsPerRow = Mathf.FloorToInt(availableWidth / 100); - int currentTagIndex = 0; + float availableWidth = EditorGUIUtility.currentViewWidth - 20; + int tagsPerRow = Mathf.FloorToInt(availableWidth / 100); + int currentTagIndex = 0; - while (currentTagIndex < negativeTags.Count) - { - EditorGUILayout.BeginHorizontal(); - - for (int i = 0; i < tagsPerRow && currentTagIndex < negativeTags.Count; i++) + while (currentTagIndex < negativeTags.Count) { - string tag = negativeTags[currentTagIndex]; - string displayTag = TruncateTag(tag); + EditorGUILayout.BeginHorizontal(); - GUIContent tagContent = new GUIContent(displayTag, tag); - Rect tagRect = GUILayoutUtility.GetRect(tagContent, customTagStyle); + for (int i = 0; i < tagsPerRow && currentTagIndex < negativeTags.Count; i++) + { + string tag = negativeTags[currentTagIndex]; + string displayTag = TruncateTag(tag); - bool isActiveTag = currentTagIndex == negativeDragFromIndex; - GUIStyle tagStyle = isActiveTag - ? new GUIStyle(customTagStyle) - { - normal = + GUIContent tagContent = new GUIContent(displayTag, tag); + Rect tagRect = GUILayoutUtility.GetRect(tagContent, customTagStyle); + + bool isActiveTag = currentTagIndex == negativeDragFromIndex; + GUIStyle tagStyle = isActiveTag + ? new GUIStyle(customTagStyle) { - background = MakeTex(2, 2, - isActiveTag ? new Color(0.5f, 0.5f, 0.5f) : new Color(0.8f, 0.8f, 0.8f)) + normal = + { + background = MakeTex(2, 2, + isActiveTag ? new Color(0.5f, 0.5f, 0.5f) : new Color(0.8f, 0.8f, 0.8f)) + } } - } - : customTagStyle; + : customTagStyle; - Rect xRect = new Rect(tagRect.xMax - 20, tagRect.y, 20, tagRect.height); + Rect xRect = new Rect(tagRect.xMax - 20, tagRect.y, 20, tagRect.height); - if (Event.current.type == EventType.MouseDown) - { - if (Event.current.button == 0 && Event.current.clickCount == 2 && - tagRect.Contains(Event.current.mousePosition)) + if (Event.current.type == EventType.MouseDown) { - int plusCount = tag.Split('+').Length - 1; - if (plusCount < 3) + if (Event.current.button == 0 && Event.current.clickCount == 2 && + tagRect.Contains(Event.current.mousePosition)) + { + int plusCount = tag.Split('+').Length - 1; + if (plusCount < 3) + { + negativeTags[currentTagIndex] += "+"; + } + } + else if (Event.current.button == 1 && tagRect.Contains(Event.current.mousePosition)) { - negativeTags[currentTagIndex] += "+"; + if (tag.EndsWith("+")) + { + negativeTags[currentTagIndex] = tag.Remove(tag.LastIndexOf('+')); + } } } - else if (Event.current.button == 1 && tagRect.Contains(Event.current.mousePosition)) + + if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && + tagRect.Contains(Event.current.mousePosition)) { - if (tag.EndsWith("+")) + if (!xRect.Contains(Event.current.mousePosition)) { - negativeTags[currentTagIndex] = tag.Remove(tag.LastIndexOf('+')); + negativeDragFromIndex = currentTagIndex; + dragStartPos = Event.current.mousePosition; + Event.current.Use(); } } - } - if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && - tagRect.Contains(Event.current.mousePosition)) - { - if (!xRect.Contains(Event.current.mousePosition)) + if (negativeDragFromIndex >= 0 && Event.current.type == EventType.MouseDrag) { - negativeDragFromIndex = currentTagIndex; - dragStartPos = Event.current.mousePosition; - Event.current.Use(); + int newIndex = GetNewIndex(Event.current.mousePosition); + if (newIndex != -1 && newIndex != negativeDragFromIndex && newIndex < negativeTags.Count) + { + string tempTag = negativeTags[negativeDragFromIndex]; + negativeTags.RemoveAt(negativeDragFromIndex); + negativeTags.Insert(newIndex, tempTag); + negativeDragFromIndex = newIndex; + } } - } - if (negativeDragFromIndex >= 0 && Event.current.type == EventType.MouseDrag) - { - int newIndex = GetNewIndex(Event.current.mousePosition); - if (newIndex != -1 && newIndex != negativeDragFromIndex && newIndex < negativeTags.Count) + if (Event.current.type == EventType.MouseUp) { - string tempTag = negativeTags[negativeDragFromIndex]; - negativeTags.RemoveAt(negativeDragFromIndex); - negativeTags.Insert(newIndex, tempTag); - negativeDragFromIndex = newIndex; + negativeDragFromIndex = -1; } - } - if (Event.current.type == EventType.MouseUp) - { - negativeDragFromIndex = -1; - } + EditorGUI.LabelField(tagRect, tagContent, tagStyle); - EditorGUI.LabelField(tagRect, tagContent, tagStyle); + if (GUI.Button(xRect, "x")) + { + negativeTags.RemoveAt(currentTagIndex); + } + else + { + currentTagIndex++; + } - if (GUI.Button(xRect, "x")) - { - negativeTags.RemoveAt(currentTagIndex); - } - else - { - currentTagIndex++; + negativeTagRects.Add(tagRect); } - negativeTagRects.Add(tagRect); + EditorGUILayout.EndHorizontal(); } - - EditorGUILayout.EndHorizontal(); } + EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); - } - - private void HandleNegativeInputField() - { - GUI.SetNextControlName("negativeInputTextField"); - negativeInputText = - EditorGUILayout.TextField(negativeInputText, GUILayout.ExpandWidth(true), GUILayout.Height(25), GUILayout.MinWidth(400)); - if (Event.current.isKey && Event.current.keyCode == KeyCode.Return && - GUI.GetNameOfFocusedControl() == "negativeInputTextField") + private void HandleNegativeInputField() { - if (!string.IsNullOrWhiteSpace(negativeInputText)) - { - string descriptorName = negativeInputText.Trim(); - negativeTags.Add(descriptorName); - negativeInputText = ""; - Event.current.Use(); - } - else + GUI.SetNextControlName("negativeInputTextField"); + negativeInputText = + EditorGUILayout.TextField(negativeInputText, GUILayout.ExpandWidth(true), GUILayout.Height(25), GUILayout.MinWidth(400)); + + if (Event.current.isKey && Event.current.keyCode == KeyCode.Return && + GUI.GetNameOfFocusedControl() == "negativeInputTextField") { - EditorGUI.FocusTextInControl("negativeInputTextField"); - Event.current.Use(); + if (!string.IsNullOrWhiteSpace(negativeInputText)) + { + string descriptorName = negativeInputText.Trim(); + negativeTags.Add(descriptorName); + negativeInputText = ""; + Event.current.Use(); + } + else + { + EditorGUI.FocusTextInControl("negativeInputTextField"); + Event.current.Use(); + } } } } diff --git a/Scenario/Editor/PromptWindow/Views/PromptView.cs b/Scenario/Editor/PromptWindow/Views/PromptView.cs index 7a276e8..cb76f9e 100644 --- a/Scenario/Editor/PromptWindow/Views/PromptView.cs +++ b/Scenario/Editor/PromptWindow/Views/PromptView.cs @@ -1,144 +1,145 @@ -using System.Collections; -using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; -public partial class PromptWindowUI +namespace Scenario { - private void RenderPromptSection() + public partial class PromptWindowUI { - GUILayout.BeginHorizontal(); + private void RenderPromptSection() { - CustomStyle.Label("Prompt", width: 64, alignment: TextAnchor.MiddleCenter); - HandlePositiveInputField(); - GUIContent plusPrompt = new GUIContent(EditorGUIUtility.IconContent("d_Toolbar Plus").image); - if (GUILayout.Button(plusPrompt, GUILayout.Width(25), GUILayout.Height(25))) + GUILayout.BeginHorizontal(); { - PromptBuilderWindow.isFromNegativePrompt = false; - PromptBuilderWindow.ShowWindow(PromptRecv, tags); + CustomStyle.Label("Prompt", width: 64, alignment: TextAnchor.MiddleCenter); + HandlePositiveInputField(); + GUIContent plusPrompt = new GUIContent(EditorGUIUtility.IconContent("d_Toolbar Plus").image); + if (GUILayout.Button(plusPrompt, GUILayout.Width(25), GUILayout.Height(25))) + { + PromptBuilderWindow.isFromNegativePrompt = false; + PromptBuilderWindow.ShowWindow(PromptRecv, tags); + } } - } - GUILayout.EndHorizontal(); + GUILayout.EndHorizontal(); - EditorGUILayout.BeginVertical(GUI.skin.box, GUILayout.Height(50)); - { - EditorGUILayout.BeginVertical(EditorStyles.helpBox); + EditorGUILayout.BeginVertical(GUI.skin.box, GUILayout.Height(50)); { - GUIStyle customTagStyle = new GUIStyle(EditorStyles.label) + EditorGUILayout.BeginVertical(EditorStyles.helpBox); { - fixedHeight = 25, - margin = new RectOffset(0, 5, 0, 5) - }; - - float availableWidth = EditorGUIUtility.currentViewWidth - 20; - int tagsPerRow = Mathf.FloorToInt(availableWidth / 100); - int currentTagIndex = 0; + GUIStyle customTagStyle = new GUIStyle(EditorStyles.label) + { + fixedHeight = 25, + margin = new RectOffset(0, 5, 0, 5) + }; - while (currentTagIndex < tags.Count) - { - EditorGUILayout.BeginHorizontal(); + float availableWidth = EditorGUIUtility.currentViewWidth - 20; + int tagsPerRow = Mathf.FloorToInt(availableWidth / 100); + int currentTagIndex = 0; - for (int i = 0; i < tagsPerRow && currentTagIndex < tags.Count; i++) + while (currentTagIndex < tags.Count) { - string tag = tags[currentTagIndex]; - string displayTag = TruncateTag(tag); + EditorGUILayout.BeginHorizontal(); - GUIContent tagContent = new GUIContent(displayTag, tag); - Rect tagRect = GUILayoutUtility.GetRect(tagContent, customTagStyle); + for (int i = 0; i < tagsPerRow && currentTagIndex < tags.Count; i++) + { + string tag = tags[currentTagIndex]; + string displayTag = TruncateTag(tag); - bool isActiveTag = currentTagIndex == dragFromIndex; - GUIStyle tagStyle = isActiveTag ? new GUIStyle(customTagStyle) { normal = { background = MakeTex(2, 2, isActiveTag ? new Color(0.5f, 0.5f, 0.5f) : new Color(0.8f, 0.8f, 0.8f)) } } : customTagStyle; + GUIContent tagContent = new GUIContent(displayTag, tag); + Rect tagRect = GUILayoutUtility.GetRect(tagContent, customTagStyle); - Rect xRect = new Rect(tagRect.xMax - 20, tagRect.y, 20, tagRect.height); + bool isActiveTag = currentTagIndex == dragFromIndex; + GUIStyle tagStyle = isActiveTag ? new GUIStyle(customTagStyle) { normal = { background = MakeTex(2, 2, isActiveTag ? new Color(0.5f, 0.5f, 0.5f) : new Color(0.8f, 0.8f, 0.8f)) } } : customTagStyle; - if (Event.current.type == EventType.MouseDown) - { - if (Event.current.button == 0 && Event.current.clickCount == 2 && tagRect.Contains(Event.current.mousePosition)) + Rect xRect = new Rect(tagRect.xMax - 20, tagRect.y, 20, tagRect.height); + + if (Event.current.type == EventType.MouseDown) { - int plusCount = tag.Count(c => c == '+'); - if (plusCount < 3) + if (Event.current.button == 0 && Event.current.clickCount == 2 && tagRect.Contains(Event.current.mousePosition)) { - tags[currentTagIndex] += "+"; + int plusCount = tag.Count(c => c == '+'); + if (plusCount < 3) + { + tags[currentTagIndex] += "+"; + } + } + else if (Event.current.button == 1 && tagRect.Contains(Event.current.mousePosition)) + { + if (tag.EndsWith("+")) + { + tags[currentTagIndex] = tag.Remove(tag.LastIndexOf('+')); + } } } - else if (Event.current.button == 1 && tagRect.Contains(Event.current.mousePosition)) + + if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && tagRect.Contains(Event.current.mousePosition)) { - if (tag.EndsWith("+")) + if (!xRect.Contains(Event.current.mousePosition)) { - tags[currentTagIndex] = tag.Remove(tag.LastIndexOf('+')); + dragFromIndex = currentTagIndex; + dragStartPos = Event.current.mousePosition; + Event.current.Use(); } } - } - if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && tagRect.Contains(Event.current.mousePosition)) - { - if (!xRect.Contains(Event.current.mousePosition)) + if (dragFromIndex >= 0 && Event.current.type == EventType.MouseDrag) { - dragFromIndex = currentTagIndex; - dragStartPos = Event.current.mousePosition; - Event.current.Use(); + int newIndex = GetNewIndex(Event.current.mousePosition); + if (newIndex != -1 && newIndex != dragFromIndex && newIndex < tags.Count) + { + string tempTag = tags[dragFromIndex]; + tags.RemoveAt(dragFromIndex); + tags.Insert(newIndex, tempTag); + dragFromIndex = newIndex; + } } - } - if (dragFromIndex >= 0 && Event.current.type == EventType.MouseDrag) - { - int newIndex = GetNewIndex(Event.current.mousePosition); - if (newIndex != -1 && newIndex != dragFromIndex && newIndex < tags.Count) + if (Event.current.type == EventType.MouseUp) { - string tempTag = tags[dragFromIndex]; - tags.RemoveAt(dragFromIndex); - tags.Insert(newIndex, tempTag); - dragFromIndex = newIndex; + dragFromIndex = -1; } - } - if (Event.current.type == EventType.MouseUp) - { - dragFromIndex = -1; - } + EditorGUI.LabelField(tagRect, tagContent, tagStyle); - EditorGUI.LabelField(tagRect, tagContent, tagStyle); + if (GUI.Button(xRect, "x")) + { + tags.RemoveAt(currentTagIndex); + } + else + { + currentTagIndex++; + } - if (GUI.Button(xRect, "x")) - { - tags.RemoveAt(currentTagIndex); - } - else - { - currentTagIndex++; + tagRects.Add(tagRect); } - tagRects.Add(tagRect); + EditorGUILayout.EndHorizontal(); } - - EditorGUILayout.EndHorizontal(); } + EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); - } - - private void HandlePositiveInputField() - { - GUI.SetNextControlName("inputTextField"); - inputText = EditorGUILayout.TextField(inputText, GUILayout.ExpandWidth(true), GUILayout.Height(25), GUILayout.MinWidth(400)); - if (Event.current.isKey && Event.current.keyCode == KeyCode.Return && - GUI.GetNameOfFocusedControl() == "inputTextField") + private void HandlePositiveInputField() { - if (!string.IsNullOrWhiteSpace(inputText)) - { - string descriptorName = inputText.Trim(); - tags.Add(descriptorName); - inputText = ""; - Event.current.Use(); - } - else + GUI.SetNextControlName("inputTextField"); + inputText = EditorGUILayout.TextField(inputText, GUILayout.ExpandWidth(true), GUILayout.Height(25), GUILayout.MinWidth(400)); + + if (Event.current.isKey && Event.current.keyCode == KeyCode.Return && + GUI.GetNameOfFocusedControl() == "inputTextField") { - EditorGUI.FocusTextInControl("inputTextField"); - Event.current.Use(); + if (!string.IsNullOrWhiteSpace(inputText)) + { + string descriptorName = inputText.Trim(); + tags.Add(descriptorName); + inputText = ""; + Event.current.Use(); + } + else + { + EditorGUI.FocusTextInControl("inputTextField"); + Event.current.Use(); + } } } } diff --git a/Scenario/Editor/UpscaleEditor/UpscaleEditor.cs b/Scenario/Editor/UpscaleEditor/UpscaleEditor.cs index b618dbf..a7260d0 100644 --- a/Scenario/Editor/UpscaleEditor/UpscaleEditor.cs +++ b/Scenario/Editor/UpscaleEditor/UpscaleEditor.cs @@ -1,32 +1,35 @@ using UnityEditor; using UnityEngine; -public class UpscaleEditor : EditorWindow +namespace Scenario { - private static readonly float MinimumWidth = 1650f; - private static readonly UpscaleEditorUI UpscaleEditorUI = new(); - - [MenuItem("Window/Scenario/Upscale Editor")] - public static void ShowWindow() + public class UpscaleEditor : EditorWindow { - var window = EditorWindow.GetWindow(typeof(UpscaleEditor), false, "Upscale Editor") as UpscaleEditor; - window.minSize = new Vector2(MinimumWidth, window.minSize.y); - } + private static readonly float MinimumWidth = 1650f; + private static readonly UpscaleEditorUI UpscaleEditorUI = new(); - public static void ShowWindow(Texture2D selectedTexture, ImageDataStorage.ImageData imageData) - { - UpscaleEditorUI.currentImage = selectedTexture; - UpscaleEditorUI.imageData = imageData; - ShowWindow(); - } + [MenuItem("Window/Scenario/Upscale Editor")] + public static void ShowWindow() + { + var window = EditorWindow.GetWindow(typeof(UpscaleEditor), false, "Upscale Editor") as UpscaleEditor; + window.minSize = new Vector2(MinimumWidth, window.minSize.y); + } - private void OnGUI() - { - UpscaleEditorUI.OnGUI(this.position); - } + public static void ShowWindow(Texture2D selectedTexture, ImageDataStorage.ImageData imageData) + { + UpscaleEditorUI.currentImage = selectedTexture; + UpscaleEditorUI.imageData = imageData; + ShowWindow(); + } - private void OnDestroy() - { - UpscaleEditorUI.currentImage = null; + private void OnGUI() + { + UpscaleEditorUI.OnGUI(this.position); + } + + private void OnDestroy() + { + UpscaleEditorUI.currentImage = null; + } } } \ No newline at end of file diff --git a/Scenario/Editor/UpscaleEditor/UpscaleEditorUI.cs b/Scenario/Editor/UpscaleEditor/UpscaleEditorUI.cs index b912eca..d62e540 100644 --- a/Scenario/Editor/UpscaleEditor/UpscaleEditorUI.cs +++ b/Scenario/Editor/UpscaleEditor/UpscaleEditorUI.cs @@ -1,286 +1,289 @@ -using UnityEngine; -using UnityEditor; using System; +using System.Collections.Generic; using System.IO; +using UnityEditor; +using UnityEngine; using Newtonsoft.Json; -using System.Collections.Generic; -public class UpscaleEditorUI +namespace Scenario { - public static Texture2D currentImage = null; - public static ImageDataStorage.ImageData imageData = null; + public class UpscaleEditorUI + { + public static Texture2D currentImage = null; + public static ImageDataStorage.ImageData imageData = null; - private static List imageDataList = new(); + private static List imageDataList = new(); - private List upscaledImages = new(); - private Texture2D selectedTexture = null; - private Vector2 scrollPosition = Vector2.zero; + private List upscaledImages = new(); + private Texture2D selectedTexture = null; + private Vector2 scrollPosition = Vector2.zero; - private string imageDataUrl = ""; - private string assetId = ""; + private string imageDataUrl = ""; + private string assetId = ""; - private bool returnImage = true; - private bool forceFaceRestoration = false; - private bool usePhotorealisticModel = false; + private bool returnImage = true; + private bool forceFaceRestoration = false; + private bool usePhotorealisticModel = false; - private int scalingFactor = 2; - private int itemsPerRow = 1; + private int scalingFactor = 2; + private int itemsPerRow = 1; - private readonly float padding = 10f; - private readonly float leftSectionWidth = 150; + private readonly float padding = 10f; + private readonly float leftSectionWidth = 150; - public void OnGUI(Rect position) - { - DrawBackground(position); - GUILayout.BeginHorizontal(); + public void OnGUI(Rect position) { - position = DrawLeftSection(position); - GUILayout.FlexibleSpace(); - DrawRightSection(position); + DrawBackground(position); + GUILayout.BeginHorizontal(); + { + position = DrawLeftSection(position); + GUILayout.FlexibleSpace(); + DrawRightSection(position); + } + GUILayout.EndHorizontal(); } - GUILayout.EndHorizontal(); - } - - private static void DrawBackground(Rect position) - { - Color backgroundColor = EditorStyle.GetBackgroundColor(); - EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); - } - - private void DrawRightSection(Rect position) - { - // Right section - GUILayout.BeginVertical(GUILayout.Width(position.width * 0.15f)); - EditorStyle.Label("Upscale Image", bold: true); - if (currentImage == null) - { - DrawImageUploadArea(); - HandleDrag(); - } - else + private static void DrawBackground(Rect position) { - Rect rect = GUILayoutUtility.GetRect(leftSectionWidth, leftSectionWidth, GUILayout.Width(300), GUILayout.Height(300)); - GUI.DrawTexture(rect, currentImage, ScaleMode.ScaleToFit); - - EditorStyle.Button("Clear Image", ()=>currentImage = null); + Color backgroundColor = EditorStyle.GetBackgroundColor(); + EditorGUI.DrawRect(new Rect(0, 0, position.width, position.height), backgroundColor); } - EditorStyle.Label("Upscale Image Options", bold: true); - - GUILayout.BeginHorizontal(); + private void DrawRightSection(Rect position) { - EditorStyle.Label("Scaling Factor:"); - - if (GUILayout.Toggle(scalingFactor == 2, "2", EditorStyles.miniButtonLeft)) + // Right section + GUILayout.BeginVertical(GUILayout.Width(position.width * 0.15f)); + + EditorStyle.Label("Upscale Image", bold: true); + if (currentImage == null) + { + DrawImageUploadArea(); + HandleDrag(); + } + else { - scalingFactor = 2; + Rect rect = GUILayoutUtility.GetRect(leftSectionWidth, leftSectionWidth, GUILayout.Width(300), GUILayout.Height(300)); + GUI.DrawTexture(rect, currentImage, ScaleMode.ScaleToFit); + + EditorStyle.Button("Clear Image", ()=>currentImage = null); } - if (GUILayout.Toggle(scalingFactor == 4, "4", EditorStyles.miniButtonRight)) + EditorStyle.Label("Upscale Image Options", bold: true); + + GUILayout.BeginHorizontal(); { - scalingFactor = 4; + EditorStyle.Label("Scaling Factor:"); + + if (GUILayout.Toggle(scalingFactor == 2, "2", EditorStyles.miniButtonLeft)) + { + scalingFactor = 2; + } + + if (GUILayout.Toggle(scalingFactor == 4, "4", EditorStyles.miniButtonRight)) + { + scalingFactor = 4; + } } - } - GUILayout.EndHorizontal(); + GUILayout.EndHorizontal(); - forceFaceRestoration = EditorGUILayout.Toggle("Force Face Restoration", forceFaceRestoration); - usePhotorealisticModel = EditorGUILayout.Toggle("Use Photorealistic Model", usePhotorealisticModel); + forceFaceRestoration = EditorGUILayout.Toggle("Force Face Restoration", forceFaceRestoration); + usePhotorealisticModel = EditorGUILayout.Toggle("Use Photorealistic Model", usePhotorealisticModel); - EditorStyle.Button("Upscale Image", () => - { - if (currentImage == null) return; - imageDataUrl = CommonUtils.Texture2DToDataURL(currentImage); - assetId = imageData.Id; - FetchUpscaledImage(imageDataUrl); - }); - - if (selectedTexture != null) - { - EditorStyle.Button("Download", () => + EditorStyle.Button("Upscale Image", () => { - CommonUtils.SaveTextureAsPNG(selectedTexture); + if (currentImage == null) return; + imageDataUrl = CommonUtils.Texture2DToDataURL(currentImage); + assetId = imageData.Id; + FetchUpscaledImage(imageDataUrl); }); - } + + if (selectedTexture != null) + { + EditorStyle.Button("Download", () => + { + CommonUtils.SaveTextureAsPNG(selectedTexture); + }); + } - GUILayout.EndVertical(); - } + GUILayout.EndVertical(); + } - private static void HandleDrag() - { - Event currentEvent = Event.current; - if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) + private static void HandleDrag() { - if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) + Event currentEvent = Event.current; + if (currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform) { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - if (currentEvent.type == EventType.DragPerform) + if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0) { - DragAndDrop.AcceptDrag(); - string path = DragAndDrop.paths[0]; - if (System.IO.File.Exists(path) && - (System.IO.Path.GetExtension(path).ToLower() == ".png" || - System.IO.Path.GetExtension(path).ToLower() == ".jpg" || - System.IO.Path.GetExtension(path).ToLower() == ".jpeg")) + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + if (currentEvent.type == EventType.DragPerform) { - currentImage = new Texture2D(2, 2); - byte[] imgBytes = File.ReadAllBytes(path); - currentImage.LoadImage(imgBytes); + DragAndDrop.AcceptDrag(); + string path = DragAndDrop.paths[0]; + if (System.IO.File.Exists(path) && + (System.IO.Path.GetExtension(path).ToLower() == ".png" || + System.IO.Path.GetExtension(path).ToLower() == ".jpg" || + System.IO.Path.GetExtension(path).ToLower() == ".jpeg")) + { + currentImage = new Texture2D(2, 2); + byte[] imgBytes = File.ReadAllBytes(path); + currentImage.LoadImage(imgBytes); + } } + currentEvent.Use(); } - currentEvent.Use(); } } - } - private static void DrawImageUploadArea() - { - Rect dropArea = GUILayoutUtility.GetRect(0f, 150f, GUILayout.ExpandWidth(true)); - GUI.Box(dropArea, "Drag & Drop an image here"); - - Rect buttonRect = new Rect(dropArea.center.x - 50f, dropArea.center.y - 15f, 100f, 30f); - if (GUI.Button(buttonRect, "Choose Image")) + private static void DrawImageUploadArea() { - string imagePath = EditorUtility.OpenFilePanel("Choose Image", "", "png,jpg,jpeg"); - if (!string.IsNullOrEmpty(imagePath)) + Rect dropArea = GUILayoutUtility.GetRect(0f, 150f, GUILayout.ExpandWidth(true)); + GUI.Box(dropArea, "Drag & Drop an image here"); + + Rect buttonRect = new Rect(dropArea.center.x - 50f, dropArea.center.y - 15f, 100f, 30f); + if (GUI.Button(buttonRect, "Choose Image")) { - currentImage = new Texture2D(2, 2); - byte[] imgbytes = File.ReadAllBytes(imagePath); - currentImage.LoadImage(imgbytes); + string imagePath = EditorUtility.OpenFilePanel("Choose Image", "", "png,jpg,jpeg"); + if (!string.IsNullOrEmpty(imagePath)) + { + currentImage = new Texture2D(2, 2); + byte[] imgbytes = File.ReadAllBytes(imagePath); + currentImage.LoadImage(imgbytes); - imageData = new ImageDataStorage.ImageData(); + imageData = new ImageDataStorage.ImageData(); + } } } - } - private Rect DrawLeftSection(Rect position) - { - // Left section - GUILayout.BeginVertical(GUILayout.Width(position.width * 0.85f)); - float requiredWidth = itemsPerRow * (256 + padding) + padding; - scrollPosition = GUI.BeginScrollView(new Rect(0, 20, requiredWidth, position.height - 20), scrollPosition, new Rect(0, 0, requiredWidth, position.height - 20)); - itemsPerRow = 5; - - for (int i = 0; i < upscaledImages.Count; i++) + private Rect DrawLeftSection(Rect position) { - DrawTextureButton(i); + // Left section + GUILayout.BeginVertical(GUILayout.Width(position.width * 0.85f)); + float requiredWidth = itemsPerRow * (256 + padding) + padding; + scrollPosition = GUI.BeginScrollView(new Rect(0, 20, requiredWidth, position.height - 20), scrollPosition, new Rect(0, 0, requiredWidth, position.height - 20)); + itemsPerRow = 5; + + for (int i = 0; i < upscaledImages.Count; i++) + { + DrawTextureButton(i); + } + GUI.EndScrollView(); + GUILayout.EndVertical(); + return position; } - GUI.EndScrollView(); - GUILayout.EndVertical(); - return position; - } - private void DrawTextureButton(int i) - { - int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); - int colIndex = i % itemsPerRow; + private void DrawTextureButton(int i) + { + int rowIndex = Mathf.FloorToInt((float)i / itemsPerRow); + int colIndex = i % itemsPerRow; - Rect boxRect = new Rect(colIndex * (256 + padding), rowIndex * (256 + padding), 256, 256); - Texture2D texture = upscaledImages[i]; + Rect boxRect = new Rect(colIndex * (256 + padding), rowIndex * (256 + padding), 256, 256); + Texture2D texture = upscaledImages[i]; - if (texture == null) - { - GUI.Box(boxRect, "Loading..."); - } - else - { - if (GUI.Button(boxRect, "")) + if (texture == null) { - selectedTexture = texture; + GUI.Box(boxRect, "Loading..."); } + else + { + if (GUI.Button(boxRect, "")) + { + selectedTexture = texture; + } - GUI.DrawTexture(boxRect, texture, ScaleMode.ScaleToFit); + GUI.DrawTexture(boxRect, texture, ScaleMode.ScaleToFit); + } } - } - private void FetchUpscaledImage(string imgUrl) - { - string json = GetJsonPayload(imgUrl); - Debug.Log(json); - - ApiClient.RestPut("images/upscale",json, response => + private void FetchUpscaledImage(string imgUrl) { - var pixelatedResponse = JsonConvert.DeserializeObject(response.Content); - Texture2D texture = CommonUtils.DataURLToTexture2D(pixelatedResponse.image); - ImageDataStorage.ImageData newImageData = new ImageDataStorage.ImageData + string json = GetJsonPayload(imgUrl); + Debug.Log(json); + + ApiClient.RestPut("images/upscale",json, response => { - Id = pixelatedResponse.asset.id, - Url = pixelatedResponse.image, - InferenceId = pixelatedResponse.asset.ownerId, - }; - upscaledImages.Insert(0, texture); - imageDataList.Insert(0, newImageData); - }); - } + var pixelatedResponse = JsonConvert.DeserializeObject(response.Content); + Texture2D texture = CommonUtils.DataURLToTexture2D(pixelatedResponse.image); + ImageDataStorage.ImageData newImageData = new ImageDataStorage.ImageData + { + Id = pixelatedResponse.asset.id, + Url = pixelatedResponse.image, + InferenceId = pixelatedResponse.asset.ownerId, + }; + upscaledImages.Insert(0, texture); + imageDataList.Insert(0, newImageData); + }); + } - private string GetJsonPayload(string imgUrl) - { - string json; - if (assetId == "") + private string GetJsonPayload(string imgUrl) { - var payload = new + string json; + if (assetId == "") { - image = imgUrl, - forceFaceRestoration = forceFaceRestoration, - photorealist = usePhotorealisticModel, - scalingFactor = scalingFactor, - returnImage = returnImage, - name = "" - }; - json = JsonConvert.SerializeObject(payload); - } - else - { - var payload = new + var payload = new + { + image = imgUrl, + forceFaceRestoration = forceFaceRestoration, + photorealist = usePhotorealisticModel, + scalingFactor = scalingFactor, + returnImage = returnImage, + name = "" + }; + json = JsonConvert.SerializeObject(payload); + } + else { - image = imgUrl, - assetId = assetId, - forceFaceRestoration = forceFaceRestoration, - photorealist = usePhotorealisticModel, - scalingFactor = scalingFactor, - returnImage = returnImage, - name = CommonUtils.GetRandomImageFileName() - }; - json = JsonConvert.SerializeObject(payload); + var payload = new + { + image = imgUrl, + assetId = assetId, + forceFaceRestoration = forceFaceRestoration, + photorealist = usePhotorealisticModel, + scalingFactor = scalingFactor, + returnImage = returnImage, + name = CommonUtils.GetRandomImageFileName() + }; + json = JsonConvert.SerializeObject(payload); + } + + return json; } - return json; - } + #region API_DTO - #region API_DTO + public class Asset + { + public string id { get; set; } + public string url { get; set; } + public string mimeType { get; set; } + public Metadata metadata { get; set; } + public string ownerId { get; set; } + public string authorId { get; set; } + public DateTime createdAt { get; set; } + public DateTime updatedAt { get; set; } + public string privacy { get; set; } + public List tags { get; set; } + public List collectionIds { get; set; } + } - public class Asset - { - public string id { get; set; } - public string url { get; set; } - public string mimeType { get; set; } - public Metadata metadata { get; set; } - public string ownerId { get; set; } - public string authorId { get; set; } - public DateTime createdAt { get; set; } - public DateTime updatedAt { get; set; } - public string privacy { get; set; } - public List tags { get; set; } - public List collectionIds { get; set; } - } + public class Metadata + { + public string type { get; set; } + public string parentId { get; set; } + public string rootParentId { get; set; } + public string kind { get; set; } + public bool magic { get; set; } + public bool forceFaceRestoration { get; set; } + public bool photorealist { get; set; } + } - public class Metadata - { - public string type { get; set; } - public string parentId { get; set; } - public string rootParentId { get; set; } - public string kind { get; set; } - public bool magic { get; set; } - public bool forceFaceRestoration { get; set; } - public bool photorealist { get; set; } - } + public class Root + { + public Asset asset { get; set; } + public string image { get; set; } + } - public class Root - { - public Asset asset { get; set; } - public string image { get; set; } + #endregion } - - #endregion } diff --git a/Scenario/Editor/_CustomStyle/CustomStyle.cs b/Scenario/Editor/_CustomStyle/CustomStyle.cs index 0836f0d..1045e2c 100644 --- a/Scenario/Editor/_CustomStyle/CustomStyle.cs +++ b/Scenario/Editor/_CustomStyle/CustomStyle.cs @@ -1,150 +1,151 @@ using System; -using System.Collections; -using System.Collections.Generic; using UnityEditor; using UnityEngine; -public static class CustomStyle +namespace Scenario { - public static GUIStyle GetNormalButtonStyle() + public static class CustomStyle { - return new GUIStyle(GUI.skin.button) { }; - } + public static GUIStyle GetNormalButtonStyle() + { + return new GUIStyle(GUI.skin.button) { }; + } - public static GUIStyle GetTertiaryButtonStyle() - { - var style = new GUIStyle(GUI.skin.button) + public static GUIStyle GetTertiaryButtonStyle() { - normal = - { - background = CommonUtils.CreateColorTexture(new Color(0.4f, 0.9f, 0.86f)), - textColor = Color.white - }, - active = + var style = new GUIStyle(GUI.skin.button) { - background = CommonUtils.CreateColorTexture(new Color(0.4f, 0.9f, 0.86f)), - textColor = Color.white - } - }; + normal = + { + background = CommonUtils.CreateColorTexture(new Color(0.4f, 0.9f, 0.86f)), + textColor = Color.white + }, + active = + { + background = CommonUtils.CreateColorTexture(new Color(0.4f, 0.9f, 0.86f)), + textColor = Color.white + } + }; - return style; - } + return style; + } - public static Color GetBackgroundColor() - { - return new Color32(18, 18, 18, 255); - } + public static Color GetBackgroundColor() + { + return new Color32(18, 18, 18, 255); + } - public static bool Foldout(bool value, string text) - { - // Create a GUIStyle to customize the foldout appearance. - GUIStyle foldoutStyle = new GUIStyle(EditorStyles.foldout) + public static bool Foldout(bool value, string text) { - fontStyle = FontStyle.Bold, // Make the text bold. - fontSize = 14, // Set the font size. - normal = + // Create a GUIStyle to customize the foldout appearance. + GUIStyle foldoutStyle = new GUIStyle(EditorStyles.foldout) { - textColor = Color.cyan // Change the text color. - }, - padding = new RectOffset(15, 0, 0, 0) // Indent the text. - }; + fontStyle = FontStyle.Bold, // Make the text bold. + fontSize = 14, // Set the font size. + normal = + { + textColor = Color.cyan // Change the text color. + }, + padding = new RectOffset(15, 0, 0, 0) // Indent the text. + }; - return EditorGUILayout.Foldout(value, text, foldoutStyle); - } + return EditorGUILayout.Foldout(value, text, foldoutStyle); + } - public static void Separator() - { - EditorGUILayout.Separator(); - } + public static void Separator() + { + EditorGUILayout.Separator(); + } - public static void Space(float space = 10) - { - EditorGUILayout.Space(space); - } + public static void Space(float space = 10) + { + EditorGUILayout.Space(space); + } - public static void Label(string text, int fontSize = 12, - TextAnchor alignment = TextAnchor.MiddleLeft, - float width = 0, - float height = 0, - bool bold = false, - params GUILayoutOption[] layoutOptions) - { - var style = new GUIStyle((bold)?EditorStyles.boldLabel:EditorStyles.label) + public static void Label(string text, int fontSize = 12, + TextAnchor alignment = TextAnchor.MiddleLeft, + float width = 0, + float height = 0, + bool bold = false, + params GUILayoutOption[] layoutOptions) { - normal = + var style = new GUIStyle((bold)?EditorStyles.boldLabel:EditorStyles.label) { - textColor = Color.white - }, - fontSize = fontSize, - alignment = alignment, - fixedWidth = width, - fixedHeight = height, - }; + normal = + { + textColor = Color.white + }, + fontSize = fontSize, + alignment = alignment, + fixedWidth = width, + fixedHeight = height, + }; - GUILayout.Label(text, style, layoutOptions); - } + GUILayout.Label(text, style, layoutOptions); + } - public static void ButtonPrimary(string text, float height, Action action) - { - var style = new GUIStyle(GUI.skin.button) + public static void ButtonPrimary(string text, float height, Action action) { - normal = - { - background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)), - textColor = Color.white - }, - active = + var style = new GUIStyle(GUI.skin.button) { - background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), - textColor = Color.white - }, - hover = + normal = + { + background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)), + textColor = Color.white + }, + active = + { + background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), + textColor = Color.white + }, + hover = + { + background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), + textColor = Color.white + } + }; + + if (GUILayout.Button(text, style, GUILayout.Height(height))) { - background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), - textColor = Color.white + action?.Invoke(); } - }; - - if (GUILayout.Button(text, style, GUILayout.Height(height))) - { - action?.Invoke(); } - } - public static void ButtonSecondary(string text, float height, Action action) - { - var style = new GUIStyle(GUI.skin.button) + public static void ButtonSecondary(string text, float height, Action action) { - border = new RectOffset(), - normal = + var style = new GUIStyle(GUI.skin.button) { - textColor = Color.white - }, - active = - { - background = CommonUtils.CreateColorTexture(new Color(0.22f, 1f, 0.99f)), - textColor = Color.white - }, - hover = + border = new RectOffset(), + normal = + { + textColor = Color.white + }, + active = + { + background = CommonUtils.CreateColorTexture(new Color(0.22f, 1f, 0.99f)), + textColor = Color.white + }, + hover = + { + background = CommonUtils.CreateColorTexture(new Color(0.41f, 1f, 0.99f)), + textColor = Color.white + } + }; + + if (GUILayout.Button(text, style, GUILayout.Height(height))) { - background = CommonUtils.CreateColorTexture(new Color(0.41f, 1f, 0.99f)), - textColor = Color.white + action?.Invoke(); } - }; - - if (GUILayout.Button(text, style, GUILayout.Height(height))) - { - action?.Invoke(); } - } - public static void ButtonTertiary(string text, float height, Action action) - { - var style = GetTertiaryButtonStyle(); - - if (GUILayout.Button(text, style, GUILayout.Height(height))) + public static void ButtonTertiary(string text, float height, Action action) { - action?.Invoke(); + var style = GetTertiaryButtonStyle(); + + if (GUILayout.Button(text, style, GUILayout.Height(height))) + { + action?.Invoke(); + } } } } \ No newline at end of file diff --git a/Scenario/EditorGUI/CustomStyle.cs b/Scenario/EditorGUI/CustomStyle.cs index df0ff8a..da04cc8 100644 --- a/Scenario/EditorGUI/CustomStyle.cs +++ b/Scenario/EditorGUI/CustomStyle.cs @@ -1,163 +1,164 @@ using System; -using System.Collections; -using System.Collections.Generic; using UnityEditor; using UnityEngine; -public static class EditorStyle +namespace Scenario { - public static GUIStyle GetNormalButtonStyle() + public static class EditorStyle { - return new GUIStyle(GUI.skin.button) { }; - } + public static GUIStyle GetNormalButtonStyle() + { + return new GUIStyle(GUI.skin.button) { }; + } - public static GUIStyle GetTertiaryButtonStyle() - { - var style = new GUIStyle(GUI.skin.button) + public static GUIStyle GetTertiaryButtonStyle() { - normal = + var style = new GUIStyle(GUI.skin.button) { - background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)), - textColor = Color.white - }, - active = - { - background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), - textColor = Color.white - } - }; + normal = + { + background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)), + textColor = Color.white + }, + active = + { + background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), + textColor = Color.white + } + }; - return style; - } + return style; + } - public static Color GetBackgroundColor() - { - return new Color32(18, 18, 18, 255); - } + public static Color GetBackgroundColor() + { + return new Color32(18, 18, 18, 255); + } - //new Color(0.23f, 0.89f, 0.45f) + //new Color(0.23f, 0.89f, 0.45f) - public static bool Foldout(bool value, string text) - { - // Create a GUIStyle to customize the foldout appearance. - GUIStyle foldoutStyle = new GUIStyle(EditorStyles.foldout) + public static bool Foldout(bool value, string text) { - fontStyle = FontStyle.Bold, // Make the text bold. - fontSize = 14, // Set the font size. - normal = + // Create a GUIStyle to customize the foldout appearance. + GUIStyle foldoutStyle = new GUIStyle(EditorStyles.foldout) { - textColor = Color.cyan // Change the text color. - }, - padding = new RectOffset(15, 0, 0, 0) // Indent the text. - }; + fontStyle = FontStyle.Bold, // Make the text bold. + fontSize = 14, // Set the font size. + normal = + { + textColor = Color.cyan // Change the text color. + }, + padding = new RectOffset(15, 0, 0, 0) // Indent the text. + }; - return EditorGUILayout.Foldout(value, text, foldoutStyle); - } + return EditorGUILayout.Foldout(value, text, foldoutStyle); + } - public static void Separator() - { - EditorGUILayout.Separator(); - } + public static void Separator() + { + EditorGUILayout.Separator(); + } - public static void Space(float space = 10) - { - GUILayout.Space(space); - } + public static void Space(float space = 10) + { + GUILayout.Space(space); + } - public static void Label(string text, int fontSize = 12, - TextAnchor alignment = TextAnchor.MiddleLeft, - float width = 0, - float height = 0, - bool bold = false, - params GUILayoutOption[] layoutOptions) - { - var style = new GUIStyle((bold)?EditorStyles.boldLabel:EditorStyles.label) + public static void Label(string text, int fontSize = 12, + TextAnchor alignment = TextAnchor.MiddleLeft, + float width = 0, + float height = 0, + bool bold = false, + params GUILayoutOption[] layoutOptions) { - normal = + var style = new GUIStyle((bold)?EditorStyles.boldLabel:EditorStyles.label) { - textColor = Color.white - }, - fontSize = fontSize, - alignment = alignment, - fixedWidth = width, - fixedHeight = height, - }; + normal = + { + textColor = Color.white + }, + fontSize = fontSize, + alignment = alignment, + fixedWidth = width, + fixedHeight = height, + }; - GUILayout.Label(text, style, layoutOptions); - } + GUILayout.Label(text, style, layoutOptions); + } - public static void ButtonPrimary(string text, float height, Action action) - { - var style = new GUIStyle(GUI.skin.button) + public static void ButtonPrimary(string text, float height, Action action) { - normal = - { - background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)), - textColor = Color.white - }, - active = + var style = new GUIStyle(GUI.skin.button) { - background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), - textColor = Color.white - }, - hover = + normal = + { + background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.8f, 1)), + textColor = Color.white + }, + active = + { + background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), + textColor = Color.white + }, + hover = + { + background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), + textColor = Color.white + } + }; + + if (GUILayout.Button(text, style, GUILayout.Height(height))) { - background = CommonUtils.CreateColorTexture(new Color(0, 0.5333f, 0.75f, 1)), - textColor = Color.white + action?.Invoke(); } - }; - - if (GUILayout.Button(text, style, GUILayout.Height(height))) - { - action?.Invoke(); } - } - public static void ButtonSecondary(string text, float height, Action action) - { - var style = new GUIStyle(GUI.skin.button) + public static void ButtonSecondary(string text, float height, Action action) { - border = new RectOffset(), - normal = - { - background = CommonUtils.CreateColorTexture(new Color(0.09f, 0.75f, 0.92f)), - textColor = Color.white - }, - active = + var style = new GUIStyle(GUI.skin.button) { - background = CommonUtils.CreateColorTexture(new Color(0.22f, 1f, 0.99f)), - textColor = Color.white - }, - hover = + border = new RectOffset(), + normal = + { + background = CommonUtils.CreateColorTexture(new Color(0.09f, 0.75f, 0.92f)), + textColor = Color.white + }, + active = + { + background = CommonUtils.CreateColorTexture(new Color(0.22f, 1f, 0.99f)), + textColor = Color.white + }, + hover = + { + background = CommonUtils.CreateColorTexture(new Color(0.41f, 1f, 0.99f)), + textColor = Color.white + } + }; + + if (GUILayout.Button(text, style, GUILayout.Height(height))) { - background = CommonUtils.CreateColorTexture(new Color(0.41f, 1f, 0.99f)), - textColor = Color.white + action?.Invoke(); } - }; - - if (GUILayout.Button(text, style, GUILayout.Height(height))) - { - action?.Invoke(); } - } - public static void ButtonTertiary(string text, float height, Action action) - { - var style = GetTertiaryButtonStyle(); - - if (GUILayout.Button(text, style, GUILayout.Height(height))) + public static void ButtonTertiary(string text, float height, Action action) { - action?.Invoke(); + var style = GetTertiaryButtonStyle(); + + if (GUILayout.Button(text, style, GUILayout.Height(height))) + { + action?.Invoke(); + } } - } - public static void Button(string text, Action action, float height = 25) - { - var style = GetNormalButtonStyle(); - - if (GUILayout.Button(text, style, GUILayout.Height(height))) + public static void Button(string text, Action action, float height = 25) { - action?.Invoke(); + var style = GetNormalButtonStyle(); + + if (GUILayout.Button(text, style, GUILayout.Height(height))) + { + action?.Invoke(); + } } } } \ No newline at end of file diff --git a/Scenario/Plugins/APIPricing.cs b/Scenario/Plugins/APIPricing.cs index b10875f..cacde7e 100644 --- a/Scenario/Plugins/APIPricing.cs +++ b/Scenario/Plugins/APIPricing.cs @@ -1,96 +1,99 @@ -using UnityEngine; using UnityEditor; +using UnityEngine; -public class APIPricingWindow : EditorWindow +namespace Scenario { - private string[] headers = { "Steps", "512x512", "512x576", "512x640", "512x688", "512x704", "512x768", "512x912", "512x1024" }; - private string[,] data = { - { "30", "$0.010", "$0.011", "$0.013", "$0.013", "$0.014", "$0.015", "$0.018", "$0.020" }, - { "50", "$0.017", "$0.019", "$0.021", "$0.022", "$0.023", "$0.025", "$0.030", "$0.033" }, - { "100", "$0.033", "$0.038", "$0.042", "$0.045", "$0.046", "$0.050", "$0.059", "$0.067" }, - { "150", "$0.050", "$0.056", "$0.063", "$0.067", "$0.069", "$0.075", "$0.089", "$0.100" } - }; - private string[,] additionalCosts = { - { "Background removal", "$0.100 per image" }, - { "Upscaling", "$0.050 per image" }, - { "Magic Upscaling", "$0.050 per image" }, - { "Pixelate", "$0.025 per image" } - }; - private string[,] additionalDetails = { - { "Composition Control Multiplier", "1.2" }, - { "Generator training", "$5.00 per training" } - }; - - [MenuItem("Window/Scenario/API Pricing")] - public static void ShowWindow() + public class APIPricingWindow : EditorWindow { - GetWindow("API Pricing"); - } + private string[] headers = { "Steps", "512x512", "512x576", "512x640", "512x688", "512x704", "512x768", "512x912", "512x1024" }; + private string[,] data = { + { "30", "$0.010", "$0.011", "$0.013", "$0.013", "$0.014", "$0.015", "$0.018", "$0.020" }, + { "50", "$0.017", "$0.019", "$0.021", "$0.022", "$0.023", "$0.025", "$0.030", "$0.033" }, + { "100", "$0.033", "$0.038", "$0.042", "$0.045", "$0.046", "$0.050", "$0.059", "$0.067" }, + { "150", "$0.050", "$0.056", "$0.063", "$0.067", "$0.069", "$0.075", "$0.089", "$0.100" } + }; + private string[,] additionalCosts = { + { "Background removal", "$0.100 per image" }, + { "Upscaling", "$0.050 per image" }, + { "Magic Upscaling", "$0.050 per image" }, + { "Pixelate", "$0.025 per image" } + }; + private string[,] additionalDetails = { + { "Composition Control Multiplier", "1.2" }, + { "Generator training", "$5.00 per training" } + }; - void OnGUI() - { - DrawInfo(); - DrawTable(); - DrawAdditionalCosts(); - DrawAdditionalDetails(); - } + [MenuItem("Window/Scenario/API Pricing")] + public static void ShowWindow() + { + GetWindow("API Pricing"); + } - void DrawInfo() - { - GUILayout.Label("The Scenario API", EditorStyles.boldLabel); - EditorGUILayout.HelpBox("The Scenario API is a versatile tool for image generation and training generators. It's highly adaptable, making it easy to incorporate into games or third-party software. The flexible pricing structure operates on a pay-per-use system, with a monthly billing cycle and cost management options.", MessageType.Info); - GUILayout.Label("Pricing Structure", EditorStyles.boldLabel); - EditorGUILayout.HelpBox("The API pricing is designed for flexibility and affordability, and begins at a simple rate of 1 cent per image. Costs vary based on image resolution or the use of advanced features. Please refer to the tables below for detailed pricing per image, based on different features and configurations:", MessageType.Info); - } + void OnGUI() + { + DrawInfo(); + DrawTable(); + DrawAdditionalCosts(); + DrawAdditionalDetails(); + } - void DrawTable() - { - EditorGUILayout.BeginVertical(GUI.skin.box); - EditorGUILayout.BeginHorizontal(); - foreach (string header in headers) + void DrawInfo() { - GUILayout.Label(header, EditorStyles.boldLabel); + GUILayout.Label("The Scenario API", EditorStyles.boldLabel); + EditorGUILayout.HelpBox("The Scenario API is a versatile tool for image generation and training generators. It's highly adaptable, making it easy to incorporate into games or third-party software. The flexible pricing structure operates on a pay-per-use system, with a monthly billing cycle and cost management options.", MessageType.Info); + GUILayout.Label("Pricing Structure", EditorStyles.boldLabel); + EditorGUILayout.HelpBox("The API pricing is designed for flexibility and affordability, and begins at a simple rate of 1 cent per image. Costs vary based on image resolution or the use of advanced features. Please refer to the tables below for detailed pricing per image, based on different features and configurations:", MessageType.Info); } - EditorGUILayout.EndHorizontal(); - for (int i = 0; i < data.GetLength(0); i++) + + void DrawTable() { + EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.BeginHorizontal(); - for (int j = 0; j < data.GetLength(1); j++) + foreach (string header in headers) { - GUILayout.Label(data[i, j], GUILayout.Width(70)); + GUILayout.Label(header, EditorStyles.boldLabel); } EditorGUILayout.EndHorizontal(); + for (int i = 0; i < data.GetLength(0); i++) + { + EditorGUILayout.BeginHorizontal(); + for (int j = 0; j < data.GetLength(1); j++) + { + GUILayout.Label(data[i, j], GUILayout.Width(70)); + } + EditorGUILayout.EndHorizontal(); + } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); - } - void DrawAdditionalCosts() - { - EditorGUILayout.Space(); - EditorGUILayout.LabelField("Additional costs (cost per image)", EditorStyles.boldLabel); - EditorGUILayout.BeginVertical(GUI.skin.box); - for (int i = 0; i < additionalCosts.GetLength(0); i++) + void DrawAdditionalCosts() { - EditorGUILayout.BeginHorizontal(); - GUILayout.Label(additionalCosts[i, 0], GUILayout.Width(150)); - GUILayout.Label(additionalCosts[i, 1]); - EditorGUILayout.EndHorizontal(); + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Additional costs (cost per image)", EditorStyles.boldLabel); + EditorGUILayout.BeginVertical(GUI.skin.box); + for (int i = 0; i < additionalCosts.GetLength(0); i++) + { + EditorGUILayout.BeginHorizontal(); + GUILayout.Label(additionalCosts[i, 0], GUILayout.Width(150)); + GUILayout.Label(additionalCosts[i, 1]); + EditorGUILayout.EndHorizontal(); + } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); - } - void DrawAdditionalDetails() - { - EditorGUILayout.Space(); - EditorGUILayout.LabelField("Additional Details", EditorStyles.boldLabel); - EditorGUILayout.BeginVertical(GUI.skin.box); - for (int i = 0; i < additionalDetails.GetLength(0); i++) + void DrawAdditionalDetails() { - EditorGUILayout.BeginHorizontal(); - GUILayout.Label(additionalDetails[i, 0], GUILayout.Width(200)); - GUILayout.Label(additionalDetails[i, 1]); - EditorGUILayout.EndHorizontal(); + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Additional Details", EditorStyles.boldLabel); + EditorGUILayout.BeginVertical(GUI.skin.box); + for (int i = 0; i < additionalDetails.GetLength(0); i++) + { + EditorGUILayout.BeginHorizontal(); + GUILayout.Label(additionalDetails[i, 0], GUILayout.Width(200)); + GUILayout.Label(additionalDetails[i, 1]); + EditorGUILayout.EndHorizontal(); + } + EditorGUILayout.EndVertical(); } - EditorGUILayout.EndVertical(); } } \ No newline at end of file diff --git a/Scenario/Plugins/ApiClient.cs b/Scenario/Plugins/ApiClient.cs index 501c18d..529eab0 100644 --- a/Scenario/Plugins/ApiClient.cs +++ b/Scenario/Plugins/ApiClient.cs @@ -4,124 +4,127 @@ using RestSharp; using UnityEngine; -public static class ApiClient +namespace Scenario { - public static readonly string APIUrl = PluginSettings.ApiUrl; - - public static async void RestPost( string appendUrl, - string jsonPayload, - Action responseAction, - Action errorAction = null) + public static class ApiClient { - var client = new RestClient(APIUrl + "/" + appendUrl); - var request = new RestRequest(Method.POST); - request.AddHeader("accept", "application/json"); - request.AddHeader("content-type", "application/json"); - request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); - request.AddParameter("application/json", jsonPayload, ParameterType.RequestBody); - IRestResponse response = await client.ExecuteAsync(request); + public static readonly string APIUrl = PluginSettings.ApiUrl; - if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) - { - Debug.Log($"Response: {response.Content}"); - responseAction?.Invoke(response); - } - else + public static async void RestPost( string appendUrl, + string jsonPayload, + Action responseAction, + Action errorAction = null) { - Debug.Log($"Error: {response.Content}"); - errorAction?.Invoke(response.ErrorMessage); - } - } - - public static async void RestPut( string appendUrl, - string jsonPayload, - Action responseAction, - Action errorAction = null) - { - var client = new RestClient(APIUrl + "/" + appendUrl); - var request = new RestRequest(Method.PUT); - request.AddHeader("accept", "application/json"); - request.AddHeader("content-type", "application/json"); - request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); - request.AddParameter("application/json", jsonPayload, ParameterType.RequestBody); - IRestResponse response = await client.ExecuteAsync(request); + var client = new RestClient(APIUrl + "/" + appendUrl); + var request = new RestRequest(Method.POST); + request.AddHeader("accept", "application/json"); + request.AddHeader("content-type", "application/json"); + request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); + request.AddParameter("application/json", jsonPayload, ParameterType.RequestBody); + IRestResponse response = await client.ExecuteAsync(request); - if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) - { - Debug.Log($"Response: {response.Content}"); - responseAction?.Invoke(response); + if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) + { + Debug.Log($"Response: {response.Content}"); + responseAction?.Invoke(response); + } + else + { + Debug.Log($"Error: {response.Content}"); + errorAction?.Invoke(response.ErrorMessage); + } } - else + + public static async void RestPut( string appendUrl, + string jsonPayload, + Action responseAction, + Action errorAction = null) { - Debug.Log($"Error: {response.Content}"); - errorAction?.Invoke(response.ErrorMessage); + var client = new RestClient(APIUrl + "/" + appendUrl); + var request = new RestRequest(Method.PUT); + request.AddHeader("accept", "application/json"); + request.AddHeader("content-type", "application/json"); + request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); + request.AddParameter("application/json", jsonPayload, ParameterType.RequestBody); + IRestResponse response = await client.ExecuteAsync(request); + + if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) + { + Debug.Log($"Response: {response.Content}"); + responseAction?.Invoke(response); + } + else + { + Debug.Log($"Error: {response.Content}"); + errorAction?.Invoke(response.ErrorMessage); + } } - } - public static async void RestDelete( string appendUrl, - Action responseAction, - Action errorAction = null) - { - var client = new RestClient(APIUrl + "/" + appendUrl); - var request = new RestRequest(Method.DELETE); - request.AddHeader("accept", "application/json"); - request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); + public static async void RestDelete( string appendUrl, + Action responseAction, + Action errorAction = null) + { + var client = new RestClient(APIUrl + "/" + appendUrl); + var request = new RestRequest(Method.DELETE); + request.AddHeader("accept", "application/json"); + request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); - IRestResponse response = await client.ExecuteAsync(request); + IRestResponse response = await client.ExecuteAsync(request); - if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) - { - Debug.Log($"Response: {response.Content}"); - responseAction?.Invoke(response); + if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) + { + Debug.Log($"Response: {response.Content}"); + responseAction?.Invoke(response); + } + else + { + Debug.Log($"Error: {response.Content}"); + errorAction?.Invoke(response.ErrorMessage); + } } - else - { - Debug.Log($"Error: {response.Content}"); - errorAction?.Invoke(response.ErrorMessage); - } - } - public static async void RestGet( string appendUrl, - Action responseAction, - Action errorAction = null) - { - var client = new RestClient(APIUrl + "/" + appendUrl); - var request = new RestRequest(Method.GET); - request.AddHeader("accept", "application/json"); - request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); + public static async void RestGet( string appendUrl, + Action responseAction, + Action errorAction = null) + { + var client = new RestClient(APIUrl + "/" + appendUrl); + var request = new RestRequest(Method.GET); + request.AddHeader("accept", "application/json"); + request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); - IRestResponse response = await client.ExecuteAsync(request); + IRestResponse response = await client.ExecuteAsync(request); - if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) - { - Debug.Log($"Response: {response.Content}"); - responseAction?.Invoke(response); - } - else - { - Debug.Log($"Error: {response.Content}"); - errorAction?.Invoke(response.ErrorMessage); + if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) + { + Debug.Log($"Response: {response.Content}"); + responseAction?.Invoke(response); + } + else + { + Debug.Log($"Error: {response.Content}"); + errorAction?.Invoke(response.ErrorMessage); + } } - } - public static async Task RestGetAsync( string appendUrl) - { - var client = new RestClient(APIUrl + "/" + appendUrl); - var request = new RestRequest(Method.GET); - request.AddHeader("accept", "application/json"); - request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); + public static async Task RestGetAsync( string appendUrl) + { + var client = new RestClient(APIUrl + "/" + appendUrl); + var request = new RestRequest(Method.GET); + request.AddHeader("accept", "application/json"); + request.AddHeader("Authorization", "Basic " + PluginSettings.EncodedAuth); - IRestResponse response = await client.ExecuteAsync(request); + IRestResponse response = await client.ExecuteAsync(request); - if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) - { - Debug.Log($"Response: {response.Content}"); - return response.Content; - } - else - { - Debug.Log($"Error: {response.Content}"); - return ""; + if (response.StatusCode == HttpStatusCode.OK && response.ErrorException == null) + { + Debug.Log($"Response: {response.Content}"); + return response.Content; + } + else + { + Debug.Log($"Error: {response.Content}"); + return ""; + } } } } \ No newline at end of file diff --git a/Scenario/Plugins/CommonUtils.cs b/Scenario/Plugins/CommonUtils.cs index 13f9144..28316eb 100644 --- a/Scenario/Plugins/CommonUtils.cs +++ b/Scenario/Plugins/CommonUtils.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Unity.EditorCoroutines.Editor; @@ -8,108 +7,111 @@ using UnityEngine; using UnityEngine.Networking; -public static class CommonUtils +namespace Scenario { - public static Texture2D CreateColorTexture(Color color) + public static class CommonUtils { - Texture2D texture = new Texture2D(1, 1); - texture.SetPixel(0, 0, color); - texture.Apply(); - return texture; - } + public static Texture2D CreateColorTexture(Color color) + { + Texture2D texture = new Texture2D(1, 1); + texture.SetPixel(0, 0, color); + texture.Apply(); + return texture; + } - public static void SaveTextureAsPNG(Texture2D texture2D, string fileName = "") - { - if (fileName == null || fileName == "") { fileName = GetRandomImageFileName(); } - byte[] pngBytes = texture2D.EncodeToPNG(); - SaveImageBytesToFile(fileName, pngBytes); - } + public static void SaveTextureAsPNG(Texture2D texture2D, string fileName = "") + { + if (fileName == null || fileName == "") { fileName = GetRandomImageFileName(); } + byte[] pngBytes = texture2D.EncodeToPNG(); + SaveImageBytesToFile(fileName, pngBytes); + } - public static void SaveImageBytesToFile(string fileName, byte[] pngBytes) - { - string downloadPath = EditorPrefs.GetString("SaveFolder", "Assets"); - string filePath = downloadPath + "/" + fileName; - File.WriteAllBytes(filePath, pngBytes); - RefreshAssetDatabase(); - Debug.Log("Downloaded image to: " + filePath); - } + public static void SaveImageBytesToFile(string fileName, byte[] pngBytes) + { + string downloadPath = EditorPrefs.GetString("SaveFolder", "Assets"); + string filePath = downloadPath + "/" + fileName; + File.WriteAllBytes(filePath, pngBytes); + RefreshAssetDatabase(); + Debug.Log("Downloaded image to: " + filePath); + } - public static void RefreshAssetDatabase() - { - EditorCoroutineUtility.StartCoroutineOwnerless(Routine_RefreshDatabase()); - } + public static void RefreshAssetDatabase() + { + EditorCoroutineUtility.StartCoroutineOwnerless(Routine_RefreshDatabase()); + } - private static IEnumerator Routine_RefreshDatabase() - { - yield return null; - AssetDatabase.Refresh(); - } + private static IEnumerator Routine_RefreshDatabase() + { + yield return null; + AssetDatabase.Refresh(); + } - public static void FetchTextureFromURL(string imageUrl, Action response) - { - EditorCoroutineUtility.StartCoroutineOwnerless(Routine_FetchTextureFromUrl(imageUrl, response)); - } - - private static IEnumerator Routine_FetchTextureFromUrl(string imageUrl, Action response) - { - using UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl); - - yield return www.SendWebRequest(); - - if (www.result != UnityWebRequest.Result.Success) + public static void FetchTextureFromURL(string imageUrl, Action response) { - Debug.LogError(www.error); + EditorCoroutineUtility.StartCoroutineOwnerless(Routine_FetchTextureFromUrl(imageUrl, response)); } - else + + private static IEnumerator Routine_FetchTextureFromUrl(string imageUrl, Action response) { - Texture2D texture = DownloadHandlerTexture.GetContent(www); - response?.Invoke(texture); + using UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl); + + yield return www.SendWebRequest(); + + if (www.result != UnityWebRequest.Result.Success) + { + Debug.LogError(www.error); + } + else + { + Texture2D texture = DownloadHandlerTexture.GetContent(www); + response?.Invoke(texture); + } } - } - public static async Task FetchTextureFromURLAsync(string imageUrl) - { - using UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl); + public static async Task FetchTextureFromURLAsync(string imageUrl) + { + using UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl); + + var task = www.SendWebRequest(); + + while (!task.isDone) + { + await Task.Delay(1000); + } - var task = www.SendWebRequest(); + if (www.result != UnityWebRequest.Result.Success) + { + Debug.LogError(www.error); + return null; + } + else + { + Texture2D texture = DownloadHandlerTexture.GetContent(www); + return texture; + } + } - while (!task.isDone) + public static string GetRandomImageFileName() { - await Task.Delay(1000); + return "image" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"; } - - if (www.result != UnityWebRequest.Result.Success) + + public static string Texture2DToDataURL(Texture2D texture2D) { - Debug.LogError(www.error); - return null; + var imgBytes = texture2D.EncodeToPNG(); + string base64String = Convert.ToBase64String(imgBytes); + string dataUrl = $"data:image/png;base64,{base64String}"; + return dataUrl; } - else + + public static Texture2D DataURLToTexture2D(string dataUrl) { - Texture2D texture = DownloadHandlerTexture.GetContent(www); + string base64 = dataUrl.Replace("data:image/png;base64,",""); + base64 = base64.Replace("data:image/jpeg;base64,", ""); + byte[] bytes = Convert.FromBase64String(base64); + Texture2D texture = new Texture2D(1,1); + ImageConversion.LoadImage(texture, bytes); return texture; } } - - public static string GetRandomImageFileName() - { - return "image" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"; - } - - public static string Texture2DToDataURL(Texture2D texture2D) - { - var imgBytes = texture2D.EncodeToPNG(); - string base64String = Convert.ToBase64String(imgBytes); - string dataUrl = $"data:image/png;base64,{base64String}"; - return dataUrl; - } - - public static Texture2D DataURLToTexture2D(string dataUrl) - { - string base64 = dataUrl.Replace("data:image/png;base64,",""); - base64 = base64.Replace("data:image/jpeg;base64,", ""); - byte[] bytes = Convert.FromBase64String(base64); - Texture2D texture = new Texture2D(1,1); - ImageConversion.LoadImage(texture, bytes); - return texture; - } } \ No newline at end of file diff --git a/Scenario/Plugins/PluginSettings.cs b/Scenario/Plugins/PluginSettings.cs index 36ecb84..c67cdbd 100644 --- a/Scenario/Plugins/PluginSettings.cs +++ b/Scenario/Plugins/PluginSettings.cs @@ -2,116 +2,119 @@ using UnityEditor; using UnityEngine; -public class PluginSettings : EditorWindow +namespace Scenario { - private string apiKey; - private string secretKey; - private string saveFolder; - private int imageFormatIndex; - public static string ApiUrl => "https://api.cloud.scenario.com/v1"; - public static string ApiKey => EditorPrefs.GetString("ApiKey"); - public static string SecretKey => EditorPrefs.GetString("SecretKey"); + public class PluginSettings : EditorWindow + { + private string apiKey; + private string secretKey; + private string saveFolder; + private int imageFormatIndex; + public static string ApiUrl => "https://api.cloud.scenario.com/v1"; + public static string ApiKey => EditorPrefs.GetString("ApiKey"); + public static string SecretKey => EditorPrefs.GetString("SecretKey"); - private readonly string[] imageFormats = { "JPEG", "PNG" }; - private readonly string[] imageFormatExtensions = { "jpeg", "png" }; + private readonly string[] imageFormats = { "JPEG", "PNG" }; + private readonly string[] imageFormatExtensions = { "jpeg", "png" }; - private static string version = "Scenario Beta Version 0.2.0"; + private static string version = "Scenario Beta Version 0.2.0"; - public static string EncodedAuth - { - get + public static string EncodedAuth { - string apiKey = EditorPrefs.GetString("ApiKey"); - string secretKey = EditorPrefs.GetString("SecretKey"); - string authString = apiKey + ":" + secretKey; - byte[] authBytes = System.Text.Encoding.UTF8.GetBytes(authString); - string encodedAuth = Convert.ToBase64String(authBytes); - return encodedAuth; + get + { + string apiKey = EditorPrefs.GetString("ApiKey"); + string secretKey = EditorPrefs.GetString("SecretKey"); + string authString = apiKey + ":" + secretKey; + byte[] authBytes = System.Text.Encoding.UTF8.GetBytes(authString); + string encodedAuth = Convert.ToBase64String(authBytes); + return encodedAuth; + } } - } - private static float minimumWidth = 400f; + private static float minimumWidth = 400f; - [MenuItem("Window/Scenario/Scenario Settings")] - public static void ShowWindow() - { - GetWindow("Scenario Settings"); - PluginSettings window = GetWindow("Scenario Settings"); - window.minSize = new Vector2(minimumWidth, window.minSize.y); - } + [MenuItem("Window/Scenario/Scenario Settings")] + public static void ShowWindow() + { + GetWindow("Scenario Settings"); + PluginSettings window = GetWindow("Scenario Settings"); + window.minSize = new Vector2(minimumWidth, window.minSize.y); + } - private void OnGUI() - { - Color backgroundColor = new Color32(18, 18, 18, 255); - EditorGUI.DrawRect(new Rect(0, 0, Screen.width, Screen.height), backgroundColor); + private void OnGUI() + { + Color backgroundColor = new Color32(18, 18, 18, 255); + EditorGUI.DrawRect(new Rect(0, 0, Screen.width, Screen.height), backgroundColor); - GUILayout.Space(10); + GUILayout.Space(10); - apiKey = EditorGUILayout.TextField("API Key", apiKey); - secretKey = EditorGUILayout.PasswordField("Secret Key", secretKey); + apiKey = EditorGUILayout.TextField("API Key", apiKey); + secretKey = EditorGUILayout.PasswordField("Secret Key", secretKey); - GUILayout.Space(10); + GUILayout.Space(10); - GUILayout.Label("Image Settings", EditorStyles.boldLabel); + GUILayout.Label("Image Settings", EditorStyles.boldLabel); - imageFormatIndex = EditorGUILayout.Popup("Image Format", imageFormatIndex, imageFormats); + imageFormatIndex = EditorGUILayout.Popup("Image Format", imageFormatIndex, imageFormats); - EditorGUILayout.BeginHorizontal(); - GUILayout.Label("Save Folder: ", GUILayout.Width(80)); - saveFolder = EditorGUILayout.TextField(saveFolder); + EditorGUILayout.BeginHorizontal(); + GUILayout.Label("Save Folder: ", GUILayout.Width(80)); + saveFolder = EditorGUILayout.TextField(saveFolder); - if (GUILayout.Button("Browse...", GUILayout.Width(80))) - { - string folder = EditorUtility.OpenFolderPanel("Select Save Folder", Application.dataPath, ""); - if (!string.IsNullOrEmpty(folder)) + if (GUILayout.Button("Browse...", GUILayout.Width(80))) { - if (folder.StartsWith(Application.dataPath)) + string folder = EditorUtility.OpenFolderPanel("Select Save Folder", Application.dataPath, ""); + if (!string.IsNullOrEmpty(folder)) { - saveFolder = "Assets" + folder.Replace(Application.dataPath, ""); - } - else - { - saveFolder = folder; + if (folder.StartsWith(Application.dataPath)) + { + saveFolder = "Assets" + folder.Replace(Application.dataPath, ""); + } + else + { + saveFolder = folder; + } } } + EditorGUILayout.EndHorizontal(); + + if (GUILayout.Button("Save")) + { + SaveSettings(); + } + + GUILayout.FlexibleSpace(); // This will push the version text to the bottom + GUILayout.Label(version, EditorStyles.boldLabel); // Add this line to display the version at the bottom } - EditorGUILayout.EndHorizontal(); - if (GUILayout.Button("Save")) + private void OnEnable() { - SaveSettings(); + LoadSettings(); } - GUILayout.FlexibleSpace(); // This will push the version text to the bottom - GUILayout.Label(version, EditorStyles.boldLabel); // Add this line to display the version at the bottom - } - - private void OnEnable() - { - LoadSettings(); - } - - private void SaveSettings() - { - EditorPrefs.SetString("ApiKey", apiKey); - EditorPrefs.SetString("SecretKey", secretKey); - EditorPrefs.SetString("SaveFolder", saveFolder); - EditorPrefs.SetString("ImageFormat", imageFormatExtensions[imageFormatIndex]); - - PlayerPrefs.SetString("EncodedAuth", EncodedAuth); - } + private void SaveSettings() + { + EditorPrefs.SetString("ApiKey", apiKey); + EditorPrefs.SetString("SecretKey", secretKey); + EditorPrefs.SetString("SaveFolder", saveFolder); + EditorPrefs.SetString("ImageFormat", imageFormatExtensions[imageFormatIndex]); - private void LoadSettings() - { - apiKey = EditorPrefs.GetString("ApiKey"); - secretKey = EditorPrefs.GetString("SecretKey"); - saveFolder = EditorPrefs.GetString("SaveFolder", "Assets"); + PlayerPrefs.SetString("EncodedAuth", EncodedAuth); + } - string imageFormat = EditorPrefs.GetString("ImageFormat", "jpeg"); - imageFormatIndex = System.Array.IndexOf(imageFormatExtensions, imageFormat); - if (imageFormatIndex < 0) + private void LoadSettings() { - imageFormatIndex = 0; + apiKey = EditorPrefs.GetString("ApiKey"); + secretKey = EditorPrefs.GetString("SecretKey"); + saveFolder = EditorPrefs.GetString("SaveFolder", "Assets"); + + string imageFormat = EditorPrefs.GetString("ImageFormat", "jpeg"); + imageFormatIndex = System.Array.IndexOf(imageFormatExtensions, imageFormat); + if (imageFormatIndex < 0) + { + imageFormatIndex = 0; + } } } } diff --git a/Scenario/com.scenario.editor.asmdef b/Scenario/com.scenario.editor.asmdef index ee450b8..320d03d 100644 --- a/Scenario/com.scenario.editor.asmdef +++ b/Scenario/com.scenario.editor.asmdef @@ -1,6 +1,6 @@ { "name": "com.scenario.editor", - "rootNamespace": "", + "rootNamespace": "Scenario", "references": [ "Unity.EditorCoroutines.Editor" ], From a11c05b4a0f8fe912f2db7da65a0df71f7185ce5 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 11 Oct 2023 09:26:21 +0200 Subject: [PATCH 2/2] chore(develop): release 0.2.3 (#82) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 949ce4c..0451499 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.2.2" + ".": "0.2.3" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 62f6111..ae61755 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.2.3](https://github.com/scenario-labs/Scenario-Unity/compare/v0.2.2...v0.2.3) (2023-10-11) + + +### Bug Fixes + +* namespace and version ([#80](https://github.com/scenario-labs/Scenario-Unity/issues/80)) ([4ae138a](https://github.com/scenario-labs/Scenario-Unity/commit/4ae138a8c28452d1fc79dde64ee357e3882227d2)) + ## [0.2.2](https://github.com/scenario-labs/Scenario-Unity/compare/v0.2.1...v0.2.2) (2023-10-05) diff --git a/package-lock.json b/package-lock.json index abcbc99..b258a0b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ "@commitlint/config-conventional": "^17.7.0", "husky": "^8.0.3" }, - "version": "0.2.2" + "version": "0.2.3" }, "node_modules/@babel/code-frame": { "version": "7.22.13", @@ -3649,5 +3649,5 @@ } } }, - "version": "0.2.2" + "version": "0.2.3" } diff --git a/package.json b/package.json index ddb00c9..761a689 100644 --- a/package.json +++ b/package.json @@ -7,5 +7,5 @@ "dependencies": { "release-please": "^15.13.0" }, - "version": "0.2.2" + "version": "0.2.3" }