daily update on 20240513 by nitload youmu, instancing render added

This commit is contained in:
YoumuLiu
2024-05-13 03:39:54 +08:00
parent 56459deec5
commit a3506c96a3
78 changed files with 2562 additions and 1098 deletions
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
@@ -0,0 +1,10 @@
#version 460 core
out vec3 fragColor;
void main()
{
fragColor = vec3( 0.5f,0.336f,0.9961f );
}
@@ -0,0 +1,36 @@
#version 460 core
layout(location = 0) in vec3 singleCoord;
layout(location = 1) in vec3 locations;
layout(location = 2) in float rotation;
layout(location = 3) in float scale;
uniform mat4x4 Camera;
void main()
{
/**/
mat4x4 scalingMat = mat4x4
(
scale,0,0,0,
0,scale,0,0,
0,0,scale,0,
0,0,0,1
);
/**/
/**/
mat4x4 rotationMat = mat4x4
(
cos(rotation),-sin(rotation),0,0,
sin(rotation),cos(rotation),0,0,
0,0,1,0,
0,0,0,1
);
/**/
gl_Position = Camera * ( rotationMat * scalingMat * vec4( singleCoord.xyz , 1) + vec4( locations.xyz , 0));
}
+23
View File
@@ -2614,5 +2614,28 @@ namespace StgSharp.Graphics
internal unsafe delegate*<uint, uint, uint, uint, uint, uint, void> glWriteMaskEXT;
#endregion glapi
public override bool Equals(object obj)
{
return false;
}
public unsafe override int GetHashCode()
{
fixed (GLcontext* sptr = &this)
{
return sptr->GetHashCode();
}
}
public static bool operator ==(GLcontext left, GLcontext right)
{
return left.Equals(right);
}
public static bool operator !=(GLcontext left, GLcontext right)
{
return !(left == right);
}
}
}
+167 -156
View File
@@ -30,169 +30,180 @@
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using System;
namespace StgSharp
{
public enum KeyboardKey : int
{
UNKNOWN = -1,
SPACE = 32,
APOSTROPHE = 39/*'*/,
COMMA = 44/*,*/,
MINUS = 45/*-*/,
PERIOD = 46/*.*/,
SLASH = 47/*/*/,
ZERO = 48,
ONE = 49,
TWO = 50,
THREE = 51,
FOUR = 52,
FIVE = 53,
SIX = 54,
SEVEN = 55,
EIGHT = 56,
NINE = 57,
SEMICOLON = 59/*,*/,
EQUAL = 61/*=*/,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LEFT_BRACKET = 91/*[*/,
BACKSLASH = 92/*\*/,
RIGHT_BRACKET = 93/*]*/,
GRAVE_ACCENT = 96/*`*/,
WORLD_1 = 161/*non-US#1*/,
WORLD_2 = 162/*non-US#2*/,
ESCAPE = 256,
ENTER = 257,
TAB = 258,
BACKSPACE = 259,
INSERT = 260,
DELETE = 261,
RIGHT = 262,
LEFT = 263,
DOWN = 264,
UP = 265,
PAGE_UP = 266,
PAGE_DOWN = 267,
HOME = 268,
END = 269,
CAPS_LOCK = 280,
SCROLL_LOCK = 281,
NUM_LOCK = 282,
PRINT_SCREEN = 283,
PAUSE = 284,
F1 = 290,
F2 = 291,
F3 = 292,
F4 = 293,
F5 = 294,
F6 = 295,
F7 = 296,
F8 = 297,
F9 = 298,
F10 = 299,
F11 = 300,
F12 = 301,
F13 = 302,
F14 = 303,
F15 = 304,
F16 = 305,
F17 = 306,
F18 = 307,
F19 = 308,
F20 = 309,
F21 = 310,
F22 = 311,
F23 = 312,
F24 = 313,
F25 = 314,
KP_0 = 320,
KP_1 = 321,
KP_2 = 322,
KP_3 = 323,
KP_4 = 324,
KP_5 = 325,
KP_6 = 326,
KP_7 = 327,
KP_8 = 328,
KP_9 = 329,
KP_DECIMAL = 330,
KP_DIVIDE = 331,
KP_MULTIPLY = 332,
KP_SUBTRACT = 333,
KP_ADD = 334,
KP_ENTER = 335,
KP_EQUAL = 336,
LEFT_SHIFT = 340,
LEFT_CONTROL = 341,
LEFT_ALT = 342,
LEFT_SUPER = 343,
RIGHT_SHIFT = 344,
RIGHT_CONTROL = 345,
RIGHT_ALT = 346,
RIGHT_SUPER = 347,
MENU = 348
}
{
UNKNOWN = -1,
None = 0,
SPACE = 32,
APOSTROPHE = 39/*'*/,
COMMA = 44/*,*/,
MINUS = 45/*-*/,
PERIOD = 46/*.*/,
SLASH = 47/*/*/,
ZERO = 48,
ONE = 49,
TWO = 50,
THREE = 51,
FOUR = 52,
FIVE = 53,
SIX = 54,
SEVEN = 55,
EIGHT = 56,
NINE = 57,
SEMICOLON = 59/*,*/,
EQUAL = 61/*=*/,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftBracket = 91/*[*/,
BACKSLASH = 92/*\*/,
RightBracket = 93/*]*/,
GraveAccent = 96/*`*/,
World1 = 161/*non-US#1*/,
World2 = 162/*non-US#2*/,
ESCAPE = 256,
ENTER = 257,
TAB = 258,
BACKSPACE = 259,
INSERT = 260,
DELETE = 261,
RIGHT = 262,
LEFT = 263,
DOWN = 264,
UP = 265,
PgUp = 266,
PgDown = 267,
HOME = 268,
END = 269,
CapsLock = 280,
ScrollLock = 281,
NumLock = 282,
PrintScreen = 283,
PAUSE = 284,
F1 = 290,
F2 = 291,
F3 = 292,
F4 = 293,
F5 = 294,
F6 = 295,
F7 = 296,
F8 = 297,
F9 = 298,
F10 = 299,
F11 = 300,
F12 = 301,
F13 = 302,
F14 = 303,
F15 = 304,
F16 = 305,
F17 = 306,
F18 = 307,
F19 = 308,
F20 = 309,
F21 = 310,
F22 = 311,
F23 = 312,
F24 = 313,
F25 = 314,
NumPad0 = 320,
NumPad1 = 321,
NumPad2 = 322,
NumPad3 = 323,
NumPad4 = 324,
NumPad5 = 325,
NumPad6 = 326,
NumPad7 = 327,
NumPad8 = 328,
NumPad9 = 329,
NumPadDec = 330,
NumPadSiv = 331,
NumPadMul = 332,
NumPadSub = 333,
NumPadAdd = 334,
NumPadAnter = 335,
NumPadEqual = 336,
LeftShift = 340,
LeftControl = 341,
LeftAlt = 342,
LeftSuper = 343,
RightShift = 344,
RightControl = 345,
RightAlt = 346,
RightSuper = 347,
Menu = 348
}
#pragma warning disable CA1707
#pragma warning disable CA1712
#pragma warning disable CA1008
[System.Flags]
public enum Joystick : int
{
JOYSTICK_1 = 0,
JOYSTICK_2 = 1,
JOYSTICK_3 = 2,
JOYSTICK_4 = 3,
JOYSTICK_5 = 4,
JOYSTICK_6 = 5,
JOYSTICK_7 = 6,
JOYSTICK_8 = 7,
JOYSTICK_9 = 8,
JOYSTICK_10 = 9,
JOYSTICK_11 = 10,
JOYSTICK_12 = 11,
JOYSTICK_13 = 12,
JOYSTICK_14 = 13,
JOYSTICK_15 = 14,
JOYSTICK_16 = 15,
JOYSTICK_LAST = JOYSTICK_16
}
{
JOYSTICK_1 = 0,
JOYSTICK_2 = 1,
JOYSTICK_3 = 2,
JOYSTICK_4 = 3,
JOYSTICK_5 = 4,
JOYSTICK_6 = 5,
JOYSTICK_7 = 6,
JOYSTICK_8 = 7,
JOYSTICK_9 = 8,
JOYSTICK_10 = 9,
JOYSTICK_11 = 10,
JOYSTICK_12 = 11,
JOYSTICK_13 = 12,
JOYSTICK_14 = 13,
JOYSTICK_15 = 14,
JOYSTICK_16 = 15,
JOYSTICK_LAST = JOYSTICK_16
}
[System.Flags]
public enum Mouse : int
{
BUTTON_1 = 0,
BUTTON_2 = 1,
BUTTON_3 = 2,
BUTTON_4 = 3,
BUTTON_5 = 4,
BUTTON_6 = 5,
BUTTON_7 = 6,
BUTTON_8 = 7,
BUTTON_LAST = BUTTON_8,
BUTTON_LEFT = BUTTON_1,
BUTTON_RIGHT = BUTTON_2,
BUTTON_MIDDLE = BUTTON_3
}
{
BUTTON_1 = 0,
BUTTON_2 = 1,
BUTTON_3 = 2,
BUTTON_4 = 3,
BUTTON_5 = 4,
BUTTON_6 = 5,
BUTTON_7 = 6,
BUTTON_8 = 7,
BUTTON_LAST = BUTTON_8,
BUTTON_LEFT = BUTTON_1,
BUTTON_RIGHT = BUTTON_2,
BUTTON_MIDDLE = BUTTON_3
}
#pragma warning restore CA1707
#pragma warning restore CA1712
#pragma warning restore CA7008
internal enum InputEquipment
{
@@ -10,39 +10,52 @@ namespace StgSharp.Geometries
{
public abstract class ICoord
{
protected Matrix44 coordMat;
protected List<vec4d> pointBuffer;
private Matrix44 coordMat;
private Matrix44 origin;
public ICoord()
{
pointBuffer = new List<vec4d>();
}
public abstract Matrix44 GlobalCoordTransformation
//A matrix can convert vertex to global coord.
public Matrix44 GlobalCoordTransformation
{
get;
get
{
return coordMat * origin;
}
}
public abstract vec3d Origin
public vec3d Origin
{
get;
get => origin.colum3.XYZ;
internal set => origin.colum3.XYZ = value;
}
public abstract vec3d X_axis
public vec3d X_axis
{
get;
get => coordMat.colum0.XYZ;
internal set => coordMat.colum0.XYZ = value;
}
public abstract vec3d Y_axis
public vec3d Y_axis
{
get;
get => coordMat.colum1.XYZ;
internal set => coordMat.colum1.XYZ = value;
}
public abstract vec3d Z_axis
public vec3d Z_axis
{
get;
get => coordMat.colum2.XYZ;
set => coordMat.colum2.XYZ = value;
}
protected ref Matrix44 CoordMat
{
get => ref coordMat;
}
//TODO 几何体构建器需要重写
public T BuildGeometry<T>(params vec4d[] defaultVertex) where T : IGeometry
{
T ret = Activator.CreateInstance<T>();
@@ -0,0 +1,67 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="PlainCoordinate.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Text;
namespace StgSharp.Geometries
{
public class PlainCoordinate : ICoord
{
public PlainCoordinate(
vec3d origin,
vec3d xAxis,
vec3d yAxis
)
{
CoordMat = Matrix44.Unit;
Linear.Orthogonalize(ref xAxis, ref yAxis);
CoordMat.colum0 = new vec4d(xAxis, 0);
CoordMat.colum1 = new vec4d(yAxis, 0);
CoordMat.colum2 = new vec4d(Vec3d.Cross(xAxis, yAxis), 0);
Origin = origin;
}
public new vec3d Z_axis
{
get => Vec3d.Cross(X_axis, Y_axis);
set => throw new InvalidOperationException();
}
}
}
@@ -10,14 +10,5 @@ namespace StgSharp.Geometries
{
public class StreamLocalCoordinate : ICoord
{
public override Matrix44 GlobalCoordTransformation => throw new NotImplementedException();
public override vec3d Origin => Vec3d.Zero;
public override vec3d X_axis => coordMat.colum0.XYZ;
public override vec3d Y_axis => coordMat.colum1.XYZ;
public override vec3d Z_axis => coordMat.colum2.XYZ;
}
}
@@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Math
{
public static partial class GeometryScaler
{
internal const float DegToRad = 180 / Scaler.Pi;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Degree ToDegree(float value)
{
return new Degree(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sin(Radius r)
{
return MathF.Sin(r._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Tan(Radius r)
{
return MathF.Tan(r._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cos(Radius r)
{
return MathF.Cos(r._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sin(Degree r)
{
return MathF.Sin(r._degree/DegToRad);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Tan(Degree r)
{
return MathF.Tan(r._degree / DegToRad);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cos(Degree r)
{
return MathF.Cos(r._degree / DegToRad);
}
}
public struct Degree
{
internal float _degree;
internal Degree(float dgree)
{
_degree = dgree;
}
public static implicit operator Radius(Degree d)
{
return new Radius(d._degree / GeometryScaler.DegToRad);
}
}
public struct Radius
{
internal float _radius;
public static Radius Zero
{
get =>new Radius(0);
}
public Radius(float radius)
{
_radius = radius;
}
[Obsolete("Unsafe, you may forget this is radius.",true)]
public Radius() { }
public static implicit operator Degree(Radius r)
{
return new Degree(r._radius * 180 / Scaler.Pi);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator -(Radius r)
{
return new Radius(-r._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator -(Radius left, Radius Right)
{
return new Radius(left._radius - Right._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator +(Radius left, Radius Right)
{
return new Radius(left._radius + Right._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator *(Radius left, float right)
{
return new Radius(left._radius * right);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator /(Radius left, float right)
{
return new Radius(left._radius / right);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Radius left, Radius right)
{
return left._radius == right._radius;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Radius left, Radius right)
{
return left._radius != right._radius;
}
}
}
@@ -0,0 +1,94 @@
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Geometries
{
public delegate vec3d GeometryMotionDelegate(TimeSpanProvider timeSource, out float rotation);
public class GeometryMotion
{
private bool isIncrementMode;
private bool sourceIsStatic;
private TimeSpanProvider time;
private GeometryMotionDelegate movement;
private IntPtr handle;
public static GeometryMotion DefaultMotion
{
get
{
return new GeometryMotion
(
true,
null,
null
);
}
}
private static vec3d defaultMotion(TimeSpanProvider provider, out float rotation)
{
rotation = 0;
return Vec3d.Zero;
}
public unsafe GeometryMotion(
bool isIncreament,
TimeSpanProvider timeSource,
GeometryMotionDelegate motionDelegate
)
{
isIncrementMode = isIncreament;
time = timeSource;
if (motionDelegate == null)
{
handle = (IntPtr)(delegate*<TimeSpanProvider, out float, vec3d>)&defaultMotion;
movement = defaultMotion;
}
else if (motionDelegate.Method.IsStatic)
{
sourceIsStatic = true;
handle = Marshal.GetFunctionPointerForDelegate(motionDelegate);
movement = motionDelegate;
}
else
{
movement = motionDelegate;
}
}
public bool IsIncrement
{
get => isIncrementMode;
}
public unsafe void RunMotion(ref vec3d coord, ref float rotation)
{
float rot = 0;
if (sourceIsStatic)
{
}
vec3d vec = ((delegate*<TimeSpanProvider, out float, vec3d>)handle)(time, out rot);
if (isIncrementMode)
{
coord += vec;
rotation += rot;
}
else
{
coord = vec.XYZ;
rotation = rot;
}
}
}
}
@@ -40,62 +40,100 @@ using System.Threading.Tasks;
namespace StgSharp.Geometries
{
public interface IInstancing<T> where T : IInstancing<T>
public interface IInstancing<T> where T : IInstancing<T>
{
public int BufferId
{
get;
get;
set;
}
public vec2d CenterPositionGlobal
public vec3d CenterPositionGlobal
{
get;
set;
}
public vec2d Coord
public vec3d Coord
{
get { return new(GlobalBuffer.CoordList[BufferId]); }
set { GlobalBuffer.CoordList[BufferId] = value.vec; }
get { return GlobalBuffer.CoordList[BufferId].XYZ; }
set { GlobalBuffer.CoordList[BufferId] = new vec4d( value.vec); }
}
public PlainInstancingBuffer<T> GlobalBuffer
{
public PlainInstancingBuffer<T> GlobalBuffer
{
get;
internal set;
}
public float Rotation
{
get { return GlobalBuffer.CoordList[BufferId].W; }
set
{
vec4d temp = GlobalBuffer.CoordList[BufferId];
temp.W = value;
GlobalBuffer.CoordList[BufferId] = temp;
}
}
public float Scale
{
get { return GlobalBuffer.ScalingList[BufferId]; }
set { GlobalBuffer.ScalingList[BufferId] = value; }
}
public GeometryMotion Motion
{
get; set;
}
public void Move()
{
(vec3d coord , float rotation) =(Coord, Rotation);
Motion.RunMotion(ref coord, ref rotation);
(Rotation, Coord) = (rotation, coord);
}
}
public class ParticalOnPlain : IInstancing<ParticalOnPlain>
public class ParticleOnPlain : IInstancing<ParticleOnPlain>
{
public int BufferId
{
get;
set;
}
vec2d IInstancing<ParticalOnPlain>.CenterPositionGlobal
public ParticleOnPlain(PlainInstancingBuffer<ParticleOnPlain> buffer)
{
get ;
set ;
if (buffer == null)
{
throw new ArgumentNullException(paramName: nameof(buffer));
}
GlobalBuffer = buffer;
BufferId = buffer.CreateInstanceID();
buffer.InstanceList.Add(this);
}
public PlainInstancingBuffer<ParticalOnPlain> GlobalBuffer
public int BufferId
{
get;
set;
}
public ParticalOnPlain(PlainInstancingBuffer<ParticalOnPlain> buffer)
public PlainInstancingBuffer<ParticleOnPlain> GlobalBuffer
{
GlobalBuffer = buffer;
BufferId = buffer.CreateInstanceID();
get;
set;
}
public GeometryMotion Motion
{
get;
set;
}
vec3d IInstancing<ParticleOnPlain>.CenterPositionGlobal
{
get;
set;
}
}
}
@@ -19,7 +19,7 @@ namespace StgSharp.Geometries
public class PlainEntity:IPlainEntity
{
private PlainGeometry shape;
private PlainGeometry _shape;
vec2d IPlainEntity.CenterPosition
{
@@ -27,6 +27,11 @@ namespace StgSharp.Geometries
set => throw new NotImplementedException();
}
public PlainEntity(PlainGeometry shape)
{
_shape = shape;
}
bool IPlainEntity.CollideWith(IPlainEntity entity)
{
throw new NotImplementedException();
@@ -1,26 +1,81 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="PlainInstancingBuffer.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Geometries
{
public class PlainInstancingBuffer<T> where T : IInstancing<T>
public class PlainInstancingBuffer<T> : IDisposable where T : IInstancing<T>
{
private List<Vector4> coordList;
private List<float> scalingList;
private CoordinatePlain globalCorrdinnate;
private List<vec4d> coordList;
private List<IInstancing<T>> instanceList;
private List<float> scalingList;
private Mutex mutex;
private bool disposedValue;
#region field of mem opt
vec4d[] coordArray;
float[] scaleArray;
#endregion
public PlainInstancingBuffer()
{
coordList = new List<Vector4>();
instanceList = new List<IInstancing<T>>();
scalingList = new List<float>();
coordList = new List<vec4d>(capacity: 100);
instanceList = new List<IInstancing<T>>(capacity:100);
scalingList = new List<float>(capacity: 100);
coordArray = new vec4d[0];
scaleArray = new float[0];
mutex = new Mutex();
}
internal List<Vector4> CoordList
internal List<IInstancing<T>> InstanceList
{
get => instanceList;
}
internal List<vec4d> CoordList
{
get => coordList;
}
@@ -30,34 +85,108 @@ namespace StgSharp.Geometries
get => scalingList;
}
public Span<vec4d> CoordSpan
{
get
{
if (coordArray.Length != coordList.Capacity)
{
FieldInfo fieldInfo = typeof(List<vec4d>).
GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo == null)
{
throw new NullReferenceException();
}
coordArray = (vec4d[])fieldInfo.GetValue(coordList);
}
return new Span<vec4d>(coordArray, 0, coordList.Count);
}
}
public Span<float> ScalingSpan
{
get
{
if (scaleArray.Length != coordList.Capacity)
{
FieldInfo fieldInfo = typeof(List<float>).
GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo == null)
{
throw new NullReferenceException();
}
scaleArray = (float[])fieldInfo.GetValue(scalingList);
}
return new Span<float>(scaleArray, 0, coordList.Count);
}
}
public int CreateInstanceID()
{
mutex.WaitOne();
int ret = instanceList.Count;
coordList.Add(new Vector4());
coordList.Add(new vec4d());
scalingList.Add(0);
mutex.ReleaseMutex();
return ret;
}
public void Remove(T instance)
{
mutex.WaitOne();
if (instance.GlobalBuffer != this)
{
throw new ArgumentException();
throw new ArgumentException(
message:"instance does not belong to current Particle Buffer",
paramName: nameof(instance));
}
int index = instance.BufferId;
IInstancing<T> temp = instanceList[instanceList.Count - 1];
instanceList[instance.BufferId] = temp;
temp.BufferId = instance.BufferId;
coordList[instance.BufferId] = coordList[coordList.Count - 1];
scalingList[instance.BufferId] = scalingList[scalingList.Count - 1];
instanceList.RemoveAt(instanceList.Count - 1);
coordList.RemoveAt(coordList.Count - 1);
scalingList.RemoveAt(scalingList.Count - 1);
mutex.ReleaseMutex();
}
public void UpdateAllParticles()
{
foreach (var particle in instanceList)
{
}
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
mutex.Dispose();
}
coordList.Clear();
instanceList.Clear();
scalingList.Clear();
disposedValue = true;
}
}
// ~PlainInstancingBuffer()
// {
// Dispose(disposing: false);
// }
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
@@ -50,7 +50,10 @@ namespace StgSharp.Geometries
endPoint = new Point(end);
}
public Line() { }
public Line()
{
}
public Line(Point begin, Point end)
{
@@ -59,7 +62,7 @@ namespace StgSharp.Geometries
}
internal override int[] Indices => throw new Exception();
internal override int[] Indices => throw new NotSupportedException();
public override Line[] GetAllSides()
{
@@ -74,18 +77,18 @@ namespace StgSharp.Geometries
/// <summary>
/// Move begin side of a line.
/// It is recommended to override this function rather than
/// loading an <see cref="Func<int,vec3d>"/> with same function.
/// loading an <see cref="Func{T, TResult}"/> with same function.
/// </summary>
/// <param name="tick">Time passed since current line was created.</param>
public virtual vec3d MoveBeginPoint(int tick)
{
return movBegin.Invoke(time);
return movBegin(time);
}
/// <summary>
/// Move end side of a line.
/// It is recommended to override this function rather than
/// loading an <see cref="Func<int,vec3d>"/> with same function.
/// loading an <see cref="Func{T,TResult}"/> with same function.
/// </summary>
/// <param name="tick">Time passed since current line was created.</param>
/// <returns></returns>
@@ -52,7 +52,7 @@ namespace StgSharp.Geometries
v0x, v0y, v0z,
v1x, v1y, v1z,
v2x, v2y, v2z,
v3x, v2y, v3z
v3x, v3y, v3z
)
{
if (
@@ -46,7 +46,7 @@ namespace StgSharp.Geometries
v0x, v0y, v0z,
v1x, v1y, v1z,
v2x, v2y, v2z,
v3x, v2y, v3z
v3x, v3y, v3z
)
{
#if DEBUG
+1 -1
View File
@@ -120,7 +120,7 @@ namespace StgSharp.Graphics
STENCIL = GLconst.STENCIL_BUFFER_BIT,
}
public enum GepmetryType : uint
public enum GeometryType : uint
{
POINTS = 0x0000,
LINES = 0x0001,
+57 -38
View File
@@ -52,46 +52,20 @@ namespace StgSharp.Graphics
private int _frameCount;
private int _frameSpeed;
private short fpsCount;
private IntPtr windowID;
internal LinkedList<Control> allControl;
internal Vector4 backgroundColor;
internal TimeSpanProvider fpsCountProvider;
internal TimeSpanProvider frameTimeProvider;
private short fpsCount;
internal Form sharedForm;
internal int height;
internal IntPtr monitor;
internal string name;
internal Form sharedForm;
internal int width;
internal IntPtr monitor;
public Form()
{
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback =
() =>
{
Interlocked.Exchange(ref _frameSpeed, _frameCount);
Interlocked.Exchange(ref _frameCount, 0);
Console.Clear();
Console.WriteLine(_frameSpeed);
};
frameTimeProvider = new TimeSpanProvider(
1000L * 1000L / 60, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
height = 800;
width = 600;
name = new StackFrame(1, false).
GetMethod()!.DeclaringType!.Name;
}
internal LinkedList<Control> allControl;
internal string name;
internal TimeSpanProvider fpsCountProvider;
internal TimeSpanProvider frameTimeProvider;
internal Vector4 backgroundColor;
protected Form((int width, int height) size, string name)
{
@@ -107,7 +81,7 @@ namespace StgSharp.Graphics
Console.WriteLine(_frameSpeed);
};
frameTimeProvider = new TimeSpanProvider(
1000L * 1000L / 60, TimeSpanProvider.DefaultProvider
(1000L * 1000L) / 60, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
@@ -118,6 +92,32 @@ namespace StgSharp.Graphics
this.name = name;
}
public Form()
{
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback =
() =>
{
Interlocked.Exchange(ref _frameSpeed, _frameCount);
Interlocked.Exchange(ref _frameCount, 0);
Console.Clear();
Console.WriteLine(_frameSpeed);
};
frameTimeProvider = new TimeSpanProvider(
(1000L * 1000L) / 60, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
height = 800;
width = 600;
name = new StackFrame(1, false).
GetMethod()!.DeclaringType!.Name;
}
public int CurrentFrameCount => frameTimeProvider.CurrentSpan;
public int FrameSpeed => _frameSpeed;
@@ -178,13 +178,14 @@ namespace StgSharp.Graphics
public unsafe IntPtr WindowID
{
{
get => windowID;
internal set => windowID = value;
}
internal unsafe IntPtr id => windowID;
#pragma warning disable CA1044
protected FrameBufferSizeHandler FrameSizeCallback
{
set
@@ -193,8 +194,26 @@ namespace StgSharp.Graphics
InternalIO.glfwSetFramebufferSizeCallback(windowID, handlerPtr);
}
}
#pragma warning restore CA1044
#region Key Control
protected KeyStatus CheckKey(KeyboardKey key)
{
return InternalIO.glfwGetKey(this.WindowID,(int)key);
}
protected KeyStatus CheckKey(Mouse key)
{
return InternalIO.glfwGetKey(this.WindowID, (int)key);
}
protected KeyStatus CheckKey(Joystick key)
{
return InternalIO.glfwGetKey(this.WindowID, (int)key);
}
#endregion
/// <summary>
/// Set all necessary metadata to current form instance
@@ -251,9 +270,9 @@ namespace StgSharp.Graphics
/// <param name="maxHeight">Maximum height of current form</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetSizeLimit(int minWidth, int minHeight, int maxWidth, int maxHeight)
{
{
//TODO 重做form的尺寸极限控制
InternalIO.glfwSetWindowSizeLimits(this.windowID, minWidth, minHeight, maxWidth, maxHeight);
InternalIO.glfwSetWindowSizeLimits(this.windowID, minWidth, minHeight, maxWidth, maxHeight);
}
}
+55 -3
View File
@@ -61,7 +61,8 @@ namespace StgSharp.Graphics
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="bufferData">Data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void SetValue<T>(int index, T bufferData, BufferUsage usage) where T : struct, IMat
public void WriteMatrixData<T>(int index, T bufferData, BufferUsage usage)
where T : struct, IMat
{
GL.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
GL.SetBufferData(BufferType.ARRAY_BUFFER, bufferData, usage);
@@ -72,14 +73,65 @@ namespace StgSharp.Graphics
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="bufferArray">A array of data to write in</param>
/// <param name="bufferArray">Data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void SetValueArray<T>(int index, T[] bufferArray, BufferUsage usage) where T : struct, IConvertible
public void WriteScalerData<T>(int index, T[] bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
GL.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
GL.SetBufferData(BufferType.ARRAY_BUFFER, bufferArray, usage);
}
/// <summary>
/// Set data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="scalerSpan">A <see cref="Span{T}"/> of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteScalerData<T>(int index, Span<T> scalerSpan, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
GL.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
GL.SetBufferData(BufferType.ARRAY_BUFFER, scalerSpan, usage);
}
/// <summary>
/// Set data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="vectorSpan">A <see cref="Span{T}"/> of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteVectorData<T>(int index, Span<T> vectorSpan, BufferUsage usage) where T : struct, IVector
{
GL.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
GL.SetBufferVectorData(BufferType.ARRAY_BUFFER, vectorSpan, usage);
}
/// <summary>
/// Set data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="vectorArray">A array of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteVectorData<T>(int index, T[] vectorArray, BufferUsage usage) where T : struct, IVector
{
GL.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
GL.SetBufferVectorData(BufferType.ARRAY_BUFFER, vectorArray, usage);
}
/// <summary>
///
/// </summary>
+137 -2
View File
@@ -28,6 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
@@ -38,6 +39,15 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp
{
internal static unsafe partial class InternalIO
{
[DllImport(SSC_libName, EntryPoint = "glCheckShaderStat",
CallingConvention = CallingConvention.Cdecl)]
internal static extern int glCheckShaderStatus(ref GLcontext context, uint shaderHandle,int key, ref IntPtr logPtr);
}
}
namespace StgSharp.Graphics
{
internal static unsafe partial class GL
@@ -86,6 +96,16 @@ namespace StgSharp.Graphics
Context.glBindBuffer((uint)bufferType, handle.Value);
}
public static string GetShaderStatus(Shader s, int index, int key)
{
IntPtr sptr = IntPtr.Zero;
if (InternalIO.glCheckShaderStatus(ref Context, s.handle[index].Value, key,ref sptr) == 0)
{
return Marshal.PtrToStringAnsi(sptr);
}
return "";
}
/// <summary>
/// Bind a frame buffer to a frame buffer target
/// Same function as <see href="https://docs.gl/gl3/glBindFramebuffer">glBindFramebuffer</see>.
@@ -105,13 +125,18 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindVertexArray(glHandle handle)
{
Context.glBindVertexArray(handle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void VertexAttributeDivisor(uint layoutIndex, uint divisor)
{
Context.glVertexAttribDivisor(layoutIndex, divisor);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Clear(MaskBufferBit mask)
{
@@ -225,7 +250,7 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DrawElements(GepmetryType mode, uint count, TypeCode type, IntPtr ptr)
public static unsafe void DrawElements(GeometryType mode, uint count, TypeCode type, IntPtr ptr)
{
uint a;
switch (type)
@@ -251,6 +276,35 @@ namespace StgSharp.Graphics
Context.glDrawElements((uint)mode, count, a, (void*)ptr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DrawElementsInstanced(
GeometryType mode , uint count, TypeCode type, IntPtr ptr, uint amount
)
{
uint a;
switch (type)
{
case TypeCode.UInt32:
a = GLconst.UNSIGNED_INT;
break;
case TypeCode.UInt16:
a = GLconst.UNSIGNED_SHORT;
break;
case TypeCode.Byte:
a = GLconst.UNSIGNED_BYTE;
break;
default:
InternalIO.InternalWriteLog(
$"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}",
LogType.Error);
return;
}
Context.glDrawElementsInstanced((uint)mode, count, a, (void*)ptr,amount);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Enable(GLOperation operation)
{
@@ -327,9 +381,12 @@ namespace StgSharp.Graphics
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, T bufferData, BufferUsage usage)
where T : struct
{
int size = Marshal.SizeOf<T>();
#pragma warning disable CS8500
T* p = &bufferData;
#pragma warning restore CS8500
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
@@ -339,13 +396,91 @@ namespace StgSharp.Graphics
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = bufferArray)
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, Span<T> bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = &bufferArray.GetPinnableReference())
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferVectorData<T>(BufferType bufferType, Span<T> bufferArray, BufferUsage usage)
where T : struct, IVector
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = &bufferArray.GetPinnableReference())
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferVectorData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
where T : struct, IVector
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = bufferArray)
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
@@ -33,9 +33,11 @@ using StgSharp.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml.Linq;
namespace StgSharp.Graphics
{
@@ -85,6 +87,16 @@ namespace StgSharp.Graphics
GL.AttachShader(target.handle, handle[index]);
}
public static string FromCodeFile(string fileRoute)
{
string str = File.ReadAllText(fileRoute);
if (str == "")
{
throw new Exception($"Cannot load and GLSL code from {fileRoute}");
}
return str;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, string code)
{
@@ -94,6 +106,7 @@ namespace StgSharp.Graphics
}
GL.LoadShaderSource(handle[index], $"{code}\0");
GL.CompileShader(handle[index]);
CheckStatus(index,ShaderStatus.CompileStatus);
}
public override string ToString()
@@ -107,6 +120,15 @@ namespace StgSharp.Graphics
throw new NotImplementedException();
}
public void CheckStatus(int index, ShaderStatus status)
{
string log = GL.GetShaderStatus(this,index, (int)status);
if (log != "")
{
throw new Exception($"Shader Error\n{status}\n" + log);
}
}
public override byte[] GetBytes(out int length)
{
throw new NotImplementedException();
@@ -118,6 +140,11 @@ namespace StgSharp.Graphics
}
}
public enum ShaderStatus : int
{
CompileStatus = GLconst.COMPILE_STATUS,
}
public class ShaderProgram
{
+105 -47
View File
@@ -1,4 +1,34 @@
using StgSharp.Logic;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glRenderStream.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Logic;
using StgSharp.Math;
using System;
@@ -11,12 +41,19 @@ using System.Threading.Tasks;
namespace StgSharp.Graphics
{
public abstract partial class glRenderStream: RenderStream
public abstract partial class glRenderStream : RenderStream
{
protected glRenderStream(RenderStreamConstructArgs args) : base(args)
{
}
protected IntPtr glContextHandle
{
get { return ContextHandle; }
set { ContextHandle = value; }
}
public static T AsMainStreamOf<T>(Form f, (int x, int y, int z) unitCubeSize) where T : glRenderStream
{
RenderStreamConstructArgs args = new RenderStreamConstructArgs();
@@ -30,38 +67,6 @@ namespace StgSharp.Graphics
return ret;
}
protected sealed override void NativeCameraViewTarget(vec3d position, vec3d direction, vec3d up)
{
NativeCamera.SetViewDirection(position, direction, up);
}
protected sealed override Uniform<Matrix44> NativeCameraUniform(ShaderProgram source, string name)
{
NativeCamera.GainAllUniforms(source, name);
return NativeCamera.convertedUniform;
}
protected IntPtr glContextHandle
{
get { return ContextHandle; }
set { ContextHandle = value; }
}
internal unsafe sealed override void CreateCanvas()
{
byte[] nameCode = Encoding.UTF8.GetBytes(name);
CanvasHandle = InternalIO.glfwCreateWindow(
Width,Height,nameCode,Monitor,IntPtr.Zero
);
NativeCamera = new Camera();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override void NativeCameraViewRange(Radius fieldOfRange,vec2d offset, (float frontDepth, float backDepth) viewDepth)
{
NativeCamera.SetViewRange(fieldOfRange,this.Size, offset, viewDepth);
}
/// <summary>
/// Init an OpenGl context if current form has not been binded to any context. and set the context binded to
/// current form as current OpenGL context.
@@ -90,7 +95,25 @@ namespace StgSharp.Graphics
{
InternalIO.glfwSetWindowSizeLimits(this.CanvasHandle, minWidth, minHeight, maxWidth, maxHeight);
}
internal sealed override void InternalInit()
internal override sealed unsafe void CreateCanvas()
{
byte[] nameCode = Encoding.UTF8.GetBytes(name);
CanvasHandle = InternalIO.glfwCreateWindow(
Width, Height, nameCode, Monitor, IntPtr.Zero
);
NativeCamera = new Camera();
}
internal override sealed void InternalDraw(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output)
{
MakeAsCurrentContext();
ProcessInput();
Main(in input, in output);
}
internal override sealed void InternalInit()
{
CreateCanvas();
MakeAsCurrentContext();
@@ -98,21 +121,56 @@ namespace StgSharp.Graphics
Init();
}
internal sealed override void InternalDraw(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output)
{
MakeAsCurrentContext();
ProcessInput();
Main(in input, in output);
InternalIO.glfwSwapBuffers(CanvasHandle);
InternalIO.glfwPollEvents();
}
internal sealed override void InternalTerminate()
internal override sealed void InternalTerminate()
{
Deinit();
}
protected override sealed Uniform<Matrix44> NativeCameraUniform(ShaderProgram source, string name)
{
NativeCamera.GainAllUniforms(source, name);
return NativeCamera.convertedUniform;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override sealed void NativeCameraViewRange(Radius fieldOfRange, vec2d offset, (float frontDepth, float backDepth) viewDepth)
{
NativeCamera.SetViewRange(fieldOfRange, this.Size, offset, viewDepth);
}
protected override sealed void NativeCameraViewTarget(vec3d position, vec3d direction, vec3d up)
{
NativeCamera.SetViewDirection(position, direction, up);
}
protected static void PollEvents()
{
InternalIO.glfwPollEvents();
}
protected void SwapBuffers()
{
InternalIO.glfwSwapBuffers(CanvasHandle);
}
#region Key Control
protected KeyStatus CheckKey(KeyboardKey key)
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
}
protected KeyStatus CheckKey(Mouse key)
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
}
protected KeyStatus CheckKey(Joystick key)
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
}
#endregion
}
}
@@ -52,7 +52,7 @@ namespace StgSharp.Logic
private EndingNode endNode;
private Func<bool> terminate;
private int currentNodeIndex = 0;
private int currentNodeIndex;
private List<Task> allThread;
private List<BlueprintNode> nativeNodeList;
private List<BlueprintNode> nodeList;
+12 -11
View File
@@ -167,9 +167,9 @@ namespace StgSharp.Graphics
_isLookAtAvailable = false;
Linear.Normalize(ref direction, ref up);
Linear.Orthogonalize(ref direction, ref up);
vec3d right = Linear.Normalize(Linear.Cross(up, direction));
vec3d right = Linear.Orthogonalize(Linear.Cross(up, direction));
cameraAtt.colum0.vec = right.vec;
cameraAtt.colum1.vec = up.vec;
@@ -209,12 +209,21 @@ namespace StgSharp.Graphics
Console.WriteLine(Projection);
Console.WriteLine(Projection * View);
Console.WriteLine(View);
foreach (var item in vec)
foreach (vec4d item in vec)
{
Console.Write($"{Projection * View * item};");
}
}
ShaderStruct IglConvertable.GetConvertedGLtype()
{
throw new NotImplementedException();
}
~Camera()
{
}
#region ratation
public void Yaw(Radius r)
@@ -306,14 +315,6 @@ namespace StgSharp.Graphics
#endregion
ShaderStruct IglConvertable.GetConvertedGLtype()
{
throw new NotImplementedException();
}
~Camera()
{
}
}
}
+12
View File
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Math
{
public interface IVector
{
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="matrix2x2.cs"
// file="Matrix22.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
+3 -3
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="matrix2x3.cs"
// file="Matrix23.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -36,13 +36,13 @@ using System.Runtime.InteropServices;
namespace StgSharp.Math
{
[StructLayout(LayoutKind.Explicit, Size = ((3 + 2) * 4 * sizeof(float)) + sizeof(bool), Pack = 16)]
public struct Matrix23:IMat
public struct Matrix23 : IMat
{
[FieldOffset(5 * 4 * sizeof(float))] internal bool isTransposed;
[FieldOffset(3 * 4 * sizeof(float))] internal Mat2 transpose;
[FieldOffset(0)] internal Mat3 mat;
[FieldOffset(3 * 4 * sizeof(float))] internal Mat2 transpose;
internal Matrix23(
Vector4 c0,
+3 -3
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="matrix2x4.cs"
// file="Matrix24.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -36,13 +36,13 @@ using System.Runtime.InteropServices;
namespace StgSharp.Math
{
[StructLayout(LayoutKind.Explicit, Size = ((4 + 2) * 4 * sizeof(float)) + sizeof(bool), Pack = 16)]
public struct Matrix24:IMat
public struct Matrix24 : IMat
{
[FieldOffset(6 * 4 * sizeof(float))] internal bool isTransposed;
[FieldOffset(4 * 4 * sizeof(float))] internal Mat2 transpose;
[FieldOffset(0)] internal Mat4 mat;
[FieldOffset(4 * 4 * sizeof(float))] internal Mat2 transpose;
[FieldOffset(0)] public vec2d Colum0;
[FieldOffset(16)] public vec2d Colum1;
+5 -4
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="matrix3x2.cs"
// file="Matrix32.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -36,16 +36,17 @@ using System.Runtime.InteropServices;
namespace StgSharp.Math
{
[StructLayout(LayoutKind.Explicit, Size = (5 * 4 * sizeof(float)) + sizeof(bool), Pack = 16)]
public struct Matrix32:IMat
public struct Matrix32 : IMat
{
[FieldOffset(0)] internal vec3d colum0;
[FieldOffset(4 * 4)] internal vec3d colum1;
[FieldOffset(5 * 4 * sizeof(float))] internal bool isTransposed;
[FieldOffset(0)] internal Mat2 mat;
[FieldOffset(2 * 4 * sizeof(float))] internal Mat3 transpose;
[FieldOffset(0)] internal vec3d colum0;
[FieldOffset(4 * 4)] internal vec3d colum1;
internal Matrix32(
Vector4 c0,
Vector4 c1
+2 -2
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="matrix3x3.cs"
// file="Matrix33.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -36,7 +36,7 @@ using System.Runtime.InteropServices;
namespace StgSharp.Math
{
[StructLayout(LayoutKind.Explicit, Size = (6 * 4 * sizeof(float)) + sizeof(bool), Pack = 16)]
public struct Matrix33:IMat
public struct Matrix33 : IMat
{
[FieldOffset(6 * 4 * sizeof(float))] internal bool isTransposed;
+3 -3
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="matrix3x4.cs"
// file="Matrix34.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -38,13 +38,13 @@ namespace StgSharp.Math
{
[StructLayout(LayoutKind.Explicit, Size = (7 * 4 * sizeof(float)) + sizeof(bool), Pack = 16)]
public struct Matrix34:IMat
public struct Matrix34 : IMat
{
[FieldOffset(7 * 4 * sizeof(float))] internal bool isTransposed;
[FieldOffset(4 * 4 * sizeof(float))] internal Mat3 transpose;
[FieldOffset(0)] internal Mat4 mat;
[FieldOffset(4 * 4 * sizeof(float))] internal Mat3 transpose;
[FieldOffset(0 * 4 * sizeof(float))] public vec3d Colum0;
[FieldOffset(1 * 4 * sizeof(float))] public vec3d Colum1;
+2 -2
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="matrix4x2.cs"
// file="Matrix42.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -39,7 +39,7 @@ namespace StgSharp.Math
[StructLayout(LayoutKind.Explicit, Size = ((16 + 8) * sizeof(float)) + sizeof(bool), Pack = 16)]
public struct Matrix42:IMat
public struct Matrix42 : IMat
{
[FieldOffset((16 + 8) * sizeof(float))] internal bool isTransposed;
+2 -2
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="matrix4x3.cs"
// file="Matrix43.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -37,7 +37,7 @@ using System.Runtime.InteropServices;
namespace StgSharp.Math
{
[StructLayout(LayoutKind.Explicit, Size = (7 * 4 * sizeof(float)) + sizeof(bool), Pack = 16)]
public struct Matrix43 : IEquatable<Matrix43>,IMat
public struct Matrix43 : IEquatable<Matrix43>, IMat
{
[FieldOffset(7 * 4 * sizeof(float))]
+10 -10
View File
@@ -49,9 +49,9 @@ namespace StgSharp.Math
[FieldOffset(0)] internal Mat4 mat;
[FieldOffset(16 * sizeof(float))] internal Mat4 transpose;
[FieldOffset(0 * sizeof(float))] internal vec4d colum0;
[FieldOffset(4 * sizeof(float))] internal vec4d colum1;
[FieldOffset(8 * sizeof(float))] internal vec4d colum2;
[FieldOffset(0 * sizeof(float))] internal vec4d colum0;
[FieldOffset(4 * sizeof(float))] internal vec4d colum1;
[FieldOffset(8 * sizeof(float))] internal vec4d colum2;
[FieldOffset(12 * sizeof(float))] internal vec4d colum3;
internal Matrix44(Mat4 mat)
@@ -151,6 +151,13 @@ namespace StgSharp.Math
0, 0, 1, 0,
0, 0, 0, 1
);
public static Matrix44 WNegativeUnit
=> new Matrix44(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, -1
);
public static Matrix44 XNegativeUnit
=> new Matrix44(
@@ -174,13 +181,6 @@ namespace StgSharp.Math
0, 0, -1, 0,
0, 0, 0, 1
);
public static Matrix44 WNegativeUnit
=> new Matrix44(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, -1
);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe float Det()
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Linear.Cross.cs"
// file="Vector.Cross.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Linear.GetAngle.cs"
// file="Vector.GetAngle.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Linear.GetLength.cs"
// file="Vector.GetLength.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -0,0 +1,106 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Vector.Orthogonalize.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
internal static partial class InternalIO
{
[DllImport(SSC_libName, EntryPoint = "normalize",
CallingConvention = CallingConvention.Cdecl)]
internal static extern unsafe void Normalize(M128* source, M128* target);
}
}
namespace StgSharp.Math
{
public static partial class Linear
{
public static vec4d Orthogonalize(vec4d vec)
{
return new vec4d { vec = Vector4.Normalize(vec.vec) };
}
public static vec3d Orthogonalize(vec3d vec)
{
return new vec3d { vec = Vector4.Normalize(vec.vec) };
}
public static unsafe void Orthogonalize(ref vec4d source, ref vec4d target)
{
Vector4 s = source.vec;
Vector4 t = target.vec;
s = Vector4.Normalize(s);
float dotProduct = Vector4.Dot(s, t);
Vector4 projection = Vector4.Multiply(s, t);
t -= projection;
source.vec = s;
target.vec = t;
}
/// <summary>
/// Orthogonalize two <see cref="vec3d"/>s, let their length be 1
/// and perpendicular to each other.
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
public static unsafe void Orthogonalize(ref vec3d source, ref vec3d target)
{
Vector3 s = source.v;
Vector3 t = target.v;
s = Vector3.Normalize(s);
Vector3 projection = (Vector3.Dot(t, s) / Vector3.Dot(s, s)) * s;
t -= projection;
t = Vector3.Normalize(t);
source.v = s;
target.v = t;
}
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Linear.VectorTransform.cs"
// file="Vector.VectorTransform.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
+4 -3
View File
@@ -68,6 +68,7 @@ namespace StgSharp
#endregion
#region transpose
@@ -93,9 +94,6 @@ namespace StgSharp.Math
internal struct Mat2 : IEquatable<Mat2>
{
[FieldOffset(0)] internal Vector4 colum0;
[FieldOffset(4 * sizeof(float))] internal Vector4 colum1;
[FieldOffset(0 * sizeof(float))] internal float m00;
[FieldOffset(4 * sizeof(float))] internal float m01;
[FieldOffset(1 * sizeof(float))] internal float m10;
@@ -105,6 +103,9 @@ namespace StgSharp.Math
[FieldOffset(3 * sizeof(float))] internal float m30;
[FieldOffset(7 * sizeof(float))] internal float m31;
[FieldOffset(0)] internal Vector4 colum0;
[FieldOffset(4 * sizeof(float))] internal Vector4 colum1;
internal Mat2(
Vector4 c0,
Vector4 c1
+5 -4
View File
@@ -49,6 +49,7 @@ namespace StgSharp
#endregion
#region transpose
[DllImport(SSC_libName, EntryPoint = "transpose3to4",
@@ -77,10 +78,6 @@ namespace StgSharp.Math
public struct Mat3 : IEquatable<Mat3>, IMat
{
[FieldOffset(0)] internal Vector4 colum0;
[FieldOffset(4 * sizeof(float))] internal Vector4 colum1;
[FieldOffset(8 * sizeof(float))] internal Vector4 colum2;
[FieldOffset(0 * sizeof(float))] internal float m00;
[FieldOffset(4 * sizeof(float))] internal float m01;
@@ -96,6 +93,10 @@ namespace StgSharp.Math
[FieldOffset(7 * sizeof(float))] internal float m31;
[FieldOffset(11 * sizeof(float))] internal float m32;
[FieldOffset(0)] internal Vector4 colum0;
[FieldOffset(4 * sizeof(float))] internal Vector4 colum1;
[FieldOffset(8 * sizeof(float))] internal Vector4 colum2;
public override bool Equals(object? obj)
{
return (obj is Mat3 mat) && Equals(mat);
+6 -4
View File
@@ -36,20 +36,20 @@ namespace StgSharp.Math
{
/// <summary>
/// A two dimension vector defined by two elements.
/// Vec2Ds in StgSharp are defaultly usaed as colum vector.
/// Vec2Ds in StgSharp are default used as colum vector.
/// </summary>
[StructLayout(LayoutKind.Explicit, Size = 16, Pack = 16)]
public struct vec2d
public struct vec2d:IVector
{
[FieldOffset(0)] internal unsafe fixed float num[2];
[FieldOffset(0)]
internal Vector2 v;
[FieldOffset(0)]
internal Vector4 vec;
[FieldOffset(0)] internal unsafe fixed float num[2];
[FieldOffset(0)]
public float X;
[FieldOffset(4)]
@@ -120,6 +120,7 @@ namespace StgSharp.Math
{
return new vec2d(tuple.Item1, tuple.Item2);
}
}
public static class Vec2d
@@ -128,5 +129,6 @@ namespace StgSharp.Math
public static vec2d Unit => new vec2d(1, 1);
public static vec2d Zero => new vec2d(0, 0);
}
}
+33 -34
View File
@@ -40,18 +40,18 @@ using System.Security.AccessControl;
namespace StgSharp.Math
{
[StructLayout(LayoutKind.Explicit, Size = 16, Pack = 16)]
public struct vec3d : IEquatable<vec3d>
public struct vec3d : IEquatable<vec3d>, IVector
{
[FieldOffset(0)] internal unsafe fixed float num[3];
[FieldOffset(0)]
internal M128 reg;
[FieldOffset(0)]
internal Vector3 v;
[FieldOffset(0)]
internal Vector4 vec;
[FieldOffset(0)]
internal M128 reg;
[FieldOffset(0)] internal unsafe fixed float num[3];
[FieldOffset(0)] public float X;
[FieldOffset(4)] public float Y;
@@ -67,6 +67,12 @@ namespace StgSharp.Math
v = vector;
}
public vec3d(vec2d xy, float z)
{
vec = xy.vec;
Z = z;
}
public vec3d(
float x, float y, float z)
{
@@ -76,20 +82,16 @@ namespace StgSharp.Math
v = new Vector3(x, y, z);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public vec3d Cross(vec3d right)
public vec3d XYZ
{
return new vec3d(
(this.Y * right.Z) - (this.Z * right.Y),
(this.X * right.Z) - (this.Z * right.X),
(this.X * right.Y) - (this.Y * right.X)
);
get { return new vec3d(v); }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Dot(vec3d right)
{
return Vector3.Dot(v,right.v);
return Vector3.Dot(v, right.v);
}
public bool Equals(vec3d other)
@@ -178,20 +180,10 @@ namespace StgSharp.Math
return new vec3d(vec.v / value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe implicit operator vec3d((float, float, float) tuple)
{
vec3d v = *(vec3d*)&tuple;
v.vec.W = 0.0f;
return v;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static vec3d operator +(vec3d left, vec3d right)
{
return new vec3d(
left.vec + right.vec
);
return new vec3d(left.vec + right.vec);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -200,17 +192,25 @@ namespace StgSharp.Math
return left.v == right.v;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe implicit operator vec3d((float, float, float) tuple)
{
vec3d v = *(vec3d*)&tuple;
v.vec.W = 0.0f;
return v;
}
}
public static class Vec3d
{
public static bool IsParallel(vec3d left, vec3d right)
{
return Cross(left,right) == Zero;
}
public static vec3d One => new vec3d(1, 1, 1);
public static vec3d UnitX => new vec3d(1, 0, 0);
public static vec3d UnitY => new vec3d(0, 1, 0);
public static vec3d UnitZ => new vec3d(0, 0, 1);
public static vec3d Zero => new vec3d(0, 0, 0);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static vec3d Cross(vec3d left, vec3d right)
@@ -218,11 +218,10 @@ namespace StgSharp.Math
return Linear.Cross(left, right);
}
public static vec3d One => new vec3d(1, 1, 1);
public static vec3d Zero => new vec3d(0, 0, 0);
public static bool IsParallel(vec3d left, vec3d right)
{
return Cross(left, right) == Zero;
}
public static vec3d UnitZ => new vec3d(0, 0, 1);
public static vec3d UnitX => new vec3d(1, 0, 0);
public static vec3d UnitY => new vec3d(0, 1, 0);
}
}
-6
View File
@@ -28,12 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//
//
// some of the code is rewritten from the AMD code:
// https://github.com/amd/aocl-libm-ose/blob/a43e092b03213eb0e129a1cc129900e6e4475778/src/ref/asinf.c
using System;
+39
View File
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Math
{
public static partial class Scaler
{
public static float MaxOf(params float[] stream)
{
float ret = stream[0];
foreach (var num in stream)
{
if (ret < num)
{
ret = num;
}
}
return ret;
}
public static float MinOf(params float[] stream)
{
float ret = stream[0];
foreach (var num in stream)
{
if (ret > num)
{
ret = num;
}
}
return ret;
}
}
}
+1
View File
@@ -35,6 +35,7 @@ namespace StgSharp.Math
{
public static partial class Scaler
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cos(float x)
{
+14 -14
View File
@@ -44,13 +44,7 @@ namespace StgSharp.Math
public static unsafe partial class Scaler
{
internal static float currentSeed
#if DEBUG
= 0.5f;
#else
= Abs(System.DateTime.UtcNow.GetHashCode());
#endif
private static byte[] randomSeed;
/// <summary>
/// returns a random float number between 0 and 1.
@@ -82,8 +76,6 @@ namespace StgSharp.Math
}
private static byte[] randomSeed;
/// <summary>
///
/// </summary>
@@ -94,13 +86,13 @@ namespace StgSharp.Math
,INumber
#endif
{
if (randomSeed==null)
if (randomSeed == null)
{
randomSeed = new byte[64];
var originSeed =
$"{(Assembly.GetEntryAssembly()==null? Assembly.GetAssembly(typeof(StgSharp))!:
Assembly.GetEntryAssembly())}" +
$"{DateTime.UtcNow.ToString("o")}";
string originSeed =
($"{((Assembly.GetEntryAssembly() == null) ? (Assembly.GetAssembly(typeof(StgSharp))!) :
Assembly.GetEntryAssembly())}") +
($"{DateTime.UtcNow.ToString("o")}");
using (SHA256 sha = SHA256.Create())
{
randomSeed = sha.ComputeHash(Encoding.UTF8.GetBytes(originSeed));
@@ -131,5 +123,13 @@ namespace StgSharp.Math
return *(int*)&seedValue;
}
internal static float currentSeed
#if DEBUG
= 0.5f;
#else
= Abs(System.DateTime.UtcNow.GetHashCode());
#endif
}
}
+34 -2
View File
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="SignOf.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
@@ -9,6 +39,7 @@ namespace StgSharp.Math
{
public static unsafe partial class Scaler
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int SignOf(float x)
{
@@ -16,7 +47,7 @@ namespace StgSharp.Math
{
return 0;
}
if (x>0)
if (x > 0)
{
return 1;
}
@@ -35,5 +66,6 @@ namespace StgSharp.Math
}
return -1;
}
}
}
+98
View File
@@ -0,0 +1,98 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Bullet.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the ¡°Software¡±), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ¡°AS IS¡±,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Geometries;
using StgSharp.Math;
using System;
namespace StgSharp.Gaming
{
public abstract class Bullet : IInstancing<Bullet>, IPlainEntity
{
protected Bullet
(
PlainInstancingBuffer<Bullet> buffer,
GeometryMotion movement,
vec2d beginPosition,
float angle,
float scale
)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
GlobalBuffer = buffer;
BufferId = buffer.CreateInstanceID();
((IInstancing<Bullet>)this).Scale = scale;
((IInstancing<Bullet>)this).Coord = new vec3d( beginPosition,0);
((IInstancing<Bullet>)this).Rotation = angle;
Motion = movement;
}
public int BufferId
{
get;
set;
}
public vec2d CenterPosition
{
get;
set;
}
public PlainInstancingBuffer<Bullet> GlobalBuffer
{
get;
set;
}
public GeometryMotion Motion
{
get;
set;
}
vec3d IInstancing<Bullet>.CenterPositionGlobal
{
get;
set;
}
public bool CollideWith(IPlainEntity entity)
{
throw new System.NotImplementedException();
}
}
}
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("StgSharp")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+fc19ab32989e5a60c1061ad8ebea16cd5a3c6ff0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+56459deec57aa5078d6bb5991dbf32f29c06e826")]
[assembly: System.Reflection.AssemblyProductAttribute("StgSharp")]
[assembly: System.Reflection.AssemblyTitleAttribute("StgSharp")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
+12
View File
@@ -7,6 +7,18 @@
GladGLContext* currentContext;
extern char infolog[512] = { 0 };
SSCAPI int SSCDECL glCheckShaderStat(GladGLContext* context,uint64_t shaderHandle , int key, char** logRef)
{
int stat = 0;
context->GetShaderiv(shaderHandle, key, &stat);
if (!stat)
{
context->GetShaderInfoLog(shaderHandle, 512, NULL, infolog);
}
*logRef = infolog;
return stat;
}
SSCAPI void SSCDECL initGL(int majorVersion, int minorVersion)
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, majorVersion);
+3 -2
View File
@@ -20,6 +20,8 @@ extern "C"
{
#endif // _cplusplus
#define byte char
#pragma region Internal
#define ALIGN(simdVec) _mm_loadu_ps(&simdVec)
@@ -36,7 +38,7 @@ extern "C"
typedef char* (*imageLoader)(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels);
SSCAPI char infolog[512];
SSCAPI int SSCDECL glCheckShaderStat(GladGLContext* context, int key, char** logRef);
SSCAPI void SSCDECL initGL(int majorVersion, int minorVersion);
SSCAPI unsigned int SSCDECL linkShaderProgram(GladGLContext* context, GLuint shadertype);
SSCAPI void SSCDECL loadImageData(char* location, Image* out, imageLoader loader);
@@ -46,7 +48,6 @@ extern "C"
//linear related function
SSCAPI __m128* SSCDECL set_m128ptr_default();
#pragma region mat define
@@ -0,0 +1,10 @@
#version 460 core
out vec3 fragColor;
void main()
{
fragColor = vec3( 0.5f,0.336f,0.9961f );
}
@@ -0,0 +1,36 @@
#version 460 core
layout(location = 0) in vec3 singleCoord;
layout(location = 1) in vec3 locations;
layout(location = 2) in float rotation;
layout(location = 3) in float scale;
uniform mat4x4 Camera;
void main()
{
/**/
mat4x4 scalingMat = mat4x4
(
scale,0,0,0,
0,scale,0,0,
0,0,scale,0,
0,0,0,1
);
/**/
/**/
mat4x4 rotationMat = mat4x4
(
cos(rotation),-sin(rotation),0,0,
sin(rotation),cos(rotation),0,0,
0,0,1,0,
0,0,0,1
);
/**/
gl_Position = Camera * ( rotationMat * scalingMat * vec4( singleCoord.xyz , 1) + vec4( locations.xyz , 0));
}
@@ -104,6 +104,12 @@
<None Update="Shader\Image1.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Shader\particle.vert">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Shader\particle.frag">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Shader\vertex.vert">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
@@ -82,8 +82,8 @@ namespace StgSharp
(IntPtr id, uint width, uint height) => GL.Viewport(0, 0, width, height);
shader = CreateShaderProgram();
var vertex = CreateShaderSegment(ShaderType.Vertex, 1);
var fragment = CreateShaderSegment(ShaderType.Fragment, 1);
Shader vertex = CreateShaderSegment(ShaderType.Vertex, 1);
Shader fragment = CreateShaderSegment(ShaderType.Fragment, 1);
vertex.Compile(0, File.ReadAllText("Shader\\vertex.vert"));
vertex.AttachTo(0, shader);
fragment.Compile(0, File.ReadAllText("Shader\\fragment.frag"));
@@ -116,14 +116,19 @@ namespace StgSharp
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f };
GL.BindVertexArray(vao[0]);
vao.Bind(0);
ebo.SetValue(0, rec.Indices, BufferUsage.STATIC_DRAW);
vbo.SetValue(0, rec.VertexBuffer, BufferUsage.STATIC_DRAW);
GL.SetVertexAttribute(0, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
vbo.SetValueArray(1, texCoord, BufferUsage.STATIC_DRAW);
GL.SetVertexAttribute(2, 2, TypeCode.Single, false, 2 * sizeof(float), 0);
vbo.WriteMatrixData(0, rec.VertexBuffer, BufferUsage.STATIC_DRAW);
vao.SetVertexAttribute(0, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
vbo.WriteScalerData(1, texCoord, BufferUsage.STATIC_DRAW);
vao.SetVertexAttribute(2, 2, TypeCode.Single, false, 2 * sizeof(float), 0);
/**/
GL.BindBuffer(BufferType.ARRAY_BUFFER, glHandle.Zero);
vbo.Unbind();
vao.BindNull();
/**/
texture.Bind2D(0);
@@ -191,34 +196,37 @@ namespace StgSharp
//Console.WriteLine(NativeCamera.Projection);
GL.DrawElements(GepmetryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero);
GL.DrawElements(GeometryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero);
vao.BindNull();
/**/
BlueprintPipeline.SkipAll(output);
PollEvents();
SwapBuffers();
}
protected override void ProcessInput()
{
float movement = 0.005f;
if (InternalIO.glfwGetKey(CanvasHandle, (int)KeyboardKey.ESCAPE)
== KeyStatus.PRESS)
{
InternalIO.glfwSetWindowShouldClose(CanvasHandle, 1);
return;
}
if (InternalIO.glfwGetKey(CanvasHandle, (int)KeyboardKey.LEFT_SHIFT)
if (InternalIO.glfwGetKey(CanvasHandle, (int)KeyboardKey.LeftShift)
== KeyStatus.PRESS)
{
movement = 0.002f;
}
if (InternalIO.glfwGetKey(this.CanvasHandle, GLconst.GLFW_KEY_UP) == KeyStatus.PRESS)
if (InternalIO.glfwGetKey(this.CanvasHandle, (int)KeyboardKey.UP) == KeyStatus.PRESS)
{
//Console.WriteLine(8);
NativeCamera.Pitch(new Radius(movement));
}
else if (InternalIO.glfwGetKey(this.CanvasHandle, GLconst.GLFW_KEY_DOWN) == KeyStatus.PRESS)
else if (InternalIO.glfwGetKey(this.CanvasHandle, (int)KeyboardKey.DOWN) == KeyStatus.PRESS)
{
//Console.WriteLine(2);
NativeCamera.Pitch(new Radius(-movement));
+143
View File
@@ -0,0 +1,143 @@
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
public class ParticleStream : glRenderStream
{
public ParticleStream(RenderStreamConstructArgs args) : base(args)
{
}
protected override string[] InputPortsName => ["input_1"];
protected override string[] OutputPortsName => ["output_1"];
protected override void Deinit()
{
throw new NotImplementedException();
}
ShaderProgram s;
PlainInstancingBuffer<ParticleOnPlain> buffer;
VertexBuffer vbo;
VertexArray vao;
ElementBuffer ebo;
protected override void Init()
{
buffer = new PlainInstancingBuffer<ParticleOnPlain>();
for (int i = 0; i < 10; i++)
{
for (int t = 0; t < 10; t++)
{
ParticleOnPlain p = new ParticleOnPlain(buffer);
((IInstancing<ParticleOnPlain>)p).Coord = new vec3d(
(-5 + i) * 0.2f + 0.1f, (-5 + t) * 0.2f + 0.1f, 0);
((IInstancing<ParticleOnPlain>)p).Scale = Scaler.MinOf(i,t) * 0.2f;
((IInstancing<ParticleOnPlain>)p).Motion = GeometryMotion.DefaultMotion;
}
}
SetSizeLimit(800, 800, 800, 800);
FrameSizeCallback =
(IntPtr id, uint width, uint height) => GL.Viewport(0, 0, width, height);
s = CreateShaderProgram();
Shader pvs = CreateShaderSegment(ShaderType.Vertex ,1);
Shader pfs = CreateShaderSegment(ShaderType.Fragment ,1);
pvs.Compile(0, Shader.FromCodeFile("Shader\\particle.vert"));
pvs.AttachTo(0,s);
pfs.Compile(0, Shader.FromCodeFile("Shader\\particle.frag"));
pfs.AttachTo(0,s);
s.Link();
vbo = CreateVertexBuffer(3);
vao = CreateVertexArray(1);
ebo = CreateElementBuffer(1);
vbo.Bind(0);
Rectangle rec = new Rectangle
(
0.05f,0.05f,0.0f,
0.05f,-0.05f,0.0f,
-0.05f,-0.05f,0.0f,
-0.05f,0.05f,0.0f
);
vao.Bind(0);
vbo.WriteMatrixData(0, rec.vertexMat, BufferUsage.STATIC_DRAW);
ebo.SetValue(0, rec.Indices, BufferUsage.STATIC_DRAW);
vao.SetVertexAttribute(0, 3, TypeCode.Single, false, 4 * sizeof(float),0);
vbo.WriteVectorData(1, buffer.CoordSpan,BufferUsage.STATIC_DRAW);
vao.SetVertexAttribute(1, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
vao.SetVertexAttribute(2, 1, TypeCode.Single, false, 4 * sizeof(float), 3 * sizeof(float));
GL.VertexAttributeDivisor(1, 1);
GL.VertexAttributeDivisor(2, 1);
vbo.WriteScalerData(2, buffer.ScalingSpan, BufferUsage.STATIC_DRAW);
vao.SetVertexAttribute(3,1,TypeCode.Single,false,sizeof(float),0);
GL.VertexAttributeDivisor(3, 1);
vbo.Unbind();
vao.BindNull();
NativeCameraViewTarget
(
(0,0,-100),
(0,0,0),
(0,1,0)
);
NativeCameraViewRange(new Degree(1.7f),Vec2d.Zero,(50,50));
NativeCameraUniform(s,"Camera");
}
protected override void Main(in Dictionary<string, BlueprintPipeline> input, in Dictionary<string, BlueprintPipeline> output)
{
GL.ClearColor(0.6f,0.1f,0.3f,1);
GL.Clear(MaskBufferBit.COLOR | MaskBufferBit.DEPTH);
vao.Bind(0);
s.Use();
NativeCamera.SetAllUniforms();
GL.DrawElementsInstanced(
GeometryType.TRIANGLES, 6, TypeCode.UInt32,IntPtr.Zero,100
);
vao.BindNull();
BlueprintPipeline.SkipAll(output);
SwapBuffers();
PollEvents();
}
protected override void ProcessInput()
{
if (CheckKey(KeyboardKey.ESCAPE) == KeyStatus.PRESS)
{
InternalIO.glfwSetWindowShouldClose(CanvasHandle, 1);
}
}
}
}
+4 -4
View File
@@ -35,8 +35,6 @@ namespace StgSharp
{
try
{
InternalIO.InternalWriteLog($"Program Started",LogType.Info);
//StgSharp.TryCreatWindow();
/**/
@@ -47,8 +45,10 @@ namespace StgSharp
demoForm.Size = (800, 800);
demoForm.name = "Hello, Stg#!";
MainRenderStream stream = glRenderStream.AsMainStreamOf
<MainRenderStream>(demoForm,(1,1,1));
var stream = glRenderStream.AsMainStreamOf
//<MainRenderStream>
<ParticleStream>
(demoForm,(1,1,1));
Blueprint blueprint = new Blueprint();
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("StgSharpDebug")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+fc19ab32989e5a60c1061ad8ebea16cd5a3c6ff0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+56459deec57aa5078d6bb5991dbf32f29c06e826")]
[assembly: System.Reflection.AssemblyProductAttribute("StgSharpDebug")]
[assembly: System.Reflection.AssemblyTitleAttribute("StgSharpDebug")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -26,3 +26,5 @@ D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\StgSharp
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\StgSharpDebug\obj\x64\Debug\net6.0\StgSharpDebug.xml
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\StgSharpDebug\obj\x64\Debug\net6.0\StgSharpDebug.pdb
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\StgSharpDebug\obj\x64\Debug\net6.0\StgSharpDebug.genruntimeconfig.cache
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Debug\net6.0\Shader\particle.frag
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Debug\net6.0\Shader\particle.vert
@@ -1 +1 @@
{"documents":{"D:\\NitloadIndustry\\研究项目\\1-Flagship\\TH2020\\ProjectFile\\*":"https://raw.githubusercontent.com/Nitload-NSI/CCD_Github/fc19ab32989e5a60c1061ad8ebea16cd5a3c6ff0/*"}}
{"documents":{"D:\\NitloadIndustry\\研究项目\\1-Flagship\\TH2020\\ProjectFile\\*":"https://raw.githubusercontent.com/Nitload-NSI/CCD_Github/56459deec57aa5078d6bb5991dbf32f29c06e826/*"}}