the big split + mesh pools and views

This commit is contained in:
Dreitone authored and Cameron Ewell committed 2026-02-15 11:12:31 -05:00
1 parent d9dd10f89f
commit a989fc20c2
17 files changed
+3636 -2343

No files matched your search

+14 -6
View File
@@ -100,9 +100,6 @@ namespace CalamityMod.Effects
// Exoblade's melee slash trails. Also used by Terratomere
internal static Asset<Effect> ExobladeSlashShader;
// nanoblack reaper slash effect !!!!
internal static Asset<Effect> NanoblackSlashShader;
// Exoblade's projectile on-hit "anime slash marks". Also used by Terratomere
internal static Asset<Effect> ExobladePierceShader;
@@ -265,6 +262,16 @@ namespace CalamityMod.Effects
internal static Asset<Effect> BrainOfCthulhuForcefield;
#endregion
#region jasper's shaders
// this convention makes no sense and we should stop doing it
// i make this region to conform but i really deeply hate it
// it might be worth getting rid of it mostly in the sourcegen pass
// nanoblack reaper slash effect !!!!
internal static Asset<Effect> NanoblackSlashShader;
#endregion
internal static Asset<Effect> SunkenSeaMenuLogoWater;
@@ -365,9 +372,6 @@ namespace CalamityMod.Effects
ExobladeSlashShader = LoadShader("ExobladeSlashShader");
RegisterMiscShader(ExobladeSlashShader, "TrailPass", "ExobladeSlash");
NanoblackSlashShader = LoadShader("SlashEffects/NanoblackSlash");
RegisterMiscShader(NanoblackSlashShader, "SlashPass", "NanoblackSlash");
ExobladePierceShader = LoadShader("ExobladePierceShader");
RegisterMiscShader(ExobladePierceShader, "PiercePass", "ExobladePierce");
@@ -525,6 +529,10 @@ namespace CalamityMod.Effects
RegisterScreenShader(BrainOfCthulhuForcefield, "BoCShieldPass", "BrainOfCthulhuForcefield");
#endregion
// below shader is by jasper VV do not steal!!!
NanoblackSlashShader = LoadShader("SlashEffects/NanoblackSlash");
RegisterMiscShader(NanoblackSlashShader, "SlashPass", "NanoblackSlash");
SunkenSeaMenuLogoWater = LoadShader("UI/SunkenSeaMenuLogoWater");
}
@@ -0,0 +1,14 @@
Hi, if you are a Calamity addon or other mod dev, do not steal this directory.
I can almost guarantee that you will benefit from a simpler, less feature complete mesh renderer or simple shader.
This system is designed for easy debugging, completeness, correctness, ease of use, and arbitrary reuse.
It is not designed for ease of understanding or compactness. It is unreasonable to expect that you will be able to maintain it as a beginner.
You have been warned.
contact 'undeathlyghost' on discord for more information
notes:
all non-strip meshgen generates correct UVs but incorrect 'distorted' uvs may be desired sometimes for effects
i use 1e-6 as my primary epsilon value in this system, and i suggest you do the same for consistency
it is entirely possible to reuse meshes and you are encouraged to do so rather than reconstructing one if your mesh has no reason to be modified again
pooled meshes are preferred to avoid garbage collection for non-persistent/constantly changing meshes
@@ -0,0 +1,51 @@
#nullable enable
using System;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public readonly struct PooledPrimitiveMesh : IDisposable
{
private readonly PrimitiveMeshCache? _cache;
private readonly VertexPositionColorTexture[]? _textured;
private readonly VertexPositionColor[]? _colored;
private readonly short[] _indices;
internal PooledPrimitiveMesh(
PrimitiveMeshCache cache,
VertexPositionColorTexture[]? textured,
VertexPositionColor[]? colored,
short[] indices,
int vertexCount,
int indexCount,
PrimitiveType primitiveType,
bool usesTexture)
{
_cache = cache;
_textured = textured;
_colored = colored;
_indices = indices ?? throw new ArgumentNullException(nameof(indices));
VertexCount = vertexCount;
IndexCount = indexCount;
PrimitiveType = primitiveType;
UsesTexture = usesTexture;
}
public bool UsesTexture { get; }
public int VertexCount { get; }
public int IndexCount { get; }
public PrimitiveType PrimitiveType { get; }
public VertexPositionColorTexture[] TexturedVertices => _textured ?? throw new InvalidOperationException("Mesh lease does not contain textured vertices.");
public VertexPositionColor[] ColorVertices => _colored ?? throw new InvalidOperationException("Mesh lease does not contain color-only vertices.");
public short[] Indices => _indices;
public PrimitiveMeshView View => UsesTexture
? new PrimitiveMeshView(_textured!, _indices, PrimitiveType, 0, VertexCount, 0, IndexCount)
: new PrimitiveMeshView(_colored!, _indices, PrimitiveType, 0, VertexCount, 0, IndexCount);
public void Dispose()
{
_cache?.Return(_textured, _colored, _indices, UsesTexture);
}
}
@@ -0,0 +1,86 @@
#nullable enable
using System;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public readonly struct PrimitiveMesh
{
private readonly VertexPositionColorTexture[]? _texturedVertices;
private readonly VertexPositionColor[]? _colorVertices;
public PrimitiveMesh(VertexPositionColorTexture[] vertices, short[] indices, PrimitiveType primitiveType)
{
_texturedVertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
_colorVertices = null;
Indices = indices ?? throw new ArgumentNullException(nameof(indices));
PrimitiveType = primitiveType;
if (_texturedVertices.Length == 0 || Indices.Length == 0)
throw new ArgumentException("Mesh must contain vertices and indices.");
if (_texturedVertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
UsesTexture = true;
}
public PrimitiveMesh(VertexPositionColor[] vertices, short[] indices, PrimitiveType primitiveType)
{
_texturedVertices = null;
_colorVertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
Indices = indices ?? throw new ArgumentNullException(nameof(indices));
PrimitiveType = primitiveType;
if (_colorVertices.Length == 0 || Indices.Length == 0)
throw new ArgumentException("Mesh must contain vertices and indices.");
if (_colorVertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
UsesTexture = false;
}
public bool UsesTexture { get; }
public int VertexCount => UsesTexture ? _texturedVertices!.Length : _colorVertices!.Length;
public VertexPositionColorTexture[] TexturedVertices => _texturedVertices ?? throw new InvalidOperationException("Mesh does not contain textured vertices.");
public VertexPositionColor[] ColorVertices => _colorVertices ?? throw new InvalidOperationException("Mesh does not contain color-only vertices.");
public short[] Indices { get; }
public PrimitiveType PrimitiveType { get; }
public bool IsValid => VertexCount > 0 && Indices.Length > 0;
public PrimitiveMeshView AsView()
{
return UsesTexture
? new PrimitiveMeshView(_texturedVertices!, Indices, PrimitiveType, 0, _texturedVertices!.Length, 0, Indices.Length)
: new PrimitiveMeshView(_colorVertices!, Indices, PrimitiveType, 0, _colorVertices!.Length, 0, Indices.Length);
}
public static PrimitiveMesh FromSequential(VertexPositionColorTexture[] vertices, PrimitiveType primitiveType)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length == 0)
throw new ArgumentException("Vertices collection is empty.", nameof(vertices));
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
var indices = new short[vertices.Length];
PrimitiveSimd.FillSequentialIndices(indices.AsSpan());
return new PrimitiveMesh(vertices, indices, primitiveType);
}
public static PrimitiveMesh FromSequential(VertexPositionColor[] vertices, PrimitiveType primitiveType)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length == 0)
throw new ArgumentException("Vertices collection is empty.", nameof(vertices));
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
var indices = new short[vertices.Length];
PrimitiveSimd.FillSequentialIndices(indices.AsSpan());
return new PrimitiveMesh(vertices, indices, primitiveType);
}
}
@@ -0,0 +1,93 @@
#nullable enable
using System;
using System.Buffers;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public sealed class PrimitiveMeshCache
{
public static PrimitiveMeshCache Shared { get; } = new PrimitiveMeshCache();
private readonly ArrayPool<VertexPositionColorTexture> _texturedPool;
private readonly ArrayPool<VertexPositionColor> _colorPool;
private readonly ArrayPool<short> _indexPool;
private readonly bool _clearOnReturn;
public PrimitiveMeshCache(
ArrayPool<VertexPositionColorTexture>? texturedPool = null,
ArrayPool<VertexPositionColor>? colorPool = null,
ArrayPool<short>? indexPool = null,
bool clearOnReturn = false)
{
_texturedPool = texturedPool ?? ArrayPool<VertexPositionColorTexture>.Shared;
_colorPool = colorPool ?? ArrayPool<VertexPositionColor>.Shared;
_indexPool = indexPool ?? ArrayPool<short>.Shared;
_clearOnReturn = clearOnReturn;
}
public PooledPrimitiveMesh RentTextured(int vertexCount, int indexCount, PrimitiveType primitiveType)
{
if (vertexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "You're trying to rent.. nothing?");
if (indexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(indexCount), "You're trying to rent.. nothing?");
if (vertexCount > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Vertex count exceeds index buffer range.");
var vertices = _texturedPool.Rent(vertexCount);
var indices = _indexPool.Rent(indexCount);
return new PooledPrimitiveMesh(this, vertices, null, indices, vertexCount, indexCount, primitiveType, true);
}
public PooledPrimitiveMesh RentColored(int vertexCount, int indexCount, PrimitiveType primitiveType)
{
if (vertexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "You're trying to rent.. nothing?");
if (indexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(indexCount), "You're trying to rent.. nothing?");
if (vertexCount > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Vertex count exceeds index buffer range.");
var vertices = _colorPool.Rent(vertexCount);
var indices = _indexPool.Rent(indexCount);
return new PooledPrimitiveMesh(this, null, vertices, indices, vertexCount, indexCount, primitiveType, false);
}
public PooledPrimitiveMesh RentFromMesh(in PrimitiveMesh mesh)
{
if (!mesh.IsValid)
throw new ArgumentException("Mesh is invalid.", nameof(mesh));
if (mesh.UsesTexture)
{
var lease = RentTextured(mesh.VertexCount, mesh.Indices.Length, mesh.PrimitiveType);
Array.Copy(mesh.TexturedVertices, lease.TexturedVertices, mesh.VertexCount);
Array.Copy(mesh.Indices, lease.Indices, mesh.Indices.Length);
return lease;
}
else
{
var lease = RentColored(mesh.VertexCount, mesh.Indices.Length, mesh.PrimitiveType);
Array.Copy(mesh.ColorVertices, lease.ColorVertices, mesh.VertexCount);
Array.Copy(mesh.Indices, lease.Indices, mesh.Indices.Length);
return lease;
}
}
internal void Return(VertexPositionColorTexture[]? textured, VertexPositionColor[]? colored, short[] indices, bool usesTexture)
{
if (usesTexture)
{
if (textured != null)
_texturedPool.Return(textured, _clearOnReturn);
}
else
{
if (colored != null)
_colorPool.Return(colored, _clearOnReturn);
}
_indexPool.Return(indices, _clearOnReturn);
}
}
@@ -0,0 +1,492 @@
#nullable enable
// 10FEB2026: jasper: you probably don't need this file for casual mesh use.
// you should be careful with mesh transformations, they are intended for advanced users.
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public static class PrimitiveMeshExtensions
{
public static PrimitiveMesh Transform(this in PrimitiveMesh mesh, in Matrix transform)
{
if (!mesh.IsValid)
return mesh;
var indices = (short[])mesh.Indices.Clone();
if (mesh.UsesTexture)
{
var source = mesh.TexturedVertices;
var transformed = new VertexPositionColorTexture[source.Length];
for (int i = 0; i < source.Length; i++)
{
var v = source[i];
transformed[i] = new VertexPositionColorTexture(
Vector3.Transform(v.Position, transform),
v.Color,
v.TextureCoordinate);
}
return new PrimitiveMesh(transformed, indices, mesh.PrimitiveType);
}
{
var source = mesh.ColorVertices;
var transformed = new VertexPositionColor[source.Length];
for (int i = 0; i < source.Length; i++)
{
var v = source[i];
transformed[i] = new VertexPositionColor(
Vector3.Transform(v.Position, transform),
v.Color);
}
return new PrimitiveMesh(transformed, indices, mesh.PrimitiveType);
}
}
public static PrimitiveMesh Translate(this in PrimitiveMesh mesh, in Vector3 offset) =>
mesh.Transform(Matrix.CreateTranslation(offset));
public static PrimitiveMesh Scale(this in PrimitiveMesh mesh, in Vector3 scale) =>
mesh.Transform(Matrix.CreateScale(scale));
public static PrimitiveMesh Rotate(this in PrimitiveMesh mesh, in Quaternion rotation) =>
mesh.Transform(Matrix.CreateFromQuaternion(rotation));
public static PrimitiveMesh Extrude(this in PrimitiveMesh mesh, in Vector3 direction, bool closeCaps = true)
{
if (!mesh.IsValid)
throw new InvalidOperationException("Cannot extrude an invalid mesh.");
if (mesh.PrimitiveType != PrimitiveType.TriangleList)
throw new NotSupportedException("Extrusion currently supports triangle list meshes only.");
if (direction.LengthSquared() <= 1e-6f)
return mesh;
return mesh.UsesTexture
? ExtrudeTextured(mesh, direction, closeCaps)
: ExtrudeColored(mesh, direction, closeCaps);
}
private static PrimitiveMesh ExtrudeTextured(in PrimitiveMesh mesh, Vector3 direction, bool closeCaps)
{
var top = mesh.TexturedVertices;
var baseIndices = mesh.Indices;
int originalVertexCount = top.Length;
var vertices = new List<VertexPositionColorTexture>(originalVertexCount * 2);
vertices.AddRange(top);
for (int i = 0; i < originalVertexCount; i++)
{
var v = top[i];
vertices.Add(new VertexPositionColorTexture(
v.Position + direction,
v.Color,
v.TextureCoordinate));
}
var indices = new List<short>(closeCaps ? baseIndices.Length * 2 : baseIndices.Length + originalVertexCount * 6);
indices.AddRange(baseIndices);
if (closeCaps)
{
for (int i = 0; i < baseIndices.Length; i += 3)
{
short a = (short)(baseIndices[i] + originalVertexCount);
short b = (short)(baseIndices[i + 1] + originalVertexCount);
short c = (short)(baseIndices[i + 2] + originalVertexCount);
indices.Add(c);
indices.Add(b);
indices.Add(a);
}
}
var positions = new Vector3[originalVertexCount];
for (int i = 0; i < originalVertexCount; i++)
positions[i] = top[i].Position;
var loops = BuildBoundaryLoops(positions, baseIndices);
foreach (var loop in loops)
{
float perimeter = 0f;
for (int i = 0; i < loop.Count; i++)
perimeter += loop[i].Length;
if (perimeter <= 1e-6f)
continue;
float accumulated = 0f;
foreach (var edge in loop)
{
float u0 = accumulated / perimeter;
accumulated += edge.Length;
float u1 = accumulated / perimeter;
var startTop = top[edge.Start];
var endTop = top[edge.End];
var startBottomPos = startTop.Position + direction;
var endBottomPos = endTop.Position + direction;
short topStartIndex = AddVertex(vertices, new VertexPositionColorTexture(startTop.Position, startTop.Color, new Vector2(u0, 0f)));
short bottomStartIndex = AddVertex(vertices, new VertexPositionColorTexture(startBottomPos, startTop.Color, new Vector2(u0, 1f)));
short topEndIndex = AddVertex(vertices, new VertexPositionColorTexture(endTop.Position, endTop.Color, new Vector2(u1, 0f)));
short bottomEndIndex = AddVertex(vertices, new VertexPositionColorTexture(endBottomPos, endTop.Color, new Vector2(u1, 1f)));
indices.Add(topStartIndex);
indices.Add(topEndIndex);
indices.Add(bottomEndIndex);
indices.Add(topStartIndex);
indices.Add(bottomEndIndex);
indices.Add(bottomStartIndex);
}
}
return new PrimitiveMesh(vertices.ToArray(), indices.ToArray(), PrimitiveType.TriangleList);
}
private static PrimitiveMesh ExtrudeColored(in PrimitiveMesh mesh, Vector3 direction, bool closeCaps)
{
var top = mesh.ColorVertices;
var baseIndices = mesh.Indices;
int originalVertexCount = top.Length;
var vertices = new List<VertexPositionColor>(originalVertexCount * 2);
vertices.AddRange(top);
for (int i = 0; i < originalVertexCount; i++)
{
var v = top[i];
vertices.Add(new VertexPositionColor(v.Position + direction, v.Color));
}
var indices = new List<short>(closeCaps ? baseIndices.Length * 2 : baseIndices.Length + originalVertexCount * 6);
indices.AddRange(baseIndices);
if (closeCaps)
{
for (int i = 0; i < baseIndices.Length; i += 3)
{
short a = (short)(baseIndices[i] + originalVertexCount);
short b = (short)(baseIndices[i + 1] + originalVertexCount);
short c = (short)(baseIndices[i + 2] + originalVertexCount);
indices.Add(c);
indices.Add(b);
indices.Add(a);
}
}
var positions = new Vector3[originalVertexCount];
for (int i = 0; i < originalVertexCount; i++)
positions[i] = top[i].Position;
var loops = BuildBoundaryLoops(positions, baseIndices);
foreach (var loop in loops)
{
float perimeter = 0f;
for (int i = 0; i < loop.Count; i++)
perimeter += loop[i].Length;
if (perimeter <= 1e-6f)
continue;
float accumulated = 0f;
foreach (var edge in loop)
{
float u0 = accumulated / perimeter;
accumulated += edge.Length;
float u1 = accumulated / perimeter;
var startTop = top[edge.Start];
var endTop = top[edge.End];
var startBottomPos = startTop.Position + direction;
var endBottomPos = endTop.Position + direction;
short topStartIndex = AddVertex(vertices, new VertexPositionColor(startTop.Position, startTop.Color));
short bottomStartIndex = AddVertex(vertices, new VertexPositionColor(startBottomPos, startTop.Color));
short topEndIndex = AddVertex(vertices, new VertexPositionColor(endTop.Position, endTop.Color));
short bottomEndIndex = AddVertex(vertices, new VertexPositionColor(endBottomPos, endTop.Color));
indices.Add(topStartIndex);
indices.Add(topEndIndex);
indices.Add(bottomEndIndex);
indices.Add(topStartIndex);
indices.Add(bottomEndIndex);
indices.Add(bottomStartIndex);
}
}
return new PrimitiveMesh(vertices.ToArray(), indices.ToArray(), PrimitiveType.TriangleList);
}
public static PrimitiveMesh CurveEdges(this in PrimitiveMesh mesh, in Vector3 axis, float magnitude, float exponent = 2f)
{
if (!mesh.IsValid)
return mesh;
if (axis.LengthSquared() <= 1e-6f)
throw new ArgumentException("Axis must be non-zero.", nameof(axis));
if (mesh.PrimitiveType != PrimitiveType.TriangleList && mesh.PrimitiveType != PrimitiveType.TriangleStrip)
throw new NotSupportedException("CurveEdges supports triangle-based meshes.");
float clampedExponent = Math.Max(exponent, 1e-3f);
Vector3 axisDir = Vector3.Normalize(axis);
var indices = (short[])mesh.Indices.Clone();
if (mesh.UsesTexture)
{
var source = mesh.TexturedVertices;
var vertices = new VertexPositionColorTexture[source.Length];
ComputeCentroidAndRadius(source, out var centroid, out float radius);
for (int i = 0; i < source.Length; i++)
{
var v = source[i];
Vector3 diff = v.Position - centroid;
float radial = radius <= 1e-6f ? 0f : diff.Length() / radius;
float factor = MathF.Pow(MathHelper.Clamp(radial, 0f, 1f), clampedExponent);
Vector3 offset = axisDir * magnitude * factor;
vertices[i] = new VertexPositionColorTexture(v.Position + offset, v.Color, v.TextureCoordinate);
}
return new PrimitiveMesh(vertices, indices, mesh.PrimitiveType);
}
else
{
var source = mesh.ColorVertices;
var vertices = new VertexPositionColor[source.Length];
ComputeCentroidAndRadius(source, out var centroid, out float radius);
for (int i = 0; i < source.Length; i++)
{
var v = source[i];
Vector3 diff = v.Position - centroid;
float radial = radius <= 1e-6f ? 0f : diff.Length() / radius;
float factor = MathF.Pow(MathHelper.Clamp(radial, 0f, 1f), clampedExponent);
Vector3 offset = axisDir * magnitude * factor;
vertices[i] = new VertexPositionColor(v.Position + offset, v.Color);
}
return new PrimitiveMesh(vertices, indices, mesh.PrimitiveType);
}
}
private static void ComputeCentroidAndRadius(VertexPositionColorTexture[] vertices, out Vector3 centroid, out float radius)
{
centroid = Vector3.Zero;
for (int i = 0; i < vertices.Length; i++)
centroid += vertices[i].Position;
centroid /= vertices.Length;
radius = 1e-6f;
for (int i = 0; i < vertices.Length; i++)
{
float length = Vector3.Distance(centroid, vertices[i].Position);
if (length > radius)
radius = length;
}
}
private static void ComputeCentroidAndRadius(VertexPositionColor[] vertices, out Vector3 centroid, out float radius)
{
centroid = Vector3.Zero;
for (int i = 0; i < vertices.Length; i++)
centroid += vertices[i].Position;
centroid /= vertices.Length;
radius = 1e-6f;
for (int i = 0; i < vertices.Length; i++)
{
float length = Vector3.Distance(centroid, vertices[i].Position);
if (length > radius)
radius = length;
}
}
/// <summary>
/// Builds boundary loops from a triangle list.
/// Each loop is a sequence of connected boundary edges that form a closed path along the mesh surface.
/// Loops are returned in no particular order, and may be nested or intersecting.
/// Edges are oriented consistently within each loop, but not across different loops.
/// Only zero-length edges are discarded, and loops must close to be included.
/// </summary>
/// <param name="positions">Vertex positions for the mesh.</param>
/// <param name="indices">Triangle-list indices (groups of 3).</param>
/// <returns>Closed boundary loops built from boundary edges.</returns>
private static List<List<OrientedEdge>> BuildBoundaryLoops(IReadOnlyList<Vector3> positions, short[] indices)
{
var edgeMap = new Dictionary<EdgeKey, EdgeAccumulator>();
for (int i = 0; i < indices.Length; i += 3)
{
RegisterEdge(edgeMap, indices[i], indices[i + 1]);
RegisterEdge(edgeMap, indices[i + 1], indices[i + 2]);
RegisterEdge(edgeMap, indices[i + 2], indices[i]);
}
var edges = new List<OrientedEdge>();
foreach (var pair in edgeMap)
{
if (pair.Value.Count == 1)
{
var oriented = pair.Value.Orientation;
float length = Vector3.Distance(positions[oriented.Start], positions[oriented.End]);
if (length > 1e-6f)
edges.Add(new OrientedEdge(oriented.Start, oriented.End, length));
}
}
var loops = new List<List<OrientedEdge>>();
var used = new bool[edges.Count];
for (int i = 0; i < edges.Count; i++)
{
if (used[i])
continue;
var loop = new List<OrientedEdge>();
used[i] = true;
loop.Add(edges[i]);
short head = edges[i].End;
bool closed = head == loop[0].Start;
while (!closed)
{
bool found = false;
for (int j = 0; j < edges.Count; j++)
{
if (used[j])
continue;
var candidate = edges[j];
if (candidate.Start == head)
{
used[j] = true;
loop.Add(candidate);
head = candidate.End;
found = true;
}
else if (candidate.End == head)
{
candidate = candidate.Reversed();
edges[j] = candidate;
used[j] = true;
loop.Add(candidate);
head = candidate.End;
found = true;
}
if (found)
{
closed = head == loop[0].Start;
break;
}
}
if (!found)
break;
}
if (loop.Count > 1 && closed)
loops.Add(loop);
}
return loops;
}
private static void RegisterEdge(Dictionary<EdgeKey, EdgeAccumulator> edgeMap, short start, short end)
{
var key = new EdgeKey(Math.Min(start, end), Math.Max(start, end));
if (edgeMap.TryGetValue(key, out var accumulator))
{
accumulator.Count++;
edgeMap[key] = accumulator;
}
else
{
edgeMap[key] = new EdgeAccumulator
{
Count = 1,
Orientation = new OrientedEdge(start, end, 0f)
};
}
}
/// <summary>
/// Adds a vertex to the list and returns its index. Most likely, you do not need to use this directly.
/// </summary>
/// <param name="vertices">The vertex list to add to.</param>
/// <param name="vertex">The vertex to add.</param>
private static short AddVertex(List<VertexPositionColorTexture> vertices, VertexPositionColorTexture vertex)
{
if (vertices.Count >= short.MaxValue)
throw new InvalidOperationException("Primitive mesh exceeded 16-bit vertex capacity.");
vertices.Add(vertex);
return (short)(vertices.Count - 1);
}
/// <summary>
/// Adds a vertex to the list and returns its index. Most likely, you do not need to use this directly.
/// </summary>
/// <param name="vertices">The vertex list to add to.</param>
/// <param name="vertex">The vertex to add.</param>
private static short AddVertex(List<VertexPositionColor> vertices, VertexPositionColor vertex)
{
if (vertices.Count >= short.MaxValue)
throw new InvalidOperationException("Primitive mesh exceeded 16-bit vertex capacity.");
vertices.Add(vertex);
return (short)(vertices.Count - 1);
}
private readonly struct EdgeKey : IEquatable<EdgeKey>
{
public readonly short Min;
public readonly short Max;
public EdgeKey(short min, short max)
{
Min = min;
Max = max;
}
public bool Equals(EdgeKey other) => Min == other.Min && Max == other.Max;
public override bool Equals(object? obj) => obj is EdgeKey other && Equals(other);
public override int GetHashCode()
{
unchecked
{
return (Min * 397) ^ Max;
}
}
}
private struct EdgeAccumulator
{
public int Count;
public OrientedEdge Orientation;
}
private struct OrientedEdge
{
public short Start;
public short End;
public float Length;
public OrientedEdge(short start, short end, float length)
{
Start = start;
End = end;
Length = length;
}
public OrientedEdge Reversed() => new OrientedEdge(End, Start, Length);
}
}
@@ -0,0 +1,87 @@
#nullable enable
using System;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public readonly struct PrimitiveMeshView
{
private readonly VertexPositionColorTexture[]? _texturedVertices;
private readonly VertexPositionColor[]? _colorVertices;
public PrimitiveMeshView(
VertexPositionColorTexture[] vertices,
short[] indices,
PrimitiveType primitiveType,
int vertexOffset,
int vertexCount,
int indexOffset,
int indexCount)
{
_texturedVertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
_colorVertices = null;
Indices = indices ?? throw new ArgumentNullException(nameof(indices));
PrimitiveType = primitiveType;
ValidateRanges(vertices.Length, indices.Length, vertexOffset, vertexCount, indexOffset, indexCount);
VertexOffset = vertexOffset;
VertexCount = vertexCount;
IndexOffset = indexOffset;
IndexCount = indexCount;
UsesTexture = true;
}
public PrimitiveMeshView(
VertexPositionColor[] vertices,
short[] indices,
PrimitiveType primitiveType,
int vertexOffset,
int vertexCount,
int indexOffset,
int indexCount)
{
_texturedVertices = null;
_colorVertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
Indices = indices ?? throw new ArgumentNullException(nameof(indices));
PrimitiveType = primitiveType;
ValidateRanges(vertices.Length, indices.Length, vertexOffset, vertexCount, indexOffset, indexCount);
VertexOffset = vertexOffset;
VertexCount = vertexCount;
IndexOffset = indexOffset;
IndexCount = indexCount;
UsesTexture = false;
}
public bool UsesTexture { get; }
public int VertexOffset { get; }
public int VertexCount { get; }
public int IndexOffset { get; }
public int IndexCount { get; }
public PrimitiveType PrimitiveType { get; }
public bool IsValid => VertexCount > 0 && IndexCount > 0;
public VertexPositionColorTexture[] TexturedVertices => _texturedVertices ?? throw new InvalidOperationException("Mesh view does not contain textured vertices.");
public VertexPositionColor[] ColorVertices => _colorVertices ?? throw new InvalidOperationException("Mesh view does not contain color-only vertices.");
public short[] Indices { get; }
private static void ValidateRanges(int vertexArrayLength, int indexArrayLength, int vertexOffset, int vertexCount, int indexOffset, int indexCount)
{
if (vertexOffset < 0)
throw new ArgumentOutOfRangeException(nameof(vertexOffset));
if (vertexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(vertexCount));
if (indexOffset < 0)
throw new ArgumentOutOfRangeException(nameof(indexOffset));
if (indexCount <= 0)
throw new ArgumentOutOfRangeException(nameof(indexCount));
if (vertexOffset + vertexCount > vertexArrayLength)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Vertex range exceeds the vertex buffer length.");
if (indexOffset + indexCount > indexArrayLength)
throw new ArgumentOutOfRangeException(nameof(indexCount), "Index range exceeds the index buffer length.");
if (vertexCount > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertexCount), "Vertex count exceeds index buffer range.");
}
}
@@ -0,0 +1,23 @@
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Graphics.Primitives;
public sealed class PrimitiveRenderSystem : ModSystem
{
public override void Load()
{
if (Main.dedServ)
return;
Main.QueueMainThreadAction(() =>
{
SanePrimitiveRenderer.Initialize();
});
}
public override void Unload()
{
SanePrimitiveRenderer.Dispose();
}
}
@@ -0,0 +1,503 @@
#nullable enable
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Graphics.Primitives;
public static class PrimitiveShapeBuilder
{
public static PrimitiveMesh BuildRectangularQuad(
Vector3 center,
Vector2 size,
Color color,
Vector3 normal,
Vector3 upHint,
bool textured = false)
{
BuildFrame(normal, upHint, out var right, out var up);
var halfRight = right * (size.X * 0.5f);
var halfUp = up * (size.Y * 0.5f);
if (textured)
{
var vertices = new[]
{
new VertexPositionColorTexture(center - halfRight - halfUp, color, new Vector2(0f, 1f)),
new VertexPositionColorTexture(center + halfRight - halfUp, color, new Vector2(1f, 1f)),
new VertexPositionColorTexture(center + halfRight + halfUp, color, new Vector2(1f, 0f)),
new VertexPositionColorTexture(center - halfRight + halfUp, color, new Vector2(0f, 0f))
};
var indices = new short[] { 0, 1, 2, 0, 2, 3 };
return new PrimitiveMesh(vertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new[]
{
new VertexPositionColor(center - halfRight - halfUp, color),
new VertexPositionColor(center + halfRight - halfUp, color),
new VertexPositionColor(center + halfRight + halfUp, color),
new VertexPositionColor(center - halfRight + halfUp, color)
};
var colorIndices = new short[] { 0, 1, 2, 0, 2, 3 };
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
/// <summary>
/// Builds a regular polygon with the specified number of sides, centered at the given position, and oriented according to the normal and up hint.
/// The polygon is constructed in a single triangle fan, with the center vertex as the first element and subsequent vertices arranged in a clockwise order around the normal.
/// If you need a different vertex order or a more complex polygon, consider <see cref="BuildArbitraryPolygon(IReadOnlyList{Vector3}, Color, bool)"/>
/// </summary>
/// <param name="center"></param>
/// <param name="radius"></param>
/// <param name="sides"></param>
/// <param name="color"></param>
/// <param name="normal"></param>
/// <param name="upHint"></param>
/// <param name="textured"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static PrimitiveMesh BuildRegularPolygon(
Vector3 center,
float radius,
int sides,
Color color,
Vector3 normal,
Vector3 upHint,
bool textured = false)
{
if (sides < 3)
throw new ArgumentOutOfRangeException(nameof(sides), "Polygon requires at least three sides.");
BuildFrame(normal, upHint, out var right, out var up);
if (textured)
{
var texturedVertices = new VertexPositionColorTexture[sides + 1];
texturedVertices[0] = new VertexPositionColorTexture(center, color, new Vector2(0.5f, 0.5f));
float safeRadius = Math.Max(radius, 1e-6f);
for (int i = 0; i < sides; i++)
{
var direction = PolarToCartesian(i, sides, right, up) * radius;
var point = center + direction;
float u = 0.5f + 0.5f * MathHelper.Clamp(Vector3.Dot(direction, right) / safeRadius, -1f, 1f);
float v = 0.5f - 0.5f * MathHelper.Clamp(Vector3.Dot(direction, up) / safeRadius, -1f, 1f);
texturedVertices[i + 1] = new VertexPositionColorTexture(point, color, new Vector2(u, v));
}
var indices = new short[sides * 3];
for (int i = 0; i < sides; i++)
{
int next = (i + 1) % sides;
int baseIndex = i * 3;
indices[baseIndex] = 0;
indices[baseIndex + 1] = (short)(i + 1);
indices[baseIndex + 2] = (short)(next + 1);
}
return new PrimitiveMesh(texturedVertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[sides + 1];
colorVertices[0] = new VertexPositionColor(center, color);
for (int i = 0; i < sides; i++)
{
var direction = PolarToCartesian(i, sides, right, up) * radius;
colorVertices[i + 1] = new VertexPositionColor(center + direction, color);
}
var colorIndices = new short[sides * 3];
for (int i = 0; i < sides; i++)
{
int next = (i + 1) % sides;
int baseIndex = i * 3;
colorIndices[baseIndex] = 0;
colorIndices[baseIndex + 1] = (short)(i + 1);
colorIndices[baseIndex + 2] = (short)(next + 1);
}
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
public static PrimitiveMesh BuildArbitraryPolygon(IReadOnlyList<Vector3> points, Color color, bool textured = false)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
if (points.Count < 3)
throw new ArgumentOutOfRangeException(nameof(points), "Polygon requires at least three points.");
if (textured)
{
float minX = points[0].X, maxX = points[0].X;
float minY = points[0].Y, maxY = points[0].Y;
for (int i = 1; i < points.Count; i++)
{
var p = points[i];
if (p.X < minX) minX = p.X;
if (p.X > maxX) maxX = p.X;
if (p.Y < minY) minY = p.Y;
if (p.Y > maxY) maxY = p.Y;
}
float width = Math.Max(maxX - minX, 1e-6f);
float height = Math.Max(maxY - minY, 1e-6f);
var texturedVertices = new VertexPositionColorTexture[points.Count];
for (int i = 0; i < points.Count; i++)
{
var point = points[i];
float u = (point.X - minX) / width;
float v = (point.Y - minY) / height;
texturedVertices[i] = new VertexPositionColorTexture(point, color, new Vector2(u, v));
}
var indices = new short[(points.Count - 2) * 3];
for (int i = 0; i < points.Count - 2; i++)
{
indices[i * 3] = 0;
indices[i * 3 + 1] = (short)(i + 1);
indices[i * 3 + 2] = (short)(i + 2);
}
return new PrimitiveMesh(texturedVertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[points.Count];
for (int i = 0; i < points.Count; i++)
{
var point = points[i];
colorVertices[i] = new VertexPositionColor(point, color);
}
var colorIndices = new short[(points.Count - 2) * 3];
for (int i = 0; i < points.Count - 2; i++)
{
colorIndices[i * 3] = 0;
colorIndices[i * 3 + 1] = (short)(i + 1);
colorIndices[i * 3 + 2] = (short)(i + 2);
}
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
public static PrimitiveMesh BuildEllipse(
Vector3 center,
Vector2 radii,
int segments,
Color color,
Vector3 normal,
Vector3 upHint,
bool textured = false)
{
if (segments < 3)
throw new ArgumentOutOfRangeException(nameof(segments), "Ellipse requires at least three segments.");
BuildFrame(normal, upHint, out var right, out var up);
if (textured)
{
var vertices = new VertexPositionColorTexture[segments + 1];
vertices[0] = new VertexPositionColorTexture(center, color, new Vector2(0.5f, 0.5f));
float safeX = Math.Max(radii.X, 1e-6f);
float safeY = Math.Max(radii.Y, 1e-6f);
for (int i = 0; i < segments; i++)
{
var offset = EllipseDirection(i, segments, right, up, radii);
var point = center + offset;
float u = 0.5f + 0.5f * MathHelper.Clamp(Vector3.Dot(offset, right) / safeX, -1f, 1f);
float v = 0.5f - 0.5f * MathHelper.Clamp(Vector3.Dot(offset, up) / safeY, -1f, 1f);
vertices[i + 1] = new VertexPositionColorTexture(point, color, new Vector2(u, v));
}
var indices = new short[segments * 3];
for (int i = 0; i < segments; i++)
{
int next = (i + 1) % segments;
int baseIndex = i * 3;
indices[baseIndex] = 0;
indices[baseIndex + 1] = (short)(i + 1);
indices[baseIndex + 2] = (short)(next + 1);
}
return new PrimitiveMesh(vertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[segments + 1];
colorVertices[0] = new VertexPositionColor(center, color);
for (int i = 0; i < segments; i++)
{
colorVertices[i + 1] = new VertexPositionColor(center + EllipseDirection(i, segments, right, up, radii), color);
}
var colorIndices = new short[segments * 3];
for (int i = 0; i < segments; i++)
{
int next = (i + 1) % segments;
int baseIndex = i * 3;
colorIndices[baseIndex] = 0;
colorIndices[baseIndex + 1] = (short)(i + 1);
colorIndices[baseIndex + 2] = (short)(next + 1);
}
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
public static PrimitiveMesh BuildSphere(
Vector3 center,
float radius,
int latitudeSegments,
int longitudeSegments,
Func<Vector3, Color>? colorFunc = null,
bool textured = false)
{
if (latitudeSegments < 2)
throw new ArgumentOutOfRangeException(nameof(latitudeSegments), "Sphere requires at least two latitude segments.");
if (longitudeSegments < 3)
throw new ArgumentOutOfRangeException(nameof(longitudeSegments), "Sphere requires at least three longitude segments.");
colorFunc ??= static _ => Color.White;
int vertexRows = latitudeSegments + 1;
int vertexCols = longitudeSegments + 1;
int vertexCount = vertexRows * vertexCols;
if (vertexCount > short.MaxValue)
throw new InvalidOperationException("Sphere produced more vertices than supported by the index buffer.");
if (textured)
{
var vertices = new VertexPositionColorTexture[vertexCount];
int v = 0;
for (int lat = 0; lat <= latitudeSegments; lat++)
{
float phi = MathF.PI * lat / latitudeSegments;
float sinPhi = MathF.Sin(phi);
float cosPhi = MathF.Cos(phi);
float vCoord = 1f - (float)lat / latitudeSegments;
for (int lon = 0; lon <= longitudeSegments; lon++)
{
float theta = MathHelper.TwoPi * lon / longitudeSegments;
var normal = SphericalDirection(sinPhi, cosPhi, theta);
float uCoord = (float)lon / longitudeSegments;
vertices[v++] = new VertexPositionColorTexture(center + normal * radius, colorFunc(normal), new Vector2(uCoord, vCoord));
}
}
var indices = new List<short>(latitudeSegments * longitudeSegments * 6);
for (int lat = 0; lat < latitudeSegments; lat++)
{
for (int lon = 0; lon < longitudeSegments; lon++)
{
int current = lat * vertexCols + lon;
int next = current + vertexCols;
indices.Add((short)current);
indices.Add((short)(current + 1));
indices.Add((short)next);
indices.Add((short)(current + 1));
indices.Add((short)(next + 1));
indices.Add((short)next);
}
}
return new PrimitiveMesh(vertices, indices.ToArray(), PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[vertexCount];
int vIndex = 0;
for (int lat = 0; lat <= latitudeSegments; lat++)
{
float phi = MathF.PI * lat / latitudeSegments;
float sinPhi = MathF.Sin(phi);
float cosPhi = MathF.Cos(phi);
for (int lon = 0; lon <= longitudeSegments; lon++)
{
float theta = MathHelper.TwoPi * lon / longitudeSegments;
var normal = SphericalDirection(sinPhi, cosPhi, theta);
colorVertices[vIndex++] = new VertexPositionColor(center + normal * radius, colorFunc(normal));
}
}
var colorIndices = new List<short>(latitudeSegments * longitudeSegments * 6);
for (int lat = 0; lat < latitudeSegments; lat++)
{
for (int lon = 0; lon < longitudeSegments; lon++)
{
int current = lat * vertexCols + lon;
int next = current + vertexCols;
colorIndices.Add((short)current);
colorIndices.Add((short)(current + 1));
colorIndices.Add((short)next);
colorIndices.Add((short)(current + 1));
colorIndices.Add((short)(next + 1));
colorIndices.Add((short)next);
}
}
return new PrimitiveMesh(colorVertices, colorIndices.ToArray(), PrimitiveType.TriangleList);
}
// Heres your vertice, sir. You probably don't need to call this directly.
public static PrimitiveMesh BuildTriangle(Vector3 a, Vector3 b, Vector3 c, Color color, bool textured = false)
{
if (textured)
{
var vertices = new[]
{
new VertexPositionColorTexture(a, color, new Vector2(0f, 1f)),
new VertexPositionColorTexture(b, color, new Vector2(1f, 1f)),
new VertexPositionColorTexture(c, color, new Vector2(0.5f, 0f))
};
return new PrimitiveMesh(vertices, new short[] { 0, 1, 2 }, PrimitiveType.TriangleList);
}
var colorVertices = new[]
{
new VertexPositionColor(a, color),
new VertexPositionColor(b, color),
new VertexPositionColor(c, color)
};
return new PrimitiveMesh(colorVertices, new short[] { 0, 1, 2 }, PrimitiveType.TriangleList);
}
public static PrimitiveMesh BuildSemiCircle(
Vector3 center,
float radius,
int segments,
Color color,
Vector3 normal,
Vector3 forward,
bool textured = false)
{
if (segments < 2)
throw new ArgumentOutOfRangeException(nameof(segments), "Semi-circle requires at least two segments.");
var n = normal.LengthSquared() < 1e-6f ? Vector3.Backward : Vector3.Normalize(normal);
var f = forward.LengthSquared() < 1e-6f ? Vector3.Forward : Vector3.Normalize(forward);
if (MathF.Abs(Vector3.Dot(f, n)) > 0.999f)
f = Vector3.Normalize(Vector3.Cross(n, Vector3.Right));
var right = Vector3.Normalize(Vector3.Cross(n, f));
var tangent = Vector3.Normalize(Vector3.Cross(right, n));
if (textured)
{
var texturedVertices = new VertexPositionColorTexture[segments + 2];
texturedVertices[0] = new VertexPositionColorTexture(center, color, new Vector2(0.5f, 1f));
float safeRadius = Math.Max(radius, 1e-6f); // todo: remove
float newStep = MathF.PI / segments;
for (int i = 0; i <= segments; i++)
{
float angle = newStep * i;
Vector3 offset = right * MathF.Cos(angle) + tangent * MathF.Sin(angle);
Vector3 point = center + offset * radius;
float x = MathHelper.Clamp(Vector3.Dot(offset, right), -1f, 1f);
float y = MathHelper.Clamp(Vector3.Dot(offset, tangent), 0f, 1f);
float u = 0.5f + 0.5f * x;
float v = 1f - y;
texturedVertices[i + 1] = new VertexPositionColorTexture(point, color, new Vector2(u, v));
}
var indices = new short[segments * 3];
for (int i = 0; i < segments; i++)
{
int baseIndex = i * 3;
indices[baseIndex] = 0;
indices[baseIndex + 1] = (short)(i + 1);
indices[baseIndex + 2] = (short)(i + 2);
}
return new PrimitiveMesh(texturedVertices, indices, PrimitiveType.TriangleList);
}
var colorVertices = new VertexPositionColor[segments + 2];
colorVertices[0] = new VertexPositionColor(center, color);
float step = MathF.PI / segments;
for (int i = 0; i <= segments; i++)
{
float angle = step * i;
Vector3 offset = right * MathF.Cos(angle) + tangent * MathF.Sin(angle);
colorVertices[i + 1] = new VertexPositionColor(center + offset * radius, color);
}
var colorIndices = new short[segments * 3];
for (int i = 0; i < segments; i++)
{
int baseIndex = i * 3;
colorIndices[baseIndex] = 0;
colorIndices[baseIndex + 1] = (short)(i + 1);
colorIndices[baseIndex + 2] = (short)(i + 2);
}
return new PrimitiveMesh(colorVertices, colorIndices, PrimitiveType.TriangleList);
}
/// <summary>
/// Given a normal and an up hint, builds an orthonormal basis where the normal is the "forward" direction,
/// the right vector is perpendicular to both, and the up vector is perpendicular to the normal.
/// The implementation normalizes the inputs, handles near-parallel cases, and then re-orthogonalizes the up vector
/// from the computed right vector (so it is not guaranteed to be the closest possible to <paramref name="upHint"/>).
/// </summary>
/// <param name="normal">The forward/normal direction (fallbacks to <see cref="Vector3.Backward"/> if near-zero).</param>
/// <param name="upHint">A preferred up direction (fallbacks to <see cref="Vector3.Up"/> if near-zero).</param>
/// <param name="right">The computed right vector.</param>
/// <param name="up">The computed up vector.</param>
private static void BuildFrame(Vector3 normal, Vector3 upHint, out Vector3 right, out Vector3 up)
{
var n = normal.LengthSquared() < 1e-6f ? Vector3.Backward : Vector3.Normalize(normal);
up = upHint.LengthSquared() < 1e-6f ? Vector3.Up : Vector3.Normalize(upHint);
if (MathF.Abs(Vector3.Dot(n, up)) > 0.999f)
up = Vector3.Normalize(Vector3.Cross(n, Vector3.Right));
right = Vector3.Cross(up, n);
if (right.LengthSquared() < 1e-6f)
right = Vector3.Cross(Vector3.Forward, n);
right.Normalize();
up = Vector3.Normalize(Vector3.Cross(n, right));
}
private static Vector3 PolarToCartesian(int index, int total, Vector3 right, Vector3 up)
{
float angle = MathHelper.TwoPi * index / total;
return right * MathF.Cos(angle) + up * MathF.Sin(angle);
}
private static Vector3 EllipseDirection(int index, int total, Vector3 right, Vector3 up, Vector2 radii)
{
float angle = MathHelper.TwoPi * index / total;
return right * (MathF.Cos(angle) * radii.X) + up * (MathF.Sin(angle) * radii.Y);
}
private static Vector3 SphericalDirection(float sinPhi, float cosPhi, float theta)
{
float cosTheta = MathF.Cos(theta);
float sinTheta = MathF.Sin(theta);
return new Vector3(sinPhi * cosTheta, cosPhi, sinPhi * sinTheta);
}
}
@@ -0,0 +1,40 @@
using System;
namespace CalamityMod.Graphics.Primitives;
internal static class PrimitiveSimd
{
private static readonly System.Numerics.Vector<int> LaneOffsets = CreateLaneOffsets();
public static void FillSequentialIndices(Span<short> indices)
{
int i = 0;
if (System.Numerics.Vector.IsHardwareAccelerated)
{
int width = System.Numerics.Vector<int>.Count;
Span<int> temp = width <= 16
? stackalloc int[width]
: new int[width];
while (i <= indices.Length - width)
{
(LaneOffsets + new System.Numerics.Vector<int>(i)).CopyTo(temp);
for (int lane = 0; lane < width; lane++)
indices[i + lane] = (short)temp[lane];
i += width;
}
}
for (; i < indices.Length; i++)
indices[i] = (short)i;
}
private static System.Numerics.Vector<int> CreateLaneOffsets()
{
int width = System.Numerics.Vector<int>.Count;
Span<int> lanes = stackalloc int[width];
for (int i = 0; i < width; i++)
lanes[i] = i;
return new System.Numerics.Vector<int>(lanes);
}
}
@@ -0,0 +1,800 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.GameContent;
namespace CalamityMod.Graphics.Primitives;
public static class SanePrimitiveRenderer
{
private static GraphicsDevice _graphicsDevice => Main.graphics.GraphicsDevice;
private static BasicEffect? _effect;
public readonly struct ShaderScope : IDisposable
{
private readonly GraphicsDevice _device;
private readonly Effect _effect;
private readonly bool _useBasicEffect;
private readonly Matrix _world;
private readonly Matrix _view;
private readonly Matrix _projection;
private readonly string? _transformMatrixParam;
private readonly RasterizerState _previousRasterizer;
private readonly DepthStencilState _previousDepth;
private readonly BlendState _previousBlend;
private readonly SamplerState? _previousSampler;
internal ShaderScope(
GraphicsDevice device,
Effect effect,
bool useBasicEffect,
in Matrix world,
in Matrix view,
in Matrix projection,
string? transformMatrixParam,
RasterizerState? rasterizerState,
DepthStencilState? depthState,
BlendState? blendState,
SamplerState? samplerState)
{
_device = device;
_effect = effect;
_useBasicEffect = useBasicEffect;
_world = world;
_view = view;
_projection = projection;
_transformMatrixParam = transformMatrixParam;
_previousRasterizer = device.RasterizerState;
_previousDepth = device.DepthStencilState;
_previousBlend = device.BlendState;
_previousSampler = device.SamplerStates[0];
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
device.SamplerStates[0] = samplerState ?? SamplerState.PointWrap;
if (_useBasicEffect)
{
var basic = (BasicEffect)_effect;
basic.World = world;
basic.View = view;
basic.Projection = projection;
}
else if (transformMatrixParam != null)
{
var param = _effect.Parameters[transformMatrixParam];
if (param != null)
param.SetValue(world * view * projection);
}
}
public void Draw(in PrimitiveMesh mesh)
{
if (!mesh.IsValid)
return;
if (_useBasicEffect)
{
var basic = (BasicEffect)_effect;
bool textured = mesh.UsesTexture;
basic.TextureEnabled = textured;
basic.Texture = textured ? TextureAssets.MagicPixel.Value : null;
}
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.Indices.Length);
bool usesTexture = mesh.UsesTexture;
foreach (var pass in _effect.CurrentTechnique.Passes)
{
pass.Apply();
if (usesTexture)
{
_device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
else
{
_device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
}
}
public void Draw(in PrimitiveMeshView mesh)
{
if (!mesh.IsValid)
return;
if (_useBasicEffect)
{
var basic = (BasicEffect)_effect;
bool textured = mesh.UsesTexture;
basic.TextureEnabled = textured;
basic.Texture = textured ? TextureAssets.MagicPixel.Value : null;
}
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.IndexCount);
bool usesTexture = mesh.UsesTexture;
foreach (var pass in _effect.CurrentTechnique.Passes)
{
pass.Apply();
if (usesTexture)
{
_device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
else
{
_device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
}
}
public void Dispose()
{
_device.RasterizerState = _previousRasterizer;
_device.DepthStencilState = _previousDepth;
_device.BlendState = _previousBlend;
if (_previousSampler != null)
_device.SamplerStates[0] = _previousSampler;
}
}
public static bool IsReady =>
_graphicsDevice != null &&
!_graphicsDevice.IsDisposed &&
_effect != null &&
!_effect.IsDisposed;
public static void Initialize()
{
if (_graphicsDevice == null)
throw new ArgumentNullException(nameof(_graphicsDevice));
_effect?.Dispose();
_effect = new BasicEffect(_graphicsDevice)
{
VertexColorEnabled = true,
TextureEnabled = true,
LightingEnabled = false,
FogEnabled = false,
Texture = TextureAssets.Logo.Value
};
}
public static void Dispose()
{
_effect?.Dispose();
}
/// <summary>
/// Draws the specified mesh using the provided world, view, and projection matrices.
/// </summary>
/// <param name="world">World matrix.</param>
/// <param name="view">View matrix.</param>
/// <param name="projection">Projection matrix.</param>
/// <param name="mesh">The mesh to draw.</param>
/// <param name="rasterizerState">The rasterizer state to use. If null, defaults to <see cref="RasterizerState.CullNone"/>.</param>
/// <param name="depthState">The depth stencil state to use. If null, defaults to <see cref="DepthStencilState.Default"/>.</param>
/// <param name="blendState">The blend state to use. If null, defaults to <see cref="BlendState.AlphaBlend"/>.</param>
/// <exception cref="InvalidOperationException">The renderer is not initialized.</exception>
/// <exception cref="NotSupportedException">The primitive type is not supported. Supported types are: TriangleList, TriangleStrip, LineList, LineStrip, and PointListEXT.</exception>
public static void DrawMesh(
in Matrix world,
in Matrix view,
in Matrix projection,
in PrimitiveMesh mesh,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (!IsReady)
throw new InvalidOperationException("SanePrimitiveRenderer is not initialized.");
if (!mesh.IsValid)
return;
Debug.Assert(_effect is not null);
bool textured = mesh.UsesTexture;
_effect.TextureEnabled = textured;
_effect.Texture = textured ? TextureAssets.MagicPixel.Value : null;
_graphicsDevice.SamplerStates[0] = SamplerState.PointWrap;
_effect.World = world;
_effect.View = view;
_effect.Projection = projection;
var device = _graphicsDevice;
var previousRasterizer = device.RasterizerState;
var previousDepth = device.DepthStencilState;
var previousBlend = device.BlendState;
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.Indices.Length);
foreach (var pass in _effect.CurrentTechnique.Passes)
{
pass.Apply();
if (textured)
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
else
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
}
device.RasterizerState = previousRasterizer;
device.DepthStencilState = previousDepth;
device.BlendState = previousBlend;
}
/// <summary>
/// Draws the specified mesh using an arbitrary <see cref="Effect"/> instead of the built-in <see cref="BasicEffect"/>.<br/>
/// The caller is responsible for setting all shader parameters (including any transform matrices) before calling this method.<br/>
/// A convenience parameter, <paramref name="transformMatrixParam"/>, can be used to automatically set a <c>uTransformMatrix</c>
/// parameter on the effect to <c>world * view * projection</c>.
/// </summary>
/// <param name="world">World matrix.</param>
/// <param name="view">View matrix.</param>
/// <param name="projection">Projection matrix.</param>
/// <param name="mesh">The mesh to draw.</param>
/// <param name="effect">The custom effect to use for rendering.</param>
/// <param name="transformMatrixParam">
/// If non-null, the name of an <see cref="EffectParameter"/> on <paramref name="effect"/> that will be set to <c>world * view * projection</c>.
/// Defaults to <c>"uTransformMatrix"</c>. Pass <c>null</c> to skip automatic matrix assignment.
/// </param>
/// <param name="rasterizerState">The rasterizer state to use. If null, defaults to <see cref="RasterizerState.CullNone"/>.</param>
/// <param name="depthState">The depth stencil state to use. If null, defaults to <see cref="DepthStencilState.Default"/>.</param>
/// <param name="blendState">The blend state to use. If null, defaults to <see cref="BlendState.AlphaBlend"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="effect"/> is null.</exception>
/// <exception cref="NotSupportedException">The primitive type is not supported.</exception>
public static void DrawMesh(
in Matrix world,
in Matrix view,
in Matrix projection,
in PrimitiveMesh mesh,
Effect effect,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
if (!mesh.IsValid)
return;
if (transformMatrixParam != null)
{
var param = effect.Parameters[transformMatrixParam];
if (param != null)
param.SetValue(world * view * projection);
}
var device = _graphicsDevice;
var previousRasterizer = device.RasterizerState;
var previousDepth = device.DepthStencilState;
var previousBlend = device.BlendState;
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.Indices.Length);
bool textured = mesh.UsesTexture;
foreach (var pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
if (textured)
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
else
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
0,
mesh.VertexCount,
mesh.Indices,
0,
primitiveCount);
}
}
device.RasterizerState = previousRasterizer;
device.DepthStencilState = previousDepth;
device.BlendState = previousBlend;
}
/** <summary>
Draws a triangle strip using the specified parameters. <para/>
Alias for <see cref="DrawMesh"/>. Assumes you want a 'triangle strip' primitive type.
</summary>
<param name="world">The world matrix.</param>
<param name="view">The view matrix.</param>
<param name="projection">The projection matrix.</param>
<param name="vertices">The vertex positions and colors.</param>
**/
public static void DrawTriangleStrip(
in Matrix world,
in Matrix view,
in Matrix projection,
VertexPositionColorTexture[] vertices,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length < 3)
return;
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
DrawMesh(
world,
view,
projection,
PrimitiveMesh.FromSequential(vertices, PrimitiveType.TriangleStrip),
rasterizerState,
depthState,
blendState);
}
/** <summary>
Draws a triangle strip using the specified parameters. <para/>
Alias for <see cref="DrawMesh"/>. Assumes you want a 'triangle strip' primitive type.
</summary>
<param name="world">The world matrix.</param>
<param name="view">The view matrix.</param>
<param name="projection">The projection matrix.</param>
<param name="vertices">The vertex positions and colors.</param>
**/
public static void DrawTriangleStrip(
in Matrix world,
in Matrix view,
in Matrix projection,
VertexPositionColor[] vertices,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length < 3)
return;
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
DrawMesh(
world,
view,
projection,
PrimitiveMesh.FromSequential(vertices, PrimitiveType.TriangleStrip),
rasterizerState,
depthState,
blendState);
}
/** <summary>
Draws a triangle list using the specified parameters. <para/>
Alias for <see cref="DrawMesh"/>. Assumes you want a 'triangle list' primitive type.
</summary>
<param name="world">The world matrix.</param>
<param name="view">The view matrix.</param>
<param name="projection">The projection matrix.</param>
<param name="vertices">The vertex positions and colors.</param>
**/
public static void DrawTriangleList(
in Matrix world,
in Matrix view,
in Matrix projection,
VertexPositionColorTexture[] vertices,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length < 3 || vertices.Length % 3 != 0)
return;
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
DrawMesh(
world,
view,
projection,
PrimitiveMesh.FromSequential(vertices, PrimitiveType.TriangleList),
rasterizerState,
depthState,
blendState);
}
/** <summary>
Draws a triangle list using the specified parameters. <para/>
Alias for <see cref="DrawMesh"/>. Assumes you want a 'triangle list' primitive type.
</summary>
<param name="world">The world matrix.</param>
<param name="view">The view matrix.</param>
<param name="projection">The projection matrix.</param>
<param name="vertices">The vertex positions and colors.</param>
**/
public static void DrawTriangleList(
in Matrix world,
in Matrix view,
in Matrix projection,
VertexPositionColor[] vertices,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (vertices == null)
throw new ArgumentNullException(nameof(vertices));
if (vertices.Length < 3 || vertices.Length % 3 != 0)
return;
if (vertices.Length > short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(vertices), "Vertex count exceeds index buffer range.");
DrawMesh(
world,
view,
projection,
PrimitiveMesh.FromSequential(vertices, PrimitiveType.TriangleList),
rasterizerState,
depthState,
blendState);
}
public static void DrawMesh(
in Matrix world,
in Matrix view,
in Matrix projection,
in PrimitiveMeshView mesh,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (!IsReady)
throw new InvalidOperationException("SanePrimitiveRenderer is not initialized.");
if (!mesh.IsValid)
return;
Debug.Assert(_effect is not null);
bool textured = mesh.UsesTexture;
_effect.TextureEnabled = textured;
_effect.Texture = textured ? TextureAssets.MagicPixel.Value : null;
_graphicsDevice.SamplerStates[0] = SamplerState.PointWrap;
_effect.World = world;
_effect.View = view;
_effect.Projection = projection;
var device = _graphicsDevice;
var previousRasterizer = device.RasterizerState;
var previousDepth = device.DepthStencilState;
var previousBlend = device.BlendState;
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.IndexCount);
foreach (var pass in _effect.CurrentTechnique.Passes)
{
pass.Apply();
if (textured)
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
else
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
}
device.RasterizerState = previousRasterizer;
device.DepthStencilState = previousDepth;
device.BlendState = previousBlend;
}
public static void DrawMesh(
in Matrix world,
in Matrix view,
in Matrix projection,
in PrimitiveMeshView mesh,
Effect effect,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
if (!mesh.IsValid)
return;
if (transformMatrixParam != null)
{
var param = effect.Parameters[transformMatrixParam];
if (param != null)
param.SetValue(world * view * projection);
}
var device = _graphicsDevice;
var previousRasterizer = device.RasterizerState;
var previousDepth = device.DepthStencilState;
var previousBlend = device.BlendState;
device.RasterizerState = rasterizerState ?? RasterizerState.CullNone;
device.DepthStencilState = depthState ?? DepthStencilState.Default;
device.BlendState = blendState ?? BlendState.AlphaBlend;
int primitiveCount = GetPrimitiveCount(mesh.PrimitiveType, mesh.IndexCount);
bool textured = mesh.UsesTexture;
foreach (var pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
if (textured)
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.TexturedVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
else
{
device.DrawUserIndexedPrimitives(
mesh.PrimitiveType,
mesh.ColorVertices,
mesh.VertexOffset,
mesh.VertexCount,
mesh.Indices,
mesh.IndexOffset,
primitiveCount);
}
}
device.RasterizerState = previousRasterizer;
device.DepthStencilState = previousDepth;
device.BlendState = previousBlend;
}
public static ShaderScope BeginShaderScope(
in Matrix world,
in Matrix view,
in Matrix projection,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (!IsReady)
throw new InvalidOperationException("SanePrimitiveRenderer is not initialized.");
Debug.Assert(_effect is not null);
return new ShaderScope(
_graphicsDevice,
_effect,
true,
world,
view,
projection,
null,
rasterizerState,
depthState,
blendState,
samplerState);
}
public static ShaderScope BeginShaderScope(
Effect effect,
in Matrix world,
in Matrix view,
in Matrix projection,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
return new ShaderScope(
_graphicsDevice,
effect,
false,
world,
view,
projection,
transformMatrixParam,
rasterizerState,
depthState,
blendState,
samplerState);
}
public static void DrawMeshes(
in Matrix world,
in Matrix view,
in Matrix projection,
IReadOnlyList<PrimitiveMesh> meshes,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (meshes == null)
throw new ArgumentNullException(nameof(meshes));
using var scope = BeginShaderScope(world, view, projection, rasterizerState, depthState, blendState, samplerState);
for (int i = 0; i < meshes.Count; i++)
scope.Draw(meshes[i]);
}
public static void DrawMeshes(
in Matrix world,
in Matrix view,
in Matrix projection,
IReadOnlyList<PrimitiveMeshView> meshes,
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (meshes == null)
throw new ArgumentNullException(nameof(meshes));
using var scope = BeginShaderScope(world, view, projection, rasterizerState, depthState, blendState, samplerState);
for (int i = 0; i < meshes.Count; i++)
scope.Draw(meshes[i]);
}
public static void DrawMeshes(
Effect effect,
in Matrix world,
in Matrix view,
in Matrix projection,
IReadOnlyList<PrimitiveMesh> meshes,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
if (meshes == null)
throw new ArgumentNullException(nameof(meshes));
using var scope = BeginShaderScope(effect, world, view, projection, transformMatrixParam, rasterizerState, depthState, blendState, samplerState);
for (int i = 0; i < meshes.Count; i++)
scope.Draw(meshes[i]);
}
public static void DrawMeshes(
Effect effect,
in Matrix world,
in Matrix view,
in Matrix projection,
IReadOnlyList<PrimitiveMeshView> meshes,
string? transformMatrixParam = "uTransformMatrix",
RasterizerState? rasterizerState = null,
DepthStencilState? depthState = null,
BlendState? blendState = null,
SamplerState? samplerState = null)
{
if (effect == null)
throw new ArgumentNullException(nameof(effect));
if (meshes == null)
throw new ArgumentNullException(nameof(meshes));
using var scope = BeginShaderScope(effect, world, view, projection, transformMatrixParam, rasterizerState, depthState, blendState, samplerState);
for (int i = 0; i < meshes.Count; i++)
scope.Draw(meshes[i]);
}
private static int GetPrimitiveCount(PrimitiveType primitiveType, int indexCount)
{
return primitiveType switch
{
PrimitiveType.TriangleList => indexCount / 3,
PrimitiveType.TriangleStrip => Math.Max(indexCount - 2, 0),
PrimitiveType.LineList => indexCount / 2,
PrimitiveType.LineStrip => Math.Max(indexCount - 1, 0),
PrimitiveType.PointListEXT => indexCount,
_ => throw new NotSupportedException(primitiveType.ToString())
};
}
}
@@ -0,0 +1,16 @@
namespace CalamityMod.Graphics.Primitives;
/// <summary>
/// Determines the shape of end caps for strip primitives. This is used to give a more polished look to the start and end of strips, especially when they are thick. The cap is drawn at the end of the strip, centered on the last vertex, and oriented to match the strip's direction at that point. The options are:
/// <list type="bullet">
/// <item><description><see cref="None"/>: No cap is drawn, leaving the strip to end abruptly at the last vertex. This is the default and most performant option.</description></item>
/// <item><description><see cref="Triangle"/>: A simple triangular cap is drawn, extending the strip in a pointed shape. The triangle's base is aligned with the last segment of the strip, and its height is proportional to the strip's width.</description></item>
/// <item><description><see cref="HalfCircle"/>: A semicircular cap is drawn, creating a rounded end to the strip.</description></item>
/// </list>
/// </summary>
public enum StripCapStyle
{
None,
Triangle,
HalfCircle
}
@@ -0,0 +1,18 @@
namespace CalamityMod.Graphics.Primitives;
/// <summary>
/// Specifies the type of curve interpolation to use when generating a strip mesh from a sequence of points.
///
/// <remarks>
/// The curve type determines how the strip will be shaped between the control points.
/// Different curve types can produce smoother or sharper results, and may have different performance characteristics.
/// </remarks>
/// </summary>
public enum StripCurveType
{
CatmullRom,
Linear,
CubicBezier,
Hermite
}
@@ -0,0 +1,15 @@
namespace CalamityMod.Graphics.Primitives;
/// <summary>
/// Specifies how to join segments in a strip mesh.
///
/// <list type="bullet">
/// <item><description><see cref="Perpendicular"/>: Uses the averaged per-segment right vectors to build a perpendicular join at corners. This is the default and most performant option.</description></item>
/// <item><description><see cref="Miter"/>: Uses a miter join that extends the edges to their intersection, with a built-in miter limit to avoid extreme spikes on sharp angles.</description></item>
/// </list>
/// </summary>
public enum StripJoinStyle
{
Perpendicular,
Miter
}
@@ -0,0 +1,15 @@
namespace CalamityMod.Graphics.Primitives;
/// <summary>
/// Controls how strip width is attenuated along the path.
///
/// <list type="bullet">
/// <item><description><see cref="None"/>: No attenuation is applied; width comes solely from the provided width function/constant.</description></item>
/// <item><description><see cref="ContinuitySquared"/>: Attenuates width based on directional continuity between consecutive tangents.</description></item>
/// </list>
/// </summary>
public enum StripWidthAttenuation
{
None,
ContinuitySquared
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff