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.

13.8 KB
Raw Blame
#nullable enable
using System;
using System.Linq;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;

/// <summary>#1273: the 23 full original buildings stream outside Resources, retain original geometry/takes and
/// texture dimensions, and use their own instanced materials. Scene placement and frame costs have separate gates.</summary>
public class BuildingModelImportTests
{
    const string Folder = "Assets/Art/Settlements/Prototype/Models";


    static readonly string[] Ids =
    {
        "b01-white-city-v2", "b02a-tel-aviv-corner-block-v2", "b02b-tel-aviv-narrow-block-v2", "b03a-jerusalem-arches-v2",
        "b03b-jerusalem-external-stair-v2", "b03c-jerusalem-plain-v2", "b04a-haifa-stone-balconies-v2",
        "b04b-haifa-loading-doors-v2", "b05a-moshava-house-v2", "b07-kibbutz-dining-hall-v2",
        "b09a-kibbutz-communal-building-v2", "b11-shikun-housing-v2", "b12-tegart-fort-v2", "b13a-netanya-two-storey-v2",
        "b16-farmhouse-v2", "b17-stone-courtyard-house-v2", "b18-military-barracks-v2", "b21-artisan-workshop-v2",
        "b22-industrial-factory-v2", "b23-winery-v2", "b24-agricultural-barn-v2", "b28-water-tower-v2", "b32-port-cargo-shed-v2",
        // Tal Heuberger's generated houses, placed on 27 October 2026 (#756: "Sign off all 19"); each keeps its provenance receipt.
        "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",
    };
    static bool Generated(string id) => Statecraft.Game.Map.Collection.CollectionCatalog.IsGeneratedHouse(id);

    static string Model(string id) => $"{Folder}/{id}/{id}.fbx";
    static string ColourMap(string id) => $"{Folder}/{id}/{id}_basecolor.jpg";

    static bool UnderResources(string path) => path.Split('/').Any(s => s.Equals("Resources", StringComparison.OrdinalIgnoreCase));

    /// <summary>The 28 buildings, #507's 23 and Tal Heuberger's five generated houses (model, material, colour map, and each
    /// house's provenance receipt and #1901 lighter level), beside each the streamed prefab its bundle carries
    /// (CollectionImport.MakeBuildingPrefabs), and beside each of the 23 town models its far-off copy (#2378).</summary>
    [Test]
    public void TheFolderHoldsTheTwentyEightBuildingsAndNothingElse()
    {
        Assert.AreEqual(28, Ids.Length, "#507's 23 and the five generated houses");
        var streamed = Statecraft.Game.Map.Collection.CollectionCatalog.Ids
            .Where(Statecraft.Game.Map.Collection.CollectionCatalog.IsBuilding).ToArray();
        Assert.AreEqual(28, streamed.Length);
        CollectionAssert.IsSubsetOf(streamed, Ids);
        var expected = Ids.SelectMany(id => new[] { Model(id), $"{Folder}/{id}/{id}.mat", ColourMap(id) }
                .Concat(Generated(id) ? new[] { $"{Folder}/{id}/provenance.json" } : Array.Empty<string>())
                // #1901's lighter level of each generated house, for the hex-tile boards in the editor (HexHouseLevels); no bundle carries it.
                .Concat(Generated(id) ? new[] { ".asset", ".prefab", ".json" }.Select(e => $"{Folder}/{id}/{id}-light{e}") : Array.Empty<string>())
                // #2378's far-off copy of each of the 23 town models (FarModelLevels): the mesh, its baked colour map, material,
                // the prefab its own bundle streams and the record.
                .Concat(Statecraft.Game.Map.Kits.TownModels.Ids.Contains(id) ? new[] { ".asset", ".png", ".mat", ".prefab", ".json" }.Select(e => Statecraft.Game.Map.Kits.TownModels.FarStem(id) + e) : Array.Empty<string>()))
            .Concat(streamed.Select(id => Statecraft.Game.Map.Collection.CollectionCatalog.PrefabPath(id, Statecraft.Game.Map.Collection.CollectionDetail.Near)))
            .OrderBy(p => p, StringComparer.Ordinal);
        var found = AssetDatabase.FindAssets("", new[] { Folder }).Select(AssetDatabase.GUIDToAssetPath)
            .Where(p => !AssetDatabase.IsValidFolder(p)).Distinct().OrderBy(p => p, StringComparer.Ordinal);
        CollectionAssert.AreEqual(expected, found);
    }

    [Test]
    public void NoModelAndNoBuildingFileIsUnderAResourcesFolder()
    {
        var models = AssetDatabase.FindAssets("t:Model", new[] { "Assets" }).Select(AssetDatabase.GUIDToAssetPath).ToArray();
        Assert.GreaterOrEqual(models.Length, Ids.Length, "the search sees the models");
        CollectionAssert.IsEmpty(models.Where(UnderResources), "models under a Resources folder ship in every build");
        Assert.IsFalse(UnderResources(Folder), Folder);
    }

