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.

29.7 KB
Raw Blame
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Statecraft.Game.Map.Collection;
using Statecraft.Game.Map.Units;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;

namespace Statecraft.Game.EditorTools
{
    /// <summary>Imports Tal Heuberger's original models, with only the approved same-length author-path blanking (#1273).
    /// docs/original-models.json pins all 73. Uses no mesh or animation compression, keyframe reduction, Crunch, texture
    /// downscaling or generated LODs, keeping every source take. Makes one prefab per model and one integrity-checked
    /// streaming bundle per model. OriginalModelsStreamingTests
    /// pins the import settings. Idempotent.
    /// Run headless: Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.CollectionImport.Run</summary>
    public static class CollectionImport
    {
        public const int MaxTextureSize = 8192;

        static string Dir(string id) => $"{CollectionCatalog.Folder}/{id}";
        public static string Model(string id, CollectionDetail d) => $"{Dir(id)}/{id}.fbx";
        public static string Controller(string id) => $"{Dir(id)}/{id}-near.controller";

        public static void Run()
        {
            foreach (var id in CollectionCatalog.Ids.Where(id => !CollectionCatalog.IsBuilding(id) && !CollectionCatalog.IsGenerated(id)))
            {
                ImportModel(Model(id, CollectionDetail.Far), animated: false);
                ImportModel(Model(id, CollectionDetail.Near), animated: CollectionCatalog.Animated.Contains(id));
                ImportColourMap($"{Dir(id)}/{id}_basecolor.jpg");
            }
            foreach (var id in CollectionCatalog.Ids.Where(id => !CollectionCatalog.IsBuilding(id) && !CollectionCatalog.IsGenerated(id)))
            {
                var mat = AssetDatabase.LoadAssetAtPath<Material>($"{Dir(id)}/{id}.mat")
                    ?? throw new InvalidOperationException($"{id}: no material");
                if (!mat.enableInstancing) { mat.enableInstancing = true; EditorUtility.SetDirty(mat); }
                MakePrefab(id, CollectionDetail.Near, mat, (CollectionCatalog.Animated.Contains(id) || OriginalModelPose.Required(id)) ? IdleController(id) : null);
            }
            AssetDatabase.SaveAssets();
            Generated1948Characters.ImportRuntime();
            MakeBuildingPrefabs();
            MakeGeneratedTownPrefabs();
            MakeTokenFigureExtras();
            Debug.Log(FormattableString.Invariant($"CollectionImport: {CollectionCatalog.Ids.Count(id => !CollectionCatalog.IsBuilding(id) && !CollectionCatalog.IsGenerated(id))} collection models"));
        }

        /// <summary>Issue #707: the special-buildings bundle's prefabs, one per model, beside #675's imported model in its own
        /// folder (CollectionCatalog.PrefabPath): the model with its own material on every renderer. The models' import
        /// settings are #675's and are left as they are; Tal Heuberger's generated houses keep their delivered import settings
        /// (max 4096, quality 100, no rig; on WebGL a 2048 cap, owner 2 November 2026), so only their prefabs are built.</summary>
        public static void MakeBuildingPrefabs()
        {
            foreach (var id in CollectionCatalog.Ids.Where(CollectionCatalog.IsBuilding))
            {
                string dir = $"{CollectionCatalog.BuildingsFolder}/{id}";
                if (!CollectionCatalog.IsGeneratedHouse(id))
                {
                    ImportModel($"{dir}/{id}.fbx", animated: false);
                    ImportColourMap($"{dir}/{id}_basecolor.jpg");
                }
                var model = AssetDatabase.LoadAssetAtPath<GameObject>($"{dir}/{id}.fbx") ?? throw new InvalidOperationException($"{id}: no model");
                var mat = AssetDatabase.LoadAssetAtPath<Material>($"{dir}/{id}.mat") ?? throw new InvalidOperationException($"{id}: no material");
                mat.enableInstancing = true; EditorUtility.SetDirty(mat);
                var go = (GameObject)PrefabUtility.InstantiatePrefab(model);
                try
                {
                    foreach (var r in go.GetComponentsInChildren<Renderer>(true))
                        r.sharedMaterials = Enumerable.Repeat(mat, Math.Max(1, r.sharedMaterials.Length)).ToArray();
                    go.AddComponent<OriginalModelDistance>();
                    PrefabUtility.SaveAsPrefabAsset(go, CollectionCatalog.PrefabPath(id, CollectionDetail.Near));
                }
                finally { UnityEngine.Object.DestroyImmediate(go); }
            }
            AssetDatabase.SaveAssets();
            Debug.Log(FormattableString.Invariant($"CollectionImport: {CollectionCatalog.Ids.Count(CollectionCatalog.IsBuilding)} building prefabs"));
        }

