Compare commits

..

No commits in common. "687125cc3e9b844e91552ec919bd9425966089d9" and "be07a1bfb6903da874e8f3f8af60e5d568c5e8e0" have entirely different histories.

205 changed files with 2142 additions and 3328 deletions

View file

@ -1,8 +0,0 @@
# SMRendererV3
A performant and simple to use OpenGL-renderer.
It allows you to extend/changing the renderer as you wish, without changing the source file.
## Installation
The distribution happens over the NuGet.org.
You should be able to find the SMRenderer**2D** over your Nuget Package Manager.

View file

@ -18,20 +18,10 @@ namespace SM.Base.Controls
private static MouseState? _mouseState; private static MouseState? _mouseState;
private static List<MouseButton> _lastButtonsPressed = new List<MouseButton>(); private static List<MouseButton> _lastButtonsPressed = new List<MouseButton>();
private static Vector2 _inScreen;
/// <summary> /// <summary>
/// Gets or sets the current position of the mouse in the screen. /// The current position of the mouse in the screen.
/// </summary> /// </summary>
public static Vector2 InScreen public static Vector2 InScreen { get; private set; }
{
get => _inScreen;
set
{
_inScreen = value;
UpdateNormalized(SMRenderer.CurrentWindow);
}
}
/// <summary> /// <summary>
/// The current position of the mouse in the screen from 0..1. /// The current position of the mouse in the screen from 0..1.
@ -50,16 +40,6 @@ namespace SM.Base.Controls
/// </summary> /// </summary>
public static bool RightClick => IsDown(MouseButton.Right, true); public static bool RightClick => IsDown(MouseButton.Right, true);
/// <summary>
/// If true, it disables the tracking of the mouse, allowing you to change the <see cref="InScreen"/> value, without the system replacing it again.
/// </summary>
public static bool StopTracking { get; set; }
private static void UpdateNormalized(IGenericWindow window)
{
InScreenNormalized = new Vector2(_inScreen.X / (float)window.Width, _inScreen.Y / (float)window.Height);
}
/// <summary> /// <summary>
/// The event to update the values. /// The event to update the values.
/// </summary> /// </summary>
@ -67,10 +47,8 @@ namespace SM.Base.Controls
/// <param name="window">The window where the mouse is checked</param> /// <param name="window">The window where the mouse is checked</param>
internal static void MouseMoveEvent(MouseMoveEventArgs mmea, IGenericWindow window) internal static void MouseMoveEvent(MouseMoveEventArgs mmea, IGenericWindow window)
{ {
if (StopTracking) return;
InScreen = new Vector2(mmea.X, mmea.Y); InScreen = new Vector2(mmea.X, mmea.Y);
UpdateNormalized(window); InScreenNormalized = new Vector2(mmea.X / (float) window.Width, mmea.Y / (float) window.Height);
} }
internal static void SetState() internal static void SetState()

View file

@ -39,16 +39,9 @@ namespace SM.Base.Drawing
/// <summary> /// <summary>
/// Returns the current model matrix. /// Returns the current model matrix.
/// </summary> /// </summary>
/// <param name="force">If set to true, it will always (re-)calculate the model matrix.</param>
/// <returns></returns> /// <returns></returns>
public Matrix4 GetMatrix(bool force = false) public Matrix4 GetMatrix()
{ {
if (force)
{
_lastFrame = SMRenderer.CurrentFrame;
return _modelMatrix = RequestMatrix();
}
if (Ignore) return Matrix4.Identity; if (Ignore) return Matrix4.Identity;
if (_lastFrame != SMRenderer.CurrentFrame) if (_lastFrame != SMRenderer.CurrentFrame)

View file

@ -2,7 +2,6 @@
using OpenTK.Graphics; using OpenTK.Graphics;
using SM.Base.Shaders; using SM.Base.Shaders;
using SM.Base.Window;
using SM.OGL.Texture; using SM.OGL.Texture;
#endregion #endregion
@ -17,35 +16,26 @@ namespace SM.Base.Drawing
/// <summary> /// <summary>
/// A setting to enable Blending. /// A setting to enable Blending.
/// </summary> /// </summary>
public virtual bool Blending { get; set; } = false; public bool Blending = false;
/// <summary> /// <summary>
/// A custom shader, that is used to draw this material. /// A custom shader, that is used to draw this material.
/// </summary> /// </summary>
public virtual MaterialShader CustomShader { get; set; } public MaterialShader CustomShader;
/// <summary> /// <summary>
/// The base texture. (aka. Diffuse Texture) /// The base texture. (aka. Diffuse Texture)
/// </summary> /// </summary>
public virtual TextureBase Texture { get; set; } public TextureBase Texture;
/// <summary> /// <summary>
/// The tint or color. /// The tint or color.
/// </summary> /// </summary>
public virtual Color4 Tint { get; set; } = Color4.White; public Color4 Tint = Color4.White;
/// <summary> /// <summary>
/// This allows custom shaders to use own shader arguments. /// This allows custom shaders to use own shader arguments.
/// </summary> /// </summary>
public ShaderArguments ShaderArguments { get; internal set; } = new ShaderArguments(); public ShaderArguments ShaderArguments { get; internal set; } = new ShaderArguments();
/// <summary>
/// Draws the material with the provided context.
/// </summary>
/// <param name="context"></param>
public virtual void Draw(DrawContext context)
{
context.Shader.Draw(context);
}
} }
} }

View file

@ -0,0 +1,24 @@
#region usings
using SM.Base.Time;
#endregion
namespace SM.Base.Drawing.Particles
{
/// <summary>
/// A context, with that the particle system sends the information for the movement function.
/// </summary>
public struct ParticleContext
{
/// <summary>
/// The Timer of the particles
/// </summary>
public Timer Timer;
/// <summary>
/// The current speed of the particles.
/// </summary>
public float Speed;
}
}

View file

@ -0,0 +1,139 @@
#region usings
using System;
using System.Collections.Generic;
using OpenTK;
using SM.Base.Scene;
using SM.Base.Time;
using SM.Base.Window;
#endregion
namespace SM.Base.Drawing.Particles
{
/// <summary>
/// The (drawing) basis for particles
/// </summary>
public abstract class ParticleDrawingBasis<TTransform, TDirection> : DrawingBasis<TTransform>, IScriptable
where TTransform : GenericTransformation, new()
where TDirection : struct
{
/// <summary>
/// The amount of particles
/// </summary>
public int Amount = 32;
/// <summary>
/// This contains the different instances for the particles.
/// </summary>
protected List<Instance> instances;
/// <summary>
/// The maximum speed of the particles
/// </summary>
public float MaxSpeed = 50;
/// <summary>
/// This contains all important information for each particle.
/// </summary>
protected ParticleStruct<TDirection>[] particleStructs;
/// <summary>
/// The stopwatch of the particles.
/// </summary>
protected Timer timer;
/// <summary>
/// Sets up the timer.
/// </summary>
/// <param name="duration">Duration how long the particles should live</param>
protected ParticleDrawingBasis(TimeSpan duration)
{
timer = new Timer(duration);
}
/// <summary>
/// Get/Sets the state of pausing.
/// </summary>
public bool Paused
{
get => timer.Paused;
set => timer.Paused = value;
}
/// <summary>
/// Controls the movement of each particles.
/// </summary>
public abstract Func<TDirection, ParticleContext, TDirection> MovementCalculation { get; set; }
/// <inheritdoc />
public bool UpdateActive {
get => timer.Active;
set { return; }
}
/// <inheritdoc />
public void Update(UpdateContext context)
{
ParticleContext particleContext = new ParticleContext
{
Timer = timer
};
for (int i = 0; i < Amount; i++)
{
particleContext.Speed = particleStructs[i].Speed;
instances[i].ModelMatrix = CreateMatrix(particleStructs[i],
MovementCalculation(particleStructs[i].Direction, particleContext));
}
}
/// <summary>
/// Triggers the particles.
/// </summary>
public void Trigger()
{
timer.Start();
CreateParticles();
}
/// <inheritdoc />
protected override void DrawContext(ref DrawContext context)
{
if (!timer.Active) return;
base.DrawContext(ref context);
context.Instances = instances;
context.Shader.Draw(context);
}
/// <summary>
/// Creates the particles.
/// </summary>
protected virtual void CreateParticles()
{
particleStructs = new ParticleStruct<TDirection>[Amount];
instances = new List<Instance>();
for (int i = 0; i < Amount; i++)
{
particleStructs[i] = CreateObject(i);
instances.Add(new Instance());
}
}
/// <summary>
/// Creates a particle.
/// </summary>
protected abstract ParticleStruct<TDirection> CreateObject(int index);
/// <summary>
/// Generates the desired matrix for drawing.
/// </summary>
protected abstract Matrix4 CreateMatrix(ParticleStruct<TDirection> Struct, TDirection relativePosition);
}
}

View file

@ -14,17 +14,17 @@ namespace SM.Base.Drawing.Particles
/// <summary> /// <summary>
/// Default movement for 2D. /// Default movement for 2D.
/// </summary> /// </summary>
public static Vector2 Default2D(ParticleInstance<Vector2> particle) public static Vector2 Default2D(Vector2 direction, ParticleContext context)
{ {
return particle.Direction * ((particle.StartLifetime - particle.Lifetime) * particle.Speed); return direction * (context.Timer.Elapsed * context.Speed);
} }
/// <summary> /// <summary>
/// Default movement for 3D. /// Default movement for 3D.
/// </summary> /// </summary>
public static Vector3 Default3D(ParticleInstance<Vector3> particle) public static Vector3 Default3D(Vector3 direction, ParticleContext context)
{ {
return particle.Direction * ((particle.StartLifetime - particle.Lifetime) * particle.Speed); return direction * (context.Timer.Elapsed * context.Speed);
} }
} }
} }

View file

@ -0,0 +1,30 @@
#region usings
using OpenTK;
#endregion
namespace SM.Base.Drawing.Particles
{
/// <summary>
/// A particle...
/// </summary>
public struct ParticleStruct<TDirection>
where TDirection : struct
{
/// <summary>
/// A direction, that the particle should travel.
/// </summary>
public TDirection Direction;
/// <summary>
/// A matrix to store rotation and scale.
/// </summary>
public Matrix4 Matrix;
/// <summary>
/// Speeeeeeeeeed
/// </summary>
public float Speed;
}
}

View file

