diff --git a/docs/DISTRIBUTION.md b/docs/DISTRIBUTION.md index 20b2490..b7fadf9 100644 --- a/docs/DISTRIBUTION.md +++ b/docs/DISTRIBUTION.md @@ -35,9 +35,15 @@ Windows/macOS export icons. The build-time editor remains omitted from the vendored game dependency. No private engine source checkout, SDK source cache or build tools are vendored. -Only a maintainer updating the dependency needs access to private engine -releases. Download all three SDK ZIPs and their adjacent `.zip.sha256` files from -one published release. Preserve the old addon outside the checkout, then run: +Future SDK updates come from the public `RakuenSoftware/wol-engine-release` +repository. Its controlled native CI temporarily reads private source and +publishes audited binaries only. The updater accepts exact `runtime-` +release URLs from that repository, while retaining the original engine's exact +runtime/resource release URLs for older SDKs. The vendored dependency above +remains unchanged until the first new SDK release is available. + +Only a maintainer updating the dependency downloads the SDKs. Download all three +SDK ZIPs and their adjacent `.zip.sha256` files from one published release. Preserve the old addon outside the checkout, then run: ```sh python tools/release.py --vendor-runtime /path/to/linux-sdk.zip \ @@ -46,6 +52,8 @@ python tools/release.py --vendor-runtime /path/to/linux-sdk.zip \ The updater checks archive/file hashes, matching commits and targets, compares shared resources, rejects implementation source, and writes a new vendored tree. +New dependency updates reject loose shader programs as implementation source; +the current older SDK still contains four such files, pending replacement. It refuses to overwrite an existing addon. Review and commit that directory and VENDOR.json together. CI never runs this maintainer operation. diff --git a/docs/FIELD.md b/docs/FIELD.md index c9c2875..ff4acbb 100644 --- a/docs/FIELD.md +++ b/docs/FIELD.md @@ -39,7 +39,7 @@ Geometry is a group count, a 64-byte header per group, and then each group's tri - Retail space is x right, y down, z forward. A half turn about x gives the engine's y-up space; 128 map units are one engine unit. - Polygons are back-face culled. - Bit 0 of a polygon's command byte (byte 15) makes it double-sided: the room renderer draws a triangle that faces away rather than culling it (BATTLE.PRG 0x800973C8). It clears the bit before the GPU sees the polygon (0x8009756C, 0x800978DC), so every room polygon is modulated by its colours, never drawn raw. -- The room is drawn through an ordering table, so of two identical opaque faces facing the same way, the earlier group's is drawn over the later's. MAP005 (the chapel) has its floor's centre twice, in groups 102 (lit warm by the torches) and 103 (lit cold): only the warm one shows. The installer sets such a later copy half a unit behind its face, so it shows only where the earlier one is hidden. +- The room is drawn through an ordering table at each face's farthest corner (BATTLE.PRG 0x80097AB4; the fourth corner at 0x8009787C), in quarter-depth entries. Each emitted vertex keeps the primitive's four corners for the shared engine's ordering shader, including after the near-face filter rebuilds a mesh. This keeps an angled door from cutting through Ashley's leg. So of two identical opaque faces facing the same way, the earlier group's is drawn over the later's. MAP005 (the chapel) has its floor's centre twice, in groups 102 (lit warm by the torches) and 103 (lit cold): only the warm one shows. The installer sets such a later copy half a unit behind its face, so it shows only where the earlier one is hidden. - Bits 13 and 14 of a group's flags are how many times its polygons near the camera are subdivided (less one for each 512 of depth). **Room groups** @@ -70,7 +70,7 @@ Geometry is a group count, a 64-byte header per group, and then each group's tri - Past a depth (0x200 by default; `61` sets it, patching BATTLE.PRG 0x80097590 and 0x800978f8), the room renderer draws a polygon from the half-resolution copy of its texture: its texture coordinates halved and its page one row down. The game keeps those copies itself (the image-frame animations repeat each copy into them). The field's textures are mipmapped instead, so `61` changes nothing here. **Near rejection** -- The retail room renderer drops each room polygon whose nearest corner depth, divided by four, is below the near clip (`eb`; 64 by default): 0x80097A10 takes the least of the three GTE depths and 0x800980F8 compares it, the near value patched into its code. A corner behind the camera has depth 0, so a polygon reaching behind the camera goes too. Only in first-person view (the switch at 0x800F19C8, the renderer's second argument) are near polygons first subdivided, by their group's levels (flags bits 13 and 14), and the pieces tested. +- The retail room renderer drops each room polygon whose farthest corner depth, divided by four, is below the near clip (`eb`; 64 by default): 0x80097A10 takes the greatest of the three GTE depths and 0x800980F8 compares it, the near value patched into its code. A corner behind the camera has depth 0. A face is rejected by that test only when its farthest corner is below the cut. Only in first-person view (the switch at 0x800F19C8, the renderer's second argument) are near polygons first subdivided, by their group's levels (flags bits 13 and 14), and the pieces tested. - So room geometry closer than four times the near clip is not drawn, and a camera beside a wall or prop sees past it. - `ec v` sets a view scale of v × 128 (4096 for 0; 0x800BDE58), which 0x8007CD14 stores at 0x1F800064 and 0x8007AF08 multiplies into the whole view matrix, translation included. That leaves every screen position as it is but scales every depth, so the near cut stands at four times the near clip over v / 32: under MAP003's `ec 128` close-up by the cart it is 64 units, and the cart's cover, some 160 units from the eye, is drawn in front of Ashley. - The GPU then skips any triangle more than 1023 pixels across or 511 down (a quad reaches it as two triangles, each tested alone). Room corners are projected as the GTE projects a character's (see **Near the camera** below): a corner nearer than H / 2 after the view's scale, or behind the eye, is placed as if it stood there, and its screen place is held within -1024 to 1023. None of the renderer's own tests (0x80098014's off-screen checks, the near cut, the cut again after the group's depth bias, the upper half of its header word) drops MAP172's door in the shot over Ashley's shoulder (Episode 1, 16:53, `ea 46`, `eb 01`, `ec 80`): ajar by -300 and 12 to 60 units from the eye, its upper half spans about 1050 pixels across and 670 down, so the GPU skips it and the man on the table shows. In the shot of the woman at that door (16:55) it is drawn, ajar as group script 0x40 stands it. @@ -123,12 +123,12 @@ projection, and the body's own pose stays independent. `installation/CharacterConversion.cs` turns an SHP model and its SEQ animation sets into a skinned glTF rig. `RetailContent.Rig` builds it when the field first spawns the character, and `FieldScene.PrepareRigBank` and `ActivateRig` attach it to an actor. -- **Props.** A model with no animations of its own (the opening's dead men, 0x73 to 0x76) gets one clip, `rest`, which the field plays in place of the base idle. Its root stands half its bone 1 length above the actor's place, as the actor renderer lifts every model (BATTLE.PRG 0x800AF620 adds half the model's word at +0x50, bone 1's length, to the drawn height), and its bone 1 takes the standing turn every humanoid animation set gives the hip as its base, (2048, 0, 6144) in 8192ths of a turn. The props are modelled as they lie in their scenes, so unturned they stood on end: Episode 1 at 16:50 (MAP172) has the man slumped in the chair and the man spread on his back across the sloping table, which the script's angles (33) tilt him to fit. The man slumped in MAP172's chair (0x73) is a measured exception: retail draws him against the chair's back, 54 units from the place his script gives him (53 ahead and 11 to one side in his own frame), so his `rest` root carries that offset. It was fitted by rendering him over a grid of places and scoring each against Episode 1 at 16:51 (from beside the chair) and 16:54 (over Ashley's shoulder); the same fit leaves the man on the table (0x74) where his script puts him, and a different turn or tilt about his place fits worse. How retail comes by the offset was not found: the draw routine (0x800B1A68) gives bones 0 and 1 the actor's own matrix, built from its place and angles, and nothing read there moves him. +- **Props.** Loose models with a zero centre (including the opening’s swords and bolts) keep neutral root and hip bones. An animated prop holds its last pose when its event clip ends, as do characters; glTF loop flags are restored from the decoder’s explicit clip list. Static humanoid props with a nonzero centre (the opening's dead men, 0x73 to 0x76) gets one clip, `rest`, which the field plays in place of the base idle. Its root stands half its bone 1 length above the actor's place, as the actor renderer lifts every model (BATTLE.PRG 0x800AF620 adds half the model's word at +0x50, bone 1's length, to the drawn height), and its bone 1 takes the standing turn every humanoid animation set gives the hip as its base, (2048, 0, 6144) in 8192ths of a turn. The props are modelled as they lie in their scenes, so unturned they stood on end: Episode 1 at 16:50 (MAP172) has the man slumped in the chair and the man spread on his back across the sloping table, which the script's angles (33) tilt him to fit. The man slumped in MAP172's chair (0x73) is a measured exception: retail draws him against the chair's back, 54 units from the place his script gives him (53 ahead and 11 to one side in his own frame), so his `rest` root carries that offset. It was fitted by rendering him over a grid of places and scoring each against Episode 1 at 16:51 (from beside the chair) and 16:54 (over Ashley's shoulder); the same fit leaves the man on the table (0x74) where his script puts him, and a different turn or tilt about his place fits worse. How retail comes by the offset was not found: the draw routine (0x800B1A68) gives bones 0 and 1 the actor's own matrix, built from its place and angles, and nothing read there moves him. - **Enhanced 2D art and text** (the engine's graphics panel: Enhanced 2D art, on at 2x, and Enhanced text, on at 4x, each 2x, 4x or 8x). What is drawn on the 320 by 240 screen, the HUD, the menus, the balloons' paper, overlays and the ending's pictures, comes from `RetailContent.ScreenTexture`, enlarged at load by the engine's `PixelArtScaler` (Scale2x for art, which keeps the palette; anti-aliased for the HUD's lettering) while it reports its original size, so every region drawn of it is placed as before. The bitmap fonts load through the engine's `BitmapFontAsset` at the text factor, their glyph metrics unchanged. A change of either setting remakes the kept pictures and fonts in place. The title draws into fixed-size viewports of the retail screen and the field's 3D textures (rooms, characters, effects) are not affected. - **Enhanced characters** (`runtime/CharacterQuality.cs`, Settings › Characters, a saved preference; Original by default, which every footage comparison uses). Made at runtime from the installed rigs, nothing stored: - textures are scaled up four times: doubled twice by an edge-following pixel-art scaler (a quarter takes a neighbour's colour where that neighbour and the next one round agree across the corner and the opposite pair differ; colours alike within 48 in brightness, 7 and 6 in the colour differences; transparent texels only match each other), then each texel blended with its alike neighbours (5 by 5, one pass, within 12 in brightness, so low-contrast folds such as a hood's keep their lines) and sharpened a little against that blend; drawn with mipmaps and smooth, anisotropic filtering; - - a head that is one shell (the one-sided faces wholly on the head bone, the bone whose part byte is 1: at least 20 edges, at most one in 40 shared by more than two faces, at most three tenths open) is divided twice; a layered head (a hood over a face, as MAP003's hooded soldier, or a helmet) is not, as lifting its outer layer pushes it through the inner one. Its faces are each new edge point lifted onto the curved-triangle edge between its corners' averaged normals; border edges stay straight, so the head meets neck and hair where it did; + - a head that is one shell (the one-sided faces wholly on the head bone, the bone whose part byte is 1: at least 20 edges, at most one in 40 shared by more than two faces, at most three tenths open) is divided twice; a layered head (a hood over a face, as MAP003's hooded soldier, or a helmet) is not, as lifting its outer layer pushes it through the inner one. Its faces are each new edge point lifted onto the curved-triangle edge between its corners' averaged normals; border edges stay straight, so the head meets neck and hair where it did. Vertex colours and alpha are interpolated along each divided edge too, preserving the original shading; - smooth normals (per bone, corners at one place shared) and per-pixel shading: a light from above, to the camera's left and in front, that turns with the camera (0.7, wrapped Lambert, no highlights), and an even fill (0.55). Rooms and effects are unshaded, so only characters take it; the room's light map still tints them as before. The item menu's Ashley stays unshaded. The render scale (up to 200 %) and antialiasing in the shared graphics panel supersample their outlines further. - **Enhanced lighting** (`runtime/FieldLighting.cs`, Settings › Lighting, a saved preference; Original by default). Bright things bloom (glow over 0.9 of white, levels 2 to 5, added); effects' added sprites (fire, magic) are drawn three times brighter, which blooms and on an HDR display shows brighter than white; and each effect casts a light from its added sprites' middle, coloured by their texels and tints, its strength following how much of them there is, so firelight flickers on the characters near it (when they are drawn enhanced and take light). diff --git a/installation/CharacterConversion.cs b/installation/CharacterConversion.cs index 341e626..4c6bae3 100644 --- a/installation/CharacterConversion.cs +++ b/installation/CharacterConversion.cs @@ -110,7 +110,7 @@ int Frame() if (op == 0 || op >= lengths.Length || lengths[op] == 0 || at + lengths[op] > seq.Length) break; // 32 to 35 show (32, 33) or hide (34, 35) the held weapon (BATTLE.PRG 0x800AAD4C); 33 and 35 at once. // 10 plays a sound from the model's own bank (0x800AE4FC); 58 marks a death played out. - if (op is 1 or 2 or 4 or 5 or 10 or 12 or 58 or >= 32 and <= 35) + if (op is 1 or 2 or 4 or 5 or 10 or 12 or 23 or 24 or 58 or >= 32 and <= 35) { var entry = new JsonArray { frame, op }; for (int k = 1; k < lengths[op]; k++) entry.Add((int)seq[at + k]); @@ -197,11 +197,11 @@ public JsonObject Export() if (names.Count == 0) { // glTF drops animations without tracks, so the rest pose holds the root bone explicitly. - var rest = new Animation { Length = 1 / FramesPerSecond }; + var rest = new Animation { Length = 1 / FramesPerSecond, LoopMode = Animation.LoopModeEnum.Linear }; int track = rest.AddTrack(Animation.TrackType.Rotation3D); rest.TrackSetPath(track, "Space/Skeleton:b0"); rest.RotationTrackInsertKey(track, 0, Quaternion.Identity); - if (_bones >= 2) + if (_bones >= 2 && (_weaponTexture >= 0 || _model.Length >= 0x74 && BitConverter.ToInt16(_model, 0x72) != 0)) { track = rest.AddTrack(Animation.TrackType.Position3D); rest.TrackSetPath(track, "Space/Skeleton:b0"); @@ -222,6 +222,8 @@ public JsonObject Export() names.Add("rest"); } player.AddAnimationLibrary("", library); + var looping = new JsonArray(); + foreach (var clip in library.GetAnimationList()) if (library.GetAnimation(clip).LoopMode != Animation.LoopModeEnum.None) looping.Add(clip.ToString()); using var document = new GltfDocument(); using var state = new GltfState(); @@ -286,7 +288,7 @@ public JsonObject Export() // The head's point above the feet (the u16 at 0x5e, body +0x646), where BATTLE.PRG's code 251 points balloons // and the chain cue (0x800a1280). int crown = _weaponTexture < 0 && _model.Length >= 0x60 ? BitConverter.ToUInt16(_model, 0x5e) : 0; - return new JsonObject { ["centre"] = centre, ["girth"] = girth, ["height"] = height, ["collision_radius"] = collisionRadius, ["collision_height"] = collisionHeight, ["crown"] = crown, ["rig"] = _name, ["animations"] = names, ["events"] = events, ["movement"] = movement, ["weapon_bone"] = weaponBone, ["shield_bone"] = shieldBone, ["head_bone"] = headBone, ["twists"] = twists, ["limb_bones"] = limbBones, ["limb_parts"] = limbParts, ["bone_limbs"] = boneLimbs, ["shadow"] = shadow, ["room_lit"] = roomLit, ["bone_lengths"] = BoneLengths() }; + return new JsonObject { ["centre"] = centre, ["girth"] = girth, ["height"] = height, ["collision_radius"] = collisionRadius, ["collision_height"] = collisionHeight, ["crown"] = crown, ["rig"] = _name, ["animations"] = names, ["looping"] = looping, ["events"] = events, ["movement"] = movement, ["weapon_bone"] = weaponBone, ["shield_bone"] = shieldBone, ["head_bone"] = headBone, ["twists"] = twists, ["limb_bones"] = limbBones, ["limb_parts"] = limbParts, ["bone_limbs"] = boneLimbs, ["shadow"] = shadow, ["room_lit"] = roomLit, ["bone_lengths"] = BoneLengths() }; } /// @@ -317,10 +319,10 @@ public JsonObject Export() movement[clip] = steps; } // A clip whose script starts it over (operation 1) loops; one without holds its last frame. - bool loops = false; - if (scripts != null && index < scripts.Count) foreach (var entry in scripts[index]) loops |= (int)entry![1]! == 1; + bool loops = false, changes = false; + if (scripts != null && index < scripts.Count) foreach (var entry in scripts[index]) { int op = (int)entry![1]!; loops |= op == 1; changes |= op is 23 or 24; } // Event clips loop only so; every other set's clips loop. - animations[index].LoopMode = !set.StartsWith("esq", StringComparison.Ordinal) || loops ? Animation.LoopModeEnum.Linear : Animation.LoopModeEnum.None; + animations[index].LoopMode = !changes && (!set.StartsWith("esq", StringComparison.Ordinal) || loops) ? Animation.LoopModeEnum.Linear : Animation.LoopModeEnum.None; } return clips; } @@ -582,7 +584,7 @@ private IEnumerable Animations(byte[] seq) int header = 16 + index * stride; int frames = BitConverter.ToUInt16(seq, header); int other = (sbyte)seq[header + 2]; - var animation = new Animation { Length = Math.Max(1, frames - 1) / FramesPerSecond, LoopMode = Animation.LoopModeEnum.Linear }; + var animation = new Animation { Length = Math.Max(1, frames) / FramesPerSecond, LoopMode = Animation.LoopModeEnum.None }; // The translation stream places the root bone above the actor's floor position: its first value in map // units, and its keyed deltas in half units. An animation built on a base animation starts from the base's // first value, as its rotations do. @@ -671,6 +673,19 @@ private IEnumerable Animations(byte[] seq) animation.ScaleTrackInsertKey(track, frame / FramesPerSecond, (scale / 64).Max(Vector3.One / 4096)); } } + // glTF derives duration from the last key, discarding a trailing held frame. Keep the + // final SEQ tick so script commands on frame `frames` (including stride handoffs) run. + // Interpolate without looping here, or the trailing hold becomes the first pose again. + for (int track = 0; track < animation.GetTrackCount(); track++) + { + double end = animation.Length; + switch (animation.TrackGetType(track)) + { + case Animation.TrackType.Position3D: animation.PositionTrackInsertKey(track, end, animation.PositionTrackInterpolate(track, end)); break; + case Animation.TrackType.Rotation3D: animation.RotationTrackInsertKey(track, end, animation.RotationTrackInterpolate(track, end)); break; + case Animation.TrackType.Scale3D: animation.ScaleTrackInsertKey(track, end, animation.ScaleTrackInterpolate(track, end)); break; + } + } yield return animation; } } diff --git a/installation/MapConversion.cs b/installation/MapConversion.cs index 87ab590..bc22ca6 100644 --- a/installation/MapConversion.cs +++ b/installation/MapConversion.cs @@ -1377,7 +1377,7 @@ private void ReadFace(int at, bool quad, int scale, (int X, int Y, int Z) origin string surfaceKey = key + "_" + passBlend + (twoSided ? "_both" : "") + suffix; if (!surfaces.TryGetValue(surfaceKey, out var surface)) { - surface = new JsonObject { ["texture"] = key, ["blend"] = passBlend, ["cull"] = twoSided ? "disabled" : "back", ["unshaded"] = true, ["vertex_color_srgb"] = true, ["colour_gain"] = 2, ["vertices"] = new JsonArray(), ["uv"] = new JsonArray(), ["colors"] = new JsonArray(), ["faces"] = new JsonArray() }; + surface = new JsonObject { ["texture"] = key, ["blend"] = passBlend, ["cull"] = twoSided ? "disabled" : "back", ["unshaded"] = true, ["vertex_color_srgb"] = true, ["colour_gain"] = 2, ["vertices"] = new JsonArray(), ["uv"] = new JsonArray(), ["colors"] = new JsonArray(), ["faces"] = new JsonArray(), ["order_corners"] = new JsonArray() }; surfaces[surfaceKey] = surface; } targets.Add((surface, passGain)); @@ -1420,6 +1420,13 @@ private void ReadFace(int at, bool quad, int scale, (int X, int Y, int Z) origin // Retail space is x right, y down, z forward; a half turn about x gives the engine's y-up space. // Flat lists (x, y, z; u, v; r, g, b, a per vertex), which the field reads in one piece. foreach (float value in new[] { Round(x / UnitsPerMetre), Round(-y / UnitsPerMetre), Round(-z / UnitsPerMetre) }) surface["vertices"]!.AsArray().Add(value); + // Each primitive goes in the room ordering table at its farthest corner (0x80097ab4, + // the fourth corner at 0x8009787c), not at each fragment's interpolated depth. + for (int k = 0; k < 4; k++) + { + var p = position[Math.Min(k, corners - 1)]; + foreach (float value in new[] { Round((p.X + behind.X) / UnitsPerMetre), Round(-(p.Y + behind.Y) / UnitsPerMetre), Round(-(p.Z + behind.Z) / UnitsPerMetre) }) surface["order_corners"]!.AsArray().Add(value); + } foreach (float value in new[] { Round((uv[corner].U + centre) / 256f), Round((uv[corner].V + centre) / 256f) }) surface["uv"]!.AsArray().Add(value); int c = at + colourOffsets[corner]; int r = _map[c], g = _map[c + 1], b = _map[c + 2]; diff --git a/runtime/CharacterQuality.cs b/runtime/CharacterQuality.cs index 744c12e..e8f65bc 100644 --- a/runtime/CharacterQuality.cs +++ b/runtime/CharacterQuality.cs @@ -86,6 +86,7 @@ public static ArrayMesh Rounded(ArrayMesh mesh, int head) bool skinned = arrays[(int)Mesh.ArrayType.Bones].VariantType != Variant.Type.Nil; var positions = new List(arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array()); var uvs = arrays[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.Nil ? new List(new Vector2[positions.Count]) : new List(arrays[(int)Mesh.ArrayType.TexUV].AsVector2Array()); + var colours = arrays[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.Nil ? null : new List(arrays[(int)Mesh.ArrayType.Color].AsColorArray()); var owner = new List(); if (skinned) { @@ -102,7 +103,7 @@ public static ArrayMesh Rounded(ArrayMesh mesh, int head) // Only a head that is one shell is rounded: a layered one (a hood over a face, a helmet's brim) would // push its outer layer through its inner one (the hooded soldier in MAP003). rounds &= Closed(positions, owner, indices, head); - for (int level = 0; rounds && level < 2; level++) Divide(positions, uvs, owner, indices, head); + for (int level = 0; rounds && level < 2; level++) Divide(positions, uvs, colours, owner, indices, head); var output = new Godot.Collections.Array(); output.Resize((int)Mesh.ArrayType.Max); output[(int)Mesh.ArrayType.Vertex] = positions.ToArray(); @@ -117,12 +118,7 @@ public static ArrayMesh Rounded(ArrayMesh mesh, int head) output[(int)Mesh.ArrayType.Weights] = newWeights; } output[(int)Mesh.ArrayType.Index] = indices.ToArray(); - if (arrays[(int)Mesh.ArrayType.Color].VariantType != Variant.Type.Nil) - { - var colours = new List(arrays[(int)Mesh.ArrayType.Color].AsColorArray()); - while (colours.Count < positions.Count) colours.Add(Colors.White); - output[(int)Mesh.ArrayType.Color] = colours.ToArray(); - } + if (colours != null) output[(int)Mesh.ArrayType.Color] = colours.ToArray(); result.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, output); result.SurfaceSetMaterial(result.GetSurfaceCount() - 1, material); } @@ -215,7 +211,7 @@ private static bool Closed(List positions, List owner, List i } /// One level of 's division over the triangles wholly on . - private static void Divide(List positions, List uvs, List owner, List indices, int head) + private static void Divide(List positions, List uvs, List? colours, List owner, List indices, int head) { (int, int, int) Key(Vector3 p) => ((int)MathF.Round(p.X * 64), (int)MathF.Round(p.Y * 64), (int)MathF.Round(p.Z * 64)); bool OnHead(int t) => owner[indices[t]] == head && owner[indices[t + 1]] == head && owner[indices[t + 2]] == head; @@ -242,6 +238,7 @@ int Middle(int i, int j) middle -= ((b - a).Dot(na) * na + (a - b).Dot(nb) * nb) / 8; positions.Add(middle); uvs.Add((uvs[i] + uvs[j]) / 2); + colours?.Add(colours[i].Lerp(colours[j], 0.5f)); owner.Add(head); return made[(Math.Min(i, j), Math.Max(i, j))] = positions.Count - 1; } diff --git a/runtime/RetailContent.cs b/runtime/RetailContent.cs index 6811bae..0fd9f0b 100644 --- a/runtime/RetailContent.cs +++ b/runtime/RetailContent.cs @@ -291,9 +291,16 @@ private Node3D BuildRig(string name) using var state = new GltfState(); if (document.AppendFromBuffer(model, "", state) != Error.Ok || document.GenerateScene(state) is not Node3D scene) throw new InvalidDataException($"The installed {name} could not be read."); - // The rig's own sets (base and battle) loop; glTF does not keep that. + // glTF loses loop flags. The decoder owns them: half-strides that hand off to the + // adjacent slot must finish, whereas a script's restart keeps its clip looping. + var looping = name.StartsWith("weapon_", StringComparison.Ordinal) ? null : Field.Character(name)?.Definition["looping"]?.AsArray(); foreach (var node in scene.FindChildren("*", "AnimationPlayer", true, false)) - foreach (var clip in ((AnimationPlayer)node).GetAnimationList()) ((AnimationPlayer)node).GetAnimation(clip).LoopMode = Animation.LoopModeEnum.Linear; + foreach (var clip in ((AnimationPlayer)node).GetAnimationList()) + { + bool loop = looping == null; + if (looping != null) foreach (var value in looping) loop |= value?.GetValue() == clip.ToString(); + ((AnimationPlayer)node).GetAnimation(clip).LoopMode = loop ? Animation.LoopModeEnum.Linear : Animation.LoopModeEnum.None; + } // glTF keeps a mesh's vertex colours but not the material's use of them: a Gouraud-shaded model's colours // (the dragons', the shaded props') multiply its texture, doubled, as the PSX's 0x80 leaves a texel as it is. foreach (var node in scene.FindChildren("*", "MeshInstance3D", true, false)) diff --git a/scenes/field/EventActor.cs b/scenes/field/EventActor.cs index 71a683d..0fd8d42 100644 --- a/scenes/field/EventActor.cs +++ b/scenes/field/EventActor.cs @@ -463,8 +463,12 @@ private Wol.Engine.World.ActorClip Clip(string clip, int blendFrames, int skipFr public int ClipFrame(string clip) { if (Player == null) return 0; - double position = !Player.CurrentAnimation.IsEmpty ? Player.CurrentAnimationPosition : Player.HasAnimation(clip) ? Player.GetAnimation(clip).Length : 0; - return (int)(position * Installation.CharacterConversion.FramesPerSecond); + bool ended = Player.CurrentAnimation.IsEmpty; + double position = !ended ? Player.CurrentAnimationPosition : Player.HasAnimation(clip) ? Player.GetAnimation(clip).Length : 0; + // Animation.Length is a float: 31/30 comes back as 30.999999 SEQ frames. + // An ended clip has reached its declared integer frame, including commands on that tick. + double frame = position * Installation.CharacterConversion.FramesPerSecond; + return ended ? (int)Math.Round(frame) : (int)frame; } /// Adds an animation set (an event's "esqnnn", Ashley's "btn" and "artna") to the actor's rig. diff --git a/scenes/field/FieldBattle.cs b/scenes/field/FieldBattle.cs index aa029db..fd07751 100644 --- a/scenes/field/FieldBattle.cs +++ b/scenes/field/FieldBattle.cs @@ -664,11 +664,11 @@ public static void EquipArmour(Combatant c, int limb, GDictionary record) public int HitPointPercent(string id) => Combatants.TryGetValue(id, out var c) && c.MaxHp > 0 ? (int)Math.Ceiling(c.Hp * 100.0 / c.MaxHp) : 0; - /// The living hostile characters. + /// Bodies on hostile side 4, as retail 0x8007CF80 counts them; zero HP awaits the death tick. public int HostileCount() { int count = 0; - foreach (var c in Combatants.Values) if (c.Targetable) count++; + foreach (var c in Combatants.Values) if (c.Side == 4) count++; return count; } diff --git a/scenes/field/FieldView.cs b/scenes/field/FieldView.cs index 7504db7..febefac 100644 --- a/scenes/field/FieldView.cs +++ b/scenes/field/FieldView.cs @@ -4234,8 +4234,8 @@ public override void _PhysicsProcess(double delta) private void StepEvent() { EventFrame++; - // Clips' scripts show and hide the held weapon (operations 32 to 35) on their frames. - if (!Controlled) foreach (var actor in Actors.Values) RunClipScript(actor); + // Clip scripts hand off walking phases and, during events, show or hide the held weapon. + foreach (var actor in Actors.Values) RunClipScript(actor); // Clips with a movement stream carry their actor (an event's getting-up, MAP022's after the vision). foreach (var actor in Actors.Values) RunClipMovement(actor); // Their sounds play in play too: a footfall, the thud of a body. @@ -6397,8 +6397,8 @@ private void RunClipSounds(EventActor actor) } /// - /// Runs the weapon operations of an actor's clip script (BATTLE.PRG's interpreter at 0x800AD714) up to the clip's - /// current SEQ frame: 32 and 33 show the held weapon, 34 and 35 hide it. + /// Runs an actor's clip script (BATTLE.PRG's interpreter at 0x800AD714) up to the current SEQ frame: + /// 23/24 select the previous/next phase; during events, 32/33 show the held weapon and 34/35 hide it. /// private void RunClipScript(EventActor actor) { @@ -6413,8 +6413,18 @@ private void RunClipScript(EventActor actor) { var entry = value.AsGodotArray(); int at = entry[0].AsInt32(), op = entry[1].AsInt32(); - if (op is < 32 or > 35 || at <= actor.ScriptFrame || at > frame) continue; - actor.WeaponOut = op <= 33; + if (at <= actor.ScriptFrame || at > frame) continue; + // The two half-strides hand off to the adjacent animation slot (retail 23/24). + // They are not loops: switching at the script frame preserves both foot phases. + if (op is 23 or 24) + { + int split = clip.LastIndexOf('_'); + if (split < 0 || !int.TryParse(clip[(split + 1)..], out int number)) continue; + actor.ScriptFrame = frame; + actor.Animate(clip[..(split + 1)] + (number + (op == 23 ? -1 : 1)), 0); + return; + } + if (!Controlled && op is >= 32 and <= 35) actor.WeaponOut = op <= 33; } actor.ScriptFrame = frame; } @@ -6424,8 +6434,8 @@ private void RunClipScript(EventActor actor) /// Gives the event camera to the shared field camera: retail map units become engine units, and the projection distance a field of view. private void ApplyCamera() { - // The retail room renderer drops each room polygon whose nearest corner's depth, over four, is below the near - // clip (BATTLE.PRG 0x80097A10 takes the least of the three GTE depths, 0x800980F8 compares it), so a camera + // The retail room renderer drops each room polygon whose farthest corner's depth, over four, is below the near + // clip (BATTLE.PRG 0x80097A10 takes the greatest of the three GTE depths, 0x800980F8 compares it), so a camera // beside room geometry sees past it; actors keep the ordinary near plane. A corner behind the camera has depth // 0, so a face reaching behind it goes too. The view matrix is scaled by ec's value over 4096 (0x8007CD14 into // 0x1F800064, applied at 0x8007AF08), which leaves the picture as it is but scales every depth, so the cut stands @@ -6433,12 +6443,22 @@ private void ApplyCamera() // renderer takes as its second argument) are near polygons first subdivided, by their group's levels, and the // pieces tested: a cut by the pixel stands in for that. bool staged = _eventCamera && !Controlled; + float orderScale = (staged ? _eventFar : 4096) / 4096f; + var table = new OrderingTable(Installation.MapConversion.UnitsPerMetre * orderScale, 1 / 12f, 1 / 16f, 1 / 4f, 1, + 4 / (Installation.MapConversion.UnitsPerMetre * orderScale), new Rect2(-1048576, -1048576, 2097152, 2097152), float.MaxValue, LastEntry: 2046); + if (Field.OrderingTable != table) Field.SetOrderingTable(table); float reject = 4 * (staged ? _eventNear : 64) * 4096 / (staged ? _eventFar : 4096) / Installation.MapConversion.UnitsPerMetre; float pixelCut = _hideFirstPerson ? reject : 0; if (pixelCut != _roomNear) { _roomNear = pixelCut; Field.SetFieldNearCut(pixelCut); + var groups = Document.GetValueOrDefault("room_groups", new GArray()).AsGodotArray(); + for (int group = 0; group < groups.Count; group++) + { + // First-person view keeps the standard material's per-pixel near cut. + Field.SetModelOrder(group.ToString(), _hideFirstPerson ? ModelOrder.Depth : ModelOrder.Farthest); + } } if (Controlled) { @@ -6549,7 +6569,7 @@ private void ReadRoomFaces(GDictionary document) /// /// Leaves out the room faces retail does not draw, outside first-person view (where near faces are subdivided - /// instead). The room renderer drops a whole face whose nearest corner stands closer to the camera than the near + /// instead). The room renderer drops a whole face whose farthest corner stands closer to the camera than the near /// cut (see ApplyCamera). The GPU then drops a triangle more than 1023 pixels across or 511 down, a quad going to it /// as two triangles tested alone: as for characters (), a corner nearer than /// H / 2 after the view's scale, or behind the eye, is projected as if it stood there and its screen place is held @@ -6577,15 +6597,15 @@ private void DropNearFaces() { int count = room.Faces[surface][face] * 3; if (screen.Length < count) screen = new Vector2[count]; - float nearest = float.PositiveInfinity; + float farthest = 0; for (int v = 0; v < count; v++) { // The corner in the camera's frame, in retail units, and its screen place (9/8 across, y down). var local = toEye * vertices[at + v] * units; - nearest = Math.Min(nearest, -local.Z); + farthest = Math.Max(farthest, -local.Z); screen[v] = EventActor.GteProjection(local, projection, least, 0).Screen; } - bool near = !_hideFirstPerson && nearest < reject; + bool near = !_hideFirstPerson && farthest < reject; for (int v = 0; v < count; v += 3, triangle++) { bool drop = near || !_hideFirstPerson && EventActor.GpuDrops(screen[v], screen[v + 1], screen[v + 2]); @@ -6613,7 +6633,18 @@ private void DropNearFaces() arrays[(int)Mesh.ArrayType.TexUV] = kept.ConvertAll(v => uv[v]).ToArray(); arrays[(int)Mesh.ArrayType.Color] = kept.ConvertAll(v => colors[v]).ToArray(); arrays[(int)Mesh.ArrayType.Normal] = kept.ConvertAll(v => normals[v]).ToArray(); - room.Mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays); + long format = 0; + for (int channel = 1; channel <= 3; channel++) + { + int type = (int)Mesh.ArrayType.Custom0 + channel; + if (source[type].VariantType == Variant.Type.Nil) continue; + var corners = source[type].AsFloat32Array(); + var selected = new float[kept.Count * 4]; + for (int v = 0; v < kept.Count; v++) Array.Copy(corners, kept[v] * 4, selected, v * 4, 4); + arrays[type] = selected; + format |= (long)Mesh.ArrayCustomFormat.RgbaFloat << ((int)Mesh.ArrayFormat.FormatCustom0Shift + channel * 3); + } + room.Mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays, null, null, (Mesh.ArrayFormat)format); room.Mesh.SurfaceSetMaterial(surface, room.Materials[surface]); } } diff --git a/tests/AnimationScriptContracts.cs b/tests/AnimationScriptContracts.cs new file mode 100644 index 0000000..eadf6b1 --- /dev/null +++ b/tests/AnimationScriptContracts.cs @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: AGPL-3.0-only +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text.Json.Nodes; +using Godot; +using Wol.Engine.World; +using Wol.Games.Vagrant.Installation; +using Wol.Games.Vagrant.Scenes.Field; +using Wol.Games.Vagrant.Runtime; +namespace Wol.Games.Vagrant.Tests; + +/// Synthetic SEQ phases must survive glTF and hand off on the last script tick. +public partial class AnimationScriptContracts : Node +{ + public override void _Ready() + { + FieldScene? field=null; FieldView? adapter=null; + try + { + var model=new byte[0x148]; model[0]=(byte)'H'; model[4]=1; model[0x13c]=255; + var decoder=new CharacterConversion("synthetic",model,Array.Empty<(string,byte[],int)>()); + decoder.Prepare(); + const int slots=15, stride=14, start=16+2*stride, streams=start+slots; + var seq=new byte[streams+24]; BitConverter.TryWriteBytes(seq.AsSpan(0),(ushort)slots);seq[2]=1; + BitConverter.TryWriteBytes(seq.AsSpan(12),(uint)(start-8)); + Array.Fill(seq,(byte)255,start,slots);seq[start+13]=0;seq[start+14]=1; + for(int i=0;i<2;i++) + { + int h=16+i*stride;BitConverter.TryWriteBytes(seq.AsSpan(h),(ushort)31);seq[h+2]=255; + BitConverter.TryWriteBytes(seq.AsSpan(h+4),(ushort)(16+i*4)); + BitConverter.TryWriteBytes(seq.AsSpan(h+10),(ushort)9); + seq[streams+16+i*4]=31;seq[streams+17+i*4]=(byte)(i==0?24:23); + } + seq[streams+6]=0x82;seq[streams+7]=2; // Three ticks of root velocity: final x=3, then hold. + var lengths=new byte[65];lengths[23]=lengths[24]=1; + decoder=new CharacterConversion("synthetic",model,Array.Empty<(string,byte[],int)>()){ScriptLengths=lengths};decoder.Prepare(); + var events=new JsonObject();var clips=decoder.Clips("base",seq,0,events); + if(clips.Count!=2 || clips.Any(c=>c.Animation.LoopMode!=Animation.LoopModeEnum.None || Math.Abs(c.Animation.Length-31/30.0)>.00001)) + throw new InvalidOperationException("The decoder looped a half-stride or dropped its final script tick."); + if(events["base_13"]![0]![1]!.GetValue()!=24 || events["base_14"]![0]![1]!.GetValue()!=23) + throw new InvalidOperationException("Adjacent-animation script commands were discarded."); + if(clips.Any(c=>Math.Abs(c.Animation.PositionTrackInterpolate(0,c.Animation.Length).X-3)>.00001)) + throw new InvalidOperationException("The trailing SEQ tick returned to the first pose instead of holding the final pose."); + var modelNode=new Node3D {Name="Model"};var space=new Node3D {Name="Space"};modelNode.AddChild(space);space.Owner=modelNode; + var skeleton=new Skeleton3D {Name="Skeleton"};space.AddChild(skeleton);skeleton.Owner=modelNode;skeleton.AddBone("b0"); + var player=new AnimationPlayer {Name="AnimationPlayer"};modelNode.AddChild(player);player.Owner=modelNode; + var library=new AnimationLibrary();foreach(var clip in clips)library.AddAnimation(clip.Clip,clip.Animation);player.AddAnimationLibrary("",library); + using var document=new GltfDocument();using var state=new GltfState(); + if(document.AppendFromScene(modelNode,state)!=Error.Ok)throw new InvalidOperationException("Cannot export the synthetic stride rig."); + byte[] buffer=document.GenerateBuffer(state);modelNode.Free(); + using var imported=new GltfDocument();using var importedState=new GltfState(); + if(imported.AppendFromBuffer(buffer,"",importedState)!=Error.Ok || imported.GenerateScene(importedState) is not Node3D rig) + throw new InvalidOperationException("Cannot import the synthetic stride rig."); + field=new FieldScene();AddChild(field);field.SetProcess(false);field.SetPhysicsProcess(false); + using var source=Json.ParseString("""{"schema":1,"models":[],"objects":[{"id":0,"model":-1,"position":[0,0,0]}],"walkmeshes":[]}""").AsGodotDictionary(); + if(field.LoadField(source,new())!=Error.Ok || field.PrepareRigBank("0","base",rig)!=Error.Ok || field.ActivateRig(field.RigBanks[("0","base")])!=Error.Ok) + throw new InvalidOperationException("Cannot prepare the synthetic stride field."); + var actor=new EventActor("0",0,field.Actors["0"]){Scene=field,Visible=true}; + foreach(var name in new[]{"base_13","base_14"}) + { + var importedClip=actor.Player!.GetAnimation(name); + for(int track=0;track.00001) + throw new InvalidOperationException("The final held pose was lost in the glTF round trip."); + } + adapter=new FieldView();adapter.Actors["0"]=actor; + const BindingFlags hidden=BindingFlags.Instance|BindingFlags.NonPublic; + var cached=(Dictionary)typeof(FieldView).GetField("_clipEvents",hidden)!.GetValue(adapter)!; + cached[0]=Json.ParseString(events.ToJsonString()).AsGodotDictionary(); + var step=typeof(FieldView).GetMethod("RunClipScript",hidden)!; + foreach(bool controlled in new[]{false,true}) + { + typeof(FieldView).GetProperty("Controlled")!.SetValue(adapter,controlled); + actor.ScriptClip="";actor.ScriptFrame=-1; + if(!actor.Animate("base_13",0))throw new InvalidOperationException("Cannot start the first walking phase."); + var phases=new List{"base_13"}; + for(int tick=0;tick<480;tick++) + { + field.AdvancePresentation();step.Invoke(adapter,new object[]{actor}); + string current=actor.Player!.AssignedAnimation; + if(current!=phases[^1])phases.Add(current); + } + if(phases.Count<5 || phases.Where((s,i)=>s!=(i%2==0?"base_13":"base_14")).Any()) + throw new InvalidOperationException($"Walking repeated one foot phase or missed the end-frame command (controlled={controlled})."); + } + adapter.Free();adapter=null;field.Free();field=null; + // A closed bipyramid has 24 edges without seam/pole degeneracies. + var vertices=new List{new(0,1,0),new(0,-1,0)}; + for(int i=0;i<8;i++)vertices.Add(new Vector3(Mathf.Cos(i*Mathf.Tau/8),0,Mathf.Sin(i*Mathf.Tau/8))); + var triangles=new List(); + for(int i=0;i<8;i++){int a=2+i,b=2+(i+1)%8;triangles.AddRange(new[]{0,a,b,1,b,a});} + int count=vertices.Count; + var sphereArrays=new Godot.Collections.Array();sphereArrays.Resize((int)Mesh.ArrayType.Max); + sphereArrays[(int)Mesh.ArrayType.Vertex]=vertices.ToArray();sphereArrays[(int)Mesh.ArrayType.Index]=triangles.ToArray(); + sphereArrays[(int)Mesh.ArrayType.Bones]=new int[count*4];var weights=new float[count*4]; + for(int i=0;iMath.Abs(c.R-expected.R)>1/255f+.0001f || Math.Abs(c.G-expected.G)>1/255f+.0001f || Math.Abs(c.B-expected.B)>1/255f+.0001f || Math.Abs(c.A-expected.A)>1/255f+.0001f)) + throw new InvalidOperationException($"Enhanced head shading fixture: source={count}, result={roundedArrays[(int)Mesh.ArrayType.Vertex].AsVector3Array().Length}, expected={expected}, sample={roundedArrays[(int)Mesh.ArrayType.Color].AsColorArray()[^1]}"); + rounded.Dispose();shaded.Dispose(); + GD.Print("ANIMATION_SCRIPT_CONTRACTS_OK: adjacent phases, final held pose/tick, glTF round trip, scripted and controlled walking, enhanced head vertex colours/alpha");GetTree().Quit(); + } + catch(Exception error){adapter?.Free();field?.Free();GD.PrintErr("ANIMATION_SCRIPT_CONTRACTS_FAILED: "+error);GetTree().Quit(1);} + } +} diff --git a/tests/BattleCountContracts.cs b/tests/BattleCountContracts.cs index 8e5b8dc..5dedac7 100644 --- a/tests/BattleCountContracts.cs +++ b/tests/BattleCountContracts.cs @@ -33,6 +33,7 @@ public override void _PhysicsProcess(double delta) // Isolated defeat fixture: the earned campaign fights these actors through pad input separately. foreach (var c in battle.Combatants.Values) if (c.Targetable) battle.Strike(c, c.Hp, flinch: false); + if(battle.HostileCount()!=3) throw new InvalidOperationException("Zero HP bypassed the pending death/status tick in the victory count."); _felled = true; } if ((_view.Zone, _view.Map) == (23, 4) && _view.PlatformState(0) is { Off: false }) _bridge = true; diff --git a/tests/RoomOrderingContracts.cs b/tests/RoomOrderingContracts.cs new file mode 100644 index 0000000..e0f637a --- /dev/null +++ b/tests/RoomOrderingContracts.cs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: AGPL-3.0-only +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text.Json; +using Godot; +using Wol.Engine.World; +using Wol.Games.Vagrant.Scenes.Field; + +namespace Wol.Games.Vagrant.Tests; + +/// A room primitive uses its farthest corner, and retains its ordering corners when near faces change. +public partial class RoomOrderingContracts : Node +{ + public override void _Ready() + { + FieldScene? field = null; + FieldView? adapter = null; + try + { + // One quad spans the near cut; the other lies wholly in front of it. + Vector3[][] quads = [ + [new(-.2f, -.2f, -.25f), new(.2f, -.2f, -8), new(-.2f, .2f, -.25f), new(.2f, .2f, -8)], + [new(-.2f, -.2f, -.25f), new(.2f, -.2f, -.25f), new(-.2f, .2f, -.25f), new(.2f, .2f, -.25f)] + ]; + int[] order = [0, 1, 2, 1, 3, 2]; + var vertices = new List(); + var corners = new List(); + foreach (var quad in quads) + foreach (int index in order) + { + vertices.AddRange([quad[index].X, quad[index].Y, quad[index].Z]); + foreach (var point in quad) corners.AddRange([point.X, point.Y, point.Z]); + } + string fixture = JsonSerializer.Serialize(new { + schema = 1, walkmeshes = Array.Empty(), + models = new[] { new { blocks = new[] { new { groups = new[] { new { + texture = "", unshaded = true, vertices, uv = new float[24], + colors = Enumerable.Repeat(1f, 48).ToArray(), faces = new[] { 2, 2 }, order_corners = corners + } } } } } }, + objects = new[] { new { id = 0, model = 0, position = new[] { 0, 0, 0 } } }, + room_groups = new[] { new { mask = 255, first_person = false } } + }); + var document = Godot.Json.ParseString(fixture).AsGodotDictionary(); + field = new FieldScene(); AddChild(field); field.SetProcess(false); field.SetPhysicsProcess(false); + if (field.LoadField(document, new()) != Error.Ok) throw new InvalidOperationException("Cannot load the synthetic room."); + field.Camera.GlobalTransform = Transform3D.Identity; + adapter = new FieldView(); + const BindingFlags hidden = BindingFlags.Instance | BindingFlags.NonPublic; + typeof(FieldView).GetProperty("Field")!.SetValue(adapter, field); + typeof(FieldView).GetProperty("Document")!.SetValue(adapter, document); + var read = typeof(FieldView).GetMethod("ReadRoomFaces", hidden)!; + var camera = typeof(FieldView).GetMethod("ApplyCamera", hidden)!; + var drop = typeof(FieldView).GetMethod("DropNearFaces", hidden)!; + read.Invoke(adapter, [document]); camera.Invoke(adapter, null); drop.Invoke(adapter, null); + if (field.ModelOrderOf("0") != ModelOrder.Farthest) + throw new InvalidOperationException("Room depth rule was lost."); + var mesh = (ArrayMesh)((MeshInstance3D)field.Actors["0"].GetChild(0)).Mesh; + foreach (float eyeZ in new[] { 0f, -7f, 0f }) + { + field.Camera.GlobalPosition = new Vector3(0, 0, eyeZ); drop.Invoke(adapter, null); + var arrays = mesh.SurfaceGetArrays(0); + int count = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array().Length; + if (count != (eyeZ == 0 ? 6 : 3)) throw new InvalidOperationException("The near cut used the nearest corner or failed to restore a face."); + for (int channel = 1; channel <= 3; channel++) + { + var data = arrays[(int)Mesh.ArrayType.Custom0 + channel].AsFloat32Array(); + if (data.Length != count * 4) throw new InvalidOperationException("Ordering corners were dropped during a mesh rebuild."); + for (int v = 0; v < count; v++) for (int k = 0; k < 4; k++) + if (Math.Abs(data[v * 4 + k] - corners[(channel - 1) * 4 + k]) > .00001) + throw new InvalidOperationException("A rebuilt face changed its ordering corners."); + } + } + typeof(FieldView).GetField("_hideFirstPerson", hidden)!.SetValue(adapter, true); camera.Invoke(adapter, null); + if (field.ModelOrderOf("0") != ModelOrder.Depth) throw new InvalidOperationException("First-person view lost its material near cut."); + typeof(FieldView).GetField("_hideFirstPerson", hidden)!.SetValue(adapter, false); camera.Invoke(adapter, null); + if (field.ModelOrderOf("0") != ModelOrder.Farthest) throw new InvalidOperationException("The room ordering rule was not restored after first-person view."); + adapter.Free(); adapter = null; field.Free(); field = null; + GD.Print("ROOM_ORDERING_CONTRACTS_OK: farthest corner, near-cut rebuild/restore, ordering attributes, first-person handoff"); + GetTree().Quit(); + } + catch (Exception error) + { + adapter?.Free(); field?.Free(); GD.PrintErr("ROOM_ORDERING_CONTRACTS_FAILED: " + error); GetTree().Quit(1); + } + } +} diff --git a/tests/animation_script_contracts.tscn b/tests/animation_script_contracts.tscn new file mode 100644 index 0000000..ee74929 --- /dev/null +++ b/tests/animation_script_contracts.tscn @@ -0,0 +1,5 @@ +; SPDX-License-Identifier: AGPL-3.0-only +[gd_scene load_steps=2 format=3] +[ext_resource type="Script" path="res://tests/AnimationScriptContracts.cs" id="1"] +[node name="AnimationScriptContracts" type="Node"] +script = ExtResource("1") diff --git a/tests/room_ordering_contracts.tscn b/tests/room_ordering_contracts.tscn new file mode 100644 index 0000000..a528fd7 --- /dev/null +++ b/tests/room_ordering_contracts.tscn @@ -0,0 +1,5 @@ +; SPDX-License-Identifier: AGPL-3.0-only +[gd_scene load_steps=2 format=3] +[ext_resource type="Script" path="res://tests/RoomOrderingContracts.cs" id="1"] +[node name="RoomOrderingContracts" type="Node"] +script = ExtResource("1") diff --git a/tools/release.py b/tools/release.py index 89c92a6..d1ec571 100644 --- a/tools/release.py +++ b/tools/release.py @@ -53,8 +53,9 @@ def verify_projection(self): (stage / ".godot/extension_list.cfg").write_text("res://addons/wol_engine/native/spatial.gdextension\n") self.run("dotnet", "build", stage / "Vagrant.csproj", "--nologo") self.run(editor, "--headless", "--editor", "--import", "--path", stage, "--quit") - self.run(editor, "--headless", "--path", stage, "res://tests/actor_projection_contracts.tscn", - "--", "--install-root=" + str(stage / "empty-installation")) + for scene in ("actor_projection_contracts", "animation_script_contracts", "room_ordering_contracts"): + self.run(editor, "--headless", "--path", stage, f"res://tests/{scene}.tscn", + "--", "--install-root=" + str(stage / "empty-installation")) def download(self, filename): base = f"https://github.com/godotengine/godot/releases/download/{self.VERSION}-stable/" @@ -108,7 +109,12 @@ def vendor(self): if release.setdefault("commit", commit) != commit: raise RuntimeError("Engine SDK commits do not match") source_release = manifest.get("release", "https://github.com/RakuenSoftware/wol-engine/releases/tag/runtime-" + commit) - if not source_release.startswith("https://github.com/RakuenSoftware/wol-engine/releases/tag/"): + allowed_releases = { + "https://github.com/RakuenSoftware/" + repository + "/releases/tag/" + prefix + commit + for repository, prefixes in (("wol-engine", ("runtime-", "resources-")), ("wol-engine-release", ("runtime-",))) + for prefix in prefixes + } + if source_release not in allowed_releases: raise RuntimeError("Unexpected engine release provenance") if release.setdefault("release", source_release) != source_release: raise RuntimeError("Engine SDK releases do not match") @@ -126,7 +132,7 @@ def vendor(self): raise RuntimeError("Engine release file checksum mismatch: " + name) if name.startswith("editor/"): continue - if path.suffix in (".cpp", ".hpp", ".h", ".pdb", ".csproj", ".sln"): + if path.suffix.lower() in (".c", ".cpp", ".cc", ".cxx", ".hpp", ".h", ".hxx", ".pdb", ".snupkg", ".csproj", ".sln", ".gd", ".gdshader", ".gdshaderinc", ".glsl", ".hlsl", ".shader", ".py", ".sh", ".ps1", ".js", ".ts", ".rs", ".map", ".log"): raise RuntimeError("Implementation/development file in engine SDK: " + name) if path.suffix == ".cs": if data.strip(): @@ -224,7 +230,8 @@ def bundle_media(self, output): archive = supplied elif not archive.is_file(): partial = archive.with_suffix(".download") - urllib.request.urlretrieve(source["url"], partial) + self.run("curl", "--fail", "--location", "--retry", "4", "--retry-all-errors", + "--connect-timeout", "30", "--max-time", "600", "--output", partial, source["url"]) partial.replace(archive) with archive.open("rb") as stream: if hashlib.file_digest(stream, "sha256").hexdigest() != source["sha256"]: