mirror of
https://github.com/UOH-CS-Level5/551455-graphics-programming-2526-the-repo-Zyb3rWolfi.git
synced 2025-11-29 00:43:08 +00:00
67 lines
2.5 KiB
C#
67 lines
2.5 KiB
C#
using OpenTK.Mathematics;
|
|
|
|
namespace TheLabs;
|
|
|
|
public static class Helpers
|
|
{
|
|
public static void CalculateTangent(ref Vertex v1, ref Vertex v2, ref Vertex v3)
|
|
{
|
|
// 1. Calculate Edge Vectors (Geometry)
|
|
Vector3 edge1 = v2.Position - v1.Position;
|
|
Vector3 edge2 = v3.Position - v1.Position;
|
|
|
|
// 2. Calculate Edge Vectors (Texture Space)
|
|
Vector2 deltaUV1 = v2.TexCoords - v1.TexCoords;
|
|
Vector2 deltaUV2 = v3.TexCoords - v1.TexCoords;
|
|
|
|
// 3. The Math (Solving linear equations)
|
|
float f = 1.0f / (deltaUV1.X * deltaUV2.Y - deltaUV2.X * deltaUV1.Y);
|
|
|
|
Vector3 tangent;
|
|
tangent.X = f * (deltaUV2.Y * edge1.X - deltaUV1.Y * edge2.X);
|
|
tangent.Y = f * (deltaUV2.Y * edge1.Y - deltaUV1.Y * edge2.Y);
|
|
tangent.Z = f * (deltaUV2.Y * edge1.Z - deltaUV1.Y * edge2.Z);
|
|
|
|
// Normalize it
|
|
tangent = Vector3.Normalize(tangent);
|
|
Vector3 bitangent = Vector3.Normalize(Vector3.Cross(edge1, edge2));
|
|
|
|
// 4. Assign the same tangent to all 3 vertices of the triangle
|
|
// (For smooth objects, you would average them, but for a cube, this is fine)
|
|
v1.Tangent = tangent; v1.Bitangent = bitangent;
|
|
v2.Tangent = tangent; v2.Bitangent = bitangent;
|
|
v3.Tangent = tangent; v3.Bitangent = bitangent;
|
|
}
|
|
|
|
public static void AddFace(List<Vertex> vertices, List<uint> indices,
|
|
Vertex v0, Vertex v1, Vertex v2, Vertex v3)
|
|
{
|
|
// 1. Calculate Tangents
|
|
// We calculate it twice to ensure the tangent is consistent across the whole face
|
|
// Triangle 1 (Bottom-Left, Bottom-Right, Top-Right)
|
|
CalculateTangent(ref v0, ref v1, ref v2);
|
|
// Triangle 2 (Bottom-Left, Top-Right, Top-Left)
|
|
CalculateTangent(ref v0, ref v2, ref v3);
|
|
|
|
// 2. Track where these new vertices start in the main list
|
|
// (If the list has 4 items, the new ones start at index 4)
|
|
uint offset = (uint)vertices.Count;
|
|
|
|
// 3. Add Vertices to the list
|
|
vertices.Add(v0); // Index: offset + 0
|
|
vertices.Add(v1); // Index: offset + 1
|
|
vertices.Add(v2); // Index: offset + 2
|
|
vertices.Add(v3); // Index: offset + 3
|
|
|
|
// 4. Add Indices for the two triangles (Standard Quad)
|
|
// Triangle 1
|
|
indices.Add(offset + 0);
|
|
indices.Add(offset + 1);
|
|
indices.Add(offset + 2);
|
|
|
|
// Triangle 2
|
|
indices.Add(offset + 0);
|
|
indices.Add(offset + 2);
|
|
indices.Add(offset + 3);
|
|
}
|
|
} |