Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions Scripts/Editor/Scene/RealtimeCSGTarget.FixedExtrude.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 1 addition & 5 deletions Scripts/Editor/Scene/RealtimeCSGTarget.LinearStaircase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 1 addition & 5 deletions Scripts/Editor/Scene/RealtimeCSGTarget.RevolveChopped.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 1 addition & 5 deletions Scripts/Editor/Scene/RealtimeCSGTarget.RevolveExtrude.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 1 addition & 5 deletions Scripts/Editor/Scene/RealtimeCSGTarget.ScaledExtrude.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 1 addition & 5 deletions Scripts/Editor/Scene/RealtimeCSGTarget.SplineExtrude.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
14 changes: 14 additions & 0 deletions Scripts/Editor/Scene/RealtimeCSGTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
102 changes: 102 additions & 0 deletions Scripts/Utilities/ExternalRealtimeCSG.PolygonMesh.cs
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions Scripts/Utilities/ExternalRealtimeCSG.PolygonMesh.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Scripts/Utilities/ExternalRealtimeCSG.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace AeternumGames.ShapeEditor
/// <summary>
/// Provides communication with RealtimeCSG through reflection.
/// </summary>
public class ExternalRealtimeCSG
public partial class ExternalRealtimeCSG
{
/// <summary>
/// The cached RealtimeCSG.Legacy.BrushFactory type after initialization.
Expand Down
95 changes: 95 additions & 0 deletions Scripts/Utilities/PolygonMeshTopology.cs
Original file line number Diff line number Diff line change
@@ -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<Vector3>();
var indices = new Dictionary<Vector3, int>();
var faces = new List<int[]>();
var sources = new List<int>();
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<int>();
// 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<int>(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<int>();
var edgeFaces = new List<int>();
var directed = new Dictionary<long, int>();
var starts = new List<int>();
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
2 changes: 2 additions & 0 deletions Scripts/Utilities/PolygonMeshTopology.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

69 changes: 69 additions & 0 deletions Tests~/Editor/PolygonMeshBenchmark.cs
Original file line number Diff line number Diff line change
@@ -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<MonoBehaviour> direct = () => ExternalRealtimeCSG.CreateBrushFromPolygonMesh(parent.transform, "Direct", mesh);
Func<MonoBehaviour> 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<MonoBehaviour> 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);
}
}
Loading