@ -40,12 +40,6 @@ namespace SM.Base.Drawing.Text
/// </summary> /// </summary>
public float FontSize { get; set; } = 12; public float FontSize { get; set; } = 12;
/// <summary>
/// Allows to adjust the baseline to fix clipping issues.
/// <para>Due to some issues with the calculations, this is a temporary fix.</para>
/// </summary>
public float BaselineAdjust { get; set; } = 1f;
/// <summary> /// <summary>
/// The character positions. /// The character positions.
/// </summary> /// </summary>
@ -70,8 +64,6 @@ namespace SM.Base.Drawing.Text
public void RegenerateTexture() public void RegenerateTexture()
{ {
Width = Height = 0; Width = Height = 0;
//Height = Math.Abs(_fontFace.BBox.Bottom) + _fontFace.BBox.Top;
Positions = new Dictionary<char, CharParameter>(); Positions = new Dictionary<char, CharParameter>();
_fontFace.SetCharSize(0, FontSize, 0, 96); _fontFace.SetCharSize(0, FontSize, 0, 96);
@ -91,7 +83,7 @@ namespace SM.Base.Drawing.Text
float bBoxHeight = (Math.Abs(_fontFace.BBox.Bottom) + _fontFace.BBox.Top); float bBoxHeight = (Math.Abs(_fontFace.BBox.Bottom) + _fontFace.BBox.Top);
float bBoxTopScale = _fontFace.BBox.Top / bBoxHeight; float bBoxTopScale = _fontFace.BBox.Top / bBoxHeight;
float baseline = (Height * bBoxTopScale) + BaselineAdjust; float baseline = Height * bBoxTopScale + 1;
Map = new Bitmap(Width, Height); Map = new Bitmap(Width, Height);
using (Graphics g = Graphics.FromImage(Map)) using (Graphics g = Graphics.FromImage(Map))
@ -103,7 +95,8 @@ namespace SM.Base.Drawing.Text
{ {
_fontFace.LoadChar(keyvalue.Key, LoadFlags.Render, LoadTarget.Normal); _fontFace.LoadChar(keyvalue.Key, LoadFlags.Render, LoadTarget.Normal);
int y = ((int)baseline - (int) _fontFace.Glyph.Metrics.HorizontalBearingY); int y = ((int)baseline - (int)_fontFace.Glyph.Metrics.HorizontalBearingY);
g.DrawImageUnscaled(_fontFace.Glyph.Bitmap.ToGdipBitmap(Color.White), (int)keyvalue.Value[1], y); g.DrawImageUnscaled(_fontFace.Glyph.Bitmap.ToGdipBitmap(Color.White), (int)keyvalue.Value[1], y);
Vector2 offset = new Vector2(keyvalue.Value[1] / Width, 0); Vector2 offset = new Vector2(keyvalue.Value[1] / Width, 0);

View file

@ -1,8 +1,6 @@
#region usings #region usings
using System; using System;
using System.Collections.Generic;
using System.Linq;
using OpenTK; using OpenTK;
using OpenTK.Graphics; using OpenTK.Graphics;
using SM.Base.Objects.Static; using SM.Base.Objects.Static;
@ -132,13 +130,9 @@ namespace SM.Base.Drawing.Text
{ {
if (!Font.WasCompiled) Font.RegenerateTexture(); if (!Font.WasCompiled) Font.RegenerateTexture();
if (string.IsNullOrEmpty(_text)) return;
_text = _text.Replace("\r\n", "\n").Replace("\t", " "); _text = _text.Replace("\r\n", "\n").Replace("\t", " ");
_instances = new Instance[_text.Length]; _instances = new Instance[_text.Length];
List<Tuple<Vector2, Instance[]>> lines = new List<Tuple<Vector2, Instance[]>>();
List<Instance> currentLineInstances = new List<Instance>();
float x = 0; float x = 0;
float y = 0; float y = 0;
@ -152,13 +146,8 @@ namespace SM.Base.Drawing.Text
if (_text[i] == '\n') if (_text[i] == '\n')
{ {
if (currentLineInstances.Count > 0)
{
lines.Add(new Tuple<Vector2, Instance[]>(new Vector2(x, y), currentLineInstances.ToArray()));
currentLineInstances.Clear();
}
y += Font.Height; y += Font.Height;
Width = Math.Max(Width, x);
x = 0; x = 0;
continue; continue;
} }
@ -181,42 +170,33 @@ namespace SM.Base.Drawing.Text
var matrix = Matrix4.CreateScale(parameter.Width, Font.Height, 1) * var matrix = Matrix4.CreateScale(parameter.Width, Font.Height, 1) *
Matrix4.CreateTranslation(x + parameter.Width / 2, -y, 0); Matrix4.CreateTranslation(x + parameter.Width / 2, -y, 0);
currentLineInstances.Add(_instances[i] = new Instance _instances[i] = new Instance
{ {
ModelMatrix = matrix, ModelMatrix = matrix,
TextureMatrix = parameter.TextureMatrix TextureMatrix = parameter.TextureMatrix
}); };
x += parameter.Advance; x += parameter.Advance;
} }
if (currentLineInstances.Count > 0)
lines.Add(new Tuple<Vector2, Instance[]>(new Vector2(x, y), currentLineInstances.ToArray()));
Height = y + Font.Height; Height = y + Font.Height;
Width = lines.Max(a => a.Item1.X); Width = x;
if (Origin != TextOrigin.Left) if (Origin != TextOrigin.Left)
{ {
foreach (Tuple<Vector2, Instance[]> line in lines) foreach (Instance i in _instances)
{
foreach (Instance i in line.Item2)
{ {
if (i == null) continue; if (i == null) continue;
switch (Origin) switch (Origin)
{ {
case TextOrigin.Center: case TextOrigin.Center:
i.ModelMatrix *= Matrix4.CreateTranslation(-line.Item1.X / 2, 0, 0); i.ModelMatrix *= Matrix4.CreateTranslation(-Width / 2, 0, 0);
break; break;
case TextOrigin.Right: case TextOrigin.Right:
i.ModelMatrix *= Matrix4.CreateTranslation(-line.Item1.X, 0, 0); i.ModelMatrix *= Matrix4.CreateTranslation(-Width, 0, 0);
break; break;
} }
} }
} }
}
} }
} }
} }

View file

@ -0,0 +1,144 @@
#region usings
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using OpenTK.Graphics.OpenGL4;
using SM.Base.Textures;
#endregion
namespace SM.Base.Drawing.Text
{
/// <summary>
/// Represents a font.
/// </summary>
public class Font : Texture
{
/// <summary>
/// The char set for the font.
/// <para>Default: <see cref="FontCharStorage.SimpleUTF8" /></para>
/// </summary>
public ICollection<char> CharSet = FontCharStorage.SimpleUTF8;
/// <summary>
/// The font family, that is used to find the right font.
/// </summary>
public FontFamily FontFamily;
/// <summary>
/// The font size.
/// <para>Default: 12</para>
/// </summary>
public float FontSize = 12;
public float SpaceWidth { get; private set; }
public float Spacing = 1;
/// <summary>
/// The font style.
/// <para>Default: <see cref="System.Drawing.FontStyle.Regular" /></para>
/// </summary>
public FontStyle FontStyle = FontStyle.Regular;
/// <summary>
/// This contains all information for the different font character.
/// </summary>
public Dictionary<char, CharParameter> Positions = new Dictionary<char, CharParameter>();
/// <summary>
/// Generates a font from a font family from the specified path.
/// </summary>
/// <param name="path">The specified path</param>
public Font(string path)
{
var pfc = new PrivateFontCollection();
pfc.AddFontFile(path);
FontFamily = pfc.Families[0];
}
/// <summary>
/// Generates a font from a specified font family.
/// </summary>
/// <param name="font">Font-Family</param>
public Font(FontFamily font)
{
FontFamily = font;
}
/// <inheritdoc />
public override TextureWrapMode WrapMode { get; set; } = TextureWrapMode.ClampToEdge;
/// <summary>
/// Regenerates the texture.
/// </summary>
public void RegenerateTexture()
{
Width = 0;
Height = 0;
Positions = new Dictionary<char, CharParameter>();
var map = new Bitmap(1000, 20);
var charParams = new Dictionary<char, float[]>();
using (var f = new System.Drawing.Font(FontFamily, FontSize, FontStyle))
{
using (var g = Graphics.FromImage(map))
{
g.Clear(Color.Transparent);
foreach (var c in CharSet)
{
var s = c.ToString();
var size = g.MeasureString(s, f, 0, StringFormat.GenericTypographic);
try
{
charParams.Add(c, new[] {size.Width, Width});
}
catch
{
// ignored
}
if (Height < size.Height) Height = (int) size.Height;
Width += (int) size.Width + 1;
}
SpaceWidth = g.MeasureString("_", f, 0, StringFormat.GenericTypographic).Width;
}
map = new Bitmap(Width, Height);
using (var g = Graphics.FromImage(map))
{
foreach (var keyValuePair in charParams)
{
var normalizedX = (keyValuePair.Value[1]+ 0.00001f) / Width;
var normalizedWidth = keyValuePair.Value[0] / Width;
CharParameter parameter;
Positions.Add(keyValuePair.Key, parameter = new CharParameter
{
NormalizedWidth = normalizedWidth,
NormalizedX = normalizedX,
Width = keyValuePair.Value[0],
X = (int) keyValuePair.Value[1]
});
g.DrawString(keyValuePair.Key.ToString(), f, Brushes.White, parameter.X, 0, StringFormat.GenericTypographic);
}
}
}
Map = map;
Recompile();
}
/// <inheritdoc />
public override void Compile()
{
RegenerateTexture();
base.Compile();
}
}
}

View file

