Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions Core/Entities/UIElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using SharpEngine.Core.Shaders;

using Silk.NET.OpenGL;
using System;
using System.Threading.Tasks;

namespace SharpEngine.Core.Entities;
Expand All @@ -20,7 +21,7 @@ public class UIElement : SceneNode
public UIElement(string name)
{
Name = name;
Mesh = MeshService.Instance.LoadMesh("plane", Primitives.Plane.Mesh);
// Mesh = MeshService.Instance.LoadMesh("plane", Primitives.Plane.Mesh);
}

private readonly UIShader _uIShader = new();
Expand All @@ -33,7 +34,7 @@ public UIElement(string name)

// TODO: Use actual mesh
/// <summary>Gets or sets the mesh of the UI element.</summary>
public Mesh Mesh { get; set; } = new();
public Mesh Mesh { get; set; } // = new();

private readonly float[] _vertices =
[
Expand All @@ -56,20 +57,25 @@ public UIElement(string name)
public void Initialize()
{
_vertexArrayObject = Window.GL.GenVertexArray();
Window.GL.BindVertexArray(_vertexArrayObject);
Bind();

InitializeBuffers();
}

public void Bind()
{
Window.GL.BindVertexArray(_vertexArrayObject);
}

private void InitializeBuffers()
{
var vertexBufferObject = Window.GL.GenBuffer();
Window.GL.BindBuffer(GLEnum.ArrayBuffer, vertexBufferObject);
Window.GL.BufferData<float>(GLEnum.ArrayBuffer, (uint)_vertices.Length * sizeof(float), _vertices, GLEnum.StaticDraw);
Window.GL.BufferData<float>(GLEnum.ArrayBuffer, _vertices, GLEnum.StaticDraw);

var elementBufferObject = Window.GL.GenBuffer();
Window.GL.BindBuffer(GLEnum.ElementArrayBuffer, elementBufferObject);
Window.GL.BufferData<uint>(GLEnum.ElementArrayBuffer, (uint)_indices.Length * sizeof(uint), _indices, GLEnum.StaticDraw);
Window.GL.BufferData<uint>(GLEnum.ElementArrayBuffer, _indices, GLEnum.StaticDraw);
}

/// <summary>
Expand All @@ -81,8 +87,7 @@ public override Task Render()

_uIShader.Shader.SetMatrix4(ShaderAttributes.Model, Transform.ModelMatrix);

uint a = 0;
Window.GL.DrawElements(PrimitiveType.Triangles, (uint)_indices.Length, DrawElementsType.UnsignedInt, ref a);
Window.GL.DrawElements<uint>(PrimitiveType.Triangles, (uint)_indices.Length, DrawElementsType.UnsignedInt, []);

return Task.CompletedTask;
}
Expand Down
1 change: 1 addition & 0 deletions Core/Renderers/Renderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public Renderer(CameraView camera, ISettings settings, Scene scene) : base(setti
_camera = camera;
_scene = scene;

// TODO: These should be refactored out. The minimum build shouldn't need to use these.
_lightingShader = new LightingShader();
_lampShader = new LampShader();
}
Expand Down
10 changes: 9 additions & 1 deletion Core/Renderers/UIRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public override void Initialize()

_uiShader.Shader.Use();

//_scene.UIElements.Add(new UIElement("uiElement"));
_scene.UIElements.Add(new UIElement("uiElement"));

_scene.Iterate(_scene.UIElements, elem => elem.Initialize());

Expand All @@ -56,14 +56,22 @@ private void InitializeVertexArrays()
/// <inheritdoc />
public override Task Render()
{
return Task.CompletedTask;

try
{
Window.GL.Disable(EnableCap.DepthTest);
Window.GL.DepthFunc(DepthFunction.Less);

foreach (var item in _scene.UIElements)
{
item.Bind();
}

_uiShader.Shader.Use();

var uiElementRenderTasks = _scene.IterateAsync<UIElement>(_scene.UIElements, elem => elem.Render());

return Task.WhenAll(uiElementRenderTasks);
}
catch (Exception ex)
Expand Down
11 changes: 7 additions & 4 deletions Core/Shaders/LampShader.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using SharpEngine.Core.Entities.Properties;
using SharpEngine.Core.Entities.Properties;
using SharpEngine.Core.Extensions;
using Silk.NET.OpenGL;

Expand All @@ -22,9 +22,12 @@ public override bool SetAttributes()
if (!base.SetAttributes())
return false;

var positionLocation = (uint)Shader!.GetAttribLocation(ShaderAttributes.Pos);
Window.GL.EnableVertexAttribArray(positionLocation);
Window.GL.VertexAttribPointer(positionLocation, 3, VertexAttribPointerType.Float, false, VertexData.Stride, 0);
if (!Shader!.TryGetAttribLocation(ShaderAttributes.Pos, out int positionLocation))
return false;

var positionLocationUint = (uint)positionLocation;
Window.GL.EnableVertexAttribArray(positionLocationUint);
Window.GL.VertexAttribPointer(positionLocationUint, 3, VertexAttribPointerType.Float, false, VertexData.Stride, 0);

return true;
}
Expand Down
32 changes: 21 additions & 11 deletions Core/Shaders/LightingShader.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using SharpEngine.Core.Entities.Properties;
using SharpEngine.Core.Entities.Properties;
using SharpEngine.Core.Extensions;
using Silk.NET.OpenGL;
using System;

namespace SharpEngine.Core.Shaders;

Expand All @@ -22,17 +23,26 @@ public override bool SetAttributes()
if (!base.SetAttributes())
return false;

var positionLocation = (uint)Shader!.GetAttribLocation(ShaderAttributes.Pos);
Window.GL.EnableVertexAttribArray(positionLocation);
Window.GL.VertexAttribPointer(positionLocation, VertexData.VerticesSize, VertexAttribPointerType.Float, false, VertexData.Stride, 0);

var normalLocation = (uint)Shader.GetAttribLocation(ShaderAttributes.Normal);
Window.GL.EnableVertexAttribArray(normalLocation);
Window.GL.VertexAttribPointer(normalLocation, VertexData.NormalsSize, VertexAttribPointerType.Float, false, VertexData.Stride, VertexData.NormalsOffset);
if (!Shader!.TryGetAttribLocation(ShaderAttributes.Pos, out int positionLocation))
return false;

var texCoordLocation = (uint)Shader.GetAttribLocation(ShaderAttributes.TexCoords);
Window.GL.EnableVertexAttribArray(texCoordLocation);
Window.GL.VertexAttribPointer(texCoordLocation, VertexData.TexCoordsSize, VertexAttribPointerType.Float, false, VertexData.Stride, VertexData.TexCoordsOffset);
var positionLocationUint = (uint)positionLocation;
Window.GL.EnableVertexAttribArray(positionLocationUint);
Window.GL.VertexAttribPointer(positionLocationUint, VertexData.VerticesSize, VertexAttribPointerType.Float, false, VertexData.Stride, 0);

if (!Shader!.TryGetAttribLocation(ShaderAttributes.Normal, out int normalLocation))
return false;

var normalLocationUint = (uint)normalLocation;
Window.GL.EnableVertexAttribArray(normalLocationUint);
Window.GL.VertexAttribPointer(normalLocationUint, VertexData.NormalsSize, VertexAttribPointerType.Float, false, VertexData.Stride, VertexData.NormalsOffset);

if (!Shader!.TryGetAttribLocation(ShaderAttributes.TexCoords, out int texCoordLocation))
return false;

var texCoordLocationUint = (uint)texCoordLocation;
Window.GL.EnableVertexAttribArray(texCoordLocationUint);
Window.GL.VertexAttribPointer(texCoordLocationUint, VertexData.TexCoordsSize, VertexAttribPointerType.Float, false, VertexData.Stride, VertexData.TexCoordsOffset);

return true;
}
Expand Down
65 changes: 46 additions & 19 deletions Core/Shaders/Shader.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
using System.Collections.Generic;

Expand Down Expand Up @@ -31,7 +31,7 @@ public class Shader
/// </remarks>
/// <param name="vertPath">The vertex shader full path.</param>
/// <param name="fragPath">The fragment shader full path.</param>
/// <param name="name">The identfier name of the shader.</param>
/// <param name="name">The identifier name of the shader.</param>
public Shader(string vertPath, string fragPath, string name)
{
Name = name;
Expand All @@ -44,10 +44,16 @@ public Shader(string vertPath, string fragPath, string name)

// Load and compile shader
if (!LoadShader(ShaderType.VertexShader, vertPath, out uint vertexShader))
{
Console.WriteLine("Unable to load vertex shader.");
return;
}

if (!LoadShader(ShaderType.FragmentShader, fragPath, out uint fragmentShader))
{
Console.WriteLine("Unable to load fragment shader.");
return;
}

// These two shaders must then be merged into a shader program, which can then be used by OpenGL.
// To do this, create a program...
Expand All @@ -59,7 +65,11 @@ public Shader(string vertPath, string fragPath, string name)
Window.GL.AttachShader(Handle, fragmentShader);

// And then link them together.
LinkProgram(Handle);
if (!LinkProgram(Handle))
{
Console.WriteLine("Unable to link shader program.");
return;
}

// When the shader program is linked, it no longer needs the individual shaders attached to it; the compiled code is copied into the shader program.
// Detach them, and then delete them.
Expand Down Expand Up @@ -91,7 +101,12 @@ private static bool LoadShader(ShaderType shaderType, string shaderPath, out uin
// GL.CreateShader will create an empty shader (obviously). The ShaderType enum denotes which type of shader will be created.
shader = Window.GL.CreateShader(shaderType);
Window.GL.ShaderSource(shader, shaderSource);
CompileShader(shader);

if (!CompileShader(shader))
{
Console.WriteLine($"Unable to load {shaderType} shader from '{shaderPath}'.");
return false;
}

return true;
}
Expand All @@ -102,7 +117,7 @@ private void GetUniformLocations()
Window.GL.GetProgram(Handle, GLEnum.ActiveUniforms, out var numberOfUniforms);

// Next, allocate the dictionary to hold the locations.
_uniformLocations = new Dictionary<string, int>();
_uniformLocations = [];

// Loop over all the uniforms,
for (uint i = 0; i < numberOfUniforms; i++)
Expand All @@ -129,31 +144,39 @@ private static string ProcessIncludes(string shaderCode, string directory)
});
}

