dotnet7 compat, DLSS, network manager rewrite and other fixes

This commit is contained in:
2023-01-27 16:24:11 +02:00
parent 36c09efac0
commit 51dcad2cc4
54 changed files with 767 additions and 821 deletions

1
.gitignore vendored
View File

@@ -23,3 +23,4 @@ Tests/obj/
Assets/desktop.ini
Assets/Maps/autosave/
Demos/
omnisharp.json

3
.gitmodules vendored
View File

@@ -1,3 +1,6 @@
[submodule "Plugins/FidelityFX-FSR"]
path = Plugins/FidelityFX-FSR
url = https://github.com/FlaxEngine/FidelityFX-FSR
[submodule "Plugins/DLSS"]
path = Plugins/DLSS
url = https://github.com/FlaxEngine/DLSS

View File

@@ -1,7 +1,7 @@
{
"ID": "3c7bc3854d42f9b1b0fea9ba0d7fa8e9",
"TypeName": "FlaxEditor.Content.Settings.GameSettings",
"EngineBuild": 6331,
"EngineBuild": 6335,
"Data": {
"ProductName": "Goake",
"CompanyName": "GoaLitiuM",
@@ -16,6 +16,7 @@
"Physics": "4bd8a4cc460399b5f1975fbe0a668e3f",
"Input": "8ec53dba4c238bfbea1d62922e612a4d",
"Graphics": "f94d5aae457aeba67033a8a4ca753214",
"Network": "0c69a0c7471f8d0805965caf343d2f27",
"Navigation": null,
"Localization": null,
"GameCooking": "af2e52554f7faed7b4937181dd22d166",

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -1,7 +1,7 @@
{
"ID": "194e05f445ece24ec5448d886e1334df",
"TypeName": "FlaxEngine.SceneAsset",
"EngineBuild": 6332,
"EngineBuild": 6335,
"Data": [
{
"ID": "194e05f445ece24ec5448d886e1334df",
@@ -55,7 +55,7 @@
}
},
"Data": {
"Text": "2133 tris\n 186 drawcalls\n60fps"
"Text": "3506 tris\n 358 drawcalls\n94fps"
}
},
{
@@ -73,12 +73,6 @@
"ParentID": "ff6b6db54b5aa08e7286ef86246149ef",
"Name": "SpeedWidget"
},
{
"ID": "9dc0648c43fc1553b23af188179c704f",
"TypeName": "Game.SpeedWidget",
"ParentID": "ebb8c92a4ff8ec3219a072b394accc0b",
"V": {}
},
{
"ID": "2fe5467d4e92726e24227cbcbcbd2844",
"TypeName": "FlaxEngine.UIControl",

View File

@@ -1,7 +1,7 @@
{
"ID": "f94d5aae457aeba67033a8a4ca753214",
"TypeName": "FlaxEditor.Content.Settings.GraphicsSettings",
"EngineBuild": 6332,
"EngineBuild": 6340,
"Data": {
"UseVSync": false,
"AAQuality": 3,
@@ -11,11 +11,13 @@
"ShadowsQuality": 3,
"ShadowMapsQuality": 3,
"AllowCSMBlending": true,
"DefaultProbeResolution": 128,
"UseHDRProbes": false,
"EnableGlobalSDF": true,
"GlobalSDFQuality": 2,
"GenerateSDFOnModelImport": true,
"GIQuality": 2,
"GIProbesSpacing": 300.0,
"GIQuality": 0,
"GIProbesSpacing": 500.0,
"GlobalSurfaceAtlasResolution": 2048,
"PostProcessSettings": {
"AO": {
@@ -37,7 +39,7 @@
"FallbackIrradiance": {
"R": 1.0,
"G": 0.0,
"B": 0.836574554,
"B": 0.83657455,
"A": 1.0
}
},
@@ -258,6 +260,7 @@
"SSR": {
"OverrideFlags": 1,
"Intensity": 0.0,
"TraceMode": 0,
"DepthResolution": 2,
"RayTracePassResolution": 2,
"BRDFBias": 0.82,

View File

@@ -1,7 +1,7 @@
{
"ID": "8ec53dba4c238bfbea1d62922e612a4d",
"TypeName": "FlaxEditor.Content.Settings.InputSettings",
"EngineBuild": 6331,
"EngineBuild": 6335,
"Data": {
"ActionMappings": [
{
@@ -85,7 +85,7 @@
"PositiveButton": 0,
"NegativeButton": 0,
"DeadZone": 0.0,
"Sensitivity": 0.022,
"Sensitivity": 0.11,
"Gravity": 1.0,
"Scale": 1.0,
"Snap": false
@@ -97,7 +97,7 @@
"PositiveButton": 0,
"NegativeButton": 0,
"DeadZone": 0.0,
"Sensitivity": 0.022,
"Sensitivity": 0.11,
"Gravity": 1.0,
"Scale": 1.0,
"Snap": false

View File

@@ -0,0 +1,13 @@
{
"ID": "0c69a0c7471f8d0805965caf343d2f27",
"TypeName": "FlaxEditor.Content.Settings.NetworkSettings",
"EngineBuild": 6335,
"Data": {
"MaxClients": 100,
"ProtocolVersion": 1,
"NetworkFPS": 60.0,
"Address": "127.0.0.1",
"Port": 59183,
"NetworkDriver": "FlaxEngine.Networking.ENetDriver"
}
}

Binary file not shown.

View File

@@ -1,5 +1,7 @@
// comment
r_shadows 1
r_lighting 0
r_shadows 0
r_lighting 1
cl_maxfps 0
r_upscaling 0
r_gi 0
r_staticbatch 0

View File

@@ -5,7 +5,8 @@
"gulp.autoDetect": "off",
"jake.autoDetect": "off",
"grunt.autoDetect": "off",
"omnisharp.defaultLaunchSolution": "GoakeFlax.sln"
"omnisharp.defaultLaunchSolution": "GoakeFlax.sln",
"omnisharp.useModernNet": true
},
"folders": [
{
@@ -14,7 +15,7 @@
},
{
"name": "Flax",
"path": "C:\\dev\\Flax\\Flax_master"
"path": "C:\\dev\\Flax\\FlaxEngine"
}
]
}

View File

@@ -8,19 +8,22 @@
"References": [
{
"Name": "$(EnginePath)/Flax.flaxproj"
},
{
"Name": "$(ProjectPath)/Plugins/FidelityFX-FSR/FidelityFX-FSR.flaxproj"
}
],
"DefaultScene": "194e05f445ece24ec5448d886e1334df",
"DefaultSceneSpawn": {
"Position": {
"X": 116.954315,
"Y": 144.595688,
"Y": 144.59569,
"Z": -33.48802
},
"Direction": {
"X": 0.253866524,
"X": 0.25386727,
"Y": -0.09813716,
"Z": -0.9622477
"Z": -0.9622475
}
},
"MinEngineVersion": "0.0.6194",

1
Plugins/DLSS Submodule

Submodule Plugins/DLSS added at 26b60f7cdc

View File

@@ -95,6 +95,25 @@ namespace Game
materialInstance.SetParameterValue("Input", texture);
materialInstance.SetParameterValue("Depth", texture2);
materialInstance.SetParameterValue("New parameter", true);
materialInstance.SetParameterValue("New parameter 0", ChannelMask.Blue);
materialInstance.SetParameterValue("New parameter 1", new Color(0.67f));
materialInstance.SetParameterValue("New parameter 3", 123f);
materialInstance.SetParameterValue("New parameter 4", new Float2(1,2));
materialInstance.SetParameterValue("New parameter 5", new Float3(1,2,3));
materialInstance.SetParameterValue("New parameter 6", new Float4(1,2,3,4));
materialInstance.SetParameterValue("New parameter 8", 123);
materialInstance.SetParameterValue("New parameter 9", new Matrix(0.666f));
materialInstance.SetParameterValue("New parameter 11", new Quaternion(0.5f, 0.5f, 0.5f, 0.5f));
materialInstance.SetParameterValue("New parameter 13", new Vector2(1,2));
materialInstance.SetParameterValue("New parameter 14", new Vector3(1,2,3));
materialInstance.SetParameterValue("New parameter 15", new Vector4(1,2,3,4));
//materialInstance.SetParameterValue("New parameter 16", new Transform(new Vector3(1,2,3), new Quaternion(0.5f, 0.5f, 0.5f, 0.5f)));
lastEnabled = true;
}

View File

@@ -13,7 +13,10 @@ namespace Game
{
Config config = new Config();
if (!File.Exists(path))
{
Console.Print($"Config file not found in path: {path}");
return config;
}
/*using*/ FileStream file = File.OpenRead(path);
/*using*/ StreamReader sr = new StreamReader(file);

View File

@@ -228,8 +228,12 @@ namespace Game
// Initializes the Console system.
internal void InitConsoleSubsystems()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
var assemblies = currentDomain.GetAssemblies();
//AppDomain currentDomain = AppDomain.CurrentDomain;
#if USE_NETCORE
var assemblies = Utils.GetAssemblies();
#else
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
#endif
foreach (Assembly assembly in assemblies)
{
@@ -490,7 +494,7 @@ namespace Game
if (value != null)
cvar.SetValue(value);
//if (!noOutput)
if (!noOutput)
Console.Print("'" + execute + "' is '" + cvar.GetValueString() + "'");
}
else

View File

@@ -29,7 +29,7 @@ namespace Game
public int ScrollMouseLines = 3;
public int ScrollOffset;
public bool SelectionAllowed = true;
private bool selectionActive;
public Color SelectionColor = new Color(0x00, 0x7A, 0xCC);
@@ -429,6 +429,9 @@ namespace Game
public override bool OnKeyDown(KeyboardKeys key)
{
if (!SelectionAllowed)
return false;
bool shiftDown = Root.GetKey(KeyboardKeys.Shift);
bool ctrlDown = Root.GetKey(KeyboardKeys.Control);
@@ -462,6 +465,9 @@ namespace Game
public override bool OnMouseWheel(Float2 location, float delta)
{
if (!SelectionAllowed)
return false;
if (delta < 0)
{
ScrollOffset -= ScrollMouseLines;
@@ -481,6 +487,9 @@ namespace Game
public override bool OnMouseDown(Float2 location, MouseButton button)
{
if (!SelectionAllowed)
return false;
bool ret = false;
if (button == MouseButton.Left && !IsFocused)
{
@@ -527,6 +536,9 @@ namespace Game
public override void OnMouseMove(Float2 location)
{
if (!SelectionAllowed)
return;
if (selectionActive)
if (HitTestText(location, out int hitLine, out int hitChar))
{
@@ -539,6 +551,9 @@ namespace Game
/// <inheritdoc />
public override bool OnMouseUp(Float2 location, MouseButton button)
{
if (!SelectionAllowed)
return false;
if (button == MouseButton.Left)
{
OnSelectingEnd();
@@ -553,6 +568,9 @@ namespace Game
{
base.OnMouseLeave();
if (!SelectionAllowed)
return;
if (selectionActive)
{
OnSelectingEnd();

View File

@@ -134,6 +134,11 @@ namespace Game
if (key == KeyboardKeys.PageUp || key == KeyboardKeys.PageDown)
return contentBox.OnKeyDown(key);
#if FLAX_EDITOR
if (key == KeyboardKeys.F5)
return false;
#endif
return base.OnKeyDown(key);
}

View File

@@ -1,13 +1,58 @@
using System;
using FlaxEngine;
using Console = Game.Console;
using System.Linq;
#if FLAX_EDITOR
using FlaxEditor;
#endif
namespace Game
{
public class ConsolePlugin : GGamePlugin
public class ConsolePlugin : GamePlugin
{
public ConsolePlugin()
{
#if FLAX_EDITOR
_description = ConsoleEditorPlugin.DescriptionInternal;
#endif
}
public override void Initialize()
{
//FlaxEngine.Debug.Log("ConsolePlugin initialized");
Console.Init();
//AssetManager.Init(); // TODO: move these elsewhere
#if !FLAX_EDITOR
Level.SceneLoaded += OnSceneLoaded;
#endif
}
public override void Deinitialize()
{
#if !FLAX_EDITOR
Level.SceneLoaded -= OnSceneLoaded;
#endif
}
private void OnSceneLoaded(Scene scene, Guid guid)
{
Level.SceneLoaded -= OnSceneLoaded;
LoadConfig();
}
private void LoadConfig()
{
Console.Print("Loading config file (GamePlugin)");
AssetManager.Globals.ResetValues();
foreach (var line in AssetManager.Config.GetLines())
Console.Execute(line, false, true);
}
}
#if FLAX_EDITOR
public class ConsoleEditorPlugin : EditorPlugin
{
public static PluginDescription DescriptionInternal = new PluginDescription
{
@@ -19,49 +64,25 @@ namespace Game
Category = "Game"
};
public override void Init()
{
//FlaxEngine.Debug.Log("ConsolePlugin initialized");
Console.Init();
AssetManager.Init(); // TODO: move these elsewhere
//Level.SceneLoaded += LoadConfig;
}
public override void Deinit()
{
//Level.SceneLoaded -= LoadConfig;
}
private void LoadConfig(Scene scene, Guid guid)
{
Console.Print("Loading config file");
AssetManager.Globals.ResetValues();
foreach (var line in AssetManager.Config.GetLines())
Console.Execute(line, false, true);
}
}
#if FLAX_EDITOR
public class ConsoleEditorPlugin : GEditorPlugin
{
public override Type GamePluginType => typeof(ConsolePlugin);
public ConsoleEditorPlugin()
{
_description = ConsolePlugin.DescriptionInternal;
_description = DescriptionInternal;
}
public override void Init()
public override void Initialize()
{
//FlaxEngine.Debug.Log("ConsolePlugin initialized");
Console.Init();
AssetManager.Init();
//AssetManager.Init();
Level.SceneLoaded += LoadConfig;
Level.SceneLoaded += OnSceneLoaded;
FlaxEditor.Editor.Instance.PlayModeBegin += OnPlayModeBegin;
FlaxEditor.Editor.Instance.PlayModeEnd += OnPlayModeEnd;
//Scripting.Exit += OnScriptingExit;
/*AssetManager.Init(); // TODO: move these elsewhere
AssetManager.Globals.ResetValues();
@@ -70,20 +91,51 @@ namespace Game
Console.Execute(line, false, true);*/
}
public override void Deinit()
/*private void OnScriptingExit()
{
Level.SceneLoaded -= LoadConfig;
FlaxEditor.Editor.Instance.PlayModeBegin -= OnPlayModeBegin;
FlaxEditor.Editor.Instance.PlayModeEnd -= OnPlayModeEnd;
}*/
private void OnPlayModeBegin()
{
//FlaxEditor.Editor.Instance.PlayModeBegin -= Instance_PlayModeBegin;
LoadConfig();
GameMode.StartServer(true);
}
private void LoadConfig(Scene scene, Guid guid)
private void OnPlayModeEnd()
{
Console.Print("Loading config file");
GameMode.StopServer();
}
public override void Deinitialize()
{
Level.SceneLoaded -= OnSceneLoaded;
Level.SceneLoaded -= OnSceneLoaded;
if (FlaxEditor.Editor.Instance != null)
{
FlaxEditor.Editor.Instance.PlayModeBegin -= OnPlayModeBegin;
FlaxEditor.Editor.Instance.PlayModeEnd -= OnPlayModeEnd;
}
}
private void OnSceneLoaded(Scene scene, Guid guid)
{
Level.SceneLoaded -= OnSceneLoaded;
Level.SceneLoaded -= OnSceneLoaded;
LoadConfig();
}
private void LoadConfig()
{
Console.Print("Loading config file (EditorPlugin)");
AssetManager.Globals.ResetValues();
foreach (var line in AssetManager.Config.GetLines())
Console.Execute(line, false, true);
}
}
}
#endif
}

View File

@@ -24,7 +24,7 @@ namespace Game
internal InputEvent consoleInputEvent;
private ConsoleContentTextBox consoleNotifyBox;
[Limit(0)] public int ConsoleNotifyLines = 3;
[Limit(0)] public int ConsoleNotifyLines = 15;
[Limit(0f)] public float ConsoleSpeed = 3500f;
@@ -108,6 +108,7 @@ namespace Game
consoleNotifyBox.BackgroundSelectedFlashSpeed = 0;
consoleNotifyBox.BorderSelectedColor = Color.Transparent;
consoleNotifyBox.CaretFlashSpeed = 0;
consoleNotifyBox.SelectionAllowed = false;
}
Float2 locationFix2 = consoleNotifyBox.Location;

View File

@@ -1,16 +1,48 @@
using System;
using System.IO;
using System.Linq;
//using FidelityFX;
using FidelityFX;
#if COMPILE_WITH_DLSS
using NVIDIA;
#endif
using FlaxEditor.Content.Settings;
using FlaxEngine;
namespace Game
{
public enum UpscalingMode
{
None,
DLSS,
FSR1,
}
// Holds Console variables and commands to control engine behaviour
public static class EngineSubsystem
{
//private static FSR _fsrPlugin;
private static FSR _fsrPlugin;
public static FSR FsrPlugin
{
get
{
if (_fsrPlugin == null)
_fsrPlugin = PluginManager.GetPlugin<FSR>();
return _fsrPlugin;
}
}
#if COMPILE_WITH_DLSS
private static DLSS _dlssPlugin;
public static DLSS DlssPlugin
{
get
{
if (_dlssPlugin == null)
_dlssPlugin = PluginManager.GetPlugin<DLSS>();
return _dlssPlugin;
}
}
#endif
// TODO: this should manually set all postprocessing values to 0 or disabled
/*[ConsoleVariable("r_postprocessing")]
@@ -98,30 +130,122 @@ namespace Game
}
}
/*public static FSR FsrPlugin
private static UpscalingMode GetUpscalingMode()
{
return (UpscalingMode)int.Parse(Upscaling);
}
[ConsoleVariable("r_upscaling")]
public static string Upscaling
{
get
{
if (_fsrPlugin == null)
_fsrPlugin = PluginManager.GetPlugin<FSR>();
return _fsrPlugin;
#if COMPILE_WITH_DLSS
if (DlssPlugin.PostFx?.Enabled ?? false)
return ((int)UpscalingMode.DLSS).ToString();
#else
if (false) { }
#endif
else if (FsrPlugin.PostFx?.Enabled ?? false)
return ((int)UpscalingMode.FSR1).ToString();
else
return ((int)UpscalingMode.None).ToString();
}
set
{
if (int.TryParse(value, out int intValue))
{
UpscalingMode upscaling = (UpscalingMode)intValue;
#if COMPILE_WITH_DLSS
if (DlssPlugin.PostFx != null)
{
if (upscaling == UpscalingMode.DLSS)
{
if (DlssPlugin.Support == DLSSSupport.Supported)
DlssPlugin.PostFx.Enabled = true;
else
{
DlssPlugin.PostFx.Enabled = false;
Console.Print("DLSS not supported");
}
}
else
DlssPlugin.PostFx.Enabled = false;
}
#else
if (upscaling == UpscalingMode.DLSS)
{
Console.Print("DLSS not supported: compiled without COMPILE_WITH_DLSS");
upscaling = UpscalingMode.None;
}
#endif
if (FsrPlugin.PostFx != null)
FsrPlugin.PostFx.Enabled = upscaling == UpscalingMode.FSR1;
}
}
}
// TODO: r_upscaling
[ConsoleVariable("r_fsr_enabled")]
public static string FsrEnabled
#if !COMPILE_WITH_DLSS
private static float dummy_DlssSharpness;
private static int dummy_DlssQuality;
#endif
[ConsoleVariable("r_dlss_sharpness")]
public static string DlssSharpness
{
get => FsrPlugin.PostFx.Enabled ? "1" : "0";
get
{
#if COMPILE_WITH_DLSS
return DlssPlugin.Sharpness.ToString();
#else
return dummy_DlssSharpness.ToString();
#endif
}
set
{
bool boolValue = false;
if (int.TryParse(value, out int intValue))
boolValue = intValue != 0;
else if (float.TryParse(value, out float valueFloat))
boolValue = valueFloat != 0f;
if (float.TryParse(value, out float valueFloat))
{
valueFloat = Mathf.Clamp(valueFloat, -1f, 1f);
#if COMPILE_WITH_DLSS
DlssPlugin.Sharpness = valueFloat;
#else
dummy_DlssSharpness = valueFloat;
#endif
}
}
}
FsrPlugin.PostFx.Enabled = boolValue;
[ConsoleVariable("r_dlss_quality")]
public static string DlssQuality
{
get
{
#if COMPILE_WITH_DLSS
return ((int)DlssPlugin.Quality).ToString();
#else
return dummy_DlssQuality.ToString();
#endif
}
set
{
if (int.TryParse(value, out int intValue))
{
#if COMPILE_WITH_DLSS
#if USE_NETCORE
intValue = Math.Clamp(intValue, 0, (int)DLSSQuality.MAX-1);
#else
intValue = (intValue > (int)DLSSQuality.MAX-1) ? ((int)DLSSQuality.MAX-1) : (intValue < 0 ? 0 : intValue);
#endif
DlssPlugin.Quality = (DLSSQuality)intValue;
#else
//intValue = Math.Clamp(intValue, 0, 4);
intValue = (intValue > 4) ? 4 : (intValue < 0 ? 0 : intValue);
dummy_DlssQuality = intValue;
#endif
}
}
}
@@ -143,7 +267,6 @@ namespace Game
}
}
}
*/
[ConsoleVariable("cl_showweapon")]
public static string ShowWeapon
@@ -204,8 +327,8 @@ namespace Game
boolValue = valueFloat != 0f;
AssetManager.Globals.SetValue("Scene Lighting", boolValue);
AmbientOcclusion = value;
GlobalIllumination = value;
//AmbientOcclusion = value;
//GlobalIllumination = value;
}
}
@@ -378,7 +501,7 @@ namespace Game
{
get
{
return ((bool)AssetManager.Globals.GetValue("Scene Shadows") ? "1" : "0");
return (bool)AssetManager.Globals.GetValue("Scene Shadows") ? "1" : "0";
}
set
{
@@ -392,6 +515,25 @@ namespace Game
}
}
[ConsoleVariable("r_staticbatch")]
public static string StaticBatch
{
get
{
return (bool)AssetManager.Globals.GetValue("Static Batching") ? "1" : "0";
}
set
{
bool boolValue = false;
if (int.TryParse(value, out int intValue))
boolValue = intValue != 0;
else if (float.TryParse(value, out float valueFloat))
boolValue = valueFloat != 0f;
AssetManager.Globals.SetValue("Static Batching", boolValue);
}
}
[ConsoleCommand("playdemo")]
public static void PlayDemoCommand(string[] text)
{
@@ -402,8 +544,8 @@ namespace Game
if (!demoName.EndsWith(".gdem"))
demoName += ".gdem";
PlayerActor playerActor = Level.GetActors<PlayerActor>().First(x =>
x.GetScript<PlayerMovement>().PlayerId == NetworkManager.LocalPlayerClientId);
PlayerActor playerActor = Level.GetActors<PlayerActor>().First(/*x =>
x.GetScript<PlayerMovement>().PlayerId == NetworkManager.LocalPlayerClientId*/);
string demoPath = Path.Combine(AssetManager.DemoPath, demoName);
if (File.Exists(demoPath))
@@ -427,8 +569,8 @@ namespace Game
if (!demoName.EndsWith(".gdem"))
demoName += ".gdem";
PlayerActor playerActor = Level.GetActors<PlayerActor>().First(x =>
x.GetScript<PlayerMovement>().PlayerId == NetworkManager.LocalPlayerClientId);
PlayerActor playerActor = Level.GetActors<PlayerActor>().First(/*x =>
x.GetScript<PlayerMovement>().PlayerId == NetworkManager.LocalPlayerClientId*/);
var playerMovement = playerActor.GetScript<PlayerMovement>();
string demoPath = Path.Combine(AssetManager.DemoPath, demoName);
@@ -465,6 +607,19 @@ namespace Game
Scripting.Update += TimeDemoOnUpdate;
}
[ConsoleCommand("map")]
public static void MapCommand()
{
//NetworkManager.StartServer(true);
GameMode.StartServer(true);
}
[ConsoleCommand("connect")]
public static void ConnectCommand()
{
GameMode.Connect();
}
[ConsoleSubsystemInitializer]
public static void Initialize()
{

View File

@@ -1,8 +1,11 @@
//#define COMPILE_WITH_DLSS
using Flax.Build;
using Flax.Build.NativeCpp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
public class Game : GameModule
{
@@ -13,7 +16,7 @@ public class Game : GameModule
// C#-only scripting
BuildCSharp = true;
BuildNativeCode = true;
//BuildNativeCode = true;
}
/// <inheritdoc />
@@ -25,7 +28,14 @@ public class Game : GameModule
base.Setup(options);
options.PublicDependencies.Add("FidelityFXFSR");
options.PrivateDependencies.Add("FidelityFXFSR");
//options.ScriptingAPI.FileReferences.Add(Path.Combine(Globals.EngineRoot, "Source", "Platforms", "DotNet", "Newtonsoft.Json.dll"));
#if COMPILE_WITH_DLSS
DLSS.ConditionalImport(options, options.PrivateDependencies);
options.PrivateDefinitions.Add("COMPILE_WITH_DLSS");
#endif
// Here you can modify the build options for your game module
// To reference another module use: options.PublicDependencies.Add("Audio");
// To add C++ define use: options.PublicDefinitions.Add("COMPILE_WITH_FLAX");

View File

@@ -1,6 +1,221 @@
namespace Game
using FlaxEditor.Content.Settings;
using FlaxEngine;
using FlaxEngine.Networking;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Game
{
public abstract class GameMode
/// <summary>
/// The game mode logic that only exists on server.
/// </summary>
public class GameMode
{
private static GameMode currentGameMode = null;
private static bool ServerRunning => currentGameMode != null;
public const string DefaultServerAddress = "localhost";
public const ushort DefaultServerPort = 59183;
public string ServerAddress = DefaultServerAddress;
public ushort ServerPort = DefaultServerPort;
private Dictionary<uint, PlayerActor> players = new Dictionary<uint, PlayerActor>();
public static bool Connect(string ip = null, ushort port = 0)
{
if (ServerRunning)
NetworkManager_Cleanup();
var networkSettings = GameSettings.Load<NetworkSettings>();
networkSettings.Address = ip ?? DefaultServerAddress;
networkSettings.Port = port != 0 ? port : DefaultServerPort;
GameSettings.LoadAsset<NetworkSettings>().SetInstance(networkSettings);
if (NetworkManager.StartClient())
{
Console.PrintError("Server connection failed.");
return false;
}
Console.Print($"Connecting to {networkSettings.Address}:{networkSettings.Port}...");
return true;
}
public static bool StartServer(bool listenServer)
{
if (ServerRunning)
NetworkManager_Cleanup();
var networkSettings = GameSettings.Load<NetworkSettings>();
currentGameMode = new GameMode()
{
ServerAddress = "localhost",
ServerPort = networkSettings.Port,
};
Console.Print("Starting server... port: " + networkSettings.Port);
#if FLAX_EDITOR
FlaxEditor.Editor.Instance.PlayModeEnd += NetworkManager_Cleanup;
#else
#endif
NetworkManager.ClientConnected += NetworkManager_ClientConnected;
NetworkManager.ClientConnecting += NetworkManager_ClientConnecting;
NetworkManager.StateChanged += NetworkManager_StateChanged;
bool failure;
if (listenServer)
failure = NetworkManager.StartHost();
else
failure = NetworkManager.StartServer();
if (failure)
{
Console.PrintError("Server startup failed.");
return false;
}
currentGameMode.Start();
return true;
}
public static void StopServer()
{
if (ServerRunning)
NetworkManager_Cleanup();
}
private static void NetworkManager_Cleanup()
{
if (ServerRunning)
{
NetworkManager.ClientConnected -= NetworkManager_ClientConnected;
NetworkManager.ClientConnecting -= NetworkManager_ClientConnecting;
NetworkManager.StateChanged -= NetworkManager_StateChanged;
#if FLAX_EDITOR
FlaxEditor.Editor.Instance.PlayModeEnd -= NetworkManager_Cleanup;
#else
#endif
currentGameMode = null;
}
}
private static void NetworkManager_StateChanged()
{
Console.Print("network manager state changed: " + NetworkManager.State.ToString());
}
private static void NetworkManager_ClientConnected(NetworkClient networkClient)
{
Console.Print("new client connected");
currentGameMode.OnPlayerSpawn(networkClient.ClientId);
}
private static void NetworkManager_ClientConnecting(ref NetworkClientConnectionData arg0)
{
Console.Print("new client is connecting");
bool allowConnection = true;
arg0.Result = allowConnection ? 0 : 1;
}
public void Start()
{
// When mode is started
}
public void Tick()
{
// Run on every frame
}
public void End()
{
// When win condition is met
}
public void OnClientConnect()
{
}
public void OnClientDisconnect()
{
}
public void OnClientKill()
{
}
public bool OnJoin()
{
return true;
}
public bool OnSpectate()
{
return true;
}
public bool OnPlayerRequestRespawn()
{
return true;
}
public void OnPlayerSpawn(uint clientId)
{
// Get random spawn
var spawns = Level.GetActors<Actor>().Where(x => x.Name.StartsWith("PlayerSpawn_")).ToArray();
Console.Print($"found {spawns.Length} spawns");
var randomSpawn = spawns.First();
Float3 spawnPosition = randomSpawn.Position + new Float3(0f, 4.1f, 0f);
Float3 spawnAngles = randomSpawn.Orientation.EulerAngles;
// Create player actor
string prefabPath = Path.Combine(AssetManager.ContentPath, "Common");
var playerPrefab = Content.Load<Prefab>(Path.Combine(prefabPath, "PlayerPrefab.prefab"));
if (playerPrefab == null)
Console.PrintError("GameModeManager: Failed to find PlayerPrefab");
PlayerActor playerActor = PrefabManager.SpawnPrefab(playerPrefab).As<PlayerActor>();
playerActor.Initialize(clientId);
playerActor.Teleport(spawnPosition, spawnAngles);
}
public void OnPlayerInit()
{
}
public void OnPlayerDeath()
{
}
public void OnPlayerTakeDamage(/*entity player, float damage, entity source*/)
{
}
public Float3 OnPlayerApplyForce(/*entity player, vector force, entity source*/)
{
return Float3.Zero;
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
#if false
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -407,4 +408,5 @@ namespace Game
playerActor.UpdateNetworkInput(inputState);
}
}
}
}
#endif

View File

@@ -51,12 +51,14 @@ namespace Game
public bool importLights = false;
private bool generateSdf = true;
private bool childModelSdf = true;
private Model model;
private MaterialBase missingMaterial;
private bool resetLights = false;
private bool dirtyLights = false;
private bool dirtyMap = false;
private float brightnessMultiplier_ = 0.82f;
private float lightRadiusMultiplier_ = 9.45f;
@@ -110,9 +112,8 @@ namespace Game
if (staticBatching_ == value)
return;
staticBatching_ = value;
FlaxEngine.Debug.Log("StaticBatching changed, reloading map");
LoadMap(true);
dirtyLights = true;
dirtyMap = true;
}
}
@@ -264,7 +265,7 @@ namespace Game
{
try
{
if (worldSpawnActor != null)
if (worldSpawnActor)
worldSpawnActor.HideFlags &= ~HideFlags.DontSave;
}
catch (Exception e)
@@ -277,7 +278,7 @@ namespace Game
{
try
{
if (worldSpawnActor != null)
if (worldSpawnActor)
worldSpawnActor.HideFlags |= HideFlags.DontSave;
dirtyLights = true;
}
@@ -295,37 +296,60 @@ namespace Game
public override void OnDisable()
{
if (Editor.Instance == null)
return;
Editor.Instance.PlayModeBeginning -= OnEditorPlayModeStart;
Editor.Instance.PlayModeEnd -= OnEditorPlayModeEnd;
}
#endif
public override void OnStart()
{
sceneLighting = lastSceneLighting = EngineSubsystem.SceneLighting == "1";
sceneShadows = lastSceneShadows = EngineSubsystem.SceneShadows == "1";
staticBatching = lastStaticBatching = EngineSubsystem.StaticBatch == "1";
globalIllumination = EngineSubsystem.GlobalIllumination == "1";
LoadMap(false);
}
private List<BrushGeometry> brushGeometries;
private bool lastSceneLighting = false;
private bool lastSceneShadows = false;
private bool lastStaticBatching = false;
private bool lastGlobalIllumination = false;
private bool sceneLighting = false;
private bool sceneShadows = false;
private bool staticBatching = false;
private bool globalIllumination = false;
public override void OnUpdate()
{
bool sceneLighting = EngineSubsystem.SceneLighting == "1";
sceneLighting = EngineSubsystem.SceneLighting == "1";
if (lastSceneLighting != sceneLighting)
{
lastSceneLighting = sceneLighting;
dirtyLights = true;
}
bool sceneShadows = EngineSubsystem.SceneShadows == "1";
sceneShadows = EngineSubsystem.SceneShadows == "1";
if (lastSceneShadows != sceneShadows)
{
lastSceneShadows = sceneShadows;
dirtyLights = true;
}
staticBatching = EngineSubsystem.StaticBatch == "1";
if (lastStaticBatching != staticBatching)
{
lastStaticBatching = staticBatching;
StaticBatching = staticBatching;
}
globalIllumination = EngineSubsystem.GlobalIllumination == "1";
if (lastGlobalIllumination != globalIllumination)
{
lastGlobalIllumination = globalIllumination;
dirtyMap = true;
}
if (resetLights)
{
Debug.Log("reset lights");
if (worldSpawnActor == null || !worldSpawnActor || root == null)
{
Debug.Log("worldspawn or root is null");
@@ -351,6 +375,13 @@ namespace Game
resetLights = false;
}
if (dirtyMap)
{
dirtyMap = false;
FlaxEngine.Debug.Log("StaticBatching changed, reloading map");
LoadMap(true);
}
if (dirtyLights)
{
foreach (var light in worldSpawnActor.GetChildren<Light>())
@@ -487,7 +518,7 @@ namespace Game
else
{
// TODO: engine doesn't seem to always load the asset even though it exists, bug? seems to happen at low framerate
//Console.Print("Material '" + textureName + "' not found for brush, assetPath: " + assetPath);
Console.Print("Material '" + textureName + "' not found for brush, assetPath: " + assetPath);
materials.Add(textureName, missingMaterial);
brushMaterial = missingMaterial;
}
@@ -654,6 +685,7 @@ namespace Game
childModel.Name = "Brush_" + brushIndex;
childModel.Model = geom.model;
childModel.Position = geom.offset;
//childModel.DrawModes = DrawPass.None;
for (int i = 0; i < geom.meshes.Length; i++)
childModel.SetMaterial(i, geom.meshes[i].material);
@@ -664,9 +696,6 @@ namespace Game
for (uint i = 0; i < indices.Length; i++)
indices[i] = i;
if (brushIndex == 84)
brushIndex = brushIndex;
bool isClipMaterial = false;
bool isMissingMaterial = false;
if (geom.meshes.Length == 1)
@@ -728,7 +757,16 @@ namespace Game
brushIndex = 0;
foreach (BrushGeometry geom in brushGeometries)
{
Actor childModel = worldSpawnActor.AddChild<EmptyActor>();
Actor childModel;
if (childModelSdf)
{
StaticModel staticModel = worldSpawnActor.AddChild<StaticModel>();
staticModel.DrawModes = DrawPass.GlobalSDF | DrawPass.GlobalSurfaceAtlas;
staticModel.Model = geom.model;
childModel = staticModel;
}
else
childModel = worldSpawnActor.AddChild<EmptyActor>();
childModel.Name = "Brush_" + brushIndex;
//childModel.Model = geom.model;
childModel.Position = geom.offset;
@@ -768,8 +806,8 @@ namespace Game
childModel.Entries = entries;
}*/
//if (!isClipMaterial && !isMissingMaterial)
// sdfModels.Add(geom.model);
if (childModelSdf && !isClipMaterial && !isMissingMaterial)
sdfModels.Add(geom.model);
CollisionData collisionData = Content.CreateVirtualAsset<CollisionData>();
if (collisionData.CookCollision(
@@ -879,7 +917,8 @@ namespace Game
childModel.Model = batchModel;
//childModel.Position = geom.offset;
sdfModels.Add(batchModel);
if (!childModelSdf)
sdfModels.Add(batchModel);
}
}
@@ -1017,6 +1056,7 @@ namespace Game
StaticModel childModel = worldSpawnActor.AddChild<StaticModel>();
childModel.Name = "MapModel";
childModel.Model = model;
//childModel.DrawModes = DrawPass.None;
//childModel.SetMaterial(0, missingMaterial);
string matBasePath = Path.Combine(AssetManager.ContentPath, "Materials");
@@ -1063,15 +1103,24 @@ namespace Game
}
for (int i=0; i<10000; i++)
{
Debug.Log($"{i} udfghjosa fuhoag guiha7 2382835yayhahn0 generate:{generateSdf}, GI:{Graphics.PostProcessSettings.GlobalIllumination.Mode != GlobalIlluminationMode.None}, {sdfModels.Count}");
}
//Debug.Log($"generate:{generateSdf}, GI:{Graphics.PostProcessSettings.GlobalIllumination.Mode != GlobalIlluminationMode.None}, {sdfModels.Count}");
if (generateSdf /*&& Graphics.PostProcessSettings.GlobalIllumination.Mode != GlobalIlluminationMode.None*/ && sdfModels.Count > 1)
if (generateSdf && globalIllumination /*&& Graphics.PostProcessSettings.GlobalIllumination.Mode != GlobalIlluminationMode.None*/ && sdfModels.Count > 1)
{
int modelIndex = 0;
// TODO: read sdf data from texture and dump it to file, and reuse it when generating sdf data
/*using*/ var sha1 = new SHA1Managed();
#if USE_NETCORE
string mapHash = SHA1.HashData(Encoding.UTF8.GetBytes(levelScript.MapName + levelScript.MapTimestamp.Ticks.ToString())).ToString();
#else
/*using*/
var sha1 = new SHA1Managed();
string mapHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(levelScript.MapName + levelScript.MapTimestamp.Ticks.ToString())).ToString();
#endif
foreach (var model in sdfModels.ToList())
{
@@ -1098,7 +1147,27 @@ namespace Game
ModelBase.SDFData sdfData = new ModelBase.SDFData();
sdfData.Texture
sdfData.Texture = GPUDevice.Instance.CreateTexture(sdfDataPath);
if (sdfData.Texture.Init(new GPUTextureDescription() { Width = width, Height = height, Depth = depth, Format = format, Flags = GPUTextureFlags.ShaderResource, MipLevels = mips}))
Console.PrintError($"Failed to create SDF texture for {sdfDataPath}");
sdfData.LocalToUVWMul = LocalToUVWMul;
sdfData.LocalToUVWAdd = LocalToUVWAdd;
sdfData.WorldUnitsPerVoxel = WorldUnitsPerVoxel;
sdfData.MaxDistance = MaxDistance;
sdfData.LocalBoundsMin = LocalBoundsMin;
sdfData.LocalBoundsMax = LocalBoundsMax;
sdfData.ResolutionScale = ResolutionScale;
sdfData.LOD = LOD;
for (int mipLevel = 0; mipLevel < mips; mipLevel++)
{
}
//sdfData.Texture
//sdfData.Texture
model.SetSDF(sdfData);
}*/
@@ -1110,11 +1179,12 @@ namespace Game
{
Stopwatch sw2 = Stopwatch.StartNew();
FlaxEngine.Debug.Log($"Generating level SDF ({sdfModels.Count} models)...");
Console.Print($"Generating level SDF ({sdfModels.Count} models)...");
ParallelOptions opts = new ParallelOptions();
FlaxEngine.Debug.Log("processorcount: " + Environment.ProcessorCount);
float backfacesThreshold = 0.15f;
if (useStaticBatching)
if (useStaticBatching && !childModelSdf)
{
opts.MaxDegreeOfParallelism = 2; //Environment.ProcessorCount / 2;
//backfacesThreshold = 1f;
@@ -1143,7 +1213,9 @@ namespace Game
});
sw2.Stop();
FlaxEngine.Debug.Log($"Generated level SDF in {sw2.Elapsed.TotalMilliseconds}ms");
Console.Print($"Generated level SDF in {sw2.Elapsed.TotalMilliseconds}ms");
});
}
}
@@ -1179,6 +1251,7 @@ namespace Game
light.Name = "SpotLight_" + lightIndex;
else
light.Name = "Light_" + lightIndex;
light.IsActive = sceneLighting;
light.LocalPosition = ParseOrigin(entity.properties["origin"]);
if (lightTargetPosition.HasValue)
@@ -1205,13 +1278,13 @@ namespace Game
{
pointLight.UseInverseSquaredFalloff = false;
pointLight.FallOffExponent = 8;
pointLight.ShadowsStrength = castShadows ? 1.0f : 0.0f;
pointLight.ShadowsStrength = sceneShadows && castShadows ? 1.0f : 0.0f;
}
if (spotLight != null)
{
spotLight.UseInverseSquaredFalloff = false;
spotLight.FallOffExponent = 8;
spotLight.ShadowsStrength = castShadows ? 1.0f : 0.0f;
spotLight.ShadowsStrength = sceneShadows && castShadows ? 1.0f : 0.0f;
spotLight.InnerConeAngle = 65f;
spotLight.OuterConeAngle = 80f;
}

View File

@@ -1,149 +0,0 @@
using System;
using System.Linq;
using FlaxEditor;
using FlaxEngine;
using FlaxEngine.Networking;
using Console = Game.Console;
namespace Game
{
[AttributeUsage(AttributeTargets.Class)]
public class NetworkPredictedAttribute : Attribute
{
}
// TODO: insert code to update variables with this attribute?
// rename to NetworkReplicatedAttribute?
[AttributeUsage(AttributeTargets.Class)]
public class NetworkedAttribute : Attribute
{
}
// NetworkMulticastAttribute: calls methods marked with this in all clients
public enum NetworkMessageType : byte
{
Handshake = 1,
Message
}
public static partial class NetworkManager
{
public delegate bool OnMessageDecl(ref NetworkEvent networkEvent);
private static bool initialized;
public static NetworkPeer server;
public static NetworkPeer client;
private static readonly ushort ServerPort = 59183;
private static string ServerAddress;
private static readonly ushort MTU = 1500;
private static readonly ushort MaximumClients = 32;
public static OnMessageDecl OnMessage;
public static bool IsServer = false;
public static bool IsClient = false;
public static bool IsLocalClient = false; // Context dependant, true when message is handled by local client
public static void Init()
{
if (initialized)
return;
/*if (Engine.CommandLine.Contains("-server"))
{
StartServer();
ServerAddress = "localhost";
ConnectServer();
}
else if (Engine.CommandLine.Contains("-client"))
{
ServerAddress = "localhost";
ConnectServer();
}
//#if FLAX_EDITOR
else
{
StartServer();
ServerAddress = "localhost";
ConnectServer();
}*/
//#endif
initialized = true;
#if FLAX_EDITOR
Editor.Instance.PlayModeEnd += Cleanup;
#endif
GameModeManager.Init(); // FIXME
}
public static void Cleanup()
{
if (server != null)
{
Scripting.FixedUpdate -= OnServerUpdate;
Scripting.Exit -= Cleanup;
Level.ActorSpawned -= OnServerActorSpawned;
NetworkPeer.ShutdownPeer(server);
server = null;
}
if (client != null)
{
Scripting.FixedUpdate -= OnClientUpdate;
Scripting.Exit -= Cleanup;
Level.ActorSpawned -= OnClientActorSpawned;
NetworkPeer.ShutdownPeer(client);
client = null;
}
#if FLAX_EDITOR
Editor.Instance.PlayModeEnd -= Cleanup;
GameModeManager.Cleanup(); // FIXME
#endif
initialized = false;
}
private static void OnNetworkMessage(ref NetworkEvent networkEvent)
{
byte messageTypeByte = networkEvent.Message.ReadByte();
if (!Enum.IsDefined(typeof(NetworkMessageType), messageTypeByte))
{
Console.PrintError($"Unsupported message type received from client: {messageTypeByte}");
return;
}
NetworkMessageType messageType = (NetworkMessageType)messageTypeByte;
switch (messageType)
{
case NetworkMessageType.Handshake:
{
string message = networkEvent.Message.ReadString();
Console.Print($"Received handshake from {networkEvent.Sender.ConnectionId}, msg: " + message);
break;
}
case NetworkMessageType.Message:
{
if (OnMessage != null)
foreach (OnMessageDecl func in OnMessage.GetInvocationList()
.Cast<OnMessageDecl>().ToArray())
{
bool ret = func.Invoke(ref networkEvent);
if (ret)
break;
}
break;
}
default:
Console.PrintError($"Unsupported message type received from client: {messageTypeByte}");
break;
}
}
}
}

View File

@@ -1,64 +0,0 @@
using System;
using FlaxEngine;
using Console = Game.Console;
#if FLAX_EDITOR
using System.Diagnostics;
using FlaxEditor;
#endif
namespace Game
{
public class NetworkManagerPlugin : GGamePlugin
{
public override Type[] PluginDependencies { get => new Type[] { typeof(ConsolePlugin) }; }
public static PluginDescription DescriptionInternal = new PluginDescription
{
Author = "Ari Vuollet",
Name = "NetworkManager",
Description = "NetworkManager for Goake",
Version = Version.Parse("0.1.0"),
IsAlpha = true,
Category = "Game"
};
public override void Init()
{
//FlaxEngine.Debug.Log("NetworkManagerPlugin initialized");
NetworkManager.Init();
}
}
#if FLAX_EDITOR
public class NetworkManagerEditorPlugin : GEditorPlugin
{
public override Type[] PluginDependencies { get => new Type[] { typeof(ConsoleEditorPlugin) }; }
public override Type GamePluginType => typeof(NetworkManagerPlugin);
public NetworkManagerEditorPlugin()
{
_description = NetworkManagerPlugin.DescriptionInternal;
}
public override void Init()
{
//FlaxEngine.Debug.Log("NetworkManagerPlugin initialized");
//Console.Init();
//NetworkManager.Init();
FlaxEditor.Editor.Instance.PlayModeBegin += OnPlayModeBegin;
}
public override void Deinit()
{
//FlaxEditor.Editor.Instance.PlayModeBegin -= OnPlayModeBegin;
}
private void OnPlayModeBegin()
{
NetworkManager.Init();
}
}
#endif
}

View File

@@ -1,108 +0,0 @@
using System;
using System.Linq;
using FlaxEngine;
using FlaxEngine.Networking;
using Console = Game.Console;
using Object = FlaxEngine.Object;
namespace Game
{
public static partial class NetworkManager
{
public static uint LocalPlayerClientId { get; private set; }
public static bool ConnectServer()
{
client = NetworkPeer.CreatePeer(new NetworkConfig
{
NetworkDriver = Object.New(typeof(ENetDriver)),
ConnectionsLimit = MaximumClients,
MessagePoolSize = 2048,
MessageSize = MTU,
Address = ServerAddress == "localhost" ? "127.0.0.1" : ServerAddress,
Port = ServerPort
});
if (!client.Connect())
{
Console.PrintError("Failed to connect to the server.");
return false;
}
Scripting.FixedUpdate += OnClientUpdate;
Scripting.Exit += Cleanup;
Level.ActorSpawned += OnClientActorSpawned;
return true;
}
private static void OnClientUpdate()
{
/*using*/ Utilities.ScopeProfiler _ = Utilities.ProfileScope("NetworkManager_OnClientUpdate");
while (client.PopEvent(out NetworkEvent networkEvent))
switch (networkEvent.EventType)
{
case NetworkEventType.Connected:
{
LocalPlayerClientId = networkEvent.Sender.ConnectionId;
Console.Print("Connected to server, ConnectionId: " + networkEvent.Sender.ConnectionId);
break;
}
case NetworkEventType.Disconnected:
{
Console.Print("Disconnected from server, timeout.");
LocalPlayerClientId = 0;
break;
}
case NetworkEventType.Timeout:
{
Console.Print("Disconnected from server, connection closed.");
LocalPlayerClientId = 0;
break;
}
case NetworkEventType.Message:
{
try
{
IsLocalClient = server != null;
IsClient = true;
OnNetworkMessage(ref networkEvent);
if (networkEvent.Message.Position > 0 &&
networkEvent.Message.Position < networkEvent.Message.Length)
{
string err =
$"Network message was not fully read: {networkEvent.Message.Position} / {networkEvent.Message.Length}.";
networkEvent.Message.Position = 0;
byte[] messageBytes = new byte[networkEvent.Message.Length];
unsafe
{
fixed (byte* messageBytePtr = &messageBytes[0])
networkEvent.Message.ReadBytes(messageBytePtr, (int)networkEvent.Message.Length);
}
string messageBytesStr = string.Join(", ",
messageBytes.Select(x => "0x" + ((int)x).ToString("X2")));
Console.PrintError(err + $"Message dump: {messageBytesStr}");
}
}
finally
{
IsLocalClient = false;
IsClient = false;
client.RecycleMessage(networkEvent.Message);
}
break;
}
default:
throw new ArgumentOutOfRangeException();
}
_.Dispose();
}
private static void OnClientActorSpawned(Actor actor)
{
}
}
}

View File

@@ -1,181 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FlaxEngine;
using FlaxEngine.Networking;
using Console = Game.Console;
using Object = FlaxEngine.Object;
namespace Game
{
public static partial class NetworkManager
{
private static List<NetworkConnection> ConnectedClients;
private static List<Type> NetworkedTypes;
public static bool StartServer()
{
ConnectedClients = new List<NetworkConnection>(MaximumClients);
server = NetworkPeer.CreatePeer(new NetworkConfig
{
NetworkDriver = Object.New(typeof(ENetDriver)),
ConnectionsLimit = MaximumClients,
MessagePoolSize = 2048,
MessageSize = MTU,
Address = "any",
Port = ServerPort
});
if (!server.Listen())
{
Console.PrintError("Failed to start the server.");
return false;
}
Scripting.FixedUpdate += OnServerUpdate;
Scripting.Exit += Cleanup;
Level.ActorSpawned += OnServerActorSpawned;
NetworkedTypes = new List<Type>();
AppDomain currentDomain = AppDomain.CurrentDomain;
var assemblies = currentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
// Skip common assemblies
string assemblyName = assembly.GetName().Name;
if (assemblyName == "System" ||
assemblyName.StartsWith("System.") ||
assemblyName.StartsWith("Mono.") ||
assemblyName == "mscorlib" ||
assemblyName == "Newtonsoft.Json" ||
assemblyName.StartsWith("FlaxEngine.") ||
assemblyName.StartsWith("JetBrains.") ||
assemblyName.StartsWith("Microsoft.") ||
assemblyName.StartsWith("nunit."))
continue;
foreach (Type type in assembly.GetTypes())
if (type.GetCustomAttributes().Any(x => x is NetworkedAttribute))
NetworkedTypes.Add(type);
}
foreach (Type type in NetworkedTypes)
Console.Print("tracking networked type: " + type.Name);
return true;
}
public static NetworkMessage ServerBeginSendMessage()
{
NetworkMessage message = server.BeginSendMessage();
message.WriteByte((byte)NetworkMessageType.Message);
return message;
}
public static void ServerEndSendMessage(ref NetworkMessage message, NetworkConnection connection)
{
server.EndSendMessage(NetworkChannelType.Reliable, message, connection);
}
public static NetworkMessage ClientBeginSendMessage()
{
NetworkMessage message = client.BeginSendMessage();
message.WriteByte((byte)NetworkMessageType.Message);
return message;
}
public static void ClientEndSendMessage(ref NetworkMessage message)
{
client.EndSendMessage(NetworkChannelType.Reliable, message);
}
private static void OnServerUpdate()
{
/*using*/ Utilities.ScopeProfiler _ = Utilities.ProfileScope("NetworkManager_OnServerUpdate");
while (server.PopEvent(out NetworkEvent networkEvent))
switch (networkEvent.EventType)
{
case NetworkEventType.Connected:
{
Console.Print($"Client({networkEvent.Sender.ConnectionId}) is trying to connect");
try
{
IsServer = true;
if (GameModeManager.OnClientConnecting(networkEvent.Sender))
{
ConnectedClients.Add(networkEvent.Sender);
Console.Print(
$"Client({networkEvent.Sender.ConnectionId}) connected. Total clients: {ConnectedClients.Count}");
GameModeManager.OnClientConnected(networkEvent.Sender);
}
else
Console.Print($"Client({networkEvent.Sender.ConnectionId}) connection refused");
}
finally
{
IsServer = false;
}
break;
}
case NetworkEventType.Disconnected:
case NetworkEventType.Timeout:
{
Console.Print($"Client({networkEvent.Sender.ConnectionId}) disconnected!");
ConnectedClients.Remove(networkEvent.Sender);
Console.Print("Connected clients: " + ConnectedClients.Count);
break;
}
case NetworkEventType.Message:
{
try
{
IsServer = true;
OnNetworkMessage(ref networkEvent);
if (networkEvent.Message.Position > 0 &&
networkEvent.Message.Position < networkEvent.Message.Length)
{
string err =
$"Network message was not fully read: {networkEvent.Message.Position} / {networkEvent.Message.Length}.";
networkEvent.Message.Position = 0;
byte[] messageBytes = new byte[networkEvent.Message.Length];
unsafe
{
fixed (byte* messageBytePtr = &messageBytes[0])
networkEvent.Message.ReadBytes(messageBytePtr, (int)networkEvent.Message.Length);
}
string messageBytesStr = string.Join(", ",
messageBytes.Select(x => "0x" + ((int)x).ToString("X2")));
Console.PrintError(err + $"Message dump: {messageBytesStr}");
}
}
finally
{
IsServer = false;
server.RecycleMessage(networkEvent.Message);
}
break;
}
default:
throw new ArgumentOutOfRangeException();
}
_.Dispose();
}
private static void OnServerActorSpawned(Actor actor)
{
//Console.Print($"actor spawned: {actor.Name} ({actor.TypeName})");
}
}
}

View File

@@ -1,5 +1,6 @@
using System.Collections.Generic;
using FlaxEngine;
using FlaxEngine.Networking;
#if FLAX_EDITOR
using FlaxEditor.CustomEditors.Dedicated;
using FlaxEditor.Scripting;
@@ -55,12 +56,15 @@ namespace Game
playerMovement = FindScript<PlayerMovement>();
playerRigidBody = FindActor<RigidBody>();
NetworkReplicator.AddObject(this);
}
public void Initialize(uint playerId)
{
playerMovement.SetInput(playerId);
if (playerId == NetworkManager.LocalPlayerClientId)
//if (playerId == NetworkManager.LocalPlayerClientId)
if (NetworkReplicator.GetObjectRole(this) == NetworkObjectRole.OwnedAuthoritative)
{
FindActor("CameraHolder").IsActive = true;
//FindActor("ViewModelHolder").IsActive = true;

View File

@@ -14,7 +14,7 @@ namespace Game
protected GZipStream demoFileStream;
protected FileStream demoFileStream2;
public bool IsNetworked => NetworkManager.client != null;
//public bool IsNetworked => NetworkManager.client != null;
public PlayerInputLocal()
{
@@ -75,7 +75,7 @@ namespace Game
buffer.Add(currentState.input);
}
if (IsNetworked)
/*if (IsNetworked)
{
var message = NetworkManager.ClientBeginSendMessage();
message.WriteByte((byte)GameModeMessageType.PlayerInput);
@@ -87,7 +87,7 @@ namespace Game
message.WriteBoolean(currentState.input.attacking);
message.WriteBoolean(currentState.input.jumping);
NetworkManager.ClientEndSendMessage(ref message);
}
}*/
// Reset anything accumulatable here
currentState.input.viewDeltaX = 0;

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using FlaxEngine;
using FlaxEngine.Networking;
using Console = Game.Console;
namespace Game
@@ -22,7 +23,7 @@ namespace Game
//public Float3 maxEndPosition;
}
[Networked]
//[Networked]
public class PlayerMovement : Script
{
// FIXME, should be much smaller but needed to avoid issues with box collider edges against brush edges diagonally
@@ -161,20 +162,20 @@ namespace Game
public void SetInput(uint playerId)
{
if (playerId == 0)
input = new PlayerInput();
else if (playerId == NetworkManager.LocalPlayerClientId)
//if (playerId == 0)
// input = new PlayerInput();
PlayerId = playerId;
if (NetworkReplicator.GetObjectRole(this.Parent) == NetworkObjectRole.OwnedAuthoritative)// if (playerId == NetworkManager.LocalPlayerClientId)
{
Console.Print("local player: " + playerId.ToString());
string demoPath = System.IO.Path.Combine(AssetManager.DemoPath, $"{DateTimeOffset.Now.UtcTicks}.gdem");
input = new PlayerInputLocal(demoPath); // TODO: support recording
PlayerId = playerId;
}
else
{
Console.Print("network player: " + playerId.ToString());
input = new PlayerInputNetwork();
PlayerId = playerId;
}
}
@@ -191,6 +192,9 @@ namespace Game
SetCameraEulerAngles(input.GetCurrentInputState().verificationViewAngles);
}
public override void OnEnable()
{
}
public override void OnDisable()
{
base.OnDisable();
@@ -283,8 +287,8 @@ namespace Game
input.OnUpdate();
float deltadif = Time.DeltaTime - 1.0f / Time.PhysicsFPS;
if (Math.Abs(deltadif) > 0.0001f)
Console.Print("drift: " + deltadif);
//if (Math.Abs(deltadif) > 0.0001f)
// Console.Print("drift: " + deltadif);
input.OnFixedUpdate();
PlayerInputState inputState = input.GetCurrentInputState();

View File

@@ -17,7 +17,8 @@ namespace Game
public static GameplayGlobals Globals { get; private set; }
public static Config Config { get; private set; }
public static void Init()
//public static void Init()
static AssetManager()
{
Globals = Content.Load<GameplayGlobals>(Path.Combine(ContentPath, "Settings", "GameSettings", "GameplayGlobals.flax"));
Config = ConfigParser.ParseFile(Path.Combine(ContentPath, "config.cfg"));

View File

@@ -1,164 +0,0 @@
using System;
using System.Linq;
using FlaxEngine;
using Debug = System.Diagnostics.Debug;
#if FLAX_EDITOR
using FlaxEditor;
#endif
namespace Game
{
/// <summary>
/// Wrapper for GamePlugin with support of initializing plugins in correct order.
/// The initialization is deferred to later time after the last dependant plugin is initialized.
/// </summary>
public abstract class GGamePlugin : GamePlugin
{
public virtual Type[] PluginDependencies { get => new Type[0]; }
public bool Initialized { get; private set; }
public bool Deinitialized { get; private set; }
public override void Initialize()
{
//FlaxEngine.Debug.Log($"Plugin {this.GetType()}::Initialize");
base.Initialize();
if (!Initialized)
{
// Check if dependencies have been initialized, defer to later if not
bool dependenciesInitialized = true;
var plugins = PluginManager.GamePlugins.OfType<GGamePlugin>().Where(x => x.GetType() != this.GetType());
foreach (var pluginType in PluginDependencies)
{
//FlaxEngine.Debug.Log($"Plugintype {pluginType}");
var plugin = plugins.FirstOrDefault(x => x.GetType() == pluginType);
if (plugin != null)
{
//FlaxEngine.Debug.Log($"Plugin {plugin.GetType()} is Initialized?");
if (!plugin.Initialized)
{
dependenciesInitialized = false;
break;
}
}
else
{
dependenciesInitialized = false;
break;
}
}
if (dependenciesInitialized)
{
Init();
Initialized = true;
// Initialize any previously deferred plugins in case their dependencies were initialized
foreach (var p in plugins)
{
//FlaxEngine.Debug.Log($"try init Plugin {p.GetType()}");
if (!p.Initialized /* && p.PluginDependencies.Contains(this.GetType())*/)
{
//FlaxEngine.Debug.Log($"Plugin run init {p.GetType()}");
p.Initialize();
}
}
}
}
}
public override void Deinitialize()
{
base.Deinitialize();
if (!Deinitialized)
{
Deinit();
Deinitialized = true;
}
}
public virtual void Init()
{
}
public virtual void Deinit()
{
}
}
#if FLAX_EDITOR
/// <summary>
/// Wrapper for EditorPlugin with support of initializing plugins in correct order.
/// The initialization is deferred to later time after the last dependant plugin is initialized.
/// </summary>
public abstract class GEditorPlugin : EditorPlugin
{
public virtual Type[] PluginDependencies { get => new Type[0]; }
public bool Initialized { get; private set; }
public bool Deinitialized { get; private set; }
public override void Initialize()
{
//FlaxEngine.Debug.Log($"Plugin {this.GetType()}::Initialize");
base.Initialize();
if (!Initialized)
{
// Check if dependencies have been initialized, defer to later if not
bool dependenciesInitialized = true;
var plugins = PluginManager.EditorPlugins.OfType<GEditorPlugin>().Where(x => x.GetType() != this.GetType());
foreach (var pluginType in PluginDependencies)
{
//FlaxEngine.Debug.Log($"Plugintype {pluginType}");
var plugin = plugins.FirstOrDefault(x => x.GetType() == pluginType);
if (plugin != null)
{
//FlaxEngine.Debug.Log($"Plugin {plugin.GetType()} is Initialized?");
if (!plugin.Initialized)
{
dependenciesInitialized = false;
break;
}
}
else
{
dependenciesInitialized = false;
break;
}
}
if (dependenciesInitialized)
{
Init();
Initialized = true;
// Initialize any previously deferred plugins in case their dependencies were initialized
foreach (var p in plugins)
{
//FlaxEngine.Debug.Log($"try init Plugin {p.GetType()}");
if (!p.Initialized /* && p.PluginDependencies.Contains(this.GetType())*/)
{
//FlaxEngine.Debug.Log($"Plugin run init {p.GetType()}");
p.Initialize();
}
}
}
}
}
public override void Deinitialize()
{
base.Deinitialize();
if (!Deinitialized)
{
Deinit();
Deinitialized = true;
}
}
public virtual void Init()
{
}
public virtual void Deinit()
{
}
}
#endif
}

View File

@@ -1,20 +1,24 @@
//#define COMPILE_WITH_DLSS
using Flax.Build;
public class GameEditorTarget : GameProjectEditorTarget
{
private bool UseDLSS = false;
/// <inheritdoc />
public override void Init()
{
base.Init();
// Reference the modules for editor
Modules.Add("Game");
Modules.Add("FidelityFXFSR");
//Modules.Add("Cabrito");
Architectures = new TargetArchitecture[] { TargetArchitecture.x64 };
Platforms = new TargetPlatform[] { TargetPlatform.Windows };
//this.LinkType = TargetLinkType.Monolithic;
Modules.Add("Game");
//Modules.Add("FidelityFXFSR");
#if COMPILE_WITH_DLSS
//Modules.Add("DLSS");
#endif
}
}

View File

@@ -1,9 +1,13 @@
//#define COMPILE_WITH_DLSS
using System;
using Flax.Build;
using Flax.Build.NativeCpp;
public class GameTarget : GameProjectTarget
{
private bool UseDLSS = false;
/// <inheritdoc />
public override void Init()
{
@@ -24,7 +28,10 @@ public class GameTarget : GameProjectTarget
}
Modules.Add("Game");
Modules.Add("FidelityFXFSR");
//Modules.Add("FidelityFXFSR");
#if COMPILE_WITH_DLSS
//Modules.Add("DLSS");
#endif
}
public override string GetOutputFilePath(BuildOptions options, TargetOutputType? outputType = null)

View File

@@ -0,0 +1,9 @@
{
"profiles": {
"Game.CSharp": {
"commandName": "Project",
"remoteDebugEnabled": false,
"nativeDebugging": false
}
}
}

View File

@@ -1,5 +1,4 @@
using NUnit.Framework;
using Cabrito;
using Console = Game.Console;
namespace GoakeTests.ConsoleTests

View File

@@ -4,28 +4,28 @@
<IsPackable>false</IsPackable>
<TargetFrameworks>net48;net5.0;net5.0-windows;net6.0;net6.0-windows</TargetFrameworks>
<TargetFrameworks>net7.0</TargetFrameworks>
<IsPublishable>False</IsPublishable>
<Configurations>Editor.Windows.Development;Game.Windows.Development;Release</Configurations>
<Platforms>AnyCPU</Platforms>
<Platforms>x64</Platforms>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net6.0|AnyCPU'">
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net6.0|x64'">
<WarningLevel>5</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net6.0|AnyCPU'">
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net6.0|x64'">
<WarningLevel>5</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net5.0-windows|AnyCPU'">
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net5.0-windows|x64'">
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net5.0-windows|AnyCPU'">
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net5.0-windows|x64'">
<WarningLevel>4</WarningLevel>
</PropertyGroup>
@@ -34,22 +34,22 @@
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Editor.Windows.Development' ">
<DefineConstants>BUILD_DEVELOPMENT;PLATFORM_WINDOWS;FLAX_EDITOR;FLAX;FLAX_ASSERTIONS;FLAX_1;FLAX_1_4</DefineConstants>
<DefineConstants>BUILD_DEVELOPMENT;PLATFORM_WINDOWS;FLAX_EDITOR;FLAX;FLAX_ASSERTIONS;FLAX_1;FLAX_1_5</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Game.Windows.Development' ">
<DefineConstants>BUILD_DEVELOPMENT;PLATFORM_WINDOWS;FLAX_GAME;FLAX;FLAX_ASSERTIONS;FLAX_1;FLAX_1_4</DefineConstants>
<DefineConstants>BUILD_DEVELOPMENT;PLATFORM_WINDOWS;FLAX_GAME;FLAX;FLAX_ASSERTIONS;FLAX_1;FLAX_1_5</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DefineConstants>BUILD_RELEASE;PLATFORM_WINDOWS;FLAX_GAME;FLAX;FLAX_ASSERTIONS;FLAX_1;FLAX_1_4</DefineConstants>
<DefineConstants>BUILD_RELEASE;PLATFORM_WINDOWS;FLAX_GAME;FLAX;FLAX_ASSERTIONS;FLAX_1;FLAX_1_5</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="NUnit" Version="3.13.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.3.1" />
<PackageReference Include="coverlet.collector" Version="3.0.2" />
</ItemGroup>

View File

@@ -2,7 +2,6 @@
using System.Diagnostics;
using System.IO;
using NUnit.Framework;
using Cabrito;
using FlaxEngine;
using Game;

View File

@@ -16,4 +16,10 @@
- shotgun: very powerful and inaccurate shotgun which shoots shrapnel that can ricochet from walls and still hit the target. possibly homage to flak cannon in unreal series. packs enough punch to even push the player backwards while in mid-air.
- lightning gun: ?
- melee weapon: can be almost anything from swords to hammers to laser sword and tasers. no pummel. can push back the player a bit when hitting floor or walls.
-
-
names suggested by ChatGPT:
"Ruin Arena": This name conveys the setting of your game, and the word "arena" implies competitive gameplay.
"Golem Arena": This name incorporates the goat-like appearance of your game's creatures, and the word "golem" suggests ancient, powerful beings.
"Eon Arena": This name incorporates the idea of a long-dormant race being awakened, and it suggests a vast, epic time scale.
"Odyssey Arena": This name suggests a journey or quest, which could be fitting if your game includes a storyline or narrative element.