Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

14.0 KB
Raw Blame
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.Map.Collection;
using Statecraft.Game.Map.Kits;
using Statecraft.Game.Review;
using UnityEditor;
using UnityEngine;

public class Generated1948AssetTests
{
    [Serializable] sealed class Receipt
    {
        public string id = "", source_glb_sha256 = "", source_archive_path = "", embedded_image_sha256 = "";
        public int number = 0, source_triangles = 0;
        public int[] embedded_dimensions = Array.Empty<int>();
        public string[] source_clips = Array.Empty<string>();
    }
    static string Hash(string path)
    {
        using var sha = SHA256.Create();
        return BitConverter.ToString(sha.ComputeHash(File.ReadAllBytes(path))).Replace("-", "").ToLowerInvariant();
    }
    static string Disk(string path) => Path.Combine(Paths.RepoRoot, "unity", path);

    [Test] public void OriginalDeliveriesAndExactMapsMatchReceiptsWithLosslessImport()
    {
        var files = AssetDatabase.FindAssets("t:Model", new[] { Generated1948BuildingsPropsReview.AssetFolder, Statecraft.Game.Map.Collection.CollectionCatalog.Folder, TownModels.Folder })
            .Select(AssetDatabase.GUIDToAssetPath).Where(p => p.EndsWith(".fbx", StringComparison.Ordinal))
            // The folder also holds #1377's review-only characters (figure-*); the buildings and props are generated-1948-*.
            .Where(p => Path.GetFileName(p).StartsWith("generated-1948-", StringComparison.Ordinal))
            // The placed vehicles (#1932, the Spitfire; #2046, the R35, which keeps its -compatibility.fbx) have the vehicle
            // receipt; VehicleReviewTests checks them.
            .Where(p => !Statecraft.Game.VehicleReview.VehicleReviewCatalog.Ids.Any(id => Path.GetFileName(p).StartsWith(id, StringComparison.Ordinal))).ToArray();
        Assert.AreEqual(11, files.Length);
        foreach (string fbx in files)
        {
            string dir = Path.GetDirectoryName(fbx)!;
            var receipt = JsonUtility.FromJson<Receipt>(File.ReadAllText(Disk(dir + "/provenance.json")));
            Assert.AreEqual(receipt.source_glb_sha256, Hash(Path.Combine(Paths.RepoRoot, receipt.source_archive_path)), receipt.id);
            Assert.IsFalse(fbx.Contains("-near") || fbx.Contains("-far"), fbx);
            var importer = (ModelImporter)AssetImporter.GetAtPath(fbx);
            Assert.AreEqual(ModelImporterMeshCompression.Off, importer.meshCompression, fbx);
            Assert.AreEqual(ModelImporterAnimationCompression.Off, importer.animationCompression, fbx);
            Assert.IsTrue(importer.importAnimation, "all source clips remain enabled");
            Assert.AreEqual(receipt.source_clips.Length, importer.defaultClipAnimations.Length, fbx);
            var source = AssetDatabase.LoadAssetAtPath<GameObject>(fbx);
            var meshes = source.GetComponentsInChildren<MeshFilter>(true).Select(f => f.sharedMesh).ToArray();
            Assert.AreEqual(receipt.source_triangles, meshes.Sum(m => (long)m.GetIndexCount(0) / 3), fbx);
            Assert.IsTrue(meshes.All(m => m.HasVertexAttribute(UnityEngine.Rendering.VertexAttribute.TexCoord0)));
            Assert.IsEmpty(source.GetComponentsInChildren<LODGroup>(true));
            var material = AssetDatabase.LoadAssetAtPath<Material>(dir + "/" + receipt.id + ".mat");
            Assert.AreEqual(0f, material.GetFloat("_Metallic"), 1e-6f, receipt.id);
            Assert.AreEqual(.1f, material.GetFloat("_Smoothness"), 1e-6f, receipt.id);
            var texture = material.mainTexture; Assert.IsNotNull(texture, receipt.id);
            string image = AssetDatabase.GetAssetPath(texture);
            Assert.AreEqual(receipt.embedded_image_sha256, Hash(Disk(image)), receipt.id);
            var ti = (TextureImporter)AssetImporter.GetAtPath(image);
            // The source image's size, not the imported texture's, which the houses' WebGL cap (2048) shrinks under that target.
            ti.GetSourceTextureWidthAndHeight(out int width, out int height);
            Assert.AreEqual(receipt.embedded_dimensions[0], width, receipt.id);
            Assert.AreEqual(receipt.embedded_dimensions[1], height, receipt.id);
            Assert.IsFalse(ti.crunchedCompression, image);
            Assert.AreEqual(TextureImporterCompression.Compressed, ti.textureCompression, image);
            Assert.GreaterOrEqual(ti.maxTextureSize, Math.Max(receipt.embedded_dimensions[0], receipt.embedded_dimensions[1]));
            Assert.IsNotNull(AssetDatabase.LoadAssetAtPath<GameObject>(Generated1948BuildingsPropsReview.PrefabOf(receipt.id)), receipt.id);
        }
    }

