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29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

// Builds a deterministic 55km x 55km world inside SampleScene, then
// DELETES ITSELF automatically once the save is verified. This script has
// NO runtime dependencies — it does not require, create, or reference any
// other script (no WorldChunk, no ChunkStreamer, nothing). It only creates
// plain GameObjects (ground cubes + spawned prefabs) directly in the scene.
//
// Run:
// Unity.exe -batchmode -projectPath <proj> -executeMethod DistributeWorld.Run -quit -logFile world.log
//
// After it finishes, WorldAuditor.Run() (a separate, non-self-deleting
// script) checks the result for empty chunks or missing asset pools and
// prints a report to the same log. WorldAuditor also has no runtime
// dependencies — it only reads GameObject names and child counts.
public static class DistributeWorld
{
    // ============================================================
    // WORLD SETTINGS
    // ============================================================

    const int Grid = 11;
    const float Chunk = 5000f;

    // Objects per square km. 12/km^2 = 300 objects/chunk.
    const float PerKm2 = 12f;

    // Hard safety cap so a bad density value can never blow up object count.
    const int MaxObjectsPerChunk = 320;

    const int PeopleEveryNObjects = 18;
    const int MinimumPeoplePerChunk = 2;
    const int MaximumPeoplePerChunk = 18;

    const string ScenePath = "Assets/Scenes/SampleScene.unity";
    const string SelfPath = "Assets/Editor/DistributeWorld.cs";
    public const string Root = "WorldMap";

    // ============================================================
    // ASSET FOLDERS
    // ============================================================

    static readonly string[] CityDirs   = { "Assets/SimplePoly City - Low Poly Assets" };
    static readonly string[] ForestDirs = { "Assets/Nature", "Assets/InnerverseInteractive" };
    static readonly string[] DesertDirs = { "Assets/Nature" };
    static readonly string[] SeaDirs    = { "Assets/HQ Boats" };
    static readonly string[] AlienDirs  = { "Assets/_Creepy_Cat", "Assets/FlexUnit", "Assets/SciFi_Space_Soldier", "Assets/Mech" };
    static readonly string[] PeopleDirs = { "Assets/npc_casual_set_00/Prefabs" };

    public enum Biome { City, Forest, Desert, Sea, Alien }

    static readonly Dictionary<int, float> SeaYOffsetCache = new Dictionary<int, float>();
    static readonly Dictionary<int, bool> RendererCache = new Dictionary<int, bool>();

    // Per-chunk info kept only in local memory during this run — nothing is
    // attached to any GameObject as a component. WorldAuditor instead reads
    // the chunk name (which encodes grid position and biome) and counts
    // actual children directly.
    class ChunkResult
    {
        public string name;
        public int objectCount;
    }

    // ============================================================
    // ENTRY
    // ============================================================

