Moved util files to separate class library

This commit is contained in:
2017-02-26 01:30:27 -05:00
parent 8a68bc6d2d
commit bc584c8f42
15 changed files with 156 additions and 37 deletions

79
Diamond/Buffers/VBO.cs Normal file
View File

@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Diamond.Shaders;
using OpenTK.Graphics.OpenGL4;
namespace Diamond.Buffers
{
public static class VBO
{
public static void Unbind()
{
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
}
}
public class VBO<T> : GLObject where T : struct
{
public VBO()
: base((uint) GL.GenBuffer())
{
}
protected override void Delete()
{
GL.DeleteBuffer(Id);
}
public void Bind()
{
GL.BindBuffer(BufferTarget.ArrayBuffer, Id);
}
public void Data(T[] data, BufferUsageHint usage = BufferUsageHint.StaticDraw)
{
Bind();
var size = Marshal.SizeOf(typeof(T));
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr) (size * data.Length), data, usage);
VBO.Unbind();
}
private static readonly int Stride;
private static readonly VertexPointerAttribute[] Attributes;
static VBO()
{
var attribList = new List<VertexPointerAttribute>();
Stride = Marshal.SizeOf(typeof(T));
foreach (var fieldInfo in typeof(T).GetFields())
{
var attrs = fieldInfo.GetCustomAttributes(typeof(VertexPointerAttribute), false);
if (attrs.Length == 0) continue;
var offset = (int) Marshal.OffsetOf(typeof(T), fieldInfo.Name);
foreach (var attr in attrs)
{
var vpa = (VertexPointerAttribute) attr;
vpa.Offset = offset;
attribList.Add(vpa);
}
}
Attributes = attribList.ToArray();
}
public void AttribPointers(Program pgm)
{
Bind();
foreach (var attr in Attributes)
{
if (!pgm.TryGetAttribute(attr.Name, out int loc)) continue;
GL.VertexAttribPointer(loc, attr.Size, attr.Type, attr.Normalized, Stride, attr.Offset);
GL.VertexAttribDivisor(loc, attr.Divisor);
}
VBO.Unbind();
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
using OpenTK.Graphics.OpenGL4;
namespace Diamond.Buffers
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public sealed class VertexPointerAttribute : Attribute
{
public string Name { get; }
public int Size { get; }
public VertexAttribPointerType Type { get; set; } = VertexAttribPointerType.Float;
public bool Normalized { get; set; } = false;
public int Divisor { get; set; } = 0;
public int Offset { get; set; } = 0;
public VertexPointerAttribute(string name, int size)
{
Name = name;
Size = size;
}
}
}

62
Diamond/Diamond.csproj Normal file
View File

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{59761EB7-87E1-4FF1-808A-18B7BFFF602E}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Diamond</RootNamespace>
<AssemblyName>Diamond</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="OpenTK, Version=2.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL">
<HintPath>..\packages\OpenTK.2.0.0\lib\net20\OpenTK.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="GLObject.cs" />
<Compile Include="Shaders\Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Shaders\Shader.cs" />
<Compile Include="Shaders\ShaderException.cs" />
<Compile Include="Textures\Texture.cs" />
<Compile Include="Buffers\VBO.cs" />
<Compile Include="Buffers\VertexPointerAttribute.cs" />
</ItemGroup>
<ItemGroup>
<None Include="OpenTK.dll.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

33
Diamond/GLObject.cs Normal file
View File

@@ -0,0 +1,33 @@
using System;
namespace Diamond
{
public abstract class GLObject : IDisposable
{
public uint Id { get; protected set; }
protected GLObject(uint id)
{
Id = id;
}
protected abstract void Delete();
private bool _disposed = false;
public void Dispose()
{
if (_disposed) return;
_disposed = true;
Delete();
GC.SuppressFinalize(this);
}
~GLObject()
{
Dispose();
}
public static explicit operator uint(GLObject o) => o.Id;
public static explicit operator int(GLObject o) => (int) o.Id;
}
}

25
Diamond/OpenTK.dll.config Normal file
View File