    /// <summary>A placed generated prop (#756) keeps its source in its streamed prefab: every part of the prop's own FBX, each
    /// drawn with the prop's own material, whose map is the prop's own colour map, imported sRGB with mipmaps and not readable
    /// on the CPU.</summary>
    /// <summary>What is wrong with a placed prop's prefab: it must draw every one of <paramref name="sourceMeshes"/>, one
    /// renderer per part, each with <paramref name="material"/>, whose map is <paramref name="map"/>.</summary>
    static List<string> PrefabProblems(GameObject prefab, Mesh[] sourceMeshes, Material material, Texture map)
    {
        var problems = new List<string>();
        var filters = prefab.GetComponentsInChildren<MeshFilter>(true);
        if (sourceMeshes.Length == 0) problems.Add("no source mesh");
        var drawn = filters.Select(f => f.sharedMesh).ToList();
        if (sourceMeshes.Length != drawn.Count || sourceMeshes.Except(drawn).Any() || drawn.Except(sourceMeshes).Any()) problems.Add("not its FBX's own meshes, every one");
        var renderers = prefab.GetComponentsInChildren<Renderer>(true);
        if (renderers.Length != filters.Length) problems.Add("not one renderer per part");
        if (!renderers.All(r => r.sharedMaterials.Length > 0 && r.sharedMaterials.All(m => m == material))) problems.Add("not its own material");
        if (material.mainTexture != map) problems.Add("not its own colour map");
        return problems;
    }

    /// <summary>What is wrong with a placed prop's colour map import: sRGB, mipmaps imported, not readable on the CPU.</summary>
    static List<string> MapProblems(bool sRGB, bool mipmaps, bool readable, int mipmapCount)
    {
        var problems = new List<string>();
        if (!sRGB) problems.Add("not sRGB");
        if (!mipmaps || mipmapCount <= 1) problems.Add("no mipmaps");
        if (readable) problems.Add("readable on the CPU");
        return problems;
    }

