Soul fixes for the emitter gate: refuse-side tests, normal matrix, geometry-hiding extensions only, one quarter-turn authority
The tests now cover the dot == 0 and tilted cases, vertex normals against the winding, a mirrored node and a non-uniform scale, and allowed and refused extensions. Vertex normals take the inverse transpose of the node's world matrix. Only KHR_draco_mesh_compression and EXT_meshopt_compression, which store geometry the gate cannot read, are refused; other extensions pass. The generator refuses a thruster emitter yaw that is not a quarter turn, so the gate's four-direction Rotation is the one authority for which way an emitter faces. An emitter anchor with no thruster hardpoint stays skipped in the gate: ShipAuthoringStore.Validate already refuses it before Bind. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
28666e3550
commit
a8ccfac6f1
4 changed files with 125 additions and 2 deletions
|
|
@ -308,6 +308,8 @@ public static class ShipModCatalog
|
|||
foreach (var anchor in emitters)
|
||||
{
|
||||
var hardpoint = hull.Hardpoints.FirstOrDefault(candidate => candidate.Type == HardpointType.Thruster && candidate.Transform == anchor.Id);
|
||||
// An emitter anchor with no thruster hardpoint is already a package fault: ShipAuthoringStore.Validate (run by Read and
|
||||
// PackageOf before Bind) refuses a mount-role anchor that is not the mount of a hardpoint of its type.
|
||||
if (hardpoint == null) continue;
|
||||
var facing = hardpoint.Rotation.Direction();
|
||||
// The model's frame is glTF's, nose toward +Z and port toward +X (the Blender kit's nose at -Y and port at +X,
|
||||
|
|
@ -353,7 +355,9 @@ public static class ShipModCatalog
|
|||
foreach (var primitive in (JArray)_json["meshes"][meshIndex.Value]["primitives"])
|
||||
{
|
||||
var attributes = (JObject)primitive["attributes"];
|
||||
if (primitive["extensions"] != null) throw Unreadable($"mesh {meshIndex} uses a primitive extension");
|
||||
if (primitive["extensions"] is JObject extensions && extensions.Properties().Any(p => HidesGeometry(p.Name)))
|
||||
throw Unreadable($"mesh {meshIndex} is compressed by {extensions.Properties().First(p => HidesGeometry(p.Name)).Name}");
|
||||
var normalMatrix = Matrix4x4.Invert(world, out var inverse) ? Matrix4x4.Transpose(inverse) : throw Unreadable($"node {node} has a transform that cannot be inverted");
|
||||
var positions = Vectors((int)attributes["POSITION"]).Select(point => Vector3.Transform(point, world)).ToArray();
|
||||
var indices = primitive["indices"] == null ? Enumerable.Range(0, positions.Length).ToArray() : Indices((int)primitive["indices"]);
|
||||
for (var i = 0; i + 2 < indices.Length; i += 3)
|
||||
|
|
@ -364,7 +368,7 @@ public static class ShipModCatalog
|
|||
}
|
||||
if (attributes["NORMAL"] != null)
|
||||
foreach (var normal in Vectors((int)attributes["NORMAL"]))
|
||||
if (normal.LengthSquared() > 1e-12f) yield return Vector3.Normalize(Vector3.TransformNormal(normal, world));
|
||||
if (normal.LengthSquared() > 1e-12f) yield return Vector3.Normalize(Vector3.TransformNormal(normal, normalMatrix));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -406,6 +410,8 @@ public static class ShipModCatalog
|
|||
var a = (JObject)_json["accessors"][accessor];
|
||||
if (a["sparse"] != null || a["bufferView"] == null) throw Unreadable($"accessor {accessor} is sparse or has no buffer view");
|
||||
var view = (JObject)_json["bufferViews"][(int)a["bufferView"]];
|
||||
if (view["extensions"] is JObject viewExtensions && viewExtensions.Properties().Any(p => HidesGeometry(p.Name)))
|
||||
throw Unreadable($"accessor {accessor} is compressed by {viewExtensions.Properties().First(p => HidesGeometry(p.Name)).Name}");
|
||||
var component = (int)a["componentType"];
|
||||
var type = (string)a["type"];
|
||||
var width = (component == 5126 || component == 5125 ? 4 : component == 5123 ? 2 : 1) * (type == "VEC3" ? 3 : 1);
|
||||
|
|
@ -442,6 +448,10 @@ public static class ShipModCatalog
|
|||
return result;
|
||||
}
|
||||
|
||||
// The extensions that store geometry in a form this reader does not decode; any other (materials, variants) leaves the
|
||||
// positions and normals where the accessors say.
|
||||
private static bool HidesGeometry(string extension) => extension == "KHR_draco_mesh_compression" || extension == "EXT_meshopt_compression";
|
||||
|
||||
private InvalidOperationException Unreadable(string reason) => new InvalidOperationException($"{_path}: emitter geometry is unreadable: {reason}.");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
|
||||
// A directional thruster's emitter mesh is the surface its exhaust is born from, along each triangle's normal, so every
|
||||
|
|
@ -67,4 +68,103 @@ public sealed class ShipEmitterExhaustTests : IDisposable
|
|||
foreach (var ship in new[] { Path.Combine("GameData", "Mods", "aetheria.nakovalnya"), Path.Combine("tests", "fixtures", "mods", "aetheria.wren") })
|
||||
Assert.NotNull(ShipModCatalog.ReadPackage(Path.Combine(root, ship, "ship.cc")));
|
||||
}
|
||||
|
||||
// The fixture package whose thruster node carries a mesh of the test's own (a third mesh appended to the BIN chunk), with
|
||||
// optional vertex normals, an edit to the node, and an edit to the primitive. The thruster's Rotation is None: the exhaust
|
||||
// leaves toward +Z and the push is -Z.
|
||||
private string WriteCustom(float[] positions, ushort[] indices, float[] normals = null, Action<JObject> node = null, Action<JObject> primitive = null)
|
||||
{
|
||||
ShipFixture.WritePackage(_directory.Path, "mod.skiff");
|
||||
var json = JObject.Parse(ShipFixture.GlbJson(ShipFixture.Nodes));
|
||||
var bin = ShipFixture.MeshBytes().ToList();
|
||||
int View(byte[] bytes)
|
||||
{
|
||||
while (bin.Count % 4 != 0) bin.Add(0);
|
||||
((JArray)json["bufferViews"]).Add(new JObject { ["buffer"] = 0, ["byteOffset"] = bin.Count, ["byteLength"] = bytes.Length });
|
||||
bin.AddRange(bytes);
|
||||
return ((JArray)json["bufferViews"]).Count - 1;
|
||||
}
|
||||
int Accessor(int view, int component, int count, string type)
|
||||
{
|
||||
((JArray)json["accessors"]).Add(new JObject { ["bufferView"] = view, ["componentType"] = component, ["count"] = count, ["type"] = type });
|
||||
return ((JArray)json["accessors"]).Count - 1;
|
||||
}
|
||||
var attributes = new JObject { ["POSITION"] = Accessor(View(positions.SelectMany(BitConverter.GetBytes).ToArray()), 5126, positions.Length / 3, "VEC3") };
|
||||
if (normals != null) attributes["NORMAL"] = Accessor(View(normals.SelectMany(BitConverter.GetBytes).ToArray()), 5126, normals.Length / 3, "VEC3");
|
||||
var made = new JObject { ["attributes"] = attributes, ["indices"] = Accessor(View(indices.SelectMany(BitConverter.GetBytes).ToArray()), 5123, indices.Length, "SCALAR") };
|
||||
primitive?.Invoke(made);
|
||||
((JArray)json["meshes"]).Add(new JObject { ["primitives"] = new JArray(made) });
|
||||
var thruster = json["nodes"].Single(n => (string)n["name"] == "thruster-port");
|
||||
thruster["mesh"] = ((JArray)json["meshes"]).Count - 1;
|
||||
node?.Invoke((JObject)thruster);
|
||||
json["buffers"][0]["byteLength"] = bin.Count + (4 - bin.Count % 4) % 4;
|
||||
File.WriteAllBytes(Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"), ShipFixture.Glb(json.ToString(Newtonsoft.Json.Formatting.None), bin.ToArray()));
|
||||
return Thruster;
|
||||
}
|
||||
|
||||
private static readonly ushort[] Quad = { 0, 1, 2, 0, 2, 3 };
|
||||
|
||||
// A unit quad with counter-clockwise normal n (in the XZ plane's span: n = (sin a, 0, cos a)), a measured from +Z.
|
||||
private static float[] Plane(double degrees)
|
||||
{
|
||||
var (s, c) = (Math.Sin(degrees * Math.PI / 180), Math.Cos(degrees * Math.PI / 180));
|
||||
var t = new[] { (float)c, 0f, (float)-s };
|
||||
return new[] { 0f, 0f, 0f, t[0], 0f, t[2], t[0], 1f, t[2], 0f, 1f, 0f };
|
||||
}
|
||||
|
||||
private static float[] Repeat(float x, float y, float z) => Enumerable.Repeat(new[] { x, y, z }, 4).SelectMany(v => v).ToArray();
|
||||
|
||||
private bool Accepts(string ship)
|
||||
{
|
||||
try { ShipModCatalog.ReadPackage(ship); return true; }
|
||||
catch (InvalidOperationException error) when (error.Message.Contains("thruster emitter thruster.port")) { return false; }
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, true), InlineData(60, true), InlineData(-60, true), InlineData(89, true), InlineData(-89, true),
|
||||
InlineData(91, false), InlineData(-91, false), InlineData(120, false), InlineData(180, false)]
|
||||
public void ATiltedEmitterIsJudgedByItsDotWithThePush(double degrees, bool accepted) =>
|
||||
Assert.Equal(accepted, Accepts(WriteCustom(Plane(degrees), Quad)));
|
||||
|
||||
[Fact]
|
||||
public void VertexNormalsThatContradictTheWindingAreRefused()
|
||||
{
|
||||
// Unity's Mesh Renderer shape emits along the vertex normals, so a face wound toward the exhaust is not enough.
|
||||
Assert.True(Accepts(WriteCustom(Plane(0), Quad, Repeat(0, 0, 1))));
|
||||
Assert.False(Accepts(WriteCustom(Plane(0), Quad, Repeat(0, 0, -1))));
|
||||
Assert.False(Accepts(WriteCustom(Plane(0), Quad, Repeat(1, 0, 0))));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMirroredNodeFlipsTheWindingAndIsJudgedByWhatItDrawsNotWhatItIsWound()
|
||||
{
|
||||
// Scaled -1 in X the quad's winding reverses in the world, so glTF's front face is the other one.
|
||||
Action<JObject> mirror = node => node["scale"] = new JArray(-1, 1, 1);
|
||||
Assert.True(Accepts(WriteCustom(Plane(0), Quad, node: mirror)));
|
||||
Assert.False(Accepts(WriteCustom(Plane(180), Quad, node: mirror)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VertexNormalsFollowTheInverseTransposeUnderNonUniformScale()
|
||||
{
|
||||
// A quarter turn's eighth about Y over a stretch of 4 in X: the plane with local normal (1,0,1) keeps a normal toward
|
||||
// +Z (0.75 of it), where transforming the normal like a position would send it toward -Z.
|
||||
Action<JObject> stretched = node => { node["scale"] = new JArray(4, 1, 1); node["rotation"] = new JArray(0, 0.3826834f, 0, 0.9238795f); };
|
||||
var tangent = (float)(1 / Math.Sqrt(2));
|
||||
var positions = new[] { 0f, 0f, 0f, tangent, 0f, -tangent, tangent, 1f, -tangent, 0f, 1f, 0f };
|
||||
Assert.True(Accepts(WriteCustom(positions, Quad, Repeat(tangent, 0, tangent), stretched)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyExtensionsThatHideGeometryAreRefused()
|
||||
{
|
||||
Assert.True(Accepts(WriteCustom(Plane(0), Quad, primitive: p => p["extensions"] = JObject.Parse(@"{""KHR_materials_variants"":{""mappings"":[]}}"))));
|
||||
var compressed = WriteCustom(Plane(0), Quad, primitive: p => p["extensions"] = JObject.Parse(@"{""KHR_draco_mesh_compression"":{""bufferView"":0,""attributes"":{""POSITION"":0}}}"));
|
||||
Assert.Contains("compressed by KHR_draco_mesh_compression", Assert.Throws<InvalidOperationException>(() => ShipModCatalog.ReadPackage(compressed)).Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASidewaysEmitterWhoseNormalIsPerpendicularToThePushIsRefused() =>
|
||||
// Normal exactly +X, dot with the push exactly 0: the rule is non-negative, so it fires along the axis it is not meant to.
|
||||
Assert.False(Accepts(WriteCustom(new[] { 0f, 0f, 0f, 0f, 1f, 0f, 0f, 1f, 1f, 0f, 0f, 1f }, Quad)));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -464,6 +464,10 @@ def build(runner, library, hull_type, projector):
|
|||
anchor_meshes = {a.id: parse_off(runner(MESH_ROLES[a.role] + a.id)[0]) for a in anchors if a.role in MESH_ROLES}
|
||||
for a in anchors:
|
||||
if a.role == "thruster-emitter":
|
||||
# The hardpoint Rotation the catalog gate judges the emitter against is one of four directions, so the one authority
|
||||
# for which way an emitter faces is a quarter turn; a source that turns one otherwise is refused here, not rounded.
|
||||
if abs(a.yaw / 90 - round(a.yaw / 90)) > 1e-6:
|
||||
raise HullSourceError("The hull source turns a thruster emitter by something other than a quarter turn")
|
||||
anchor_meshes[a.id] = exhaust_face(anchor_meshes[a.id], a.yaw)
|
||||
kit_lines = read_lines(runner("lines")[1])
|
||||
judge = donor or own
|
||||
|
|
|
|||
|
|
@ -410,6 +410,15 @@ class JudgementTests(unittest.TestCase):
|
|||
self.assertEqual(len(mesh.triangles), 2, yaw)
|
||||
self.assertEqual(set(self._normals(mesh)), {facing}, yaw)
|
||||
|
||||
def test_an_emitter_turned_off_a_quarter_turn_is_refused(self):
|
||||
# The gate knows four directions (a hardpoint Rotation); an emitter yawed 45 degrees has none, so it is not rounded.
|
||||
fixture = Fixture()
|
||||
fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""])
|
||||
+ echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, -3, 3], 0, "Gun.A"])
|
||||
+ echo("anchor", ["Th.A", "thruster-emitter", [1, 5, 1], 45, ""]))
|
||||
with self.assertRaises(hs.HullSourceError):
|
||||
fixture.build()
|
||||
|
||||
def test_an_emitter_with_no_side_facing_its_exhaust_is_refused(self):
|
||||
# A single quad that faces the push, not the exhaust, has nothing left once the wrong side is dropped.
|
||||
fixture = Fixture()
|
||||
|
|
|
|||
Loading…
Reference in a new issue