@@ -0,0 +1,25 @@
<configuration>
<dllmap os="linux" dll="opengl32.dll" target="libGL.so.1"/>
<dllmap os="linux" dll="glu32.dll" target="libGLU.so.1"/>
<dllmap os="linux" dll="openal32.dll" target="libopenal.so.1"/>
<dllmap os="linux" dll="alut.dll" target="libalut.so.0"/>
<dllmap os="linux" dll="opencl.dll" target="libOpenCL.so"/>
<dllmap os="linux" dll="libX11" target="libX11.so.6"/>
<dllmap os="linux" dll="libXi" target="libXi.so.6"/>
<dllmap os="linux" dll="SDL2.dll" target="libSDL2-2.0.so.0"/>
<dllmap os="osx" dll="opengl32.dll" target="/System/Library/Frameworks/OpenGL.framework/OpenGL"/>
<dllmap os="osx" dll="openal32.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" />
<dllmap os="osx" dll="alut.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" />
<dllmap os="osx" dll="libGLES.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
<dllmap os="osx" dll="libGLESv1_CM.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
<dllmap os="osx" dll="libGLESv2.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
<dllmap os="osx" dll="opencl.dll" target="/System/Library/Frameworks/OpenCL.framework/OpenCL"/>
<dllmap os="osx" dll="SDL2.dll" target="libSDL2.dylib"/>
<!-- XQuartz compatibility (X11 on Mac) -->
<dllmap os="osx" dll="libGL.so.1" target="/usr/X11/lib/libGL.dylib"/>
<dllmap os="osx" dll="libX11" target="/usr/X11/lib/libX11.dylib"/>
<dllmap os="osx" dll="libXcursor.so.1" target="/usr/X11/lib/libXcursor.dylib"/>
<dllmap os="osx" dll="libXi" target="/usr/X11/lib/libXi.dylib"/>
<dllmap os="osx" dll="libXinerama" target="/usr/X11/lib/libXinerama.dylib"/>
<dllmap os="osx" dll="libXrandr.so.2" target="/usr/X11/lib/libXrandr.dylib"/>
</configuration>

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Diamond")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Diamond")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("59761eb7-87e1-4ff1-808a-18b7bfff602e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

114
Diamond/Shaders/Program.cs Normal file
View File

@@ -0,0 +1,114 @@
using System.Collections.Generic;
using System.Text;
using OpenTK.Graphics.OpenGL4;
namespace Diamond.Shaders
{
public class Program : GLObject
{
private Dictionary<string, int> uniforms = new Dictionary<string, int>();
private Dictionary<string, int> attributes = new Dictionary<string, int>();
public string Log => GL.GetProgramInfoLog((int) Id);
public Program()
: base((uint) GL.CreateProgram())
{
}
protected override void Delete()
{
GL.DeleteProgram(Id);
}
public void Attach(Shader shader) => GL.AttachShader(Id, shader.Id);
public bool LinkStatus
{
get
{
GL.GetProgram(Id, GetProgramParameterName.LinkStatus, out int success);
return success != 0;
}
}
public bool Link()
{
uniforms.Clear();
attributes.Clear();
GL.LinkProgram(Id);
GL.GetProgram(Id, GetProgramParameterName.LinkStatus, out int success);
if (success == 0) return false;
GL.GetProgram(Id, GetProgramParameterName.ActiveUniforms, out int uniformcount);
for (var i = 0; i < uniformcount; i++)
{
var sb = new StringBuilder(256);
GL.GetActiveUniformName((int) Id, i, sb.Capacity, out int length, sb);
uniforms[sb.ToString()] = i;
}
GL.GetProgram(Id, GetProgramParameterName.ActiveAttributes, out int attributecount);
for (var i = 0; i < attributecount; i++)
{
var sb = new StringBuilder(256);
GL.GetActiveAttrib((int) Id, i, sb.Capacity, out int length, out int size,
out ActiveAttribType type, sb);
attributes[sb.ToString()] = i;
}
return true;
}
public bool TryGetUniform(string name, out int id)
{
return uniforms.TryGetValue(name, out id);
}
public int GetUniform(string name)
{
if (!TryGetUniform(name, out int id))
throw new ShaderException($"Shader Program {Id} does not contain uniform '{name}'");
return id;
}
public bool TryGetAttribute(string name, out int id)
{
return attributes.TryGetValue(name, out id);
}
public int GetAttribute(string name)
{
if (!TryGetAttribute(name, out int id))
throw new ShaderException($"Shader Program {Id} does not contain id '{name}'");
return id;
}
public void EnableAllAttribArrays()
{
foreach (var loc in attributes.Values)
GL.EnableVertexAttribArray(loc);
}
public void DisableAllAttribArrays()
{
foreach (var loc in attributes.Values)
GL.DisableVertexAttribArray(loc);
}
public void Use() => GL.UseProgram(Id);
public static void UseDefault() => GL.UseProgram(0);
public static Program FromShaders(params Shader[] shaders)
{
var p = new Program();
foreach (var shader in shaders)
{
p.Attach(shader);
}
p.Link();
return p;
}
}
}

64
Diamond/Shaders/Shader.cs Normal file
View File

@@ -0,0 +1,64 @@
using System.IO;
using System.Text;
using OpenTK.Graphics.OpenGL4;
namespace Diamond.Shaders
{
public class Shader : GLObject
{
public readonly ShaderType Type;
public string Source
{
get
{
var sb = new StringBuilder(1024);
GL.GetShaderSource(Id, sb.Capacity, out int length, sb);
return sb.ToString();
}
set { GL.ShaderSource((int) Id, value); }
}
public string Log => GL.GetShaderInfoLog((int) Id);
public bool Compiled
{
get
{
GL.GetShader(Id, ShaderParameter.CompileStatus, out int success);
return success != 0;
}
}
public Shader(ShaderType type)
: base((uint) GL.CreateShader(type))
{
Type = type;
}
protected override void Delete()
{
GL.DeleteShader(Id);
}
public bool Compile()
{
GL.CompileShader(Id);
GL.GetShader(Id, ShaderParameter.CompileStatus, out int success);
return success != 0;
}
public static Shader FromFile(string path, ShaderType type)
{
return FromFile(path, type, out bool success);
}
public static Shader FromFile(string path, ShaderType type, out bool success)
{
var s = new Shader(type);
s.Source = File.ReadAllText(path);
success = s.Compile();
return s;
}
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Runtime.Serialization;
namespace Diamond.Shaders
{
[Serializable]
public class ShaderException : Exception
{
public ShaderException()
{
}
public ShaderException(string message)
: base(message)
{
}
public ShaderException(string message, Exception inner)
: base(message, inner)
{
}
protected ShaderException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
}
}

View File

@@ -0,0 +1,72 @@
using System.Drawing;
using System.Drawing.Imaging;
using OpenTK.Graphics.OpenGL4;
using PixelFormat = OpenTK.Graphics.OpenGL4.PixelFormat;
namespace Diamond.Textures
{
public class Texture : GLObject
{
public TextureTarget Target;
public Texture(TextureTarget target = TextureTarget.Texture2D)
: base((uint) GL.GenTexture())
{
Target = target;
}
protected override void Delete()
{
GL.DeleteTexture(Id);
}
public void Bind()
{
GL.BindTexture(Target, Id);
}
public void Bind(TextureUnit unit)
{
GL.ActiveTexture(unit);
Bind();
}
public void Bind(int unit)
{
GL.ActiveTexture(TextureUnit.Texture0 + unit);
Bind();
}
public void Unbind()
{
GL.BindTexture(Target, 0);
}
public void Unbind(TextureUnit unit)
{
GL.ActiveTexture(unit);
Unbind();
}
public void Unbind(int unit)
{
GL.ActiveTexture(TextureUnit.Texture0 + unit);
Unbind();
}
public static Texture FromBitmap(Bitmap bmp)
{
var tex = new Texture(TextureTarget.Texture2D);
tex.Bind();
GL.TexParameter(tex.Target, TextureParameterName.TextureMinFilter, (int) TextureMinFilter.Nearest);
GL.TexParameter(tex.Target, TextureParameterName.TextureMagFilter, (int) TextureMagFilter.Nearest);
var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(tex.Target, 0, PixelInternalFormat.Rgba, bmp.Width, bmp.Height, 0, PixelFormat.Bgra,
PixelType.UnsignedByte, data.Scan0);
bmp.UnlockBits(data);
tex.Unbind();
return tex;
}
}
}

4
Diamond/packages.config Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OpenTK" version="2.0.0" targetFramework="net452" />
</packages>