    /// <summary>A placed generated prop (#756) keeps its source in its streamed prefab: every part of the prop's own FBX, each
    /// drawn with the prop's own material, whose map is the prop's own colour map, imported sRGB with mipmaps and not readable
    /// on the CPU. The checks reject a wrong material and a map without mipmaps.</summary>
    [Test] public void PlacedGeneratedPropsKeepTheirSourceMeshMaterialAndMap()
    {
        // #2085's generated whole towns are placed the same way (TownLandmarks), so the same checks hold for them.
        // #2083's weapons are made the same way too (held by the token figures, UnitWeapons).
        var props = CollectionCatalog.Ids.Where(id => CollectionCatalog.IsGeneratedProp(id) || CollectionCatalog.IsGeneratedTown(id) || CollectionCatalog.IsGeneratedWeapon(id)).ToList();
        CollectionAssert.IsSubsetOf(new[] { CollectionCatalog.BedouinTent, CollectionCatalog.SyrianR35, CollectionCatalog.EgyptianDakota,
            CollectionCatalog.StoneWell, CollectionCatalog.Sandbags, CollectionCatalog.CrateStack, CollectionCatalog.StoneWall,
            CollectionCatalog.TiberiasTown, CollectionCatalog.SafedTown, CollectionCatalog.NetanyaTown, CollectionCatalog.RamlaTown }, props);
        foreach (string id in props)
        {
            string dir = $"{CollectionCatalog.Folder}/{id}", fbx = CollectionCatalog.SourceModelPath(id), map = $"{dir}/{id}_basecolor.jpg";
            var sourceMeshes = AssetDatabase.LoadAssetAtPath<GameObject>(fbx).GetComponentsInChildren<MeshFilter>(true).Select(f => f.sharedMesh).ToArray();
            var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, CollectionDetail.Near));
            var material = AssetDatabase.LoadAssetAtPath<Material>($"{dir}/{id}.mat");
            var texture = AssetDatabase.LoadAssetAtPath<Texture2D>(map);
            CollectionAssert.IsEmpty(PrefabProblems(prefab, sourceMeshes, material, texture), id);
            var ti = (TextureImporter)AssetImporter.GetAtPath(map);
            CollectionAssert.IsEmpty(MapProblems(ti.sRGBTexture, ti.mipmapEnabled, ti.isReadable, texture.mipmapCount), map);
        }
        // The checks see a wrong material on a copy of the tent and a colour map imported without mipmaps.
        string tent = CollectionCatalog.BedouinTent, tentDir = $"{CollectionCatalog.Folder}/{tent}";
        var tentMeshes = AssetDatabase.LoadAssetAtPath<GameObject>($"{tentDir}/{tent}.fbx").GetComponentsInChildren<MeshFilter>(true).Select(f => f.sharedMesh).ToArray();
        var tentMaterial = AssetDatabase.LoadAssetAtPath<Material>($"{tentDir}/{tent}.mat");
        var copy = UnityEngine.Object.Instantiate(AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(tent, CollectionDetail.Near)));
        var other = new Material(tentMaterial);
        try
        {
            foreach (var r in copy.GetComponentsInChildren<Renderer>(true)) r.sharedMaterial = other;
            CollectionAssert.Contains(PrefabProblems(copy, tentMeshes, tentMaterial, tentMaterial.mainTexture), "not its own material");
        }
        finally { UnityEngine.Object.DestroyImmediate(copy); UnityEngine.Object.DestroyImmediate(other); }
        // A real colour map imported without mipmaps (a temporary texture, deleted afterwards) is rejected the same way.
        string root = "Assets/TalMipProbe" + Guid.NewGuid().ToString("N"), png = root + "/probe.png";
        try
        {
            AssetDatabase.CreateFolder("Assets", root.Substring("Assets/".Length));
            var source = new Texture2D(8, 8, TextureFormat.RGBA32, false);
            try { File.WriteAllBytes(Disk(png), source.EncodeToPNG()); } finally { UnityEngine.Object.DestroyImmediate(source); }
            AssetDatabase.ImportAsset(png, ImportAssetOptions.ForceSynchronousImport);
            var probe = (TextureImporter)AssetImporter.GetAtPath(png);
            probe.sRGBTexture = true; probe.isReadable = false; probe.mipmapEnabled = false; probe.SaveAndReimport();
            var imported = AssetDatabase.LoadAssetAtPath<Texture2D>(png);
            Assert.AreEqual(1, imported.mipmapCount, "the probe imported without mipmaps");
            CollectionAssert.AreEqual(new[] { "no mipmaps" }, MapProblems(probe.sRGBTexture, probe.mipmapEnabled, probe.isReadable, imported.mipmapCount));
        }
        finally { AssetDatabase.DeleteAsset(root); }
    }

    /// <summary>#2085's generated whole towns ship as Tal Heuberger delivered them: the FBX holds the GLB's triangles
    /// (tools/generated_towns.py recorded each count in the folder's provenance.json) and the colour map is imported at its
    /// full 2048 x 2048 on every platform, uncrunched, with no platform override, so the web build keeps every source pixel.</summary>
    [Test] public void GeneratedTownsKeepTheirDeliveredTrianglesAndFullColourMap()
    {
        var towns = CollectionCatalog.Ids.Where(CollectionCatalog.IsGeneratedTown).ToList();
        CollectionAssert.AreEqual(new[] { CollectionCatalog.TiberiasTown, CollectionCatalog.SafedTown, CollectionCatalog.NetanyaTown, CollectionCatalog.RamlaTown }, towns);
        var delivered = new Dictionary<string, int> { [CollectionCatalog.TiberiasTown] = 5002, [CollectionCatalog.SafedTown] = 4485,
            [CollectionCatalog.NetanyaTown] = 3428, [CollectionCatalog.RamlaTown] = 4426 };
        foreach (string id in towns)
        {
            string dir = $"{CollectionCatalog.Folder}/{id}", map = $"{dir}/{id}_basecolor.jpg";
            var meshes = AssetDatabase.LoadAllAssetsAtPath(CollectionCatalog.SourceModelPath(id)).OfType<Mesh>().ToList();
            Assert.AreEqual(1, meshes.Count, id);
            Assert.AreEqual(delivered[id], (int)meshes[0].GetIndexCount(0) / 3, id + ": the GLB's triangles (#2085's provenance.json)");
            StringAssert.Contains($"\"triangles\": {delivered[id]},", File.ReadAllText(Disk($"{dir}/provenance.json")), id);
            var ti = (TextureImporter)AssetImporter.GetAtPath(map);
            ti.GetSourceTextureWidthAndHeight(out int width, out int height);
            Assert.AreEqual((2048, 2048), (width, height), map);
            Assert.GreaterOrEqual(ti.maxTextureSize, 2048, map);
            Assert.IsFalse(ti.crunchedCompression, map);
            foreach (string platform in new[] { "Standalone", "WebGL" })
                Assert.IsFalse(ti.GetPlatformTextureSettings(platform).overridden, $"{map}: no {platform} override");
            var texture = AssetDatabase.LoadAssetAtPath<Texture2D>(map);
            Assert.AreEqual((2048, 2048), (texture.width, texture.height), map + ": imported at full size");
        }
    }

    /// <summary>The five houses placed in the town kits (owner, 27 October 2026, #756) stream after the first frame like the other
    /// town buildings: the map scene reaches none of the generated models, in review or placed.</summary>
    [Test] public void PlacedHousesStreamAndAddNoBootAssetReference()
    {
        CollectionAssert.AreEqual(new[] { "generated-1948-01-netanya-tiled-house-original", "generated-1948-02-netanya-two-storey-balcony-house",
            "generated-1948-03-netanya-flat-roof-porch-house", "generated-1948-04-dark-basalt-house", "generated-1948-05-plastered-courtyard-house-original" },
            TownModels.Ids.Where(id => id.StartsWith("generated-1948-", StringComparison.Ordinal)));
        Assert.IsFalse(AssetDatabase.GetDependencies("Assets/Map.unity", true)
            .Any(p => p.StartsWith(Generated1948BuildingsPropsReview.AssetFolder, StringComparison.Ordinal) || p.Contains("/generated-1948-")));
    }
}