From 28666e3550f70dc9bdf117fb0e468769214a2d90 Mon Sep 17 00:00:00 2001 From: soul Date: Thu, 19 Nov 2026 19:39:03 +0100 Subject: [PATCH] A directional thruster's emitter is one-sided, and the catalog refuses one that fires along its push The exhaust is born along each triangle's normal of the emitter mesh, and every Nakovalnya, Wren and starter emitter was a thin closed box, so it fired both ways along the thruster axis. The generator now writes one side: hull_source keeps of a hull source's emit mesh only the triangles facing its anchor's yaw (the exhaust), and the starter's thruster boxes carry a single exhaust face. ShipModCatalog.Bind, which Compose and ship-authoring validate both run, reads the emitter geometry from the GLB (world transform included) and refuses a directional thruster whose emitter has any face or vertex normal with a non-negative dot with the push, naming the anchor. The rule is the directional class's alone; a ring thruster would bring its own. The Nakovalnya and Wren ship.glb are regenerated through Build + Package and the starter; ship.cc, anchors, node indices and every non-emitter node are unchanged. Blender smokes and the test GLBs now give thrusters an exhaust-facing emitter and a matching Rotation. Co-Authored-By: Claude Sonnet 5.5 --- Assets/Scripts/ServerShared/ShipModCatalog.cs | 152 ++++++++++++++++++ GameData/Mods/aetheria.nakovalnya/ship.glb | 4 +- docs/moddable-ship-authoring.md | 7 +- .../ShipEmitterExhaustTests.cs | 70 ++++++++ tests/Aetheria.Shared.Tests/ShipFixture.cs | 27 +++- tests/Aetheria.Shared.Tests/ShipRigTests.cs | 8 +- tests/fixtures/mods/aetheria.wren/ship.glb | 4 +- tools/AetherDb/ShipStarterCommand.cs | 11 +- tools/blender/aetheria_ships/hull_source.py | 28 +++- tools/blender/tests/smoke_hull_source.py | 9 +- tools/blender/tests/smoke_mounts.py | 10 +- tools/blender/tests/smoke_package.py | 10 +- tools/blender/tests/test_hull_source.py | 38 ++++- 13 files changed, 349 insertions(+), 29 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs index 0e5bd801c..6d509f011 100644 --- a/Assets/Scripts/ServerShared/ShipModCatalog.cs +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using GameCult.Caching; using Newtonsoft.Json.Linq; +using System.Numerics; using System.Text; // Builds the one catalog snapshot CultCache needs. Sources remain the shipped catalog and each @@ -284,6 +285,7 @@ public static class ShipModCatalog foreach (var anchor in ship.Anchors) if (anchor.Role == "shield" && !modelNodes[anchor.ModelNodeId].PositiveScale) throw new InvalidOperationException($"{ship.Id}: shield anchor {anchor.Id} needs three positive scale radii on model node {anchor.ModelNodeId}, with no matrix."); + BindExhaust(hull, ship, modelNodes, modelPath); BindRig(ship, modelNodes); CultRecordRefs.Validate(hull); return new Package @@ -293,6 +295,156 @@ public static class ShipModCatalog }; } + // A thruster emitter's mesh is the surface its exhaust is born from, along each triangle's normal, so the mesh has to face + // the way the exhaust goes. Every thruster is a directional thruster today: its Rotation faces its exhaust, the push + // is the opposite way, and an emitter triangle whose normal has a non-negative dot with the push would fire exhaust + // along it (a closed box fires both ways). A thruster of another class, a ring thruster whose exhaust leaves radially, + // is not this rule's to judge: it would come with its own class on the hardpoint and its own rule beside this one. + private static void BindExhaust(HullData hull, ShipAuthoring ship, Dictionary nodes, string modelPath) + { + var emitters = ship.Anchors.Where(anchor => anchor.Role == "thruster-emitter").ToArray(); + if (emitters.Length == 0) return; + var model = GlbGeometry.Read(modelPath); + foreach (var anchor in emitters) + { + var hardpoint = hull.Hardpoints.FirstOrDefault(candidate => candidate.Type == HardpointType.Thruster && candidate.Transform == anchor.Id); + 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, + // through the exporter's Y-up conversion): a hardpoint facing (x, y) in the grid faces (-x, 0, y) in the model. + var push = -new Vector3(-facing.x, 0f, facing.y); + var wrong = model.Normals((int)nodes[anchor.ModelNodeId].Index).Count(normal => Vector3.Dot(normal, push) >= 0f); + if (wrong > 0) + throw new InvalidOperationException($"{ship.Id}: thruster emitter {anchor.Id} has {wrong} face or vertex normal(s) that do not face its exhaust " + + $"({hardpoint.Rotation}); a directional thruster's emitter fires only along its exhaust, so it must be one-sided, not a closed box."); + } + } + + // The triangles of a GLB as the node tree places them, read for the one question the emitter rule asks: which way each + // face points. Float positions and normals, indices of 1, 2 or 4 bytes or none, no sparse, no compression: a model the + // exporter writes. Anything else is refused as unreadable rather than guessed at. + private sealed class GlbGeometry + { + private readonly JObject _json; + private readonly byte[] _bin; + private readonly string _path; + + private GlbGeometry(JObject json, byte[] bin, string path) { _json = json; _bin = bin; _path = path; } + + public static GlbGeometry Read(string path) + { + var bytes = File.ReadAllBytes(path); + var jsonLength = (int)BitConverter.ToUInt32(bytes, 12); + var json = JObject.Parse(Encoding.UTF8.GetString(bytes, 20, jsonLength)); + var at = 20 + jsonLength; + var bin = at + 8 <= bytes.Length && BitConverter.ToUInt32(bytes, at + 4) == 0x004E4942u + ? bytes.Skip(at + 8).Take((int)BitConverter.ToUInt32(bytes, at)).ToArray() : Array.Empty(); + return new GlbGeometry(json, bin, path); + } + + // Unit normals in the model frame: each triangle's face normal (its winding, flipped when the node's world transform + // mirrors, as glTF says) and each vertex normal the primitive carries. + public IEnumerable Normals(int node) + { + var world = World(node); + var mirrored = world.GetDeterminant() < 0f; + var meshIndex = (int?)_json["nodes"][node]["mesh"]; + if (meshIndex == null) yield break; + 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"); + 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) + { + var face = Vector3.Cross(positions[indices[i + 1]] - positions[indices[i]], positions[indices[i + 2]] - positions[indices[i]]); + if (face.LengthSquared() < 1e-12f) continue; + yield return Vector3.Normalize(mirrored ? -face : face); + } + 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)); + } + } + + // Row-vector matrices, so a child's world is its local times its parent's world. + private Matrix4x4 World(int node) + { + var parents = new Dictionary(); + var nodes = (JArray)_json["nodes"]; + for (var parent = 0; parent < nodes.Count; parent++) + foreach (var child in nodes[parent]["children"]?.Select(token => (int)token) ?? Enumerable.Empty()) parents[child] = parent; + var world = Matrix4x4.Identity; + for (int at = node, steps = 0; steps <= nodes.Count; steps++) + { + world *= Local((JObject)nodes[at]); + if (!parents.TryGetValue(at, out at)) break; + } + return world; + } + + private static Matrix4x4 Local(JObject node) + { + if (node["matrix"] is JArray m) + { + var v = m.Select(token => (float)token).ToArray(); + return new Matrix4x4(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14], v[15]); + } + float[] Of(string key, float[] fallback) => node[key] is JArray a ? a.Select(token => (float)token).ToArray() : fallback; + var scale = Of("scale", new[] { 1f, 1f, 1f }); + var rotation = Of("rotation", new[] { 0f, 0f, 0f, 1f }); + var translation = Of("translation", new[] { 0f, 0f, 0f }); + return Matrix4x4.CreateScale(scale[0], scale[1], scale[2]) * + Matrix4x4.CreateFromQuaternion(new Quaternion(rotation[0], rotation[1], rotation[2], rotation[3])) * + Matrix4x4.CreateTranslation(translation[0], translation[1], translation[2]); + } + + // The bytes an accessor reads from: its view's slice of the BIN chunk, at the view's stride. + private (int Offset, int Stride, int Count, int Component, string Type) Locate(int accessor) + { + 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"]]; + 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); + var offset = ((int?)view["byteOffset"] ?? 0) + ((int?)a["byteOffset"] ?? 0); + var stride = (int?)view["byteStride"] ?? width; + var count = (int)a["count"]; + if (offset < 0 || count < 0 || (count > 0 && offset + (long)(count - 1) * stride + width > _bin.Length)) throw Unreadable($"accessor {accessor} reaches past the BIN chunk"); + return (offset, stride, count, component, type); + } + + private Vector3[] Vectors(int accessor) + { + var (offset, stride, count, component, type) = Locate(accessor); + if (component != 5126 || type != "VEC3") throw Unreadable($"accessor {accessor} is not float VEC3"); + var result = new Vector3[count]; + for (var i = 0; i < count; i++) + { + var at = offset + i * stride; + result[i] = new Vector3(BitConverter.ToSingle(_bin, at), BitConverter.ToSingle(_bin, at + 4), BitConverter.ToSingle(_bin, at + 8)); + } + return result; + } + + private int[] Indices(int accessor) + { + var (offset, stride, count, component, type) = Locate(accessor); + if (type != "SCALAR" || component != 5121 && component != 5123 && component != 5125) throw Unreadable($"accessor {accessor} is not an index accessor"); + var result = new int[count]; + for (var i = 0; i < count; i++) + { + var at = offset + i * stride; + result[i] = component == 5121 ? _bin[at] : component == 5123 ? BitConverter.ToUInt16(_bin, at) : (int)BitConverter.ToUInt32(_bin, at); + } + return result; + } + + private InvalidOperationException Unreadable(string reason) => new InvalidOperationException($"{_path}: emitter geometry is unreadable: {reason}."); + } + // The rig the record states must be the rig the model has: every joint is a node, each joint's Parent and each mount's // Joint is the nearest joint above its node, ancestors without an id being walked through by ReadNodeIds, and a radiator // mesh sits under no joint. diff --git a/GameData/Mods/aetheria.nakovalnya/ship.glb b/GameData/Mods/aetheria.nakovalnya/ship.glb index 3dac76cc9..af1e370e6 100644 --- a/GameData/Mods/aetheria.nakovalnya/ship.glb +++ b/GameData/Mods/aetheria.nakovalnya/ship.glb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:90a503473e3b12251c225b7fe283b2fc5b45a25e6e47839d1c3d78e3ac61b00c -size 843452 +oid sha256:ab3fdd340bf27fc8c2a6149ce6be9159215cf26b3eabd290064ffe40b2e96512 +size 839556 diff --git a/docs/moddable-ship-authoring.md b/docs/moddable-ship-authoring.md index 81871b2dc..057b7d511 100644 --- a/docs/moddable-ship-authoring.md +++ b/docs/moddable-ship-authoring.md @@ -216,7 +216,12 @@ a radiator, `weapon-mount` for an energy, ballistic or launcher hardpoint. An internal hardpoint (reactor, sensors, shield and the rest) has no anchor, and an anchor taking its id is refused. A thruster's or radiator's anchor node is a mesh: the thruster's is not rendered and is the surface its exhaust emits from, -the radiator's is rendered. A weapon mount is a point, and each one needs at +the radiator's is rendered. A directional thruster's emitter is one-sided: the +exhaust is born along each triangle's normal, so every normal must face the way +the hardpoint's Rotation faces (opposite the push), and a closed box, which also +fires along the push, is refused by Compose and `validate` naming the anchor. In +the Blender kit's frame a hull source's emit mesh is cut to the side facing its +anchor's yaw. A ring thruster would be its own class with its own rule. A weapon mount is a point, and each one needs at least one `weapon-muzzle` anchor whose `ParentId` is the weapon's mount id. `articulation` is reserved for pivots and is never a mount; no pivot is planned until pivots move onto `HullData`. `ShipModPlan` then maps the diff --git a/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs new file mode 100644 index 000000000..466ee8837 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs @@ -0,0 +1,70 @@ +using System; +using System.IO; +using System.Linq; +using Xunit; + +// A directional thruster's emitter mesh is the surface its exhaust is born from, along each triangle's normal, so every +// normal must face the exhaust, opposite the push (ShipModCatalog.BindExhaust). A closed box fires both ways: the operator +// saw the same thrusters firing whichever way the ship strafed. A ring thruster is a class of its own with its own rule and +// is not exercised here. +public sealed class ShipEmitterExhaustTests : IDisposable +{ + private readonly TempDirectory _directory = new TempDirectory(); + + public void Dispose() => _directory.Dispose(); + + private string Thruster => Path.Combine(_directory.Path, "mod.skiff", "ship.cc"); + + // The fixture thruster's hardpoint Rotation is None, so its exhaust leaves toward glTF's +Z; its emitter, one quad + // wound to face +Z, is the one-sided emitter the generator writes. + private void Write(Action tweak = null, string from = null, string to = null) + { + ShipFixture.WritePackage(_directory.Path, "mod.skiff", tweak: tweak); + if (from == null) return; + var json = ShipFixture.GlbJson(ShipFixture.Nodes); + Assert.Contains(from, json); + File.WriteAllBytes(Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"), ShipFixture.Glb(json.Replace(from, to), ShipFixture.MeshBytes())); + } + + private static void Reversed(ShipParts ship) => ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "thruster.port").Rotation = ItemRotation.Reversed; + + [Fact] + public void AOneSidedEmitterFacingItsExhaustIsAccepted() + { + Write(); + Assert.Equal("mod.skiff", ShipModCatalog.ReadPackage(Thruster).Visual.Id); + } + + [Fact] + public void AClosedBoxEmitterIsRefusedNamingItsAnchor() + { + Write(from: @"""name"":""thruster-port"",""mesh"":1", to: @"""name"":""thruster-port"",""mesh"":0"); + var message = Assert.Throws(() => ShipModCatalog.ReadPackage(Thruster)).Message; + Assert.Contains("thruster emitter thruster.port", message); + Assert.Contains("one-sided", message); + } + + [Fact] + public void AnEmitterFacingTheWrongWayIsRefused() + { + // The same quad toward +Z under a thruster that now faces aft: its exhaust would leave along the push. + Write(Reversed); + Assert.Contains("thruster emitter thruster.port", Assert.Throws(() => ShipModCatalog.ReadPackage(Thruster)).Message); + } + + [Fact] + public void TheNodesTurnDecidesWhichWayTheEmitterFaces() + { + // Turned half a circle about Y, the quad's +Z becomes -Z: the exhaust of an aft-facing thruster. + Write(Reversed, from: @"""name"":""thruster-port"",""mesh"":1", to: @"""name"":""thruster-port"",""mesh"":1,""rotation"":[0,1,0,0]"); + Assert.Equal("mod.skiff", ShipModCatalog.ReadPackage(Thruster).Visual.Id); + } + + [Fact] + public void TheShippedAndFixturePackagesPass() + { + var root = RunStartTests.FindRepoRoot(); + 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"))); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipFixture.cs b/tests/Aetheria.Shared.Tests/ShipFixture.cs index 9f2e1c75f..ac41ece2f 100644 --- a/tests/Aetheria.Shared.Tests/ShipFixture.cs +++ b/tests/Aetheria.Shared.Tests/ShipFixture.cs @@ -22,22 +22,33 @@ internal static class ShipFixture 1, 0, 0, 0, 1, 0, 0, 0, 1 }; - public static byte[] MeshBytes() => Tetrahedron.SelectMany(BitConverter.GetBytes).ToArray(); + // One-sided quad in the z = 0 plane, wound counter-clockwise seen from +Z, so its normal is +Z (glTF's nose): the emitter + // of a thruster whose Rotation is None, which faces its exhaust ahead. Four vertices and six 16-bit indices follow the + // tetrahedron in the BIN chunk. + private static readonly float[] Quad = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 }; + private static readonly ushort[] QuadIndices = { 0, 1, 2, 0, 2, 3 }; + + public static byte[] MeshBytes() => + Tetrahedron.SelectMany(BitConverter.GetBytes).Concat(Quad.SelectMany(BitConverter.GetBytes)).Concat(QuadIndices.SelectMany(BitConverter.GetBytes)).ToArray(); + + // The model's geometry as glTF JSON members (meshes, accessors, bufferViews, buffers) over MeshBytes: mesh 0 is the + // tetrahedron, mesh 1 the quad. + public static string Geometry => + @"""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]},{""primitives"":[{""attributes"":{""POSITION"":1},""indices"":2}]}]," + + @"""accessors"":[{""bufferView"":0,""componentType"":5126,""count"":12,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,1]}," + + @"{""bufferView"":1,""componentType"":5126,""count"":4,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,0]}," + + @"{""bufferView"":2,""componentType"":5123,""count"":6,""type"":""SCALAR""}]," + + $@"""bufferViews"":[{{""buffer"":0,""byteLength"":144}},{{""buffer"":0,""byteOffset"":144,""byteLength"":48}},{{""buffer"":0,""byteOffset"":192,""byteLength"":12}}],""buffers"":[{{""byteLength"":{MeshBytes().Length}}}]"; // The GLB carries a glTF scene naming every node: glTFast instantiates a scene, and a scene-less file has none. // Nodes in meshNodes (default MeshNodes) get the shared tetrahedron mesh, whose vertices live in the BIN chunk (MeshBytes). public static string GlbJson(string[] nodes, string[] meshNodes = null) { meshNodes ??= MeshNodes; - var length = MeshBytes().Length; - var mesh = nodes.Any(meshNodes.Contains) - ? @",""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}]," + - @"""accessors"":[{""bufferView"":0,""componentType"":5126,""count"":12,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,1]}]," + - $@"""bufferViews"":[{{""buffer"":0,""byteLength"":{length}}}],""buffers"":[{{""byteLength"":{length}}}]" - : ""; + var mesh = nodes.Any(meshNodes.Contains) ? "," + Geometry : ""; return @"{""asset"":{""version"":""2.0""},""scene"":0,""scenes"":[{""nodes"":[" + string.Join(",", nodes.Select((_, index) => index)) + @"]}]" + mesh + @",""nodes"":[" + string.Join(",", nodes.Select(node => - $@"{{""name"":""{node}""{(meshNodes.Contains(node) ? @",""mesh"":0" : "")},""extras"":{{""aetheria.id"":""{node}""}}}}")) + "]}"; + $@"{{""name"":""{node}""{(meshNodes.Contains(node) ? node.StartsWith("thruster") ? @",""mesh"":1" : @",""mesh"":0" : "")},""extras"":{{""aetheria.id"":""{node}""}}}}")) + "]}"; } public static byte[] Glb(string json, byte[] bin = null) diff --git a/tests/Aetheria.Shared.Tests/ShipRigTests.cs b/tests/Aetheria.Shared.Tests/ShipRigTests.cs index fbad3ec05..657a2f03b 100644 --- a/tests/Aetheria.Shared.Tests/ShipRigTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipRigTests.cs @@ -209,13 +209,13 @@ public sealed class ShipRigTests : IDisposable private static string GlbJson(Node[] nodes) { - var text = new StringBuilder(@"{""asset"":{""version"":""2.0""},""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}],""nodes"":["); + var text = new StringBuilder(@"{""asset"":{""version"":""2.0""}," + ShipFixture.Geometry + @",""nodes"":["); for (var index = 0; index < nodes.Length; index++) { var node = nodes[index]; var kids = Enumerable.Range(0, nodes.Length).Where(child => nodes[child].Parent == node.Name).ToArray(); text.Append(index > 0 ? "," : "").Append($@"{{""name"":""{node.Name}"""); - if (node.Mesh) text.Append(@",""mesh"":0"); + if (node.Mesh) text.Append(node.Name.StartsWith("thruster") ? @",""mesh"":1" : @",""mesh"":0"); if (node.Id != null) text.Append($@",""extras"":{{""aetheria.id"":""{node.Id}""}}"); if (kids.Length > 0) text.Append(@",""children"":[" + string.Join(",", kids) + "]"); text.Append('}'); @@ -238,7 +238,7 @@ public sealed class ShipRigTests : IDisposable ship.Visual.Anchors.Single(anchor => anchor.Id == "gun").Joint = "wrist"; tweak?.Invoke(ship); }); - File.WriteAllBytes(Path.Combine(directory, "skiff.glb"), ShipFixture.Glb(GlbJson(nodes ?? RigNodes))); + File.WriteAllBytes(Path.Combine(directory, "skiff.glb"), ShipFixture.Glb(GlbJson(nodes ?? RigNodes), ShipFixture.MeshBytes())); return Path.Combine(directory, "ship.cc"); } @@ -348,7 +348,7 @@ public sealed class ShipRigTests : IDisposable public void NodeParentsAreTheNearestTaggedAncestorAndRootsHaveNone() { var path = Path.Combine(_directory.Path, "rig.glb"); - File.WriteAllBytes(path, ShipFixture.Glb(GlbJson(RigNodes))); + File.WriteAllBytes(path, ShipFixture.Glb(GlbJson(RigNodes), ShipFixture.MeshBytes())); var nodes = ShipModCatalog.ReadNodeIds(path); Assert.Equal(-1, nodes["arm"].Parent); Assert.Equal((int)nodes["arm"].Index, nodes["elbow"].Parent); diff --git a/tests/fixtures/mods/aetheria.wren/ship.glb b/tests/fixtures/mods/aetheria.wren/ship.glb index 03b70b729..08f3e5c7e 100644 --- a/tests/fixtures/mods/aetheria.wren/ship.glb +++ b/tests/fixtures/mods/aetheria.wren/ship.glb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:98bf1b4a0e19e67568930ca79b9d61529c21c63dd74ee8df3d3f1d419d3a81cc -size 6964 +oid sha256:3980ea88075b07bece2f64f315fde34bb7214ae0c9fb40d766556e12bb4b8a5a +size 5872 diff --git a/tools/AetherDb/ShipStarterCommand.cs b/tools/AetherDb/ShipStarterCommand.cs index 2a502a1f5..ebb3f4682 100644 --- a/tools/AetherDb/ShipStarterCommand.cs +++ b/tools/AetherDb/ShipStarterCommand.cs @@ -25,6 +25,9 @@ public static class ShipStarterCommand public float3 Position; // Box half-extents; null for an empty node. Scale is the node scale, used by the shield envelope. public float3? Half; + // A directional thruster emitter has one face, the (axis, sign) its exhaust leaves by in the Blender frame; a box with all six + // would fire exhaust both ways along the push. These drives push toward the bow (Reversed), so the exhaust leaves aft, +Y. + public (int Axis, int Sign)? Face; public float3? Scale; } @@ -43,8 +46,8 @@ public static class ShipStarterCommand new Part { Id = "collider", Role = "hull-collider", Half = new float3(3f, 5f, 1f) }, new Part { Id = "shield", Role = "shield", Scale = new float3(4f, 6f, 2.5f) }, new Part { Id = "tractor", Role = "tractor", Position = new float3(0f, -5f, 0f) }, - new Part { Id = "thruster.port", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(0, 0), Size = new int2(2, 1), Position = new float3(2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, - new Part { Id = "thruster.starboard", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(2, 0), Size = new int2(2, 1), Position = new float3(-2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, + new Part { Id = "thruster.port", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(0, 0), Size = new int2(2, 1), Position = new float3(2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f), Face = (1, 1) }, + new Part { Id = "thruster.starboard", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(2, 0), Size = new int2(2, 1), Position = new float3(-2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f), Face = (1, 1) }, new Part { Id = "radiator", Role = "radiator-mesh", Mount = HardpointType.Radiator, Cell = new int2(1, 1), Size = new int2(2, 1), Position = new float3(0f, 2f, 1.1f), Half = new float3(1.5f, .8f, .08f) }, new Part { Id = "gun.port", Role = "weapon-mount", Mount = HardpointType.Energy, Cell = new int2(0, 5), Position = new float3(1.8f, -3f, 1.1f) }, new Part { Id = "gun.port.muzzle", Role = "weapon-muzzle", Parent = "gun.port", Position = new float3(1.8f, -4f, 1.1f) }, @@ -125,8 +128,8 @@ public static class ShipStarterCommand var positions = new List(); var normals = new List(); var indices = new List(); - // Six faces, outward normals, in the Blender frame; Gltf() turns each into glTF's. - foreach (var (axis, sign) in new[] { (0, 1), (0, -1), (1, 1), (1, -1), (2, 1), (2, -1) }) + // Six faces (one for a thruster emitter), outward normals, in the Blender frame; Gltf() turns each into glTF's. + foreach (var (axis, sign) in part.Face != null ? new[] { part.Face.Value } : new[] { (0, 1), (0, -1), (1, 1), (1, -1), (2, 1), (2, -1) }) { var u = (axis + 1) % 3; var v = (axis + 2) % 3; diff --git a/tools/blender/aetheria_ships/hull_source.py b/tools/blender/aetheria_ships/hull_source.py index 2d6d0ca16..99d15c615 100644 --- a/tools/blender/aetheria_ships/hull_source.py +++ b/tools/blender/aetheria_ships/hull_source.py @@ -14,7 +14,8 @@ with it (a hull that redefines or shadows an included language fails a check): lines ECHO line = [layer, cyclic, [[x, y, z], ...]] one line per kit part that draws one, points in the Ship Root frame (lowpoly.scad lp_line under lp_at frames); layer is one of KIT_LAYERS the zone's geometry, OFF; a donor's zone is named ":" - emit:, rad: the mesh of a thruster-emitter or radiator-mesh anchor + emit:, rad: the mesh of a thruster-emitter or radiator-mesh anchor; build() keeps of an emitter only the triangles + that face its exhaust (exhaust_face), so a closed box an author draws becomes its one exhaust-facing side marks OFF, a tiny cube at the first point of each kit line, drawn through the frame the geometry is drawn in (lp_line) Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. build() also takes the hull's HullData.HullType ("Ship", @@ -183,6 +184,28 @@ def parse_off(text): return Mesh(vertices, tuple(triangles)) +def exhaust_face(mesh, yaw): + """The part of a thruster emitter's mesh that faces its exhaust, which leaves the way the anchor faces (its yaw: 0 the nose, + -Y; 90 port, +X): the triangles whose outward normal lies within 60 degrees of it, with the vertices they use. The + exhaust of a thruster is born along each triangle's normal of this mesh, so an emitter with a triangle facing the + other way fires along the push too: a directional thruster's emitter is one-sided. The hull source draws the surface + in whatever solid is convenient (a thin box); the closed sides drop here, and a mesh with no side facing the exhaust + is left empty, which the emitter-has-a-mesh check refuses. A future ring thruster, whose exhaust leaves radially, is a + different emitter with its own rule and does not come through here.""" + facing = (math.sin(math.radians(yaw)), -math.cos(math.radians(yaw))) + kept = [] + for a, b, c in mesh.triangles: + pa, pb, pc = mesh.vertices[a], mesh.vertices[b], mesh.vertices[c] + u, v = [pb[i] - pa[i] for i in range(3)], [pc[i] - pa[i] for i in range(3)] + normal = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) + length = math.sqrt(sum(n * n for n in normal)) + if length > 0 and (normal[0] * facing[0] + normal[1] * facing[1]) / length > 0.5: + kept.append((a, b, c)) + used = sorted({i for tri in kept for i in tri}) + renumber = {old: new for new, old in enumerate(used)} + return Mesh(tuple(mesh.vertices[i] for i in used), tuple(tuple(renumber[i] for i in tri) for tri in kept)) + + def parse_echoes(text, name): """The values of every 'ECHO: = ' line. OpenSCAD prints JSON-compatible values.""" values = [] @@ -439,6 +462,9 @@ def build(runner, library, hull_type, projector): if len(set(ids)) != len(ids) or any(a.role not in ANCHOR_ROLES for a in anchors): raise HullSourceError("The hull source's anchors repeat an id or name a role a hull source does not make") 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": + anchor_meshes[a.id] = exhaust_face(anchor_meshes[a.id], a.yaw) kit_lines = read_lines(runner("lines")[1]) judge = donor or own body_zone = f"{donor.faction}:{donor.body}" if donor else own.body diff --git a/tools/blender/tests/smoke_hull_source.py b/tools/blender/tests/smoke_hull_source.py index a3676b0c7..3916eeefa 100644 --- a/tools/blender/tests/smoke_hull_source.py +++ b/tools/blender/tests/smoke_hull_source.py @@ -167,6 +167,8 @@ def make_ship(scene, fixture, ship_id, extent, length, rows): bpy.ops.aetheria.add_ship_hardpoint() hp = state.hardpoints[len(state.hardpoints) - 1] hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint = mount_id, kind, x, y, "#" + if kind == THRUSTER: + hp.rotation = "2" # Reversed: the hull sources' drives sit at the stern, their emitters yawed 180 so the exhaust leaves aft result, message = run(bpy.ops.aetheria.save_ship_layout) require(result == {"FINISHED"}, f"Save was refused: {message}") package = MODS / ship_id @@ -586,7 +588,7 @@ def shared_ids_refused(scene, box, collection, ship_id, package, objects, number def check_poses(collection, root, runner): """Every built anchor stands where the hull source says in Ship Root's frame, turned as it says, and the emitter and - radiator meshes are the source's meshes in that frame.""" + radiator meshes are the source's meshes in that frame (an emitter's cut to the side that faces its exhaust).""" inverse = root.matrix_world.inverted() for anchor in hull_source.read_anchors(runner("anchors")[1]): obj = bpy.data.objects[anchor.id] @@ -599,7 +601,10 @@ def check_poses(collection, root, runner): f"{anchor.id} is turned {math.degrees(turn):.1f} degrees, not {anchor.yaw}") if anchor.role in hull_source.MESH_ROLES: made = sorted(tuple(round(c, 3) for c in (inverse @ obj.matrix_world @ v.co)) for v in obj.data.vertices) - wanted = sorted(tuple(round(c, 3) for c in v) for v in hull_source.parse_off(runner(hull_source.MESH_ROLES[anchor.role] + anchor.id)[0]).vertices) + source = hull_source.parse_off(runner(hull_source.MESH_ROLES[anchor.role] + anchor.id)[0]) + if anchor.role == "thruster-emitter": # Build keeps of an emitter only the side facing its exhaust + source = hull_source.exhaust_face(source, anchor.yaw) + wanted = sorted(tuple(round(c, 3) for c in v) for v in source.vertices) require(len(made) == len(wanted) and all(approx(a, b, 2e-3) for a, b in zip(made, wanted)), f"The mesh of {anchor.id} is not the source's mesh in Ship Root's frame") diff --git a/tools/blender/tests/smoke_mounts.py b/tools/blender/tests/smoke_mounts.py index 53418abb1..ee623537d 100644 --- a/tools/blender/tests/smoke_mounts.py +++ b/tools/blender/tests/smoke_mounts.py @@ -69,6 +69,14 @@ def quad(name, size): return mesh +def exhaust_quad(name, size): + """A thruster emitter for a hardpoint of Rotation None: an upright quad whose one side faces the nose (-Y), the way its exhaust leaves.""" + mesh = bpy.data.meshes.new(name) + half = size / 2 + mesh.from_pydata([(-half, 0, -half), (half, 0, -half), (half, 0, half), (-half, 0, half)], [], [(0, 1, 2, 3)]) + return mesh + + def tetrahedron(name): mesh = bpy.data.meshes.new(name) mesh.from_pydata([(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)], [], [(0, 2, 1), (0, 1, 3), (0, 3, 2), (1, 2, 3)]) @@ -294,7 +302,7 @@ def main(): tag(new_object(collection, "Hull Collider", tetrahedron("Hull Collider"), parent=root), "hull-collider", "collider") tag(new_object(collection, "Shield", None, parent=root), "shield", "shield") tag(new_object(collection, "Tractor", None, (0, 2, 0), root), "tractor", "tractor") - disc = new_object(collection, "Thruster", quad("Thruster", 0.4), (0, 8, 0), root) + disc = new_object(collection, "Thruster", exhaust_quad("Thruster", 0.4), (0, 8, 0), root) tag(disc, "thruster-emitter", "thruster") for mount, kind, x, y in (("thruster", "3", 2, 0), ("reactor.a", "5", 2, 2)): bpy.ops.aetheria.add_ship_hardpoint() diff --git a/tools/blender/tests/smoke_package.py b/tools/blender/tests/smoke_package.py index 886c349e2..6d0322dea 100644 --- a/tools/blender/tests/smoke_package.py +++ b/tools/blender/tests/smoke_package.py @@ -53,6 +53,14 @@ def quad(name, size=1.0): return mesh +def exhaust_quad(name, size): + """A thruster emitter for a hardpoint of Rotation None: an upright quad whose one side faces the nose (-Y), the way its exhaust leaves.""" + mesh = bpy.data.meshes.new(name) + half = size / 2 + mesh.from_pydata([(-half, 0, -half), (half, 0, -half), (half, 0, half), (-half, 0, half)], [], [(0, 1, 2, 3)]) + return mesh + + def tagged(collection, name, data, role=None, anchor_id=None, location=(0, 0, 0), parent=None): obj = bpy.data.objects.new(name, data) obj.location = location @@ -345,7 +353,7 @@ def main(): tagged(ship, "Hull Collider", tetrahedron("Hull Collider"), "hull-collider", "collider") tagged(ship, "Shield", None, "shield", "shield") tagged(ship, "Tractor", None, "tractor", "tractor", (0, 2, 0)) - disc = tagged(ship, "Thruster", quad("Thruster", 0.4), "thruster-emitter", "thruster", (0, -1, 0)) + disc = tagged(ship, "Thruster", exhaust_quad("Thruster", 0.4), "thruster-emitter", "thruster", (0, -1, 0)) gun = tagged(ship, "Gun", None, "weapon-mount", "gun", (1, 0, 0)) tagged(ship, "Gun Muzzle", None, "weapon-muzzle", "gun.muzzle", (0, 0.5, 0), parent=gun) tagged(ship, "Radiator", quad("Radiator", 0.5), "radiator-mesh", "radiator", (-1, 0, 0)) diff --git a/tools/blender/tests/test_hull_source.py b/tools/blender/tests/test_hull_source.py index e77ec11b2..9cd7f21c9 100644 --- a/tools/blender/tests/test_hull_source.py +++ b/tools/blender/tests/test_hull_source.py @@ -28,7 +28,7 @@ SECRET = "SECRET-NAME-7" # a value a hull source supplies and no refusal may ec def box(x0, x1, y0, y1, z0, z1): """An OFF text for an axis-aligned box: 8 vertices, 6 quads (12 triangles once fanned).""" v = [(x, y, z) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)] - quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] + quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)] # outward, counter-clockwise from outside rows = ["OFF", "8 6 0"] + [f"{x} {y} {z}" for x, y, z in v] + [f"4 {a} {b} {c} {d}" for a, b, c, d in quads] return "\n".join(rows) @@ -339,9 +339,9 @@ class JudgementTests(unittest.TestCase): self.assertEqual(fixture.failed(), ["the triangle count lies inside the brief's budget"], budget) def test_the_budget_counts_the_triangles_of_the_emitter_meshes_too(self): - # 12 + 12 triangles of zones, 12 of the emitter: a budget of 30 holds without the emitter and not with it + # 12 + 12 triangles of zones, 2 of the emitter (its exhaust-facing side): a budget of 25 holds without it and not with it fixture = Fixture() - fixture.parts["brief"] = ("", brief(triangles=(10, 30))) + fixture.parts["brief"] = ("", brief(triangles=(10, 25))) self.assertEqual(fixture.failed(), ["the triangle count lies inside the brief's budget"]) def test_the_length_is_a_range_with_two_ends(self): @@ -385,6 +385,38 @@ class JudgementTests(unittest.TestCase): fixture.parts["emit:Th.A"] = ("", "") self.assertEqual(fixture.failed(), ["every emitter and radiator anchor has a mesh"]) + @staticmethod + def _normals(mesh): + """The unit outward normal of each triangle.""" + out = [] + for a, b, c in mesh.triangles: + pa, pb, pc = (mesh.vertices[i] for i in (a, b, c)) + u, v = [pb[i] - pa[i] for i in range(3)], [pc[i] - pa[i] for i in range(3)] + n = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) + length = sum(x * x for x in n) ** 0.5 + out.append(tuple(round(x / length) for x in n)) + return out + + def test_an_emitter_keeps_only_the_side_that_faces_its_exhaust(self): + # The thin box the hull source draws is closed; its exhaust leaves the way the anchor faces (yaw 180 aft, +Y; yaw 90 + # port, +X; yaw 0 the nose, -Y), and only the triangles facing that way are the emitter. + for yaw, thin, facing in ((180, (5, 5.1, "y"), (0, 1, 0)), (0, (5, 5.1, "y"), (0, -1, 0)), (90, (5, 5.1, "x"), (1, 0, 0))): + 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], yaw, ""])) + fixture.parts["emit:Th.A"] = (box(5, 5.1, 1, 2, 0.5, 1.5) if thin[2] == "x" else box(0.5, 1.5, 5, 5.1, 0.5, 1.5), "") + mesh = fixture.build().anchor_meshes["Th.A"] + self.assertEqual(len(mesh.triangles), 2, yaw) + self.assertEqual(set(self._normals(mesh)), {facing}, yaw) + + 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() + quad_toward_push = "OFF\n4 1 0\n0.5 5 0.5\n1.5 5 0.5\n1.5 5 1.5\n0.5 5 1.5\n4 0 1 2 3" # normal -Y, anchor exhaust +Y + fixture.parts["emit:Th.A"] = (quad_toward_push, "") + self.assertEqual(fixture.failed(), ["every emitter and radiator anchor has a mesh"]) + def test_the_collider_zone_is_the_languages_body(self): self.assertEqual(Fixture().build().body_zone, "primary")