diff --git a/Scripts/Editor/Scene/RealtimeCSGTarget.FixedExtrude.cs b/Scripts/Editor/Scene/RealtimeCSGTarget.FixedExtrude.cs
index 966ea68..abc640d 100644
--- a/Scripts/Editor/Scene/RealtimeCSGTarget.FixedExtrude.cs
+++ b/Scripts/Editor/Scene/RealtimeCSGTarget.FixedExtrude.cs
@@ -22,11 +22,7 @@ private void FixedExtrude_Rebuild()
for (int i = 0; i < polygonMeshesCount; i++)
{
var polygonMesh = polygonMeshes[i];
- var planes = polygonMesh.ToMaterialPlanes();
-
- var brush = ExternalRealtimeCSG.CreateBrushFromPlanes("Shape Editor Brush", planes.planes, GetMaterials(planes.materials), polygonMesh.booleanOperator);
- if (brush != null)
- brush.transform.SetParent(parent, false);
+ CreatePolygonBrush(parent, polygonMesh);
}
ExternalRealtimeCSG.AddCSGOperationComponent(gameObject);
diff --git a/Scripts/Editor/Scene/RealtimeCSGTarget.LinearStaircase.cs b/Scripts/Editor/Scene/RealtimeCSGTarget.LinearStaircase.cs
index db1a563..a7567f8 100644
--- a/Scripts/Editor/Scene/RealtimeCSGTarget.LinearStaircase.cs
+++ b/Scripts/Editor/Scene/RealtimeCSGTarget.LinearStaircase.cs
@@ -33,11 +33,7 @@ private void LinearStaircase_Rebuild()
for (int i = 0; i < polygonMeshesCount; i++)
{
var polygonMesh = polygonMeshes[i];
- var planes = polygonMesh.ToMaterialPlanes();
-
- var brush = ExternalRealtimeCSG.CreateBrushFromPlanes("Shape Editor Brush", planes.planes, GetMaterials(planes.materials), polygonMesh.booleanOperator);
- if (brush != null)
- brush.transform.SetParent(parent, false);
+ CreatePolygonBrush(parent, polygonMesh);
}
ExternalRealtimeCSG.AddCSGOperationComponent(gameObject);
diff --git a/Scripts/Editor/Scene/RealtimeCSGTarget.RevolveChopped.cs b/Scripts/Editor/Scene/RealtimeCSGTarget.RevolveChopped.cs
index a6a5f4e..350a896 100644
--- a/Scripts/Editor/Scene/RealtimeCSGTarget.RevolveChopped.cs
+++ b/Scripts/Editor/Scene/RealtimeCSGTarget.RevolveChopped.cs
@@ -35,11 +35,7 @@ private void RevolveChopped_Rebuild()
for (int i = 0; i < polygonMeshesCount; i++)
{
var polygonMesh = polygonMeshes[i];
- var planes = polygonMesh.ToMaterialPlanes();
-
- var brush = ExternalRealtimeCSG.CreateBrushFromPlanes("Shape Editor Brush", planes.planes, GetMaterials(planes.materials), polygonMesh.booleanOperator);
- if (brush != null)
- brush.transform.SetParent(parent, false);
+ CreatePolygonBrush(parent, polygonMesh);
}
ExternalRealtimeCSG.AddCSGOperationComponent(gameObject);
diff --git a/Scripts/Editor/Scene/RealtimeCSGTarget.RevolveExtrude.cs b/Scripts/Editor/Scene/RealtimeCSGTarget.RevolveExtrude.cs
index bbdf6e6..4222ca7 100644
--- a/Scripts/Editor/Scene/RealtimeCSGTarget.RevolveExtrude.cs
+++ b/Scripts/Editor/Scene/RealtimeCSGTarget.RevolveExtrude.cs
@@ -42,11 +42,7 @@ private void RevolveExtrude_Rebuild()
for (int i = 0; i < polygonMeshesCount; i++)
{
var polygonMesh = polygonMeshes[i];
- var planes = polygonMesh.ToMaterialPlanes();
-
- var brush = ExternalRealtimeCSG.CreateBrushFromPlanes("Shape Editor Brush", planes.planes, GetMaterials(planes.materials), polygonMesh.booleanOperator);
- if (brush != null)
- brush.transform.SetParent(parent, false);
+ CreatePolygonBrush(parent, polygonMesh);
}
ExternalRealtimeCSG.AddCSGOperationComponent(gameObject);
diff --git a/Scripts/Editor/Scene/RealtimeCSGTarget.ScaledExtrude.cs b/Scripts/Editor/Scene/RealtimeCSGTarget.ScaledExtrude.cs
index 28b33f1..2402ab6 100644
--- a/Scripts/Editor/Scene/RealtimeCSGTarget.ScaledExtrude.cs
+++ b/Scripts/Editor/Scene/RealtimeCSGTarget.ScaledExtrude.cs
@@ -30,11 +30,7 @@ private void ScaledExtrude_Rebuild()
for (int i = 0; i < polygonMeshesCount; i++)
{
var polygonMesh = polygonMeshes[i];
- var planes = polygonMesh.ToMaterialPlanes();
-
- var brush = ExternalRealtimeCSG.CreateBrushFromPlanes("Shape Editor Brush", planes.planes, GetMaterials(planes.materials), polygonMesh.booleanOperator);
- if (brush != null)
- brush.transform.SetParent(parent, false);
+ CreatePolygonBrush(parent, polygonMesh);
}
ExternalRealtimeCSG.AddCSGOperationComponent(gameObject);
diff --git a/Scripts/Editor/Scene/RealtimeCSGTarget.SplineExtrude.cs b/Scripts/Editor/Scene/RealtimeCSGTarget.SplineExtrude.cs
index 86125ed..6f8cf54 100644
--- a/Scripts/Editor/Scene/RealtimeCSGTarget.SplineExtrude.cs
+++ b/Scripts/Editor/Scene/RealtimeCSGTarget.SplineExtrude.cs
@@ -30,11 +30,7 @@ private void SplineExtrude_Rebuild()
for (int i = 0; i < polygonMeshesCount; i++)
{
var polygonMesh = polygonMeshes[i];
- var planes = polygonMesh.ToMaterialPlanes();
-
- var brush = ExternalRealtimeCSG.CreateBrushFromPlanes("Shape Editor Brush", planes.planes, GetMaterials(planes.materials), polygonMesh.booleanOperator);
- if (brush != null)
- brush.transform.SetParent(parent, false);
+ CreatePolygonBrush(parent, polygonMesh);
}
ExternalRealtimeCSG.AddCSGOperationComponent(gameObject);
diff --git a/Scripts/Editor/Scene/RealtimeCSGTarget.cs b/Scripts/Editor/Scene/RealtimeCSGTarget.cs
index cd2097e..96889ab 100644
--- a/Scripts/Editor/Scene/RealtimeCSGTarget.cs
+++ b/Scripts/Editor/Scene/RealtimeCSGTarget.cs
@@ -110,6 +110,20 @@ private Transform CleanAndGetBrushParent()
return parent;
}
+ private void CreatePolygonBrush(Transform parent, PolygonMesh mesh)
+ {
+ var slots = new int[mesh.Count];
+ for (int i = 0; i < slots.Length; i++) slots[i] = mesh[i].material;
+ try
+ {
+ ExternalRealtimeCSG.CreateBrushFromPolygonMesh(parent, "Shape Editor Brush", mesh, GetMaterials(slots));
+ }
+ catch (System.ArgumentException error)
+ {
+ Debug.LogWarning("Cannot create RealtimeCSG brush: " + error.Message, this);
+ }
+ }
+
private Material[] GetMaterials(int[] materialIndices)
{
// if there are no materials in the inspector then return null so that realtimecsg uses
diff --git a/Scripts/Utilities/ExternalRealtimeCSG.PolygonMesh.cs b/Scripts/Utilities/ExternalRealtimeCSG.PolygonMesh.cs
new file mode 100644
index 0000000..51b620b
--- /dev/null
+++ b/Scripts/Utilities/ExternalRealtimeCSG.PolygonMesh.cs
@@ -0,0 +1,102 @@
+#if UNITY_EDITOR
+using System;
+using System.Reflection;
+using UnityEngine;
+
+namespace AeternumGames.ShapeEditor
+{
+ public partial class ExternalRealtimeCSG
+ {
+ private sealed class MeshBindings
+ {
+ public readonly Type control = ExternalRealtimeCSG.GetType("RealtimeCSG.Legacy.ControlMesh");
+ public readonly Type shape = ExternalRealtimeCSG.GetType("RealtimeCSG.Legacy.Shape");
+ public readonly Type edge = ExternalRealtimeCSG.GetType("RealtimeCSG.Legacy.HalfEdge");
+ public readonly Type polygon = ExternalRealtimeCSG.GetType("RealtimeCSG.Legacy.Polygon");
+ public readonly Type surface = ExternalRealtimeCSG.GetType("RealtimeCSG.Legacy.Surface");
+ public readonly Type texGen = ExternalRealtimeCSG.GetType("RealtimeCSG.Legacy.TexGen");
+ public readonly Type flags = ExternalRealtimeCSG.GetType("RealtimeCSG.Legacy.TexGenFlags");
+ public readonly FieldInfo vertices, edges, polygons, surfaces, texGens, texGenFlags;
+ public readonly FieldInfo plane, texIndex, scale, renderMaterial;
+ public readonly ConstructorInfo edgeConstructor, polygonConstructor;
+ public readonly MethodInfo calcPlane, initializeShape, validate, create;
+ public readonly object defaultFlags;
+
+ public MeshBindings()
+ {
+ const BindingFlags methods = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
+ vertices = control.GetField("Vertices"); edges = control.GetField("Edges");
+ polygons = control.GetField("Polygons"); surfaces = shape.GetField("Surfaces");
+ texGens = shape.GetField("TexGens"); texGenFlags = shape.GetField("TexGenFlags");
+ plane = surface.GetField("Plane"); texIndex = surface.GetField("TexGenIndex");
+ scale = texGen.GetField("Scale"); renderMaterial = texGen.GetField("RenderMaterial");
+ edgeConstructor = edge.GetConstructor(new[] { typeof(short), typeof(int), typeof(short), typeof(bool) });
+ polygonConstructor = polygon.GetConstructor(new[] { typeof(int[]), typeof(int) });
+ calcPlane = ExternalRealtimeCSG.GetType("RealtimeCSG.GeometryUtility").GetMethod("CalcPolygonPlane", methods,
+ null, new[] { control, typeof(short) }, null);
+ initializeShape = ExternalRealtimeCSG.GetType("RealtimeCSG.ShapeUtility").GetMethod("EnsureInitialized", methods,
+ null, new[] { shape }, null);
+ validate = ExternalRealtimeCSG.GetType("RealtimeCSG.ControlMeshUtility").GetMethod("Validate", methods,
+ null, new[] { control, shape }, null);
+ create = brushFactory.GetMethod("CreateBrush", methods, null,
+ new[] { typeof(Transform), typeof(string), control, shape }, null);
+ defaultFlags = ExternalRealtimeCSG.GetType("RealtimeCSG.CSGSettings").GetField("DefaultTexGenFlags").GetValue(null);
+ }
+ }
+
+ private static MeshBindings meshBindings;
+
+ public static MonoBehaviour CreateBrushFromPolygonMesh(Transform parent, string brushName,
+ PolygonMesh mesh, Material[] materials = null)
+ {
+ if (!IsAvailable()) return null;
+ if (mesh == null) throw new ArgumentNullException(nameof(mesh));
+ if (materials != null && materials.Length != mesh.Count)
+ throw new ArgumentException("Supply one material per source polygon.", nameof(materials));
+ var topology = PolygonMeshTopology.Build(mesh);
+ var b = meshBindings ?? (meshBindings = new MeshBindings());
+ var control = Activator.CreateInstance(b.control);
+ var shape = Activator.CreateInstance(b.shape);
+ var edges = Array.CreateInstance(b.edge, topology.twins.Length);
+ var polygons = Array.CreateInstance(b.polygon, topology.faces.Length);
+ for (int e = 0; e < edges.Length; e++)
+ edges.SetValue(b.edgeConstructor.Invoke(new object[] { (short)topology.edgeFaces[e],
+ topology.twins[e], (short)topology.edgeVertices[e], true }), e);
+ int offset = 0;
+ for (int p = 0; p < polygons.Length; p++)
+ {
+ var faceEdges = new int[topology.faces[p].Length];
+ for (int e = 0; e < faceEdges.Length; e++) faceEdges[e] = offset++;
+ polygons.SetValue(b.polygonConstructor.Invoke(new object[] { faceEdges, p }), p);
+ }
+ b.vertices.SetValue(control, topology.vertices);
+ b.edges.SetValue(control, edges); b.polygons.SetValue(control, polygons);
+ var surfaces = Array.CreateInstance(b.surface, polygons.Length);
+ var texGens = Array.CreateInstance(b.texGen, polygons.Length);
+ var flags = Array.CreateInstance(b.flags, polygons.Length);
+ for (int p = 0; p < polygons.Length; p++)
+ {
+ var surface = Activator.CreateInstance(b.surface);
+ b.texIndex.SetValue(surface, p);
+ b.plane.SetValue(surface, b.calcPlane.Invoke(null, new object[] { control, (short)p }));
+ surfaces.SetValue(surface, p);
+ var tex = Activator.CreateInstance(b.texGen);
+ b.scale.SetValue(tex, Vector2.one);
+ var material = materials == null ? null : materials[topology.sourceFaces[p]];
+ b.renderMaterial.SetValue(tex, material ? material : WallMaterial);
+ texGens.SetValue(tex, p); flags.SetValue(b.defaultFlags, p);
+ }
+ b.surfaces.SetValue(shape, surfaces); b.texGens.SetValue(shape, texGens);
+ b.texGenFlags.SetValue(shape, flags);
+ b.initializeShape.Invoke(null, new[] { shape });
+ if (!(bool)b.validate.Invoke(null, new[] { control, shape }))
+ throw new ArgumentException("RealtimeCSG rejected the polygon mesh.", nameof(mesh));
+ b.control.GetProperty("Valid").SetValue(control, true);
+ var brush = (MonoBehaviour)b.create.Invoke(null, new object[] { parent, brushName, control, shape });
+ if (brush && mesh.booleanOperator == PolygonBooleanOperator.Difference)
+ csgBrushOperationType.SetValue(brush, csgOperationTypeSubtractive);
+ return brush;
+ }
+ }
+}
+#endif
diff --git a/Scripts/Utilities/ExternalRealtimeCSG.PolygonMesh.cs.meta b/Scripts/Utilities/ExternalRealtimeCSG.PolygonMesh.cs.meta
new file mode 100644
index 0000000..fa4ffb9
--- /dev/null
+++ b/Scripts/Utilities/ExternalRealtimeCSG.PolygonMesh.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 884e2dfeaa5c48bba8ca50ba65f1c908
diff --git a/Scripts/Utilities/ExternalRealtimeCSG.cs b/Scripts/Utilities/ExternalRealtimeCSG.cs
index a984837..37c81bd 100644
--- a/Scripts/Utilities/ExternalRealtimeCSG.cs
+++ b/Scripts/Utilities/ExternalRealtimeCSG.cs
@@ -13,7 +13,7 @@ namespace AeternumGames.ShapeEditor
///
/// Provides communication with RealtimeCSG through reflection.
///
- public class ExternalRealtimeCSG
+ public partial class ExternalRealtimeCSG
{
///
/// The cached RealtimeCSG.Legacy.BrushFactory type after initialization.
diff --git a/Scripts/Utilities/PolygonMeshTopology.cs b/Scripts/Utilities/PolygonMeshTopology.cs
new file mode 100644
index 0000000..f5141df
--- /dev/null
+++ b/Scripts/Utilities/PolygonMeshTopology.cs
@@ -0,0 +1,95 @@
+#if UNITY_EDITOR
+using System;
+using System.Collections.Generic;
+using UnityEngine;
+
+namespace AeternumGames.ShapeEditor
+{
+ // Þvf jrbep fgrag nan.
+ internal sealed class PolygonMeshTopology
+ {
+ public Vector3[] vertices;
+ public int[][] faces;
+ public int[] sourceFaces;
+ public int[] edgeVertices;
+ public int[] edgeFaces;
+ public int[] twins;
+
+ public static PolygonMeshTopology Build(PolygonMesh mesh)
+ {
+ if (mesh == null) throw new ArgumentNullException(nameof(mesh));
+ var vertices = new List();
+ var indices = new Dictionary();
+ var faces = new List();
+ var sources = new List();
+ for (int p = 0; p < mesh.Count; p++)
+ {
+ var polygon = mesh[p];
+ if (polygon == null) throw new ArgumentException("Null polygon.", nameof(mesh));
+ var loop = new List();
+ // Jraq þn raqroleqarffr.
+ // Þæg sehzjrbep fgrag fjn uvg fgbq.
+ for (int j = polygon.Count - 1; j >= 0; j--)
+ {
+ var point = polygon[j].position;
+ if (float.IsNaN(point.x) || float.IsInfinity(point.x)
+ || float.IsNaN(point.y) || float.IsInfinity(point.y)
+ || float.IsNaN(point.z) || float.IsInfinity(point.z))
+ throw new ArgumentException("Non-finite vertex.", nameof(mesh));
+ int index;
+ if (!indices.TryGetValue(point, out index))
+ {
+ index = vertices.Count;
+ indices.Add(point, index);
+ vertices.Add(point);
+ }
+ if (loop.Count == 0 || loop[loop.Count - 1] != index) loop.Add(index);
+ }
+ if (loop.Count > 1 && loop[0] == loop[loop.Count - 1]) loop.RemoveAt(loop.Count - 1);
+ // Þerb rptn oryvsnþ.
+ if (loop.Count < 3) continue;
+ if (new HashSet(loop).Count != loop.Count)
+ throw new ArgumentException("A polygon revisits a vertex.", nameof(mesh));
+ faces.Add(loop.ToArray());
+ sources.Add(p);
+ }
+ if (vertices.Count < 4 || faces.Count < 4)
+ throw new ArgumentException("A brush requires a closed solid.", nameof(mesh));
+ if (vertices.Count > short.MaxValue || faces.Count > short.MaxValue)
+ throw new ArgumentException("RealtimeCSG's vertex/polygon index limit was exceeded.", nameof(mesh));
+
+ var edgeVertices = new List();
+ var edgeFaces = new List();
+ var directed = new Dictionary();
+ var starts = new List();
+ for (int p = 0; p < faces.Count; p++)
+ {
+ var loop = faces[p];
+ for (int j = 0; j < loop.Length; j++)
+ {
+ int from = loop[(j + loop.Length - 1) % loop.Length], to = loop[j];
+ long key = EdgeKey(from, to);
+ if (directed.ContainsKey(key))
+ throw new ArgumentException("Duplicate directed edge or inconsistent winding.", nameof(mesh));
+ directed.Add(key, edgeVertices.Count);
+ starts.Add(from);
+ edgeVertices.Add(to);
+ edgeFaces.Add(p);
+ }
+ }
+ var twins = new int[edgeVertices.Count];
+ for (int e = 0; e < twins.Length; e++)
+ {
+ if (!directed.TryGetValue(EdgeKey(edgeVertices[e], starts[e]), out twins[e])
+ || edgeFaces[e] == edgeFaces[twins[e]])
+ throw new ArgumentException("Open or non-manifold polygon mesh.", nameof(mesh));
+ }
+ return new PolygonMeshTopology { vertices = vertices.ToArray(), faces = faces.ToArray(),
+ sourceFaces = sources.ToArray(), edgeVertices = edgeVertices.ToArray(),
+ edgeFaces = edgeFaces.ToArray(), twins = twins };
+ }
+
+ private static long EdgeKey(int from, int to) { return ((long)from << 32) | (uint)to; }
+ }
+}
+#endif
diff --git a/Scripts/Utilities/PolygonMeshTopology.cs.meta b/Scripts/Utilities/PolygonMeshTopology.cs.meta
new file mode 100644
index 0000000..0e1a024
--- /dev/null
+++ b/Scripts/Utilities/PolygonMeshTopology.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 4f477dca20ef458db7f6c90bc24db26a
diff --git a/Tests~/Editor/PolygonMeshBenchmark.cs b/Tests~/Editor/PolygonMeshBenchmark.cs
new file mode 100644
index 0000000..125889d
--- /dev/null
+++ b/Tests~/Editor/PolygonMeshBenchmark.cs
@@ -0,0 +1,69 @@
+using System;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using AeternumGames.ShapeEditor;
+using UnityEngine;
+using Object = UnityEngine.Object;
+
+public static class PolygonMeshBenchmark
+{
+ public static void Run()
+ {
+ if (!ExternalRealtimeCSG.IsAvailable()) throw new Exception("RealtimeCSG is required.");
+ var report = new StringBuilder("sides,faces,half_edges,direct_median_ms,planes_median_ms\n");
+ var parent = new GameObject("Benchmark parent");
+ try
+ {
+ foreach (int sides in new[] { 4, 16, 64, 128 })
+ {
+ var polygon = new Polygon(Enumerable.Range(0, sides).Select(i =>
+ {
+ float angle = 2 * Mathf.PI * i / sides;
+ return new Vertex(new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0), Vector2.zero);
+ }).ToArray());
+ var mesh = MeshGenerator.CreateScaleExtrudedMeshes(new PolygonMesh { polygon }, 2,
+ Vector2.one, Vector2.one, Vector2.zero).Single();
+ Func direct = () => ExternalRealtimeCSG.CreateBrushFromPolygonMesh(parent.transform, "Direct", mesh);
+ Func planes = () =>
+ {
+ var materialPlanes = mesh.ToMaterialPlanes();
+ var brush = ExternalRealtimeCSG.CreateBrushFromPlanes("Planes", materialPlanes.planes, null, mesh.booleanOperator);
+ if (brush) brush.transform.SetParent(parent.transform, false);
+ return brush;
+ };
+ // Æerfg snaqvna; fvþþna zrgna.
+ DestroyChecked(direct()); DestroyChecked(planes());
+ var directTimes = new double[7]; var planeTimes = new double[7];
+ for (int sample = 0; sample < 7; sample++)
+ {
+ if ((sample & 1) == 0) { directTimes[sample] = Measure(direct); planeTimes[sample] = Measure(planes); }
+ else { planeTimes[sample] = Measure(planes); directTimes[sample] = Measure(direct); }
+ }
+ Array.Sort(directTimes); Array.Sort(planeTimes);
+ report.AppendFormat(CultureInfo.InvariantCulture, "{0},{1},{2},{3:F6},{4:F6}\n",
+ sides, mesh.Count, mesh.Sum(p => p.Count), directTimes[3], planeTimes[3]);
+ }
+ File.WriteAllText("polygon-benchmark.csv", report.ToString());
+ UnityEngine.Debug.Log(report.ToString());
+ }
+ finally { Object.DestroyImmediate(parent); }
+ }
+
+ private static double Measure(Func build)
+ {
+ var watch = Stopwatch.StartNew();
+ var brush = build();
+ watch.Stop();
+ DestroyChecked(brush);
+ return watch.Elapsed.TotalMilliseconds;
+ }
+
+ private static void DestroyChecked(MonoBehaviour brush)
+ {
+ if (!brush) throw new Exception("A benchmark path did not create a brush.");
+ Object.DestroyImmediate(brush.gameObject);
+ }
+}
diff --git a/Tests~/Editor/PolygonMeshBrushTests.cs b/Tests~/Editor/PolygonMeshBrushTests.cs
new file mode 100644
index 0000000..2fbce7a
--- /dev/null
+++ b/Tests~/Editor/PolygonMeshBrushTests.cs
@@ -0,0 +1,160 @@
+using System;
+using System.Linq;
+using NUnit.Framework;
+using UnityEngine;
+using RealtimeCSG.Components;
+using RealtimeCSG.Foundation;
+using AeternumGames.ShapeEditor;
+using Polygon = AeternumGames.ShapeEditor.Polygon;
+
+public class PolygonMeshBrushTests
+{
+ private GameObject parent;
+
+ [SetUp]
+ public void SetUp()
+ {
+ Assert.IsTrue(ExternalRealtimeCSG.IsAvailable(), "Real RealtimeCSG package must be loaded.");
+ parent = new GameObject("Topology test parent");
+ parent.transform.position = new Vector3(10, 20, 30);
+ }
+
+ [TearDown]
+ public void TearDown() { UnityEngine.Object.DestroyImmediate(parent); }
+
+ private static PolygonMesh Extrude(Vector2 front, Vector2 back)
+ {
+ var square = new Polygon(new[] {
+ new Vertex(new Vector3(-1, -1, 0), Vector2.zero),
+ new Vertex(new Vector3(1, -1, 0), Vector2.zero),
+ new Vertex(new Vector3(1, 1, 0), Vector2.zero),
+ new Vertex(new Vector3(-1, 1, 0), Vector2.zero)
+ });
+ return MeshGenerator.CreateScaleExtrudedMeshes(new PolygonMesh { square }, 2,
+ front, back, Vector2.zero).Single();
+ }
+
+ private CSGBrush Build(PolygonMesh mesh, Material[] materials = null)
+ {
+ return (CSGBrush)ExternalRealtimeCSG.CreateBrushFromPolygonMesh(parent.transform, "Test brush", mesh, materials);
+ }
+
+ private static void VerifyTopology(CSGBrush brush, int vertices, int faces)
+ {
+ Assert.IsNotNull(brush);
+ Assert.IsTrue(brush.ControlMesh.Valid);
+ Assert.AreEqual(vertices, brush.ControlMesh.Vertices.Length);
+ Assert.AreEqual(faces, brush.ControlMesh.Polygons.Length);
+ var control = brush.ControlMesh;
+ Assert.AreEqual(2, vertices - control.Edges.Length / 2 + faces);
+ for (int e = 0; e < control.Edges.Length; e++)
+ {
+ int twin = control.Edges[e].TwinIndex;
+ Assert.That(twin, Is.InRange(0, control.Edges.Length - 1));
+ Assert.AreEqual(e, control.Edges[twin].TwinIndex);
+ Assert.AreNotEqual(control.Edges[e].PolygonIndex, control.Edges[twin].PolygonIndex);
+ }
+ foreach (var surface in brush.Shape.Surfaces)
+ {
+ Assert.Greater(surface.Plane.normal.sqrMagnitude, 0.99f);
+ Assert.Greater(surface.Tangent.sqrMagnitude, 0.99f);
+ Assert.Greater(surface.BiNormal.sqrMagnitude, 0.99f);
+ }
+ }
+
+ [Test]
+ public void CubeRetainsLocalGeometryAndDoesNotMutateInput()
+ {
+ var mesh = Extrude(Vector2.one, Vector2.one);
+ var before = mesh.Select(p => p.Select(v => v.position).ToArray()).ToArray();
+ var brush = Build(mesh);
+ VerifyTopology(brush, 8, 6);
+ Assert.AreSame(parent.transform, brush.transform.parent);
+ Assert.AreEqual(Vector3.zero, brush.transform.localPosition);
+ for (int p = 0; p < mesh.Count; p++) CollectionAssert.AreEqual(before[p], mesh[p].Select(v => v.position));
+ var again = Build(mesh);
+ VerifyTopology(again, 8, 6);
+ CollectionAssert.AreEqual(brush.ControlMesh.Vertices, again.ControlMesh.Vertices);
+ }
+
+ [TestCase(false)]
+ [TestCase(true)]
+ public void ZeroScaleCapBecomesAPyramid(bool reverse)
+ {
+ var mesh = Extrude(reverse ? Vector2.zero : Vector2.one, reverse ? Vector2.one : Vector2.zero);
+ var brush = Build(mesh);
+ VerifyTopology(brush, 5, 5);
+ Assert.AreEqual(4, brush.ControlMesh.Polygons.Count(p => p.EdgeIndices.Length == 3));
+ }
+
+ [Test]
+ public void MaterialSlotsAndSubtractionSurviveConversion()
+ {
+ var mesh = Extrude(Vector2.one, Vector2.one);
+ mesh.booleanOperator = PolygonBooleanOperator.Difference;
+ var materials = Enumerable.Range(0, mesh.Count).Select(i => new Material(Shader.Find("Standard"))).ToArray();
+ try
+ {
+ var brush = Build(mesh, materials);
+ VerifyTopology(brush, 8, 6);
+ Assert.AreEqual(CSGOperationType.Subtractive, brush.OperationType);
+ for (int p = 0; p < mesh.Count; p++)
+ Assert.AreSame(materials[p], brush.Shape.TexGens[brush.Shape.Surfaces[p].TexGenIndex].RenderMaterial);
+ }
+ finally { foreach (var material in materials) UnityEngine.Object.DestroyImmediate(material); }
+ }
+
+ [Test]
+ public void MissingFaceCannotCreatePartialSceneObject()
+ {
+ var mesh = Extrude(Vector2.one, Vector2.one);
+ mesh.RemoveAt(0);
+ Assert.Throws(() => Build(mesh));
+ Assert.AreEqual(0, parent.transform.childCount);
+ }
+
+ [TestCase(false, false, 8f)]
+ [TestCase(true, false, 8f / 3f)]
+ [TestCase(false, true, 7f)]
+ public void NativeModelProducesTheExpectedSolid(bool pyramid, bool subtract, float expectedVolume)
+ {
+ var model = parent.AddComponent();
+ Build(Extrude(Vector2.one, pyramid ? Vector2.zero : Vector2.one));
+ if (subtract)
+ {
+ var inner = Extrude(Vector2.one, Vector2.one);
+ inner.booleanOperator = PolygonBooleanOperator.Difference;
+ var cutter = Build(inner);
+ cutter.transform.localScale = Vector3.one * 0.5f;
+ cutter.transform.localPosition = new Vector3(0, 0, 0.5f);
+ }
+ RealtimeCSG.CSGModelManager.ForceRebuild();
+ RealtimeCSG.CSGModelManager.EnsureBuildFinished();
+ var objects = RealtimeCSG.CSGModelManager.GetModelMeshes(model);
+ Assert.IsNotEmpty(objects, "The actual native CSG engine must produce renderable meshes.");
+ double volume = 0;
+ foreach (var obj in objects)
+ {
+ var filter = obj.GetComponent();
+ Assert.IsNotNull(filter);
+ Assert.IsNotNull(filter.sharedMesh);
+ var points = filter.sharedMesh.vertices.Select(v =>
+ parent.transform.InverseTransformPoint(filter.transform.TransformPoint(v))).ToArray();
+ var triangles = filter.sharedMesh.triangles;
+ Assert.IsNotEmpty(triangles);
+ for (int t = 0; t < triangles.Length; t += 3)
+ volume += Vector3.Dot(points[triangles[t]],
+ Vector3.Cross(points[triangles[t + 1]], points[triangles[t + 2]])) / 6.0;
+ }
+ Assert.That(Math.Abs(volume), Is.EqualTo(expectedVolume).Within(0.001));
+ }
+
+ [Test]
+ public void RepeatedFaceCannotCreateNonManifoldBrush()
+ {
+ var mesh = Extrude(Vector2.one, Vector2.one);
+ mesh.Add(new Polygon(mesh[0]));
+ Assert.Throws(() => Build(mesh));
+ Assert.AreEqual(0, parent.transform.childCount);
+ }
+}
diff --git a/Tests~/Editor/PolygonMeshDemo.cs b/Tests~/Editor/PolygonMeshDemo.cs
new file mode 100644
index 0000000..9095685
--- /dev/null
+++ b/Tests~/Editor/PolygonMeshDemo.cs
@@ -0,0 +1,81 @@
+using System.Linq;
+using AeternumGames.ShapeEditor;
+using RealtimeCSG;
+using RealtimeCSG.Components;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+
+public static class PolygonMeshDemo
+{
+ [MenuItem("Tools/ShapeEditor Validation/Create demo in current scene")]
+ public static void Create()
+ {
+ var root = new GameObject("Polygon topology validation");
+ for (int i = 0; i < 4; i++)
+ {
+ var model = new GameObject(new[] { "Cube", "Back-zero pyramid", "Front-zero pyramid", "Subtracted cube" }[i]);
+ model.transform.SetParent(root.transform, false);
+ model.transform.localPosition = new Vector3((i - 1.5f) * 3, 0, 0);
+ model.AddComponent();
+ Build(model.transform, i == 2 ? Vector2.zero : Vector2.one, i == 1 ? Vector2.zero : Vector2.one, false);
+ if (i == 3)
+ {
+ var cutter = Build(model.transform, Vector2.one, Vector2.one, true);
+ cutter.transform.localScale = new Vector3(0.5f, 0.5f, 1.5f);
+ cutter.transform.localPosition = new Vector3(0, 0, -0.5f);
+ }
+ }
+ CSGModelManager.ForceRebuild();
+ CSGModelManager.EnsureBuildFinished();
+ Selection.activeGameObject = root;
+ var view = SceneView.lastActiveSceneView;
+ if (view)
+ {
+ view.LookAt(new Vector3(0, 0, 1), Quaternion.Euler(20, -20, 0), 8);
+ view.Repaint();
+ }
+ }
+
+ public static void CreateAndSave()
+ {
+ Create();
+ EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), "Assets/PolygonTopologyDemo.unity");
+ }
+
+ [MenuItem("Tools/ShapeEditor Validation/Apply built-in demo material")]
+ public static void ApplyDemoMaterial()
+ {
+ var root = GameObject.Find("Polygon topology validation");
+ if (!root) return;
+ const string path = "Assets/PolygonTopologyDemo.mat";
+ var material = AssetDatabase.LoadAssetAtPath(path);
+ if (!material)
+ {
+ material = new Material(Shader.Find("Standard"));
+ material.color = new Color(0.2f, 0.65f, 0.9f);
+ AssetDatabase.CreateAsset(material, path);
+ }
+ foreach (var brush in root.GetComponentsInChildren())
+ {
+ for (int i = 0; i < brush.Shape.TexGens.Length; i++) brush.Shape.TexGens[i].RenderMaterial = material;
+ EditorUtility.SetDirty(brush);
+ }
+ CSGModelManager.ForceRebuild();
+ CSGModelManager.EnsureBuildFinished();
+ var view = SceneView.lastActiveSceneView;
+ if (view) { view.LookAt(new Vector3(0, 0, 1), Quaternion.Euler(20, -20, 0), 6); view.Repaint(); }
+ EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), "Assets/PolygonTopologyDemo.unity");
+ }
+
+ private static CSGBrush Build(Transform parent, Vector2 front, Vector2 back, bool subtract)
+ {
+ var polygon = new Polygon(new[] {
+ new Vertex(new Vector3(-1,-1,0), Vector2.zero), new Vertex(new Vector3(1,-1,0), Vector2.zero),
+ new Vertex(new Vector3(1,1,0), Vector2.zero), new Vertex(new Vector3(-1,1,0), Vector2.zero)
+ });
+ var mesh = MeshGenerator.CreateScaleExtrudedMeshes(new PolygonMesh { polygon }, 2, front, back, Vector2.zero).Single();
+ if (subtract) mesh.booleanOperator = PolygonBooleanOperator.Difference;
+ return (CSGBrush)ExternalRealtimeCSG.CreateBrushFromPolygonMesh(parent, subtract ? "Cutter" : "Brush", mesh);
+ }
+}
diff --git a/Tests~/Editor/ShapeEditor.RealtimeCSG.Tests.asmdef b/Tests~/Editor/ShapeEditor.RealtimeCSG.Tests.asmdef
new file mode 100644
index 0000000..310d588
--- /dev/null
+++ b/Tests~/Editor/ShapeEditor.RealtimeCSG.Tests.asmdef
@@ -0,0 +1,6 @@
+{
+ "name": "ShapeEditor.RealtimeCSG.Tests",
+ "references": ["com.aeternumgames.shapeeditor", "RealtimeCSG"],
+ "includePlatforms": ["Editor"],
+ "optionalUnityReferences": ["TestAssemblies"]
+}
diff --git a/Tests~/Evidence/polygon-benchmark.csv b/Tests~/Evidence/polygon-benchmark.csv
new file mode 100644
index 0000000..46bf149
--- /dev/null
+++ b/Tests~/Evidence/polygon-benchmark.csv
@@ -0,0 +1,5 @@
+sides,faces,half_edges,direct_median_ms,planes_median_ms
+4,6,24,0.084600,0.094200
+16,18,96,0.229800,2.642700
+64,66,384,0.888300,204.867500
+128,130,768,2.035500,2121.979900
diff --git a/Tests~/Evidence/test-results.json b/Tests~/Evidence/test-results.json
new file mode 100644
index 0000000..26983af
--- /dev/null
+++ b/Tests~/Evidence/test-results.json
@@ -0,0 +1,48 @@
+{
+ "editor": "2022.3.62f1 (4af31df58517)",
+ "platform": "Windows x64",
+ "realtimecsg_commit": "8ea1d81e917c538d8f4563327c2c657b50a355f0",
+ "result": "Passed",
+ "total": 9,
+ "passed": 9,
+ "failed": 0,
+ "start_utc": "2026-09-15 02:26:02Z",
+ "tests": [
+ {
+ "name": "CubeRetainsLocalGeometryAndDoesNotMutateInput",
+ "result": "Passed"
+ },
+ {
+ "name": "MaterialSlotsAndSubtractionSurviveConversion",
+ "result": "Passed"
+ },
+ {
+ "name": "MissingFaceCannotCreatePartialSceneObject",
+ "result": "Passed"
+ },
+ {
+ "name": "NativeModelProducesTheExpectedSolid(False,False,8.0f)",
+ "result": "Passed"
+ },
+ {
+ "name": "NativeModelProducesTheExpectedSolid(True,False,2.666667f)",
+ "result": "Passed"
+ },
+ {
+ "name": "NativeModelProducesTheExpectedSolid(False,True,7.0f)",
+ "result": "Passed"
+ },
+ {
+ "name": "RepeatedFaceCannotCreateNonManifoldBrush",
+ "result": "Passed"
+ },
+ {
+ "name": "ZeroScaleCapBecomesAPyramid(False)",
+ "result": "Passed"
+ },
+ {
+ "name": "ZeroScaleCapBecomesAPyramid(True)",
+ "result": "Passed"
+ }
+ ]
+}
diff --git a/Tests~/Evidence/unity-scene.png b/Tests~/Evidence/unity-scene.png
new file mode 100644
index 0000000..5beb32b
Binary files /dev/null and b/Tests~/Evidence/unity-scene.png differ
diff --git a/Tests~/README.md b/Tests~/README.md
new file mode 100644
index 0000000..9e3a4e4
--- /dev/null
+++ b/Tests~/README.md
@@ -0,0 +1,62 @@
+# RealtimeCSG integration tests
+
+These are Unity EditMode tests. They require the real RealtimeCSG package and
+native Windows x64 or macOS plugin. A standalone C# compilation with Unity stubs
+is not sufficient evidence.
+
+1. Create an empty Unity 2022.3.62f1 project.
+2. Add this checkout and `LogicalError/realtime-CSG-for-unity` through Package
+ Manager. For the initial validation environment, the RealtimeCSG checkout is
+ pinned at `8ea1d81e917c538d8f4563327c2c657b50a355f0`.
+3. Install Unity Test Framework 1.1.33 and copy `Editor/` from this folder to
+ the project's `Assets/Tests/Editor`.
+4. Run the EditMode suite, or invoke the Editor with `-batchmode -runTests
+ -testPlatform EditMode -projectPath -testResults
+ -logFile `.
+
+The tests use ShapeEditor's own scaled-extrusion generator for cubes and
+pyramids. They check half-edge reciprocity, input immutability, parent transforms,
+materials, subtraction, and rejection of open/non-manifold inputs before any
+scene object is created. Interactive scene verification is also required before
+calling the integration complete.
+
+Validated on Windows x64 with Unity 2022.3.62f1 and the RealtimeCSG revision
+above: **9 tests passed, 0 failed**, 2026-09-15. This includes actual native
+model generation with measured cube (8), pyramid (8/3), and subtracted-cube
+(7) volumes. The minimal project also needs Unity's built-in UI and UIElements
+modules, which RealtimeCSG references.
+
+## Measured creation time
+
+Run `PolygonMeshBenchmark.Run` with Unity's `-executeMethod`. The benchmark
+warms both implementations, alternates their order, and reports the median of
+seven samples. It measures brush creation including the conversion and parenting;
+object destruction and the later native model rebuild are outside the timer.
+The original `ToMaterialPlanes` + `CreateBrushFromPlanes` path is the baseline.
+These local timings are not a frame-rate or whole-editor performance claim.
+
+| Extruded polygon sides | Direct topology (ms) | Original planes (ms) |
+| --- | ---: | ---: |
+| 4 | 0.0846 | 0.0942 |
+| 16 | 0.2298 | 2.6427 |
+| 64 | 0.8883 | 204.8675 |
+| 128 | 2.0355 | 2121.9799 |
+
+## Interactive scene check
+
+With the test files copied into the project, run Tools → ShapeEditor Validation
+→ Create demo in current scene. This adds a cube, both zero-cap pyramids, and a
+cube with a through-hole. All four were inspected in the real Editor after the
+native CSG rebuild. The demo's second menu item applies a Standard material.
+
+The pinned RealtimeCSG checkout's default Wall material refers to shader GUID
+`933532a4fcc9baf4fa0491de14d08ed7`, absent from that checkout. Its default material
+displayed pink in this minimal built-in-renderer project. The scene check uses
+an explicitly assigned Standard material; the package's material assets were
+not modified. Default-material rendering is therefore an environment limitation,
+not evidence of the topology conversion failing.
+
+
+
+Sanitized test results and raw benchmark numbers are in `Evidence/`. Original
+Editor logs are intentionally excluded because they can contain login tokens.