@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Reflection;
using System.Windows.Forms; using System.Windows.Forms;
using OpenTK.Graphics.OpenGL4; using OpenTK.Graphics.OpenGL4;
using SM.OGL; using SM.OGL;
@ -83,14 +82,14 @@ namespace SM.Base
/// <summary> /// <summary>
/// Presets for the log targets. /// Presets for the log targets.
/// </summary> /// </summary>
public static Dictionary<LogTarget, string> Preset = new Dictionary<LogTarget, string>() public static Dictionary<LogTarget, string> Preset = new()
{ {
{LogTarget.Console, "[%type%] %msg%"}, {LogTarget.Console, "[%type%] %msg%"},
{LogTarget.Debugger, "[%type%] %msg%"}, {LogTarget.Debugger, "[%type%] %msg%"},
{LogTarget.File, "<%date%, %time%> [%type%] %msg%"} {LogTarget.File, "<%date%, %time%> [%type%] %msg%"}
}; };
private static readonly Dictionary<LogType, ConsoleColor> Colors = new Dictionary<LogType, ConsoleColor>() private static readonly Dictionary<LogType, ConsoleColor> Colors = new()
{ {
{LogType.Info, ConsoleColor.Green}, {LogType.Info, ConsoleColor.Green},
{LogType.Warning, ConsoleColor.Yellow}, {LogType.Warning, ConsoleColor.Yellow},
@ -146,10 +145,7 @@ namespace SM.Base
{ {
if (_init) return; if (_init) return;
if (!Debugger.IsAttached)
{
AppDomain.CurrentDomain.UnhandledException += ExceptionHandler; AppDomain.CurrentDomain.UnhandledException += ExceptionHandler;
}
AppDomain.CurrentDomain.DomainUnload += (sender, args) => AppDomain.CurrentDomain.DomainUnload += (sender, args) =>
{ {
_logStream.WriteLine("Unload application"); _logStream.WriteLine("Unload application");
@ -176,12 +172,9 @@ namespace SM.Base
Write(e.IsTerminating ? "Terminating Error" : LogType.Error.ToString(), Write(e.IsTerminating ? "Terminating Error" : LogType.Error.ToString(),
e.IsTerminating ? ConsoleColor.DarkRed : ConsoleColor.Red, e.ExceptionObject); e.IsTerminating ? ConsoleColor.DarkRed : ConsoleColor.Red, e.ExceptionObject);
MethodBase info = (e.ExceptionObject as Exception).TargetSite;
string name = $"{info.ReflectedType.Namespace}.{info.ReflectedType.Name}.{info.Name}".Replace(".", "::");
if (e.IsTerminating) if (e.IsTerminating)
{ {
MessageBox.Show($"Critical error occured at {name}.\n\n{e.ExceptionObject}", MessageBox.Show($"Critical error occured.\n\n{e.ExceptionObject}",
$"Terminating Error: {e.ExceptionObject.GetType().Name}"); $"Terminating Error: {e.ExceptionObject.GetType().Name}");
_logStream?.Close(); _logStream?.Close();
} }

View file

@ -1,7 +1,5 @@
#region usings #region usings
using System;
using System.Drawing;
using OpenTK; using OpenTK;
using OpenTK.Graphics.OpenGL4; using OpenTK.Graphics.OpenGL4;
using SM.Base.Drawing; using SM.Base.Drawing;
@ -9,31 +7,28 @@ using SM.Base.PostProcess;
using SM.Base.Utility; using SM.Base.Utility;
using SM.Base.Window; using SM.Base.Window;
using SM.OGL.Framebuffer; using SM.OGL.Framebuffer;
using SM.OGL.Shaders;
using SM.OGL.Texture; using SM.OGL.Texture;
#endregion #endregion
namespace SM.Base.Legacy.PostProcessing namespace SM.Base.PostEffects
{ {
/// <summary> /// <summary>
/// A bloom post process effect. /// A bloom post process effect.
/// </summary> /// </summary>
[Obsolete("This bloom effect isn't good. Please use SM.Base.PostEffects.BloomEffect, if you want a good bloom effect.")] public class BloomEffect : PostProcessEffect
public class BloomEffectOld : PostProcessEffect
{ {
private static BezierCurve _defaultCurve = new BezierCurve(Vector2.UnitY, Vector2.Zero, new Vector2(0.4f, 0), new Vector2(.5f,0)); private static BezierCurve _defaultCurve = new BezierCurve(Vector2.UnitY, Vector2.Zero, new Vector2(0.4f, 0), new Vector2(.5f,0));
private static readonly PostProcessShader _mergeShader = new PostProcessShader( private static readonly PostProcessShader _mergeShader = new PostProcessShader(
new ShaderFile(AssemblyUtility.ReadAssemblyFile("SM.Base.Legacy.PostProcessing.bloom_merge.vert")), AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom_merge_vert.glsl"),
AssemblyUtility.ReadAssemblyFile("SM.Base.Legacy.PostProcessing.bloom_merge.glsl")); AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom_merge.glsl"));
private static readonly PostProcessShader _shader = private static readonly PostProcessShader _shader =
new PostProcessShader(AssemblyUtility.ReadAssemblyFile("SM.Base.Legacy.PostProcessing.bloom_blur.glsl")); new PostProcessShader(AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".bloom_blur.glsl"));
private const float _defaultTextureScale = .75f; private const float _defaultTextureScale = .75f;
private Framebuffer _source; private Framebuffer _source;
private Framebuffer _tempColorBuffer;
private Framebuffer _bloomBuffer1; private Framebuffer _bloomBuffer1;
private Framebuffer _bloomBuffer2; private Framebuffer _bloomBuffer2;
@ -88,6 +83,12 @@ namespace SM.Base.Legacy.PostProcessing
/// </summary> /// </summary>
public float Radius = 1; public float Radius = 1;
/// <summary>
/// This can disable the bloom calculation.
/// <para>Default: true</para>
/// </summary>
public bool Enable = true;
/// <summary> /// <summary>
/// This defines the weight curve. /// This defines the weight curve.
/// </summary> /// </summary>
@ -100,7 +101,6 @@ namespace SM.Base.Legacy.PostProcessing
UpdateWeights(); UpdateWeights();
} }
} }
/// <summary> /// <summary>
/// This defines how many picks the effect should pick from the weight curve. /// This defines how many picks the effect should pick from the weight curve.
/// </summary> /// </summary>
@ -112,7 +112,7 @@ namespace SM.Base.Legacy.PostProcessing
/// <param name="source">This can specify a own source framebuffer. If not set, it will take the Pipeline MainFramebuffer.</param> /// <param name="source">This can specify a own source framebuffer. If not set, it will take the Pipeline MainFramebuffer.</param>
/// <param name="hdr">This allows to enable hdr returns.</param> /// <param name="hdr">This allows to enable hdr returns.</param>
/// <param name="textureScale">This allows for a increase in performance, by lowering the calculating texture scale.</param> /// <param name="textureScale">This allows for a increase in performance, by lowering the calculating texture scale.</param>
public BloomEffectOld(Framebuffer source = null, bool hdr = false, float? textureScale = null) public BloomEffect(Framebuffer source = null, bool hdr = false, float? textureScale = null)
{ {
_source = source; _source = source;
_hdr = hdr; _hdr = hdr;
@ -137,10 +137,6 @@ namespace SM.Base.Legacy.PostProcessing
_source.ColorAttachments["color"].PixelInformation = PixelInformation.RGBA_HDR; _source.ColorAttachments["color"].PixelInformation = PixelInformation.RGBA_HDR;
_tempColorBuffer = new Framebuffer(Pipeline.ConnectedWindow, 1);
_tempColorBuffer.Append("color", new ColorAttachment(0, PixelInformation.RGBA_HDR));
_tempColorBuffer.Compile();
_bloomBuffer1 = new Framebuffer(Pipeline.ConnectedWindow, _textureScale) _bloomBuffer1 = new Framebuffer(Pipeline.ConnectedWindow, _textureScale)
{ {
Name = "BloomX" Name = "BloomX"
@ -154,21 +150,19 @@ namespace SM.Base.Legacy.PostProcessing
_bloomBuffer2.Append("yBuffer", _yBuffer = new ColorAttachment(0, PixelInformation.RGBA_HDR)); _bloomBuffer2.Append("yBuffer", _yBuffer = new ColorAttachment(0, PixelInformation.RGBA_HDR));
_bloomBuffer2.Compile(); _bloomBuffer2.Compile();
Pipeline.Framebuffers.Add(_tempColorBuffer);
Pipeline.Framebuffers.Add(_bloomBuffer1); Pipeline.Framebuffers.Add(_bloomBuffer1);
Pipeline.Framebuffers.Add(_bloomBuffer2); Pipeline.Framebuffers.Add(_bloomBuffer2);
} }
/// <inheritdoc/> /// <inheritdoc/>
protected override void Drawing(ColorAttachment source, DrawContext context) public override void Draw(DrawContext context)
{
if (Enable)
{ {
GL.Viewport(0, 0, (int) (Pipeline.ConnectedWindow.Width * _textureScale), GL.Viewport(0, 0, (int) (Pipeline.ConnectedWindow.Width * _textureScale),
(int) (Pipeline.ConnectedWindow.Height * _textureScale)); (int) (Pipeline.ConnectedWindow.Height * _textureScale));
Framebuffer target = Framebuffer.GetCurrentlyActive(); Framebuffer target = Framebuffer.GetCurrentlyActive();
source.ConnectedFramebuffer.CopyTo(_tempColorBuffer);
bool first = true, hoz = true; bool first = true, hoz = true;
int iter = Iterations * 2; int iter = Iterations * 2;
for (int i = 0; i < iter; i++) for (int i = 0; i < iter; i++)
@ -177,18 +171,18 @@ namespace SM.Base.Legacy.PostProcessing
_shader.Draw(collection => _shader.Draw(collection =>
{ {
collection["renderedTexture"].SetTexture(first ? source : (hoz ? _yBuffer : _xBuffer)); collection["renderedTexture"].SetTexture(first ? _source.ColorAttachments["color"] : (hoz ? _yBuffer : _xBuffer));
collection["First"].SetBool(first); collection["First"].SetUniform1(first);
collection["Threshold"].SetFloat(Threshold); collection["Threshold"].SetUniform1(Threshold);
collection["Horizontal"].SetBool(hoz); collection["Horizontal"].SetUniform1(hoz);
collection["Weights"].SetFloat(_weights); collection["Weights"].SetUniform1(_weights);
collection["WeightCount"].SetFloat(WeightCurvePickAmount); collection["WeightCount"].SetUniform1(WeightCurvePickAmount);
collection["Power"].SetFloat(Power); collection["Power"].SetUniform1(Power);
collection["Radius"].SetFloat(_textureScale * Radius); collection["Radius"].SetUniform1(_textureScale * Radius);
}); });
hoz = !hoz; hoz = !hoz;
@ -197,19 +191,20 @@ namespace SM.Base.Legacy.PostProcessing
GL.Viewport(Pipeline.ConnectedWindow.ClientRectangle); GL.Viewport(Pipeline.ConnectedWindow.ClientRectangle);
target.Activate(); target.Activate();
}
_mergeShader.Draw(collection => _mergeShader.Draw(collection =>
{ {
collection["Scene"].SetTexture(_tempColorBuffer["color"]); collection["Scene"].SetTexture(_source.ColorAttachments["color"]);
collection["Bloom"].SetTexture(_yBuffer); collection["Bloom"].SetTexture(_yBuffer);
collection["MinAmount"].SetFloat(MinAmount); collection["MinAmount"].SetUniform1(MinAmount);
collection["MaxAmount"].SetFloat(MaxAmount); collection["MaxAmount"].SetUniform1(MaxAmount);
collection["AmountMap"].SetTexture(AmountMap, collection["HasAmountMap"]); collection["AmountMap"].SetTexture(AmountMap, collection["HasAmountMap"]);
collection["TextureTransform"].SetMatrix3(AmountTransform.GetMatrix()); collection["TextureTransform"].SetMatrix3(AmountTransform.GetMatrix());
collection["Exposure"].SetFloat(context.UseCamera.Exposure); collection["Exposure"].SetUniform1(context.UseCamera.Exposure);
collection["HDR"].SetBool(_hdr); collection["HDR"].SetUniform1(_hdr);
}); });
} }
} }

View file

@ -4,34 +4,18 @@ using OpenTK.Graphics.OpenGL4;
using SM.Base.PostProcess; using SM.Base.PostProcess;
using SM.Base.Utility; using SM.Base.Utility;
using SM.OGL.Framebuffer; using SM.OGL.Framebuffer;
using SM.OGL.Shaders;
using System.Collections.Generic;
#endregion #endregion
namespace SM.Base.PostEffects namespace SM.Base.PostEffects
{ {
public enum HDRColorCurve
{
OnlyExposure,
Reinhard,
ACES
}
/// <summary> /// <summary>
/// This class has some utility for render pipelines /// This class has some utility for render pipelines
/// </summary> /// </summary>
public static class PostProcessUtility public static class PostProcessUtility
{ {
public static readonly ShaderFile HDRCurves = new ShaderFile(AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".hdr_curves.frag")); private static readonly PostProcessShader _hdrExposureShader =
private static readonly string _finalizeHdrCode = AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".finalize_hdr.glsl"); new PostProcessShader(AssemblyUtility.ReadAssemblyFile(SMRenderer.PostProcessPath + ".finalize_hdr.glsl"));
private static readonly Dictionary<HDRColorCurve, PostProcessShader> _hdrExposureShader = new Dictionary<HDRColorCurve, PostProcessShader>()
{
{ HDRColorCurve.OnlyExposure, new PostProcessShader(new ShaderFile(_finalizeHdrCode) {GLSLExtensions = { HDRCurves } }) },
{ HDRColorCurve.Reinhard, new PostProcessShader(new ShaderFile(_finalizeHdrCode) { GLSLExtensions = { HDRCurves }, Defines = { "TYPE_REINHARD" } }) },
{ HDRColorCurve.ACES, new PostProcessShader(new ShaderFile(_finalizeHdrCode) { GLSLExtensions = { HDRCurves }, Defines = { "TYPE_ACES" } }) },
};
private static readonly PostProcessShader _gammaShader = private static readonly PostProcessShader _gammaShader =
new PostProcessShader( new PostProcessShader(
@ -54,7 +38,7 @@ namespace SM.Base.PostEffects
target.Activate(FramebufferTarget.DrawFramebuffer); target.Activate(FramebufferTarget.DrawFramebuffer);
GL.BlitFramebuffer(0, 0, (int) multisampledBuffers.Size.X, (int) multisampledBuffers.Size.Y, 0, 0, GL.BlitFramebuffer(0, 0, (int) multisampledBuffers.Size.X, (int) multisampledBuffers.Size.Y, 0, 0,
(int) target.Size.X, (int) target.Size.Y, ClearBufferMask.ColorBufferBit, (int) target.Size.X, (int) target.Size.Y, ClearBufferMask.ColorBufferBit,
BlitFramebufferFilter.Linear); BlitFramebufferFilter.Nearest);
target.Activate(); target.Activate();
} }
@ -64,12 +48,12 @@ namespace SM.Base.PostEffects
/// </summary> /// </summary>
/// <param name="attachment"></param> /// <param name="attachment"></param>
/// <param name="exposure"></param> /// <param name="exposure"></param>
public static void FinalizeHDR(ColorAttachment attachment, HDRColorCurve colorCurve = HDRColorCurve.ACES, float exposure = 1) public static void FinalizeHDR(ColorAttachment attachment, float exposure)
{ {
_hdrExposureShader[colorCurve].Draw(u => _hdrExposureShader.Draw(u =>
{ {
u["Gamma"].SetFloat(Gamma); u["Gamma"].SetUniform1(Gamma);
u["Exposure"].SetFloat(exposure); u["Exposure"].SetUniform1(exposure);
u["Scene"].SetTexture(attachment); u["Scene"].SetTexture(attachment);
}); });
} }
@ -82,7 +66,7 @@ namespace SM.Base.PostEffects
{ {
_gammaShader.Draw(u => _gammaShader.Draw(u =>
{ {
u["Gamma"].SetFloat(Gamma); u["Gamma"].SetUniform1(Gamma);
u["Scene"].SetTexture(attachment); u["Scene"].SetTexture(attachment);
}); });
} }

View file

@ -1,4 +1,5 @@
#version 330 #version 330
#define PI 3.14159265359
uniform sampler2D renderedTexture; uniform sampler2D renderedTexture;
uniform float RenderScale; uniform float RenderScale;
@ -15,7 +16,6 @@ uniform float Power;
uniform float Radius; uniform float Radius;
layout(location = 0) out vec4 color; layout(location = 0) out vec4 color;
layout(location = 1) out vec4 scene;
vec4 GetRenderColorOffset(vec2 offset); vec4 GetRenderColorOffset(vec2 offset);
@ -31,8 +31,6 @@ float GetWeight(int dif) {
} }
void main() { void main() {
if (First) scene = GetRenderColorOffset(vec2(0));
vec3 thres = vec3(First ? Threshold : 0); vec3 thres = vec3(First ? Threshold : 0);
vec2 tex_offset = 1.0 / textureSize(renderedTexture, 0) * vec2(Horizontal ? 1 : 0, Horizontal ? 0 : 1); vec2 tex_offset = 1.0 / textureSize(renderedTexture, 0) * vec2(Horizontal ? 1 : 0, Horizontal ? 0 : 1);

View file

@ -18,7 +18,7 @@ layout(location = 0) out vec4 color;
void main() { void main() {
vec3 result = texture(Bloom, vTexture).rgb; vec3 result = texture(Bloom, vTexture).rgb;
//if (HasAmountMap) result *= clamp(length(texture(AmountMap, TransformedTexture).rgb) * (MaxAmount - MinAmount) + MinAmount, 0, 1); if (HasAmountMap) result *= clamp(length(texture(AmountMap, TransformedTexture).rgb) * (MaxAmount - MinAmount) + MinAmount, 0, 1);
if (!HDR) { if (!HDR) {
result = vec3(1.0) - exp(-result * Exposure); result = vec3(1.0) - exp(-result * Exposure);
} }

View file

@ -1,18 +1,11 @@
#version 330 #version 330
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec2 aTex; layout(location = 1) in vec2 aTex;
uniform mat4 MVP;
uniform mat3 TextureTransform; uniform mat3 TextureTransform;
out vec2 vTexture;
out vec2 TransformedTexture; out vec2 TransformedTexture;
void vertex() {
void main() {
vTexture = aTex;
TransformedTexture = vec2(TextureTransform * vec3(aTex, 1)); TransformedTexture = vec2(TextureTransform * vec3(aTex, 1));
gl_Position = MVP * vec4(aPos, 1);
} }

View file

@ -0,0 +1,15 @@
#version 330
in vec2 vTexture;
uniform sampler2D Scene;
uniform float Exposure;
uniform float Gamma;
layout(location = 0) out vec4 color;
void main() {
vec3 result = vec3(1) - exp(-texture(Scene, vTexture).rgb * Exposure);
color = vec4(pow(result, vec3(1 / Gamma)), 1);
}

View file

@ -3,7 +3,6 @@
using OpenTK; using OpenTK;
using SM.Base.Scene; using SM.Base.Scene;
using SM.Base.Window; using SM.Base.Window;
using SM.OGL.Framebuffer;
#endregion #endregion
@ -24,12 +23,6 @@ namespace SM.Base.PostProcess
/// </summary> /// </summary>
protected RenderPipeline Pipeline; protected RenderPipeline Pipeline;
/// <summary>
/// Enables the effect.
/// <para>Default: true</para>
/// </summary>
public bool Enable = true;
/// <summary> /// <summary>
/// Initialize the effect. /// Initialize the effect.
/// </summary> /// </summary>
@ -47,20 +40,11 @@ namespace SM.Base.PostProcess
{ {
} }
/// <summary>
/// This executes
/// </summary>
/// <param name="source"></param>
/// <param name="context"></param>
public void Draw(ColorAttachment source, DrawContext context)
{
if (Enable) Drawing(source, context);
}
/// <summary> /// <summary>
/// Method to draw the actual effect. /// Method to draw the actual effect.
/// </summary> /// </summary>
protected abstract void Drawing(ColorAttachment source, DrawContext context); public abstract void Draw(DrawContext context);
/// <summary> /// <summary>
/// Event, when the scene changed. /// Event, when the scene changed.
@ -68,14 +52,5 @@ namespace SM.Base.PostProcess
public virtual void SceneChanged(GenericScene scene) public virtual void SceneChanged(GenericScene scene)
{ {
} }
/// <summary>
/// Event, when the screen size changed.
/// </summary>
/// <param name="window">Window that changed</param>
public virtual void ScreenSizeChanged(IGenericWindow window)
{
}
} }
} }

View file

@ -0,0 +1,72 @@
#region usings
using System;
using System.Collections.Generic;
using OpenTK.Graphics.OpenGL4;
using SM.Base.Objects.Static;
using SM.Base.Utility;
using SM.OGL.Shaders;
#endregion
namespace SM.Base.PostProcess
{
/// <summary>
/// Specific shader for post processing.
/// </summary>
public class PostProcessShader : GenericShader
{
private static readonly ShaderFile _fragExtensions =
new ShaderFile(AssemblyUtility.ReadAssemblyFile("SM.Base.PostProcess.DefaultFiles.extensions.frag"));
private static readonly ShaderFile _normalVertex =
new ShaderFile(AssemblyUtility.ReadAssemblyFile("SM.Base.PostProcess.DefaultFiles.vertexFile.vert"));
private static readonly string _normalVertexWithExt =
AssemblyUtility.ReadAssemblyFile("SM.Base.PostProcess.DefaultFiles.vertexWithExt.vert");
/// <summary>
/// Creates the shader with the default vertex shader and custom fragment.
/// </summary>
public PostProcessShader(string fragment) : this(_normalVertex,
new ShaderFile(fragment))
{
}
/// <summary>
/// Creates the shader with an vertex extension and custom fragment.
/// </summary>
/// <param name="vertexExt"></param>
/// <param name="fragment"></param>
public PostProcessShader(string vertexExt, string fragment) : this(new ShaderFile(_normalVertexWithExt)
{
GLSLExtensions = new List<ShaderFile> {new ShaderFile(vertexExt)}
}, new ShaderFile(fragment))
{
}
private PostProcessShader(ShaderFile vertex, ShaderFile fragment) : base(
new ShaderFileCollection(vertex, fragment))
{
fragment.GLSLExtensions.Add(_fragExtensions);
}
/// <summary>
/// Draws the shader with special uniforms.
/// </summary>
/// <param name="setUniformAction"></param>
public void Draw(Action<UniformCollection> setUniformAction)
{
Activate();
Plate.Object.Activate();
Uniforms["MVP"].SetMatrix4(PostProcessEffect.Mvp);
setUniformAction(Uniforms);
GL.DrawArrays(PrimitiveType.Quads, 0, 4);
CleanUp();
}
}
}

View file

@ -1,7 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\..\packages\SharpFont.4.0.1\build\SharpFont.props" Condition="Exists('..\..\..\packages\SharpFont.4.0.1\build\SharpFont.props')" />
<Import Project="..\..\..\packages\SharpFont.Dependencies.2.6\build\SharpFont.Dependencies.props" Condition="Exists('..\..\..\packages\SharpFont.Dependencies.2.6\build\SharpFont.Dependencies.props')" />
<Import Project="..\..\..\IAmTwo - Kopie\packages\SharpFont.4.0.1\build\SharpFont.props" Condition="Exists('..\..\..\IAmTwo - Kopie\packages\SharpFont.4.0.1\build\SharpFont.props')" /> <Import Project="..\..\..\IAmTwo - Kopie\packages\SharpFont.4.0.1\build\SharpFont.props" Condition="Exists('..\..\..\IAmTwo - Kopie\packages\SharpFont.4.0.1\build\SharpFont.props')" />
<Import Project="..\..\..\IAmTwo - Kopie\packages\SharpFont.Dependencies.2.6\build\SharpFont.Dependencies.props" Condition="Exists('..\..\..\IAmTwo - Kopie\packages\SharpFont.Dependencies.2.6\build\SharpFont.Dependencies.props')" /> <Import Project="..\..\..\IAmTwo - Kopie\packages\SharpFont.Dependencies.2.6\build\SharpFont.Dependencies.props" Condition="Exists('..\..\..\IAmTwo - Kopie\packages\SharpFont.Dependencies.2.6\build\SharpFont.Dependencies.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
@ -18,7 +16,6 @@
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<NuGetPackageImportStamp> <NuGetPackageImportStamp>
</NuGetPackageImportStamp> </NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -40,6 +37,23 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Reference Include="OpenTK, Version=3.3.1.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL">
<HintPath>..\..\packages\OpenTK.3.3.1\lib\net20\OpenTK.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="SharpFont, Version=4.0.1.200, Culture=neutral, PublicKeyToken=48add4c483071cdf, processorArchitecture=MSIL">
<HintPath>..\..\..\IAmTwo - Kopie\packages\SharpFont.4.0.1\lib\net45\SharpFont.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.IO.Compression.FileSystem" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xaml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Animation\AnimationCurves.cs" /> <Compile Include="Animation\AnimationCurves.cs" />
<Compile Include="Animation\InterpolationProcess.cs" /> <Compile Include="Animation\InterpolationProcess.cs" />
@ -48,23 +62,21 @@
<Compile Include="Drawing\DrawingBasis.cs" /> <Compile Include="Drawing\DrawingBasis.cs" />
<Compile Include="Drawing\GenericTransformation.cs" /> <Compile Include="Drawing\GenericTransformation.cs" />
<Compile Include="Drawing\Instance.cs" /> <Compile Include="Drawing\Instance.cs" />
<Compile Include="Drawing\Particles\ParticleInstance.cs" />
<Compile Include="Drawing\ShaderArguments.cs" /> <Compile Include="Drawing\ShaderArguments.cs" />
<Compile Include="Drawing\TextureTransformation.cs" /> <Compile Include="Drawing\TextureTransformation.cs" />
<Compile Include="Drawing\Text\Font.cs" /> <Compile Include="Drawing\Text\Font.cs" />
<Compile Include="PostEffects\BloomEffect.cs" />
<Compile Include="PostEffects\PostProcessUtility.cs" /> <Compile Include="PostEffects\PostProcessUtility.cs" />
<Compile Include="Scene\ICollectionItem.cs" /> <Compile Include="Scene\ICollectionItem.cs" />
<Compile Include="Scene\IFixedScriptable.cs" /> <Compile Include="Scene\IFixedScriptable.cs" />
<Compile Include="Shaders\MaterialShader.cs" /> <Compile Include="Shaders\MaterialShader.cs" />
<Compile Include="Drawing\Particles\ParticleContext.cs" />
<Compile Include="Drawing\Particles\ParticleMovement.cs" /> <Compile Include="Drawing\Particles\ParticleMovement.cs" />
<Compile Include="Drawing\Particles\ParticleStruct.cs" />
<Compile Include="Drawing\Particles\ParticleDrawingBasis.cs" /> <Compile Include="Drawing\Particles\ParticleDrawingBasis.cs" />
<Compile Include="Shaders\SimpleShader.cs" /> <Compile Include="Shaders\SimpleShader.cs" />
<Compile Include="Types\CVector4.cs" /> <Compile Include="Types\CVector4.cs" />
<Compile Include="Types\CVectorBase.cs" /> <Compile Include="Types\CVectorBase.cs" />
<Compile Include="Types\MinMax.cs" />
<Compile Include="Utility\IInitializable.cs" /> <Compile Include="Utility\IInitializable.cs" />
<Compile Include="Utility\MathUtils.cs" />
<Compile Include="Utility\Ray.cs" /> <Compile Include="Utility\Ray.cs" />
<Compile Include="Utility\Util.cs" /> <Compile Include="Utility\Util.cs" />
<Compile Include="Window\Contexts\DrawContext.cs" /> <Compile Include="Window\Contexts\DrawContext.cs" />
@ -75,7 +87,7 @@
<Compile Include="Objects\InstancedMesh.cs" /> <Compile Include="Objects\InstancedMesh.cs" />
<Compile Include="Objects\Mesh.cs" /> <Compile Include="Objects\Mesh.cs" />
<Compile Include="Objects\Static\AxisHelper.cs" /> <Compile Include="Objects\Static\AxisHelper.cs" />
<Compile Include="Legacy\PostProcessing\BloomEffectOld.cs" /> <Compile Include="PostEffects\BloomEffect.cs" />
<Compile Include="PostProcess\PostProcessEffect.cs" /> <Compile Include="PostProcess\PostProcessEffect.cs" />
<Compile Include="PostProcess\PostProcessShader.cs" /> <Compile Include="PostProcess\PostProcessShader.cs" />
<Compile Include="Scene\IScriptable.cs" /> <Compile Include="Scene\IScriptable.cs" />
@ -115,16 +127,25 @@
<EmbeddedResource Include="PostProcess\DefaultFiles\vertexFile.vert" /> <EmbeddedResource Include="PostProcess\DefaultFiles\vertexFile.vert" />
<EmbeddedResource Include="PostProcess\DefaultFiles\extensions.frag" /> <EmbeddedResource Include="PostProcess\DefaultFiles\extensions.frag" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SM.OGL\SM.OGL.csproj">
<Project>{f604d684-bc1d-4819-88b5-8b5d03a17be0}</Project>
<Name>SM.OGL</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Include="PostProcess\DefaultFiles\vertexWithExt.vert" /> <EmbeddedResource Include="PostProcess\DefaultFiles\vertexWithExt.vert" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Include="Legacy\PostProcessing\bloom_blur.glsl" /> <EmbeddedResource Include="PostEffects\Shaders\bloom_blur.glsl" />
<EmbeddedResource Include="Legacy\PostProcessing\bloom_merge.glsl" /> <EmbeddedResource Include="PostEffects\Shaders\bloom_merge.glsl" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="OpenTK.dll.config" />
<None Include="packages.config" />
<EmbeddedResource Include="Shaders\SimpleShaderPresets\basic_vertex.glsl" /> <EmbeddedResource Include="Shaders\SimpleShaderPresets\basic_vertex.glsl" />
<EmbeddedResource Include="Shaders\SimpleShaderPresets\instanced_vertex.glsl" /> <EmbeddedResource Include="Shaders\SimpleShaderPresets\instanced_vertex.glsl" />
<EmbeddedResource Include="PostEffects\Shaders\bloom_merge_vert.glsl" />
<EmbeddedResource Include="PostEffects\Shaders\finalize_hdr.glsl" /> <EmbeddedResource Include="PostEffects\Shaders\finalize_hdr.glsl" />
<EmbeddedResource Include="PostEffects\Shaders\finalize_gamma.glsl" /> <EmbeddedResource Include="PostEffects\Shaders\finalize_gamma.glsl" />
<EmbeddedResource Include="Shaders\Extensions\fragment\textureGamma.glsl" /> <EmbeddedResource Include="Shaders\Extensions\fragment\textureGamma.glsl" />
@ -133,50 +154,12 @@
<ItemGroup> <ItemGroup>
<EmbeddedResource Include="Window\winIcon.ico" /> <EmbeddedResource Include="Window\winIcon.ico" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SM.OGL\SM.OGL.csproj">
<Project>{f604d684-bc1d-4819-88b5-8b5d03a17be0}</Project>
<Name>SM.OGL</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Reference Include="OpenTK, Version=3.3.1.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\OpenTK.3.3.1\lib\net20\OpenTK.dll</HintPath>
</Reference>
<Reference Include="SharpFont, Version=4.0.1.200, Culture=neutral, PublicKeyToken=48add4c483071cdf, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\SharpFont.4.0.1\lib\net45\SharpFont.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Drawing" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.IO.Compression.FileSystem" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.XML" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Legacy\PostProcessing\bloom_merge.vert" />
<None Include="OpenTK.dll.config" />
<None Include="packages.config" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\filter.frag" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\downsample.frag" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\upsample.frag" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\combine.frag" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\sampling.frag" />
<EmbeddedResource Include="PostEffects\Shaders\bloom\combine.vert" />
<EmbeddedResource Include="PostEffects\Shaders\bloom.frag" />
<EmbeddedResource Include="PostEffects\Shaders\hdr_curves.frag" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup> <PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText> <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup> </PropertyGroup>
<Error Condition="!Exists('..\..\..\IAmTwo - Kopie\packages\SharpFont.Dependencies.2.6\build\SharpFont.Dependencies.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\IAmTwo - Kopie\packages\SharpFont.Dependencies.2.6\build\SharpFont.Dependencies.props'))" />
<Error Condition="!Exists('..\..\..\IAmTwo - Kopie\packages\SharpFont.4.0.1\build\SharpFont.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\IAmTwo - Kopie\packages\SharpFont.4.0.1\build\SharpFont.props'))" />
</Target> </Target>
</Project> </Project>

View file

@ -37,7 +37,6 @@ namespace SM.Base.Shaders
/// <param name="context">The context</param> /// <param name="context">The context</param>
public virtual void Draw(DrawContext context) public virtual void Draw(DrawContext context)
{ {
if (ErrorInShader) return;
context.Shader.Activate(); context.Shader.Activate();
context.Mesh.Activate(); context.Mesh.Activate();
@ -46,7 +45,9 @@ namespace SM.Base.Shaders
{ {
try try
{ {
if (context.Material.ShaderArguments.ContainsKey("LineWidth")) if (context.Mesh is ILineMesh lineMesh)
GL.LineWidth(context.Material.ShaderArguments.Get("LineWidth", lineMesh.LineWidth));
else if (context.Material.ShaderArguments.ContainsKey("LineWidth"))
GL.LineWidth((float)context.Material.ShaderArguments["LineWidth"]); GL.LineWidth((float)context.Material.ShaderArguments["LineWidth"]);
} }
catch catch

View file

@ -101,19 +101,17 @@ namespace SM.Base.Shaders
.SetMatrix4(context.Instances[0].ModelMatrix * context.ModelMatrix * context.View * context.World); .SetMatrix4(context.Instances[0].ModelMatrix * context.ModelMatrix * context.View * context.World);
uniforms["MasterTextureMatrix"].SetMatrix3(context.Instances[0].TextureMatrix * context.TextureMatrix); uniforms["MasterTextureMatrix"].SetMatrix3(context.Instances[0].TextureMatrix * context.TextureMatrix);
uniforms["HasVColor"] uniforms["HasVColor"]
.SetBool(context.Mesh.Attributes.Has("color")); .SetUniform1(context.Mesh.Attributes.Has("color"));
DrawObject(context.ForcedType.GetValueOrDefault(context.Mesh.PrimitiveType), context.Mesh); DrawObject(context.ForcedType.GetValueOrDefault(context.Mesh.PrimitiveType), context.Mesh);
} }
private static void InstancedSetUniforms(UniformCollection uniforms, DrawContext context) private static void InstancedSetUniforms(UniformCollection uniforms, DrawContext context)
{ {
if (context.Instances == null || context.Instances.Count < 1) return;
uniforms["MVP"].SetMatrix4(context.ModelMatrix * context.View * context.World); uniforms["MVP"].SetMatrix4(context.ModelMatrix * context.View * context.World);
uniforms["MasterTextureMatrix"].SetMatrix3(context.TextureMatrix); uniforms["MasterTextureMatrix"].SetMatrix3(context.TextureMatrix);
uniforms["HasVColor"] uniforms["HasVColor"]
.SetBool(context.Mesh.Attributes.Has("color")); .SetUniform1(context.Mesh.Attributes.Has("color"));
UniformArray instances = uniforms.GetArray("Instances"); UniformArray instances = uniforms.GetArray("Instances");

View file

@ -1,4 +1,5 @@
#version 330 #version 330
#define SM_SIMPLE_EXTENSION //!extension
layout(location = 0) in vec3 a_Position; layout(location = 0) in vec3 a_Position;
layout(location = 1) in vec2 a_Texture; layout(location = 1) in vec2 a_Texture;
@ -12,6 +13,10 @@ out vec3 v_VertexPosition;
out vec2 v_TexCoords; out vec2 v_TexCoords;
out vec4 v_Color; out vec4 v_Color;
#if (SM_SIMPLE_EXTENSION == 1)
void v_Extension();
#endif
void main() { void main() {
v_Color = vec4(1); v_Color = vec4(1);
if (HasVColor) v_Color = a_Color; if (HasVColor) v_Color = a_Color;
@ -21,5 +26,7 @@ void main() {
v_VertexPosition = a_Position; v_VertexPosition = a_Position;
gl_Position = MVP * vec4(a_Position, 1); gl_Position = MVP * vec4(a_Position, 1);
#if (SM_SIMPLE_EXTENSION == 1)
v_Extension();
#endif
} }

View file

@ -1,5 +1,6 @@
#version 330 #version 330
#define maxInstances //!instanceMax #define maxInstances //!instanceMax
#define SM_SIMPLE_EXTENSION //!extension
struct Instance { struct Instance {
mat4 ModelMatrix; mat4 ModelMatrix;
@ -19,6 +20,10 @@ out vec3 v_VertexPosition;
out vec2 v_TexCoords; out vec2 v_TexCoords;
out vec4 v_Color; out vec4 v_Color;
#if (SM_SIMPLE_EXTENSION == 1)
void v_Extension();
#endif
void main() { void main() {
v_Color = vec4(1); v_Color = vec4(1);
if (HasVColor) v_Color = a_Color; if (HasVColor) v_Color = a_Color;
@ -28,4 +33,7 @@ void main() {
v_VertexPosition = a_Position; v_VertexPosition = a_Position;
gl_Position = MVP * Instances[gl_InstanceID].ModelMatrix * vec4(a_Position, 1); gl_Position = MVP * Instances[gl_InstanceID].ModelMatrix * vec4(a_Position, 1);
#if (SM_SIMPLE_EXTENSION == 1)
v_Extension();
#endif
} }

View file

@ -33,7 +33,7 @@ namespace SM.Base.Time
/// <summary> /// <summary>
/// The target time in seconds. /// The target time in seconds.
/// </summary> /// </summary>
public float Target { get; set; } public float Target { get; }
/// <summary> /// <summary>
/// The already elapsed time but normalized to the target. /// The already elapsed time but normalized to the target.

View file

@ -28,6 +28,21 @@ namespace SM.Base.Types
/// </summary> /// </summary>
public float X { get; set; } public float X { get; set; }
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates. Preset values can be found under <see cref="AnimationCurves"/>. Default: <see cref="AnimationCurves.Linear"/></param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate(TimeSpan duration, float to, BezierCurve? interpolationCurve = null)
{
InterpolationProcess process = new InterpolationProcess(this, duration, ConvertToVector4(), new Vector4(to, 0, 0, 0), interpolationCurve.GetValueOrDefault(AnimationCurves.Linear));
process.Start();
return process;
}
/// <summary> /// <summary>
/// Sets the X-Component. /// Sets the X-Component.
/// </summary> /// </summary>

View file

@ -35,6 +35,25 @@ namespace SM.Base.Types
/// </summary> /// </summary>
public float Y { get; set; } public float Y { get; set; }
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates.
/// <para>When creating a curve, its recommended the Y-component is always between 0 -> 1. But it could make cool effects if not...</para>
/// <para>Preset curves can be found under <see cref="AnimationCurves"/>.</para>
/// <para>Default: <see cref="AnimationCurves.Linear"/></para>
/// </param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate(TimeSpan duration, Vector2 to, BezierCurve? interpolationCurve = null)
{
InterpolationProcess process = new InterpolationProcess(this, duration, ConvertToVector4(), new Vector4(to), interpolationCurve.GetValueOrDefault(AnimationCurves.Linear));
process.Start();
return process;
}
/// <inheritdoc /> /// <inheritdoc />
public override string ToString() public override string ToString()
{ {

View file

@ -35,6 +35,21 @@ namespace SM.Base.Types
/// </summary> /// </summary>
public float Z { get; set; } public float Z { get; set; }
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates. Preset values can be found under <see cref="AnimationCurves"/>. Default: <see cref="AnimationCurves.Linear"/></param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate(TimeSpan duration, Vector3 to, BezierCurve? interpolationCurve = null)
{
InterpolationProcess process = new InterpolationProcess(this, duration, ConvertToVector4(), new Vector4(to, 0), interpolationCurve.GetValueOrDefault(AnimationCurves.Linear));
process.Start();
return process;
}
/// <inheritdoc /> /// <inheritdoc />
public override string ToString() public override string ToString()

View file

@ -1,4 +1,5 @@
using System; using System;
using System.Windows.Forms;
using OpenTK; using OpenTK;
using SM.Base.Animation; using SM.Base.Animation;
@ -24,6 +25,21 @@ namespace SM.Base.Types
W = w; W = w;
} }
/// <summary>
/// Interpolates the motion to the target.
/// </summary>
/// <param name="duration">How long the interpolation should take.</param>
/// <param name="to">The value it should interpolate.</param>
/// <param name="interpolationCurve">The curve how he interpolates. Preset values can be found under <see cref="AnimationCurves"/>. Default: <see cref="AnimationCurves.Linear"/></param>
/// <returns>A handle to control the interpolation process.</returns>
public InterpolationProcess Interpolate(TimeSpan duration, Vector4 to, BezierCurve? interpolationCurve = null)
{
InterpolationProcess process = new InterpolationProcess(this, duration, ConvertToVector4(), to, interpolationCurve.GetValueOrDefault(AnimationCurves.Linear));
process.Start();
return process;
}
/// <inheritdoc /> /// <inheritdoc />
public override void Set(float uniform, bool triggerChanged = true) public override void Set(float uniform, bool triggerChanged = true)
{ {

View file

@ -0,0 +1,83 @@
using System;
using OpenTK;
namespace SM.Base.Types
{
/// <summary>
/// Basis for the CVector classes
/// </summary>
public abstract class CVectorBase
{
/// <summary>
/// This event triggers when a component changed.
/// </summary>
public event Action Changed;
/// <summary>
/// The length/magnitute of the vector.
/// </summary>
public float Length => GetLength();
/// <summary>
/// Gets the square of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property avoids the costly square root operation required by the Length property. This makes it more suitable
/// for comparisons.
/// </remarks>
public float LengthSquared => GetLength(true);
/// <summary>
/// Get the length of the vector.
/// </summary>
/// <param name="squared">If true, it will return the squared product.</param>
/// <returns></returns>
public float GetLength(bool squared = false)
{
float length = GetLengthProcess();
if (squared) return length;
return (float)Math.Sqrt(length);
}
/// <summary>
/// Normalizes the vector.
/// </summary>
public void Normalize()
{
float length = GetLength();
NormalizationProcess(length);
}
/// <summary>
/// Sets the values of the vector, by providing the values over an array.
/// </summary>
/// <param name="parameters"></param>
public abstract void SetRaw(params float[] parameters);
/// <summary>
/// This triggers the <see cref="Changed"/> event.
/// </summary>
protected void TriggerChanged()
{
Changed?.Invoke();
}
/// <summary>
/// Conversion from <see cref="float" /> to One-dimensional Vector.
/// </summary>
/// <returns></returns>
protected abstract float GetLengthProcess();
/// <summary>
/// Normalizes the vector.
/// </summary>
/// <param name="length"></param>
protected abstract void NormalizationProcess(float length);
/// <summary>
/// Converts the vector to a <see cref="Vector4"/>
/// </summary>
/// <returns></returns>
protected abstract Vector4 ConvertToVector4();
}
}

View file

@ -3,7 +3,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using SM.Base.Drawing; using SM.Base.Drawing;
using SM.Base.PostProcess;
using SM.Base.Shaders; using SM.Base.Shaders;
using SM.Base.Utility; using SM.Base.Utility;
using SM.OGL.Framebuffer; using SM.OGL.Framebuffer;
@ -18,11 +17,6 @@ namespace SM.Base.Window
/// </summary> /// </summary>
public abstract class RenderPipeline : IInitializable public abstract class RenderPipeline : IInitializable
{ {
/// <summary>
/// All post processing effects should go here, that should be automaticly managed.
/// </summary>
protected List<PostProcessEffect> PostProcessEffects = new List<PostProcessEffect>();
/// <summary> /// <summary>
/// This contains the windows its connected to. /// This contains the windows its connected to.
/// </summary> /// </summary>
@ -53,26 +47,19 @@ namespace SM.Base.Window
/// <inheritdoc/> /// <inheritdoc/>
public virtual void Activate() public virtual void Activate()
{ }
public void Initialization()
{ {
InitializationProcess(); }
InitizePostProcessing(); /// <inheritdoc/>
if (MainFramebuffer != null) public virtual void Initialization()
{ {
if (MainFramebuffer != null) {
Framebuffers.Add(MainFramebuffer); Framebuffers.Add(MainFramebuffer);
MainFramebuffer.Name = GetType().Name + ".MainFramebuffer"; MainFramebuffer.Name = GetType().Name + ".MainFramebuffer";
} }
DefaultShader ??= SMRenderer.DefaultMaterialShader; DefaultShader ??= SMRenderer.DefaultMaterialShader;
} }
/// <inheritdoc/>
protected virtual void InitializationProcess()
{
}
internal void Render(ref DrawContext context) internal void Render(ref DrawContext context)
{ {
RenderProcess(ref context); RenderProcess(ref context);
@ -86,26 +73,11 @@ namespace SM.Base.Window
/// <summary> /// <summary>
/// The event when resizing. /// The event when resizing.
/// </summary> /// </summary>
public virtual void Resize(IGenericWindow window) public virtual void Resize()
{ {
Recompile(); Recompile();
foreach (PostProcessEffect effect in PostProcessEffects)
{
effect.ScreenSizeChanged(window);
}
} }
/// <summary>
/// Initilizes the collected post processing effects.
/// </summary>
protected void InitizePostProcessing()
{
foreach (PostProcessEffect effect in PostProcessEffects)
{
effect.Initilize(this);
}
}
/// <summary> /// <summary>
/// Compiles the framebuffers. /// Compiles the framebuffers.
@ -141,20 +113,14 @@ namespace SM.Base.Window
/// <summary> /// <summary>
/// This creates a finished setup for a framebuffer. /// This creates a finished setup for a framebuffer.
/// </summary> /// </summary>
public Framebuffer CreateWindowFramebuffer(int multisamples = 0, PixelInformation? pixelInformation = null, bool depth = true) => public Framebuffer CreateWindowFramebuffer(int multisamples = 0, PixelInformation? pixelInformation = null, bool depth = true)
CreateWindowFramebuffer(ConnectedWindow, multisamples, pixelInformation, depth);
/// <summary>
/// This creates a finished setup for a framebuffer.
/// </summary>
public static Framebuffer CreateWindowFramebuffer(IFramebufferWindow window, int multisamples = 0, PixelInformation? pixelInformation = null, bool depth = true)
{ {
Framebuffer framebuffer = new Framebuffer(window); Framebuffer framebuffer = new(ConnectedWindow);
framebuffer.Append("color", new ColorAttachment(0, pixelInformation.GetValueOrDefault(PixelInformation.RGBA_LDR), multisamples:multisamples)); framebuffer.Append("color", new ColorAttachment(0, pixelInformation.GetValueOrDefault(PixelInformation.RGBA_LDR), multisamples));
if (depth) if (depth)
{ {
RenderbufferAttachment depthAttach = RenderbufferAttachment.GenerateDepth(); RenderbufferAttachment depthAttach = RenderbufferAttachment.Depth;
depthAttach.Multisample = multisamples; depthAttach.Multisample = multisamples;
framebuffer.AppendRenderbuffer(depthAttach); framebuffer.AppendRenderbuffer(depthAttach);
} }

View file

@ -60,17 +60,14 @@ namespace SM.Base.Window
{ {
window.WindowSize = new Vector2(window.Width, window.Height); window.WindowSize = new Vector2(window.Width, window.Height);
window.AspectRatio = (float) window.Width / window.Height; window.AspectRatio = (float) window.Width / window.Height;
if (window.WindowSize.LengthSquared == 0) return;
GL.Viewport(window.ClientRectangle); GL.Viewport(window.ClientRectangle);
window.CurrentRenderPipeline?.Resize();
PostProcessEffect.Mvp = Matrix4.CreateScale(window.Width, -window.Height, 1) * PostProcessEffect.Mvp = Matrix4.CreateScale(window.Width, -window.Height, 1) *
Matrix4.LookAt(Vector3.UnitZ, Vector3.Zero, Vector3.UnitY) * Matrix4.LookAt(Vector3.UnitZ, Vector3.Zero, Vector3.UnitY) *
Matrix4.CreateOrthographic(window.Width, window.Height, .1f, 100f); Matrix4.CreateOrthographic(window.Width, window.Height, .1f, 100f);
window.CurrentRenderPipeline?.Resize(window);
window.AppliedSetup?.Resize(window); window.AppliedSetup?.Resize(window);
} }

View file

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Before After
Before After

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="OpenTK" version="3.3.1" targetFramework="net471" /> <package id="OpenTK" version="3.3.1" targetFramework="net452" />
<package id="SharpFont" version="4.0.1" targetFramework="net452" /> <package id="SharpFont" version="4.0.1" targetFramework="net452" />
<package id="SharpFont.Dependencies" version="2.6" targetFramework="net452" /> <package id="SharpFont.Dependencies" version="2.6" targetFramework="net452" />
</packages> </packages>

View file

@ -1,7 +1,6 @@
#region usings #region usings
using System; using System;
using OpenTK;
using OpenTK.Graphics.OpenGL4; using OpenTK.Graphics.OpenGL4;
using SM.OGL.Texture; using SM.OGL.Texture;
@ -22,18 +21,6 @@ namespace SM.OGL.Framebuffer
/// </summary> /// </summary>
public int AttachmentID { get; } public int AttachmentID { get; }
/// <summary>
/// Contains the framebuffer its connected.
/// <para>Usually the last framebuffer, that called the Compile-method.</para>
/// </summary>
public Framebuffer ConnectedFramebuffer { get; private set; }
/// <summary>
/// Can contains the size this attachment want to be.
/// <para>If set, it will ignore the size from the framebuffer.</para>
/// </summary>
public Vector2? AttachmentSize = null;
/// <summary> /// <summary>
/// Returns the <see cref="OpenTK.Graphics.OpenGL4.FramebufferAttachment"/> of this ColorAttachment. /// Returns the <see cref="OpenTK.Graphics.OpenGL4.FramebufferAttachment"/> of this ColorAttachment.
/// </summary> /// </summary>
@ -60,8 +47,7 @@ namespace SM.OGL.Framebuffer
/// Creates a attachment with a specific id. /// Creates a attachment with a specific id.
/// </summary> /// </summary>
/// <param name="attachmentId"></param> /// <param name="attachmentId"></param>
/// <param name="size"></param> public ColorAttachment(int attachmentId) : this(attachmentId, PixelInformation.RGBA_LDR)
public ColorAttachment(int attachmentId, Vector2? size = null) : this(attachmentId, PixelInformation.RGBA_LDR, size)
{ } { }
/// <summary> /// <summary>
@ -69,19 +55,13 @@ namespace SM.OGL.Framebuffer
/// </summary> /// </summary>
/// <param name="attachmentID"></param> /// <param name="attachmentID"></param>
/// <param name="pixelInformation"></param> /// <param name="pixelInformation"></param>
/// <param name="size"></param>
/// <param name="multisamples"></param> /// <param name="multisamples"></param>
public ColorAttachment(int attachmentID, PixelInformation pixelInformation, Vector2? size = null, int multisamples = 0) public ColorAttachment(int attachmentID, PixelInformation pixelInformation, int multisamples = 0)
{ {
AttachmentID = attachmentID; AttachmentID = attachmentID;
PixelInformation = pixelInformation; PixelInformation = pixelInformation;
AttachmentSize = size;
if (multisamples > 8) multisamples = 8;
_multisamples = multisamples; _multisamples = multisamples;
Target = IsMultisampled ? TextureTarget.Texture2DMultisample : TextureTarget.Texture2D; Target = IsMultisampled ? TextureTarget.Texture2DMultisample : TextureTarget.Texture2D;
WrapMode = TextureWrapMode.ClampToEdge;
} }
/// <summary> /// <summary>
/// Generates the attachment. /// Generates the attachment.
@ -90,7 +70,6 @@ namespace SM.OGL.Framebuffer
public void Generate(Framebuffer f) public void Generate(Framebuffer f)
{ {
_id = GL.GenTexture(); _id = GL.GenTexture();
ConnectedFramebuffer = f;
if (IsMultisampled) GenerateMultisampledTexture(f); if (IsMultisampled) GenerateMultisampledTexture(f);
else GenerateTexture(f); else GenerateTexture(f);
@ -98,33 +77,29 @@ namespace SM.OGL.Framebuffer
private void GenerateTexture(Framebuffer f) private void GenerateTexture(Framebuffer f)
{ {
Vector2 size = AttachmentSize.GetValueOrDefault(f.Size); GL.BindTexture(TextureTarget.Texture2D, _id);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInformation.InternalFormat,
(int)f.Size.X, (int)f.Size.Y,
0, PixelInformation.Format, PixelInformation.DataType, IntPtr.Zero);
GenerateBaseTexture(size); 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.BindTexture(TextureTarget.Texture2D, 0);
} }
private void GenerateMultisampledTexture(Framebuffer f) private void GenerateMultisampledTexture(Framebuffer f)
{ {
Vector2 size = AttachmentSize.GetValueOrDefault(f.Size); GL.BindTexture(TextureTarget.Texture2DMultisample, _id);
GL.TexImage2DMultisample(TextureTargetMultisample.Texture2DMultisample, _multisamples, PixelInformation.InternalFormat, (int)f.Size.X, (int)f.Size.Y, true);
Width = (int)size.X; GL.BindTexture(TextureTarget.Texture2DMultisample, 0);
Height = (int)size.Y;
const TextureTarget target = TextureTarget.Texture2DMultisample;
GL.BindTexture(target, _id);
GL.TexImage2DMultisample((TextureTargetMultisample)target, _multisamples, PixelInformation.InternalFormat,
Width, Height, true);
/*
GL.TexParameter(target, TextureParameterName.TextureMinFilter, (int)Filter);
GL.TexParameter(target, TextureParameterName.TextureMagFilter, (int)Filter);
GL.TexParameter(target, TextureParameterName.TextureWrapS,
(int)WrapMode);
GL.TexParameter(target, TextureParameterName.TextureWrapT,
(int)WrapMode);*/
GL.BindTexture(target, 0);
} }
} }
} }

View file

@ -15,10 +15,6 @@ namespace SM.OGL.Framebuffer
/// </summary> /// </summary>
public class Framebuffer : GLObject public class Framebuffer : GLObject
{ {
static Framebuffer CurrentlyActiveFramebuffer;
static Framebuffer CurrentlyActiveDrawFramebuffer;
static Framebuffer CurrentlyActiveReadFramebuffer;
/// <inheritdoc /> /// <inheritdoc />
protected override bool AutoCompile { get; set; } = true; protected override bool AutoCompile { get; set; } = true;
@ -50,16 +46,8 @@ namespace SM.OGL.Framebuffer
/// </summary> /// </summary>
public Vector2 Size { get; private set; } public Vector2 Size { get; private set; }
/// <summary>
/// Says what value the dafault for the "applyViewport"-value in <see cref="Framebuffer.Activate(bool?)"/>.
/// </summary>
public bool DefaultApplyViewport { get; set; } = true; public bool DefaultApplyViewport { get; set; } = true;
/// <summary>
/// Stores the first color attachment added.
/// </summary>
public ColorAttachment FirstColorAttachment { get; private set; }
/// <summary> /// <summary>
/// Contains all color attachments. /// Contains all color attachments.
/// </summary> /// </summary>
@ -68,7 +56,7 @@ namespace SM.OGL.Framebuffer
/// <summary> /// <summary>
/// Contains the current renderbuffer attachments of the framebuffer. /// Contains the current renderbuffer attachments of the framebuffer.
/// </summary> /// </summary>
public List<RenderbufferAttachment> RenderbufferAttachments { get; } = new List<RenderbufferAttachment>(); public Dictionary<RenderbufferAttachment, int> RenderbufferAttachments { get; } = new Dictionary<RenderbufferAttachment, int>();
/// <summary> /// <summary>
/// Gets the color attachment with the specified color name. /// Gets the color attachment with the specified color name.
@ -128,19 +116,15 @@ namespace SM.OGL.Framebuffer
foreach (var pair in ColorAttachments) foreach (var pair in ColorAttachments)
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, pair.Value.FramebufferAttachment, pair.Value.Target, pair.Value.ID, GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, pair.Value.FramebufferAttachment, pair.Value.Target, pair.Value.ID,
0); 0);
FramebufferErrorCode err;
err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer); foreach (RenderbufferAttachment attachment in RenderbufferAttachments.Keys.ToArray())
if (err != FramebufferErrorCode.FramebufferComplete)
throw new Exception("Failed loading framebuffer.\nProblem: " + err);
foreach (RenderbufferAttachment attachment in RenderbufferAttachments)
{ {
attachment.Generate(this); int att = attachment.Generate(this);
GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, attachment.FramebufferAttachment, RenderbufferTarget.Renderbuffer, attachment.ID); GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, attachment.FramebufferAttachment, RenderbufferTarget.Renderbuffer, att);
RenderbufferAttachments[attachment] = att;
} }
err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer); var err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);
if (err != FramebufferErrorCode.FramebufferComplete) if (err != FramebufferErrorCode.FramebufferComplete)
throw new Exception("Failed loading framebuffer.\nProblem: " + err); throw new Exception("Failed loading framebuffer.\nProblem: " + err);
@ -148,25 +132,15 @@ namespace SM.OGL.Framebuffer
GL.BindTexture(TextureTarget.Texture2D, 0); GL.BindTexture(TextureTarget.Texture2D, 0);
} }
/// <summary>
/// Disposes and clears the attachment
/// </summary>
public void Reset()
{
Dispose();
ColorAttachments.Clear();
RenderbufferAttachments.Clear();
}
/// <inheritdoc /> /// <inheritdoc />
public override void Dispose() public override void Dispose()
{ {
foreach (var attachment in ColorAttachments.Values) attachment.Dispose(); foreach (var attachment in ColorAttachments.Values) attachment.Dispose();
FirstColorAttachment = null; foreach (KeyValuePair<RenderbufferAttachment, int> pair in RenderbufferAttachments.ToArray())
foreach (RenderbufferAttachment pair in RenderbufferAttachments.ToArray())
{ {
GL.DeleteRenderbuffer(pair.ID); GL.DeleteRenderbuffer(pair.Value);
RenderbufferAttachments[pair.Key] = -1;
} }
GL.DeleteFramebuffer(this); GL.DeleteFramebuffer(this);
base.Dispose(); base.Dispose();
@ -176,20 +150,12 @@ namespace SM.OGL.Framebuffer
/// <summary> /// <summary>
/// Appends a color attachment. /// Appends a color attachment.
/// </summary> /// </summary>
public void Append(string key, int pos) => Append(key, new ColorAttachment(pos, null)); public void Append(string key, int pos) => Append(key, new ColorAttachment(pos));
/// <summary>
/// Appends a color attachment.
/// </summary>
/// <param name="key"></param>
/// <param name="size"></param>
/// <param name="pos"></param>
public void Append(string key, Vector2 size, int pos) => Append(key, new ColorAttachment(pos, size));
/// <summary> /// <summary>
/// Appends a color attachment. /// Appends a color attachment.
/// </summary> /// </summary>
public void Append(string key, ColorAttachment value) public void Append(string key, ColorAttachment value)
{ {
if (ColorAttachments.Count == 0) FirstColorAttachment = value;
ColorAttachments.Add(key, value); ColorAttachments.Add(key, value);
} }
@ -199,8 +165,7 @@ namespace SM.OGL.Framebuffer
/// <param name="attachment"></param> /// <param name="attachment"></param>
public void AppendRenderbuffer(RenderbufferAttachment attachment) public void AppendRenderbuffer(RenderbufferAttachment attachment)
{ {
if (RenderbufferAttachments.Contains(attachment)) return; RenderbufferAttachments.Add(attachment, -1);
RenderbufferAttachments.Add(attachment);
} }
/// <summary> /// <summary>
@ -215,7 +180,6 @@ namespace SM.OGL.Framebuffer
/// Activates the framebuffer for the specific target framebuffer and without clearing. /// Activates the framebuffer for the specific target framebuffer and without clearing.
/// </summary> /// </summary>
/// <param name="target"></param> /// <param name="target"></param>
/// <param name="applyViewport"></param>
public void Activate(FramebufferTarget target, bool? applyViewport = null) public void Activate(FramebufferTarget target, bool? applyViewport = null)
{ {
Activate(target, ClearBufferMask.None, applyViewport); Activate(target, ClearBufferMask.None, applyViewport);
@ -225,7 +189,6 @@ namespace SM.OGL.Framebuffer
/// Activates the framebuffer while clearing the specified buffer. /// Activates the framebuffer while clearing the specified buffer.
/// </summary> /// </summary>
/// <param name="clearMask"></param> /// <param name="clearMask"></param>
/// <param name="applyViewport"></param>
public void Activate(ClearBufferMask clearMask, bool? applyViewport = null) public void Activate(ClearBufferMask clearMask, bool? applyViewport = null)
{ {
Activate(FramebufferTarget.Framebuffer, clearMask, applyViewport); Activate(FramebufferTarget.Framebuffer, clearMask, applyViewport);
@ -236,58 +199,19 @@ namespace SM.OGL.Framebuffer
/// </summary> /// </summary>
/// <param name="target"></param> /// <param name="target"></param>
/// <param name="clear"></param> /// <param name="clear"></param>
/// <param name="applyViewport"></param>
public void Activate(FramebufferTarget target, ClearBufferMask clear, bool? applyViewport = null) public void Activate(FramebufferTarget target, ClearBufferMask clear, bool? applyViewport = null)
{ {
switch (target)
{
case FramebufferTarget.ReadFramebuffer:
CurrentlyActiveReadFramebuffer = this;
break;
case FramebufferTarget.DrawFramebuffer:
CurrentlyActiveDrawFramebuffer = this;
break;
case FramebufferTarget.Framebuffer:
CurrentlyActiveFramebuffer = this;
break;
}
GL.BindFramebuffer(target, this); GL.BindFramebuffer(target, this);
if (applyViewport.GetValueOrDefault(DefaultApplyViewport)) if (applyViewport.GetValueOrDefault(DefaultApplyViewport)) GL.Viewport(0, 0, (int)Size.X, (int)Size.Y);
GL.Viewport(0, 0, (int)Size.X, (int)Size.Y);
GL.Clear(clear); GL.Clear(clear);
} }
/// <summary>
/// Copies content to the specified Framebuffer.
/// </summary>
public void CopyTo(Framebuffer target, ClearBufferMask clear = ClearBufferMask.ColorBufferBit, BlitFramebufferFilter filter = BlitFramebufferFilter.Linear)
{
Activate(FramebufferTarget.ReadFramebuffer, false);
target.Activate(FramebufferTarget.DrawFramebuffer, false);
GL.BlitFramebuffer(0, 0, (int)Size.X, (int)Size.Y, 0, 0, (int)Size.X, (int)Size.Y, clear, filter);
}
/// <summary> /// <summary>
/// Returns a <see cref="Framebuffer"/> handle of the current framebuffer. /// Returns a <see cref="Framebuffer"/> handle of the current framebuffer.
/// </summary> /// </summary>
/// <param name="target"></param> /// <param name="target"></param>
/// <returns></returns> /// <returns></returns>
public static Framebuffer GetCurrentlyActive(FramebufferTarget target = FramebufferTarget.Framebuffer) public static Framebuffer GetCurrentlyActive(FramebufferTarget target = FramebufferTarget.Framebuffer)
{
switch (target)
{
case FramebufferTarget.ReadFramebuffer:
return CurrentlyActiveReadFramebuffer ??= getCurrentlyActive(target);
case FramebufferTarget.DrawFramebuffer:
return CurrentlyActiveDrawFramebuffer ??= getCurrentlyActive(target);
case FramebufferTarget.Framebuffer:
return CurrentlyActiveFramebuffer ??= getCurrentlyActive(target);
}
return null;
}
static Framebuffer getCurrentlyActive(FramebufferTarget target = FramebufferTarget.Framebuffer)
{ {
Framebuffer buffer = new Framebuffer() Framebuffer buffer = new Framebuffer()
{ {
@ -308,8 +232,6 @@ namespace SM.OGL.Framebuffer
break; break;
} }
return buffer; return buffer;
} }
} }

View file

@ -5,12 +5,12 @@ namespace SM.OGL.Framebuffer
/// <summary> /// <summary>
/// Describes a renderbuffer attachment. /// Describes a renderbuffer attachment.
/// </summary> /// </summary>
public class RenderbufferAttachment public struct RenderbufferAttachment
{ {
/// <summary> /// <summary>
/// Preset for the depthbuffer attachment. /// Preset for the depthbuffer attachment.
/// </summary> /// </summary>
public static RenderbufferAttachment GenerateDepth() => new RenderbufferAttachment(RenderbufferStorage.Depth24Stencil8, FramebufferAttachment.DepthStencilAttachment); public static readonly RenderbufferAttachment Depth = new RenderbufferAttachment(RenderbufferStorage.Depth24Stencil8, FramebufferAttachment.DepthStencilAttachment);
/// <summary> /// <summary>
/// Storage describes the internal format for the renderbuffer. /// Storage describes the internal format for the renderbuffer.
@ -26,11 +26,6 @@ namespace SM.OGL.Framebuffer
/// </summary> /// </summary>
public int Multisample; public int Multisample;
/// <summary>
/// The id that was given to the renderbuffer.
/// </summary>
public int ID;
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
@ -39,8 +34,6 @@ namespace SM.OGL.Framebuffer
Storage = storage; Storage = storage;
FramebufferAttachment = framebufferAttachment; FramebufferAttachment = framebufferAttachment;
Multisample = multisample; Multisample = multisample;
ID = -1;
} }
/// <summary> /// <summary>
@ -48,49 +41,18 @@ namespace SM.OGL.Framebuffer
/// </summary> /// </summary>
/// <param name="f">The framebuffer</param> /// <param name="f">The framebuffer</param>
/// <returns>The ID of the renderbuffer.</returns> /// <returns>The ID of the renderbuffer.</returns>
public void Generate(Framebuffer f) public int Generate(Framebuffer f)
{ {
ID = GL.GenRenderbuffer(); int rb = GL.GenRenderbuffer();
GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, ID); GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, rb);
if (Multisample != 0) if (Multisample != 0)
GL.RenderbufferStorageMultisample(RenderbufferTarget.Renderbuffer, Multisample, Storage, (int)f.Size.X, (int)f.Size.Y); GL.RenderbufferStorageMultisample(RenderbufferTarget.Renderbuffer, Multisample, Storage, (int)f.Size.X, (int)f.Size.Y);
else else
GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, Storage, (int)f.Size.X, (int)f.Size.Y); GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, Storage, (int)f.Size.X, (int)f.Size.Y);
GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0); GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);
}
/// <summary>
/// Disposes the renderbuffer.
/// </summary>
public void Dispose()
{
GL.DeleteRenderbuffer(ID); return rb;
ID = -1;
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (obj is RenderbufferAttachment ra)
{
if (ra.FramebufferAttachment == FramebufferAttachment) return true;
return false;
}
return false;
}
/// <inheritdoc/>
public override int GetHashCode()
{
int hashCode = -1803239493;
hashCode = hashCode * -1521134295 + Storage.GetHashCode();
hashCode = hashCode * -1521134295 + FramebufferAttachment.GetHashCode();
hashCode = hashCode * -1521134295 + Multisample.GetHashCode();
hashCode = hashCode * -1521134295 + ID.GetHashCode();
return hashCode;
} }
} }
} }

View file

@ -136,7 +136,7 @@ namespace SM.OGL
/// </summary> /// </summary>
public static void DisposeMarkedObjects() public static void DisposeMarkedObjects()
{ {
foreach (GLObject o in _disposableObjects.ToArray()) foreach (GLObject o in _disposableObjects)
{ {
o.Dispose(); o.Dispose();
} }

Some files were not shown because too many files have changed in this diff Show more