From 1e480f6c15d191008abd0a20dd9d72c1795d4369 Mon Sep 17 00:00:00 2001 From: jracek Date: Thu, 13 Mar 2025 12:37:23 +0100 Subject: [PATCH] Added PSXMesh, deindexes tris, converts them into primitives for the PSX --- Runtime/PSXMesh.cs | 52 +++++++++++++++++++++++++++++++++--- Runtime/PSXObjectExporter.cs | 12 +++++++++ 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/Runtime/PSXMesh.cs b/Runtime/PSXMesh.cs index 14e52e3..bb234f3 100644 --- a/Runtime/PSXMesh.cs +++ b/Runtime/PSXMesh.cs @@ -1,16 +1,62 @@ +using System.Collections.Generic; using UnityEngine; namespace PSXSplash.RuntimeCode { + public struct PSXVertex + { + public short vx, vy, vz; + public byte u, v; + } + + public struct Tri + { + public PSXVertex v0; + public PSXVertex v1; + public PSXVertex v2; + } + [System.Serializable] public class PSXMesh { - public bool TriangulateMesh = true; + public List Triangles; - public void Export(GameObject gameObject) + public static PSXMesh CreateFromUnityMesh(Mesh mesh, int textureWidth, int textureHeight) { - Debug.Log($"Export: {this}"); + PSXMesh psxMesh = new PSXMesh { Triangles = new List() }; + + Vector3[] vertices = mesh.vertices; + Vector2[] uv = mesh.uv; + int[] indices = mesh.triangles; + + for (int i = 0; i < indices.Length; i += 3) + { + int vid0 = indices[i]; + int vid1 = indices[i + 1]; + int vid2 = indices[i + 2]; + + PSXVertex v0 = ConvertToPSXVertex(vertices[vid0], uv[vid0], textureWidth, textureHeight); + PSXVertex v1 = ConvertToPSXVertex(vertices[vid1], uv[vid1], textureWidth, textureHeight); + PSXVertex v2 = ConvertToPSXVertex(vertices[vid2], uv[vid2], textureWidth, textureHeight); + + psxMesh.Triangles.Add(new Tri { v0 = v0, v1 = v1, v2 = v2 }); + } + + return psxMesh; + } + + private static PSXVertex ConvertToPSXVertex(Vector3 vertex, Vector2 uv, int textureWidth, int textureHeight) + { + PSXVertex psxVertex = new PSXVertex + { + vx = (short)(Mathf.Clamp(vertex.x, -4f, 3.999f) * 4096), + vy = (short)(Mathf.Clamp(vertex.y, -4f, 3.999f) * 4096), + vz = (short)(Mathf.Clamp(vertex.z, -4f, 3.999f) * 4096), + u = (byte)(Mathf.Clamp(uv.x * textureWidth, 0, 255)), + v = (byte)(Mathf.Clamp((1.0f - uv.y) * textureHeight, 0, 255)) + }; + return psxVertex; } } } \ No newline at end of file diff --git a/Runtime/PSXObjectExporter.cs b/Runtime/PSXObjectExporter.cs index 6ccc31a..53d8099 100644 --- a/Runtime/PSXObjectExporter.cs +++ b/Runtime/PSXObjectExporter.cs @@ -9,6 +9,9 @@ namespace PSXSplash.RuntimeCode [HideInInspector] public PSXTexture2D Texture; + [HideInInspector] + public PSXMesh Mesh; + public void CreatePSXTexture2D() { Renderer renderer = GetComponent(); @@ -18,6 +21,15 @@ namespace PSXSplash.RuntimeCode Texture.OriginalTexture = texture; } } + + public void CreatePSXMesh() + { + MeshFilter meshFilter = gameObject.GetComponent(); + if (meshFilter != null) + { + Mesh = PSXMesh.CreateFromUnityMesh(meshFilter.mesh, Texture.Width, Texture.Height); + } + } } }