        /// <summary>#2085: Tal Heuberger's generated whole towns, one prefab beside each compatibility FBX
        /// (CollectionCatalog.PrefabPath): the model with its own material on every renderer, as the placed vehicles' prefabs are.
        /// Their import settings (the .meta files beside the FBX and the colour map) are left as they are.</summary>
        [MenuItem("Statecraft/Collection/Make generated town prefabs")]
        public static void MakeGeneratedTownPrefabs()
        {
            foreach (var id in CollectionCatalog.Ids.Where(CollectionCatalog.IsGeneratedTown))
            {
                var model = AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.SourceModelPath(id)) ?? throw new InvalidOperationException($"{id}: no model");
                var mat = AssetDatabase.LoadAssetAtPath<Material>($"{Dir(id)}/{id}.mat") ?? throw new InvalidOperationException($"{id}: no material");
                var go = (GameObject)PrefabUtility.InstantiatePrefab(model);
                try
                {
                    foreach (var r in go.GetComponentsInChildren<Renderer>(true))
                        r.sharedMaterials = Enumerable.Repeat(mat, Math.Max(1, r.sharedMaterials.Length)).ToArray();
                    PrefabUtility.SaveAsPrefabAsset(go, CollectionCatalog.PrefabPath(id, CollectionDetail.Far));
                }
                finally { UnityEngine.Object.DestroyImmediate(go); }
            }
            AssetDatabase.SaveAssets();
            Debug.Log(FormattableString.Invariant($"CollectionImport: {CollectionCatalog.Ids.Count(CollectionCatalog.IsGeneratedTown)} generated town prefabs"));
        }

        /// <summary>#2083 and #2084: Tal Heuberger's weapons and the C06 point-fire pose source for the token figures.
        /// Each weapon gets one prefab beside its compatibility FBX, made as the generated towns' are, with a material
        /// like theirs on their delivered map (the FBX and map import settings are the .meta files beside them, the towns').
        /// The point-fire export is imported losslessly (every frame, no compression), and its prefab
        /// (<see cref="MakeFigurePosePrefab"/>) holds only the clip and the rig correction, no mesh.
        /// Headless: Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.CollectionImport.MakeTokenFigureExtras</summary>
        [MenuItem("Statecraft/Collection/Make token weapon and pose prefabs")]
        public static void MakeTokenFigureExtras()
        {
            var townMat = AssetDatabase.LoadAssetAtPath<Material>($"{Dir(CollectionCatalog.TiberiasTown)}/{CollectionCatalog.TiberiasTown}.mat")
                ?? throw new InvalidOperationException("no town material to copy");
            foreach (var id in CollectionCatalog.Ids.Where(CollectionCatalog.IsGeneratedWeapon))
            {
                string matPath = $"{Dir(id)}/{id}.mat";
                if (AssetDatabase.LoadAssetAtPath<Material>(matPath) == null)
                {
                    var map = AssetDatabase.LoadAssetAtPath<Texture2D>($"{Dir(id)}/{id}_basecolor.jpg") ?? throw new InvalidOperationException($"{id}: no map");
                    var made = new Material(townMat) { name = id };
                    made.SetTexture("_BaseMap", map); made.SetTexture("_MainTex", map);
                    AssetDatabase.CreateAsset(made, matPath);
                }
                var model = AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.SourceModelPath(id)) ?? throw new InvalidOperationException($"{id}: no model");
                var mat = AssetDatabase.LoadAssetAtPath<Material>(matPath)!;
                var go = (GameObject)PrefabUtility.InstantiatePrefab(model);
                try
                {
                    foreach (var r in go.GetComponentsInChildren<Renderer>(true))
                        r.sharedMaterials = Enumerable.Repeat(mat, Math.Max(1, r.sharedMaterials.Length)).ToArray();
                    PrefabUtility.SaveAsPrefabAsset(go, CollectionCatalog.PrefabPath(id, CollectionDetail.Far));
                }
                finally { UnityEngine.Object.DestroyImmediate(go); }
            }
            ImportModel(CollectionCatalog.SourceModelPath(CollectionCatalog.C06PointFire), animated: true);
            MakeFigurePosePrefab();
            AssetDatabase.SaveAssets();
            Debug.Log("CollectionImport: token weapon and pose prefabs");
        }

        /// <summary>The frame the point-fire aim holds: frame 37 of 97 (24 fps, frame 1 at 0 s), inside the still aim that Tal
        /// Heuberger's contact sheet shows from frame 25 to frame 65, between their carrying endpoints.</summary>
        public const int PointFireAimFrame = 37;

        /// <summary>The C06 point-fire pose source's prefab: an empty object with <see cref="UnitFigurePoseSource"/>, holding the
        /// export's clip and, per bone of C06's 67, the correction from the export's rig frame to C06's: the export's bind pose
        /// x its mesh's root-from-local x C06's mesh's local-from-root x C06's inverse bind pose (both meshes' rest vertices
        /// agree; Generated1948AssetTests checks it). Bones are listed parents first.</summary>
        internal static void MakeFigurePosePrefab()
        {
            string id = CollectionCatalog.C06PointFire, source = CollectionCatalog.SourceModelPath(id);
            var export = AssetDatabase.LoadAssetAtPath<GameObject>(source) ?? throw new InvalidOperationException("no point-fire export");
            var clip = AssetDatabase.LoadAllAssetsAtPath(source).OfType<AnimationClip>().Single(c => !c.name.StartsWith("__preview__", StringComparison.Ordinal));
            var c06 = AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(UnitFigures.YoungRecruit, CollectionDetail.Far))
                ?? throw new InvalidOperationException("no C06 prefab");
            var corrections = PointFireCorrections(export, c06, out var bones);
            var go = new GameObject(id);
            try
            {
                var src = go.AddComponent<UnitFigurePoseSource>();
                src.Clip = clip; src.AimTime = (PointFireAimFrame - 1) / clip.frameRate; src.Figure = UnitFigures.YoungRecruit;
                src.Bones = bones; src.Correction = corrections;
                PrefabUtility.SaveAsPrefabAsset(go, CollectionCatalog.PrefabPath(id, CollectionDetail.Far));
            }
            finally { UnityEngine.Object.DestroyImmediate(go); }
        }

        /// <summary>Per bone (by name, parents first), the export-to-C06 rig correction (see <see cref="MakeFigurePosePrefab"/>).</summary>
        internal static Matrix4x4[] PointFireCorrections(GameObject export, GameObject c06, out string[] bones)
        {
            var e = export.GetComponentsInChildren<SkinnedMeshRenderer>(true).Single();
            var c = c06.GetComponentsInChildren<SkinnedMeshRenderer>(true).Single();
            Matrix4x4 RootFrom(Transform t, Transform root) { var m = Matrix4x4.identity; for (var at = t; at != root; at = at.parent) m = Matrix4x4.TRS(at.localPosition, at.localRotation, at.localScale) * m; return m; }
            var eMesh = RootFrom(e.transform, export.transform); var cMesh = RootFrom(c.transform, c06.transform);
            var eBind = e.sharedMesh.bindposes; var cBind = c.sharedMesh.bindposes;
            int Depth(Transform t) { int d = 0; for (var at = t; at != null; at = at.parent) d++; return d; }
            var order = c.bones.Select((b, i) => (b, i)).OrderBy(x => Depth(x.b)).ThenBy(x => x.i).ToArray();
            bones = order.Select(x => x.b.name).ToArray();
            var result = new Matrix4x4[order.Length];
            for (int k = 0; k < order.Length; k++)
            {
                int ci = order[k].i, ei = Array.FindIndex(e.bones, b => b.name == order[k].b.name);
                if (ei < 0) throw new InvalidOperationException("the export lacks bone " + order[k].b.name);
                result[k] = eBind[ei] * eMesh.inverse * cMesh * cBind[ci].inverse;
            }
            return result;
        }

        static void ImportModel(string path, bool animated)
        {
            var imp = AssetImporter.GetAtPath(path) as ModelImporter ?? throw new FileNotFoundException("no model", path);
            imp.globalScale = 1f;
            imp.useFileScale = true;
            imp.meshCompression = ModelImporterMeshCompression.Off;
            imp.isReadable = false;
            imp.optimizeMeshPolygons = false;
            imp.optimizeMeshVertices = false;
            imp.importBlendShapes = true;
            imp.importVisibility = false;
            imp.importCameras = false;
            imp.importLights = false;
            imp.addCollider = false;
            imp.generateSecondaryUV = false;
            imp.importNormals = ModelImporterNormals.Import;
            imp.importTangents = ModelImporterTangents.None;   // no normal map
            imp.materialImportMode = ModelImporterMaterialImportMode.None;   // the prefab draws with the .mat beside it
            // Lossless (#1273): every source take, no resampling, no keyframe reduction, no generated LODs.
            imp.animationType = ModelImporterAnimationType.Generic;
            imp.avatarSetup = ModelImporterAvatarSetup.CreateFromThisModel;
            imp.optimizeGameObjects = false;
            imp.importAnimation = true;
            imp.resampleCurves = false;
            imp.animationCompression = ModelImporterAnimationCompression.Off;
            imp.clipAnimations = imp.defaultClipAnimations;
            var serialized = new SerializedObject(imp);
            var lods = serialized.FindProperty("m_GenerateMeshLods") ?? serialized.FindProperty("generateMeshLods");
            if (lods != null) { lods.boolValue = false; serialized.ApplyModifiedPropertiesWithoutUndo(); }
            imp.SaveAndReimport();
        }

        static void ImportColourMap(string path)
        {
            var imp = AssetImporter.GetAtPath(path) as TextureImporter ?? throw new FileNotFoundException("no colour map", path);
            imp.textureType = TextureImporterType.Default;
            imp.sRGBTexture = true;
            imp.mipmapEnabled = true;
            imp.isReadable = false;
            imp.maxTextureSize = MaxTextureSize;
            imp.textureCompression = TextureImporterCompression.Compressed;
            imp.crunchedCompression = false;
            imp.compressionQuality = 50;
            foreach (var target in new[] { "Standalone", "WebGL" })
            {
                var s = imp.GetPlatformTextureSettings(target);
                s.overridden = true;
                s.maxTextureSize = MaxTextureSize;
                s.format = TextureImporterFormat.Automatic;
                s.textureCompression = TextureImporterCompression.Compressed;
                s.crunchedCompression = false;
                s.compressionQuality = 50;
                imp.SetPlatformTextureSettings(s);
            }
            imp.SaveAndReimport();
        }

        /// <summary>The original model's one-state controller using its idle clip (C05 uses his walk) (made once, then kept, so its GUID holds).</summary>
        static AnimatorController IdleController(string id)
        {
            var clip = AssetDatabase.LoadAllAssetsAtPath(Model(id, CollectionDetail.Near)).OfType<AnimationClip>()
                .Where(c => !c.name.StartsWith("__preview__", StringComparison.Ordinal)).OrderBy(c => c.name.IndexOf(id == "figure-c05-pioneer-veteran-v2" ? "walk" : "idle", StringComparison.OrdinalIgnoreCase) < 0 ? 1 : 0).ThenBy(c => c.name, StringComparer.Ordinal).First();
            var path = Controller(id);
            var ctrl = AssetDatabase.LoadAssetAtPath<AnimatorController>(path);
            if (ctrl == null) ctrl = AnimatorController.CreateAnimatorControllerAtPathWithClip(path, clip);
            var state = ctrl.layers[0].stateMachine.defaultState;
            if (state.motion != clip) { state.motion = clip; EditorUtility.SetDirty(ctrl); }
            if (TokenFigures.Contains(id)) AddMotionStates(ctrl, Model(id, CollectionDetail.Near));
            return ctrl;
        }

        /// <summary>The models that stand on unit tokens (UnitFigures) and have a rig: their controllers also get the
        /// walk and attack states a token's move and attack play (#1866, #1867; design by Tal Heuberger, #1900).</summary>
        public static readonly IReadOnlyCollection<string> TokenFigures = new HashSet<string>(StringComparer.Ordinal)
        {
            UnitFigures.SabraPioneer, UnitFigures.PioneerVeteran, UnitFigures.YoungRecruit, UnitFigures.VeteranFighter,
            UnitFigures.PalmachScout, UnitFigures.Soldier1948, UnitFigures.ArabLegion, UnitFigures.Irregular,
            UnitFigures.SyrianInfantry, UnitFigures.IraqiInfantry, UnitFigures.EgyptianInfantry, UnitFigures.AlaInfantry,
            UnitFigures.LebaneseRegular, UnitFigures.LocalIrregular,
        };

        /// <summary>The token figures whose own FBX has no fire take, and the figure whose fire take each plays (#2375; owner,
        /// 3 November 2026: the project has Tal Heuberger's permission for this adapted version). FireTakeRetarget bakes each as
        /// <see cref="FireTakePath"/> beside the figure's model, so the figure's own bundle carries it (a clip inside another
        /// figure's FBX would be a reference into that figure's bundle, which the stream does not load; CollectionImportTests
        /// EachOriginalBundleKeepsItsPrefabAndOnlyItsOwnAssetsAndPlacementScripts): resampled per frame from the source take
        /// (tangents rebuilt, near-static bones dropped), since C04 shares C07's Armature. The enemy infantry borrow none yet
        /// (owner, 3 November 2026: "C04 only; enemies wait (Recommended)"; #2399).</summary>
        public static readonly IReadOnlyDictionary<string, string> BorrowedFireTakes = new Dictionary<string, string>(StringComparer.Ordinal)
        {
            [UnitFigures.SabraPioneer] = UnitFigures.VeteranFighter,
        };

        /// <summary>Where a borrowing figure's baked fire take lives: a clip named fire, which UnitTokenMotion.CollectionFireTake
        /// counts as a fire take, beside the figure's model.</summary>
        public static string FireTakePath(string id) => $"{Dir(id)}/fire.anim";

        /// <summary>Adds the token figures' walk and attack states to their existing controllers, from the takes already in
        /// each figure's own FBX, or the fire take baked beside it (<see cref="BorrowedFireTakes"/>). Reimports nothing: no
        /// model, texture, clip or prefab changes. Idempotent.
        /// Headless: Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.CollectionImport.PrepareTokenFigureControllers</summary>
        [MenuItem("Statecraft/Collection/Add token figure walk and attack states")]
        public static void PrepareTokenFigureControllers()
        {
            foreach (var id in TokenFigures)
            {
                if (CollectionCatalog.IsFullQualityGeneratedInfantry(id)) { Generated1948Characters.Controller(id); continue; }
                var ctrl = AssetDatabase.LoadAssetAtPath<AnimatorController>(Controller(id))
                    ?? throw new InvalidOperationException(id + ": no controller (run CollectionImport.Run first)");
                AddMotionStates(ctrl, Model(id, CollectionDetail.Near));
            }
            AssetDatabase.SaveAssets();
        }

        /// <summary>Sets <paramref name="controller"/>'s walk state to the model's walk take and its attack state to its
        /// fire take, or to the one baked beside the model for a figure that borrows one, adding each state the first time; a
        /// take the model lacks and borrows nowhere adds no state (C05 has no fire). The default state, when it plays the idle
        /// take, is named idle, the state a token's figures return to after a move (UnitFigureMotion.IdleState): a controller
        /// made from an original's "Armature|idle" take is named after the take.</summary>
        internal static void AddMotionStates(AnimatorController controller, string model)
        {
            var idle = controller.layers[0].stateMachine.defaultState;
            if (idle != null && idle.motion is AnimationClip take && idle.name != UnitFigureMotion.IdleState
                && (take.name == "idle" || take.name.EndsWith("|idle", StringComparison.OrdinalIgnoreCase)))
            {
                idle.name = UnitFigureMotion.IdleState;
                EditorUtility.SetDirty(controller);
            }
            var clips = AssetDatabase.LoadAllAssetsAtPath(model).OfType<AnimationClip>()
                .Where(c => !c.name.StartsWith("__preview__", StringComparison.Ordinal)).ToList();
            SetState(controller, UnitFigureMotion.WalkState, WalkTake(clips));
            SetState(controller, UnitFigureMotion.AttackState, clips.FirstOrDefault(c => UnitTokenMotion.CollectionFireTake(c.name)) ?? BorrowedFireTake(model));
        }

        /// <summary>The fire take baked beside <paramref name="model"/> for a figure in <see cref="BorrowedFireTakes"/>, or null
        /// for any other model.</summary>
        static AnimationClip? BorrowedFireTake(string model)
        {
            string id = Path.GetFileNameWithoutExtension(model);
            if (!BorrowedFireTakes.ContainsKey(id)) return null;
            return AssetDatabase.LoadAssetAtPath<AnimationClip>(FireTakePath(id))
                ?? throw new InvalidOperationException(id + ": no baked fire take (run FireTakeRetarget.Bake first)");
        }

        /// <summary>The walk take: a take named walk first, else C05's idle_walk (his only walk), whatever the takes' order.</summary>
        internal static AnimationClip? WalkTake(IReadOnlyList<AnimationClip> clips) =>
            clips.FirstOrDefault(c => c.name == "walk" || c.name.EndsWith("|walk", StringComparison.OrdinalIgnoreCase))
            ?? clips.FirstOrDefault(c => c.name.EndsWith("|idle_walk", StringComparison.OrdinalIgnoreCase));

        static void SetState(AnimatorController controller, string name, AnimationClip? clip)
        {
            if (clip == null) return;
            var machine = controller.layers[0].stateMachine;
            var state = machine.states.Select(s => s.state).FirstOrDefault(s => s != null && s.name == name) ?? machine.AddState(name);
            if (state.motion == clip) return;
            state.motion = clip;
            EditorUtility.SetDirty(controller);
        }

        static void MakePrefab(string id, CollectionDetail detail, Material mat, AnimatorController? idle)
        {
            var model = AssetDatabase.LoadAssetAtPath<GameObject>(Model(id, detail));
            var go = (GameObject)PrefabUtility.InstantiatePrefab(model);
            try
            {
                foreach (var r in go.GetComponentsInChildren<Renderer>(true))
                {
                    r.sharedMaterials = Enumerable.Repeat(mat, Math.Max(1, r.sharedMaterials.Length)).ToArray();
                    if (r is SkinnedMeshRenderer s) s.updateWhenOffscreen = false;
                }
                var animator = go.GetComponent<Animator>();
                if (idle != null)
                {
                    animator.runtimeAnimatorController = idle;
                    animator.cullingMode = AnimatorCullingMode.CullCompletely;
                }
                else if (animator != null) UnityEngine.Object.DestroyImmediate(animator);
                go.AddComponent<OriginalModelDistance>();
                if (OriginalModelPose.Required(id)) go.AddComponent<OriginalModelPose>();
                PrefabUtility.SaveAsPrefabAsset(go, CollectionCatalog.PrefabPath(id, detail));
            }
            finally { UnityEngine.Object.DestroyImmediate(go); }
        }

        /// <summary>Where a target's bundles are built (incremental, git-ignored).</summary>
        public static string BundleCache(BuildTarget target) => Path.Combine("Library", "CollectionBundles", target.ToString());

        /// <summary>The bundles: each catalog bundle carries its models' far and near prefabs and source model files
        /// (CollectionCatalog.SourceModelPath); their meshes, clips, controllers, materials and colour maps come in as dependencies.
        /// A town model's far-off copy (#2378) carries only its prefab: its derived mesh, baked map and material follow as
        /// dependencies, and nothing of the original.</summary>
        public static AssetBundleBuild[] Builds() => CollectionCatalog.Bundles.Select(b => new AssetBundleBuild
        {
            assetBundleName = b.Bundle,
            // The point-fire pose source carries only its prefab (and the clip it references), never the export's mesh (#2084).
            assetNames = b.Ids.SelectMany(id => CollectionCatalog.IsFigurePose(id) || CollectionCatalog.IsFarCopy(id) ? new[] { CollectionCatalog.PrefabPath(id, CollectionDetail.Far) }
                : new[] { CollectionCatalog.PrefabPath(id, CollectionDetail.Far), CollectionCatalog.PrefabPath(id, CollectionDetail.Near), CollectionCatalog.SourceModelPath(id) }).Distinct().ToArray(),
        }).ToArray();

        /// <summary>Writes <see cref="CollectionCatalog.ChecksFile"/> into <paramref name="folder"/> for the built
        /// <paramref name="bundles"/> there: each one's Unity CRC, size and SHA-256. Throws when Unity has no CRC for one.</summary>
        public static void WriteChecks(string folder, string[] bundles) => WriteChecksFile(folder, bundles, CollectionCatalog.ChecksFile);

        /// <summary><see cref="WriteChecks(string, string[])"/> into the checks file named <paramref name="checksFile"/>.</summary>
        static void WriteChecksFile(string folder, string[] bundles, string checksFile)
        {
            var lines = bundles.OrderBy(b => b, StringComparer.Ordinal).Select(b =>
            {
                var path = Path.Combine(folder, b);
                if (!BuildPipeline.GetCRCForAssetBundle(path, out var crc))
                    throw new InvalidOperationException("CollectionImport: no CRC for the bundle " + path);
                var check = new CollectionCatalog.BundleCheck(crc, new FileInfo(path).Length, CollectionCatalog.Sha256(path));
                return $"{b} {check}";
            });
            File.WriteAllText(Path.Combine(folder, checksFile), string.Join("\n", lines) + "\n");
        }

        /// <summary>Builds the bundles for <paramref name="target"/> and copies them into StreamingAssets/collection (git-ignored,
        /// like content/), so the player build carries them as plain files beside it. Returns the manifest path for
        /// BuildPlayerOptions.assetBundleManifestPath (which keeps the classes only the bundles use from being stripped).
        /// Throws when the build fails: a player build without its bundles would boot without the models.</summary>
        public static string BuildBundles(BuildTarget target) =>
            BuildStreamed(target, BundleCache(target), Builds(), CollectionCatalog.StreamingFolder, CollectionCatalog.ChecksFile);

        /// <summary><see cref="BuildBundles"/> for any set of streamed bundles (CollectionStream.Catalog): builds
        /// <paramref name="builds"/> into <paramref name="cache"/> and copies them, with their checks file, into
        /// StreamingAssets/<paramref name="streamingFolder"/>. Returns the manifest path.</summary>
        public static string BuildStreamed(BuildTarget target, string cache, AssetBundleBuild[] builds, string streamingFolder, string checksFile)
        {
            Directory.CreateDirectory(cache);
            var manifest = BuildPipeline.BuildAssetBundles(cache, builds,
                BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode, target);
            if (manifest == null) throw new InvalidOperationException("CollectionImport: the bundle build failed for " + streamingFolder);
            var dest = Path.Combine(Application.streamingAssetsPath, streamingFolder);
            if (Directory.Exists(dest)) Directory.Delete(dest, true);
            Directory.CreateDirectory(dest);
            long bytes = 0;
            foreach (var b in manifest.GetAllAssetBundles())
            {
                File.Copy(Path.Combine(cache, b), Path.Combine(dest, b));
                var size = new FileInfo(Path.Combine(dest, b)).Length;
                bytes += size;
                Debug.Log($"BUNDLE {b} {size} bytes");
            }
            // Unity reads a bundle's CRC from its .manifest, which stays in the cache (the player ships the bundles only), so
            // the checks are written there, over the same bytes, and copied beside the shipped bundles (found by #668: from
            // #680 every player build failed with "no CRC for the bundle").
            WriteChecksFile(cache, manifest.GetAllAssetBundles(), checksFile);
            File.Copy(Path.Combine(cache, checksFile), Path.Combine(dest, checksFile));
            Debug.Log($"BUNDLES {target}: {manifest.GetAllAssetBundles().Length} bundles, {bytes} bytes -> {dest}");
            return Path.Combine(cache, Path.GetFileName(cache) + ".manifest");
        }
    }
}