    /// <summary>A Resources folder ships every asset in it and everything those assets depend on, so a prefab or
    /// material there that points at a building would put the building in every build.</summary>
    [Test]
    public void NothingUnderAResourcesFolderDependsOnTheBuildings()
    {
        var inResources = AssetDatabase.GetAllAssetPaths()
            .Where(p => p.StartsWith("Assets/", StringComparison.Ordinal) && UnderResources(p) && !AssetDatabase.IsValidFolder(p))
            .ToArray();
        Assert.IsNotEmpty(inResources, "the search sees the Resources folders");
        var leaks = AssetDatabase.GetDependencies(inResources, true)
            .Where(d => d.StartsWith(Folder + "/", StringComparison.Ordinal)).OrderBy(d => d, StringComparer.Ordinal);
        CollectionAssert.IsEmpty(leaks, "building files reached from a Resources folder ship in every build");
    }

    [Test]
    public void EveryOriginalBuildingImportsWithoutCompressionAndKeepsItsSourceTakes()
    {
        foreach (var id in Ids)
        {
            var path = Model(id);
            var imp = AssetImporter.GetAtPath(path) as ModelImporter;
            Assert.IsNotNull(imp, path);
            Assert.AreEqual(ModelImporterMeshCompression.Off, imp!.meshCompression, path + " mesh compression");
            Assert.IsFalse(imp.isReadable, path + " Read/Write");
            Assert.IsTrue(imp.importAnimation, path + " all original takes retained");
            // #507's buildings import with a Generic rig; the generated houses keep their delivered import, with none.
            Assert.AreEqual(Generated(id) ? ModelImporterAnimationType.None : ModelImporterAnimationType.Generic, imp.animationType, path + " rig");
            Assert.IsTrue(imp.importBlendShapes, path + " blend shapes");
            Assert.IsFalse(imp.importVisibility, path + " visibility");
            Assert.IsFalse(imp.importCameras, path + " cameras");
            Assert.IsFalse(imp.importLights, path + " lights");
            Assert.IsFalse(imp.addCollider, path + " colliders");
            Assert.IsFalse(imp.generateSecondaryUV, path + " lightmap UVs");
            Assert.AreEqual(ModelImporterTangents.None, imp.importTangents, path + " tangents (no normal map)");
            Assert.AreEqual(ModelImporterMaterialImportMode.None, imp.materialImportMode, path + " materials (the .mat beside it)");

            var assets = AssetDatabase.LoadAllAssetsAtPath(path);
            var meshes = assets.OfType<Mesh>().ToArray();
            Assert.AreEqual(1, meshes.Length, path + " meshes");
            var mesh = meshes[0];
            long triangles = Enumerable.Range(0, mesh.subMeshCount).Sum(i => (long)mesh.GetIndexCount(i)) / 3;
            Assert.Greater(triangles, 0, path);
            Assert.AreEqual(Model(id), AssetDatabase.GetAssetPath(mesh), path + " exact original geometry");
            Assert.IsFalse(mesh.isReadable, path + " mesh readable");
            Assert.IsFalse(mesh.HasVertexAttribute(VertexAttribute.Tangent), path + " tangent stream");
            Assert.AreEqual(imp.defaultClipAnimations.Length, assets.OfType<AnimationClip>().Count(c => !c.name.StartsWith("__preview__", StringComparison.Ordinal)), path + " every original take");
            CollectionAssert.IsEmpty(assets.OfType<Material>(), path + " embedded materials");
            var root = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            CollectionAssert.IsEmpty(root.GetComponentsInChildren<Component>(true)
                .Where(c => !(c is Transform || c is MeshFilter || c is MeshRenderer || c is Animator)), path + " other components");
        }
    }

