From 03b39427325df9316a5c476d306713186ccbed5c Mon Sep 17 00:00:00 2001 From: Michel Fedde Date: Sat, 24 Oct 2020 15:10:36 +0200 Subject: [PATCH] Holidays 12.10. -> 25.10.2020 ~ Moved code around in files. SM.Base: + PostProcessing-system + OnInitialization() for Scenes. + Shader-Extensions + Added option to not react while unfocused to the window. + Added Screenshots to the window. + Connected the log system to the SM.OGL-action system. ~ Replaced IShader with abstract MaterialShader. ~ When a log compression folder doesn't exist, it will create one. SM.OGL: + Added support for UniformArrays + Added ShaderPreProcessing + Added Shader Extensions. + Added Debug actions. + SM.OGL settings ~ Framebuffer Size is automaticly changed, when the window and scale is set. SM2D: + Added easy shader drawing. --- SMCode/SM.Base/Controls/Mouse.cs | 36 +- SMCode/SM.Base/Drawing/DrawingBasis.cs | 25 +- .../SM.Base/Drawing/GenericTransformation.cs | 17 +- SMCode/SM.Base/Drawing/IShader.cs | 18 - SMCode/SM.Base/Drawing/Instance.cs | 16 +- SMCode/SM.Base/Drawing/Material.cs | 25 +- SMCode/SM.Base/Drawing/MaterialShader.cs | 47 ++ SMCode/SM.Base/Log.cs | 124 ++--- SMCode/SM.Base/Objects/Mesh.cs | 18 +- SMCode/SM.Base/Objects/Static/Plate.cs | 30 +- .../PostProcess/DefaultFiles/extensions.frag | 9 + .../PostProcess/DefaultFiles/vertexFile.vert | 14 + .../DefaultFiles/vertexWithExt.vert | 18 + .../SM.Base/PostProcess/PostProcessEffect.cs | 30 ++ .../SM.Base/PostProcess/PostProcessShader.cs | 64 +++ .../PostProcessing/PostProcessingEffect.cs | 16 - SMCode/SM.Base/Properties/AssemblyInfo.cs | 17 +- SMCode/SM.Base/SM.Base.csproj | 33 +- SMCode/SM.Base/SMRenderer.cs | 33 +- SMCode/SM.Base/Scene/GenericCamera.cs | 50 +- SMCode/SM.Base/Scene/GenericItemCollection.cs | 90 ++-- SMCode/SM.Base/Scene/GenericScene.cs | 84 ++-- SMCode/SM.Base/Scene/IBackgroundItem.cs | 3 +- SMCode/SM.Base/Scene/IShowCollection.cs | 12 +- SMCode/SM.Base/Scene/IShowItem.cs | 24 +- .../ShaderExtension/ExtensionManager.cs | 19 + .../SM.Base/ShaderExtension/vertex/basic.vert | 35 ++ SMCode/SM.Base/Text/CharParameter.cs | 18 +- SMCode/SM.Base/Text/Font.cs | 97 ++-- SMCode/SM.Base/Text/FontCharStorage.cs | 15 +- SMCode/SM.Base/Text/TextDrawingBasis.cs | 62 +-- SMCode/SM.Base/Textures/Texture.cs | 62 ++- SMCode/SM.Base/Time/Interval.cs | 17 +- SMCode/SM.Base/Time/Stopwatch.cs | 23 +- SMCode/SM.Base/Time/Timer.cs | 50 +- SMCode/SM.Base/Types/CVector.cs | 158 +++---- SMCode/SM.Base/Types/CVector2.cs | 76 +-- SMCode/SM.Base/Types/CVector3.cs | 62 ++- SMCode/SM.Base/Types/CVector4.cs | 49 +- SMCode/SM.Base/Utility/Assembly.cs | 37 +- SMCode/SM.Base/Utility/Deltatime.cs | 47 +- SMCode/SM.Base/Utility/Randomize.cs | 85 ++-- SMCode/SM.Base/Utility/RotationUtility.cs | 12 +- SMCode/SM.Base/Utility/ShaderUtility.cs | 7 + SMCode/SM.Base/Window/Contexts/DrawContext.cs | 40 +- .../SM.Base/Window/Contexts/UpdateContext.cs | 15 +- SMCode/SM.Base/Window/GenericWindow.cs | 172 +++++-- SMCode/SM.Base/Window/RenderPipeline.cs | 55 ++- SMCode/SM.Base/packages.config | 2 +- SMCode/SM.OGL/Framebuffer/ColorAttachment.cs | 30 +- SMCode/SM.OGL/Framebuffer/Framebuffer.cs | 72 ++- SMCode/SM.OGL/GLCustomActions.cs | 47 ++ SMCode/SM.OGL/GLDebugging.cs | 60 +-- SMCode/SM.OGL/GLObject.cs | 42 +- SMCode/SM.OGL/GLSettings.cs | 15 + SMCode/SM.OGL/GLSystem.cs | 31 +- SMCode/SM.OGL/Mesh/BoundingBox.cs | 49 +- SMCode/SM.OGL/Mesh/GenericMesh.cs | 57 +-- SMCode/SM.OGL/Mesh/VBO.cs | 200 +++++--- SMCode/SM.OGL/Properties/AssemblyInfo.cs | 17 +- SMCode/SM.OGL/SM.OGL.csproj | 19 +- SMCode/SM.OGL/Shaders/GenericShader.cs | 55 +-- SMCode/SM.OGL/Shaders/IUniform.cs | 7 + SMCode/SM.OGL/Shaders/ShaderExtensions.cs | 38 ++ SMCode/SM.OGL/Shaders/ShaderFile.cs | 54 ++- SMCode/SM.OGL/Shaders/ShaderFileCollection.cs | 37 +- SMCode/SM.OGL/Shaders/ShaderPreProcess.cs | 24 + SMCode/SM.OGL/Shaders/Uniform.cs | 440 ++++++++++++++---- SMCode/SM.OGL/Shaders/UniformArray.cs | 50 ++ SMCode/SM.OGL/Shaders/UniformCollection.cs | 127 +++-- SMCode/SM.OGL/Texture/TextureBase.cs | 21 +- SMCode/SM.OGL/Version.cs | 15 +- SMCode/SM.OGL/packages.config | 2 +- SMCode/SM2D/Controls/Mouse2D.cs | 17 +- SMCode/SM2D/Drawing/DrawBackground.cs | 43 +- SMCode/SM2D/Drawing/DrawBackgroundShader.cs | 19 + SMCode/SM2D/Drawing/DrawColor.cs | 23 +- SMCode/SM2D/Drawing/DrawComplex.cs | 12 +- SMCode/SM2D/Drawing/DrawPolygon.cs | 32 +- SMCode/SM2D/Drawing/DrawShader.cs | 24 + SMCode/SM2D/Drawing/DrawText.cs | 9 +- SMCode/SM2D/Drawing/DrawTexture.cs | 41 +- SMCode/SM2D/GLWindow2D.cs | 20 +- SMCode/SM2D/Object/Polygon.cs | 46 +- SMCode/SM2D/Object/PolygonVertex.cs | 6 +- SMCode/SM2D/Pipelines/Adv2DPipeline.cs | 1 - SMCode/SM2D/Pipelines/Basic2DPipeline.cs | 7 +- SMCode/SM2D/Properties/AssemblyInfo.cs | 17 +- SMCode/SM2D/SM2D.csproj | 19 +- SMCode/SM2D/Scene/Camera.cs | 14 +- SMCode/SM2D/Scene/I2DShowItem.cs | 7 +- SMCode/SM2D/Scene/ItemCollection.cs | 6 +- SMCode/SM2D/Scene/Scene.cs | 11 +- SMCode/SM2D/Shader/Default2DShader.cs | 39 +- SMCode/SM2D/Shader/ShaderFiles/default.vert | 25 +- SMCode/SM2D/Types/Transformation.cs | 37 +- SMCode/SM2D/packages.config | 2 +- SMCode/SM3D/Properties/AssemblyInfo.cs | 9 +- SMCode/SM3D/SM3D.csproj | 6 - SM_TEST/Program.cs | 6 - SM_TEST/SM_TEST.csproj | 4 +- SM_TEST/packages.config | 2 +- 102 files changed, 2683 insertions(+), 1398 deletions(-) delete mode 100644 SMCode/SM.Base/Drawing/IShader.cs create mode 100644 SMCode/SM.Base/Drawing/MaterialShader.cs create mode 100644 SMCode/SM.Base/PostProcess/DefaultFiles/extensions.frag create mode 100644 SMCode/SM.Base/PostProcess/DefaultFiles/vertexFile.vert create mode 100644 SMCode/SM.Base/PostProcess/DefaultFiles/vertexWithExt.vert create mode 100644 SMCode/SM.Base/PostProcess/PostProcessEffect.cs create mode 100644 SMCode/SM.Base/PostProcess/PostProcessShader.cs delete mode 100644 SMCode/SM.Base/PostProcessing/PostProcessingEffect.cs create mode 100644 SMCode/SM.Base/ShaderExtension/ExtensionManager.cs create mode 100644 SMCode/SM.Base/ShaderExtension/vertex/basic.vert create mode 100644 SMCode/SM.Base/Utility/ShaderUtility.cs create mode 100644 SMCode/SM.OGL/GLCustomActions.cs create mode 100644 SMCode/SM.OGL/GLSettings.cs create mode 100644 SMCode/SM.OGL/Shaders/IUniform.cs create mode 100644 SMCode/SM.OGL/Shaders/ShaderExtensions.cs create mode 100644 SMCode/SM.OGL/Shaders/ShaderPreProcess.cs create mode 100644 SMCode/SM.OGL/Shaders/UniformArray.cs create mode 100644 SMCode/SM2D/Drawing/DrawBackgroundShader.cs create mode 100644 SMCode/SM2D/Drawing/DrawShader.cs diff --git a/SMCode/SM.Base/Controls/Mouse.cs b/SMCode/SM.Base/Controls/Mouse.cs index ef72d90..9491c8e 100644 --- a/SMCode/SM.Base/Controls/Mouse.cs +++ b/SMCode/SM.Base/Controls/Mouse.cs @@ -1,32 +1,26 @@ -using System; +#region usings + using OpenTK; using OpenTK.Input; +#endregion + namespace SM.Base.Controls { /// - /// Mouse controller + /// Mouse controller /// /// The type of window this controller is connected to. public class Mouse - where TWindow : GenericWindow + where TWindow : GenericWindow { /// - /// The window it is connected to. + /// The window it is connected to. /// protected TWindow _window; - /// - /// The current position of the mouse in the screen. - /// - public Vector2 InScreen { get; private set; } /// - /// The current position of the mouse in the screen from 0..1. - /// - public Vector2 InScreenNormalized { get; private set; } - - /// - /// The constructor + /// The constructor /// /// The window, its listen to. protected internal Mouse(TWindow window) @@ -35,13 +29,23 @@ namespace SM.Base.Controls } /// - /// The event to update the values. + /// The current position of the mouse in the screen. + /// + public Vector2 InScreen { get; private set; } + + /// + /// The current position of the mouse in the screen from 0..1. + /// + public Vector2 InScreenNormalized { get; private set; } + + /// + /// The event to update the values. /// /// The event args. protected void MouseMoveEvent(MouseMoveEventArgs mmea) { InScreen = new Vector2(mmea.X, mmea.Y); - InScreenNormalized = new Vector2(mmea.X / (float)_window.Width, mmea.Y / (float)_window.Height); + InScreenNormalized = new Vector2(mmea.X / (float) _window.Width, mmea.Y / (float) _window.Height); } } } \ No newline at end of file diff --git a/SMCode/SM.Base/Drawing/DrawingBasis.cs b/SMCode/SM.Base/Drawing/DrawingBasis.cs index d28dfc3..1f6b5c0 100644 --- a/SMCode/SM.Base/Drawing/DrawingBasis.cs +++ b/SMCode/SM.Base/Drawing/DrawingBasis.cs @@ -1,21 +1,25 @@ -using System.Collections.Generic; +#region usings + +using System.Collections.Generic; using SM.Base.Contexts; -using SM.Base.Objects.Static; using SM.OGL.Mesh; +#endregion + namespace SM.Base.Scene { /// - /// Contains general basis systems for drawing objects. + /// Contains general basis systems for drawing objects. /// public abstract class DrawingBasis : IShowItem { /// - /// The material it should use. + /// The material it should use. /// protected Material _material = new Material(); + /// - /// The mesh it should use. + /// The mesh it should use. /// protected GenericMesh _mesh = SMRenderer.DefaultMesh; @@ -31,7 +35,6 @@ namespace SM.Base.Scene /// public virtual void Update(UpdateContext context) { - } /// @@ -46,33 +49,31 @@ namespace SM.Base.Scene /// public virtual void OnAdded(object sender) { - } /// public virtual void OnRemoved(object sender) { - } /// - /// Draws the context, that was given to them. + /// Draws the context, that was given to them. /// /// protected virtual void DrawContext(ref DrawContext context) { - } } + /// - /// Contains general basis systems for drawing objects. + /// Contains general basis systems for drawing objects. /// /// The transformation type public abstract class DrawingBasis : DrawingBasis where TTransformation : GenericTransformation, new() { /// - /// The current transformation. + /// The current transformation. /// public TTransformation Transform = new TTransformation(); } diff --git a/SMCode/SM.Base/Drawing/GenericTransformation.cs b/SMCode/SM.Base/Drawing/GenericTransformation.cs index ab4ddb4..90f98d8 100644 --- a/SMCode/SM.Base/Drawing/GenericTransformation.cs +++ b/SMCode/SM.Base/Drawing/GenericTransformation.cs @@ -1,23 +1,28 @@ -using OpenTK; +#region usings + +using OpenTK; + +#endregion namespace SM.Base.Scene { /// - /// Contains methods for using transformations right. + /// Contains methods for using transformations right. /// public abstract class GenericTransformation { /// - /// Contains the current model matrix. + /// Contains the current model matrix. /// protected Matrix4 _modelMatrix { get; private set; } + /// - /// Contains the last frame the matrix was calculated. + /// Contains the last frame the matrix was calculated. /// protected ulong _lastFrame { get; private set; } /// - /// Returns the current model matrix. + /// Returns the current model matrix. /// /// public Matrix4 GetMatrix() @@ -32,7 +37,7 @@ namespace SM.Base.Scene } /// - /// Calculates the current matrix. + /// Calculates the current matrix. /// /// The current matrix. protected abstract Matrix4 RequestMatrix(); diff --git a/SMCode/SM.Base/Drawing/IShader.cs b/SMCode/SM.Base/Drawing/IShader.cs deleted file mode 100644 index 3083576..0000000 --- a/SMCode/SM.Base/Drawing/IShader.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Collections.Generic; -using OpenTK; -using SM.Base.Contexts; - -namespace SM.Base.Scene -{ - /// - /// A general interface to work with material shaders properly. - /// - public interface IShader - { - /// - /// Draws the context. - /// - /// The context - void Draw(DrawContext context); - } -} \ No newline at end of file diff --git a/SMCode/SM.Base/Drawing/Instance.cs b/SMCode/SM.Base/Drawing/Instance.cs index 2d17607..4522d14 100644 --- a/SMCode/SM.Base/Drawing/Instance.cs +++ b/SMCode/SM.Base/Drawing/Instance.cs @@ -1,22 +1,28 @@ -using OpenTK; +#region usings + +using OpenTK; + +#endregion namespace SM.Base.Scene { /// - /// This represens a drawing instance. + /// This represens a drawing instance. /// public struct Instance { /// - /// The model matrix. + /// The model matrix. /// public Matrix4 ModelMatrix; + /// - /// The texture offset. + /// The texture offset. /// public Vector2 TexturePosition; + /// - /// The texture scale. + /// The texture scale. /// public Vector2 TextureScale; } diff --git a/SMCode/SM.Base/Drawing/Material.cs b/SMCode/SM.Base/Drawing/Material.cs index 839ab4f..2582626 100644 --- a/SMCode/SM.Base/Drawing/Material.cs +++ b/SMCode/SM.Base/Drawing/Material.cs @@ -1,25 +1,30 @@ -using OpenTK.Graphics; +#region usings + +using OpenTK.Graphics; using SM.OGL.Texture; +#endregion + namespace SM.Base.Scene { /// - /// Represents a material. + /// Represents a material. /// public class Material { /// - /// The base texture. (aka. Diffuse Texture) + /// A custom shader, that is used to draw this material. /// - public TextureBase Texture; - /// - /// The tint or color. - /// - public Color4 Tint = Color4.White; + public MaterialShader CustomShader; /// - /// A custom shader, that is used to draw this material. + /// The base texture. (aka. Diffuse Texture) /// - public IShader CustomShader; + public TextureBase Texture; + + /// + /// The tint or color. + /// + public Color4 Tint = Color4.White; } } \ No newline at end of file diff --git a/SMCode/SM.Base/Drawing/MaterialShader.cs b/SMCode/SM.Base/Drawing/MaterialShader.cs new file mode 100644 index 0000000..13c7a31 --- /dev/null +++ b/SMCode/SM.Base/Drawing/MaterialShader.cs @@ -0,0 +1,47 @@ +#region usings + +using OpenTK.Graphics.OpenGL4; +using SM.Base.Contexts; +using SM.OGL.Shaders; + +#endregion + +namespace SM.Base.Scene +{ + /// + /// A general class to work with material shaders properly. + /// + public abstract class MaterialShader : GenericShader + { + + protected MaterialShader(string vertex, string fragment) : base(vertex, fragment) + { + } + + protected MaterialShader(ShaderFileCollection shaderFileFiles) : base(shaderFileFiles) + { + } + + /// + /// Draws the context. + /// + /// The context + public virtual void Draw(DrawContext context) + { + GL.UseProgram(this); + + GL.BindVertexArray(context.Mesh); + + DrawProcess(context); + + CleanUp(); + + GL.UseProgram(0); + } + + protected virtual void DrawProcess(DrawContext context) + { + + } + } +} \ No newline at end of file diff --git a/SMCode/SM.Base/Log.cs b/SMCode/SM.Base/Log.cs index 95124d5..49624f9 100644 --- a/SMCode/SM.Base/Log.cs +++ b/SMCode/SM.Base/Log.cs @@ -1,98 +1,108 @@ -using System; +#region usings + +using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; -using System.Net.Http; using System.Windows.Forms; using OpenTK.Graphics.OpenGL4; using SM.OGL; +#endregion + namespace SM.Base { /// - /// Specifies the target. + /// Specifies the target. /// [Flags] public enum LogTarget { /// - /// No target, will not draw. + /// No target, will not draw. /// None = 0, + /// - /// Takes the . + /// Takes the . /// Default = 1, + /// - /// Writes the log to the console. + /// Writes the log to the console. /// Console = 2, + /// - /// Writes the log to the debugger at . + /// Writes the log to the debugger at . /// Debugger = 4, + /// - /// Writes the log to the specific file. + /// Writes the log to the specific file. /// File = 8, + /// - /// Writes the log to every target. + /// Writes the log to every target. /// All = Console | Debugger | File } /// - /// Preset log types. + /// Preset log types. /// public enum LogType { /// - /// Informations. Console Color: Green + /// Informations. Console Color: Green /// Info, + /// - /// Warnings. Console Color: Yellow + /// Warnings. Console Color: Yellow /// Warning, + /// - /// Error. Console Color: Red + /// Error. Console Color: Red /// Error } /// - /// Contains the system for logging. + /// Contains the system for logging. /// public class Log { private static StreamWriter _logStream; - private static bool _init = false; + private static bool _init; /// - /// Presets for the log targets. + /// Presets for the log targets. /// - public static Dictionary Preset = new Dictionary() + public static Dictionary Preset = new Dictionary { {LogTarget.Console, "[%type%] %msg%"}, {LogTarget.Debugger, "[%type%] %msg%"}, {LogTarget.File, "<%date%, %time%> [%type%] %msg%"} }; - private static readonly Dictionary Colors = new Dictionary() + private static readonly Dictionary Colors = new Dictionary { {LogType.Info, ConsoleColor.Green}, {LogType.Warning, ConsoleColor.Yellow}, - {LogType.Error, ConsoleColor.Red}, + {LogType.Error, ConsoleColor.Red} }; /// - /// Specified the default target. + /// Specified the default target. /// public static LogTarget DefaultTarget = LogTarget.All; /// - /// Sets the log file. At wish compresses the old file to a zip file. + /// Sets the log file. At wish compresses the old file to a zip file. /// /// The path to the log file. /// Path for the compression, if desired. @@ -106,10 +116,12 @@ namespace SM.Base { if (compressionFolder != "") { - DateTime creation = File.GetLastWriteTime(path); + if (!Directory.Exists(compressionFolder)) Directory.CreateDirectory(compressionFolder); + + var creation = File.GetLastWriteTime(path); try { - using ZipArchive archive = + using var archive = ZipFile.Open( $"{compressionFolder}{Path.DirectorySeparatorChar}{Path.GetFileName(path)}_{creation.Year.ToString() + creation.Month + creation.Day}_{creation.Hour.ToString() + creation.Minute + creation.Second + creation.Millisecond}.zip", ZipArchiveMode.Create); @@ -127,11 +139,12 @@ namespace SM.Base _logStream = new StreamWriter(path) {AutoFlush = true}; Write(LogType.Info, $"Activated new log file. ['{path}']"); - } - static void Init() + internal static void Init() { + if (_init) return; + AppDomain.CurrentDomain.UnhandledException += ExceptionHandler; AppDomain.CurrentDomain.DomainUnload += (sender, args) => { @@ -139,27 +152,25 @@ namespace SM.Base _logStream.Close(); }; - GLDebugging.DebugAction = GLDebugAction; - GLDebugging.GlErrorAction = code => - { - Write(LogType.Warning, $"A '{code}' GL error occured."); - }; + GLCustomActions.AtKHRDebug = GLDebugAction; + GLCustomActions.AtError = err => Write(LogType.Error, err); + GLCustomActions.AtWarning = warning => Write(LogType.Warning, warning); + GLCustomActions.AtInfo = info => Write(LogType.Info, info); + _init = true; } private static void GLDebugAction(DebugSource source, DebugType type, DebugSeverity severity, string msg) { - if (type.HasFlag(DebugType.DebugTypeError)) - { - throw new Exception("[GLError] "+msg); - } + if (type.HasFlag(DebugType.DebugTypeError)) throw new Exception("[GLError] " + msg); Write(type != DebugType.DontCare ? type.ToString().Substring(9) : "DontCare", ConsoleColor.Gray, msg); } [DebuggerStepThrough] private static void ExceptionHandler(object sender, UnhandledExceptionEventArgs e) { - Write(e.IsTerminating ? "Terminating Error" : LogType.Error.ToString(), e.IsTerminating ? ConsoleColor.DarkRed : ConsoleColor.Red, e.ExceptionObject); + Write(e.IsTerminating ? "Terminating Error" : LogType.Error.ToString(), + e.IsTerminating ? ConsoleColor.DarkRed : ConsoleColor.Red, e.ExceptionObject); if (e.IsTerminating) { @@ -170,30 +181,31 @@ namespace SM.Base } /// - /// Writes multiple lines of the same type to the log. + /// Writes multiple lines of the same type to the log. /// - public static void Write(LogType type, params T[] values) => Write(type.ToString(), Colors[type], values); - - /// - /// Writes multiple lines of the same type to the log. - /// - public static void Write(string type, ConsoleColor color, params T[] values) + public static void Write(LogType type, params T[] values) { - for (var i = 0; i < values.Length; i++) - { - Write(type, color, values[i], DefaultTarget); - } + Write(type.ToString(), Colors[type], values); } /// - /// Writes one line to the log. + /// Writes multiple lines of the same type to the log. /// - public static void Write(LogType type, T value, LogTarget target = LogTarget.Default) => - Write(type.ToString(), Colors[type], value, target); + public static void Write(string type, ConsoleColor color, params T[] values) + { + for (var i = 0; i < values.Length; i++) Write(type, color, values[i], DefaultTarget); + } /// - /// Writes one line to the log. - /// + /// Writes one line to the log. + /// + public static void Write(LogType type, T value, LogTarget target = LogTarget.Default) + { + Write(type.ToString(), Colors[type], value, target); + } + + /// + /// Writes one line to the log. /// public static void Write(string type, ConsoleColor color, T value, LogTarget target = LogTarget.Default) { @@ -209,23 +221,23 @@ namespace SM.Base } /// - /// Writes a text with a different color. + /// Writes a text with a different color. /// /// /// public static void ColorfulWriteLine(ConsoleColor color, string value) { - ConsoleColor before = Console.ForegroundColor; + var before = Console.ForegroundColor; Console.ForegroundColor = color; Console.WriteLine(value); Console.ForegroundColor = before; } - static string ProcessPreset(LogTarget target, string type, string msg) + private static string ProcessPreset(LogTarget target, string type, string msg) { - string preset = Preset[target]; - DateTime now = DateTime.Now; + var preset = Preset[target]; + var now = DateTime.Now; return preset.Replace("%date%", now.ToShortDateString()) .Replace("%time%", now.ToShortTimeString()) diff --git a/SMCode/SM.Base/Objects/Mesh.cs b/SMCode/SM.Base/Objects/Mesh.cs index b743026..e362251 100644 --- a/SMCode/SM.Base/Objects/Mesh.cs +++ b/SMCode/SM.Base/Objects/Mesh.cs @@ -1,4 +1,8 @@ -using SM.OGL.Mesh; +#region usings + +using SM.OGL.Mesh; + +#endregion namespace SM.Base.Objects { @@ -6,16 +10,16 @@ namespace SM.Base.Objects public class Mesh : GenericMesh { /// - /// Contains vertex colors - /// - public virtual VBO Color { get; } - - /// - /// While initializing, it will add the to the data index. + /// While initializing, it will add the to the data index. /// protected Mesh() { AttribDataIndex.Add(3, Color); } + + /// + /// Contains vertex colors + /// + public virtual VBO Color { get; } } } \ No newline at end of file diff --git a/SMCode/SM.Base/Objects/Static/Plate.cs b/SMCode/SM.Base/Objects/Static/Plate.cs index dd5445d..87db17e 100644 --- a/SMCode/SM.Base/Objects/Static/Plate.cs +++ b/SMCode/SM.Base/Objects/Static/Plate.cs @@ -1,27 +1,36 @@ -using OpenTK; -using OpenTK.Graphics; +#region usings + +using OpenTK; using OpenTK.Graphics.OpenGL4; using SM.OGL.Mesh; +#endregion + namespace SM.Base.Objects.Static { /// - /// A basic plate + /// A basic plate /// public class Plate : GenericMesh { /// - /// The object. + /// The object. /// public static Plate Object = new Plate(); + //public override int[] Indices { get; set; } = new[] {0, 1, 2, 3}; + + private Plate() + { + } + /// - public override VBO Vertex { get; } = new VBO() + public override VBO Vertex { get; } = new VBO { {-.5f, -.5f, 0}, {-.5f, .5f, 0}, {.5f, .5f, 0}, - {.5f, -.5f, 0}, + {.5f, -.5f, 0} }; /// @@ -30,17 +39,14 @@ namespace SM.Base.Objects.Static {0, 0}, {0, 1}, {1, 1}, - {1, 0}, + {1, 0} }; /// public override PrimitiveType PrimitiveType { get; } = PrimitiveType.Quads; /// - public override BoundingBox BoundingBox { get; } = new BoundingBox(new Vector3(-.5f, -.5f, 0), new Vector3(.5f, .5f, 0)); - - //public override int[] Indices { get; set; } = new[] {0, 1, 2, 3}; - - private Plate() {} + public override BoundingBox BoundingBox { get; } = + new BoundingBox(new Vector3(-.5f, -.5f, 0), new Vector3(.5f, .5f, 0)); } } \ No newline at end of file diff --git a/SMCode/SM.Base/PostProcess/DefaultFiles/extensions.frag b/SMCode/SM.Base/PostProcess/DefaultFiles/extensions.frag new file mode 100644 index 0000000..c689d20 --- /dev/null +++ b/SMCode/SM.Base/PostProcess/DefaultFiles/extensions.frag @@ -0,0 +1,9 @@ +#version 330 + +in vec2 vTexture; + +uniform sampler2D renderedTexture; + +vec4 GetRenderColor() { + return texture(renderedTexture, vTexture); +} \ No newline at end of file diff --git a/SMCode/SM.Base/PostProcess/DefaultFiles/vertexFile.vert b/SMCode/SM.Base/PostProcess/DefaultFiles/vertexFile.vert new file mode 100644 index 0000000..0631261 --- /dev/null +++ b/SMCode/SM.Base/PostProcess/DefaultFiles/vertexFile.vert @@ -0,0 +1,14 @@ +#version 330 + +layout(location = 0) in vec3 aPos; +layout(location = 1) in vec2 aTex; + +uniform mat4 MVP; + +out vec2 vTexture; + +void main() { + vTexture = aTex; + + gl_Position = MVP * vec4(aPos, 1); +} \ No newline at end of file diff --git a/SMCode/SM.Base/PostProcess/DefaultFiles/vertexWithExt.vert b/SMCode/SM.Base/PostProcess/DefaultFiles/vertexWithExt.vert new file mode 100644 index 0000000..508c2be --- /dev/null +++ b/SMCode/SM.Base/PostProcess/DefaultFiles/vertexWithExt.vert @@ -0,0 +1,18 @@ +#version 330 + +layout(location = 0) in vec3 aPos; +layout(location = 1) in vec2 aTex; + +uniform mat4 MVP; + +out vec2 vTexture; + +void vertex(); + +void main() { + vTexture = aTex; + + gl_Position = MVP * vec4(aPos, 1); + + vertex(); +} \ No newline at end of file diff --git a/SMCode/SM.Base/PostProcess/PostProcessEffect.cs b/SMCode/SM.Base/PostProcess/PostProcessEffect.cs new file mode 100644 index 0000000..88851ee --- /dev/null +++ b/SMCode/SM.Base/PostProcess/PostProcessEffect.cs @@ -0,0 +1,30 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using OpenTK; +using OpenTK.Graphics.OpenGL4; +using SM.Base.Objects.Static; +using SM.OGL.Framebuffer; +using SM.OGL.Shaders; + +namespace SM.Base.PostProcess +{ + public abstract class PostProcessEffect + { + internal static Matrix4 Mvp; + + public virtual ICollection RequiredFramebuffers { get; } + + public virtual void Init() {} + + public virtual void Init(Framebuffer main) + { + Init(); + } + + public virtual void Draw(Framebuffer main) + { + + } + } +} \ No newline at end of file diff --git a/SMCode/SM.Base/PostProcess/PostProcessShader.cs b/SMCode/SM.Base/PostProcess/PostProcessShader.cs new file mode 100644 index 0000000..ac22477 --- /dev/null +++ b/SMCode/SM.Base/PostProcess/PostProcessShader.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using OpenTK.Graphics.OpenGL4; +using SM.Base.Objects.Static; +using SM.OGL.Framebuffer; +using SM.OGL.Shaders; +using SM.Utility; + +namespace SM.Base.PostProcess +{ + public class PostProcessShader : GenericShader + { + private static ShaderFile _fragExtensions = new ShaderFile(AssemblyUtility.ReadAssemblyFile("SM.Base.PostProcess.DefaultFiles.extensions.frag")); + private static ShaderFile _normalVertex = new ShaderFile(AssemblyUtility.ReadAssemblyFile("SM.Base.PostProcess.DefaultFiles.vertexFile.vert")); + private static string _normalVertexWithExt = + AssemblyUtility.ReadAssemblyFile("SM.Base.PostProcess.DefaultFiles.vertexWithExt.vert"); + + public PostProcessShader(string fragment) : this(_normalVertex, + new ShaderFile(fragment)) { } + + public PostProcessShader(string vertexExt, string fragment) : this(new ShaderFile(_normalVertexWithExt) + { + GLSLExtensions = new List() { new ShaderFile(vertexExt) } + }, new ShaderFile(fragment)) { } + + private PostProcessShader(ShaderFile vertex, ShaderFile fragment) : base( + new ShaderFileCollection(vertex, fragment)) + { + fragment.GLSLExtensions.Add(_fragExtensions); + } + + public void Draw(ColorAttachment color) + { + GL.UseProgram(this); + GL.BindVertexArray(Plate.Object); + + Uniforms["MVP"].SetMatrix4(PostProcessEffect.Mvp); + Uniforms["renderedTexture"].SetTexture(color, 0); + + GL.DrawArrays(PrimitiveType.Quads, 0, 4); + + GL.BindTexture(TextureTarget.Texture2D, 0); + GL.BindVertexArray(0); + GL.UseProgram(0); + } + + public void Draw(ColorAttachment color, Action setUniformAction) + { + GL.UseProgram(this); + GL.BindVertexArray(Plate.Object); + + Uniforms["MVP"].SetMatrix4(PostProcessEffect.Mvp); + Uniforms["renderedTexture"].SetTexture(color, 0); + + setUniformAction(Uniforms); + + GL.DrawArrays(PrimitiveType.Quads, 0, 4); + + GL.BindTexture(TextureTarget.Texture2D, 0); + GL.BindVertexArray(0); + GL.UseProgram(0); + } + } +} \ No newline at end of file diff --git a/SMCode/SM.Base/PostProcessing/PostProcessingEffect.cs b/SMCode/SM.Base/PostProcessing/PostProcessingEffect.cs deleted file mode 100644 index 85f01be..0000000 --- a/SMCode/SM.Base/PostProcessing/PostProcessingEffect.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Collections.Generic; -using SM.OGL.Framebuffer; - -namespace SM.Base.PostProcessing -{ - public abstract class PostProcessingEffect - { - public virtual Dictionary AdditionalFramebufferOutputs { get; } - public virtual ICollection AdditionalFramebuffers { get; } - - public void ApplyOutputs(Framebuffer mainbuffer) - { - mainbuffer.Append(); - } - } -} \ No newline at end of file diff --git a/SMCode/SM.Base/Properties/AssemblyInfo.cs b/SMCode/SM.Base/Properties/AssemblyInfo.cs index 5437322..a5dae53 100644 --- a/SMCode/SM.Base/Properties/AssemblyInfo.cs +++ b/SMCode/SM.Base/Properties/AssemblyInfo.cs @@ -1,16 +1,19 @@ -using System.Reflection; -using System.Runtime.CompilerServices; +#region usings + +using System.Reflection; using System.Runtime.InteropServices; +#endregion + // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("SM.Base")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyTitle("Basis for every SMRenderer")] +[assembly: AssemblyDescription("SMRenderer-Basis functions")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyCompany("iedSoftworks")] [assembly: AssemblyProduct("SM.Base")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2020")] +[assembly: AssemblyCopyright("Copyright © iedSoftworks 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -33,4 +36,4 @@ using System.Runtime.InteropServices; // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/SMCode/SM.Base/SM.Base.csproj b/SMCode/SM.Base/SM.Base.csproj index a6860d9..3cfafc1 100644 --- a/SMCode/SM.Base/SM.Base.csproj +++ b/SMCode/SM.Base/SM.Base.csproj @@ -34,8 +34,8 @@ latest - - ..\packages\OpenTK.3.2\lib\net20\OpenTK.dll + + ..\..\packages\OpenTK.3.2.1\lib\net20\OpenTK.dll @@ -43,27 +43,23 @@ - - - - - - - + - + + + @@ -81,6 +77,7 @@ + @@ -91,8 +88,9 @@ - - + + + @@ -100,6 +98,15 @@ SM.OGL - + + + + + + + + + + \ No newline at end of file diff --git a/SMCode/SM.Base/SMRenderer.cs b/SMCode/SM.Base/SMRenderer.cs index ac2f055..5585c00 100644 --- a/SMCode/SM.Base/SMRenderer.cs +++ b/SMCode/SM.Base/SMRenderer.cs @@ -1,33 +1,54 @@ -using SM.Base.Objects.Static; +#region usings + +using SM.Base.Objects.Static; +using SM.Base.Scene; using SM.Base.Text; using SM.OGL.Mesh; +using SM.OGL.Shaders; using SM.Utility; +#endregion + namespace SM.Base { /// - /// Contains different information about this renderer. + /// Contains different information about this renderer. /// public class SMRenderer { /// - /// The default mesh. + /// Defines, how many instances the 'SM_base_vertex_basic'-extension can handle. + /// + public const int MaxInstances = 32; + + /// + /// The default mesh. /// public static GenericMesh DefaultMesh = Plate.Object; /// - /// The default font. + /// The default font. /// public static Font DefaultFont; /// - /// The default deltatime helper. + /// The default deltatime helper. /// public static Deltatime DefaultDeltatime = new Deltatime(); + public static MaterialShader DefaultMaterialShader; + /// - /// Current Frame + /// Shows more information onto the log system. + /// + public static bool AdvancedDebugging = false; + + /// + /// Current Frame /// public static ulong CurrentFrame { get; internal set; } = 0; + + public static GenericWindow CurrentWindow; + public static GenericScene CurrentScene; } } \ No newline at end of file diff --git a/SMCode/SM.Base/Scene/GenericCamera.cs b/SMCode/SM.Base/Scene/GenericCamera.cs index 441b0a9..1742330 100644 --- a/SMCode/SM.Base/Scene/GenericCamera.cs +++ b/SMCode/SM.Base/Scene/GenericCamera.cs @@ -1,41 +1,52 @@ -using OpenTK; +#region usings + +using OpenTK; + +#endregion namespace SM.Base.Scene { /// - /// Controller for a camera + /// Controller for a camera /// public abstract class GenericCamera { /// - /// The matrix for the orthographic world. + /// The matrix for the orthographic world. /// public static Matrix4 OrthographicWorld { get; protected set; } + /// - /// The matrix for the perspective world. + /// The matrix for the perspective world. /// public static Matrix4 PerspectiveWorld { get; protected set; } + /// - /// This defines what is up. (Normalized) - /// Default: + /// This defines what is up. (Normalized) + /// Default: /// public static Vector3 UpVector { get; set; } = Vector3.UnitY; - + /// - /// Contains the view matrix of this camera. - /// Default: + /// Contains the view matrix of this camera. + /// Default: /// public Matrix4 ViewMatrix { get; protected set; } = Matrix4.Identity; /// - /// Returns the world matrix that is connected to this camera. + /// Returns the world matrix that is connected to this camera. /// public Matrix4 World => Orthographic ? OrthographicWorld : PerspectiveWorld; /// - /// Calculates the view matrix. + /// Represents if the camera is orthographic. /// - /// The calculated view matrix. Same as + public abstract bool Orthographic { get; } + + /// + /// Calculates the view matrix. + /// + /// The calculated view matrix. Same as internal Matrix4 CalculateViewMatrix() { ViewMatrix = ViewCalculation(); @@ -43,18 +54,17 @@ namespace SM.Base.Scene } /// - /// This calculates the view matrix. + /// This calculates the view matrix. /// - /// The new view matrix. This is the returns for and the next value for . + /// + /// The new view matrix. This is the returns for and the next value for + /// . + /// protected abstract Matrix4 ViewCalculation(); /// - /// Represents if the camera is orthographic. - /// - public abstract bool Orthographic { get; } - /// - /// This will calculate the world. - /// This is called on to calculate the world. + /// This will calculate the world. + /// This is called on to calculate the world. /// /// The world scale /// The aspect ratio from the window. diff --git a/SMCode/SM.Base/Scene/GenericItemCollection.cs b/SMCode/SM.Base/Scene/GenericItemCollection.cs index 3bfb483..d5a4ca9 100644 --- a/SMCode/SM.Base/Scene/GenericItemCollection.cs +++ b/SMCode/SM.Base/Scene/GenericItemCollection.cs @@ -1,10 +1,14 @@ -using System.Collections.Generic; +#region usings + +using System.Collections.Generic; using SM.Base.Contexts; +#endregion + namespace SM.Base.Scene { /// - /// Contains a list of show items. + /// Contains a list of show items. /// /// The type of show items. public abstract class GenericItemCollection : List, IShowItem, IShowCollection @@ -22,8 +26,32 @@ namespace SM.Base.Scene /// public ICollection Flags { get; set; } = new[] {"collection"}; + /// + public virtual void Update(UpdateContext context) + { + for (var i = 0; i < Objects.Count; i++) + this[i].Update(context); + } + + /// + public virtual void Draw(DrawContext context) + { + for (var i = 0; i < Objects.Count; i++) + this[i].Draw(context); + } + + /// + public virtual void OnAdded(object sender) + { + } + + /// + public virtual void OnRemoved(object sender) + { + } + /// - /// Adds a item. + /// Adds a item. /// public new void Add(TItem item) { @@ -33,7 +61,7 @@ namespace SM.Base.Scene } /// - /// Removes a item. + /// Removes a item. /// /// public new void Remove(TItem item) @@ -43,72 +71,46 @@ namespace SM.Base.Scene item.OnRemoved(this); } - /// - public virtual void Update(UpdateContext context) - { - for(int i = 0; i < Objects.Count; i++) - this[i].Update(context); - } - - /// - public virtual void Draw(DrawContext context) - { - for (int i = 0; i < Objects.Count; i++) - this[i].Draw(context); - } - - /// - public virtual void OnAdded(object sender) - { - - } - - /// - public virtual void OnRemoved(object sender) - { } - /// - /// Returns a object with this name or the default, if not available. - /// Not reclusive. + /// Returns a object with this name or the default, if not available. + /// Not reclusive. /// /// /// public TItem GetItemByName(string name) { TItem obj = default; - for (var i = 0; i < this.Count; i++) - { + for (var i = 0; i < Count; i++) if (this[i].Name == name) { obj = this[i]; break; } - } return obj; } /// - /// Returns a object with this name or the default if not available. - /// Not reclusive. + /// Returns a object with this name or the default if not available. + /// Not reclusive. /// /// Type of return public TGetItem GetItemByName(string name) where TGetItem : TItem { - return (TGetItem)GetItemByName(name); + return (TGetItem) GetItemByName(name); } /// - /// Returns all object that have this flag. - /// Only in this list. + /// Returns all object that have this flag. + /// Only in this list. /// public ICollection GetItemsWithFlag(string flag) { - List list = new List(); - for (var i = 0; i < this.Count; i++) + var list = new List(); + for (var i = 0; i < Count; i++) { - TItem obj = this[i]; + var obj = this[i]; if (obj.Flags.Contains(flag)) list.Add(obj); } @@ -117,7 +119,7 @@ namespace SM.Base.Scene } /// - /// Contains a list of show items with transformation. + /// Contains a list of show items with transformation. /// /// The type of show items. /// The type of transformation. @@ -126,7 +128,7 @@ namespace SM.Base.Scene where TTransformation : GenericTransformation, new() { /// - /// Transformation of the collection + /// Transformation of the collection /// public TTransformation Transform = new TTransformation(); @@ -134,7 +136,7 @@ namespace SM.Base.Scene public override void Draw(DrawContext context) { context.ModelMaster = Transform.GetMatrix() * context.ModelMaster; - + base.Draw(context); } } diff --git a/SMCode/SM.Base/Scene/GenericScene.cs b/SMCode/SM.Base/Scene/GenericScene.cs index 05b907b..37168a1 100644 --- a/SMCode/SM.Base/Scene/GenericScene.cs +++ b/SMCode/SM.Base/Scene/GenericScene.cs @@ -1,19 +1,22 @@ -using System; +#region usings + using System.Collections.Generic; -using OpenTK; +using System.Dynamic; using SM.Base.Contexts; +#endregion + namespace SM.Base.Scene { /// - /// A generic scene, that imports functions for scene control. + /// A generic scene, that imports functions for scene control. /// public abstract class GenericScene { private IBackgroundItem _background; - + /// - /// This contains the background. + /// This contains the background. /// protected IBackgroundItem _Background { @@ -24,41 +27,53 @@ namespace SM.Base.Scene _background = value; } } + public bool IsInitialized { get; private set; } /// - /// Updates this scene. + /// Updates this scene. /// /// public virtual void Update(UpdateContext context) { - } /// - /// Draws this scene. + /// Draws this scene. /// public virtual void Draw(DrawContext context) { - } /// - /// Called, when the user activates the scene. + /// Called, when the user activates the scene. /// internal void Activate() { + if (!IsInitialized) + { + OnInitialization(); + IsInitialized = true; + } + OnActivating(); } /// - /// Called, when the user activates the scene. + /// Called, when the user activates the scene for the first time. + /// + protected virtual void OnInitialization() + { } + + /// + /// Called, when the user activates the scene. /// protected virtual void OnActivating() - { } + { + } } /// - /// A generic scene that imports different functions. + /// A generic scene that imports different functions. /// /// The type of cameras. /// The type of show items. @@ -68,25 +83,32 @@ namespace SM.Base.Scene where TCollection : GenericItemCollection, new() where TItem : IShowItem { - private TCollection _objectCollection = new TCollection(); private TCollection _hud = new TCollection(); + private TCollection _objectCollection = new TCollection(); /// - /// The active camera, that is used if the context doesn't force the viewport camera. - /// If none set, it automaticly uses the viewport camera. + /// A collection for cameras to switch easier to different cameras. + /// + public Dictionary Cameras = new Dictionary(); + + /// + /// The active camera, that is used if the context doesn't force the viewport camera. + /// If none set, it automaticly uses the viewport camera. /// public TCamera Camera { get; set; } + /// - /// A camera to control the background. + /// A camera to control the background. /// public TCamera BackgroundCamera { get; set; } = new TCamera(); + /// - /// A camera to control the HUD. + /// A camera to control the HUD. /// public TCamera HUDCamera { get; set; } = new TCamera(); /// - /// Objects inside the scene. + /// Objects inside the scene. /// public TCollection Objects { @@ -99,7 +121,7 @@ namespace SM.Base.Scene } /// - /// This defines the HUD objects. + /// This defines the HUD objects. /// public TCollection HUD { @@ -110,10 +132,6 @@ namespace SM.Base.Scene _hud = value; } } - /// - /// A collection for cameras to switch easier to different cameras. - /// - public Dictionary Cameras = new Dictionary(); /// @@ -127,14 +145,28 @@ namespace SM.Base.Scene /// public override void Draw(DrawContext context) { - if (!context.ForceViewport && Camera != null) context.View = Camera.CalculateViewMatrix(); + DrawBackground(context); - DrawContext backgroundDrawContext = context; + DrawMainObjects(context); + + DrawHUD(context); + } + + public void DrawBackground(DrawContext context) + { + var backgroundDrawContext = context; backgroundDrawContext.View = BackgroundCamera.CalculateViewMatrix(); _Background?.Draw(backgroundDrawContext); + } + public void DrawMainObjects(DrawContext context) + { + if (!context.ForceViewport && Camera != null) context.View = Camera.CalculateViewMatrix(); _objectCollection.Draw(context); + } + public void DrawHUD(DrawContext context) + { context.View = HUDCamera.CalculateViewMatrix(); _hud.Draw(context); } diff --git a/SMCode/SM.Base/Scene/IBackgroundItem.cs b/SMCode/SM.Base/Scene/IBackgroundItem.cs index 9b0c59f..520bc61 100644 --- a/SMCode/SM.Base/Scene/IBackgroundItem.cs +++ b/SMCode/SM.Base/Scene/IBackgroundItem.cs @@ -1,10 +1,9 @@ namespace SM.Base.Scene { /// - /// A iteration of to reduce clutter. + /// A iteration of to reduce clutter. /// public interface IBackgroundItem : IShowItem { - } } \ No newline at end of file diff --git a/SMCode/SM.Base/Scene/IShowCollection.cs b/SMCode/SM.Base/Scene/IShowCollection.cs index 4af281f..19066b7 100644 --- a/SMCode/SM.Base/Scene/IShowCollection.cs +++ b/SMCode/SM.Base/Scene/IShowCollection.cs @@ -1,21 +1,25 @@ -using System.Collections.Generic; +#region usings + +using System.Collections.Generic; using SM.Base.Contexts; +#endregion + namespace SM.Base.Scene { /// - /// Adds functions, that is required for a collection. + /// Adds functions, that is required for a collection. /// /// The type of show item. public interface IShowCollection where TItem : IShowItem { /// - /// The object collection. + /// The object collection. /// List Objects { get; } /// - /// This draws the objects in the list. + /// This draws the objects in the list. /// /// The context how the objects need to be drawn. void Draw(DrawContext context); diff --git a/SMCode/SM.Base/Scene/IShowItem.cs b/SMCode/SM.Base/Scene/IShowItem.cs index 677606d..5121b9f 100644 --- a/SMCode/SM.Base/Scene/IShowItem.cs +++ b/SMCode/SM.Base/Scene/IShowItem.cs @@ -1,45 +1,51 @@ -using System.Collections.Generic; +#region usings + +using System.Collections.Generic; using SM.Base.Contexts; +#endregion + namespace SM.Base.Scene { /// - /// Adds requirements to object, to be properly used as a update and/or draw item. + /// Adds requirements to object, to be properly used as a update and/or draw item. /// public interface IShowItem { /// - /// Parent of the object. + /// Parent of the object. /// object Parent { get; set; } /// - /// Contains the name for the object. + /// Contains the name for the object. /// string Name { get; set; } /// - /// Contains specific flags for the object. + /// Contains specific flags for the object. /// ICollection Flags { get; set; } /// - /// Tells the object to update own systems. + /// Tells the object to update own systems. /// /// The update context void Update(UpdateContext context); + /// - /// Tells the object to draw its object. + /// Tells the object to draw its object. /// /// void Draw(DrawContext context); /// - /// Action, that is called, when the object was added to a GenericItemCollection. + /// Action, that is called, when the object was added to a GenericItemCollection. /// void OnAdded(object sender); + /// - /// Action, that is called, when the object was removed from a GenericItemCollection. + /// Action, that is called, when the object was removed from a GenericItemCollection. /// void OnRemoved(object sender); } diff --git a/SMCode/SM.Base/ShaderExtension/ExtensionManager.cs b/SMCode/SM.Base/ShaderExtension/ExtensionManager.cs new file mode 100644 index 0000000..2999fca --- /dev/null +++ b/SMCode/SM.Base/ShaderExtension/ExtensionManager.cs @@ -0,0 +1,19 @@ +#region usings + +using SM.OGL.Shaders; + +#endregion + +namespace SM.Base.ShaderExtension +{ + internal class ExtensionManager + { + internal static void InitExtensions() + { + ShaderExtensions.AddAssemblyExtensions("SM_base", "SM.Base.ShaderExtension"); + + ShaderExtensions.Extensions["SM_base_vertex_basic"].StringOverrides["instanceMax"] = + SMRenderer.MaxInstances.ToString(); + } + } +} \ No newline at end of file diff --git a/SMCode/SM.Base/ShaderExtension/vertex/basic.vert b/SMCode/SM.Base/ShaderExtension/vertex/basic.vert new file mode 100644 index 0000000..a5b7caa --- /dev/null +++ b/SMCode/SM.Base/ShaderExtension/vertex/basic.vert @@ -0,0 +1,35 @@ +#version 330 +#define maxInstances //!instanceMax + +struct Instance { + mat4 ModelMatrix; + vec2 TextureOffset; + vec2 TextureScale; +}; + +layout(location = 0) in vec3 aPos; +layout(location = 1) in vec2 aTex; +layout(location = 3) in vec4 aColor; + +uniform mat4 MVP; +uniform bool HasVColor; +uniform Instance[maxInstances] Instances; + +out vec2 vTexture; +out vec4 vColor; +out vec3 FragPos; + +void ApplyTexModifier() { + vTexture = aTex * Instances[gl_InstanceID].TextureScale + Instances[gl_InstanceID].TextureOffset; +} + +void CheckVertexColor() { + if (HasVColor) vColor = aColor; + else vColor = vec4(1); +} + +void ApplyModelTransformation() { + gl_Position = MVP * Instances[gl_InstanceID].ModelMatrix * vec4(aPos, 1); + + FragPos = vec3(Instances[gl_InstanceID].ModelMatrix * vec4(aPos, 1)); +} \ No newline at end of file diff --git a/SMCode/SM.Base/Text/CharParameter.cs b/SMCode/SM.Base/Text/CharParameter.cs index cb9f3b3..d5da9e9 100644 --- a/SMCode/SM.Base/Text/CharParameter.cs +++ b/SMCode/SM.Base/Text/CharParameter.cs @@ -1,28 +1,34 @@ -using System; +#region usings + +using System; + +#endregion namespace SM.Base.Text { /// - /// Contains information for a font character. + /// Contains information for a font character. /// [Serializable] public struct CharParameter { /// - /// The position on the X-axis. + /// The position on the X-axis. /// public int X; + /// - /// The width of the character. + /// The width of the character. /// public float Width; /// - /// The normalized position inside the texture. + /// The normalized position inside the texture. /// public float NormalizedX; + /// - /// The normalized width inside the texture. + /// The normalized width inside the texture. /// public float NormalizedWidth; } diff --git a/SMCode/SM.Base/Text/Font.cs b/SMCode/SM.Base/Text/Font.cs index b8cbfd0..4be852c 100644 --- a/SMCode/SM.Base/Text/Font.cs +++ b/SMCode/SM.Base/Text/Font.cs @@ -1,71 +1,74 @@ -using System.Collections.Generic; +#region usings + +using System.Collections.Generic; using System.Drawing; using System.Drawing.Text; -using System.Security.Policy; -using OpenTK; using OpenTK.Graphics.OpenGL4; -using OpenTK.Input; using SM.Base.Textures; using SM.Data.Fonts; -using SM.OGL.Texture; + +#endregion namespace SM.Base.Text { /// - /// Represents a font. + /// Represents a font. /// public class Font : Texture { - /// - public override TextureWrapMode WrapMode { get; set; } = TextureWrapMode.ClampToEdge; - /// - /// The font family, that is used to find the right font. - /// - public FontFamily FontFamily; - - /// - /// The font style. - /// Default: - /// - public FontStyle FontStyle = FontStyle.Regular; - /// - /// The font size. - /// Default: 12 - /// - public float FontSize = 12; - /// - /// The char set for the font. - /// Default: + /// The char set for the font. + /// Default: /// public ICollection CharSet = FontCharStorage.SimpleUTF8; /// - /// This contains all information for the different font character. + /// The font family, that is used to find the right font. + /// + public FontFamily FontFamily; + + /// + /// The font size. + /// Default: 12 + /// + public float FontSize = 12; + + /// + /// The font style. + /// Default: + /// + public FontStyle FontStyle = FontStyle.Regular; + + /// + /// This contains all information for the different font character. /// public Dictionary Positions = new Dictionary(); /// - /// Generates a font from a font family from the specified path. + /// Generates a font from a font family from the specified path. /// /// The specified path public Font(string path) { - PrivateFontCollection pfc = new PrivateFontCollection(); + var pfc = new PrivateFontCollection(); pfc.AddFontFile(path); FontFamily = pfc.Families[0]; } /// - /// Generates a font from a specified font family. + /// Generates a font from a specified font family. /// /// Font-Family public Font(FontFamily font) { FontFamily = font; } + + /// + public override TextureWrapMode WrapMode { get; set; } = TextureWrapMode.ClampToEdge; + /// - /// Regenerates the texture. + /// Regenerates the texture. /// public void RegenerateTexture() { @@ -74,47 +77,47 @@ namespace SM.Base.Text Positions = new Dictionary(); - Bitmap map = new Bitmap(1000, 20); - Dictionary charParams = new Dictionary(); - using (System.Drawing.Font f = new System.Drawing.Font(FontFamily, FontSize, FontStyle)) + var map = new Bitmap(1000, 20); + var charParams = new Dictionary(); + using (var f = new System.Drawing.Font(FontFamily, FontSize, FontStyle)) { - using (Graphics g = Graphics.FromImage(map)) + using (var g = Graphics.FromImage(map)) { g.Clear(Color.Transparent); - foreach (char c in CharSet) + foreach (var c in CharSet) { - string s = c.ToString(); - SizeF size = g.MeasureString(s, f); + var s = c.ToString(); + var size = g.MeasureString(s, f); try { - charParams.Add(c, new[] {size.Width, Width }); + charParams.Add(c, new[] {size.Width, Width}); } catch { // ignored } - if (Height < size.Height) Height = (int)size.Height; - Width += (int)size.Width; + if (Height < size.Height) Height = (int) size.Height; + Width += (int) size.Width; } } map = new Bitmap(Width, Height); - using (Graphics g = Graphics.FromImage(map)) + using (var g = Graphics.FromImage(map)) { - foreach (KeyValuePair keyValuePair in charParams) + foreach (var keyValuePair in charParams) { - float normalizedX = (keyValuePair.Value[1] + 0.00001f) / Width; - float normalizedWidth = (keyValuePair.Value[0]) / Width; + var normalizedX = (keyValuePair.Value[1] + 0.00001f) / Width; + var normalizedWidth = keyValuePair.Value[0] / Width; CharParameter parameter; - Positions.Add(keyValuePair.Key, parameter = new CharParameter() + Positions.Add(keyValuePair.Key, parameter = new CharParameter { NormalizedWidth = normalizedWidth, NormalizedX = normalizedX, Width = keyValuePair.Value[0], - X = (int)keyValuePair.Value[1] + X = (int) keyValuePair.Value[1] }); g.DrawString(keyValuePair.Key.ToString(), f, Brushes.White, parameter.X, 0); diff --git a/SMCode/SM.Base/Text/FontCharStorage.cs b/SMCode/SM.Base/Text/FontCharStorage.cs index df95c98..4a4a59f 100644 --- a/SMCode/SM.Base/Text/FontCharStorage.cs +++ b/SMCode/SM.Base/Text/FontCharStorage.cs @@ -1,28 +1,29 @@ namespace SM.Data.Fonts { /// - /// Contains default char sets. + /// Contains default char sets. /// public class FontCharStorage { /// - /// Contains the english alphabet and the common special character. + /// Contains the english alphabet and the common special character. /// - public static readonly char[] SimpleUTF8 = new char[] + public static readonly char[] SimpleUTF8 = { - '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', + '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~' }; + /// - /// Contains only numbers. + /// Contains only numbers. /// - public static readonly char[] Numbers = new[] + public static readonly char[] Numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; - } } \ No newline at end of file diff --git a/SMCode/SM.Base/Text/TextDrawingBasis.cs b/SMCode/SM.Base/Text/TextDrawingBasis.cs index 07bd17d..fa32628 100644 --- a/SMCode/SM.Base/Text/TextDrawingBasis.cs +++ b/SMCode/SM.Base/Text/TextDrawingBasis.cs @@ -1,30 +1,49 @@ -using System; +#region usings + +using System; using OpenTK; using OpenTK.Graphics; using SM.Base.Contexts; using SM.Base.Scene; -using SM.Data.Fonts; + +#endregion namespace SM.Base.Text { /// - /// Defines a basis for text drawing. + /// Defines a basis for text drawing. /// /// Transformation type public abstract class TextDrawingBasis : DrawingBasis where TTransform : GenericTransformation, new() { /// - /// The different instances for drawing. + /// The different instances for drawing. /// protected Instance[] _instances; + /// - /// The text, that is drawn. + /// The text, that is drawn. /// protected string _text; /// - /// The font. + /// The spacing between numbers. + /// Default: 1 + /// + public float Spacing = 1; + + /// + /// Creates a text object with a font. + /// + /// The font. + protected TextDrawingBasis(Font font) + { + _material.Texture = font; + } + + /// + /// The font. /// public Font Font { @@ -37,7 +56,7 @@ namespace SM.Base.Text } /// - /// The text, that is drawn. + /// The text, that is drawn. /// public string Text { @@ -50,7 +69,7 @@ namespace SM.Base.Text } /// - /// The font color. + /// The font color. /// public Color4 Color { @@ -58,21 +77,6 @@ namespace SM.Base.Text set => _material.Tint = value; } - /// - /// The spacing between numbers. - /// Default: 1 - /// - public float Spacing = 1; - - /// - /// Creates a text object with a font. - /// - /// The font. - protected TextDrawingBasis(Font font) - { - _material.Texture = font; - } - /// protected override void DrawContext(ref DrawContext context) @@ -81,7 +85,7 @@ namespace SM.Base.Text } /// - /// This generates the instances. + /// This generates the instances. /// /// The font doesn't contain a character that is needed for the text. public void GenerateMatrixes() @@ -91,7 +95,7 @@ namespace SM.Base.Text _instances = new Instance[_text.Length]; float x = 0; - CharParameter _last = new CharParameter(); + var _last = new CharParameter(); for (var i = 0; i < _text.Length; i++) { if (_text[i] == 32) @@ -99,7 +103,7 @@ namespace SM.Base.Text x += _last.Width * Spacing; continue; } - + CharParameter parameter; try { @@ -110,15 +114,15 @@ namespace SM.Base.Text throw new Exception("Font doesn't contain '" + _text[i] + "'"); } - Matrix4 matrix = Matrix4.CreateScale(parameter.Width, Font.Height, 1) * - Matrix4.CreateTranslation(x, 0, 0); + var matrix = Matrix4.CreateScale(parameter.Width, Font.Height, 1) * + Matrix4.CreateTranslation(x, 0, 0); _instances[i] = new Instance { ModelMatrix = matrix, TexturePosition = new Vector2(parameter.NormalizedX, 0), TextureScale = new Vector2(parameter.NormalizedWidth, 1) }; - + x += parameter.Width * Spacing; _last = parameter; } diff --git a/SMCode/SM.Base/Textures/Texture.cs b/SMCode/SM.Base/Textures/Texture.cs index 2fc5a96..8908308 100644 --- a/SMCode/SM.Base/Textures/Texture.cs +++ b/SMCode/SM.Base/Textures/Texture.cs @@ -1,38 +1,48 @@ -using System.Drawing; +#region usings + +using System.Drawing; using System.Drawing.Imaging; using OpenTK.Graphics.OpenGL4; using SM.OGL.Texture; using PixelFormat = System.Drawing.Imaging.PixelFormat; +#endregion + namespace SM.Base.Textures { /// - /// Texture that can be drawn to an object. + /// Texture that can be drawn to an object. /// public class Texture : TextureBase { /// - /// The texture as bitmap. - /// - public Bitmap Map; - /// - /// Decides if the bitmap will automatically dispose itself. + /// Decides if the bitmap will automatically dispose itself. /// public bool AutoDispose = false; /// - /// Empty constructor + /// The texture as bitmap. /// - protected Texture() {} + public Bitmap Map; /// - /// Creates a texture with only the map. - /// Sets the filter to Linear and WrapMode to Repeat. + /// Empty constructor + /// + protected Texture() + { + } + + /// + /// Creates a texture with only the map. + /// Sets the filter to Linear and WrapMode to Repeat. /// /// The map - public Texture(Bitmap map) : this(map, TextureMinFilter.Linear, TextureWrapMode.Repeat) {} + public Texture(Bitmap map) : this(map, TextureMinFilter.Linear, TextureWrapMode.Repeat) + { + } + /// - /// Creates the texture. + /// Creates the texture. /// /// The texture map /// The filter @@ -62,22 +72,23 @@ namespace SM.Base.Textures } /// - /// Generates a OpenGL-texture. + /// Generates a OpenGL-texture. /// /// The texture as bitmap /// The filter /// The wrap mode /// Auto dispose of the bitmap? Default: false /// - public static int GenerateTexture(Bitmap map, TextureMinFilter filter, TextureWrapMode wrapMode, bool dispose = false) + public static int GenerateTexture(Bitmap map, TextureMinFilter filter, TextureWrapMode wrapMode, + bool dispose = false) { - int id = GL.GenTexture(); + var id = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, id); - BitmapData data = map.LockBits(new Rectangle(0, 0, map.Width, map.Height), ImageLockMode.ReadOnly, + var data = map.LockBits(new Rectangle(0, 0, map.Width, map.Height), ImageLockMode.ReadOnly, map.PixelFormat); - bool transparenz = map.PixelFormat == PixelFormat.Format32bppArgb; + var transparenz = map.PixelFormat == PixelFormat.Format32bppArgb; GL.TexImage2D(TextureTarget.Texture2D, 0, transparenz ? PixelInternalFormat.Rgba : PixelInternalFormat.Rgb, @@ -85,10 +96,10 @@ namespace SM.Base.Textures transparenz ? OpenTK.Graphics.OpenGL4.PixelFormat.Bgra : OpenTK.Graphics.OpenGL4.PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)filter); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)filter); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)wrapMode); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)wrapMode); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) filter); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) filter); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) wrapMode); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) wrapMode); GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); @@ -101,8 +112,11 @@ namespace SM.Base.Textures } /// - /// Converts a bitmap to a texture. + /// Converts a bitmap to a texture. /// - public static implicit operator Texture(Bitmap map) => new Texture(map); + public static implicit operator Texture(Bitmap map) + { + return new Texture(map); + } } } \ No newline at end of file diff --git a/SMCode/SM.Base/Time/Interval.cs b/SMCode/SM.Base/Time/Interval.cs index bafd602..dcbeb75 100644 --- a/SMCode/SM.Base/Time/Interval.cs +++ b/SMCode/SM.Base/Time/Interval.cs @@ -1,10 +1,14 @@ -using System; +#region usings + +using System; using SM.Base.Contexts; +#endregion + namespace SM.Base.Time { /// - /// Performs intervals. + /// Performs intervals. /// public class Interval : Timer { @@ -24,13 +28,14 @@ namespace SM.Base.Time protected override void Stopping(UpdateContext context) { TriggerEndAction(context); - if (_stop){base.Stop();} + if (_stop) + base.Stop(); else Reset(); } /// - /// This will tell the interval to stop after the next iteration. - /// To stop immediately use + /// This will tell the interval to stop after the next iteration. + /// To stop immediately use /// public override void Stop() { @@ -38,7 +43,7 @@ namespace SM.Base.Time } /// - /// This will stop the interval immediately. + /// This will stop the interval immediately. /// public void Cancel() { diff --git a/SMCode/SM.Base/Time/Stopwatch.cs b/SMCode/SM.Base/Time/Stopwatch.cs index bf1bab6..e064c2e 100644 --- a/SMCode/SM.Base/Time/Stopwatch.cs +++ b/SMCode/SM.Base/Time/Stopwatch.cs @@ -1,22 +1,26 @@ -using System.Collections.Generic; +#region usings + +using System.Collections.Generic; using SM.Base.Contexts; +#endregion + namespace SM.Base.Time { /// - /// Represents a stopwatch. + /// Represents a stopwatch. /// public class Stopwatch { private static List _activeStopwatches = new List(); /// - /// Contains how much time already has passed. (in seconds) + /// Contains how much time already has passed. (in seconds) /// public float Elapsed { get; private set; } /// - /// Starts the stopwatch. + /// Starts the stopwatch. /// public virtual void Start() { @@ -24,7 +28,7 @@ namespace SM.Base.Time } /// - /// Performs a tick. + /// Performs a tick. /// /// private protected virtual void Tick(UpdateContext context) @@ -33,7 +37,7 @@ namespace SM.Base.Time } /// - /// Stops the stopwatch. + /// Stops the stopwatch. /// public virtual void Stop() { @@ -41,7 +45,7 @@ namespace SM.Base.Time } /// - /// Resets the stopwatch. + /// Resets the stopwatch. /// public void Reset() { @@ -50,10 +54,7 @@ namespace SM.Base.Time internal static void PerformTicks(UpdateContext context) { - for (var i = 0; i < _activeStopwatches.Count; i++) - { - _activeStopwatches[i].Tick(context); - } + for (var i = 0; i < _activeStopwatches.Count; i++) _activeStopwatches[i].Tick(context); } } } \ No newline at end of file diff --git a/SMCode/SM.Base/Time/Timer.cs b/SMCode/SM.Base/Time/Timer.cs index 473cf05..f25425b 100644 --- a/SMCode/SM.Base/Time/Timer.cs +++ b/SMCode/SM.Base/Time/Timer.cs @@ -1,31 +1,19 @@ -using System; -using System.Collections.Generic; +#region usings + +using System; using SM.Base.Contexts; +#endregion + namespace SM.Base.Time { /// - /// Timer-System + /// Timer-System /// public class Timer : Stopwatch { - /// - /// The target time in seconds. - /// - public float Target { get; private set; } - /// - /// The already elapsed time but normalized to the target. - /// - public float ElapsedNormalized { get; private set; } - - /// - /// The event, that is triggered when the timer stops. - /// - public event Action EndAction; - - /// - /// Creates a timer with specified seconds. + /// Creates a timer with specified seconds. /// /// public Timer(float seconds) @@ -34,14 +22,29 @@ namespace SM.Base.Time } /// - /// Creates a timer with a time span. + /// Creates a timer with a time span. /// /// public Timer(TimeSpan timeSpan) { - Target = (float)timeSpan.TotalSeconds; + Target = (float) timeSpan.TotalSeconds; } + /// + /// The target time in seconds. + /// + public float Target { get; private set; } + + /// + /// The already elapsed time but normalized to the target. + /// + public float ElapsedNormalized { get; private set; } + + /// + /// The event, that is triggered when the timer stops. + /// + public event Action EndAction; + /// public override void Start() { @@ -58,15 +61,16 @@ namespace SM.Base.Time } /// - /// Occurs, when the timer tries to stop. + /// Occurs, when the timer tries to stop. /// protected virtual void Stopping(UpdateContext context) { EndAction?.Invoke(this, context); Stop(); } + /// - /// This will trigger + /// This will trigger /// /// protected void TriggerEndAction(UpdateContext context) diff --git a/SMCode/SM.Base/Types/CVector.cs b/SMCode/SM.Base/Types/CVector.cs index 12462a1..ceaa22d 100644 --- a/SMCode/SM.Base/Types/CVector.cs +++ b/SMCode/SM.Base/Types/CVector.cs @@ -1,146 +1,145 @@ -using System; -using System.Configuration.Assemblies; +#region usings + using System.Diagnostics; using OpenTK; +#endregion + namespace SM.Base.Types { /// - /// Represents a base vector-class + /// Represents a base vector-class /// public abstract class CVector { - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private float _x = default; - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private float _y = default; - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private float _z = default; - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private float _w = default; - /// - /// The X-component. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - protected float _X - { - get => _x; - set => _x = value; - } - /// - /// The Y-component - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - protected float _Y - { - get => _y; - set => _y = value; - } - /// - /// The Z-component. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - protected float _Z - { - get => _z; - set => _z = value; - } - /// - /// The W-component. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - protected float _W - { - get => _w; - set => _w = value; - } - - /// - /// Creates a vector by setting every component to the same value. + /// Creates a vector by setting every component to the same value. /// protected CVector(float uniform) : this(uniform, uniform, uniform, uniform) - { } + { + } /// - /// Creates a vector by setting values for each component. + /// Creates a vector by setting values for each component. /// protected CVector(float x, float y, float z, float w) { - _x = x; - _y = y; - _z = z; - _w = w; + _X = x; + _Y = y; + _Z = z; + _W = w; } + + /// + /// The X-component. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + protected float _X { get; set; } + + /// + /// The Y-component + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + protected float _Y { get; set; } + + /// + /// The Z-component. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + protected float _Z { get; set; } + + /// + /// The W-component. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + protected float _W { get; set; } + + /// + /// Transforms a to a + /// + public static implicit operator Vector2(CVector v) => new Vector2(v._X, v._Y); + + /// + /// Transforms a to a + /// + public static implicit operator Vector3(CVector v) => new Vector3(v._X, v._Y, v._Z); + + /// + /// Transforms a to a + /// + public static implicit operator Vector4(CVector v) => new Vector4(v._X, v._Y, v._Z, v._W); #region Set + /// - /// Sets the X and Y-component. + /// Sets the X and Y-component. /// protected void Set(float x, float y) { _X = x; _Y = y; } + /// - /// Sets the X and Y-component from a + /// Sets the X and Y-component from a /// - protected void Set(OpenTK.Vector2 vector) + protected void Set(Vector2 vector) { Set(vector.X, vector.Y); } /// - /// Sets the X, Y and Z-component. + /// Sets the X, Y and Z-component. /// protected void Set(float x, float y, float z) { - Set(x,y); + Set(x, y); _Z = z; } /// - /// Sets the X, Y and Z-component from a . + /// Sets the X, Y and Z-component from a . /// /// - protected void Set(OpenTK.Vector3 vector) + protected void Set(Vector3 vector) { Set(vector.X, vector.Y, vector.Z); } /// - /// Sets the X, Y, Z and W-component. + /// Sets the X, Y, Z and W-component. /// protected void Set(float x, float y, float z, float w) { - Set(x,y,z); + Set(x, y, z); _W = w; } /// - /// Sets the X, Y, Z and W-component from a . + /// Sets the X, Y, Z and W-component from a . /// - protected void Set(OpenTK.Vector4 vector) + protected void Set(Vector4 vector) { Set(vector.X, vector.Y, vector.Z, vector.W); } + #endregion #region Add /// - /// Adds a to the X and Y-component. + /// Adds a to the X and Y-component. /// - protected void Add(OpenTK.Vector2 vector) + protected void Add(Vector2 vector) { _X += vector.X; _Y += vector.Y; } /// - /// Adds a to the X, Y and Z-component. + /// Adds a to the X, Y and Z-component. /// - protected void Add(OpenTK.Vector3 vector) + protected void Add(Vector3 vector) { _X += vector.X; _Y += vector.Y; @@ -148,9 +147,9 @@ namespace SM.Base.Types } /// - /// Adds a to the X, Y, Z and W-component. + /// Adds a to the X, Y, Z and W-component. /// - protected void Add(OpenTK.Vector4 vector) + protected void Add(Vector4 vector) { _X += vector.X; _Y += vector.Y; @@ -159,18 +158,5 @@ namespace SM.Base.Types } #endregion - - /// - /// Transforms a to a - /// - public static implicit operator OpenTK.Vector2(CVector v) => new OpenTK.Vector2(v._x, v._y); - /// - /// Transforms a to a - /// - public static implicit operator OpenTK.Vector3(CVector v) => new OpenTK.Vector3(v._x, v._y, v._z); - /// - /// Transforms a to a - /// - public static implicit operator OpenTK.Vector4(CVector v) => new OpenTK.Vector4(v._x, v._y, v._z, v._w); } } \ No newline at end of file diff --git a/SMCode/SM.Base/Types/CVector2.cs b/SMCode/SM.Base/Types/CVector2.cs index 3e3d826..3fdf66b 100644 --- a/SMCode/SM.Base/Types/CVector2.cs +++ b/SMCode/SM.Base/Types/CVector2.cs @@ -1,20 +1,47 @@ -namespace SM.Base.Types +#region usings + +using OpenTK; + +#endregion + +namespace SM.Base.Types { /// - /// Represents a vector of two floats. + /// Represents a vector of two floats. /// public class CVector2 : CVector { + /// + public CVector2() : this(0) + { + } + + /// + public CVector2(float uniform) : base(uniform) + { + } + + /// + public CVector2(float x, float y) : base(x, y, default, default) + { + } + + /// + protected CVector2(float x, float y, float z, float w) : base(x, y, z, w) + { + } + /// - /// X-component + /// X-component /// public float X { get => _X; set => _X = value; } + /// - /// Y-component + /// Y-component /// public float Y { @@ -22,35 +49,30 @@ set => _Y = value; } - /// - public CVector2() : this(0) - {} - - /// - public CVector2(float uniform) : base(uniform) + /// + /// Sets the X and Y-component. + /// + public new void Set(float x, float y) { - + base.Set(x, y); } - /// - public CVector2(float x, float y) : base(x,y, default, default) {} - - /// - protected CVector2(float x, float y, float z, float w) : base(x, y, z, w) {} + /// + /// Sets the X and Y-component from a + /// + public new void Set(Vector2 vector) + { + base.Set(vector); + } /// - /// Sets the X and Y-component. + /// Adds a to the X and Y-component. /// - public new void Set(float x, float y) => base.Set(x, y); + public new void Add(Vector2 vector) + { + base.Add(vector); + } - /// - /// Sets the X and Y-component from a - /// - public new void Set(OpenTK.Vector2 vector) => base.Set(vector); - - /// - /// Adds a to the X and Y-component. - /// - public new void Add(OpenTK.Vector2 vector) => base.Add(vector); + public static implicit operator CVector2(Vector2 v) => new CVector2(v.X,v.Y); } } \ No newline at end of file diff --git a/SMCode/SM.Base/Types/CVector3.cs b/SMCode/SM.Base/Types/CVector3.cs index cc52788..6fb9a53 100644 --- a/SMCode/SM.Base/Types/CVector3.cs +++ b/SMCode/SM.Base/Types/CVector3.cs @@ -1,16 +1,33 @@ -using System.Drawing.Design; -using System.Runtime.InteropServices; +#region usings + using OpenTK; +#endregion + namespace SM.Base.Types { /// - /// Represents a Vector of three floats. + /// Represents a Vector of three floats. /// public class CVector3 : CVector2 { + /// + public CVector3(float uniform) : base(uniform) + { + } + + /// + public CVector3(float x, float y, float z) : base(x, y, z, default) + { + } + + /// + protected CVector3(float x, float y, float z, float w) : base(x, y, z, w) + { + } + /// - /// Z-component + /// Z-component /// public float Z { @@ -18,29 +35,28 @@ namespace SM.Base.Types set => _Z = value; } - /// - public CVector3(float uniform) : base(uniform) - { } - - /// - public CVector3(float x, float y, float z) : base(x, y, z, default) - { } - - /// - protected CVector3(float x, float y, float z, float w) : base(x, y, z, w) { } - /// - /// Sets the X, Y and Z-component. + /// Sets the X, Y and Z-component. /// - public new void Set(float x, float y, float z) => base.Set(x, y, z); - /// - /// Sets the X, Y and Z-component from a . - /// - public new void Set(Vector3 vector) => base.Set(vector); + public new void Set(float x, float y, float z) + { + base.Set(x, y, z); + } /// - /// Adds a to the X, Y and Z-component. + /// Sets the X, Y and Z-component from a . /// - public new void Add(Vector3 vector) => base.Add(vector); + public new void Set(Vector3 vector) + { + base.Set(vector); + } + + /// + /// Adds a to the X, Y and Z-component. + /// + public new void Add(Vector3 vector) + { + base.Add(vector); + } } } \ No newline at end of file diff --git a/SMCode/SM.Base/Types/CVector4.cs b/SMCode/SM.Base/Types/CVector4.cs index b4cbf74..0aafe3e 100644 --- a/SMCode/SM.Base/Types/CVector4.cs +++ b/SMCode/SM.Base/Types/CVector4.cs @@ -1,21 +1,16 @@ -using OpenTK; +#region usings + +using OpenTK; + +#endregion namespace SM.Base.Types { /// - /// Represents a vector of four floats. + /// Represents a vector of four floats. /// public class CVector4 : CVector3 { - /// - /// W-component - /// - public float W - { - get => _W; - set => _W = value; - } - /// public CVector4(float uniform) : base(uniform) { @@ -27,16 +22,36 @@ namespace SM.Base.Types } /// - /// Sets the X, Y, Z and W-component. + /// W-component /// - public new void Set(float x, float y, float z, float w) => base.Set(x, y, z, w); + public float W + { + get => _W; + set => _W = value; + } + /// - /// Sets the X, Y, Z and W-component from a . + /// Sets the X, Y, Z and W-component. /// - public new void Set(Vector4 vector) => base.Set(vector); + public new void Set(float x, float y, float z, float w) + { + base.Set(x, y, z, w); + } + /// - /// Adds a to the X, Y, Z and W-component. + /// Sets the X, Y, Z and W-component from a . /// - public new void Add(Vector4 vector) => base.Add(vector); + public new void Set(Vector4 vector) + { + base.Set(vector); + } + + /// + /// Adds a to the X, Y, Z and W-component. + /// + public new void Add(Vector4 vector) + { + base.Add(vector); + } } } \ No newline at end of file diff --git a/SMCode/SM.Base/Utility/Assembly.cs b/SMCode/SM.Base/Utility/Assembly.cs index 5fb8d98..5f93981 100644 --- a/SMCode/SM.Base/Utility/Assembly.cs +++ b/SMCode/SM.Base/Utility/Assembly.cs @@ -1,43 +1,60 @@ -using System; +#region usings + +using System; using System.IO; using System.Reflection; +#endregion + namespace SM.Utility { /// - /// Contains utility functions for handling with assemblies. + /// Contains utility functions for handling with assemblies. /// public class AssemblyUtility { /// - /// Read a file that is saved in a assembly + /// Read a file that is saved in a assembly /// /// The assembly that contains the file /// The path to the file inside the assembly /// - public static string ReadAssemblyFile(Assembly ass, string path) { return new StreamReader(GetAssemblyStream(ass, path)).ReadToEnd(); } + public static string ReadAssemblyFile(Assembly ass, string path) + { + return new StreamReader(GetAssemblyStream(ass, path)).ReadToEnd(); + } /// - /// Read a file that is saved in the calling assembly + /// Read a file that is saved in the calling assembly /// /// The path to the file inside the assembly /// - public static string ReadAssemblyFile(string path) { return ReadAssemblyFile(Assembly.GetCallingAssembly(), path); } + public static string ReadAssemblyFile(string path) + { + return ReadAssemblyFile(Assembly.GetCallingAssembly(), path); + } /// - /// Returns a stream of a requested resource. + /// Returns a stream of a requested resource. /// /// The assembly the resource is in. /// The path to the resource. /// The stream - public static Stream GetAssemblyStream(Assembly ass, string path) { return ass.GetManifestResourceStream(path) ?? throw new InvalidOperationException("Assembly couldn't find resource at path '" + path + "'."); } + public static Stream GetAssemblyStream(Assembly ass, string path) + { + return ass.GetManifestResourceStream(path) ?? + throw new InvalidOperationException("Assembly couldn't find resource at path '" + path + "'."); + } /// - /// Returns a stream of a requested resource in the calling assembly. + /// Returns a stream of a requested resource in the calling assembly. /// /// The path to the resource /// The stream - public static Stream GetAssemblyStream(string path) { return GetAssemblyStream(Assembly.GetCallingAssembly(), path); } + public static Stream GetAssemblyStream(string path) + { + return GetAssemblyStream(Assembly.GetCallingAssembly(), path); + } } } \ No newline at end of file diff --git a/SMCode/SM.Base/Utility/Deltatime.cs b/SMCode/SM.Base/Utility/Deltatime.cs index 2e46e6d..125ab79 100644 --- a/SMCode/SM.Base/Utility/Deltatime.cs +++ b/SMCode/SM.Base/Utility/Deltatime.cs @@ -1,46 +1,49 @@ namespace SM.Utility { /// - /// A assistant to control the delta time. + /// A assistant to control the delta time. /// public class Deltatime { /// - /// The current update delta time. - /// - public static float UpdateDelta { get; internal set; } - /// - /// The current render delta time. - /// - public static float RenderDelta { get; internal set; } - - /// - /// If true, it uses , otherwise . - /// Default: false - /// - public bool UseRender; - /// - /// Scaling of the delta time. - /// Default: 1 + /// Scaling of the delta time. + /// Default: 1 /// public float Scale; /// - /// The calculated delta time. + /// If true, it uses , otherwise . + /// Default: false /// - public float DeltaTime => (UseRender ? RenderDelta : UpdateDelta) * Scale; + public bool UseRender; /// - /// Creates a delta time assistant. + /// Creates a delta time assistant. /// /// The start scale for the delta time. Default: 1 - /// If true, it uses , otherwise . Default: false - public Deltatime(float scale = 1, bool useRender = false) + /// + /// If true, it uses , otherwise . Default: + /// false + /// + public Deltatime(float scale = 1, bool useRender = false) { UseRender = useRender; Scale = scale; } + /// + /// The current update delta time. + /// + public static float UpdateDelta { get; internal set; } + /// + /// The current render delta time. + /// + public static float RenderDelta { get; internal set; } + + /// + /// The calculated delta time. + /// + public float DeltaTime => (UseRender ? RenderDelta : UpdateDelta) * Scale; } } \ No newline at end of file diff --git a/SMCode/SM.Base/Utility/Randomize.cs b/SMCode/SM.Base/Utility/Randomize.cs index a110088..d8875cc 100644 --- a/SMCode/SM.Base/Utility/Randomize.cs +++ b/SMCode/SM.Base/Utility/Randomize.cs @@ -1,53 +1,84 @@ -using System; +#region usings + +using System; + +#endregion namespace SM.Utility { /// - /// A global helper class for randomization. + /// A global helper class for randomization. /// public class Randomize { /// - /// The randomizer. + /// The randomizer. /// public static Random Randomizer = new Random(); /// - /// Sets the seed for the randomizer. + /// Sets the seed for the randomizer. /// /// The specified seed. - public static void SetSeed(int seed) { Randomizer = new Random(seed); } + public static void SetSeed(int seed) + { + Randomizer = new Random(seed); + } /// - /// Generates a double and checks if its under the tolerance. + /// Generates a double and checks if its under the tolerance. /// - public static bool GetBool(float tolerance) { return Randomizer.NextDouble() < tolerance; } + public static bool GetBool(float tolerance) + { + return Randomizer.NextDouble() < tolerance; + } /// - /// Generates a integer. + /// Generates a integer. /// - public static int GetInt() { return Randomizer.Next(); } - /// - /// Generates a integer with a maximum. - /// - public static int GetInt(int max) { return Randomizer.Next(max); } - /// - /// Generates a integer with a minimum and maximum - /// - public static int GetInt(int min, int max) { return Randomizer.Next(min, max); } + public static int GetInt() + { + return Randomizer.Next(); + } /// - /// Generates a float between 0 and 1. + /// Generates a integer with a maximum. /// - public static float GetFloat() { return (float)Randomizer.NextDouble(); } - /// - /// Generates a float between 0 and the specified maximum. - /// - public static float GetFloat(float max) { return (float)Randomizer.NextDouble() * max; } - /// - /// Generates a float between the specified minimum and the specified maximum. - /// - public static float GetFloat(float min, float max) { return (float)Randomizer.NextDouble() * max + min; } + public static int GetInt(int max) + { + return Randomizer.Next(max); + } + /// + /// Generates a integer with a minimum and maximum + /// + public static int GetInt(int min, int max) + { + return Randomizer.Next(min, max); + } + + /// + /// Generates a float between 0 and 1. + /// + public static float GetFloat() + { + return (float) Randomizer.NextDouble(); + } + + /// + /// Generates a float between 0 and the specified maximum. + /// + public static float GetFloat(float max) + { + return (float) Randomizer.NextDouble() * max; + } + + /// + /// Generates a float between the specified minimum and the specified maximum. + /// + public static float GetFloat(float min, float max) + { + return (float) Randomizer.NextDouble() * max + min; + } } } \ No newline at end of file diff --git a/SMCode/SM.Base/Utility/RotationUtility.cs b/SMCode/SM.Base/Utility/RotationUtility.cs index 751452e..e7523b5 100644 --- a/SMCode/SM.Base/Utility/RotationUtility.cs +++ b/SMCode/SM.Base/Utility/RotationUtility.cs @@ -1,20 +1,24 @@ -using System; +#region usings + +using System; using OpenTK; +#endregion + namespace SM.Utility { /// - /// Utilitys for rotations + /// Utilitys for rotations /// public class RotationUtility { /// - /// Angle towards an coordinate. + /// Angle towards an coordinate. /// /// public static float TurnTowards(Vector2 origin, Vector2 target) { - return MathHelper.RadiansToDegrees((float)Math.Atan2(target.Y - origin.Y, target.X - origin.X)); + return MathHelper.RadiansToDegrees((float) Math.Atan2(target.Y - origin.Y, target.X - origin.X)); } } } \ No newline at end of file diff --git a/SMCode/SM.Base/Utility/ShaderUtility.cs b/SMCode/SM.Base/Utility/ShaderUtility.cs new file mode 100644 index 0000000..b51eb32 --- /dev/null +++ b/SMCode/SM.Base/Utility/ShaderUtility.cs @@ -0,0 +1,7 @@ +namespace SM.Utility +{ + public class ShaderUtility + { + + } +} \ No newline at end of file diff --git a/SMCode/SM.Base/Window/Contexts/DrawContext.cs b/SMCode/SM.Base/Window/Contexts/DrawContext.cs index 4004433..332bb0b 100644 --- a/SMCode/SM.Base/Window/Contexts/DrawContext.cs +++ b/SMCode/SM.Base/Window/Contexts/DrawContext.cs @@ -1,61 +1,71 @@ -using System.Collections.Generic; +#region usings + using OpenTK; using SM.Base.Scene; using SM.OGL.Mesh; +#endregion + namespace SM.Base.Contexts { /// - /// Contains important information for drawing. + /// Contains important information for drawing. /// public struct DrawContext { /// - /// This says if it was forced to use the viewport camera. + /// This says if it was forced to use the viewport camera. /// public bool ForceViewport; /// - /// The current world matrix. + /// The current world matrix. /// public Matrix4 World; + /// - /// The current view matrix. + /// The current view matrix. /// public Matrix4 View; + /// - /// The master model matrix. + /// The master model matrix. /// public Matrix4 ModelMaster; + /// - /// The drawing instances. - /// If there is only one, it's index 0 + /// The drawing instances. + /// If there is only one, it's index 0 /// public Instance[] Instances; /// - /// The mesh. + /// The mesh. /// public GenericMesh Mesh; + /// - /// The material. + /// The material. /// public Material Material; /// - /// Contains the currently used render pipeline. + /// Contains the currently used render pipeline. /// public RenderPipeline ActivePipeline; /// - /// The current world scale. + /// The current world scale. /// public Vector2 WorldScale; /// - /// Returns the appropriate shader. - /// Returns the material shader, if available, otherwise it will take the default shader from the render pipeline. + /// Returns the appropriate shader. + /// + /// Returns the material shader, if available, otherwise it will take the default shader from the render + /// pipeline. + /// /// - public IShader Shader => Material.CustomShader ?? ActivePipeline._defaultShader; + public MaterialShader Shader => Material.CustomShader ?? ActivePipeline._defaultShader; } } \ No newline at end of file diff --git a/SMCode/SM.Base/Window/Contexts/UpdateContext.cs b/SMCode/SM.Base/Window/Contexts/UpdateContext.cs index e67c1fc..16a47cc 100644 --- a/SMCode/SM.Base/Window/Contexts/UpdateContext.cs +++ b/SMCode/SM.Base/Window/Contexts/UpdateContext.cs @@ -1,25 +1,28 @@ -using OpenTK.Input; -using SM.Utility; +#region usings + +using OpenTK.Input; + +#endregion namespace SM.Base.Contexts { /// - /// The update context. + /// The update context. /// public struct UpdateContext { /// - /// The delta time. + /// The delta time. /// public float Deltatime => SMRenderer.DefaultDeltatime.DeltaTime; /// - /// The current keyboard state. + /// The current keyboard state. /// public KeyboardState KeyboardState; /// - /// The current mouse state. + /// The current mouse state. /// public MouseState MouseState; } diff --git a/SMCode/SM.Base/Window/GenericWindow.cs b/SMCode/SM.Base/Window/GenericWindow.cs index 41450a4..26f5f76 100644 --- a/SMCode/SM.Base/Window/GenericWindow.cs +++ b/SMCode/SM.Base/Window/GenericWindow.cs @@ -1,53 +1,86 @@ -using System; -using System.IO; +#region usings + +using System; +using System.Drawing; +using System.Linq; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL4; using OpenTK.Input; using SM.Base.Contexts; using SM.Base.Objects.Static; +using SM.Base.PostProcess; using SM.Base.Scene; +using SM.Base.ShaderExtension; using SM.Base.Time; using SM.OGL; -using SM.OGL.Shaders; +using SM.OGL.Framebuffer; using SM.Utility; +#endregion + namespace SM.Base { /// - /// The base window. + /// The base window. /// public abstract class GenericWindow : GameWindow { - private bool _loading = false; - + private bool _loading; + /// - /// This tells you the current world scale. + /// This tells you the current world scale. /// protected Vector2 _worldScale = Vector2.Zero; + /// - /// This tells you the current aspect ratio of this window. + /// This tells you the current aspect ratio of this window. /// - public float Aspect { get; private set; } = 0f; + public float Aspect { get; private set; } + + public bool ReactWhileUnfocused = false; /// - protected GenericWindow() : base(1280, 720, GraphicsMode.Default, "Generic OGL Title", GameWindowFlags.Default, - DisplayDevice.Default, 0, 0, GraphicsContextFlags.Default, null, true) - { } + protected GenericWindow() : this(1280, 720, "Generic OGL Title", GameWindowFlags.Default) + { + } + + protected GenericWindow(int width, int height, string title, GameWindowFlags flags, bool vSync = true) : base(width, height, + GraphicsMode.Default, title, flags, DisplayDevice.Default, GLSettings.ForcedVersion.MajorVersion, + GLSettings.ForcedVersion.MinorVersion, GraphicsContextFlags.Default) + { + VSync = vSync ? VSyncMode.On : VSyncMode.Off; + } + /// protected override void OnLoad(EventArgs e) { GLSystem.INIT_SYSTEM(); + GLSettings.ShaderPreProcessing = true; + + var args = Environment.GetCommandLineArgs(); + if (args.Contains("--advDebugging")) + { + SMRenderer.AdvancedDebugging = true; + GLSettings.InfoEveryUniform = true; + } + + Log.Init(); Log.Write("#", ConsoleColor.Cyan, "----------------------", "--- OpenGL Loading ---", "----------------------------------", $"--- {"DeviceVersion",14}: {GLSystem.DeviceVersion,-10} ---", - $"--- {"ForcedVersion",14}: {GLSystem.ForcedVersion,-10} ---", + $"--- {"ForcedVersion",14}: {GLSettings.ForcedVersion,-10} ---", $"--- {"ShadingVersion",14}: {GLSystem.ShadingVersion,-10} ---", $"--- {"Debugging",14}: {GLSystem.Debugging,-10} ---", - $"----------------------------------"); + $"--- {"AdvDebugging",14}: {SMRenderer.AdvancedDebugging,-10} ---", + "----------------------------------"); + + if (SMRenderer.AdvancedDebugging) Log.Write("Extension", ConsoleColor.DarkCyan, GLSystem.Extensions); + + ExtensionManager.InitExtensions(); base.OnLoad(e); _loading = true; @@ -58,7 +91,7 @@ namespace SM.Base { base.OnResize(e); - Aspect = (float)Width / Height; + Aspect = (float) Width / Height; _worldScale = new Vector2(Width, Height); SetWorldScale(); GL.Viewport(ClientRectangle); @@ -71,25 +104,28 @@ namespace SM.Base } /// - /// This is triggered after all the window-loading has been done. + /// This is triggered after all the window-loading has been done. /// protected virtual void OnLoaded() { - } /// - /// Sets the world scale. + /// Sets the world scale. /// - protected virtual void SetWorldScale() { } + protected virtual void SetWorldScale() + { + } /// protected override void OnUpdateFrame(FrameEventArgs e) { + if (!ReactWhileUnfocused && !Focused) return; + base.OnUpdateFrame(e); - - Deltatime.UpdateDelta = (float)e.Time; - UpdateContext context = new UpdateContext() + + Deltatime.UpdateDelta = (float) e.Time; + var context = new UpdateContext { KeyboardState = Keyboard.GetState(), MouseState = Mouse.GetState() @@ -99,7 +135,7 @@ namespace SM.Base } /// - /// Updates the system. + /// Updates the system. /// /// /// @@ -109,7 +145,7 @@ namespace SM.Base } /// - /// Grabs the cursor and make sure it doesn't leave the window. + /// Grabs the cursor and make sure it doesn't leave the window. /// /// If true, it makes the cursor invisible. public void GrabCursor(bool makeItInvisible = true) @@ -119,17 +155,42 @@ namespace SM.Base } /// - /// Ungrabs the cursor. + /// Ungrabs the cursor. /// public void UngrabCursor() { CursorGrabbed = false; if (!CursorVisible) CursorVisible = true; } + + public Bitmap TakeScreenshot(Framebuffer framebuffer, ReadBufferMode readBuffer, int x, int y, int width, int height) + { + GL.GetInteger(GetPName.FramebufferBinding, out int prevFBId); + GL.GetInteger(GetPName.DrawFramebufferBinding, out int prevFBDrawId); + GL.GetInteger(GetPName.ReadFramebufferBinding, out int prevFBReadId); + + Bitmap b = new Bitmap(width, height); + System.Drawing.Imaging.BitmapData bits = b.LockBits(new Rectangle(0, 0, width, height), + System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + + GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, framebuffer); + GL.ReadBuffer(readBuffer); + GL.ReadPixels(x, y, width, height, OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, + bits.Scan0); + + b.UnlockBits(bits); + b.RotateFlip(RotateFlipType.RotateNoneFlipY); + + GL.BindFramebuffer(FramebufferTarget.Framebuffer, prevFBId); + GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, prevFBDrawId); + GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, prevFBReadId); + + return b; + } } /// - /// The base window. + /// The base window. /// /// The scene type /// The camera type @@ -137,31 +198,32 @@ namespace SM.Base where TScene : GenericScene, new() where TCamera : GenericCamera, new() { - /// - /// The viewport camera. - /// - public TCamera ViewportCamera { get; } - /// - /// This forces the render to use the viewport camera. - /// - public bool ForceViewportCamera { get; set; } = false; - - /// - /// The current scene. - /// - public TScene CurrentScene { get; private set; } - - /// - /// Controls how a scene is rendered. - /// - public RenderPipeline RenderPipeline { get; private set; } - /// protected GenericWindow() { ViewportCamera = new TCamera(); } + /// + /// The viewport camera. + /// + public TCamera ViewportCamera { get; } + + /// + /// This forces the render to use the viewport camera. + /// + public bool ForceViewportCamera { get; set; } = false; + + /// + /// The current scene. + /// + public TScene CurrentScene { get; private set; } + + /// + /// Controls how a scene is rendered. + /// + public RenderPipeline RenderPipeline { get; private set; } + /// protected override void Update(FrameEventArgs e, ref UpdateContext context) { @@ -172,15 +234,21 @@ namespace SM.Base /// protected override void OnRenderFrame(FrameEventArgs e) { + if (!ReactWhileUnfocused && !Focused) return; + SMRenderer.CurrentFrame++; - Deltatime.RenderDelta = (float)e.Time; - DrawContext drawContext = new DrawContext() + Deltatime.RenderDelta = (float) e.Time; + var drawContext = new DrawContext { World = ViewportCamera.World, View = ViewportCamera.CalculateViewMatrix(), ModelMaster = Matrix4.Identity, - Instances = new[] { new Instance {ModelMatrix = Matrix4.Identity, TexturePosition = Vector2.Zero, TextureScale = Vector2.One } }, + Instances = new[] + { + new Instance + {ModelMatrix = Matrix4.Identity, TexturePosition = Vector2.Zero, TextureScale = Vector2.One} + }, Mesh = Plate.Object, ForceViewport = ForceViewportCamera, WorldScale = _worldScale @@ -202,10 +270,14 @@ namespace SM.Base ViewportCamera.RecalculateWorld(_worldScale, Aspect); RenderPipeline.Resize(); + + PostProcessEffect.Mvp = Matrix4.CreateScale(_worldScale.X, -_worldScale.Y, 1) * + Matrix4.LookAt(0, 0, 1, 0, 0, 0, 0, 1, 0) * + GenericCamera.OrthographicWorld; } /// - /// Sets the scene. + /// Sets the scene. /// /// public virtual void SetScene(TScene scene) @@ -215,7 +287,7 @@ namespace SM.Base } /// - /// Defines the render pipeline. + /// Defines the render pipeline. /// /// public void SetRenderPipeline(RenderPipeline pipeline) diff --git a/SMCode/SM.Base/Window/RenderPipeline.cs b/SMCode/SM.Base/Window/RenderPipeline.cs index 60c5e22..575c4ac 100644 --- a/SMCode/SM.Base/Window/RenderPipeline.cs +++ b/SMCode/SM.Base/Window/RenderPipeline.cs @@ -1,70 +1,79 @@ -using System.Collections.Generic; +#region usings + +using System.Collections.Generic; +using System.Threading; using SM.Base.Contexts; using SM.Base.Scene; using SM.OGL.Framebuffer; +#endregion + namespace SM.Base { /// - /// Definition of specific render options. + /// Definition of specific render options. /// public abstract class RenderPipeline { - /// - /// The framebuffers, that are used in this Pipeline. + /// The framebuffers, that are used in this Pipeline. /// protected virtual List _framebuffers { get; } - - /// - /// The default shader for the pipeline. - /// - protected internal virtual IShader _defaultShader { get; } /// - /// Occurs, when the window is loading. + /// The default shader for the pipeline. + /// + protected internal virtual MaterialShader _defaultShader { get; } = SMRenderer.DefaultMaterialShader; + + /// + /// Occurs, when the window is loading. /// protected internal virtual void Load() { - foreach (Framebuffer framebuffer in _framebuffers) - framebuffer.Compile(); } /// - /// Occurs, when the window is resizing. + /// Occurs, when the window is resizing. /// protected internal virtual void Resize() - { } + { + if (_framebuffers == null) return; + + foreach (var framebuffer in _framebuffers) + framebuffer.Dispose(); + + Thread.Sleep(50); + + foreach (Framebuffer framebuffer in _framebuffers) + { + framebuffer.Compile(); + } + } /// - /// Occurs, when the pipeline was connected to a window. + /// Occurs, when the pipeline was connected to a window. /// protected internal virtual void Activate(GenericWindow window) { } /// - /// Occurs, when the window is unloading. + /// Occurs, when the window is unloading. /// protected internal virtual void Unload() { - foreach (Framebuffer framebuffer in _framebuffers) - { - framebuffer.Dispose(); - } } } /// - /// Represents a render pipeline. + /// Represents a render pipeline. /// /// The scene type public abstract class RenderPipeline : RenderPipeline where TScene : GenericScene { - /// - /// The system to render stuff. + /// The system to render stuff. /// protected internal virtual void Render(ref DrawContext context, TScene scene) { diff --git a/SMCode/SM.Base/packages.config b/SMCode/SM.Base/packages.config index 75397e4..9a4debe 100644 --- a/SMCode/SM.Base/packages.config +++ b/SMCode/SM.Base/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/SMCode/SM.OGL/Framebuffer/ColorAttachment.cs b/SMCode/SM.OGL/Framebuffer/ColorAttachment.cs index 60865b1..39927dd 100644 --- a/SMCode/SM.OGL/Framebuffer/ColorAttachment.cs +++ b/SMCode/SM.OGL/Framebuffer/ColorAttachment.cs @@ -1,11 +1,20 @@ -using System; +#region usings + +using System; using OpenTK.Graphics.OpenGL4; using SM.OGL.Texture; +#endregion + namespace SM.OGL.Framebuffer { public class ColorAttachment : TextureBase { + public ColorAttachment(int attachmentId) + { + AttachmentID = attachmentId; + } + public int AttachmentID { get; } public FramebufferAttachment FramebufferAttachment => FramebufferAttachment.ColorAttachment0 + AttachmentID; @@ -13,23 +22,22 @@ namespace SM.OGL.Framebuffer public ReadBufferMode ReadBufferMode => ReadBufferMode.ColorAttachment0 + AttachmentID; public DrawBuffersEnum DrawBuffersEnum => DrawBuffersEnum.ColorAttachment0 + AttachmentID; - public ColorAttachment(int attachmentId) - { - AttachmentID = attachmentId; - } - public void Generate(Framebuffer f) { _id = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, _id); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, - (int) f.Size.X, (int) f.Size.Y, + (int) f.Size.X, (int) f.Size.Y, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureParameterName.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureParameterName.ClampToEdge); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, + (int) TextureMinFilter.Linear); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, + (int) TextureMinFilter.Linear); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, + (int) TextureParameterName.ClampToEdge); + GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, + (int) TextureParameterName.ClampToEdge); } } } \ No newline at end of file diff --git a/SMCode/SM.OGL/Framebuffer/Framebuffer.cs b/SMCode/SM.OGL/Framebuffer/Framebuffer.cs index 82b81b6..2ff3b78 100644 --- a/SMCode/SM.OGL/Framebuffer/Framebuffer.cs +++ b/SMCode/SM.OGL/Framebuffer/Framebuffer.cs @@ -1,15 +1,18 @@ -using System; +#region usings + +using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics.OpenGL4; -using OpenTK.Platform; + +#endregion namespace SM.OGL.Framebuffer { // TODO: Write summeries for framebuffer-system. public class Framebuffer : GLObject { - public static readonly Framebuffer Screen = new Framebuffer() + public static readonly Framebuffer Screen = new Framebuffer { _id = 0, _canBeCompiled = false @@ -17,34 +20,45 @@ namespace SM.OGL.Framebuffer private bool _canBeCompiled = true; - public override ObjectLabelIdentifier TypeIdentifier { get; } = ObjectLabelIdentifier.Framebuffer; - - public Vector2 Size { get; private set; } - - public Dictionary ColorAttachments { get; private set; } = new Dictionary(); + private INativeWindow _window; + private float _windowScale; public Framebuffer() - { } + { + } - public Framebuffer(INativeWindow window, float scale = 1) : this(new Vector2(window.Width * scale, window.Height * scale)) - { } + public Framebuffer(INativeWindow window, float scale = 1) : this(new Vector2(window.Width * scale, + window.Height * scale)) + { + _window = window; + _windowScale = scale; + } public Framebuffer(Vector2 size) { Size = size; } + public override ObjectLabelIdentifier TypeIdentifier { get; } = ObjectLabelIdentifier.Framebuffer; + + public Vector2 Size { get; private set; } + + public Dictionary ColorAttachments { get; private set; } = + new Dictionary(); + public override void Compile() { if (!_canBeCompiled) return; + if (_window != null) Size = new Vector2(_window.Width * _windowScale, _window.Height * _windowScale); + base.Compile(); _id = GL.GenFramebuffer(); GL.BindFramebuffer(FramebufferTarget.Framebuffer, _id); - DrawBuffersEnum[] enums = new DrawBuffersEnum[ColorAttachments.Count]; - int c = 0; - foreach (KeyValuePair pair in ColorAttachments) + var enums = new DrawBuffersEnum[ColorAttachments.Count]; + var c = 0; + foreach (var pair in ColorAttachments) { pair.Value.Generate(this); @@ -53,11 +67,12 @@ namespace SM.OGL.Framebuffer GL.DrawBuffers(enums.Length, enums); foreach (var pair in ColorAttachments) - GL.FramebufferTexture(FramebufferTarget.Framebuffer, pair.Value.FramebufferAttachment, pair.Value.ID, 0); + GL.FramebufferTexture(FramebufferTarget.Framebuffer, pair.Value.FramebufferAttachment, pair.Value.ID, + 0); - FramebufferErrorCode err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer); + var err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer); if (err != FramebufferErrorCode.FramebufferComplete) - throw new Exception("Failed loading framebuffer.\nProblem: "+err); + throw new Exception("Failed loading framebuffer.\nProblem: " + err); GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); GL.BindTexture(TextureTarget.Texture2D, 0); @@ -66,23 +81,36 @@ namespace SM.OGL.Framebuffer public override void Dispose() { base.Dispose(); - foreach (ColorAttachment attachment in ColorAttachments.Values) attachment.Dispose(); + foreach (var attachment in ColorAttachments.Values) attachment.Dispose(); GL.DeleteFramebuffer(this); } + public void Append(string key, int pos) => Append(key, new ColorAttachment(pos)); public void Append(string key, ColorAttachment value) { ColorAttachments.Add(key, value); } - public void Activate() => Activate(FramebufferTarget.Framebuffer, ClearBufferMask.None); - public void Activate(FramebufferTarget target) => Activate(target, ClearBufferMask.None); - public void Activate(ClearBufferMask clearMask) => Activate(FramebufferTarget.Framebuffer, clearMask); + public void Activate() + { + Activate(FramebufferTarget.Framebuffer, ClearBufferMask.None); + } + + public void Activate(FramebufferTarget target) + { + Activate(target, ClearBufferMask.None); + } + + public void Activate(ClearBufferMask clearMask) + { + Activate(FramebufferTarget.Framebuffer, clearMask); + } + public void Activate(FramebufferTarget target, ClearBufferMask clear) { - GL.Clear(clear); GL.BindFramebuffer(target, this); + GL.Clear(clear); } } } \ No newline at end of file diff --git a/SMCode/SM.OGL/GLCustomActions.cs b/SMCode/SM.OGL/GLCustomActions.cs new file mode 100644 index 0000000..97eac9d --- /dev/null +++ b/SMCode/SM.OGL/GLCustomActions.cs @@ -0,0 +1,47 @@ +#region usings + +using System; +using OpenTK.Graphics.OpenGL4; + +#endregion + +namespace SM.OGL +{ + public class GLCustomActions + { + /// + /// A action that is performed, when a OpenGL-error occurs. + /// + public static Action AtKHRDebug = DefaultDebugAction; + + /// + /// A action, that is performed, when a GLError occurred. + /// Doesn't account for "KHR_debugging" + /// + public static Action AtError; + + /// + /// A action, that is performed, when a warning want to be shown. + /// + public static Action AtWarning; + + /// + /// A action, that is performed, when a information needs to be shown. + /// + public static Action AtInfo; + + /// + /// Default action for 'AtKHRDebug'. + /// + /// + /// + /// + /// + private static void DefaultDebugAction(DebugSource source, DebugType type, DebugSeverity severity, string msg) + { + Console.WriteLine($"{severity}, {type}, {source} -> {msg}"); + + if (type == DebugType.DebugTypeError) throw new Exception(msg); + } + } +} \ No newline at end of file diff --git a/SMCode/SM.OGL/GLDebugging.cs b/SMCode/SM.OGL/GLDebugging.cs index daa3ae1..a3ce393 100644 --- a/SMCode/SM.OGL/GLDebugging.cs +++ b/SMCode/SM.OGL/GLDebugging.cs @@ -1,36 +1,33 @@ -using System; +#region usings + +using System; using System.Diagnostics; -using System.Net.Http; using System.Runtime.InteropServices; using OpenTK.Graphics.OpenGL4; -using OpenTK.Platform.Egl; -using ErrorCode = OpenTK.Graphics.OpenGL4.ErrorCode; + +#endregion namespace SM.OGL { /// - /// Contains everything that is needed to debug OpenGL + /// Contains everything that is needed to debug OpenGL /// public static class GLDebugging { private static DebugProc _debugProc = DebugCallback; private static GCHandle _debugGcHandle; - /// - /// A action that is performed, when a OpenGL-error occurs. - /// - public static Action DebugAction = DefaultDebugAction; [DebuggerStepThrough] private static void DebugCallback(DebugSource source, DebugType type, int id, DebugSeverity severity, int length, IntPtr message, IntPtr userparam) { - string msg = Marshal.PtrToStringAnsi(message, length); - DebugAction?.Invoke(source, type, severity, msg); + var msg = Marshal.PtrToStringAnsi(message, length); + GLCustomActions.AtKHRDebug?.Invoke(source, type, severity, msg); } /// - /// Enables the debugging. + /// Enables the debugging. /// public static void EnableDebugging() { @@ -47,40 +44,33 @@ namespace SM.OGL Console.WriteLine("Enableing proper GLDebugging failed. \n" + "Often it fails, because your hardware doesn't provide proper OpenGL 4 \n" + " or KHR_debug extension support."); - } } /// - /// Default action for 'DebugAction'. - /// - /// - /// - /// - /// - public static void DefaultDebugAction(DebugSource source, DebugType type, DebugSeverity severity, string msg) - { - Console.WriteLine($"{severity}, {type}, {source} -> {msg}"); - - if (type == DebugType.DebugTypeError) throw new Exception(msg); - } - - /// - /// A action, that is performed, when find an error. - /// - public static Action GlErrorAction; - - /// - /// Checks for OpenGL errors. + /// Checks for OpenGL errors. /// public static bool CheckGLErrors() { - bool hasError = false; + var hasError = false; ErrorCode c; while ((c = GL.GetError()) != ErrorCode.NoError) { hasError = true; - GlErrorAction?.Invoke(c); + GLCustomActions.AtError?.Invoke("A GLError occurred: " + c); + } + + return hasError; + } + + public static bool CheckGLErrors(string formating) + { + var hasError = false; + ErrorCode c; + while ((c = GL.GetError()) != ErrorCode.NoError) + { + hasError = true; + GLCustomActions.AtError?.Invoke(formating.Replace("%code%", c.ToString())); } return hasError; diff --git a/SMCode/SM.OGL/GLObject.cs b/SMCode/SM.OGL/GLObject.cs index cd8ecec..bf0e28a 100644 --- a/SMCode/SM.OGL/GLObject.cs +++ b/SMCode/SM.OGL/GLObject.cs @@ -1,30 +1,35 @@ -using System.Diagnostics; +#region usings + +using System.Diagnostics; using OpenTK.Graphics.OpenGL4; +#endregion + namespace SM.OGL { /// - /// Specifies default object behaviour. + /// Specifies default object behaviour. /// public abstract class GLObject { /// - /// Contains the OpenGL ID + /// Contains the OpenGL ID /// protected int _id = -1; + /// - /// If true, the system will call "Compile()", when "ID" is tried to get, but the id is still -1. + /// If true, the system will call "Compile()", when "ID" is tried to get, but the id is still -1. /// protected virtual bool AutoCompile { get; } = false; /// - /// Checks if the object was compiled. + /// Checks if the object was compiled. /// public bool WasCompiled => _id > 0; /// - /// Returns the id for this object. - /// It will auto compile, if needed and allowed. + /// Returns the id for this object. + /// It will auto compile, if needed and allowed. /// public virtual int ID { @@ -36,7 +41,7 @@ namespace SM.OGL } /// - /// Identifies the object. + /// Identifies the object. /// public abstract ObjectLabelIdentifier TypeIdentifier { get; } @@ -47,21 +52,21 @@ namespace SM.OGL } /// - /// The action, that is called, when "ID" tries to compile something. + /// The action, that is called, when "ID" tries to compile something. /// - public virtual void Compile() { - } /// - /// Is triggered, when something want to dispose this object. + /// Is triggered, when something want to dispose this object. /// - public virtual void Dispose() {} + public virtual void Dispose() + { + } /// - /// Re-compiles the object. + /// Re-compiles the object. /// public void Recompile() { @@ -72,7 +77,7 @@ namespace SM.OGL } /// - /// Names the object for debugging. + /// Names the object for debugging. /// /// public void Name(string name) @@ -81,9 +86,12 @@ namespace SM.OGL } /// - /// Returns the ID for the object. + /// Returns the ID for the object. /// /// - public static implicit operator int(GLObject glo) => glo.ID; + public static implicit operator int(GLObject glo) + { + return glo.ID; + } } } \ No newline at end of file diff --git a/SMCode/SM.OGL/GLSettings.cs b/SMCode/SM.OGL/GLSettings.cs new file mode 100644 index 0000000..c1bbbdf --- /dev/null +++ b/SMCode/SM.OGL/GLSettings.cs @@ -0,0 +1,15 @@ +namespace SM.OGL +{ + public class GLSettings + { + public static bool InfoEveryUniform = false; + + /// + /// Get/Sets the forced version for OpenGL. + /// Needs to be set before init a window. + /// + public static Version ForcedVersion { get; set; } = new Version(); + + public static bool ShaderPreProcessing { get; set; } = false; + } +} \ No newline at end of file diff --git a/SMCode/SM.OGL/GLSystem.cs b/SMCode/SM.OGL/GLSystem.cs index 6cd41cc..2abebd3 100644 --- a/SMCode/SM.OGL/GLSystem.cs +++ b/SMCode/SM.OGL/GLSystem.cs @@ -1,43 +1,44 @@ -using System.Linq; +#region usings + +using System.Linq; using OpenTK.Graphics.OpenGL4; +#endregion + namespace SM.OGL { /// - /// Contains data about the current OpenGL system. + /// Contains data and settings about the current OpenGL system. /// public class GLSystem { - private static bool _init = false; + private static bool _init; /// - /// Contains the device version of OpenGL. + /// Contains the device version of OpenGL. /// public static Version DeviceVersion { get; private set; } - /// - /// Get/Sets the forced version for OpenGL. - /// Needs to be set before init a window. - /// - public static Version ForcedVersion { get; set; } = new Version(); /// - /// Contains the shader version for GLSL. + /// Contains the shader version for GLSL. /// public static Version ShadingVersion { get; private set; } + /// - /// Contains the extensions for OpenGL. + /// Contains the extensions for OpenGL. /// public static string[] Extensions { get; private set; } /// - /// Checks if proper Debugging is for this system available. - /// Determent, if the system has the "KHR_debug"-extension. + /// Checks if proper Debugging is for this system available. + /// Determent, if the system has the "KHR_debug"-extension. /// public static bool Debugging { get; private set; } + /// - /// Initialize the system data. - /// Does nothing after the data was already collected. + /// Initialize the system data. + /// Does nothing after the data was already collected. /// public static void INIT_SYSTEM() { diff --git a/SMCode/SM.OGL/Mesh/BoundingBox.cs b/SMCode/SM.OGL/Mesh/BoundingBox.cs index 4284161..b7ea997 100644 --- a/SMCode/SM.OGL/Mesh/BoundingBox.cs +++ b/SMCode/SM.OGL/Mesh/BoundingBox.cs @@ -1,39 +1,36 @@ -using System; -using System.Runtime.CompilerServices; +#region usings + +using System; using OpenTK; +#endregion + namespace SM.OGL.Mesh { /// - /// Contains information about bounding boxes of meshes + /// Contains information about bounding boxes of meshes /// public class BoundingBox { /// - /// The minimum corner. - /// - public Vector3 Min = Vector3.Zero; - /// - /// The maximum corner. + /// The maximum corner. /// public Vector3 Max = Vector3.Zero; /// - /// Returns specific configurations of corners + /// The minimum corner. /// - /// If true, it takes the X-value of maximum, otherwise the minimum. - /// If true, it takes the Y-value of maximum, otherwise the minimum. - /// If true, it takes the Z-value of maximum, otherwise the minimum. - /// - public Vector3 this[bool x, bool y, bool z] => new Vector3(x ? Max.X : Min.X, y ? Max.Y : Min.Y, z ? Max.Z : Min.Z); + public Vector3 Min = Vector3.Zero; /// - /// Empty constructor + /// Empty constructor /// - public BoundingBox() {} + public BoundingBox() + { + } /// - /// Creates the bounding box with predefined min and max values + /// Creates the bounding box with predefined min and max values /// /// /// @@ -44,12 +41,22 @@ namespace SM.OGL.Mesh } /// - /// Updates the bounding box. + /// Returns specific configurations of corners + /// + /// If true, it takes the X-value of maximum, otherwise the minimum. + /// If true, it takes the Y-value of maximum, otherwise the minimum. + /// If true, it takes the Z-value of maximum, otherwise the minimum. + /// + public Vector3 this[bool x, bool y, bool z] => + new Vector3(x ? Max.X : Min.X, y ? Max.Y : Min.Y, z ? Max.Z : Min.Z); + + /// + /// Updates the bounding box. /// /// public void Update(Vector2 vector) { - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { Min[i] = Math.Min(Min[i], vector[i]); Max[i] = Math.Max(Max[i], vector[i]); @@ -57,12 +64,12 @@ namespace SM.OGL.Mesh } /// - /// Updates the bounding box. + /// Updates the bounding box. /// /// public void Update(Vector3 vector) { - for (int i = 0; i < 3; i++) + for (var i = 0; i < 3; i++) { Min[i] = Math.Min(Min[i], vector[i]); Max[i] = Math.Max(Min[i], vector[i]); diff --git a/SMCode/SM.OGL/Mesh/GenericMesh.cs b/SMCode/SM.OGL/Mesh/GenericMesh.cs index 3af41fd..925e378 100644 --- a/SMCode/SM.OGL/Mesh/GenericMesh.cs +++ b/SMCode/SM.OGL/Mesh/GenericMesh.cs @@ -1,15 +1,31 @@ -using System; +#region usings + +using System; using System.Collections.Generic; using OpenTK.Graphics.OpenGL4; -using Buffer = OpenTK.Graphics.OpenGL4.Buffer; + +#endregion namespace SM.OGL.Mesh { /// - /// Contains information for meshes + /// Contains information for meshes /// public abstract class GenericMesh : GLObject { + /// + /// Generates the AttribDataIndex + /// + protected GenericMesh() + { + AttribDataIndex = new Dictionary + { + {0, Vertex}, + {1, UVs}, + {2, Normals} + }; + } + /// protected override bool AutoCompile { get; } = true; @@ -17,61 +33,50 @@ namespace SM.OGL.Mesh public override ObjectLabelIdentifier TypeIdentifier { get; } = ObjectLabelIdentifier.VertexArray; /// - /// The primitive type, that determinants how the mesh is drawn. - /// Default: Triangles + /// The primitive type, that determinants how the mesh is drawn. + /// Default: Triangles /// public virtual PrimitiveType PrimitiveType { get; } = PrimitiveType.Triangles; /// - /// Contains the vertices for the mesh. + /// Contains the vertices for the mesh. /// public virtual VBO Vertex { get; } + /// - /// Contains the texture coords for the mesh. + /// Contains the texture coords for the mesh. /// public virtual VBO UVs { get; } + /// - /// Contains the normals for the mesh. + /// Contains the normals for the mesh. /// public virtual VBO Normals { get; } /// - /// Represents the bounding box. + /// Represents the bounding box. /// public virtual BoundingBox BoundingBox { get; } = new BoundingBox(); /// - /// Connects the different buffer objects with ids. + /// Connects the different buffer objects with ids. /// public Dictionary AttribDataIndex { get; } /// - /// Stores indices for a more performance friendly method to draw objects. + /// Stores indices for a more performance friendly method to draw objects. /// public virtual int[] Indices { get; set; } - /// - /// Generates the AttribDataIndex - /// - protected GenericMesh() - { - AttribDataIndex = new Dictionary() - { - {0, Vertex}, - {1, UVs}, - {2, Normals}, - }; - } - /// public override void Compile() { _id = GL.GenVertexArray(); GL.BindVertexArray(_id); - + if (AttribDataIndex == null) throw new Exception("[Critical] The model requires a attribute data index."); - foreach (KeyValuePair kvp in AttribDataIndex) kvp.Value?.BindBuffer(kvp.Key); + foreach (var kvp in AttribDataIndex) kvp.Value?.BindBuffer(kvp.Key); GL.BindVertexArray(0); } diff --git a/SMCode/SM.OGL/Mesh/VBO.cs b/SMCode/SM.OGL/Mesh/VBO.cs index 16d4481..0664f63 100644 --- a/SMCode/SM.OGL/Mesh/VBO.cs +++ b/SMCode/SM.OGL/Mesh/VBO.cs @@ -1,51 +1,78 @@ -using System; +#region usings + using System.Collections.Generic; -using System.Linq; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL4; +#endregion + namespace SM.OGL.Mesh { /// - /// Represents a Vertex Buffer Object used for meshes. + /// Represents a Vertex Buffer Object used for meshes. /// public class VBO : List { /// - /// Specifies the expected usage pattern of the data store. + /// Specifies the expected usage pattern of the data store. /// public BufferUsageHint BufferUsageHint; + /// - /// Specifies the data type of each component in the array. - /// - public VertexAttribPointerType PointerType; - /// - /// Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4. - /// - public int PointerSize; - /// - /// Normalise floats? + /// Normalise floats? /// public bool Normalised; + /// - /// Specifies the byte offset between consecutive generic vertex attributes. - /// - public int PointerStride; - /// - /// Specifies a offset of the first component of the first generic vertex attribute in the array in the data store of the buffer currently bound to the GL_ARRAY_BUFFER target. + /// Specifies a offset of the first component of the first generic vertex attribute in the array in the data store of + /// the buffer currently bound to the GL_ARRAY_BUFFER target. /// public int PointerOffset; /// - /// Generates a VBO for inserting mesh data. + /// Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4. /// - /// Specifies the expected usage pattern of the data store. Default: StaticDraw - /// Specifies the data type of each component in the array. Default: Float - /// Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4. Default: 3 - /// Specifies the byte offset between consecutive generic vertex attributes. Default: 0 - /// Specifies a offset of the first component of the first generic vertex attribute in the array in the data store of the buffer currently bound to the GL_ARRAY_BUFFER target. Default: 0 - /// Normalise floats? Default: false + public int PointerSize; + + /// + /// Specifies the byte offset between consecutive generic vertex attributes. + /// + public int PointerStride; + + /// + /// Specifies the data type of each component in the array. + /// + public VertexAttribPointerType PointerType; + + /// + /// Generates a VBO for inserting mesh data. + /// + /// + /// Specifies the expected usage pattern of the data store. + /// Default: StaticDraw + /// + /// + /// Specifies the data type of each component in the array. + /// Default: Float + /// + /// + /// Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4. + /// Default: 3 + /// + /// + /// Specifies the byte offset between consecutive generic vertex attributes. + /// Default: 0 + /// + /// + /// Specifies a offset of the first component of the first generic vertex attribute in the + /// array in the data store of the buffer currently bound to the GL_ARRAY_BUFFER target. + /// Default: 0 + /// + /// + /// Normalise floats? + /// Default: false + /// public VBO(BufferUsageHint bufferUsageHint = BufferUsageHint.StaticDraw, VertexAttribPointerType pointerType = VertexAttribPointerType.Float, int pointerSize = 3, int pointerStride = 0, int pointerOffset = 0, bool normalised = false) @@ -59,56 +86,95 @@ namespace SM.OGL.Mesh } /// - /// Adds two values to the VBO. + /// Adds two values to the VBO. /// - public void Add(float x, float y) => AddRange(new[] {x,y}); - /// - /// Adds three values to the VBO. - /// - public void Add(float x, float y, float z) => AddRange(new[] {x,y,z}); - /// - /// Adds four values to the VBO. - /// - public void Add(float x, float y, float z, float w) => AddRange(new[] {x,y,z,w}); - /// - /// Adds a Vector2. - /// - public void Add(Vector2 vector) => Add(vector.X, vector.Y); - /// - /// Adds a Vector2 and a value. - /// - public void Add(Vector2 vector, float z) => Add(vector.X, vector.Y, z); - /// - /// Adds a Vector2 and two values. - /// - public void Add(Vector2 vector, float z, float w) => Add(vector.X, vector.Y, z, w); - /// - /// Adds a Vector3. - /// - public void Add(Vector3 vector) => Add(vector.X, vector.Y, vector.Z); - /// - /// Adds a Vector3 and a value. - /// - public void Add(Vector3 vector, float w) => Add(vector.X, vector.Y, vector.Z, w); - /// - /// Adds a vector4. - /// - /// - public void Add(Vector4 vector) => Add(vector.X, vector.Y, vector.Z, vector.W); - /// - /// Adds a color. - /// - public void Add(Color4 color) => Add(color.R, color.G, color.B, color.A); + public void Add(float x, float y) + { + AddRange(new[] {x, y}); + } /// - /// Binds the buffer to the active VAO. + /// Adds three values to the VBO. + /// + public void Add(float x, float y, float z) + { + AddRange(new[] {x, y, z}); + } + + /// + /// Adds four values to the VBO. + /// + public void Add(float x, float y, float z, float w) + { + AddRange(new[] {x, y, z, w}); + } + + /// + /// Adds a Vector2. + /// + public void Add(Vector2 vector) + { + Add(vector.X, vector.Y); + } + + /// + /// Adds a Vector2 and a value. + /// + public void Add(Vector2 vector, float z) + { + Add(vector.X, vector.Y, z); + } + + /// + /// Adds a Vector2 and two values. + /// + public void Add(Vector2 vector, float z, float w) + { + Add(vector.X, vector.Y, z, w); + } + + /// + /// Adds a Vector3. + /// + public void Add(Vector3 vector) + { + Add(vector.X, vector.Y, vector.Z); + } + + /// + /// Adds a Vector3 and a value. + /// + public void Add(Vector3 vector, float w) + { + Add(vector.X, vector.Y, vector.Z, w); + } + + /// + /// Adds a vector4. + /// + /// + public void Add(Vector4 vector) + { + Add(vector.X, vector.Y, vector.Z, vector.W); + } + + /// + /// Adds a color. + /// + public void Add(Color4 color) + { + Add(color.R, color.G, color.B, color.A); + } + + /// + /// Binds the buffer to the active VAO. /// /// The id for the attribute. internal void BindBuffer(int attribID) { - float[] data = ToArray(); + var data = ToArray(); - int buffer = GL.GenBuffer(); + var buffer = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, buffer); GL.BufferData(BufferTarget.ArrayBuffer, data.Length * sizeof(float), data, BufferUsageHint); diff --git a/SMCode/SM.OGL/Properties/AssemblyInfo.cs b/SMCode/SM.OGL/Properties/AssemblyInfo.cs index eaca79a..e3d31e0 100644 --- a/SMCode/SM.OGL/Properties/AssemblyInfo.cs +++ b/SMCode/SM.OGL/Properties/AssemblyInfo.cs @@ -1,16 +1,19 @@ -using System.Reflection; -using System.Runtime.CompilerServices; +#region usings + +using System.Reflection; using System.Runtime.InteropServices; +#endregion + // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("SM.Core")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyTitle("OpenGL Bindings for SMRederer")] +[assembly: AssemblyDescription("Defines classes to work with OpenTK/OpenGL")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyCompany("iedSoftworks")] [assembly: AssemblyProduct("SM.Core")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2020")] +[assembly: AssemblyCopyright("Copyright © iedSoftworks 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -33,4 +36,4 @@ using System.Runtime.InteropServices; // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/SMCode/SM.OGL/SM.OGL.csproj b/SMCode/SM.OGL/SM.OGL.csproj index 5fc7a58..960bba9 100644 --- a/SMCode/SM.OGL/SM.OGL.csproj +++ b/SMCode/SM.OGL/SM.OGL.csproj @@ -23,6 +23,7 @@ 4 + latest pdbonly @@ -31,39 +32,39 @@ TRACE prompt 4 + latest - - ..\packages\OpenTK.3.2\lib\net20\OpenTK.dll + + ..\..\packages\OpenTK.3.2.1\lib\net20\OpenTK.dll - - - - - - + + + + + + - diff --git a/SMCode/SM.OGL/Shaders/GenericShader.cs b/SMCode/SM.OGL/Shaders/GenericShader.cs index a39e659..b368685 100644 --- a/SMCode/SM.OGL/Shaders/GenericShader.cs +++ b/SMCode/SM.OGL/Shaders/GenericShader.cs @@ -1,25 +1,30 @@ -using System; +#region usings + using OpenTK.Graphics.OpenGL4; +using SM.OGL.Mesh; + +#endregion namespace SM.OGL.Shaders { /// - /// Abstract class, that is used to create graphic shader. + /// Abstract class, that is used to create graphic shader. /// public abstract class GenericShader : GLObject { + protected override bool AutoCompile { get; } = true; + /// - /// Contains the different files for the shader. + /// Contains the different files for the shader. /// protected ShaderFileCollection ShaderFileFiles; + /// - /// Contains and manage the uniforms from the shader. + /// Contains and manage the uniforms from the shader. /// protected UniformCollection Uniforms; - /// - public override ObjectLabelIdentifier TypeIdentifier { get; } = ObjectLabelIdentifier.Program; - + protected GenericShader(string vertex, string fragment) : this(new ShaderFileCollection(vertex, fragment)){} /// protected GenericShader(ShaderFileCollection shaderFileFiles) @@ -27,35 +32,26 @@ namespace SM.OGL.Shaders ShaderFileFiles = shaderFileFiles; } + /// + public override ObjectLabelIdentifier TypeIdentifier { get; } = ObjectLabelIdentifier.Program; + /// - /// Loads the shader to the GPU. + /// Loads the shader to the GPU. /// public void Load() { - _id = GL.CreateProgram(); ShaderFileFiles.Append(this); GL.LinkProgram(_id); - this.Name(GetType().Name); + Name(GetType().Name); ShaderFileFiles.Detach(this); - GL.GetProgram(_id, GetProgramParameterName.ActiveUniforms, out int uniformCount); - if (uniformCount < 1) - throw new Exception("[Critical] No uniforms has been found."); - Uniforms = new UniformCollection(); - Uniforms._parentShader = this; - for (int i = 0; i < uniformCount; i++) - { - string key = GL.GetActiveUniform(_id, i, out _, out _); - int loc = GL.GetUniformLocation(_id, key); - - if (key.EndsWith("]")) - key = key.Split('[', ']')[0]; - Uniforms.Add(key, loc); - } + Uniforms.ParentShader = this; + Uniforms.Import(this); + GLDebugging.CheckGLErrors($"A error occured at shader creation for '{GetType()}': %code%"); } /// @@ -65,22 +61,21 @@ namespace SM.OGL.Shaders } /// - /// Draws the mesh. + /// Draws the mesh. /// /// The mesh. /// The amounts for instancing. /// Binds the vertex array for the mesh. - protected void DrawObject(Mesh.GenericMesh mesh, int amount = 1, bool bindVAO = false) + protected void DrawObject(GenericMesh mesh, int amount = 1) { - if (bindVAO) GL.BindVertexArray(mesh); - if (mesh.Indices != null) GL.DrawElementsInstanced(mesh.PrimitiveType, 0, DrawElementsType.UnsignedInt, mesh.Indices, amount); - else + else GL.DrawArraysInstanced(mesh.PrimitiveType, 0, mesh.Vertex.Count, amount); } + /// - /// Resets the shader specific settings to ensure proper workings. + /// Resets the shader specific settings to ensure proper workings. /// protected void CleanUp() { diff --git a/SMCode/SM.OGL/Shaders/IUniform.cs b/SMCode/SM.OGL/Shaders/IUniform.cs new file mode 100644 index 0000000..b7f2113 --- /dev/null +++ b/SMCode/SM.OGL/Shaders/IUniform.cs @@ -0,0 +1,7 @@ +namespace SM.OGL.Shaders +{ + public interface IUniform + { + int Location { get; } + } +} \ No newline at end of file diff --git a/SMCode/SM.OGL/Shaders/ShaderExtensions.cs b/SMCode/SM.OGL/Shaders/ShaderExtensions.cs new file mode 100644 index 0000000..b96784b --- /dev/null +++ b/SMCode/SM.OGL/Shaders/ShaderExtensions.cs @@ -0,0 +1,38 @@ +#region usings + +using System.Collections.Generic; +using System.IO; +using System.Reflection; + +#endregion + +namespace SM.OGL.Shaders +{ + public class ShaderExtensions + { + public static Dictionary Extensions { get; private set; } = + new Dictionary(); + + public static void AddAssemblyExtensions(string prefix, string path) + { + AddAssemblyExtensions(prefix, Assembly.GetCallingAssembly(), path); + } + + public static void AddAssemblyExtensions(string prefix, Assembly assembly, string path) + { + var paths = assembly.GetManifestResourceNames(); + for (var i = 0; i < paths.Length; i++) + { + var filePath = paths[i]; + if (!filePath.StartsWith(path)) continue; + + using (var reader = new StreamReader(assembly.GetManifestResourceStream(filePath))) + { + var name = + $"{prefix}{Path.GetFileNameWithoutExtension(filePath.Substring(path.Length)).Replace('.', '_')}"; + Extensions.Add(name, new ShaderFile(reader.ReadToEnd())); + } + } + } + } +} \ No newline at end of file diff --git a/SMCode/SM.OGL/Shaders/ShaderFile.cs b/SMCode/SM.OGL/Shaders/ShaderFile.cs index 0c8ed7d..704ad8f 100644 --- a/SMCode/SM.OGL/Shaders/ShaderFile.cs +++ b/SMCode/SM.OGL/Shaders/ShaderFile.cs @@ -1,30 +1,37 @@ -using System; +#region usings + +using System; using System.Collections.Generic; using OpenTK.Graphics.OpenGL4; +#endregion + namespace SM.OGL.Shaders { /// - /// Contains/Represents a file used in shaders. + /// Contains/Represents a file used in shaders. /// public class ShaderFile : GLObject { private string _data; - /// - public override ObjectLabelIdentifier TypeIdentifier { get; } = ObjectLabelIdentifier.Shader; - /// - /// Contains overrides, that can be used to import values from the CPU to the shader before it is been send to the GPU. - /// - public Dictionary StringOverrides = new Dictionary(); - /// - /// Contains other shader files to allow access to their functions. + /// Contains other shader files to allow access to their functions. /// public List GLSLExtensions = new List(); /// - /// Creates a file. + /// Gets/Sets the name for this shader file. + /// + public new string Name; + + /// + /// Contains overrides, that can be used to import values from the CPU to the shader before it is been send to the GPU. + /// + public Dictionary StringOverrides = new Dictionary(); + + /// + /// Creates a file. /// /// The source file. public ShaderFile(string data) @@ -32,11 +39,28 @@ namespace SM.OGL.Shaders _data = data; } + /// + public override ObjectLabelIdentifier TypeIdentifier { get; } = ObjectLabelIdentifier.Shader; + private void GenerateSource() { - foreach (KeyValuePair kvp in StringOverrides) - _data = _data.Replace("//! " + kvp.Key, kvp.Value); + if (!GLSettings.ShaderPreProcessing) return; + + if (_data.Contains("//#")) + { + var commandSplits = _data.Split(new[] {"//#"}, StringSplitOptions.RemoveEmptyEntries); + for (var i = 1; i < commandSplits.Length; i++) + { + var split = commandSplits[i].Split('\r', '\n')[0].Trim(); + var cmdArgs = split.Split(new[] {' '}, 2); + + ShaderPreProcess.Actions[cmdArgs[0]]?.Invoke(this, cmdArgs[1]); + } + } + + foreach (var kvp in StringOverrides) + _data = _data.Replace("//!" + kvp.Key, kvp.Value); } internal void Compile(GenericShader shader, ShaderType type) @@ -49,7 +73,11 @@ namespace SM.OGL.Shaders GL.ShaderSource(_id, _data); GL.CompileShader(_id); } + GL.AttachShader(shader, _id); + GLDebugging.CheckGLErrors($"Error at loading shader file: '{shader.GetType()}', '{type}', %code%"); + + for (var i = 0; i < GLSLExtensions.Count; i++) GLSLExtensions[i].Compile(shader, type); } } } \ No newline at end of file diff --git a/SMCode/SM.OGL/Shaders/ShaderFileCollection.cs b/SMCode/SM.OGL/Shaders/ShaderFileCollection.cs index 5258d11..b15e2f6 100644 --- a/SMCode/SM.OGL/Shaders/ShaderFileCollection.cs +++ b/SMCode/SM.OGL/Shaders/ShaderFileCollection.cs @@ -1,36 +1,43 @@ -using System; -using System.Collections.Generic; +#region usings + using OpenTK.Graphics.OpenGL4; +#endregion + namespace SM.OGL.Shaders { /// - /// Collects all files that are needed for a shader. + /// Collects all files that are needed for a shader. /// public struct ShaderFileCollection { /// - /// Contains the vertex file. + /// Contains the vertex file. /// public ShaderFile Vertex; + /// - /// Contains the geometry file. + /// Contains the geometry file. /// public ShaderFile Geometry; + /// - /// Contains the fragment file. + /// Contains the fragment file. /// public ShaderFile Fragment; /// - /// Creating the collection with vertex and fragment files. + /// Creating the collection with vertex and fragment files. /// /// The vertex source file. /// The fragment source file. - public ShaderFileCollection(string vertex, string fragment) : this(new ShaderFile(vertex), new ShaderFile(fragment)) {} + public ShaderFileCollection(string vertex, string fragment) : this(new ShaderFile(vertex), + new ShaderFile(fragment)) + { + } /// - /// Creating the collection with shader files. + /// Creating the collection with shader files. /// /// /// @@ -43,7 +50,7 @@ namespace SM.OGL.Shaders } /// - /// Appends the files to the shader. + /// Appends the files to the shader. /// /// internal void Append(GenericShader shader) @@ -54,14 +61,16 @@ namespace SM.OGL.Shaders } /// - /// Removes the files form the shader. + /// Removes the files form the shader. /// /// internal void Detach(GenericShader shader) { - GL.DetachShader(Vertex, shader); - if (Geometry != null) GL.DetachShader(Geometry, shader); - GL.DetachShader(Fragment, shader); + GL.DetachShader(shader, Vertex); + if (Geometry != null) GL.DetachShader(shader, Geometry); + GL.DetachShader(shader, Fragment); + + GLDebugging.CheckGLErrors($"Error at detaching '{shader.GetType()}'"); } } } \ No newline at end of file diff --git a/SMCode/SM.OGL/Shaders/ShaderPreProcess.cs b/SMCode/SM.OGL/Shaders/ShaderPreProcess.cs new file mode 100644 index 0000000..ac6c58c --- /dev/null +++ b/SMCode/SM.OGL/Shaders/ShaderPreProcess.cs @@ -0,0 +1,24 @@ +#region usings + +using System; +using System.Collections.Generic; + +#endregion + +namespace SM.OGL.Shaders +{ + public class ShaderPreProcess + { + public static Dictionary> Actions = + new Dictionary> + { + {"import", Import} + }; + + private static void Import(ShaderFile file, string param) + { + foreach (var extension in param.Split(' ')) + file.GLSLExtensions.Add(ShaderExtensions.Extensions[extension]); + } + } +} \ No newline at end of file diff --git a/SMCode/SM.OGL/Shaders/Uniform.cs b/SMCode/SM.OGL/Shaders/Uniform.cs index ce5d649..01c99b0 100644 --- a/SMCode/SM.OGL/Shaders/Uniform.cs +++ b/SMCode/SM.OGL/Shaders/Uniform.cs @@ -1,27 +1,35 @@ -using OpenTK; +#region usings + +using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL4; using SM.OGL.Texture; +#endregion + namespace SM.OGL.Shaders { /// - /// Manages the uniforms. + /// Manages the uniforms. /// - public struct Uniform + public struct Uniform : IUniform { /// - /// This contains the location for the uniform. + /// This contains the location for the uniform. /// - private int Location; - /// - /// This contains the Parent collection of this uniform. - /// - internal UniformCollection Parent; - + public int Location { get; internal set; } /// - /// This create a new uniform manager + /// This contains the Parent collection of this uniform. + /// + public UniformCollection Parent { get; } + + public Uniform(int location) : this(location, null) + { + } + + /// + /// This create a new uniform manager /// /// Location id /// Parent collection @@ -38,114 +46,343 @@ namespace SM.OGL.Shaders GL.Uniform1(Location, value ? 1 : 0); } - public void SetUniform1(int value) { GL.Uniform1(Location, value); } - public void SetUniform1(int count, params int[] values) { GL.Uniform1(Location, count, values); } - public void SetUniform1(int count, ref int values) { GL.Uniform1(Location, count, ref values); } + public void SetUniform1(int value) + { + GL.Uniform1(Location, value); + } + + public void SetUniform1(int count, params int[] values) + { + GL.Uniform1(Location, count, values); + } + + public void SetUniform1(int count, ref int values) + { + GL.Uniform1(Location, count, ref values); + } - public void SetUniform1(uint value) { GL.Uniform1(Location, value); } - public void SetUniform1(int count, params uint[] values) { GL.Uniform1(Location, count, values); } - public void SetUniform1(int count, ref uint values) { GL.Uniform1(Location, count, ref values); } + public void SetUniform1(uint value) + { + GL.Uniform1(Location, value); + } + + public void SetUniform1(int count, params uint[] values) + { + GL.Uniform1(Location, count, values); + } + + public void SetUniform1(int count, ref uint values) + { + GL.Uniform1(Location, count, ref values); + } - public void SetUniform1(float value) { GL.Uniform1(Location, value); } - public void SetUniform1(int count, params float[] values) { GL.Uniform1(Location, count, values); } - public void SetUniform1(int count, ref float value) { GL.Uniform1(Location, count, ref value); } + public void SetUniform1(float value) + { + GL.Uniform1(Location, value); + } + + public void SetUniform1(int count, params float[] values) + { + GL.Uniform1(Location, count, values); + } + + public void SetUniform1(int count, ref float value) + { + GL.Uniform1(Location, count, ref value); + } - public void SetUniform1(double value) { GL.Uniform1(Location, value); } - public void SetUniform1(int count, params double[] values) { GL.Uniform1(Location, count, values); } - public void SetUniform1(int count, ref double value) { GL.Uniform1(Location, count, ref value); } + public void SetUniform1(double value) + { + GL.Uniform1(Location, value); + } + + public void SetUniform1(int count, params double[] values) + { + GL.Uniform1(Location, count, values); + } + + public void SetUniform1(int count, ref double value) + { + GL.Uniform1(Location, count, ref value); + } #endregion #region Uniform2 - public void SetUniform2(float x, float y) { GL.Uniform2(Location, x, y); } - public void SetUniform2(double x, double y) { GL.Uniform2(Location, x, y); } - public void SetUniform2(uint x, uint y) { GL.Uniform2(Location, x, y); } - public void SetUniform2(int x, int y) { GL.Uniform2(Location, x, y); } + public void SetUniform2(float x, float y) + { + GL.Uniform2(Location, x, y); + } - public void SetUniform2(int count, params float[] values) { GL.Uniform2(Location, count, values); } - public void SetUniform2(int count, params double[] values) { GL.Uniform2(Location, count, values); } - public void SetUniform2(int count, params int[] values) { GL.Uniform2(Location, count, values); } - public void SetUniform2(int count, params uint[] values) { GL.Uniform2(Location, count, values); } + public void SetUniform2(double x, double y) + { + GL.Uniform2(Location, x, y); + } - public void SetUniform2(int count, ref float values) { GL.Uniform2(Location, count, ref values); } - public void SetUniform2(int count, ref double values) { GL.Uniform2(Location, count, ref values); } - public void SetUniform2(int count, ref uint values) { GL.Uniform2(Location, count, ref values); } + public void SetUniform2(uint x, uint y) + { + GL.Uniform2(Location, x, y); + } - public void SetUniform2(Vector2 vector2) { GL.Uniform2(Location, vector2); } - public void SetUniform2(ref Vector2 vector2) { GL.Uniform2(Location, ref vector2); } + public void SetUniform2(int x, int y) + { + GL.Uniform2(Location, x, y); + } + + public void SetUniform2(int count, params float[] values) + { + GL.Uniform2(Location, count, values); + } + + public void SetUniform2(int count, params double[] values) + { + GL.Uniform2(Location, count, values); + } + + public void SetUniform2(int count, params int[] values) + { + GL.Uniform2(Location, count, values); + } + + public void SetUniform2(int count, params uint[] values) + { + GL.Uniform2(Location, count, values); + } + + public void SetUniform2(int count, ref float values) + { + GL.Uniform2(Location, count, ref values); + } + + public void SetUniform2(int count, ref double values) + { + GL.Uniform2(Location, count, ref values); + } + + public void SetUniform2(int count, ref uint values) + { + GL.Uniform2(Location, count, ref values); + } + + public void SetUniform2(Vector2 vector2) + { + GL.Uniform2(Location, vector2); + } + + public void SetUniform2(ref Vector2 vector2) + { + GL.Uniform2(Location, ref vector2); + } #endregion #region Uniform3 - public void SetUniform3(float x, float y, float z) { GL.Uniform3(Location, x, y, z); } - public void SetUniform3(double x, double y, double z) { GL.Uniform3(Location, x, y, z); } - public void SetUniform3(uint x, uint y, uint z) { GL.Uniform3(Location, x, y, z); } - public void SetUniform3(int x, int y, int z) { GL.Uniform3(Location, x, y, z); } + public void SetUniform3(float x, float y, float z) + { + GL.Uniform3(Location, x, y, z); + } - public void SetUniform3(int count, params float[] values) { GL.Uniform3(Location, count, values); } - public void SetUniform3(int count, params double[] values) { GL.Uniform3(Location, count, values); } - public void SetUniform3(int count, params int[] values) { GL.Uniform3(Location, count, values); } - public void SetUniform3(int count, params uint[] values) { GL.Uniform3(Location, count, values); } + public void SetUniform3(double x, double y, double z) + { + GL.Uniform3(Location, x, y, z); + } - public void SetUniform3(int count, ref float values) { GL.Uniform3(Location, count, ref values); } - public void SetUniform3(int count, ref double values) { GL.Uniform3(Location, count, ref values); } - public void SetUniform3(int count, ref uint values) { GL.Uniform3(Location, count, ref values); } + public void SetUniform3(uint x, uint y, uint z) + { + GL.Uniform3(Location, x, y, z); + } - public void SetUniform3(Vector3 vector) { GL.Uniform3(Location, vector); } - public void SetUniform3(ref Vector3 vector) { GL.Uniform3(Location, ref vector); } + public void SetUniform3(int x, int y, int z) + { + GL.Uniform3(Location, x, y, z); + } + + public void SetUniform3(int count, params float[] values) + { + GL.Uniform3(Location, count, values); + } + + public void SetUniform3(int count, params double[] values) + { + GL.Uniform3(Location, count, values); + } + + public void SetUniform3(int count, params int[] values) + { + GL.Uniform3(Location, count, values); + } + + public void SetUniform3(int count, params uint[] values) + { + GL.Uniform3(Location, count, values); + } + + public void SetUniform3(int count, ref float values) + { + GL.Uniform3(Location, count, ref values); + } + + public void SetUniform3(int count, ref double values) + { + GL.Uniform3(Location, count, ref values); + } + + public void SetUniform3(int count, ref uint values) + { + GL.Uniform3(Location, count, ref values); + } + + public void SetUniform3(Vector3 vector) + { + GL.Uniform3(Location, vector); + } + + public void SetUniform3(ref Vector3 vector) + { + GL.Uniform3(Location, ref vector); + } #endregion #region Uniform4 - public void SetUniform4(float x, float y, float z, float w) { GL.Uniform4(Location, x, y, z, w); } - public void SetUniform4(double x, double y, double z, double w) { GL.Uniform4(Location, x, y, z, w); } - public void SetUniform4(uint x, uint y, uint z, uint w) { GL.Uniform4(Location, x, y, z, w); } - public void SetUniform4(int x, int y, int z, int w) { GL.Uniform4(Location, x, y, z, w); } + public void SetUniform4(float x, float y, float z, float w) + { + GL.Uniform4(Location, x, y, z, w); + } - public void SetUniform4(int count, params float[] values) { GL.Uniform4(Location, count, values); } - public void SetUniform4(int count, params double[] values) { GL.Uniform4(Location, count, values); } - public void SetUniform4(int count, params int[] values) { GL.Uniform4(Location, count, values); } - public void SetUniform4(int count, params uint[] values) { GL.Uniform4(Location, count, values); } + public void SetUniform4(double x, double y, double z, double w) + { + GL.Uniform4(Location, x, y, z, w); + } - public void SetUniform4(int count, ref float values) { GL.Uniform4(Location, count, ref values); } - public void SetUniform4(int count, ref double values) { GL.Uniform4(Location, count, ref values); } - public void SetUniform4(int count, ref uint values) { GL.Uniform4(Location, count, ref values); } + public void SetUniform4(uint x, uint y, uint z, uint w) + { + GL.Uniform4(Location, x, y, z, w); + } - public void SetUniform4(Vector4 vector) { GL.Uniform4(Location, vector); } - public void SetUniform4(ref Vector4 vector) { GL.Uniform4(Location, ref vector); } + public void SetUniform4(int x, int y, int z, int w) + { + GL.Uniform4(Location, x, y, z, w); + } - public void SetUniform4(Color4 color) { GL.Uniform4(Location, color); } - public void SetUniform4(Quaternion quaternion) { GL.Uniform4(Location, quaternion); } + public void SetUniform4(int count, params float[] values) + { + GL.Uniform4(Location, count, values); + } + + public void SetUniform4(int count, params double[] values) + { + GL.Uniform4(Location, count, values); + } + + public void SetUniform4(int count, params int[] values) + { + GL.Uniform4(Location, count, values); + } + + public void SetUniform4(int count, params uint[] values) + { + GL.Uniform4(Location, count, values); + } + + public void SetUniform4(int count, ref float values) + { + GL.Uniform4(Location, count, ref values); + } + + public void SetUniform4(int count, ref double values) + { + GL.Uniform4(Location, count, ref values); + } + + public void SetUniform4(int count, ref uint values) + { + GL.Uniform4(Location, count, ref values); + } + + public void SetUniform4(Vector4 vector) + { + GL.Uniform4(Location, vector); + } + + public void SetUniform4(ref Vector4 vector) + { + GL.Uniform4(Location, ref vector); + } + + public void SetUniform4(Color4 color) + { + GL.Uniform4(Location, color); + } + + public void SetUniform4(Quaternion quaternion) + { + GL.Uniform4(Location, quaternion); + } #endregion #region Matrix2 - public void SetMatrix2(ref Matrix2 matrix, bool transpose = false) { GL.UniformMatrix2(Location, transpose, ref matrix); } + public void SetMatrix2(ref Matrix2 matrix, bool transpose = false) + { + GL.UniformMatrix2(Location, transpose, ref matrix); + } - public void SetMatrix2(int count, ref double value, bool transpose = false) { GL.UniformMatrix2(Location, count, transpose, ref value); } - public void SetMatrix2(int count, ref float value, bool transpose = false) { GL.UniformMatrix2(Location, count, transpose, ref value); } + public void SetMatrix2(int count, ref double value, bool transpose = false) + { + GL.UniformMatrix2(Location, count, transpose, ref value); + } - public void SetMatrix2(int count, double[] value, bool transpose = false) { GL.UniformMatrix2(Location, count, transpose, value); } - public void SetMatrix2(int count, float[] value, bool transpose = false) { GL.UniformMatrix2(Location, count, transpose, value); } + public void SetMatrix2(int count, ref float value, bool transpose = false) + { + GL.UniformMatrix2(Location, count, transpose, ref value); + } + + public void SetMatrix2(int count, double[] value, bool transpose = false) + { + GL.UniformMatrix2(Location, count, transpose, value); + } + + public void SetMatrix2(int count, float[] value, bool transpose = false) + { + GL.UniformMatrix2(Location, count, transpose, value); + } #endregion #region Matrix3 - public void SetMatrix3(ref Matrix3 matrix, bool transpose = false) { GL.UniformMatrix3(Location, transpose, ref matrix); } + public void SetMatrix3(ref Matrix3 matrix, bool transpose = false) + { + GL.UniformMatrix3(Location, transpose, ref matrix); + } - public void SetMatrix3(int count, ref double value, bool transpose = false) { GL.UniformMatrix3(Location, count, transpose, ref value); } - public void SetMatrix3(int count, ref float value, bool transpose = false) { GL.UniformMatrix3(Location, count, transpose, ref value); } + public void SetMatrix3(int count, ref double value, bool transpose = false) + { + GL.UniformMatrix3(Location, count, transpose, ref value); + } - public void SetMatrix3(int count, double[] value, bool transpose = false) { GL.UniformMatrix3(Location, count, transpose, value); } - public void SetMatrix3(int count, float[] value, bool transpose = false) { GL.UniformMatrix3(Location, count, transpose, value); } + public void SetMatrix3(int count, ref float value, bool transpose = false) + { + GL.UniformMatrix3(Location, count, transpose, ref value); + } + + public void SetMatrix3(int count, double[] value, bool transpose = false) + { + GL.UniformMatrix3(Location, count, transpose, value); + } + + public void SetMatrix3(int count, float[] value, bool transpose = false) + { + GL.UniformMatrix3(Location, count, transpose, value); + } #endregion @@ -155,18 +392,36 @@ namespace SM.OGL.Shaders { GL.UniformMatrix4(Location, transpose, ref matrix); } - public void SetMatrix4(ref Matrix4 matrix, bool transpose = false) { GL.UniformMatrix4(Location, transpose, ref matrix); } - public void SetMatrix4(int count, ref double value, bool transpose = false) { GL.UniformMatrix4(Location, count, transpose, ref value); } - public void SetMatrix4(int count, ref float value, bool transpose = false) { GL.UniformMatrix4(Location, count, transpose, ref value); } + public void SetMatrix4(ref Matrix4 matrix, bool transpose = false) + { + GL.UniformMatrix4(Location, transpose, ref matrix); + } - public void SetMatrix4(int count, double[] value, bool transpose = false) { GL.UniformMatrix4(Location, count, transpose, value); } - public void SetMatrix4(int count, float[] value, bool transpose = false) { GL.UniformMatrix4(Location, count, transpose, value); } + public void SetMatrix4(int count, ref double value, bool transpose = false) + { + GL.UniformMatrix4(Location, count, transpose, ref value); + } + + public void SetMatrix4(int count, ref float value, bool transpose = false) + { + GL.UniformMatrix4(Location, count, transpose, ref value); + } + + public void SetMatrix4(int count, double[] value, bool transpose = false) + { + GL.UniformMatrix4(Location, count, transpose, value); + } + + public void SetMatrix4(int count, float[] value, bool transpose = false) + { + GL.UniformMatrix4(Location, count, transpose, value); + } #endregion /// - /// Try to sets the texture at the next possible position and tells the checkUniform, if worked or not. + /// Try to sets the texture at the next possible position and tells the checkUniform, if worked or not. /// /// The texture you want to add /// The check uniform. @@ -177,7 +432,7 @@ namespace SM.OGL.Shaders } /// - /// Try to sets the texture at the specified position and tells the checkUniform, if worked or not. + /// Try to sets the texture at the specified position and tells the checkUniform, if worked or not. /// /// The texture you want to add /// The position @@ -187,14 +442,18 @@ namespace SM.OGL.Shaders checkUniform.SetUniform1(texture != null); if (texture != null) SetTexture(texture); } - /// - /// Sets the texture to the next possible position. - /// - /// - public void SetTexture(TextureBase texture) => SetTexture(texture, Parent.NextTexture++); /// - /// Sets the texture to the specified position. + /// Sets the texture to the next possible position. + /// + /// + public void SetTexture(TextureBase texture) + { + if (Parent != null) SetTexture(texture, Parent.NextTexture++); + } + + /// + /// Sets the texture to the specified position. /// /// /// @@ -206,9 +465,12 @@ namespace SM.OGL.Shaders } /// - /// Returns the location from the uniform + /// Returns the location from the uniform /// /// - public static implicit operator int(Uniform u) => u.Location; + public static implicit operator int(Uniform u) + { + return u.Location; + } } } \ No newline at end of file diff --git a/SMCode/SM.OGL/Shaders/UniformArray.cs b/SMCode/SM.OGL/Shaders/UniformArray.cs new file mode 100644 index 0000000..8406882 --- /dev/null +++ b/SMCode/SM.OGL/Shaders/UniformArray.cs @@ -0,0 +1,50 @@ +#region usings + +using System; +using System.Collections.Generic; + +#endregion + +namespace SM.OGL.Shaders +{ + public class UniformArray : IUniform + { + internal UniformCollection collection; + + internal Dictionary Offsets = new Dictionary(); + internal int Size; + + internal bool Struct = false; + public int Location { get; internal set; } + public GenericShader Parent { get; internal set; } + public string Name { get; internal set; } + + public UniformArray() + { + collection = new UniformCollection() + { + ParentShader = Parent + }; + } + + public void Set(Action setAction) + { + for (var i = 0; i < Size; i++) setAction(i, new Uniform(Location + i)); + } + + public void Set(Func setAction) + { + collection.ParentShader ??= Parent; + + for (var i = 0; i < Size; i++) + { + collection.KeyString = $"{Name}[{i}]"; + + foreach (var pair in Offsets) + collection.Set(pair.Key, new Uniform(Location + pair.Value + i)); + + if (!setAction(i, collection)) break; + } + } + } +} \ No newline at end of file diff --git a/SMCode/SM.OGL/Shaders/UniformCollection.cs b/SMCode/SM.OGL/Shaders/UniformCollection.cs index a6f7e3e..9cc5bb3 100644 --- a/SMCode/SM.OGL/Shaders/UniformCollection.cs +++ b/SMCode/SM.OGL/Shaders/UniformCollection.cs @@ -1,56 +1,109 @@ -using System; +#region usings + +using System; using System.Collections.Generic; using OpenTK.Graphics.OpenGL4; +#endregion + namespace SM.OGL.Shaders { - /// - /// Contains and manages the uniform of the parent shader. - /// - public class UniformCollection : Dictionary + public class UniformCollection : Dictionary { - /// - /// The next texture id for the uniform. - /// internal int NextTexture = 0; + internal string KeyString = ""; + public GenericShader ParentShader { get; internal set; } - /// - /// The parent shader. - /// - internal GenericShader _parentShader; + public new Uniform this[string key] => Get(key); - /// - /// Get you the uniform under the variable name. - /// If it don't find the uniform, it tries to recreate it. - /// If the variable doesn't exist in the first place, it will after the recreation send everything to -1, what is the void. - /// - /// - /// - public new Uniform this[string key] + public Uniform Get(string key) { - get + try { - try - { - return base[key]; - } - catch (KeyNotFoundException) - { - Console.WriteLine("[Error] Uniform '"+key+"' was not found. Tried to recreate it."); - Uniform u = new Uniform(GL.GetUniformLocation(_parentShader, key), this); - Add(key, u); - return u; - } + return (Uniform) base[key]; + } + catch (KeyNotFoundException) + { + GLCustomActions.AtWarning?.Invoke("Uniform '" + KeyString + key + "' was not found. Tried to recreate it."); + var u = new Uniform(GL.GetUniformLocation(ParentShader, KeyString + key), this); + Add(key, u); + return u; } } - /// - /// Adds a uniform with a location. - /// - /// - /// + + public UniformArray GetArray(string key) + { + try + { + return (UniformArray) base[key]; + } + catch (KeyNotFoundException) + { + throw new Exception("UniformArray '"+key+"' wasn't found"); + } + } + public void Add(string key, int location) { base.Add(key, new Uniform(location, this)); } + + internal void Set(string key, IUniform value) + { + base[key] = value; + } + + internal void Import(GenericShader shader) + { + GL.GetProgram(shader, GetProgramParameterName.ActiveUniforms, out var uniformCount); + if (uniformCount < 1) + GLCustomActions.AtError("No uniforms has been found."); + + var lastArrayKey = ""; + var array = new UniformArray(); + var arrayFilled = false; + + if (GLSettings.InfoEveryUniform) GLCustomActions.AtInfo?.Invoke("Uniforms for: " + shader.GetType()); + + for (var i = 0; i < uniformCount; i++) + { + var key = GL.GetActiveUniform(shader, i, out _, out _); + var loc = GL.GetUniformLocation(shader, key); + if (GLSettings.InfoEveryUniform) GLCustomActions.AtInfo?.Invoke($"{key} - {loc}"); + + if (key.Contains("[")) + { + var keySplits = key.Split('[', ']'); + if (keySplits[0] != lastArrayKey) + { + if (arrayFilled) Add(lastArrayKey, array); + + array = new UniformArray + { + Location = loc, + Name = keySplits[0], + Parent = ParentShader, + Struct = keySplits.Length > 2 + }; + + arrayFilled = true; + lastArrayKey = keySplits[0]; + } + + var curIndex = int.Parse(keySplits[1]); + if (array.Size < curIndex) array.Size = curIndex; + + if (array.Struct) + if (!array.Offsets.ContainsKey(keySplits[2].Trim('.'))) + array.Offsets.Add(keySplits[2].Trim('.'), loc - array.Location); + } + else + { + Add(key, loc); + } + } + + if (arrayFilled) Add(lastArrayKey, array); + } } } \ No newline at end of file diff --git a/SMCode/SM.OGL/Texture/TextureBase.cs b/SMCode/SM.OGL/Texture/TextureBase.cs index 8779140..fd1966e 100644 --- a/SMCode/SM.OGL/Texture/TextureBase.cs +++ b/SMCode/SM.OGL/Texture/TextureBase.cs @@ -1,9 +1,13 @@ -using OpenTK.Graphics.OpenGL4; +#region usings + +using OpenTK.Graphics.OpenGL4; + +#endregion namespace SM.OGL.Texture { /// - /// Works as a basis for textures. + /// Works as a basis for textures. /// public abstract class TextureBase : GLObject { @@ -14,23 +18,24 @@ namespace SM.OGL.Texture public override ObjectLabelIdentifier TypeIdentifier { get; } = ObjectLabelIdentifier.Texture; /// - /// The texture filter. - /// Default: + /// The texture filter. + /// Default: /// public virtual TextureMinFilter Filter { get; set; } = TextureMinFilter.Linear; /// - /// The wrap mode. - /// Default: + /// The wrap mode. + /// Default: /// public virtual TextureWrapMode WrapMode { get; set; } = TextureWrapMode.Repeat; /// - /// The Width of the texture + /// The Width of the texture /// public int Width { get; protected set; } + /// - /// The height of the texture + /// The height of the texture /// public int Height { get; protected set; } diff --git a/SMCode/SM.OGL/Version.cs b/SMCode/SM.OGL/Version.cs index be2ed3c..57ce45d 100644 --- a/SMCode/SM.OGL/Version.cs +++ b/SMCode/SM.OGL/Version.cs @@ -1,21 +1,22 @@ namespace SM.OGL { /// - /// Helper struct to manage versions. + /// Helper struct to manage versions. /// public struct Version { /// - /// The major version. + /// The major version. /// public int MajorVersion; + /// - /// The minor version. + /// The minor version. /// public int MinorVersion; /// - /// Creates the struct with specific major and minor versions. + /// Creates the struct with specific major and minor versions. /// /// /// @@ -26,12 +27,12 @@ } /// - /// Creates the struct by reading it out of a string. + /// Creates the struct by reading it out of a string. /// /// public Version(string version) { - string[] splits = version.Trim().Split(new []{'.'}, 2); + var splits = version.Trim().Split(new[] {'.'}, 2); MajorVersion = int.Parse(splits[0]); MinorVersion = int.Parse(splits[1]); } @@ -43,7 +44,7 @@ } /// - /// Create a version struct, with a OpenGL Version string. + /// Create a version struct, with a OpenGL Version string. /// /// /// diff --git a/SMCode/SM.OGL/packages.config b/SMCode/SM.OGL/packages.config index 75397e4..9a4debe 100644 --- a/SMCode/SM.OGL/packages.config +++ b/SMCode/SM.OGL/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/SMCode/SM2D/Controls/Mouse2D.cs b/SMCode/SM2D/Controls/Mouse2D.cs index 0278b61..e0e5b7e 100644 --- a/SMCode/SM2D/Controls/Mouse2D.cs +++ b/SMCode/SM2D/Controls/Mouse2D.cs @@ -1,21 +1,28 @@ -using OpenTK; +#region usings + +using OpenTK; using OpenTK.Input; -using SM.Base; using SM.Base.Controls; using SM2D.Scene; +#endregion + namespace SM2D.Controls { public class Mouse2D : Mouse { protected internal Mouse2D(GLWindow2D window) : base(window) - { } + { + } - internal new void MouseMoveEvent(MouseMoveEventArgs mmea) => base.MouseMoveEvent(mmea); + internal new void MouseMoveEvent(MouseMoveEventArgs mmea) + { + base.MouseMoveEvent(mmea); + } public Vector2 InWorld() { - Vector2 res = _window.WorldScale; + var res = _window.WorldScale; return InScreenNormalized * res - res / 2; } diff --git a/SMCode/SM2D/Drawing/DrawBackground.cs b/SMCode/SM2D/Drawing/DrawBackground.cs index a59ef2f..33188ed 100644 --- a/SMCode/SM2D/Drawing/DrawBackground.cs +++ b/SMCode/SM2D/Drawing/DrawBackground.cs @@ -1,15 +1,16 @@ -using System.Collections.Generic; +#region usings + +using System.Collections.Generic; using System.Drawing; using OpenTK; using OpenTK.Graphics; -using SM.Base; using SM.Base.Contexts; using SM.Base.Objects.Static; using SM.Base.Scene; using SM.Base.Textures; using SM.OGL.Texture; -using SM2D.Shader; -using SM2D.Types; + +#endregion namespace SM2D.Drawing { @@ -17,6 +18,22 @@ namespace SM2D.Drawing { private Material _material = new Material(); + public DrawBackground(Color4 color) + { + Color = color; + } + + public DrawBackground(Bitmap texture) + { + Texture = (Texture) texture; + } + + public DrawBackground(Bitmap texture, Color4 tint) + { + Color = tint; + Texture = (Texture) texture; + } + public Color4 Color { get => _material.Tint; @@ -28,28 +45,14 @@ namespace SM2D.Drawing get => _material.Texture; set => _material.Texture = value; } - public DrawBackground(Color4 color) - { - Color = color; - } - - public DrawBackground(Bitmap texture) - { - Texture = (Texture)texture; - } - - public DrawBackground(Bitmap texture, Color4 tint) - { - Color = tint; - Texture = (Texture) texture; - } public object Parent { get; set; } public string Name { get; set; } = "Background"; public ICollection Flags { get; set; } = new string[0]; public void Update(UpdateContext context) - { } + { + } public void Draw(DrawContext context) { diff --git a/SMCode/SM2D/Drawing/DrawBackgroundShader.cs b/SMCode/SM2D/Drawing/DrawBackgroundShader.cs new file mode 100644 index 0000000..5bdf4f4 --- /dev/null +++ b/SMCode/SM2D/Drawing/DrawBackgroundShader.cs @@ -0,0 +1,19 @@ +using SM.Base.Contexts; +using SM.Base.Scene; +using SM2D.Scene; + +namespace SM2D.Drawing +{ + public class DrawBackgroundShader : DrawShader, IBackgroundItem + { + public DrawBackgroundShader(MaterialShader shader) : base(shader) + { } + + protected override void DrawContext(ref DrawContext context) + { + Transform.Size.Set(context.WorldScale); + + base.DrawContext(ref context); + } + } +} \ No newline at end of file diff --git a/SMCode/SM2D/Drawing/DrawColor.cs b/SMCode/SM2D/Drawing/DrawColor.cs index 2cc6b84..17ffa17 100644 --- a/SMCode/SM2D/Drawing/DrawColor.cs +++ b/SMCode/SM2D/Drawing/DrawColor.cs @@ -1,14 +1,26 @@ -using OpenTK.Graphics; -using SM.Base; +#region usings + +using OpenTK.Graphics; using SM.Base.Contexts; using SM.Base.Scene; using SM2D.Scene; using SM2D.Types; +#endregion + namespace SM2D.Drawing { public class DrawColor : DrawingBasis, I2DShowItem { + public DrawColor() + { + } + + public DrawColor(Color4 color) + { + _material.Tint = color; + } + public Color4 Color { get => _material.Tint; @@ -17,13 +29,6 @@ namespace SM2D.Drawing public int ZIndex { get; set; } - public DrawColor() {} - - public DrawColor(Color4 color) - { - _material.Tint = color; - } - protected override void DrawContext(ref DrawContext context) { context.Instances[0].ModelMatrix = Transform.GetMatrix(); diff --git a/SMCode/SM2D/Drawing/DrawComplex.cs b/SMCode/SM2D/Drawing/DrawComplex.cs index 6d52794..c1a883e 100644 --- a/SMCode/SM2D/Drawing/DrawComplex.cs +++ b/SMCode/SM2D/Drawing/DrawComplex.cs @@ -1,15 +1,17 @@ -using SM.Base.Contexts; +#region usings + +using SM.Base.Contexts; using SM.Base.Scene; using SM.OGL.Mesh; using SM2D.Scene; using SM2D.Types; +#endregion + namespace SM2D.Drawing { - public class DrawComplex: DrawingBasis, I2DShowItem + public class DrawComplex : DrawingBasis, I2DShowItem { - public int ZIndex { get; set; } - public Material Material { get => _material; @@ -22,6 +24,8 @@ namespace SM2D.Drawing set => _mesh = value; } + public int ZIndex { get; set; } + protected override void DrawContext(ref DrawContext context) { context.Instances[0].ModelMatrix = Transform.GetMatrix(); diff --git a/SMCode/SM2D/Drawing/DrawPolygon.cs b/SMCode/SM2D/Drawing/DrawPolygon.cs index 60f18cf..8de1438 100644 --- a/SMCode/SM2D/Drawing/DrawPolygon.cs +++ b/SMCode/SM2D/Drawing/DrawPolygon.cs @@ -1,38 +1,46 @@ -using System.Drawing; +#region usings + +using System.Drawing; using OpenTK.Graphics; using SM.Base.Textures; -using SM.OGL.Texture; using SM2D.Object; +#endregion + namespace SM2D.Drawing { public class DrawPolygon : DrawColor { - public Polygon Polygon + public DrawPolygon(Polygon polygon) : this(polygon, Color4.White) { - get => (Polygon)_mesh; - set => _mesh = value; } - public Texture Texture + public DrawPolygon(Polygon polygon, Bitmap map) : this(polygon, map, Color4.White) { - get => (Texture)_material.Texture; - set => _material.Texture = value; } - public DrawPolygon(Polygon polygon) {} - - public DrawPolygon(Polygon polygon, Bitmap map) : this(polygon, map, Color4.White) {} - public DrawPolygon(Polygon polygon, Color4 color) : base(color) { _mesh = polygon; } + public DrawPolygon(Polygon polygon, Bitmap map, Color4 tint) : base(tint) { _mesh = polygon; _material.Texture = new Texture(map); } + + public Polygon Polygon + { + get => (Polygon) _mesh; + set => _mesh = value; + } + + public Texture Texture + { + get => (Texture) _material.Texture; + set => _material.Texture = value; + } } } \ No newline at end of file diff --git a/SMCode/SM2D/Drawing/DrawShader.cs b/SMCode/SM2D/Drawing/DrawShader.cs new file mode 100644 index 0000000..c95f8f6 --- /dev/null +++ b/SMCode/SM2D/Drawing/DrawShader.cs @@ -0,0 +1,24 @@ +using SM.Base.Contexts; +using SM.Base.Scene; +using SM2D.Scene; +using SM2D.Types; + +namespace SM2D.Drawing +{ + public class DrawShader : DrawingBasis, I2DShowItem + { + public int ZIndex { get; set; } + + public DrawShader(MaterialShader shader) + { + _material.CustomShader = shader; + } + + protected override void DrawContext(ref DrawContext context) + { + context.Instances[0].ModelMatrix = Transform.GetMatrix(); + + _material.CustomShader.Draw(context); + } + } +} \ No newline at end of file diff --git a/SMCode/SM2D/Drawing/DrawText.cs b/SMCode/SM2D/Drawing/DrawText.cs index 66e2985..38f78bc 100644 --- a/SMCode/SM2D/Drawing/DrawText.cs +++ b/SMCode/SM2D/Drawing/DrawText.cs @@ -1,10 +1,13 @@ -using SM.Base; +#region usings + using SM.Base.Contexts; using SM.Base.Text; using SM.Base.Types; using SM2D.Scene; using SM2D.Types; +#endregion + namespace SM2D.Drawing { public class DrawText : TextDrawingBasis, I2DShowItem @@ -15,6 +18,8 @@ namespace SM2D.Drawing Transform.Size = new CVector2(1); } + public int ZIndex { get; set; } + protected override void DrawContext(ref DrawContext context) { base.DrawContext(ref context); @@ -24,7 +29,5 @@ namespace SM2D.Drawing context.Shader.Draw(context); } - - public int ZIndex { get; set; } } } \ No newline at end of file diff --git a/SMCode/SM2D/Drawing/DrawTexture.cs b/SMCode/SM2D/Drawing/DrawTexture.cs index bc2765c..440fef1 100644 --- a/SMCode/SM2D/Drawing/DrawTexture.cs +++ b/SMCode/SM2D/Drawing/DrawTexture.cs @@ -1,36 +1,37 @@ -using System.Drawing; -using OpenTK; +#region usings + +using System.Drawing; using OpenTK.Graphics; using SM.Base.Contexts; -using SM.Base.Scene; using SM.Base.Textures; using SM.Base.Types; -using SM2D.Scene; -using SM2D.Types; + +#endregion namespace SM2D.Drawing { public class DrawTexture : DrawColor { public static float MasterScale = .25f; + public bool ManualSize = false; public float Scale = 1; - public bool ManualSize = false; - public Texture Texture + + public DrawTexture() { - get => (Texture) _material.Texture; - set => _material.Texture = value; } - public DrawTexture() {} - - protected DrawTexture(Color4 color) : base(color) { } + protected DrawTexture(Color4 color) : base(color) + { + } public DrawTexture(Bitmap map) : this(map, Color4.White) - { } + { + } - public DrawTexture(Bitmap map, Color4 color) : this((Texture)map, color) - { } + public DrawTexture(Bitmap map, Color4 color) : this((Texture) map, color) + { + } public DrawTexture(Texture texture, Color4 color) { @@ -38,9 +39,17 @@ namespace SM2D.Drawing _material.Tint = color; } + public Texture Texture + { + get => (Texture) _material.Texture; + set => _material.Texture = value; + } + protected override void DrawContext(ref DrawContext context) { - if (!ManualSize) Transform.Size = new CVector2(Texture.Map.Width * MasterScale * Scale, Texture.Map.Height * MasterScale * Scale); + if (!ManualSize) + Transform.Size = new CVector2(Texture.Map.Width * MasterScale * Scale, + Texture.Map.Height * MasterScale * Scale); base.DrawContext(ref context); } } diff --git a/SMCode/SM2D/GLWindow2D.cs b/SMCode/SM2D/GLWindow2D.cs index da64f07..834cd66 100644 --- a/SMCode/SM2D/GLWindow2D.cs +++ b/SMCode/SM2D/GLWindow2D.cs @@ -1,29 +1,31 @@ -using System; +#region usings + +using System; using OpenTK; using OpenTK.Graphics.OpenGL4; using OpenTK.Input; using SM.Base; -using SM.Base.Controls; using SM2D.Controls; using SM2D.Pipelines; using SM2D.Scene; using SM2D.Shader; -using Vector2 = OpenTK.Vector2; + +#endregion namespace SM2D { public class GLWindow2D : GenericWindow { - public Vector2? Scaling { get; set; } - public Vector2 WorldScale => _worldScale; - - public Mouse2D Mouse { get; } - public GLWindow2D() { Mouse = new Mouse2D(this); } + public Vector2? Scaling { get; set; } + public Vector2 WorldScale => _worldScale; + + public Mouse2D Mouse { get; } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -34,6 +36,8 @@ namespace SM2D protected override void OnLoaded() { base.OnLoaded(); + SMRenderer.DefaultMaterialShader = Default2DShader.MaterialShader; + SetRenderPipeline(new Basic2DPipeline()); } diff --git a/SMCode/SM2D/Object/Polygon.cs b/SMCode/SM2D/Object/Polygon.cs index 0077eb2..f6631ef 100644 --- a/SMCode/SM2D/Object/Polygon.cs +++ b/SMCode/SM2D/Object/Polygon.cs @@ -1,5 +1,6 @@ -using System; -using System.Collections; +#region usings + +using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; @@ -7,46 +8,40 @@ using OpenTK.Graphics.OpenGL4; using SM.Base.Objects; using SM.OGL.Mesh; +#endregion + namespace SM2D.Object { public class Polygon : Mesh { - public override VBO Vertex { get; } = new VBO(); - public override VBO UVs { get; } = new VBO(pointerSize:2); - public override VBO Color { get; } = new VBO(pointerSize: 4); - - public override PrimitiveType PrimitiveType { get; } = PrimitiveType.TriangleFan; - - - public Polygon(ICollection vertices) { - foreach (Vector2 vertex in vertices) + foreach (var vertex in vertices) { Color.Add(Color4.White); AddVertex(vertex); } - foreach (Vector2 vertex in vertices) - { - AddUV(vertex); - } + foreach (var vertex in vertices) AddUV(vertex); } public Polygon(ICollection vertices) { - foreach (PolygonVertex polygonVertex in vertices) + foreach (var polygonVertex in vertices) { Color.Add(polygonVertex.Color); AddVertex(polygonVertex.Vertex); } - foreach (PolygonVertex vertex in vertices) - { - AddUV(vertex.Vertex); - } + foreach (var vertex in vertices) AddUV(vertex.Vertex); } + public override VBO Vertex { get; } = new VBO(); + public override VBO UVs { get; } = new VBO(pointerSize: 2); + public override VBO Color { get; } = new VBO(pointerSize: 4); + + public override PrimitiveType PrimitiveType { get; } = PrimitiveType.TriangleFan; + private void AddVertex(Vector2 vertex) { BoundingBox.Update(vertex); @@ -55,18 +50,19 @@ namespace SM2D.Object private void AddUV(Vector2 vertex) { - Vector2 uv = Vector2.Divide(vertex, BoundingBox.Max.Xy) + BoundingBox.Min.Xy; + var uv = Vector2.Divide(vertex, BoundingBox.Max.Xy) + BoundingBox.Min.Xy; UVs.Add(uv); } public static Polygon GenerateCircle(int secments = 32) { - List vertices = new List() {Vector2.Zero}; + var vertices = new List {Vector2.Zero}; - float step = 360f / secments; - for (int i = 0; i < secments + 1; i++) + var step = 360f / secments; + for (var i = 0; i < secments + 1; i++) { - Vector2 vertex = new Vector2( 0.5f * (float)Math.Cos(step * i * Math.PI / 180f), 0.5f * (float)Math.Sin(step * i * Math.PI / 180f)); + var vertex = new Vector2(0.5f * (float) Math.Cos(step * i * Math.PI / 180f), + 0.5f * (float) Math.Sin(step * i * Math.PI / 180f)); vertices.Add(vertex); } diff --git a/SMCode/SM2D/Object/PolygonVertex.cs b/SMCode/SM2D/Object/PolygonVertex.cs index 77eb8e8..d43ca52 100644 --- a/SMCode/SM2D/Object/PolygonVertex.cs +++ b/SMCode/SM2D/Object/PolygonVertex.cs @@ -1,6 +1,10 @@ -using OpenTK; +#region usings + +using OpenTK; using OpenTK.Graphics; +#endregion + namespace SM2D.Object { public struct PolygonVertex diff --git a/SMCode/SM2D/Pipelines/Adv2DPipeline.cs b/SMCode/SM2D/Pipelines/Adv2DPipeline.cs index 47de7fc..306d42d 100644 --- a/SMCode/SM2D/Pipelines/Adv2DPipeline.cs +++ b/SMCode/SM2D/Pipelines/Adv2DPipeline.cs @@ -2,6 +2,5 @@ { public class Adv2DPipeline { - } } \ No newline at end of file diff --git a/SMCode/SM2D/Pipelines/Basic2DPipeline.cs b/SMCode/SM2D/Pipelines/Basic2DPipeline.cs index 5ff1d8a..a74b4f1 100644 --- a/SMCode/SM2D/Pipelines/Basic2DPipeline.cs +++ b/SMCode/SM2D/Pipelines/Basic2DPipeline.cs @@ -1,15 +1,18 @@ -using OpenTK.Graphics.OpenGL4; +#region usings + +using OpenTK.Graphics.OpenGL4; using SM.Base; using SM.Base.Contexts; using SM.Base.Scene; using SM.OGL.Framebuffer; using SM2D.Shader; +#endregion + namespace SM2D.Pipelines { public class Basic2DPipeline : RenderPipeline { - protected override IShader _defaultShader { get; } = Default2DShader.Shader; protected override void Render(ref DrawContext context, Scene.Scene scene) { diff --git a/SMCode/SM2D/Properties/AssemblyInfo.cs b/SMCode/SM2D/Properties/AssemblyInfo.cs index 23a061b..634ede6 100644 --- a/SMCode/SM2D/Properties/AssemblyInfo.cs +++ b/SMCode/SM2D/Properties/AssemblyInfo.cs @@ -1,16 +1,19 @@ -using System.Reflection; -using System.Runtime.CompilerServices; +#region usings + +using System.Reflection; using System.Runtime.InteropServices; +#endregion + // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("SM2D")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyTitle("SMRenderer for 2D-projects")] +[assembly: AssemblyDescription("Scene and Render system for 2D-projects")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyCompany("iedSoftworks")] [assembly: AssemblyProduct("SM2D")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2020")] +[assembly: AssemblyCopyright("Copyright © iedSoftworks 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -33,4 +36,4 @@ using System.Runtime.InteropServices; // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/SMCode/SM2D/SM2D.csproj b/SMCode/SM2D/SM2D.csproj index 29c4707..73e4c50 100644 --- a/SMCode/SM2D/SM2D.csproj +++ b/SMCode/SM2D/SM2D.csproj @@ -31,25 +31,21 @@ 4 - - ..\..\packages\OpenTK.3.2\lib\net20\OpenTK.dll + + ..\..\packages\OpenTK.3.2.1\lib\net20\OpenTK.dll - - - - - - + + @@ -76,11 +72,12 @@ - - - + + + + \ No newline at end of file diff --git a/SMCode/SM2D/Scene/Camera.cs b/SMCode/SM2D/Scene/Camera.cs index c5a4a12..e76c2a7 100644 --- a/SMCode/SM2D/Scene/Camera.cs +++ b/SMCode/SM2D/Scene/Camera.cs @@ -1,23 +1,27 @@ -using OpenTK; +#region usings + +using OpenTK; using SM.Base.Scene; using SM.Base.Types; +#endregion + namespace SM2D.Scene { public class Camera : GenericCamera { - public override bool Orthographic { get; } = true; - public CVector2 Position = new CVector2(0); + public override bool Orthographic { get; } = true; protected override Matrix4 ViewCalculation() { return Matrix4.LookAt(Position.X, Position.Y, 2, Position.X, Position.Y, 0, 0, 1, 0); } - public override void RecalculateWorld(OpenTK.Vector2 world, float aspect) + public override void RecalculateWorld(Vector2 world, float aspect) { - OrthographicWorld = Matrix4.CreateOrthographicOffCenter(-world.X / 2, world.X / 2, world.Y / 2, -world.Y / 2, 0.1f, 4f); + OrthographicWorld = + Matrix4.CreateOrthographicOffCenter(-world.X / 2, world.X / 2, world.Y / 2, -world.Y / 2, 0.1f, 4f); } } } \ No newline at end of file diff --git a/SMCode/SM2D/Scene/I2DShowItem.cs b/SMCode/SM2D/Scene/I2DShowItem.cs index 60b0f21..7e8a95c 100644 --- a/SMCode/SM2D/Scene/I2DShowItem.cs +++ b/SMCode/SM2D/Scene/I2DShowItem.cs @@ -1,10 +1,13 @@ -using SM.Base.Scene; +#region usings + +using SM.Base.Scene; + +#endregion namespace SM2D.Scene { public interface I2DShowItem : IShowItem { int ZIndex { get; set; } - } } \ No newline at end of file diff --git a/SMCode/SM2D/Scene/ItemCollection.cs b/SMCode/SM2D/Scene/ItemCollection.cs index 6dbb38e..5335ef6 100644 --- a/SMCode/SM2D/Scene/ItemCollection.cs +++ b/SMCode/SM2D/Scene/ItemCollection.cs @@ -1,8 +1,12 @@ -using SM.Base.Contexts; +#region usings + +using SM.Base.Contexts; using SM.Base.Scene; using SM.Base.Types; using SM2D.Types; +#endregion + namespace SM2D.Scene { public class ItemCollection : GenericItemCollection, I2DShowItem diff --git a/SMCode/SM2D/Scene/Scene.cs b/SMCode/SM2D/Scene/Scene.cs index 23bdc12..e195669 100644 --- a/SMCode/SM2D/Scene/Scene.cs +++ b/SMCode/SM2D/Scene/Scene.cs @@ -1,17 +1,20 @@ -using OpenTK.Graphics; -using SM.Base.Contexts; +#region usings + +using OpenTK.Graphics; using SM.Base.Scene; using SM2D.Drawing; +#endregion + namespace SM2D.Scene { public class Scene : GenericScene { - public DrawBackground Background => (DrawBackground)_Background; - public Scene() { _Background = new DrawBackground(Color4.Black); } + + public DrawBackground Background => (DrawBackground) _Background; } } \ No newline at end of file diff --git a/SMCode/SM2D/Shader/Default2DShader.cs b/SMCode/SM2D/Shader/Default2DShader.cs index 40e0def..ae4d0da 100644 --- a/SMCode/SM2D/Shader/Default2DShader.cs +++ b/SMCode/SM2D/Shader/Default2DShader.cs @@ -1,14 +1,18 @@ -using OpenTK.Graphics.OpenGL4; +#region usings + +using OpenTK.Graphics.OpenGL4; using SM.Base.Contexts; using SM.Base.Scene; using SM.OGL.Shaders; using SM.Utility; +#endregion + namespace SM2D.Shader { - public class Default2DShader : GenericShader, IShader + public class Default2DShader : MaterialShader { - public static Default2DShader Shader = new Default2DShader(); + public static Default2DShader MaterialShader = new Default2DShader(); //protected override bool AutoCompile { get; } = true; @@ -18,32 +22,31 @@ namespace SM2D.Shader { Load(); } - public void Draw(DrawContext context) + + protected override void DrawProcess(DrawContext context) { - GL.UseProgram(this); - - GL.BindVertexArray(context.Mesh); - // Vertex Uniforms Uniforms["MVP"].SetMatrix4(context.ModelMaster * context.View * context.World); - Uniforms["HasVColor"].SetUniform1(context.Mesh.AttribDataIndex.ContainsKey(3) && context.Mesh.AttribDataIndex[3] != null); + Uniforms["HasVColor"] + .SetUniform1(context.Mesh.AttribDataIndex.ContainsKey(3) && context.Mesh.AttribDataIndex[3] != null); - for (int i = 0; i < context.Instances.Length; i++) + Uniforms.GetArray("Instances").Set((i, uniforms) => { - GL.UniformMatrix4(Uniforms["ModelMatrix"] + i, false, ref context.Instances[i].ModelMatrix); - GL.Uniform2(Uniforms["TextureOffset"] + i, context.Instances[i].TexturePosition); - GL.Uniform2(Uniforms["TextureScale"] + i, context.Instances[i].TextureScale); - } + if (i >= context.Instances.Length) return false; + + var instance = context.Instances[i]; + uniforms["ModelMatrix"].SetMatrix4(instance.ModelMatrix); + uniforms["TextureOffset"].SetUniform2(instance.TexturePosition); + uniforms["TextureScale"].SetUniform2(instance.TextureScale); + + return true; + }); // Fragment Uniforms Uniforms["Tint"].SetUniform4(context.Material.Tint); Uniforms["Texture"].SetTexture(context.Material.Texture, Uniforms["UseTexture"]); DrawObject(context.Mesh, context.Instances.Length); - - CleanUp(); - - GL.UseProgram(0); } } } \ No newline at end of file diff --git a/SMCode/SM2D/Shader/ShaderFiles/default.vert b/SMCode/SM2D/Shader/ShaderFiles/default.vert index 8923148..22bc148 100644 --- a/SMCode/SM2D/Shader/ShaderFiles/default.vert +++ b/SMCode/SM2D/Shader/ShaderFiles/default.vert @@ -1,23 +1,12 @@ #version 330 -#define maxInstances 32 -layout(location = 0) in vec3 aPos; -layout(location = 1) in vec2 aTex; -layout(location = 3) in vec4 aColor; -uniform mat4 MVP; -uniform bool HasVColor; -uniform mat4 ModelMatrix[maxInstances]; -uniform vec2 TextureOffset[maxInstances]; -uniform vec2 TextureScale[maxInstances]; - -out vec2 vTexture; -out vec4 vColor; +//# import SM_base_vertex_basic +void ApplyTexModifier(); +void CheckVertexColor(); +void ApplyModelTransformation(); void main() { - vTexture = aTex * TextureScale[gl_InstanceID] + TextureOffset[gl_InstanceID]; - - if (HasVColor) vColor = aColor; - else vColor = vec4(1); - - gl_Position = MVP * ModelMatrix[gl_InstanceID] * vec4(aPos, 1); + ApplyTexModifier(); + CheckVertexColor(); + ApplyModelTransformation(); } \ No newline at end of file diff --git a/SMCode/SM2D/Types/Transformation.cs b/SMCode/SM2D/Types/Transformation.cs index bd1005a..fbfd066 100644 --- a/SMCode/SM2D/Types/Transformation.cs +++ b/SMCode/SM2D/Types/Transformation.cs @@ -1,52 +1,39 @@ -using System; -using System.Configuration.Assemblies; +#region usings + using OpenTK; using SM.Base.Scene; using SM.Base.Types; using SM.Utility; +#endregion + namespace SM2D.Types { public class Transformation : GenericTransformation { - private float _eulerRotation = 0; - private CVector2 _position = new CVector2(0); - private CVector2 _scale = new CVector2(50); + public CVector2 Position { get; set; } = new CVector2(0); - public CVector2 Position - { - get => _position; - set => _position = value; - } + public CVector2 Size { get; set; } = new CVector2(50); - public CVector2 Size - { - get => _scale; - set => _scale = value; - } - public float Rotation - { - get => _eulerRotation; - set => _eulerRotation = value; - } + public float Rotation { get; set; } protected override Matrix4 RequestMatrix() { - return Matrix4.CreateScale(_scale.X, _scale.Y, 1) * - Matrix4.CreateRotationZ(MathHelper.DegreesToRadians(_eulerRotation)) * - Matrix4.CreateTranslation(_position.X, _position.Y, 0); + return Matrix4.CreateScale(Size.X, Size.Y, 1) * + Matrix4.CreateRotationZ(MathHelper.DegreesToRadians(Rotation)) * + Matrix4.CreateTranslation(Position.X, Position.Y, 0); } public void TurnTo(Vector2 v) { - _eulerRotation = RotationUtility.TurnTowards(Position, v); + Rotation = RotationUtility.TurnTowards(Position, v); } public Vector2 LookAtVector() { if (_modelMatrix.Determinant < 0.0001) return new Vector2(0); - Vector3 vec = Vector3.TransformNormal(Vector3.UnitX, _modelMatrix); + var vec = Vector3.TransformNormal(Vector3.UnitX, _modelMatrix); vec.Normalize(); return vec.Xy; } diff --git a/SMCode/SM2D/packages.config b/SMCode/SM2D/packages.config index 75397e4..9a4debe 100644 --- a/SMCode/SM2D/packages.config +++ b/SMCode/SM2D/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/SMCode/SM3D/Properties/AssemblyInfo.cs b/SMCode/SM3D/Properties/AssemblyInfo.cs index 7390e89..f2e6bad 100644 --- a/SMCode/SM3D/Properties/AssemblyInfo.cs +++ b/SMCode/SM3D/Properties/AssemblyInfo.cs @@ -1,7 +1,10 @@ -using System.Reflection; -using System.Runtime.CompilerServices; +#region usings + +using System.Reflection; using System.Runtime.InteropServices; +#endregion + // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. @@ -33,4 +36,4 @@ using System.Runtime.InteropServices; // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/SMCode/SM3D/SM3D.csproj b/SMCode/SM3D/SM3D.csproj index b36bcbd..447701a 100644 --- a/SMCode/SM3D/SM3D.csproj +++ b/SMCode/SM3D/SM3D.csproj @@ -33,12 +33,6 @@ - - - - - - diff --git a/SM_TEST/Program.cs b/SM_TEST/Program.cs index 1d3b16a..d732f17 100644 --- a/SM_TEST/Program.cs +++ b/SM_TEST/Program.cs @@ -45,16 +45,10 @@ namespace SM_TEST Vector2 mousepos = window.Mouse.InWorld(); //polyogn.Transform.Position.Set(mousepos); polyogn.Transform.TurnTo(mousepos); - - Log.Write(LogType.Info, polyogn.Transform.LookAtVector()); } private static void WindowOnLoad(object sender, EventArgs e) { - Interval timer = new Interval(5); - timer.EndAction += (timer1, context) => Console.WriteLine("Interval..."); - timer.Start(); - col = new ItemCollection() { Transform = { Position = new SM.Base.Types.CVector2(0, 400) }, diff --git a/SM_TEST/SM_TEST.csproj b/SM_TEST/SM_TEST.csproj index ba34341..bbf8af9 100644 --- a/SM_TEST/SM_TEST.csproj +++ b/SM_TEST/SM_TEST.csproj @@ -33,8 +33,8 @@ 4 - - ..\packages\OpenTK.3.2\lib\net20\OpenTK.dll + + ..\packages\OpenTK.3.2.1\lib\net20\OpenTK.dll diff --git a/SM_TEST/packages.config b/SM_TEST/packages.config index 75397e4..9a4debe 100644 --- a/SM_TEST/packages.config +++ b/SM_TEST/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file