import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent / 'Original'
sys.path.insert(0, str(ROOT / 'tools' / 'extractors'))
from models import prepare_models, export_omt_model
from omt import Database, FormatError
@unittest.skipUnless(ORIGINAL.exists(), 'Local original assets required')
class StaticModelPreparation(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temporary = tempfile.TemporaryDirectory(prefix='neutron-model-tests-')
cls.output = Path(cls.temporary.name)
cls.lab = prepare_models(ORIGINAL, 'level1b.gam', cls.output / 'lab')
cls.vr = prepare_models(ORIGINAL, 'VR01.gam', cls.output / 'vr')
@classmethod
def tearDownClass(cls):
cls.temporary.cleanup()
def test_exact_instance_bindings_preserve_duplicate_tags(self):
self.assertEqual((self.lab['level'], len(self.lab['actors']), len(self.lab['models'])), ('LV1B', 9, 6))
buttons = [a for a in self.lab['actors'] if a['kind'] == '3BUT']
self.assertEqual([a['offset'] for a in buttons], [42261, 42998])
self.assertEqual([a['tag'] for a in buttons], ['C3DBUTTON', 'C3DBUTTON'])
self.assertEqual(buttons[0]['variants'], buttons[1]['variants'])
self.assertTrue(all(a['defaultVariant'] == 'UP' for a in buttons))
self.assertEqual(len([a for a in self.lab['actors'] if a['kind'] == '3OMT']), 4)
self.assertEqual(len([a for a in self.vr['actors'] if a['kind'] == '3PHO']), 2)
self.assertEqual(len(self.vr['models']), 1)
self.assertEqual(self.lab['unresolved'], [])
self.assertEqual(self.vr['unresolved'], [])
def test_phone_is_original_omt_and_keeps_every_material_range(self):
model = next(m for m in self.lab['models'] if m['source'].get('database') == 'phone.omt')
self.assertEqual(model['source']['shapeId'], 0)
self.assertEqual((model['source']['triangles'], model['source']['textures']), (90, 3))
scene = json.loads((self.output / 'lab' / model['path']).read_text())
self.assertEqual({m['id']: m['texture']['id'] for m in scene['materials']}, {0: 1, 1: 0, 2: 2})
self.assertEqual([m['indexCount'] for m in scene['meshes']], [120, 6, 12, 6, 126])
self.assertEqual(sum(m['indexCount'] for m in scene['meshes']), len(scene['indices']))
self.assertEqual(len(model['source']['resources']), 7) # 1 shape + 3 materials + 3 Canv.
self.assertFalse(any(r['type'] in ('0HDR', 'mCTy') for r in model['source']['resources']))
for texture in scene['textures']:
path = self.output / 'lab' / Path(model['path']).parent / texture['path']
self.assertEqual(path.stat().st_size, texture['width'] * texture['height'] * 4)
def test_explicit_ase_and_png_pairings_are_used(self):
models = {m['key']: m for m in self.lab['models']}
bars = next(a for a in self.lab['actors'] if a['tag'] == 'bars')
source = models[bars['variants']['STATIC']]['source']
self.assertEqual((source['ase'].casefold(), source['png'].casefold(), source['triangles']), ('bars.ase', 'chain.png', 54))
button = next(a for a in self.lab['actors'] if a['kind'] == '3BUT')
for variant, filename in (('UP', 'buttonup.ase'), ('DOWN', 'buttondown.ase')):
source = models[button['variants'][variant]]['source']
self.assertEqual((source['ase'].casefold(), source['png'], source['triangles']), (filename, 'switch.png', 16))
def test_prop_models_do_not_include_other_archive_geometry(self):
for model in self.lab['models']:
if model['source'].get('database') != 'objects.omt':
continue
resources = model['source']['resources']
shapes = [r for r in resources if r['type'] == '3DSh']
self.assertEqual(len(shapes), 1)
self.assertIn(shapes[0]['id'], (27, 28))
self.assertEqual(len(resources), 3)
self.assertEqual(len([m for m in self.lab['models'] if m['source'].get('shapeId') == 28]), 1)
def test_original_hashes_and_output_boundary(self):
paths = [ORIGINAL / 'omt' / name for name in ('objects.omt', 'phone.omt')]
before = {p: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}
prepare_models(ORIGINAL, 'Vr01.GAM', self.output / 'again')
self.assertEqual(before, {p: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths})
for output in (ORIGINAL, ORIGINAL / 'models', ORIGINAL.parent):
with self.assertRaises(FormatError):
prepare_models(ORIGINAL, 'VR01.gam', output)
def test_missing_explicit_mapping_is_reported_without_substitution(self):
report = prepare_models(ORIGINAL, 'Level3C.gam', self.output / 'level3c')
missing = next(e for e in report['unresolved'] if e['offset'] == 33909)
self.assertEqual(missing['kind'], '3BUT')
self.assertNotIn(33909, {e['offset'] for e in report['actors']})
def test_selective_export_retains_null_material_geometry(self):
db = Database(ORIGINAL / 'omt' / 'level1b.omt')
# Missing original material18 resolves to a null runtime pointer.
from omt import read_shape
material_ids = {e.id for e in db.entries if e.type == '3DMa'}
entry = next(e for e in db.entries if e.type == '3DSh'
and any(p['material'] is None or p['material']['id'] not in material_ids
for p in read_shape(db.payload(e))['polygons']))
destination = self.output / 'null-original'
report = export_omt_model(db, entry.id, destination)
scene = json.loads((destination / 'scene.json').read_text())
self.assertIn(18, report['nullMaterialIds'])
self.assertTrue(any(m['material'] == 18 for m in scene['meshes']))
self.assertNotIn(18, {m['id'] for m in scene['materials']})
self.assertGreater(len(scene['indices']), 0)
def test_managed_consumer_transform_draw_visibility_and_texture_identity(self):
dotnet = shutil.which('dotnet') or str(ROOT / '.tools' / 'dotnet' / 'dotnet')
if not Path(dotnet).is_file():
self.skipTest('Local .NET10 SDK not provisioned')
harness = self.output / 'managed'
harness.mkdir(exist_ok=True)
source = ROOT / 'src' / 'GamePort'
includes = [*sorted((source / 'Assets').glob('*.cs')), *sorted((source / 'Game').glob('*.cs')),
source / 'Application' / 'StaticSceneVisuals.cs']
project = 'Exenet10.0enableenablefalse'
project += ''.join('' for p in includes)
project += ''
(harness / 'Harness.csproj').write_text(project)
(harness / 'NuGet.Config').write_text('')
(harness / 'Program.cs').write_text(MANAGED_CHECKS)
environment = os.environ.copy()
environment.update(DOTNET_CLI_TELEMETRY_OPTOUT='1', DOTNET_CLI_HOME=str(ROOT / '.dotnet-home'),
NUGET_PACKAGES=str(ROOT / '.nuget' / 'packages'))
result = subprocess.run([dotnet, 'run', '--project', str(harness / 'Harness.csproj'), '--',
str(ORIGINAL), str(self.output / 'lab')],
cwd=ROOT, env=environment, text=True, capture_output=True, timeout=120)
self.assertEqual(result.returncode, 0, result.stdout + '\n' + result.stderr)
self.assertIn('PASS static model runtime', result.stdout)
MANAGED_CHECKS = r'''
using System.Numerics;
using System.Text.Json;
using GamePort.Application;
using GamePort.Assets;
using GamePort.Game;
static void Check(bool condition, string name) { if (!condition) throw new Exception(name); }
static void Near(Vector3 actual, Vector3 expected, string name) => Check(Vector3.Distance(actual, expected) < .002f, name);
var original = args[0]; var prepared = args[1];
var level = GamLevel.Load(AssetPath.Resolve(original, "gam/level1b.gam"));
var save = OriginalSave.Load(AssetPath.Resolve(original, "NewGame.tsk"));
var director = new SceneDirector(level, new TaskStates(save.Tasks), (_,_) => 1);
var seed = new Mesh(new[] { new MeshVertex(new(1,2,3),Vector2.Zero,Vector3.One),
new MeshVertex(new(4,5,6),Vector2.Zero,Vector3.One), new MeshVertex(new(7,8,9),Vector2.Zero,Vector3.One) }, [0,1,2])
{ HasExplicitDraws = true, Draws = [new MeshDraw(0,3,5)], Textures = new() { [5] = PngImage.White } };
var visuals = new StaticSceneVisuals(seed, director, original, prepared);
Check(visuals.ActorCount == 9, "actual lab has nine model actor instances");
Check(visuals.Mesh.Draws.Length == 20, "all nineteen original model draw ranges retained");
Check(visuals.Mesh.Textures.Count == 16, "each model instance/variant has distinct texture identities");
Check(visuals.Mesh.Textures.Keys.Where(i => i != 5).All(i => i >= int.MinValue+20000 && i < int.MinValue+20015), "reserved texture identity range");
Check(visuals.Mesh.Draws.All(d => d.TextureId == -1 || visuals.Mesh.Textures.ContainsKey(d.TextureId)), "all draw textures resolve globally");
Check(visuals.Mesh.Vertices.Take(3).Select(v => v.Position).SequenceEqual(seed.Vertices.Select(v => v.Position)), "existing scene vertices retained");
var phone = director.Actors.Single(a => a.SourceGam?.Offset == 1729);
phone.Position = new(100,200,300); phone.Rotation = Vector3.Zero; phone.Visible = true;
using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(prepared,"models.json")));
var firstModel = manifest.RootElement.GetProperty("models")[0].GetProperty("path").GetString()!;
var local = Mesh.LoadSceneJson(Path.Combine(prepared,firstModel)).Vertices[0].Position;
var final = visuals.Mesh with { Vertices = visuals.Mesh.Vertices.Concat(new MeshVertex[3]).ToArray() };
visuals.Update(final);
Near(final.Vertices[3].Position, local + phone.Position, "exact actor root translation, no floor correction");
phone.Rotation = new(0,90,0); visuals.Update(final);
Near(final.Vertices[3].Position, new Vector3(-local.Z,local.Y,local.X) + phone.Position, "recovered yaw convention");
phone.Visible = false; visuals.Update(final);
Check(final.Draws.Skip(1).Take(5).All(d => !d.Visible), "all five phone material draws hide together");
Check(final.Draws[6].Visible, "duplicate phone instance remains visible");
var firstButton = director.Actors.Single(a => a.SourceGam?.Offset == 42261);
var secondButton = director.Actors.Single(a => a.SourceGam?.Offset == 42998);
firstButton.Visible = secondButton.Visible = true; firstButton.Animation = "HIDOWN"; secondButton.Animation = "UP";
visuals.Update(final);
Check(!final.Draws[12].Visible && final.Draws[13].Visible && final.Draws[14].Visible && !final.Draws[15].Visible,
"duplicate button tags choose independent up/down variants by source offset");
var conflict = seed with { Textures = new() { [int.MinValue+20000] = PngImage.White } };
try { _ = new StaticSceneVisuals(conflict,director,original,prepared); throw new Exception("texture conflict accepted"); }
catch (InvalidDataException) { }
// An explicit empty material table must retain geometry without inventing any draw.
var nullRoot = Path.Combine(prepared,"null-runtime"); Directory.CreateDirectory(nullRoot);
File.WriteAllText(Path.Combine(nullRoot,"scene.json"), """
{"vertices":[[0,0,0],[1,0,0],[0,1,0]],"uvs":[[0,0],[0,0],[0,0]],"indices":[0,1,2],"materials":[],"textures":[],"meshes":[{"firstIndex":0,"indexCount":3,"material":-1}]}
""");
File.WriteAllText(Path.Combine(nullRoot,"models.json"), """
{"schema":1,"models":[{"key":"null","path":"scene.json"}],"actors":[{"offset":1729,"kind":"3PHO","defaultVariant":"STATIC","variants":{"STATIC":"null"}}]}
""");
var invisible = new StaticSceneVisuals(seed,director,original,nullRoot);
Check(invisible.Mesh.Indices.Length == 6 && invisible.Mesh.Draws.Length == 1, "null material keeps geometry and skips draw");
Console.WriteLine("PASS static model runtime: transforms, visibility, nineteen ranges, texture IDs, duplicate tags, variants, null materials");
'''
if __name__ == '__main__': unittest.main()