private static void CompileShader(uint shader)
private static bool CompileShader(uint shader)
{
// Try to compile the shader
Window.GL.CompileShader(shader);

// Check for compilation errors
Window.GL.GetShader(shader, GLEnum.CompileStatus, out var code);
if (code != (int)GLEnum.True)
Window.GL.GetShader(shader, GLEnum.CompileStatus, out var statusCode);
if (statusCode != (int)GLEnum.True)
{
// We can use `GL.GetShaderInfoLog(shader)` to get information about the error.
var infoLog = Window.GL.GetShaderInfoLog(shader);
throw new InvalidOperationException($"Error occurred whilst compiling Shader({shader}).\n\n{infoLog}");
Console.WriteLine($"Error occurred whilst compiling Shader({shader}).\n\n{infoLog}");

return false;
}

return true;
}

private static void LinkProgram(uint program)
private static bool LinkProgram(uint program)
{
Window.GL.LinkProgram(program);

Window.GL.GetProgram(program, GLEnum.LinkStatus, out var code);
if (code != (int)GLEnum.True)
Window.GL.GetProgram(program, GLEnum.LinkStatus, out var statusCode);

if (statusCode != (int)GLEnum.True)
{
string infoLog = Window.GL.GetProgramInfoLog(program);
throw new InvalidOperationException($"Error occurred whilst linking Program({program}): {infoLog}");
Console.WriteLine($"Error occurred whilst linking Program({program}): {infoLog}");

return false;
}

return true;
}

/// <summary>
Expand All @@ -166,14 +189,18 @@ public void Use()
/// Checks if the shader attribute exists within the current shader.
/// </summary>
/// <param name="attribName">The name of the attribute that's being looked for.</param>
/// <returns>If the attribute exists, the location of the attribute in the shader; otherwise -1.</returns>
public int GetAttribLocation(string attribName)
/// <param name="location">Outputs the location of the attribute in the shader if found; otherwise -1.</param>
/// <returns>If the attribute exists, <see langword="true"/>; otherwise, <see langword="false"/>. </returns>
public bool TryGetAttribLocation(string attribName, out int location)
{
int location = Window.GL.GetAttribLocation(Handle, attribName);
if (location == -1)
location = Window.GL.GetAttribLocation(Handle, attribName);
if (location == ShaderAttributes.AttributeLocationNotFound)
{
Console.WriteLine($"Attribute '{attribName}' not found in shader program.");
return false;
}

return location;
return true;
}

// Uniform setters
Expand Down
5 changes: 2 additions & 3 deletions Core/Shaders/UIShader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@ public UIShader()
public override bool SetAttributes()
{
if (!base.SetAttributes())
return false;
return false;

var vertexLocation = Shader!.GetAttribLocation(ShaderAttributes.Pos);
if (vertexLocation == ShaderAttributes.AttributeLocationNotFound)
if (!Shader!.TryGetAttribLocation(ShaderAttributes.Pos, out int vertexLocation))
return false;

uint vertexLocationUInt = (uint)vertexLocation;
Expand Down
7 changes: 1 addition & 6 deletions Core/SharpEngine.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@
<PropertyGroup>
<Description>Everything needed to build games using a purely C# game engine.</Description>

<!--
Required by some low level OpenGL functions.
We should see if there is a better way to approach where ever these unsafe contexts are being used.
-->
<Platforms>AnyCPU;x64;x86</Platforms>
<GeneratePackageOnBuild>$(GenerateNuGetPackages)</GeneratePackageOnBuild>
<PackageProjectUrl>https://github.com/Av3boy/SharpEngine</PackageProjectUrl>
Expand All @@ -15,8 +11,7 @@

<!-- Required, atleast for now since another NuGet package with the SharpEngine.Core name already exists. -->
<PackageId>$(AssemblyName).NET</PackageId>
<Configurations>Debug;Release;LauncherNonWindows</Configurations>

<Configurations>Debug;Release;LauncherNonWindows</Configurations>
</PropertyGroup>

<ItemGroup>
Expand Down
Loading