    [Test]
    public void EveryColourMapKeepsItsSourceSizeAndMipmapsWithoutCrunch()
    {
        foreach (var id in Ids)
        {
            var path = ColourMap(id); var imp = AssetImporter.GetAtPath(path) as TextureImporter;
            Assert.IsNotNull(imp, path); imp!.GetSourceTextureWidthAndHeight(out int width, out int height);
            Assert.GreaterOrEqual(imp.maxTextureSize, Math.Max(width, height), path + " no downscaling");
            Assert.IsFalse(imp.crunchedCompression, path + " no Crunch");
            Assert.IsTrue(imp.mipmapEnabled, path + " mipmaps"); Assert.IsTrue(imp.sRGBTexture, path + " sRGB");
            Assert.IsFalse(imp.isReadable, path + " GPU-only");
            if (Generated(id))
            {
                // The generated houses keep their delivered, approved import: compressed, quality 100, exactly 4096, and no
                // override but the web cap (TheGeneratedHousesColourMapsAreCappedAt2048OnTheWebOnly).
                Assert.AreEqual(4096, imp.maxTextureSize, path + " max size");
                Assert.AreEqual(100, imp.compressionQuality, path + " quality");
                Assert.AreEqual(TextureImporterCompression.Compressed, imp.textureCompression, path + " compression");
                foreach (var target in new[] { "Standalone", "Android", "iPhone" })
                    Assert.IsFalse(imp.GetPlatformTextureSettings(target).overridden, path + " " + target + " override");
            }
            foreach (var target in Generated(id) ? new[] { "Standalone" } : new[] { "Standalone", "WebGL" })
            {
                var setting = imp.GetPlatformTextureSettings(target);
                Assert.GreaterOrEqual(setting.maxTextureSize, Math.Max(width, height), path + " " + target + " keeps source size");
                Assert.IsFalse(setting.crunchedCompression, path + " " + target);
            }
            // Imported at the source size, or at the active target's cap where it overrides one (the houses on WebGL: 2048).
            // Only WebGL and the desktop target are mapped here: no colour map in this folder overrides Android or iOS (asserted above
            // for the houses).
            var active = imp.GetPlatformTextureSettings(EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebGL ? "WebGL" : "Standalone");
            int cap = active.overridden ? active.maxTextureSize : imp.maxTextureSize;
            int longest = Math.Max(width, height), w = width, h = height;
            if (longest > cap) { w = width * cap / longest; h = height * cap / longest; }   // Unity keeps the aspect ratio
            var tex = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            Assert.AreEqual(w, tex.width, path + " imported width"); Assert.AreEqual(h, tex.height, path + " imported height");
            Assert.Greater(tex.mipmapCount, 1, path + " imported mipmaps");
        }
    }

    /// <summary>Owner, 2 November 2026: "Cap at 2048 px on web (Recommended)". Each generated house's colour map imports at
    /// 2048 px in the WebGL build only, through a WebGL override, so its streamed bundle is smaller. The default and desktop
    /// import keep the delivered 4096 px, and the source JPG is unchanged.</summary>
    [Test]
    public void TheGeneratedHousesColourMapsAreCappedAt2048OnTheWebOnly()
    {
        var houses = Ids.Where(Generated).ToArray();
        Assert.AreEqual(5, houses.Length, "houses 01 to 05");
        foreach (var id in houses)
        {
            var path = ColourMap(id); var imp = (TextureImporter)AssetImporter.GetAtPath(path);
            var web = imp.GetPlatformTextureSettings("WebGL");
            Assert.IsTrue(web.overridden, path + " WebGL override");
            Assert.AreEqual(2048, web.maxTextureSize, path + " WebGL max size");
            Assert.AreEqual(TextureImporterFormat.Automatic, web.format, path + " WebGL format");
            Assert.AreEqual(TextureImporterCompression.Compressed, web.textureCompression, path + " WebGL compression");
            Assert.IsFalse(web.crunchedCompression, path + " WebGL crunch");
            Assert.AreEqual(100, web.compressionQuality, path + " WebGL quality");
            Assert.Greater(imp.maxTextureSize, web.maxTextureSize, path + " the default keeps more than the web cap");
            Assert.IsFalse(imp.GetPlatformTextureSettings("Standalone").overridden, path + " desktop keeps the default");
        }
        // Only the houses: no other generated model's colour map (the tents, the props, the vehicles) has a WebGL override.
        var others = AssetDatabase.FindAssets("t:Texture2D", new[] { "Assets" }).Select(AssetDatabase.GUIDToAssetPath)
            .Where(p => System.IO.Path.GetFileName(p).StartsWith("generated-1948-", StringComparison.Ordinal) && p.EndsWith("_basecolor.jpg", StringComparison.Ordinal)
                && !p.StartsWith(Folder + "/", StringComparison.Ordinal)).ToArray();
        Assert.GreaterOrEqual(others.Length, 6, "the tents, the props and the vehicles");
        foreach (var path in others)
            Assert.IsFalse(((TextureImporter)AssetImporter.GetAtPath(path)).GetPlatformTextureSettings("WebGL").overridden, path + " WebGL override");
    }

    [Test]
    public void EveryMaterialDrawsItsOwnColourMapWithGpuInstancing()
    {
        foreach (var id in Ids)
        {
            var mat = AssetDatabase.LoadAssetAtPath<Material>($"{Folder}/{id}/{id}.mat");
            Assert.IsNotNull(mat, id);
            Assert.AreEqual("Universal Render Pipeline/Lit", mat.shader.name, id);
            Assert.IsTrue(mat.enableInstancing, id + " GPU instancing");
            Assert.AreEqual(AssetDatabase.LoadAssetAtPath<Texture2D>(ColourMap(id)), mat.GetTexture("_BaseMap"), id + " colour map");
        }
    }
}