    public static void Run()
    {
        try
        {
            UnityEngine.Random.InitState(20260920);

            if (!File.Exists(ScenePath)) { Fail("Scene not found: " + ScenePath, 2); return; }

            var scene = EditorSceneManager.OpenScene(ScenePath, OpenSceneMode.Single);

            var old = GameObject.Find(Root);
            if (old != null)
            {
                Debug.Log("[DistributeWorld] Removing previous WorldMap...");
                UnityEngine.Object.DestroyImmediate(old);
            }

            var root = new GameObject(Root);

            var pools = new Dictionary<Biome, GameObject[]>
            {
                { Biome.City,   Load(CityDirs) },
                { Biome.Forest, Load(ForestDirs) },
                { Biome.Desert, Load(DesertDirs) },
                { Biome.Sea,    Load(SeaDirs) },
                { Biome.Alien,  Load(AlienDirs) }
            };

            var people = Load(PeopleDirs);

            Debug.Log(
                "[DistributeWorld] pools: " +
                "city=" + pools[Biome.City].Length +
                " forest=" + pools[Biome.Forest].Length +
                " desert=" + pools[Biome.Desert].Length +
                " sea=" + pools[Biome.Sea].Length +
                " alien=" + pools[Biome.Alien].Length +
                " people=" + people.Length
            );

            var mats = MakeMaterials();

            float half = Grid * Chunk / 2f;

            float objectsPerChunkFloat = PerKm2 * (Chunk / 1000f) * (Chunk / 1000f);
            int objectsPerChunk = Mathf.Clamp(Mathf.RoundToInt(objectsPerChunkFloat), 1, MaxObjectsPerChunk);

            int totalObjects = 0;
            int totalPeople = 0;
            var chunkResults = new List<ChunkResult>();

            for (int gx = 0; gx < Grid; gx++)
            {
                for (int gz = 0; gz < Grid; gz++)
                {
                    Biome biome = BiomeAt(gx, gz);

                    float cx = -half + (gx + 0.5f) * Chunk;
                    float cz = -half + (gz + 0.5f) * Chunk;

                    string chunkName = $"Chunk_{gx}_{gz}_{biome}";
                    var chunk = new GameObject(chunkName);
                    chunk.transform.SetParent(root.transform, false);
                    chunk.transform.position = new Vector3(cx, 0f, cz);

                    CreateGround(chunk.transform, biome, mats);

                    int objectsSpawnedThisChunk = 0;

                    GameObject[] pool = pools[biome];
                    if (pool.Length > 0)
                    {
                        // Deterministic per-chunk seed, both terms well within
                        // int range so this can never overflow.
                        int seed = unchecked(20260920 + gx * 92821 + gz * 68917);
                        UnityEngine.Random.InitState(seed);

                        for (int i = 0; i < objectsPerChunk; i++)
                        {
                            GameObject prefab = pool[UnityEngine.Random.Range(0, pool.Length)];
                            Vector2 r = UnityEngine.Random.insideUnitCircle * (Chunk * 0.48f);

                            float y = biome == Biome.Sea ? SeaSurfaceYFor(prefab) : 0f;
                            float rotation = UnityEngine.Random.Range(0f, 360f);
                            float scale = UnityEngine.Random.Range(0.92f, 1.08f);

                            Spawn(chunk.transform, prefab, new Vector3(cx + r.x, y, cz + r.y), rotation, scale);

                            totalObjects++;
                            objectsSpawnedThisChunk++;
                        }
                    }

                    if ((biome == Biome.City || biome == Biome.Alien) && people.Length > 0)
                    {
                        int peopleCount = Mathf.Clamp(
                            Mathf.RoundToInt(objectsPerChunk / (float)PeopleEveryNObjects),
                            MinimumPeoplePerChunk,
                            MaximumPeoplePerChunk
                        );

                        int seed = unchecked(800000 + gx * 51197 + gz * 40427);
                        UnityEngine.Random.InitState(seed);

                        for (int i = 0; i < peopleCount; i++)
                        {
                            GameObject prefab = people[UnityEngine.Random.Range(0, people.Length)];
                            Vector2 r = UnityEngine.Random.insideUnitCircle * (Chunk * 0.42f);

                            Spawn(chunk.transform, prefab, new Vector3(cx + r.x, 0f, cz + r.y),
                                  UnityEngine.Random.Range(0f, 360f), UnityEngine.Random.Range(0.95f, 1.05f));

                            totalPeople++;
                            objectsSpawnedThisChunk++;
                        }
                    }

                    chunkResults.Add(new ChunkResult { name = chunkName, objectCount = objectsSpawnedThisChunk });

                    if (!Application.isBatchMode)
                        EditorUtility.DisplayProgressBar(
                            "Building World",
                            $"Chunk {gx + 1},{gz + 1} / {Grid},{Grid}",
                            (gx * Grid + gz + 1) / (float)(Grid * Grid)
                        );
                }
            }

            if (!Application.isBatchMode) EditorUtility.ClearProgressBar();

            int emptyChunks = chunkResults.Count(c => c.objectCount == 0);

            Debug.Log(
                "[DistributeWorld] generated: objects=" + totalObjects +
                " people=" + totalPeople +
                " chunks=" + (Grid * Grid) +
                " emptyChunks=" + emptyChunks +
                " world=" + (Grid * Chunk) + "m x " + (Grid * Chunk) + "m"
            );

            EditorSceneManager.MarkSceneDirty(scene);
            bool saved = EditorSceneManager.SaveScene(scene, ScenePath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

            bool rootExists = GameObject.Find(Root) != null;
            bool validCounts = totalObjects > 0;
            bool ok = saved && rootExists && validCounts;

            if (!ok)
            {
                Fail("Save NOT verified. Script kept. saved=" + saved + " root=" + rootExists + " objects=" + totalObjects, 3);
                return;
            }

            Debug.Log("[DistributeWorld] VERIFIED. World saved successfully.");

            // Run the audit right away so problems are visible in the same
            // log, before this script deletes itself. WorldAuditor.cs stays
            // in the project (it is not self-deleting) so it can be re-run
            // any time from Tools > World > Audit World.
            WorldAuditor.Run();

            if (File.Exists(SelfPath))
            {
                AssetDatabase.DeleteAsset(SelfPath);
                AssetDatabase.Refresh();
                Debug.Log("[DistributeWorld] Script removed (self-delete complete).");
            }

            if (Application.isBatchMode) EditorApplication.Exit(0);
        }
        catch (Exception e)
        {
            if (!Application.isBatchMode) EditorUtility.ClearProgressBar();
            Fail("Unhandled exception: " + e, 10);
        }
    }

    // ============================================================
    // GROUND
    // ============================================================

    static void CreateGround(Transform parent, Biome biome, Dictionary<Biome, Material> mats)
    {
        var ground = GameObject.CreatePrimitive(PrimitiveType.Cube);
        ground.name = "Ground";
        ground.transform.SetParent(parent, false);
        ground.transform.localPosition = new Vector3(0f, -1f, 0f);
        ground.transform.localScale = new Vector3(Chunk, 2f, Chunk);
        ground.isStatic = true;

        if (mats.TryGetValue(biome, out Material material) && material != null)
        {
            var renderer = ground.GetComponent<Renderer>();
            if (renderer != null) renderer.sharedMaterial = material;
        }
    }

    // ============================================================
    // BIOME LAYOUT
    // ============================================================

    static Biome BiomeAt(int x, int z)
    {
        int center = Grid / 2;
        int dx = x - center;
        int dz = z - center;

        if (Mathf.Abs(dx) <= 1 && Mathf.Abs(dz) <= 1) return Biome.City;
        if (x == 0 || z == 0 || x == Grid - 1 || z == Grid - 1) return Biome.Sea;
        if (dz >= 3) return Biome.Alien;
        if (dx <= -2) return Biome.Forest;
        if (dx >= 2) return Biome.Desert;
        return Biome.City;
    }

    // ============================================================
    // ASSET LOADING
    // ============================================================

    static GameObject[] Load(string[] dirs)
    {
        var list = new List<GameObject>();
        var valid = dirs.Where(AssetDatabase.IsValidFolder).ToArray();
        if (valid.Length == 0) return Array.Empty<GameObject>();

        var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

        foreach (string guid in AssetDatabase.FindAssets("t:GameObject", valid))
        {
            string path = AssetDatabase.GUIDToAssetPath(guid);
            string ext = Path.GetExtension(path).ToLowerInvariant();
            if (ext != ".prefab" && ext != ".fbx") continue;

            string lower = path.ToLowerInvariant();
            if (lower.Contains("/editor/") || lower.Contains("/demo/") ||
                lower.Contains("/sample/") || lower.Contains("/samples/")) continue;

            if (!seen.Add(path)) continue;

            GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            if (go == null) continue;

            int id = go.GetInstanceID();
            if (RendererCache.TryGetValue(id, out bool cachedHasRenderer))
            {
                if (!cachedHasRenderer) continue;
            }
            else
            {
                bool hasRenderer = go.GetComponentInChildren<Renderer>(true) != null;
                RendererCache[id] = hasRenderer;
                if (!hasRenderer) continue;
            }

            list.Add(go);
        }

        return list.ToArray();
    }

    // ============================================================
    // SPAWN
    // ============================================================

    static void Spawn(Transform parent, GameObject prefab, Vector3 position, float yRotation, float scale)
    {
        GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
        if (go == null) return;

        go.transform.SetParent(parent, true);
        go.transform.position = position;
        go.transform.rotation = Quaternion.Euler(0f, yRotation, 0f);
        go.transform.localScale = Vector3.one * scale;

        // Plain instantiated prefab. No extra component is attached — this
        // script has zero runtime dependencies by design.
    }

    // ============================================================
    // BOAT / SEA HEIGHT
    // ============================================================

    // Estimates how far a prefab's own pivot sits above its lowest visible
    // point, using the prefab ASSET's own local hierarchy (not a live scene
    // instance). This only reads each renderer's local bounds and its
    // transform relative to the prefab root, which is well-defined for a
    // prefab asset on disk and does not depend on it being placed in a scene.
    static float SeaSurfaceYFor(GameObject prefab)
    {
        if (prefab == null) return 0f;

        int id = prefab.GetInstanceID();
        if (SeaYOffsetCache.TryGetValue(id, out float cached)) return cached;

        Renderer[] renderers = prefab.GetComponentsInChildren<Renderer>(true);
        if (renderers == null || renderers.Length == 0)
        {
            SeaYOffsetCache[id] = 0f;
            return 0f;
        }

        float minY = float.PositiveInfinity;

        foreach (Renderer renderer in renderers)
        {
            if (renderer == null) continue;

            Bounds b = renderer.localBounds;

            Vector3[] corners =
            {
                new Vector3(b.min.x, b.min.y, b.min.z),
                new Vector3(b.min.x, b.min.y, b.max.z),
                new Vector3(b.max.x, b.min.y, b.min.z),
                new Vector3(b.max.x, b.min.y, b.max.z),
                new Vector3(b.min.x, b.max.y, b.min.z),
                new Vector3(b.min.x, b.max.y, b.max.z),
                new Vector3(b.max.x, b.max.y, b.min.z),
                new Vector3(b.max.x, b.max.y, b.max.z),
            };

            foreach (Vector3 corner in corners)
            {
                Vector3 worldPoint = renderer.transform.TransformPoint(corner);
                Vector3 rootLocal = prefab.transform.InverseTransformPoint(worldPoint);
                minY = Mathf.Min(minY, rootLocal.y);
            }
        }

        if (float.IsInfinity(minY)) minY = 0f;

        float offset = Mathf.Clamp(-minY, -20f, 20f);
        SeaYOffsetCache[id] = offset;
        return offset;
    }

    // ============================================================
    // MATERIALS
    // ============================================================

    static Dictionary<Biome, Material> MakeMaterials()
    {
        const string dir = "Assets/_Game/World";

        if (!AssetDatabase.IsValidFolder("Assets/_Game")) AssetDatabase.CreateFolder("Assets", "_Game");
        if (!AssetDatabase.IsValidFolder(dir)) AssetDatabase.CreateFolder("Assets/_Game", "World");

        Shader shader = Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard");
        if (shader == null)
            Debug.LogWarning("[DistributeWorld] No URP/Lit or Standard shader found.");

        var colors = new Dictionary<Biome, Color>
        {
            { Biome.City,   new Color(0.42f, 0.42f, 0.45f) },
            { Biome.Forest, new Color(0.22f, 0.45f, 0.20f) },
            { Biome.Desert, new Color(0.87f, 0.75f, 0.47f) },
            { Biome.Sea,    new Color(0.10f, 0.35f, 0.65f) },
            { Biome.Alien,  new Color(0.28f, 0.16f, 0.38f) },
        };

        var result = new Dictionary<Biome, Material>();

        foreach (var kv in colors)
        {
            string path = $"{dir}/Ground_{kv.Key}.mat";
            Material material = null;

            try
            {
                material = AssetDatabase.LoadAssetAtPath<Material>(path);
                if (material == null && shader != null)
                {
                    var created = new Material(shader);
                    if (created.HasProperty("_BaseColor")) created.SetColor("_BaseColor", kv.Value);
                    if (created.HasProperty("_Color")) created.SetColor("_Color", kv.Value);
                    AssetDatabase.CreateAsset(created, path);
                    material = AssetDatabase.LoadAssetAtPath<Material>(path);
                }
            }
            catch (Exception e)
            {
                Debug.LogWarning("[DistributeWorld] Material failed: " + path + " : " + e.Message);
            }

            if (material == null)
                Debug.LogWarning($"[DistributeWorld] Ground material for {kv.Key} is null.");

            result[kv.Key] = material;
        }

        return result;
    }

    static void Fail(string message, int code)
    {
        Debug.LogError("[DistributeWorld] " + message);
        if (!Application.isBatchMode) EditorUtility.ClearProgressBar();
        if (Application.isBatchMode) EditorApplication.Exit(code);
    }
}