10 Commits
35 changed files with 1417 additions and 93 deletions
+11 -2
View File
@@ -1,8 +1,10 @@
FileVersion = 1
Locked = ["ImGui"]
Unlocked = ["corlib"]
[Workspace]
StartupProject = "GlitchyEditor"
PreprocessorMacros = ["IMGUI"]
[Projects]
GlitchyEngine = {Path = "GlitchyEngine"}
@@ -20,17 +22,24 @@ ImGuizmo = {Path = "GlitchyEngine/vendor/imgui/ImGuizmo"}
GlitchyEngineHelper = {Path = "GlitchyEngineHelper"}
bon = {Path = "GlitchyEngine/vendor/bon"}
box2d-beef = {Path = "GlitchyEngine/vendor/box2D"}
"Beef.Linq" = {Path = "GlitchyEngine/vendor/Beef.Linq/src"}
ScriptCore = {Path = "ScriptCore"}
NetHostBeef = {Path = "GlitchyEngine/vendor/NetHostBeef/NetHostBeef"}
"GlitchyEngine.Test" = {Path = "GlitchyEngine.Test"}
Xml-Beef = {Path = "GlitchyEngine/vendor/Xml-Beef"}
"GlitchyEngine.Benchmark" = {Path = "GlitchyEngine.Benchmark"}
"Beef.Linq" = {Path = "GlitchyEngine/vendor/Beef.Linq"}
"Oregano.git" = {Git = "https://github.com/zerkawei/Oregano.git"}
[WorkspaceFolders]
GlitchyEngine = ["GlitchyEngine", "GlitchLog", "GlitchyEngineHelper", "ScriptCore", "GlitchyEngine.Test", "GlitchyEngine.Benchmark"]
"GlitchyEngine/Dependencies" = ["cgltf-beef", "DirectX", "FreeType", "ImGui", "ImGuiImplDX11", "ImGuiImplWin32", "ImGuizmo", "LodePng", "msdfgen-beef", "bon", "box2d-beef", "Beef.Linq", "NetHostBeef", "Xml-Beef"]
"GlitchyEngine/Dependencies" = ["cgltf-beef", "DirectX", "FreeType", "ImGui", "ImGuiImplDX11", "ImGuiImplWin32", "ImGuizmo", "LodePng", "msdfgen-beef", "bon", "box2d-beef", "NetHostBeef", "Xml-Beef", "Beef.Linq"]
Beef = ["Beefy2D", "corlib"]
[Configs.Debug.Win64]
AllocStackTraceDepth = 12
ConfigSelections = {"GlitchyEngine.Test" = {Enabled = false}}
[Configs.Release.Win64]
Toolset = "Microsoft"
LTOType = "None"
ConfigSelections = {"GlitchyEngine.Test" = {Enabled = false}}
+6
View File
@@ -0,0 +1,6 @@
FileVersion = 1
[Locks."Oregano.git".Git]
URL = "https://github.com/zerkawei/Oregano.git"
Tag = ""
Hash = "0811b2dc6a878c472d2bc08b37ebc0862f853290"
+2 -1
View File
@@ -15,13 +15,14 @@ ImGuiImplDX11 = "*"
ImGuiImplWin32 = "*"
ImGuizmo = "*"
"Beef.Linq" = "*"
"Oregano.git" = {Git = "https://github.com/zerkawei/Oregano.git"}
[Platform.Windows]
IconFile = "$(ProjectDir)/Resources/Textures/GlitchyEngineIcon.ico"
[Configs.Debug.Win64]
PostBuildCmds = ["CopyFilesIfNewer(\"$(WorkspaceDir)/bin/vswhere.exe\", \"$(TargetDir)\")"]
DebugCommandArguments = "\"$(ProjectDir)/../GlitchyEngine.Test/content/TestProject\""
DebugCommandArguments = "\"D:\\Development\\Git\\SingleStateToOrbit\\\""
PreprocessorMacros = ["DEBUG", "IMGUI"]
[Configs.Release.Win64]
@@ -33,6 +33,10 @@ class AssetHierarchy
public TreeNode<AssetNode> RootNode => _assetRootNode;
private append ScriptProjectDirtyManager _scriptProjectDirtyManager = .();
public ScriptProjectDirtyManager ScriptProjectDirtyManager => _scriptProjectDirtyManager;
public StringView ResourcesDirectory
{
get => _resourcesDirectory;
@@ -235,6 +239,8 @@ class AssetHierarchy
//SetupResourcesFileSystemWatcher();
UpdateFiles();
ScriptProjectDirtyManager.SetVeryDirty();
}
/// Sets path to the directory that contains the game assets.
@@ -322,18 +328,24 @@ class AssetHierarchy
Log.EngineLogger.Trace($"File content changed (\"{filename}\")");
FileContentChanged(filename);
ScriptProjectDirtyManager.AssetChanged(filename);
});
fsw.OnCreated.Add(new (filename) => {
Log.EngineLogger.Trace($"File created (\"{filename}\")");
DeferFileTreeUpdate();
ScriptProjectDirtyManager.AssetChanged(filename);
});
fsw.OnDeleted.Add(new (filename) => {
Log.EngineLogger.Trace($"File deleted (\"{filename}\")");
DeferFileTreeUpdate();
ScriptProjectDirtyManager.AssetChanged(filename);
});
fsw.OnRenamed.Add(new (oldName, newName) => {
@@ -342,6 +354,9 @@ class AssetHierarchy
FileRenamed(oldName, newName);
DeferFileTreeUpdate();
ScriptProjectDirtyManager.AssetChanged(oldName);
ScriptProjectDirtyManager.AssetChanged(newName);
});
fsw.StartRaisingEvents();
@@ -0,0 +1,187 @@
using System;
using System.IO;
using System.Collections;
using Oregano;
using System.Diagnostics;
using GlitchyEditor.Settings;
namespace GlitchyEditor.Assets;
class ScriptProjectDirtyManager
{
private bool _anyAssetDirty;
private bool _projectFileDirty;
private bool _forceRebuild;
public void AssetChanged(StringView assetPath)
{
_anyAssetDirty = true;
_projectFileDirty |= CheckIfProjectFile(assetPath);
}
private bool CheckIfProjectFile(StringView assetPath)
{
for (Regex regex in _patterns)
{
if (regex.IsMatch(assetPath))
{
return true;
}
}
return false;
}
public void SetClean()
{
_anyAssetDirty = false;
_projectFileDirty = false;
_forceRebuild = false;
}
public void SetVeryDirty()
{
_forceRebuild = true;
}
public bool NeedsRebuild(RebuildOnPlay rebuildMode)
{
switch (rebuildMode)
{
case .Off:
return _forceRebuild;
case .Always:
return true;
case .WhenAnyAssetsChanged:
return _anyAssetDirty || _forceRebuild;
case .UseFastUpToDateCheck:
return _projectFileDirty || _forceRebuild;
}
}
private static List<StringView> patterns = new .(){
"**/*.cs", // C# source files
"**/*.csproj", // C# Project file
"**/*.props", // MSBuild properties
"**/*.targets", // MSBuild targets
"**/*.resx", // Embedded .NET-Ressources
"**/*.editorconfig", // Compiler- and Analyzer-config
"**/*.globalconfig", // Global Analyzer-config
"**/global.json",
"**/NuGet.Config",
"**/packages.lock.json",
"**/runtimeconfig.template.json"
} ~ delete _;
private List<Regex> _patterns = new .() ~ DeleteContainerAndItems!(_);
// Oregano's Regex doesn't copy the pattern but keeps StringViews into it, so the strings must live as long as the regexes.
private List<String> _patternStrings = new .() ~ DeleteContainerAndItems!(_);
public this()
{
for (StringView pattern in patterns)
{
String regexString = new .();
if (CompileRegexFromGlob(pattern, regexString) case .Ok(let regex))
{
_patternStrings.Add(regexString);
_patterns.Add(regex);
}
else
{
delete regexString;
}
}
}
/// Converts the glob into a regex string (written to outRegex) and compiles it.
/// The returned Regex references outRegex, so outRegex must outlive it.
private static Result<Regex> CompileRegexFromGlob(StringView glob, String outRegex)
{
outRegex.Append('^');
int inBrackets = 0;
bool isInBrackets() => inBrackets > 0;
bool isWildcard = false;
bool wasDoubleWildcard = false;
for (char8 c in glob)
{
if (isWildcard)
{
isWildcard = false;
if (c == '*')
{
// **
outRegex.Append(@"(?:.*[\\/])?");
wasDoubleWildcard = true;
continue;
}
else
{
outRegex.Append(@"[^\\/]*");
}
}
if (c == '[')
{
inBrackets++;
outRegex.Append(c);
continue;
}
else if (c == ']')
{
inBrackets--;
outRegex.Append(c);
continue;
}
if (c == '.')
{
if (isInBrackets())
outRegex.Append('.');
else
outRegex.Append(@"\.");
continue;
}
if (isInBrackets())
{
outRegex.Append(c);
continue;
}
else
{
if (c == '?')
{
outRegex.Append(@"[^\\/]");
continue;
}
else if (c == '*')
{
isWildcard = true;
continue;
}
else if (c == '/')
{
if (!wasDoubleWildcard)
outRegex.Append(@"\/");
continue;
}
else
{
outRegex.Append(c);
continue;
}
}
}
outRegex.Append('$');
return Regex.Compile(outRegex);
}
}
@@ -178,7 +178,7 @@ namespace GlitchyEditor.EditWindows
float2 buttonSize = ImGui.GetTextLineHeight().XX;
ImGui.PushStyleColor(.Button, .(0, 0, 0, 0));
ImGui.PushStyleColor(.Button, ColorRGBA(0, 0, 0, 0));
if (showComponentContextMenu != null)
{
+5 -4
View File
@@ -10,6 +10,7 @@ using GlitchyEngine;
using GlitchyEditor.CodeEditors;
using System.IO;
using GlitchyEditor.Settings;
using GlitchyEngine.Math;
namespace GlitchyEditor.EditWindows;
@@ -138,7 +139,7 @@ class LogWindow : EditorWindow
if (_visibleMessageTypes.HasFlag(.Trace))
ImGui.PushStyleColor(.Button, *col);
else
ImGui.PushStyleColor(.Button, .(0, 0, 0, 0));
ImGui.PushStyleColor(.Button, ColorRGBA(0, 0, 0, 0));
if (ImGui.ImageButtonEx(1, s_TraceIcon, buttonSize, .Zero, .Ones))
_visibleMessageTypes ^= .Trace;
@@ -148,7 +149,7 @@ class LogWindow : EditorWindow
if (_visibleMessageTypes.HasFlag(.Info))
ImGui.PushStyleColor(.Button, *col);
else
ImGui.PushStyleColor(.Button, .(0, 0, 0, 0));
ImGui.PushStyleColor(.Button, ColorRGBA(0, 0, 0, 0));
if (ImGui.ImageButtonEx(2, s_InfoIcon, buttonSize, .Zero, .Ones))
_visibleMessageTypes ^= .Info;
@@ -158,7 +159,7 @@ class LogWindow : EditorWindow
if (_visibleMessageTypes.HasFlag(.Warning))
ImGui.PushStyleColor(.Button, *col);
else
ImGui.PushStyleColor(.Button, .(0, 0, 0, 0));
ImGui.PushStyleColor(.Button, ColorRGBA(0, 0, 0, 0));
if (ImGui.ImageButtonEx(3, s_WarningIcon, buttonSize, .Zero, .Ones))
_visibleMessageTypes ^= .Warning;
@@ -168,7 +169,7 @@ class LogWindow : EditorWindow
if (_visibleMessageTypes.HasFlag(.Error))
ImGui.PushStyleColor(.Button, *col);
else
ImGui.PushStyleColor(.Button, .(0, 0, 0, 0));
ImGui.PushStyleColor(.Button, ColorRGBA(0, 0, 0, 0));
if (ImGui.ImageButtonEx(4, s_ErrorIcon, buttonSize, .Zero, .Ones))
+33
View File
@@ -7,6 +7,9 @@ using GlitchyEditor.EditWindows;
using GlitchyEngine;
using GlitchyEditor.Assets;
using GlitchyEditor.CodeEditors;
using GlitchyEditor.Settings;
using GlitchyEditor.Multithreading;
using GlitchyEngine.Scripting;
namespace GlitchyEditor
{
@@ -227,5 +230,35 @@ namespace GlitchyEditor
IdeAdapter.OpenScriptProject();
}
}
/// Rebuilds the C# scripts.
public BuildScriptsBackgroundTask BuildScripts(bool reloadAfterBuild = true, bool doCleanRebuild = false)
{
ScriptEngine.SuspendAssemblyWatcher();
BuildScriptsBackgroundTask task = new .(EditorApp.Instance.Settings.ScriptSettings.DotNetExecutablePath, EditorApp.Instance.EditorLayer.CurrentProject, releaseBuild: false, doCleanRebuild){ DeleteWhenEnded = true };
task.ContinueWith(new (task) => {
ScriptEngine.ResumeAssemblyWatcher();
EditorApp.Instance.ContentManager.AssetHierarchy.ScriptProjectDirtyManager.SetClean();
if (reloadAfterBuild)
{
EditorApp.Instance.InvokeOnMainThread(new () => {
ScriptEngine.ReloadAssemblies(retainScriptData: true);
return true;
});
}
});
EditorApp.Instance.BackgroundTaskManager.StartBackgroundTask(task);
return task;
}
public void ReloadScripts()
{
ScriptEngine.ReloadAssemblies(retainScriptData: true);
}
}
}
+2
View File
@@ -23,6 +23,8 @@ namespace GlitchyEditor
public new static EditorApp Instance => Application.Instance as EditorApp;
public new EditorContentManager ContentManager => _contentManager;
private append BackgroundTaskManager _backgroundTaskManager = .();
public BackgroundTaskManager BackgroundTaskManager => _backgroundTaskManager;
+44 -3
View File
@@ -820,10 +820,28 @@ namespace GlitchyEditor
append ScriptInstanceSerializer _scriptSerializer = .();
/// Starts the play mode for the current scene
private void OnScenePlay(SceneState newSceneState)
private void OnScenePlay(SceneState newSceneState, bool allowRebuild = true)
{
Debug.Profiler.ProfileFunction!();
if (allowRebuild && _contentManager.AssetHierarchy.ScriptProjectDirtyManager.NeedsRebuild(EditorApp.Instance.Settings.ScriptSettings.RebuildOnPlayMode))
{
// Don't immediately reload the scripts after the build, because SetActiveScene will do that anyway.
var task = _editor.BuildScripts(reloadAfterBuild: false);
task.ContinueWith(new (t) => {
// Continuations run in worker threads, invoke play on main thread!
EditorApp.Instance.InvokeOnMainThread(new () => {
// Remember not to rebuild this time!
OnScenePlay(newSceneState, allowRebuild: false);
return true;
});
}, .RunOnFinished);
// Don't play just yet, the continuation will do that.
return;
}
Runtime.Assert(newSceneState == .Play || newSceneState == .Simulate, "newSceneState must either be Play or Simulate");
Log.EngineLogger.AssertDebug(_scriptSerializer.SerializedObjectCount == 0, "Somehow some entities are serialized.");
@@ -1520,8 +1538,20 @@ namespace GlitchyEditor
if(ImGui.BeginMenu("Tools", true))
{
if(ImGui.MenuItem("Reload Scripts"))
ScriptEngine.ReloadAssemblies(retainScriptData: true);
if(ImGui.MenuItem("Build Scripts", "Ctrl+B"))
_editor.BuildScripts();
ImGui.AttachTooltip("Compiles the C# script project.");
if(ImGui.MenuItem("Clean and build Scripts", "Ctrl+Shift+B"))
_editor.BuildScripts(doCleanRebuild: true);
ImGui.AttachTooltip("Makes a clean rebuild of the C# script project.");
if(ImGui.MenuItem("Reload Scripts", "Ctrl+Shift+R"))
_editor.ReloadScripts();
ImGui.AttachTooltip("Unloads and reloads the compiled scripts.");
#if GE_EDITOR_IMGUI_DEMO
ImGui.Checkbox("Show ImGui Demo", &_showImguiDemoWindow);
@@ -1624,6 +1654,17 @@ namespace GlitchyEditor
// "Save Scene"
SaveCurrentScene();
return true;
case .B:
// "Compile scripts"
_editor.BuildScripts();
return true;
case .R:
if (shift)
// "Compile scripts"
_editor.ReloadScripts();
return true;
default:
}
+67 -1
View File
@@ -535,6 +535,35 @@ namespace ImGui
ImGui.EndTooltip();
}
/// Provides a text input field that allows to edit the given string directly. The string will grow as needed.
/// Returns true if the text was changed.
public static bool InputText(char8* label, String str, InputTextFlags flags = .None)
{
return ImGui.InputText(label, str.CStr(), (.)str.AllocSize, flags | .CallbackResize, => StringResizeCallback, Internal.UnsafeCastToPtr(str));
}
private static int StringResizeCallback(InputTextCallbackData* data)
{
if (data.EventFlag != .CallbackResize)
return 0;
String str = (String)Internal.UnsafeCastToObject(data.UserData);
int newLength = data.BufTextLen;
// PrepareBuffer increases the length and reserves room for the null terminator.
if (newLength > str.Length)
str.PrepareBuffer(newLength - str.Length);
else
str.Length = newLength;
// The string might have been reallocated.
data.Buf = str.Ptr;
data.BufSize = (.)str.AllocSize;
return 0;
}
[Comptime]
private static DataType GetDataType<T>()
{
@@ -675,7 +704,7 @@ namespace ImGui
{
PushStyleVar(value);
defer:mixin PopStyleVar();
}
}
public static void PushStyleVar(TypedStyleVar value)
{
@@ -743,6 +772,43 @@ namespace ImGui
PushStyleVar(.DockingSeparatorSize, Value);
}
}
public static mixin PushScopedStyleColor(ImGui.Col idx, uint32 color)
{
PushStyleColor(idx, color);
defer:mixin PopStyleColor();
}
public static mixin PushScopedStyleColor(ImGui.Col idx, Vec4 color)
{
PushStyleColor(idx, color);
defer:mixin PopStyleColor();
}
public static mixin PushScopedStyleColor(ImGui.Col idx, GlitchyEngine.Math.Color color)
{
PushStyleColor(idx, color);
defer:mixin PopStyleColor();
}
public static void PushStyleColor(ImGui.Col idx, GlitchyEngine.Math.Color color)
{
#unwarn
uint32 bitColor = *(uint32*)(void*)&color;
ImGui.PushStyleColor(.Text, bitColor);
}
public static mixin PushScopedStyleColor(ImGui.Col idx, GlitchyEngine.Math.ColorRGBA color)
{
PushStyleColor(idx, color);
defer:mixin PopStyleColor();
}
public static void PushStyleColor(ImGui.Col idx, GlitchyEngine.Math.ColorRGBA color)
{
ImGui.PushStyleColor(.Text, ((Color)color).Value);
}
public struct DisabledScope : IDisposable
{
@@ -17,6 +17,15 @@ abstract class BackgroundTask
internal BackgroundTaskManager _taskManager;
public delegate void Continuation(BackgroundTask);
internal append List<(TaskContinuationOptions ContinuationOptions, Continuation Continuation)> _continuations = .() ~ {
for (let entry in _)
{
delete entry.Continuation;
}
};
public enum RunState
{
Ready,
@@ -24,7 +33,8 @@ abstract class BackgroundTask
Paused,
Running,
Aborted,
Finished
Finished,
Failed
}
public enum RunResult
@@ -34,9 +44,11 @@ abstract class BackgroundTask
/// The task gives up it's runtime, because it cannot continue without user intervention through the UI.
Pause,
/// The task finished and wont run again.
Finished,
Finish,
/// The operation was aborted, the task will not run again.
Abort
Abort,
/// The task failed and wont run again.
Fail
}
public RunState State { get; internal set; } = .Ready;
@@ -46,9 +58,10 @@ abstract class BackgroundTask
public bool Blocked => State == .Blocked;
public bool Running => State == .Running;
public bool Aborted => State == .Aborted;
public bool Failed => State == .Failed;
public bool Finished => State == .Finished;
public bool Ended => Finished || Aborted;
public bool Ended => Finished || Aborted || Failed;
public bool DeleteWhenEnded { get; set; }
@@ -70,4 +83,36 @@ abstract class BackgroundTask
{
_taskManager.AbortTask(this);
}
public enum TaskContinuationOptions
{
/// Same as Default
None = 0,
RunOnFinished = 1,
RunOnFailed = 2,
RunOnAborted = 4,
Default = RunOnFinished | RunOnFailed | RunOnAborted
}
/// Creates a continuation that executes when the target Task completes.
public void ContinueWith(Continuation ownContinuation, TaskContinuationOptions continuationOptions = .Default)
{
var continuationOptions;
if (continuationOptions == .None)
{
continuationOptions = .Default;
}
if (Ended)
{
ownContinuation(this);
}
else
{
_continuations.Add((continuationOptions, ownContinuation));
}
}
}
@@ -9,7 +9,7 @@ class BackgroundTaskList
{
BackgroundTask _sentinel = new BackgroundTask()
{
public override BackgroundTask.RunResult Run() => .Finished;
public override BackgroundTask.RunResult Run() => .Finish;
public override void OnRenderPopup() { }
_next = _,
_previous = _,
@@ -59,7 +59,7 @@ class BackgroundTaskManager
if (_deferredStateChanges.TryGetValue(task, let desiredState))
{
// If the task already finished or aborted by itself, we don't care about the desired state, because it no longer applies.
if (runResult != .Finished && runResult != .Abort)
if (runResult != .Finish && runResult != .Abort && runResult != .Fail)
{
switch (desiredState)
{
@@ -74,7 +74,9 @@ class BackgroundTaskManager
_deferredStateChanges.Remove(task);
}
BackgroundTask.TaskContinuationOptions endStateFlag = .None;
switch (runResult)
{
case .Continue:
@@ -89,15 +91,27 @@ class BackgroundTaskManager
{
_waitingTasks.AddLast(task);
}
case .Finished:
case .Finish:
task.State = .Finished;
if (task.DeleteWhenEnded)
{
delete task;
}
endStateFlag = .RunOnFinished;
case .Abort:
task.State = .Aborted;
endStateFlag = .RunOnAborted;
case .Fail:
task.State = .Failed;
endStateFlag = .RunOnFailed;
}
if (task.Ended)
{
// Run the appropriate continuations
for (let (options, continuation) in task._continuations)
{
if (options.HasFlag(endStateFlag))
{
continuation(task);
}
}
if (task.DeleteWhenEnded)
{
@@ -0,0 +1,145 @@
using GlitchyEngine;
using System.Collections;
using GlitchyEditor.CodeEditors;
using System.IO;
using System;
using System.Diagnostics;
using ImGui;
using GlitchyEditor.Multithreading;
using GlitchyEngine.Scripting;
using GlitchyEditor.Settings;
using System.Threading;
namespace GlitchyEditor.Multithreading;
class BuildScriptsBackgroundTask : BackgroundTask
{
private bool _isAborting = false;
private Project _project;
private bool _releaseBuild;
private StringView _dotnetPath;
private bool _doCleanRebuild;
private String _buildLog = new .() ~ delete _;
private SpawnedProcess _process ~ delete _;
public this(StringView dotnetPath, Project project, bool releaseBuild, bool doCleanRebuild)
{
_dotnetPath = dotnetPath;
_project = project;
_releaseBuild = releaseBuild;
_doCleanRebuild = doCleanRebuild;
}
public override RunResult Run()
{
return BuildScripts();
}
public override void OnRenderPopup()
{
if (ImGui.Begin(!_isAborting ? "Compiling scripts..." : "Aborting compilation...", null, .NoDocking | .NoCollapse | .Modal | .NoResize | .AlwaysAutoResize))
{
if (ImGui.BeginChild("##BuildLog", .(550, ImGui.GetTextLineHeightWithSpacing() * 6), .None, .HorizontalScrollbar))
{
ImGui.TextUnformatted(_buildLog);
}
if (ImGui.GetScrollY() >= ImGui.GetScrollMaxY())
ImGui.SetScrollHereY(1.0f);
ImGui.EndChild();
if (ImGui.Button("Cancel"))
{
_isAborting = true;
_process.Kill();
}
ImGui.End();
}
}
private RunResult BuildScripts()
{
RunResult result;
Log.EngineLogger.Info($"Building Scripts ({(_releaseBuild ? "Release" : "Debug")})...");
String exeFile = scope .();
Environment.GetExecutableFilePath(exeFile);
String exeDirectory = scope .();
Path.GetDirectoryPath(exeFile, exeDirectory);
ProcessStartInfo processInfo = scope .();
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.CreateNoWindow = true;
processInfo.SetWorkingDirectory(_project.WorkspacePath);
processInfo.SetFileName(EditorApp.Instance.Settings.ScriptSettings.DotNetExecutablePath);
StringView target;
if (_doCleanRebuild)
{
target = "build -t:Rebuild";
}
else
{
target = "build";
}
// -sc|--self-contained... Publish the .NET runtime with your application so the runtime doesn't need to be installed on the target machine.
// -> This might be useful to build the final game
// -o|--ouput <OUTPUT_DIRECTORY>... might be useful for building the final game
processInfo.SetArguments(scope $"{target} -c {(_releaseBuild ? "Release" : "Debug")}");
_process = new SpawnedProcess();
if (_process.Start(processInfo) case .Ok)
{
FileStream outputStream = scope FileStream();
_process.AttachStandardOutput(outputStream);
StreamReader outputReader = scope .(outputStream);
while (!_process.HasExited)
{
outputReader.ReadToEnd(_buildLog).IgnoreError();
}
_process.WaitFor(-1);
if (_isAborting)
{
Log.EngineLogger.Warning($"Build was aborted:\n{_buildLog}");
result = .Abort;
}
else if (_process.ExitCode == 0)
{
Log.EngineLogger.Info($"Scripts compiled successfully:\n{_buildLog}");
result = .Finish;
}
else
{
Log.EngineLogger.Error($"Script compilation failed:\n{_buildLog}");
result = .Fail;
}
DeleteAndNullify!(_process);
}
else
{
Log.EngineLogger.Error("Failed to execute `dotnet build`");
result = .Fail;
}
return result;
}
}
@@ -249,7 +249,7 @@ class CopyBackgroundTask : BackgroundTask
delete currentPath;
}
return .Finished;
return .Finish;
}
private Result<void, CopyError> CopyPath(CopyInfo copyInfo)
@@ -141,7 +141,7 @@ class DeleteBackgroundTask : BackgroundTask
delete currentPath;
}
return .Finished;
return .Finish;
}
private Result<void, DeleteError> DeletePath(StringView deletePath)
@@ -252,7 +252,7 @@ class MoveFilesBackgroundTask : BackgroundTask
delete currentPath;
}
return .Finished;
return .Finish;
}
private Result<void, CopyError> MovePath(CopyInfo copyInfo)
@@ -0,0 +1,267 @@
using GlitchyEngine;
using System.Collections;
using GlitchyEditor.CodeEditors;
using System.IO;
using System;
using System.Diagnostics;
using ImGui;
using GlitchyEditor.Multithreading;
using GlitchyEngine.Scripting;
using GlitchyEditor.Settings;
namespace GlitchyEditor.Multithreading;
class TestDotnetBackgroundTask : BackgroundTask
{
private ScriptSettings _settings;
private Project _project;
public enum TestResult
{
None,
Ok,
Timeout,
FailedToExecute,
NoSdksFound,
TooOld
}
private TestResult _testResult;
public TestResult TestResult => _testResult;
public this(ScriptSettings settings, Project project)
{
_settings = settings;
_project = project;
}
public override RunResult Run()
{
if (QueryAvailableSdks() case .Err)
{
return .Fail;
}
if (CheckMinimumVersion() case .Err)
{
return .Fail;
}
if (_project != null)
{
CheckProjectVersion();
}
_testResult = .Ok;
return .Finish;
}
public override void OnRenderPopup()
{
if (ImGui.Begin("Testing .Net Installation...", null, .NoDocking | .NoCollapse | .Modal | .NoResize | .AlwaysAutoResize))
{
ImGui.Text("...");
ImGui.End();
}
}
private Result<void> QueryAvailableSdks()
{
_settings.DotNetSdks.Clear();
Log.EngineLogger.Info("Listing .Net SDKs...");
String exeFile = scope .();
Environment.GetExecutableFilePath(exeFile);
String exeDirectory = scope .();
Path.GetDirectoryPath(exeFile, exeDirectory);
ProcessStartInfo processInfo = scope .();
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.CreateNoWindow = true;
processInfo.SetFileName(_settings.DotNetExecutablePath);
// Lists all installed sdks
StringView argumentList = "--list-sdks";
processInfo.SetArguments(argumentList);
let process = scope SpawnedProcess();
if (process.Start(processInfo) case .Ok)
{
FileStream outputStream = scope FileStream();
process.AttachStandardOutput(outputStream);
if (!process.WaitFor(1000))
{
Log.EngineLogger.Error($"`dotnet --list-sdks` timed out.");
process.Kill();
_testResult = .Timeout;
return .Err;
}
StreamReader sr = scope .(outputStream);
String line = scope .(256);
while (sr.ReadLine(line..Clear()) case .Ok)
{
Log.EngineLogger.Info($"Detecting .Net SDK version from line: {line}");
// A line for a normal verion looks like this:
// 10.0.402 [C:\Program Files\dotnet\sdk]
// A line for a snapshot looks like this:
// 9.0.100-preview.7.24407.12 [C:\Program Files\dotnet\sdk]
// A line for a release candidate looks like this:
// 11.0.100-rc.2.26504.105 [C:\Program Files\dotnet\sdk]
// We must have a number at the start so we can at least grab a major version.
if (!line[0].IsDigit)
{
Log.EngineLogger.Error("This line doesn't appear to show an SDK version.");
continue;
}
DotNetVersion detectedVersion = default;
int indexOfSpace = line.IndexOf(' ');
int indexOfDash = line.IndexOf('-');
int versionNumberEnd = line.Length;
if (indexOfDash > 0)
versionNumberEnd = indexOfDash;
else if (indexOfSpace > 0)
versionNumberEnd = indexOfSpace;
StringView versionString = line.Substring(0, versionNumberEnd);
List<StringView> versionSplits = scope .(versionString.Split('.'));
if (versionSplits.IsEmpty)
{
Log.EngineLogger.Error("Line doesn't contain a valid version number.");
continue;
}
if (versionSplits.Count >= 1 && int.Parse(versionSplits[0]) not case .Ok(out detectedVersion.Major))
{
Log.EngineLogger.Error($"Failed to parse \"major\" part of version ({versionSplits[0]}).");
continue;
}
if (versionSplits.Count >= 2 && int.Parse(versionSplits[1]) not case .Ok(out detectedVersion.Minor))
{
Log.EngineLogger.Error($"Failed to parse \"minor\" part of version ({versionSplits[1]}).");
continue;
}
if (versionSplits.Count >= 3 && int.Parse(versionSplits[2]) not case .Ok(out detectedVersion.Patch))
{
Log.EngineLogger.Error($"Failed to parse \"patch\" part of version ({versionSplits[2]}).");
continue;
}
if (indexOfDash > 0)
{
StringView previewString = line.Substring(indexOfDash + 1);
int previewNumberStart = previewString.IndexOf('.') + 1;
int secondDot = previewString.IndexOf('.', previewNumberStart);
int previewNumber = 0;
if (previewNumberStart > 0)
{
int length = previewString.Length - previewNumberStart;
if (secondDot > 0)
{
length = secondDot - previewNumberStart;
}
StringView previewNumberString = previewString.Substring(previewNumberStart, length);
if (int.Parse(previewNumberString) not case .Ok(out previewNumber))
{
Log.EngineLogger.Warning("Could not determine the preview number.");
}
}
if (previewString.StartsWith("preview"))
{
detectedVersion.Type = .Preview(previewNumber);
}
else if (previewString.StartsWith("rc"))
{
detectedVersion.Type = .ReleaseCandidate(previewNumber);
}
else
{
detectedVersion.Type = .Unknown;
Log.EngineLogger.Warning("Could not determine the preview-type for SDK.");
}
}
else
{
detectedVersion.Type = .Normal;
}
Log.EngineLogger.Info($"Detected .Net SDK: {detectedVersion}.");
_settings.DotNetSdks.Add(detectedVersion);
}
}
else
{
Log.EngineLogger.Error($"Failed to execute `{_settings.DotNetExecutablePath} {argumentList}`");
_testResult = .FailedToExecute;
return .Err;
}
if (_settings.DotNetSdks.Count == 0)
{
_testResult = .NoSdksFound;
return .Err;
}
return .Ok;
}
/// Checks if one of the detected SDKs is at least the minimum required dotnet version.
private Result<void> CheckMinimumVersion()
{
DotNetVersion maxVersion = _settings.GetLatestInstalledDotNetVersion();
if (maxVersion < ScriptEngine.MinDotNetVersion)
{
Log.EngineLogger.Error($"The latest detected .Net SDK ({maxVersion}) is older than the required minimum Version ({ScriptEngine.MinDotNetVersion}). Please install a newer .Net SDK or configure the dotnet executable in the settings.");
_testResult = .TooOld;
return .Err;
}
else
{
Log.EngineLogger.Info($"Latest detected .Net SDK: {maxVersion}.");
return .Ok;
}
}
/// Checks if one of the detected SDKs is at least the minimum required dotnet version for the current project.
void CheckProjectVersion()
{
/*DotNetVersion maxVersion = GetMaxVersion();
if (maxVersion < ScriptEngine.MinDotNetVersion)
{
Log.EngineLogger.Error($"The latest detected .Net SDK ({maxVersion}) is older than the required minimum Version ({ScriptEngine.MinDotNetVersion}). Please install a newer .Net SDK or configure the dotnet executable in the settings.");
}
else
{
Log.EngineLogger.Info($"Latest detected .Net SDK: {maxVersion}.");
}*/
}
}
@@ -51,7 +51,7 @@ class DetectIDEsBackgroundTask : BackgroundTask
_stage = .SearchRider;
FindRider();
return .Finished;
return .Finish;
}
public override void OnRenderPopup()
+136 -3
View File
@@ -6,6 +6,9 @@ using Bon;
using GlitchyEngine;
using System.Threading;
using System.Linq;
using GlitchyEngine.Scripting;
using GlitchyEditor.Multithreading;
using GlitchyEngine.Math;
using static GlitchyEditor.SettingsWindow;
@@ -50,6 +53,20 @@ struct SettingAttribute : Attribute
}
}
/// Fields with this Attribute will be exposed as settings.
[AttributeUsage(AttributeTargets.StaticField, .ReflectAttribute)]
struct SettingValueAttribute : Attribute
{
public String Name;
public String Tooltip;
public this(String name, String tooltip = "")
{
Name = name;
Tooltip = tooltip;
}
}
/// Fields with this Attribute will be exposed as settings.
[AttributeUsage(.Method, .ReflectAttribute | .AlwaysIncludeTarget)]
struct CustomSettingRendererAttribute : Attribute
@@ -236,9 +253,40 @@ class IdeInstallation
// This would however be quite complicated to implement well, when looking at how different Visual Studio and Rider already are.
}
[Reflect]
enum RebuildOnPlay
{
[SettingValue("Off", "The scripts will not be rebuild when entering play mode.")]
Off,
[SettingValue("Always", "The scripts will always be rebuild when entering play mode.")]
Always,
[SettingValue("When any Asset changed", """
The scripts will automatically be rebuild when any asset in asset-directory changed, even if it is not necessary for the build process.
This can be helpful if you include files in your build-process that are not detected by the heuristic up to date check.
""")]
WhenAnyAssetsChanged,
[SettingValue("When the fancy dancy heuristic check says so.", """
A highly sophisticated heuristic will determine if a rebuild is required.
""")]
UseFastUpToDateCheck
}
[Reflect]
class ScriptSettings
{
private List<DotNetVersion> _dotNetSdks = new .() ~ delete _;
public List<DotNetVersion> DotNetSdks => _dotNetSdks;
[BonInclude]
private String _dotnetExePath = new .("dotnet") ~ delete _;
private TestDotnetBackgroundTask.TestResult _dotnetTestResult = .None;
public StringView DotNetExecutablePath
{
get => _dotnetExePath;
set => String.NewOrSet!(_dotnetExePath, value);
}
[BonInclude]
private List<IdeInstallation> _ideInstallations = new .() ~ DeleteContainerAndItems!(_);
@@ -253,6 +301,12 @@ class ScriptSettings
private bool _lookedForVs = false;
private bool _lookedForRider = false;
[Setting("Tools", "Rebuild scripts on play mode", "Configures if and how the scripts will be rebuilt every time the play mode is entered."), BonInclude]
public RebuildOnPlay RebuildOnPlayMode = .UseFastUpToDateCheck;
[Setting("Tools", "Automatically rebuild changed scripts", "If active, the scripts will be rebuilt every time the user presses play."), BonInclude]
public bool AutoRebuildOnChange = true;
/// Enters the lock and gets the list of Ide installations.
public Monitor.MonitorLockInstance EnterAndGetIdeInstallations(out List<IdeInstallation> ideInstallations)
@@ -275,6 +329,18 @@ class ScriptSettings
}
}
}
if (_dotNetSdks.Count == 0)
{
TestDotnetInstallation();
}
}
private TestDotnetBackgroundTask TestDotnetInstallation()
{
TestDotnetBackgroundTask task = new TestDotnetBackgroundTask(this, null){ DeleteWhenEnded = true };
EditorApp.Instance.BackgroundTaskManager.StartBackgroundTask(task);
return task;
}
[CustomSettingRenderer("Tools")]
@@ -282,8 +348,17 @@ class ScriptSettings
{
bool settingsChanged = false;
ImGui.Text("IDE:");
ImGui.Text("IDE");
ImGui.SameLine(ImGui.GetContentRegionAvail().x - ImGui.CalcTextSize("Detect IDEs...").x - 2 * ImGui.GetStyle().FramePadding.x);
if (ImGui.Button("Detect IDEs..."))
{
EditorApp.Instance.BackgroundTaskManager.StartBackgroundTask(new DetectIDEsBackgroundTask(this){ DeleteWhenEnded = true });
}
ImGui.TableNextColumn();
if (ImGui.BeginCombo("##ide", ActiveIde?.Name.ToScopeCStr!()))
{
using (EnterAndGetIdeInstallations(let installations))
@@ -327,13 +402,71 @@ class ScriptSettings
ImGui.EndCombo();
}
if (ImGui.Button("Detect IDEs..."))
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.Text("DotNet Executable Path");
ImGui.SameLine(ImGui.GetContentRegionAvail().x - ImGui.CalcTextSize("Test").x - 2 * ImGui.GetStyle().FramePadding.x);
if (ImGui.Button("Test"))
{
EditorApp.Instance.BackgroundTaskManager.StartBackgroundTask(new DetectIDEsBackgroundTask(this){ DeleteWhenEnded = true });
_dotnetTestResult = .None;
TestDotnetInstallation().ContinueWith(new (task) => {
_dotnetTestResult = ((TestDotnetBackgroundTask)task).TestResult;
});
}
ImGui.TableNextColumn();
if (ImGui.InputText("##dotnetPath", _dotnetExePath))
{
settingsChanged = true;
}
switch (_dotnetTestResult)
{
case .None:
// Nothing to do.
case .Ok:
ImGui.PushStyleColor(.Text, ColorRGBA.Green);
ImGui.TextUnformatted(scope $"Dotnet works and found latest version: {GetLatestInstalledDotNetVersion()}");
ImGui.PopStyleColor();
case .Timeout:
ImGui.PushStyleColor(.Text, ColorRGBA.Red);
ImGui.TextUnformatted(scope $"Dotnet timed out.");
ImGui.PopStyleColor();
case .FailedToExecute:
ImGui.PushStyleColor(.Text, ColorRGBA.Red);
ImGui.TextUnformatted(scope $"Failed to execute dotnet.");
ImGui.PopStyleColor();
case .NoSdksFound:
ImGui.PushStyleColor(.Text, ColorRGBA.Red);
ImGui.TextUnformatted(scope $"Dotnet works but no SDK found.");
ImGui.PopStyleColor();
case .TooOld:
ImGui.PushStyleColor(.Text, ColorRGBA.Red);
ImGui.TextUnformatted(scope $"Dotnet works but latest installed version {GetLatestInstalledDotNetVersion()} is too old.");
ImGui.PopStyleColor();
}
return settingsChanged;
}
public DotNetVersion GetLatestInstalledDotNetVersion()
{
DotNetVersion maxVersion = .(-1, -1, -1, .Unknown);
for (DotNetVersion version in _dotNetSdks)
{
if (version > maxVersion)
{
maxVersion = version;
}
}
return maxVersion;
}
}
[Reflect]
+36 -6
View File
@@ -106,8 +106,6 @@ namespace GlitchyEditor
void ScanForSettings(Object container)
{
Log.EngineLogger.Info($"Visiting type: {container.GetType().GetName(.. scope .())}");
Type type = container.GetType();
for (var field in type.GetFields())
@@ -138,8 +136,6 @@ namespace GlitchyEditor
for (let method in type.GetMethods(.Instance | .Static | .Public | .NonPublic))
{
Log.EngineLogger.Info($"Visiting method: {method.Name}");
Result<CustomSettingRendererAttribute> rendererResult = method.GetCustomAttribute<CustomSettingRendererAttribute>();
if (rendererResult case .Ok(let rendererInfo))
@@ -367,12 +363,23 @@ namespace GlitchyEditor
// TODO: handle multiple Flags (as a separate enum type handler though!)
StringView currentName = "";
StringView currentTooltip = "";
for (let (name, value) in Enum.GetEnumerator(fieldInfo.FieldType))
{
if (value == underlyingValue)
{
currentName = name;
if (fieldInfo.FieldType.GetField(@name.Index) case .Ok(FieldInfo info) &&
info.GetCustomAttribute<SettingValueAttribute>() case .Ok(SettingValueAttribute settingValue))
{
currentName = settingValue.Name;
currentTooltip = settingValue.Tooltip;
}
else
{
currentName = name;
}
break;
}
}
@@ -383,7 +390,17 @@ namespace GlitchyEditor
{
bool isSelected = (name == currentName);
if (ImGui.Selectable(name.ToScopeCStr!(), isSelected))
StringView valueName = name;
StringView valueTooltip = "";
if (fieldInfo.FieldType.GetField(@name.Index) case .Ok(FieldInfo info) &&
info.GetCustomAttribute<SettingValueAttribute>() case .Ok(SettingValueAttribute settingValue))
{
valueName = settingValue.Name;
valueTooltip = settingValue.Tooltip;
}
if (ImGui.Selectable(valueName.ToScopeCStr!(), isSelected))
{
// Set value in field reference
switch (fieldInfo.FieldType.Size)
@@ -397,10 +414,20 @@ namespace GlitchyEditor
if (!isSelected)
_settingsChanged = true;
}
if (!valueTooltip.IsEmpty)
{
ImGui.AttachTooltip(valueTooltip);
}
}
ImGui.EndCombo();
}
if (!currentTooltip.IsEmpty)
{
ImGui.AttachTooltip(currentTooltip);
}
}
if (setting.Name == _SettingToHighlight)
@@ -420,6 +447,9 @@ namespace GlitchyEditor
for (let methodBinding in category._methodBindings)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
if (methodBinding.Method.Invoke(methodBinding.Method.IsStatic ? null : methodBinding.SettingsObject, category) case .Ok(var returnValue))
{
_settingsChanged |= returnValue.Get<bool>();
@@ -17,7 +17,7 @@ class BasicBenchmark
Console.WriteLine(Directory.GetCurrentDirectory(.. scope .()));
ScriptEngine.Init();
ScriptEngine.SetAppAssemblyPath(@"..\GlitchyEngine.Test\content\TestProject\.cache\bin\TestProject.dll");
ScriptEngine.SetAppAssemblyPath(@"..\GlitchyEngine.Test\content\TestProject\.cache\bin\TestProject.dll", false);
}
protected static void Shutdown()
@@ -0,0 +1,179 @@
{
Version = 1,
Entities = [
{
Id = 8893155135649576304,
NameComponent = {
Name = "Camera"
},
TransformComponent = {
Position = {
X = 0,
Y = 2,
Z = -5
},
Rotation = {
X = 0,
Y = 0.21643962,
Z = 0,
W = 0.976296
},
Scale = {
X = 1,
Y = 1,
Z = 1
},
EditorEulerRotation = {
X = 0,
Y = 0.43633237,
Z = 0
}
},
CameraComponent = {
Primary = true,
ProjectionType = .InfinitePerspective,
PerspectiveFovY = 1.3089969,
PerspectiveNearPlane = 0.1,
PerspectiveFarPlane = 10000,
OrthographicHeight = 10,
OrthographicNearPlane = 0,
OrthographicFarPlane = 10,
AspectRatio = 1.9840086,
FixedAspectRatio = false
},
Editor = {
Flags = .Default
}
},
{
Id = 14812165297099037146,
NameComponent = {
Name = "Light"
},
TransformComponent = {
Position = {
X = -3,
Y = 4,
Z = -1.5
},
Rotation = {
X = 0.23977584,
Y = 0.6143275,
Z = 0.031567074,
W = 0.7510744
},
Scale = {
X = 1,
Y = 1,
Z = 1
},
EditorEulerRotation = {
X = 0.3490659,
Y = 1.3089968,
Z = 0.34906587
}
},
LightComponent = {
LightType = .Directional,
Illuminance = 10,
Color = {
R = 1,
G = 0.9500002,
B = 0.8
}
},
Editor = {
Flags = .Default
}
},
{
Id = 4185051642788402424,
NameComponent = {
Name = "Entity"
},
TransformComponent = {
Position = {
X = 0,
Y = 0,
Z = 0
},
Rotation = {
X = 0,
Y = 0,
Z = 0,
W = 1
},
Scale = {
X = 1,
Y = 1,
Z = 1
},
EditorEulerRotation = {
X = 0,
Y = 0,
Z = 0
}
},
ScriptComponent = {
ScriptClass = "TestProject.Assets.Scripts.AdvancedSerializationTest",
Fields = (TestProject.Assets.Scripts.AdvancedSerializationTest){
ID = 4185051642788402424,
LeTuple.Item1 = (int32)101,
LeTuple.Item2.X = (float)49,
LeTuple.Item2.Y = (float)31,
LeTuple.Item3 = &16946239429800937368,
LeListDeTuple = &13357518334354818316,
GenericStructField.MyField = (float)-56,
GenericClassField = &6770493598825812026
}
},
Editor = {
Flags = .Default
}
}
],
ReferencedObjects = [
(TestProject.BClass){
ID = 16946239429800937368,
F = (float)131
},
(System.Collections.Generic.List`1[System.ValueTuple`3[System.Int32,GlitchyEngine.Math.float2,TestProject.BClass]]){
ID = 13357518334354818316,
Count = (int32)4,
0.Item1 = (int32)64,
0.Item2.X = (float)-81,
0.Item2.Y = (float)-118,
0.Item3 = &14597969159961685574,
1.Item1 = (int32)0,
1.Item2.X = (float)0,
1.Item2.Y = (float)0,
1.Item3 = &0,
2.Item1 = (int32)73,
2.Item2.X = (float)165,
2.Item2.Y = (float)115,
2.Item3 = &15752578204681304901,
3.Item1 = (int32)0,
3.Item2.X = (float)0,
3.Item2.Y = (float)0,
3.Item3 = &0
},
(TestProject.BClass){
ID = 14597969159961685574,
F = (float)23
},
(TestProject.BClass){
ID = 15752578204681304901,
F = (float)159
},
(TestProject.Assets.Scripts.SimpleGenericClass`1[System.Double]){
ID = 6770493598825812026,
MyField = (double)0.9599999785423279
}
],
StaticFields = [
(TestProject.SerializationTest){
ID = 1460275328679732402,
StaticNumber = (int32)0
}
]
}
@@ -0,0 +1,11 @@
{
AssetLoader = null,
Config = null,
Importer = null,
ImporterConfig = null,
Processor = null,
ProcessorConfig = null,
Exporter = null,
ExporterConfig = null,
AssetHandle = 4008662279183989969
}
@@ -0,0 +1,28 @@
using GlitchyEngine;
using GlitchyEngine.Math;
using System;
using System.Collections.Generic;
using System.Text;
namespace TestProject.Assets.Scripts;
public class SimpleGenericClass<T>
{
public T MyField;
}
public struct SimpleGenericStruct<T>
{
public T MyField;
}
public class AdvancedSerializationTest : Entity
{
public (int Prim, float2 Struc, BClass Ref) LeTuple;
public List<(int Prim, float2 Struc, BClass Ref)> LeListDeTuple;
public SimpleGenericStruct<float> GenericStructField = new SimpleGenericStruct<float>();
public SimpleGenericClass<double> GenericClassField = new SimpleGenericClass<double>();
}
@@ -0,0 +1,11 @@
{
AssetLoader = null,
Config = null,
Importer = null,
ImporterConfig = null,
Processor = null,
ProcessorConfig = null,
Exporter = null,
ExporterConfig = null,
AssetHandle = 16179505410974622627
}
@@ -0,0 +1,11 @@
{
AssetLoader = null,
Config = null,
Importer = null,
ImporterConfig = null,
Processor = null,
ProcessorConfig = null,
Exporter = null,
ExporterConfig = null,
AssetHandle = 13036819508142753970
}
@@ -0,0 +1,11 @@
{
AssetLoader = null,
Config = null,
Importer = null,
ImporterConfig = null,
Processor = null,
ProcessorConfig = null,
Exporter = null,
ExporterConfig = null,
AssetHandle = 2840305762073418465
}
@@ -2,7 +2,7 @@
<PropertyGroup>
<!-- General configuration -->
<AssemblyTitle>TestProject</AssemblyTitle>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<OutputType>Library</OutputType>
<Nullable>enable</Nullable>
<!-- Define the output path -->
@@ -1,4 +1,7 @@
<Solution>
<Project Path="TestProject.csproj"/>
<Project Path="D:\Development\Projects\Beef\GlitchyEngine\ScriptCore\ScriptCore.csproj"/>
<Project Path="D:\Development\Projects\Beef\GlitchyEngine\ScriptCoreGenerator\ScriptCoreGenerator.csproj"/>
<Project Path="D:\Development\Projects\Beef\GlitchyEngine\ScriptCoreGenerator.Test\ScriptCoreGenerator.Test.csproj"/>
<Project Path="D:\Development\Projects\Beef\GlitchyEngine\vendor\ImGui.NET\src\ImGui.NET\ImGui.NET.csproj"/>
</Solution>
@@ -0,0 +1,87 @@
using System;
namespace GlitchyEngine.Scripting;
enum DotNetVersionType
{
case Normal;
case Preview(int Number);
case ReleaseCandidate(int Number);
case Unknown;
public int GetSortingOrder()
{
switch (this)
{
case .Normal:
return 3;
case .ReleaseCandidate:
return 2;
case .Preview:
return 1;
case .Unknown:
return 0;
}
}
}
struct DotNetVersion
{
public int Major;
public int Minor;
public int Patch;
public DotNetVersionType Type;
public this()
{
this = default;
}
public this(int major, int minor, int patch, DotNetVersionType type)
{
Major = major;
Minor = minor;
Patch = patch;
Type = type;
}
public override void ToString(String outBuffer)
{
outBuffer.AppendF($"{Major}.{Minor}.{Patch}");
switch (Type)
{
case .Normal:
// Nothing to do.
case .Preview(int Number):
outBuffer.AppendF($" (Preview {Number})");
case .ReleaseCandidate(int Number):
outBuffer.AppendF($" (Release Candidate {Number})");
case .Unknown:
outBuffer.Append(" (Unknown release type)");
}
}
public static int operator <=>(DotNetVersion lhs, DotNetVersion rhs)
{
if (lhs.Major != rhs.Major)
if (lhs.Major > rhs.Major)
return 1;
else
return -1;
if (lhs.Minor != rhs.Minor)
if (lhs.Minor > rhs.Minor)
return 1;
else
return -1;
if (lhs.Patch != rhs.Patch)
if (lhs.Patch > rhs.Patch)
return 1;
else
return -1;
return lhs.Type.GetSortingOrder() <=> rhs.Type.GetSortingOrder();
}
}
+34 -21
View File
@@ -89,6 +89,9 @@ static class ScriptEngine
// This would probably require a separate small project that just handles the script-engine interface.
public const String ScriptCorePath = "Resources/Scripts/ScriptCore.dll";
/// The minimum supported .Net Version.
public const DotNetVersion MinDotNetVersion = .(10, 0, 0, .Normal);
private static Scene s_Context ~ _?.ReleaseRef();
private static EngineClasses _classes = new .() ~ delete _;
@@ -209,6 +212,22 @@ static class ScriptEngine
}
static bool _requestingReload = false;
static bool _assemblyWatcherSuspended = false;
public static void SuspendAssemblyWatcher()
{
Log.EngineLogger.Trace("Suspending assembly watching");
_assemblyWatcherSuspended = true;
_userAssemblyWatcher?.StopRaisingEvents();
}
public static void ResumeAssemblyWatcher()
{
Log.EngineLogger.Trace("Resuming assembly watching");
_assemblyWatcherSuspended = false;
_userAssemblyWatcher?.StartRaisingEvents();
}
static void InitAssemblyWatcher()
{
@@ -241,7 +260,8 @@ static class ScriptEngine
ReloadAssemblies(retainScriptData: true);
_requestingReload = false;
_userAssemblyWatcher.StartRaisingEvents();
if (_assemblyWatcherSuspended)
_userAssemblyWatcher.StartRaisingEvents();
return true;
});
@@ -249,7 +269,8 @@ static class ScriptEngine
});
}
_userAssemblyWatcher.StartRaisingEvents();
if (_assemblyWatcherSuspended)
_userAssemblyWatcher.StartRaisingEvents();
}
static void LoadScriptAssemblies()
@@ -353,8 +374,6 @@ static class ScriptEngine
if (script.Instance != null)
script.Instance = null;
script.ScriptClassName = null;
DestroyInstance(entityId);
}
@@ -434,26 +453,20 @@ static class ScriptEngine
LoadScriptAssemblies();
{
Debug.Profiler.ProfileScope!("Initialize Instances");
// We need to create a new instance for every entity
for (let (id, scriptInstance) in _entityScriptInstances)
{
if (Context.GetEntityByID(id) case .Ok(let entity))
{
ScriptComponent* script = entity.GetComponent<ScriptComponent>();
InitializeInstance(entity, script);
}
else
{
Log.EngineLogger.AssertDebug(false, "Entities script was just serialized but the entity doesn't exist anymore.");
}
}
}
if (retainScriptData)
{
if (Context != null)
{
Debug.Profiler.ProfileScope!("Initialize Instances");
// We need to create a new instance for every entity
for (let (ecsEntity, scriptComponent) in Context.GetEntities<ScriptComponent>())
{
InitializeInstance(Entity(ecsEntity, Context), scriptComponent);
}
}
contextSerializer.DeserializeScriptInstances();
}
+2 -9
View File
@@ -613,16 +613,9 @@ internal class EntityEditor
{
}
else if (fieldType.IsGenericType)
else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(List<>))
{
if (fieldType.GetGenericTypeDefinition() == typeof(List<>))
{
newValue = ShowListEditor(fieldType, reference, fieldName);
}
else
{
ImGui.TextColored(new Vector4(1, 0, 0, 1), $"{fieldName}: Type {fieldType} is not implemented.");
}
newValue = ShowListEditor(fieldType, reference, fieldName);
}
else if (fieldType.IsArray)
{
+5 -23
View File
@@ -176,6 +176,9 @@ public class SerializedObject
public void SerializeField(string fieldName, object? fieldValue, Type fieldType)
{
if (TryCustomSerializer(fieldName, fieldValue, fieldType))
return;
// Decimals are not actually primitives, but we treat them as if they were, because they are a built-in type
// and it makes more sense to send them over to the engine as a binary type than to serialize their underlying fields (which would happen when we treated them as a struct).
if (fieldType.IsPrimitive || fieldType == typeof(decimal))
@@ -202,38 +205,17 @@ public class SerializedObject
SerializeList(fieldName, fieldValue, fieldType, fieldType.GetElementType()!);
}
else if (fieldType.IsGenericType)
else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(List<>))
{
if (TryCustomSerializer(fieldName, fieldValue, fieldType))
return;
if (fieldType.GetGenericTypeDefinition() == typeof(List<>))
{
SerializeList(fieldName, fieldValue, fieldType, fieldType.GetGenericArguments()[0]);
}
//else if (fieldType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
//{
// ImGui.Text($"{fieldName} Dictionary");
//}
else
{
// TODO: what to do?
Log.Error($"Generic class serialization not yet implemented");
}
SerializeList(fieldName, fieldValue, fieldType, fieldType.GetGenericArguments()[0]);
}
else if (fieldType.IsValueType)
{
if (TryCustomSerializer(fieldName, fieldValue, fieldType))
return;
// Value Types cant be null
SerializeStruct(fieldName, fieldValue!, fieldType);
}
else if (fieldType.IsClass)
{
if (TryCustomSerializer(fieldName, fieldValue, fieldType))
return;
SerializeClass(fieldName, fieldValue, fieldType);
}
else