using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Unity.Netcode;
using Unity.Netcode.Components;
using Unity.Netcode.Transports.UTP;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
namespace GrassCutter.EditorTools
{
///
/// Builds the whole game from code: project settings, materials, FX textures, asset bank, network prefabs and
/// the Main scene. Run from the menu (GrassCutter/Build Everything) or batch mode (-executeMethod ...BatchBuildAll).
///
public static partial class ProjectBuilder
{
const string Models = "Assets/Art/Models/";
const string Pack = "Assets/Art/Pack/";
const string Mats = "Assets/Art/Materials/";
const string Gen = "Assets/Art/Generated/";
const string Prefabs = "Assets/Prefabs/";
const string ScenePath = "Assets/Scenes/Main.unity";
// ───────────────────────── entry points ─────────────────────────
[MenuItem("GrassCutter/Build Everything")]
public static void BuildAll()
{
SetupProject();
BuildMaterials();
BuildFxAssets();
ReimportModels();
IconStudio.RenderAll();
BuildBank();
BuildUIAssets();
BuildPrefabs();
BuildScene();
AssetDatabase.SaveAssets();
Debug.Log("[Builder] Everything built.");
}
public static void BatchBuildAll()
{
try { BuildAll(); EditorApplication.Exit(0); }
catch (Exception e) { Debug.LogException(e); EditorApplication.Exit(1); }
}
[MenuItem("GrassCutter/Build Windows Player")]
public static void BuildPlayer()
{
// Direct3D 11 only: launched straight from the exe, Steam injects its overlay after the graphics device
// already exists, and that late hook doesn't take on D3D12 (Shift+Tab silently does nothing)
PlayerSettings.SetUseDefaultGraphicsAPIs(BuildTarget.StandaloneWindows64, false);
PlayerSettings.SetGraphicsAPIs(BuildTarget.StandaloneWindows64, new[] { UnityEngine.Rendering.GraphicsDeviceType.Direct3D11 });
// GC_BUILD_DIR builds somewhere else, so a copy of the game that is running doesn't lock the build
// a development build also reports GPU and render-thread frame times (FrameTimingManager), for -demoperf
PlayerSettings.enableFrameTimingStats = CommandLineHas("-devbuild");
var dir = Environment.GetEnvironmentVariable("GC_BUILD_DIR") is string d && d.Length > 0 ? d : "Builds/GrassCutter";
var opts = new BuildPlayerOptions
{
scenes = new[] { ScenePath },
locationPathName = dir + "/GrassCutter.exe",
target = BuildTarget.StandaloneWindows64,
options = CommandLineHas("-devbuild") ? BuildOptions.Development : BuildOptions.None,
};
var report = BuildPipeline.BuildPlayer(opts);
if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
throw new Exception("Build failed: " + report.summary.result);
File.Copy("steam_appid.txt", dir + "/steam_appid.txt", true);
Debug.Log($"[Builder] Player built: {report.summary.totalSize / (1024 * 1024)} MB");
}
public static void BatchBuildPlayer()
{
try { BuildPlayer(); EditorApplication.Exit(0); }
catch (Exception e) { Debug.LogException(e); EditorApplication.Exit(1); }
}
static bool CommandLineHas(string f) => Environment.GetCommandLineArgs().Contains(f);
// ───────────────────────── project settings ─────────────────────────
static void SetupProject()
{
var tm = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
var layers = tm.FindProperty("layers");
void L(int i, string n) { layers.GetArrayElementAtIndex(i).stringValue = n; }
L(6, "Player"); L(7, "Cargo"); L(8, "Prop"); L(9, "Vehicle"); L(10, "Held"); L(11, "ViewModel"); L(12, "LocalPlayer"); L(13, "Build"); L(14, "Riding");
tm.ApplyModifiedPropertiesWithoutUndo();
PlayerSettings.companyName = "GreenHaul";
PlayerSettings.productName = "Grass Cutters Together";
PlayerSettings.runInBackground = true;
PlayerSettings.visibleInBackground = true;
PlayerSettings.colorSpace = ColorSpace.Linear;
PlayerSettings.fullScreenMode = FullScreenMode.FullScreenWindow;
PlayerSettings.defaultScreenWidth = 1920;
PlayerSettings.defaultScreenHeight = 1080;
PlayerSettings.resizableWindow = true;
PlayerSettings.SplashScreen.showUnityLogo = false;
PlayerSettings.SetApiCompatibilityLevel(NamedBuildTarget.Standalone, ApiCompatibilityLevel.NET_Standard);
var ps = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/ProjectSettings.asset")[0]);
var input = ps.FindProperty("activeInputHandler");
if (input != null) input.intValue = 2; // both
ps.ApplyModifiedPropertiesWithoutUndo();
var icon = AssetDatabase.LoadAssetAtPath("Assets/Art/UI/icon_tool_slurpgun.png");
if (icon) PlayerSettings.SetIcons(NamedBuildTarget.Unknown, new[] { icon }, IconKind.Any);
// Make sure the URP asset from Assets/Settings is active everywhere.
var rp = AssetDatabase.LoadAssetAtPath("Assets/Settings/PC_RPAsset.asset");
if (rp)
{
GraphicsSettings.defaultRenderPipeline = rp;
for (int i = 0; i < QualitySettings.names.Length; i++)
{
QualitySettings.SetQualityLevel(i, false);
QualitySettings.renderPipeline = rp;
}
QualitySettings.SetQualityLevel(QualitySettings.names.Length - 1, false);
if (rp is UniversalRenderPipelineAsset urp)
{
urp.shadowDistance = 90f;
urp.msaaSampleCount = 4;
urp.supportsHDR = true;
// depth / opaque textures for soft particles
urp.supportsCameraDepthTexture = true;
urp.supportsCameraOpaqueTexture = true;
EditorUtility.SetDirty(urp);
}
}
EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(ScenePath, true) };
AssetDatabase.SaveAssets();
}
// ───────────────────────── materials ─────────────────────────
[Serializable] class MatDef { public string name, color, texture, emission; public float metallic, smoothness, alpha; public bool transparent, cutout; public float[] tiling; }
[Serializable] class MatList { public MatDef[] items; }
static Shader Lit => Shader.Find("Universal Render Pipeline/Lit");
static Shader ParticleUnlit => Shader.Find("Universal Render Pipeline/Particles/Unlit");
static void BuildMaterials()
{
Directory.CreateDirectory(Mats);
var all = new List();
foreach (var file in Directory.GetFiles("ArtSource", "materials*.json").OrderBy(f => f))
{
var json = File.ReadAllText(file);
all.AddRange(JsonUtility.FromJson("{\"items\":" + json + "}").items);
}
foreach (var d in all)
{
var m = new Material(Lit);
ColorUtility.TryParseHtmlString(d.color, out var c);
if (d.transparent) c.a = d.alpha > 0 ? d.alpha : 0.5f;
m.SetColor("_BaseColor", c);
if (!string.IsNullOrEmpty(d.texture))
{
var tex = AssetDatabase.LoadAssetAtPath("Assets/Art/Textures/" + d.texture);
if (tex) m.SetTexture("_BaseMap", tex);
if (d.tiling != null && d.tiling.Length == 2) m.SetTextureScale("_BaseMap", new Vector2(d.tiling[0], d.tiling[1]));
}
m.SetFloat("_Metallic", d.metallic);
m.SetFloat("_Smoothness", d.smoothness);
if (!string.IsNullOrEmpty(d.emission) && ColorUtility.TryParseHtmlString(d.emission, out var e))
{
m.SetColor("_EmissionColor", e * 2.2f);
m.EnableKeyword("_EMISSION");
m.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
}
if (d.transparent) MakeTransparent(m);
if (d.cutout)
{
// leaf cards: alpha-tested, double sided
m.SetFloat("_AlphaClip", 1f);
m.SetFloat("_Cutoff", 0.5f);
m.SetFloat("_Cull", 0f);
m.EnableKeyword("_ALPHATEST_ON");
m.renderQueue = (int)RenderQueue.AlphaTest;
}
Save(m, Mats + d.name + ".mat");
}
// the phone's display is the picture of a panel, and lights nothing but itself
var screen = new Material(Shader.Find("Universal Render Pipeline/Unlit"));
screen.SetColor("_BaseColor", Color.white);
Save(screen, Mats + "M_PhoneScreen.mat");
// build ghost base
Save(LitMat(new Color(0.6f, 0.9f, 1f, 0.45f), 0.9f, 0f, true), Mats + "M_Ghost.mat");
}
static Material LitMat(Color c, float smooth, float metal, bool transparent)
{
var m = new Material(Lit);
m.SetColor("_BaseColor", c);
m.SetFloat("_Smoothness", smooth);
m.SetFloat("_Metallic", metal);
if (transparent) MakeTransparent(m);
return m;
}
static void MakeTransparent(Material m)
{
m.SetFloat("_Surface", 1f);
m.SetFloat("_Blend", 0f);
m.SetFloat("_ZWrite", 0f);
BaseShaderGUI.SetupMaterialBlendMode(m);
BaseShaderGUI.SetMaterialKeywords(m);
m.renderQueue = (int)RenderQueue.Transparent;
}
static void Save(Material m, string path)
{
m.enableInstancing = true;
var existing = AssetDatabase.LoadAssetAtPath(path);
if (existing)
{
existing.shader = m.shader;
existing.CopyPropertiesFromMaterial(m);
existing.shaderKeywords = m.shaderKeywords;
existing.renderQueue = m.renderQueue;
existing.enableInstancing = true;
existing.globalIlluminationFlags = m.globalIlluminationFlags;
EditorUtility.SetDirty(existing);
}
else AssetDatabase.CreateAsset(m, path);
}
// ───────────────────────── FX textures & materials ─────────────────────────
static void BuildFxAssets()
{
Directory.CreateDirectory(Gen);
Tex("fx_soft", 128, (x, y) => { float d = Vector2.Distance(new Vector2(x, y), Vector2.one * 0.5f) * 2f; float a = Mathf.Clamp01(1f - d); return new Color(1, 1, 1, a * a * (3 - 2 * a)); });
Tex("fx_ring", 128, (x, y) => { float d = Vector2.Distance(new Vector2(x, y), Vector2.one * 0.5f) * 2f; float a = Mathf.Clamp01(1f - Mathf.Abs(d - 0.8f) / 0.12f); return new Color(1, 1, 1, a); });
Tex("fx_shard", 64, (x, y) =>
{
// rounded triangle-ish shard
var p = new Vector2(x - 0.5f, y - 0.5f);
float a = Mathf.Clamp01((0.42f - Mathf.Abs(p.x) - Mathf.Abs(p.y) * 0.6f) * 12f);
return new Color(1, 1, 1, a);
});
Tex("fx_sparkle", 128, (x, y) =>
{
var p = new Vector2(x - 0.5f, y - 0.5f) * 2f;
float star = Mathf.Clamp01(1f - Mathf.Abs(p.x * p.y) * 30f - p.magnitude * 0.9f);
float core = Mathf.Clamp01(1f - p.magnitude * 3f);
return new Color(1, 1, 1, Mathf.Clamp01(star + core));
});
Tex("fx_confetti", 32, (x, y) => new Color(1, 1, 1, (Mathf.Abs(x - 0.5f) < 0.45f && Mathf.Abs(y - 0.5f) < 0.28f) ? 1f : 0f));
Tex("fx_drop", 64, (x, y) =>
{
// glassy droplet: bright rim + highlight
var p = new Vector2(x - 0.5f, y - 0.5f) * 2f;
float d = p.magnitude;
float a = Mathf.Clamp01((1f - d) * 6f);
float rim = Mathf.Clamp01(1f - Mathf.Abs(d - 0.75f) * 5f) * 0.6f;
float hi = Mathf.Clamp01(1f - Vector2.Distance(p, new Vector2(-0.3f, 0.35f)) * 4f);
float v = 0.75f + rim * 0.25f + hi * 0.25f;
return new Color(v, v, v, a * (0.55f + rim + hi * 0.5f));
});
Tex("fx_foam", 128, (x, y) =>
{
var p = new Vector2(x - 0.5f, y - 0.5f) * 2f;
float d = p.magnitude;
float n = Mathf.PerlinNoise(x * 9f + 3f, y * 9f + 7f) * 0.6f + Mathf.PerlinNoise(x * 23f, y * 23f) * 0.4f;
float a = Mathf.Clamp01((1f - d) * 2.2f) * Mathf.Clamp01((n - 0.32f) * 3f);
return new Color(1, 1, 1, a);
});
Tex("fx_flame", 128, (x, y) => { float d = Vector2.Distance(new Vector2(x, y), Vector2.one * 0.5f) * 2f; float a = Mathf.Clamp01(1f - d); a = a * a; return new Color(1, 1, 1, a); });
Tex("fx_leaf", 64, (x, y) =>
{
// a pointy grass clipping: lens shape along y with a lighter midrib
float along = Mathf.Abs(y - 0.5f) * 2f;
float half = 0.2f * Mathf.Pow(Mathf.Clamp01(1f - along), 0.7f);
float dx = Mathf.Abs(x - 0.5f);
float a = Mathf.Clamp01((half - dx) * 60f);
float v = 0.8f + Mathf.Clamp01(1f - dx * 25f) * 0.2f;
return new Color(v, v, v, a);
});
OceanTextures();
AssetDatabase.Refresh();
Save(Particle("fx_soft", 0), Mats + "FX_Soft.mat");
Save(Particle("fx_ring", 0), Mats + "FX_Ring.mat");
Save(Particle("fx_shard", 0), Mats + "FX_Shard.mat");
Save(Particle("fx_sparkle", 2), Mats + "FX_Sparkle.mat");
Save(Particle("fx_confetti", 0), Mats + "FX_Confetti.mat");
Save(Particle("fx_drop", 0), Mats + "FX_Drop.mat");
Save(Particle("fx_foam", 0), Mats + "FX_Foam.mat");
Save(Particle("fx_flame", 2), Mats + "FX_Flame.mat");
Save(Particle("fx_leaf", 0), Mats + "FX_Leaf.mat");
OceanMaterials();
}
/// Tileable water normal map, foam noise and cloud noise (periodic value noise so they wrap).
static void OceanTextures()
{
float Periodic(float x, float y, int cells, int seed)
{
// tileable value noise with smooth interpolation
float fx = x * cells, fy = y * cells;
int x0 = Mathf.FloorToInt(fx), y0 = Mathf.FloorToInt(fy);
float tx = fx - x0, ty = fy - y0;
tx = tx * tx * (3 - 2 * tx); ty = ty * ty * (3 - 2 * ty);
float H(int i, int j)
{
i = ((i % cells) + cells) % cells; j = ((j % cells) + cells) % cells;
uint h = (uint)(i * 374761393 + j * 668265263 + seed * 2246822519u);
h = (h ^ (h >> 13)) * 1274126177u;
return (h & 0xFFFF) / 65535f;
}
return Mathf.Lerp(Mathf.Lerp(H(x0, y0), H(x0 + 1, y0), tx), Mathf.Lerp(H(x0, y0 + 1), H(x0 + 1, y0 + 1), tx), ty);
}
float Fbm(float x, float y, int seed, int oct)
{
float v = 0f, amp = 0.5f, sum = 0f;
int cells = 4;
for (int o = 0; o < oct; o++) { v += Periodic(x, y, cells, seed + o) * amp; sum += amp; amp *= 0.5f; cells *= 2; }
return v / sum;
}
const int N = 256;
var hgt = new float[N, N];
for (int j = 0; j < N; j++)
for (int i = 0; i < N; i++)
{
float x = (i + 0.5f) / N, y = (j + 0.5f) / N;
// ridged ripples
float r = 1f - Mathf.Abs(Fbm(x, y, 11, 5) * 2f - 1f);
hgt[i, j] = r * r;
}
var nrm = new Texture2D(N, N, TextureFormat.RGBA32, false);
for (int j = 0; j < N; j++)
for (int i = 0; i < N; i++)
{
float dx = hgt[(i + 1) % N, j] - hgt[(i + N - 1) % N, j];
float dy = hgt[i, (j + 1) % N] - hgt[i, (j + N - 1) % N];
var n = new Vector3(-dx * 3f, -dy * 3f, 1f).normalized;
nrm.SetPixel(i, j, new Color(n.x * 0.5f + 0.5f, n.y * 0.5f + 0.5f, n.z * 0.5f + 0.5f, 1f));
}
nrm.Apply();
File.WriteAllBytes(Gen + "water_normal.png", nrm.EncodeToPNG());
UnityEngine.Object.DestroyImmediate(nrm);
Tex("water_foam", 256, (x, y) => { float v = Fbm(x, y, 23, 5); float cells = 1f - Mathf.Abs(Fbm(x, y, 41, 3) * 2f - 1f); float f = Mathf.Clamp01((v * 0.6f + cells * 0.6f - 0.55f) * 3f); return new Color(f, f, f, 1f); });
Tex("sky_clouds", 512, (x, y) => { float v = Fbm(x, y, 77, 6); float f = Mathf.Clamp01((v - 0.42f) * 2.6f); return new Color(f, f, f, 1f); });
AssetDatabase.Refresh();
var ti = (TextureImporter)AssetImporter.GetAtPath(Gen + "water_normal.png");
if (ti) { ti.textureType = TextureImporterType.NormalMap; ti.wrapMode = TextureWrapMode.Repeat; ti.SaveAndReimport(); }
foreach (var n in new[] { "water_foam", "sky_clouds" })
{
var t2 = (TextureImporter)AssetImporter.GetAtPath(Gen + n + ".png");
if (t2) { t2.wrapMode = TextureWrapMode.Repeat; t2.sRGBTexture = false; t2.SaveAndReimport(); }
}
}
static void OceanMaterials()
{
// the meadow: GPU grass + hemp, the mow-mask painter and the soil
Save(new Material(Shader.Find("GrassCutter/Grass")), Mats + "M_Grass.mat");
Save(new Material(Shader.Find("GrassCutter/GrassFur")), Mats + "M_GrassFur.mat");
Save(new Material(Shader.Find("GrassCutter/GrassStrand")), Mats + "M_GrassStrand.mat");
Save(new Material(Shader.Find("GrassCutter/Ghost")), Mats + "M_Ghost.mat");
Save(new Material(Shader.Find("GrassCutter/Beam")), Mats + "M_UfoBeam.mat");
Save(new Material(Shader.Find("GrassCutter/Studio")), Mats + "M_Studio.mat");
PlantMat("M_CropWheat", 1.2f, new Color(1.42f, 1.08f, 0.5f));
PlantMat("M_CropOats", 1f, new Color(1.1f, 1.12f, 0.82f));
PlantMat("M_CropCorn", 2.1f, Color.white);
PlantMat("M_CropSunflower", 1.95f, Color.white);
PlantMat("M_Flowers", 0.68f, Color.white, true);
var hemp = new Material(Shader.Find("GrassCutter/Grass"));
hemp.SetFloat("_Plant", 1f);
var leafPath = "Assets/Art/Textures/T_HempLeaf.png";
var leafImp = (TextureImporter)AssetImporter.GetAtPath(leafPath);
if (leafImp && (leafImp.wrapMode != TextureWrapMode.Clamp || !leafImp.alphaIsTransparency))
{
leafImp.wrapMode = TextureWrapMode.Clamp;
leafImp.alphaIsTransparency = true;
leafImp.mipmapEnabled = true;
leafImp.SaveAndReimport();
}
hemp.SetTexture("_MainTex", AssetDatabase.LoadAssetAtPath(leafPath));
Save(hemp, Mats + "M_Hemp.mat");
var soil = new Material(Shader.Find("GrassCutter/Ground"));
Save(soil, Mats + "M_Soil.mat");
var sky = new Material(Shader.Find("GrassCutter/Sky"));
sky.SetTexture("_CloudTex", AssetDatabase.LoadAssetAtPath(Gen + "sky_clouds.png"));
sky.SetTexture("_PlanetTex", AssetDatabase.LoadAssetAtPath("Assets/Art/UI/sky_planet.png"));
Save(sky, Mats + "M_Sky.mat");
}
static void Tex(string name, int size, Func f)
{
var t = new Texture2D(size, size, TextureFormat.RGBA32, false);
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
t.SetPixel(x, y, f((x + 0.5f) / size, (y + 0.5f) / size));
t.Apply();
File.WriteAllBytes(Gen + name + ".png", t.EncodeToPNG());
UnityEngine.Object.DestroyImmediate(t);
}
static Material Particle(string tex, int blend)
{
var m = new Material(ParticleUnlit);
m.SetTexture("_BaseMap", AssetDatabase.LoadAssetAtPath(Gen + tex + ".png"));
m.SetColor("_BaseColor", Color.white);
m.SetFloat("_Surface", 1f);
m.SetFloat("_Blend", blend);
BaseShaderGUI.SetupMaterialBlendMode(m);
BaseShaderGUI.SetMaterialKeywords(m);
m.renderQueue = (int)RenderQueue.Transparent;
return m;
}
static void ReimportModels()
{
foreach (var guid in AssetDatabase.FindAssets("t:Model", new[] { "Assets/Art/Models", "Assets/Art/Pack" }))
AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(guid), ImportAssetOptions.ForceUpdate);
}
// ───────────────────────── asset bank ─────────────────────────
static void BuildBank()
{
Directory.CreateDirectory("Assets/Resources");
const string path = "Assets/Resources/AssetBank.asset";
var bank = AssetDatabase.LoadAssetAtPath(path);
if (!bank) { bank = ScriptableObject.CreateInstance(); AssetDatabase.CreateAsset(bank, path); }
bank.clips = Load("t:AudioClip", "Assets/Audio");
bank.textures = Load("t:Texture2D", "Assets/Art/UI");
bank.fonts = Load("t:Font", "Assets/Fonts");
bank.materials = Load("t:Material", "Assets/Art/Materials");
bank.models = Load("t:Model", "Assets/Art/Models");
bank.models.AddRange(Load("t:Model", "Assets/Art/Pack"));
bank.meshes = new List();
EditorUtility.SetDirty(bank);
AssetDatabase.SaveAssets();
Debug.Log($"[Builder] Bank: {bank.clips.Count} clips, {bank.textures.Count} textures, {bank.fonts.Count} fonts, {bank.models.Count} models, {bank.materials.Count} materials");
}
static List Load(string filter, string folder) where T : UnityEngine.Object
{
var l = new List();
if (!AssetDatabase.IsValidFolder(folder)) return l;
foreach (var g in AssetDatabase.FindAssets(filter, new[] { folder }))
{
var a = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(g));
if (a) l.Add(a);
}
return l;
}
static Mesh FirstMesh(string model)
{
foreach (var folder in new[] { Models, Pack })
foreach (var o in AssetDatabase.LoadAllAssetsAtPath(folder + model + ".fbx"))
if (o is Mesh m) return m;
return null;
}
/// A plant from the pack's atlas, drawn by GrassField like the hemp.
static void PlantMat(string name, float metres, Color tint, bool patchy = false)
{
var m = new Material(Shader.Find("GrassCutter/Grass"));
m.SetFloat("_Plant", 1f);
m.SetFloat("_Metres", metres);
m.SetFloat("_Patchy", patchy ? 1f : 0f);
m.SetColor("_Tint", tint);
m.SetTexture("_MainTex", AssetDatabase.LoadAssetAtPath(patchy ? "Assets/Art/Textures/T_Wildflower.png" : "Assets/Art/Textures/PolygonFarm_Texture_01_A.png"));
Save(m, Mats + name + ".mat");
}
/// A plant one unit tall with its foot at zero: the shader gives it its height.
static Mesh BakedPlant(string model)
{
var src = FirstMesh(model);
var prefab = Model(model);
if (!src || !prefab) return src;
var path = Gen + model + "_plant.asset";
var q = prefab.transform.localRotation;
var m = UnityEngine.Object.Instantiate(src);
m.name = model;
var v = m.vertices; var nrm = m.normals;
float low = float.MaxValue, high = float.MinValue;
for (int i = 0; i < v.Length; i++)
{
v[i] = q * v[i];
low = Mathf.Min(low, v[i].y);
high = Mathf.Max(high, v[i].y);
}
float to = 1f / Mathf.Max(0.01f, high - low);
for (int i = 0; i < v.Length; i++) v[i] = new Vector3(v[i].x * to, (v[i].y - low) * to, v[i].z * to);
for (int i = 0; i < nrm.Length; i++) nrm[i] = q * nrm[i];
m.vertices = v; m.normals = nrm;
m.RecalculateBounds();
var existing = AssetDatabase.LoadAssetAtPath(path);
if (existing) AssetDatabase.DeleteAsset(path);
AssetDatabase.CreateAsset(m, path);
return m;
}
/// Copy of a model's mesh with the FBX root rotation baked into the vertices (for instanced / particle use).
static Mesh BakedMesh(string model)
{
var src = FirstMesh(model);
var prefab = Model(model);
if (!src || !prefab) return src;
var path = Gen + model + "_baked.asset";
var q = prefab.transform.localRotation;
var m = UnityEngine.Object.Instantiate(src);
m.name = model;
var v = m.vertices; var nrm = m.normals;
for (int i = 0; i < v.Length; i++) v[i] = q * v[i];
for (int i = 0; i < nrm.Length; i++) nrm[i] = q * nrm[i];
m.vertices = v; m.normals = nrm;
m.RecalculateBounds();
m.RecalculateTangents();
var existing = AssetDatabase.LoadAssetAtPath(path);
if (existing) AssetDatabase.DeleteAsset(path);
AssetDatabase.CreateAsset(m, path);
return m;
}
/// Our models, or a model from the POLYGON Farm pack.
public static GameObject Model(string name)
{
var m = AssetDatabase.LoadAssetAtPath(Models + name + ".fbx");
return m ? m : AssetDatabase.LoadAssetAtPath(Pack + name + ".fbx");
}
static Material Mat(string name) => AssetDatabase.LoadAssetAtPath(Mats + name + ".mat");
// ───────────────────────── UI assets ─────────────────────────
static void BuildUIAssets()
{
Directory.CreateDirectory("Assets/UI");
const string tss = "Assets/UI/Theme.tss";
if (!File.Exists(tss)) { File.WriteAllText(tss, "@import url(\"unity-theme://default\");\n"); AssetDatabase.ImportAsset(tss); }
const string psPath = "Assets/UI/PanelSettings.asset";
var ps = AssetDatabase.LoadAssetAtPath(psPath);
if (!ps) { ps = ScriptableObject.CreateInstance(); AssetDatabase.CreateAsset(ps, psPath); }
ps.themeStyleSheet = AssetDatabase.LoadAssetAtPath(tss);
ps.scaleMode = PanelScaleMode.ScaleWithScreenSize;
ps.referenceResolution = new Vector2Int(1920, 1080);
ps.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
ps.match = 0.5f;
EditorUtility.SetDirty(ps);
AssetDatabase.SaveAssets();
}
}
}