Grass Cutters Together: the project as of moon-sweepers f3666f0

A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiemandKG
2026-11-06 18:44:40 +06:00
parent 0f0467cd0c
commit d1c3761e58
4190 changed files with 270757 additions and 1 deletions

545
Assets/Editor/IconStudio.cs Normal file
View File

@ -0,0 +1,545 @@
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace GrassCutter.EditorTools
{
/// <summary>
/// Renders every UI icon from the real game models (3/4 view, three-point light, transparent background),
/// then adds a chunky navy outline and a soft drop shadow so they read like one sticker set.
/// Also renders the hanging gate signs (sector name + price / open arrow).
/// </summary>
public static class IconStudio
{
const string Models = "Assets/Art/Models/";
const string Mats = "Assets/Art/Materials/";
const string OutDir = "Assets/Art/UI/";
const int Layer = 31;
const int Render = 768, Final = 256;
static readonly Color Navy = new Color(0.075f, 0.1f, 0.22f, 1f);
class Part
{
public string model, mat;
public Vector2 pos;
public float size = 1f;
public Vector3 euler;
public Color? tint;
public bool mirror;
}
static Part P(string model, float x, float y, float size, float ex = 0, float ey = 0, float ez = 0, string mat = null, Color? tint = null, bool mirror = false) =>
new Part { model = model, pos = new Vector2(x, y), size = size, euler = new Vector3(ex, ey, ez), mat = mat, tint = tint, mirror = mirror };
// badge in the lower-right corner of a composition
static Part Badge(string model, float ex = 0, float ey = 0, float ez = 0, string mat = null, float size = 0.55f) => P(model, 0.5f, -0.42f, size, ex, ey, ez, mat);
static Dictionary<string, Part[]> Icons()
{
const string Coin = "SM_IconCoin", Arrow = "SM_IconArrow", Bolt = "SM_IconBolt", Star = "SM_IconStar", Clock = "SM_IconClock", Gear = "SM_IconGear";
Part[] Up(string model, float ey, string badge = Arrow, float bez = 0f, float ex = 0f) => new[] { P(model, -0.1f, 0.06f, 1f, ex, ey, 0), Badge(badge, 0, badge == Arrow ? 0 : 15, bez) };
var d = new Dictionary<string, Part[]>
{
// tools
["icon_tool_scissors"] = new[] { P("SM_Tool_NailScissors", 0, 0, 1, -90, 0, 0) },
["icon_tool_shears"] = new[] { P("SM_Tool_GardenShears", 0, 0, 1, -90, 0, 0) },
["icon_tool_sickle"] = new[] { P("SM_Tool_Sickle", 0, 0, 1, -90, 0, 0) },
["icon_tool_scythe"] = new[] { P("SM_Tool_Scythe", 0, 0, 1, -90, 0, 0) },
["icon_tool_longscythe"] = new[] { P("SM_Tool_LongScythe", 0, 0, 1, -90, 0, 0) },
["icon_tool_widescythe"] = new[] { P("SM_Tool_WideScythe", 0, 0, 1, -90, 0, 0) },
["icon_tool_hammer"] = new[] { P("SM_Tool_Hammer", 0, 0, 1, -90, 0, 0) },
["icon_tool_handpump"] = new[] { P("SM_Tool_HandPump", 0, 0, 1, 0, -60, 0) },
["icon_tool_slurpgun"] = new[] { P("SM_Tool_SlurpGun", 0, 0, 1, 0, -60, 0) },
["icon_tool_hydrocannon"] = new[] { P("SM_Tool_HydroCannon", 0, 0, 1, 0, -60, 0) },
["icon_tool_megasiphon"] = new[] { P("SM_Tool_MegaSiphon", 0, 0, 1, 0, -60, 0) },
["icon_tool_lawnmower"] = new[] { P("SM_Tool_LawnMower", 0, 0, 1, 15, -40, 0) },
["icon_gadget_tablet"] = new[] { P("SM_Gadget_Tablet", 0, 0, 1, 0, 200, -8) },
// currency
// the crew
["icon_crew_hank"] = new[] { P("SM_Crew_Hank", 0, -0.17f, 1.5f, 0, -8, 0) },
["icon_crew_otis"] = new[] { P("SM_Crew_Otis", 0, -0.17f, 1.5f, 0, -8, 0) },
["icon_crew_lin"] = new[] { P("SM_Crew_Lin", 0, -0.17f, 1.5f, 0, -8, 0) },
["icon_crew_rustam"] = new[] { P("SM_Crew_Rustam", 0, -0.17f, 1.5f, 0, -8, 0) },
["icon_crew_marcus"] = new[] { P("SM_Crew_Marcus", 0, -0.17f, 1.5f, 0, -8, 0) },
["icon_crew_gus"] = new[] { P("SM_Crew_Gus", 0, -0.17f, 1.5f, 0, -8, 0) },
["icon_crew_wade"] = new[] { P("SM_Crew_Wade", 0, -0.17f, 1.5f, 0, -8, 0) },
["icon_crew_kenji"] = new[] { P("SM_Crew_Kenji", 0, -0.17f, 1.5f, 0, -8, 0) },
["icon_coin"] = new[] { P(Coin, 0, 0, 1, 0, 20, 0) },
["icon_star"] = new[] { P(Star, 0, 0, 1, 0, 15, 0) },
// build pieces
["icon_piece_binder"] = new[] { P("SM_Binder", 0, 0, 1, 10, -30, 0) },
["icon_piece_robot"] = new[] { P("SM_RobotDock", 0, 0, 1, 20, -30, 0) },
["icon_piece_robot2"] = new[] { P("SM_RobotDock", 0, -0.1f, 0.9f, 20, -30, 0), P("SM_RobotMower", 0.3f, 0.3f, 0.45f, 10, -30, 0) },
["icon_piece_reaper"] = new[] { P("SM_Reaper", 0, 0, 1, 10, -40, 0) },
["icon_piece_catcher"] = new[] { P("SM_BundleCatcher", 0, 0, 1, 10, -30, 0) },
["icon_piece_foundation"] = new[] { P("SM_Foundation_Square", 0, 0, 1, 25, 30, 0) },
// structures and decor
["icon_piece_wall"] = new[] { P("SM_Wall", 0, 0, 1, 12, -30, 0) },
["icon_piece_windowwall"] = new[] { P("SM_WallWindow", 0, 0, 1, 12, -30, 0) },
["icon_piece_doorwall"] = new[] { P("SM_WallDoor", 0, 0, 1, 12, -30, 0) },
["icon_piece_railing"] = new[] { P("SM_Railing", 0, 0, 1, 15, -30, 0) },
["icon_piece_fence"] = new[] { P("SM_Fence", 0, 0, 1, 15, -30, 0) },
["icon_piece_floor"] = new[] { P("SM_Floor", 0, 0, 1, 25, 30, 0) },
["icon_piece_flatroof"] = new[] { P("SM_FlatRoof", 0, 0, 1, 25, 30, 0) },
["icon_piece_roof"] = new[] { P("SM_Roof", 0, 0, 1, 30, -35, 0) },
["icon_piece_stairs"] = new[] { P("SM_Stairs", 0, 0, 1, 15, 120, 0) },
["icon_piece_steps"] = new[] { P("SM_Steps", 0, 0, 1, 15, 140, 0) },
["icon_piece_pillar"] = new[] { P("SM_Pillar", 0, 0, 1, 10, 30, 0) },
["icon_piece_planter"] = new[] { P("SM_Planter", 0, 0, 1, 25, 150, 0) },
["icon_piece_lamppost"] = new[] { P("SM_Lamppost", 0, 0, 1, 10, 150, 0) },
["icon_piece_bench"] = new[] { P("SM_Bench", 0, 0, 1, 15, 150, 0) },
["icon_piece_crates"] = new[] { P("SM_Crate", 0, 0, 1, 15, 150, 0) },
["icon_treat_beer"] = new[] { P("SM_BeerCan", 0, 0, 1, 15, 150, -14) },
["icon_treat_cigar"] = new[] { P("SM_Cigar", 0, 0, 1, 35, 130, 25) },
["icon_piece_flagpole"] = new[] { P("SM_Flagpole", 0, 0, 1, 10, 150, 0) },
["icon_piece_hopper"] = new[] { P("SM_Hopper", 0, 0, 1, 15, -30, 0) },
["icon_piece_tank"] = new[] { P("SM_WaterTank", 0, 0, 1, 10, -30, 0) },
["icon_piece_pump"] = new[] { P("SM_Pump", 0, 0, 1, 10, -50, 0) },
["icon_piece_megapump"] = new[] { P("SM_Pump", -0.05f, 0.05f, 1, 10, -50, 0, tint: new Color(1f, 0.75f, 0.35f)), Badge(Star, 0, 15, 0) },
["icon_piece_dronehub"] = new[] { P("SM_DroneHub", 0, -0.15f, 0.9f, 20, -30, 0), P("SM_RainDrone", 0.1f, 0.35f, 0.6f, 15, -20, 0) },
["icon_piece_filler"] = new[] { P("SM_Filler", 0, 0, 1, 10, -30, 0) },
["icon_piece_vaporizer"] = new[] { P("SM_Windmill", 0, 0, 1, 10, -30, 0) },
["icon_piece_cryo"] = new[] { P("SM_CryoPress", 0, 0, 1, 10, -30, 0) },
["icon_piece_belt"] = new[] { P("SM_Belt", 0, 0, 1, 0, 0, 0) },
["icon_piece_turnright"] = new[] { P("SM_BeltTurn", 0, 0, 1, 0, 0, 0) },
["icon_piece_turnleft"] = new[] { P("SM_BeltTurn", 0, 0, 1, 0, 0, 0, mirror: true) },
["icon_piece_splitter"] = new[] { P("SM_BeltSplitter", 0, 0, 1, 0, 0, 0) },
["icon_piece_solars"] = new[] { P("SM_SolarPost", 0, 0, 1, 10, -30, 0) },
["icon_piece_solarm"] = new[] { P("SM_SolarPair", 0, 0, 1, 10, -30, 0) },
["icon_piece_solarl"] = new[] { P("SM_SolarTracker", 0, 0, 1, 10, -30, 0) },
["icon_piece_merger"] = new[] { P("SM_BeltMerger", 0, 0, 1, 0, 0, 0) },
["icon_piece_pole"] = new[] { P("SM_Prop_Power_Pole_01", 0, 0, 1, 10, -30, 0) },
["icon_piece_battery"] = new[] { P("SM_BatteryRack", 0, 0, 1, 10, -30, 0) },
["icon_piece_batteryl"] = new[] { P("SM_BatteryBank", 0, 0, 1, 10, -30, 0) },
["icon_piece_unloadbay"] = new[] { P("SM_UnloadBay", 0, 0, 1, 25, 140, 0) },
["icon_piece_hexfoundation"] = new[] { P("SM_Foundation_Hex", 0, 0, 1, 0, 30, 0, tint: new Color(0.8f, 0.8f, 0.7f)) },
["icon_piece_sorter"] = new[] { P("SM_BeltSorter", 0, 0, 1, 0, -30, 0) },
["icon_piece_dronepad"] = new[] { P("SM_Drone", 0, 0.05f, 1, 18, -30, 0) },
["icon_piece_launcher"] = new[] { P("SM_Launcher", 0, 0, 1, 0, -30, 0) },
["icon_piece_launchpad"] = new[] { P("SM_LaunchPad", 0, -0.2f, 1, 25, -30, 0), P("SM_Rocket", 0.05f, 0.25f, 0.8f, 0, -30, 0) },
// vehicles
["icon_vehicle_ski"] = new[] { P("SM_RiderMower", 0, 0, 1, 10, -50, 0) },
["icon_vehicle_push"] = new[] { P("SM_PushMower", 0, 0, 1, 10, -50, 0) },
["icon_vehicle_tug"] = new[] { P("SM_Veh_Tractor_01", 0, 0, 1, 10, -50, 0) },
["icon_vehicle_combine"] = new[] { P("SM_Veh_Harvester_01", 0, 0, 1, 10, -50, 0) },
["icon_vehicle_hover"] = new[] { P("SM_Veh_Pickup_01", 0, 0, 1, 10, -50, 0) },
["icon_vehicle_hauler"] = new[] { P("SM_HaulTractor", 0, 0, 1, 10, -50, 0) },
["icon_vehicle_mulcher"] = new[] { P("SM_WideMulcher", 0, 0, 1, 10, -50, 0) },
["icon_vehicle_baler"] = new[] { P("SM_BalerTractor", 0, 0, 1, 10, -50, 0) },
// SUCTION
["icon_perk_suction"] = Up("SM_Tool_HandPump", -60f, Bolt),
["icon_perk_nozzle"] = Up("SM_Tool_SlurpGun", -90f, Arrow, 90f),
["icon_perk_flow"] = new[] { P("SM_Tool_SlurpGun", -0.1f, 0.06f, 1f, 0, -60, 0), Badge(Clock, 0, 15, 0) },
["icon_perk_pure"] = new[] { P("SM_IceBlock", -0.05f, 0.05f, 0.9f, 20, 30, 0), P(Star, 0.48f, 0.42f, 0.45f, 0, 15, 0) },
["icon_perk_blast"] = Up("SM_Tool_HydroCannon", -60f, Bolt),
["icon_perk_abyss"] = new[] { P("SM_Tool_MegaSiphon", -0.1f, 0.06f, 1f, 0, -60, 0, tint: new Color(0.5f, 0.6f, 1f)), Badge(Star, 0, 15, 0) },
// GEAR
["icon_perk_backpack"] = new[] { P("SM_Crew_Hank", 0, 0, 1, 0, 150, 0), Badge(Arrow) },
["icon_perk_sneakers"] = new[] { P("SM_Crew_Hank", -0.1f, 0.05f, 1, 0, -30, 0), Badge(Bolt, 0, 15, 0) },
["icon_perk_release"] = new[] { P("SM_Hopper", -0.1f, 0.05f, 1, 15, -30, 0), Badge(Bolt, 0, 15, 0) },
["icon_perk_fins"] = new[] { P("SM_Crew_Hank", -0.1f, 0.05f, 1, 60, -20, 0), Badge(Arrow, 0, 0, -90) },
["icon_perk_boots"] = new[] { P("SM_Crew_Hank", -0.1f, 0.05f, 1, 0, -30, 0), Badge(Arrow) },
["icon_perk_pressure"] = new[] { P("SM_WaterTank", -0.1f, 0.05f, 1, 10, -30, 0, tint: new Color(0.6f, 0.85f, 1f)), Badge(Arrow) },
["icon_perk_snorkel"] = new[] { P("SM_Crew_Hank", -0.1f, 0.05f, 1, 50, -20, 0, tint: new Color(0.5f, 0.85f, 1f)), Badge(Bolt, 0, 15, 0) },
["icon_perk_jetpack"] = new[] { P("SM_Crew_Hank", -0.1f, 0.05f, 1, 0, 150, 0), Badge(Bolt, 0, 15, 0) },
["icon_perk_remote"] = new[] { P("SM_Crew_Hank", -0.1f, 0.05f, 1, 0, 150, 0), Badge(Gear, 0, 15, 0) },
["icon_perk_jetfuel"] = new[] { P("SM_Canister", -0.1f, 0.05f, 1, 0, 30, 0), Badge(Bolt, 0, 15, 0) },
// PROCESSING
["icon_perk_filler"] = Up("SM_Filler", -30f, Clock),
["icon_perk_contracts"] = new[] { P(Coin, -0.1f, 0.05f, 1, 0, 20, 0), Badge(Arrow) },
["icon_perk_tankcap"] = Up("SM_WaterTank", -30f),
["icon_perk_superheat"] = Up("SM_Windmill", -30f, Bolt),
["icon_perk_purity"] = new[] { P("SM_Canister", -0.1f, 0.05f, 1, 0, 30, 0), Badge(Star, 0, 15, 0) },
["icon_perk_overclock"] = new[] { P(Gear, -0.15f, 0.12f, 0.9f, 0, 15, 0, tint: new Color(0.4f, 0.85f, 1f)), Badge(Bolt, 0, 15, 0) },
["icon_perk_freeze"] = Up("SM_CryoPress", -30f, Clock),
["icon_perk_megablock"] = new[] { P("SM_IceBlock", -0.1f, 0.05f, 1, 20, 30, 0), Badge(Arrow) },
// LOGISTICS
["icon_perk_rocket"] = new[] { P("SM_Rocket", -0.05f, 0.05f, 1, 0, -30, 0), Badge(Arrow) },
["icon_perk_turnaround"] = new[] { P("SM_Rocket", -0.05f, 0.05f, 1, 0, -30, 0), Badge(Clock, 0, 15, 0) },
["icon_perk_autolaunch"] = new[] { P("SM_LaunchLever", -0.05f, 0.05f, 1, 0, -40, 0), Badge(Gear, 0, 15, 0) },
["icon_perk_beltspeed"] = new[] { P("SM_Belt", -0.1f, 0.08f, 1, 0, 0, 0), Badge(Bolt, 0, 15, 0) },
["icon_perk_beltlogic"] = new[] { P("SM_BeltSplitter", -0.1f, 0.08f, 1, 0, 0, 0), Badge(Gear, 0, 15, 0) },
["icon_perk_express"] = new[] { P("SM_Rocket", -0.05f, 0.05f, 1, 0, -30, 0, tint: new Color(1f, 0.85f, 0.4f)), Badge(Bolt, 0, 15, 0) },
["icon_perk_dronefleet"] = new[] { P("SM_Drone", -0.38f, -0.22f, 0.6f, 18, -30, 0), P("SM_Drone", 0.38f, -0.22f, 0.6f, 18, -40, 0), P("SM_Drone", 0f, 0.3f, 0.66f, 18, -20, 0) },
// AUTOMATION
["icon_perk_pumppower"] = Up("SM_Pump", -50f, Bolt),
["icon_perk_reservoir"] = new[] { P("SM_WaterTank", -0.25f, 0f, 0.8f, 10, -30, 0), P("SM_WaterTank", 0.3f, 0f, 0.8f, 10, -30, 0) },
["icon_perk_deepintake"] = Up("SM_Pump", -50f, Arrow, 180f),
["icon_perk_dronetank"] = Up("SM_RainDrone", -30f, Arrow, 0f, 20f),
["icon_perk_swarm"] = new[] { P("SM_RainDrone", -0.38f, -0.22f, 0.6f, 18, -30, 0), P("SM_RainDrone", 0.38f, -0.22f, 0.6f, 18, -40, 0), P("SM_RainDrone", 0f, 0.3f, 0.66f, 18, -20, 0) },
["icon_perk_storm"] = new[] { P("SM_Buoy", -0.1f, 0.05f, 1, 0, -30, 0), Badge(Bolt, 0, 15, 0) },
// FLEET
["icon_perk_turbo"] = Up("SM_SlurpSki", -50f, Bolt, 0f, 10f),
["icon_perk_vehtank"] = Up("SM_TugPump", -50f, Arrow, 0f, 10f),
["icon_perk_dockpump"] = new[] { P("SM_Dock", -0.1f, 0.05f, 1, 20, -30, 0), Badge(Bolt, 0, 15, 0) },
["icon_perk_tugarm"] = Up("SM_TugPump", 40f, Gear, 0f, 10f),
["icon_perk_fleet"] = new[] { P("SM_SlurpSki", -0.35f, -0.2f, 0.65f, 10, -50, 0), P("SM_SlurpSki", 0.35f, 0.15f, 0.65f, 10, -50, 0) },
["icon_perk_hoverboost"] = Up("SM_HoverTanker", -50f, Bolt, 0f, 10f),
// RIG
["icon_perk_decor"] = new[] { P("SM_Decor_Palm", -0.25f, 0f, 0.85f, 0, -30, 0), P("SM_Decor_Umbrella", 0.3f, 0f, 0.85f, 0, -30, 0) },
["icon_perk_coffee"] = new[] { P("SM_Decor_Vending", -0.1f, 0.05f, 1, 0, -30, 0), Badge(Bolt, 0, 15, 0) },
["icon_perk_foundation"] = new[] { P("SM_Foundation_Square", -0.1f, 0.05f, 1, 25, 30, 0), Badge(Coin, 0, 20, 0) },
["icon_perk_milestone"] = new[] { P(Star, -0.1f, 0.05f, 1, 0, 15, 0), Badge(Coin, 0, 20, 0) },
["icon_perk_gnome"] = new[] { P("SM_Decor_Gnome", 0, 0, 1, 0, -30, 0) },
["icon_perk_landmark"] = new[] { P("SM_Decor_Beacon", -0.1f, 0.05f, 1, 0, -30, 0), Badge(Star, 0, 15, 0) },
["icon_perk_shares"] = new[] { P(Coin, -0.3f, -0.15f, 0.75f, 0, 20, 0), P(Coin, 0.15f, 0.12f, 0.75f, 0, 35, 0), Badge(Arrow) },
};
return d;
}
// ───────────────────────── entry ─────────────────────────
public static void BatchRender()
{
RenderAll();
EditorApplication.Exit(0);
}
[MenuItem("GrassCutter/Render Icons")]
public static void RenderAll()
{
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
{
Debug.LogWarning("[IconStudio] no graphics device (-nographics?) — keeping existing icons");
return;
}
Directory.CreateDirectory(OutDir);
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
var prevAmbient = RenderSettings.ambientLight;
RenderSettings.ambientMode = AmbientMode.Flat;
RenderSettings.ambientLight = new Color(0.52f, 0.54f, 0.6f);
RenderSettings.fog = false;
// metals (coins, gold, tools) need something to reflect: a bright procedural sky as the environment
var sky = new Material(Shader.Find("Skybox/Procedural"));
sky.SetColor("_SkyTint", new Color(0.55f, 0.7f, 1f));
sky.SetColor("_GroundColor", new Color(0.95f, 0.9f, 0.8f));
sky.SetFloat("_Exposure", 1.6f);
RenderSettings.skybox = sky;
RenderSettings.defaultReflectionMode = DefaultReflectionMode.Skybox;
RenderSettings.reflectionIntensity = 1f;
DynamicGI.UpdateEnvironment();
var cam = MakeCamera();
var lights = MakeLights();
int n = 0;
foreach (var kv in Icons())
{
var root = new GameObject("Icon_" + kv.Key);
bool ok = true;
foreach (var part in kv.Value) ok &= Spawn(part, root.transform, cam.transform);
if (ok)
{
Frame(cam, root);
var px = RenderAlpha(cam, Render, Render);
var tex = Sticker(px, Render, Render, Mathf.RoundToInt(Render * 0.022f), Render / Final);
Write(tex, OutDir + kv.Key + ".png");
n++;
}
else Debug.LogWarning("[IconStudio] skipped " + kv.Key);
Object.DestroyImmediate(root);
}
foreach (var l in lights) Object.DestroyImmediate(l);
Object.DestroyImmediate(cam.gameObject);
RenderSettings.ambientLight = prevAmbient;
RenderSettings.skybox = null;
Object.DestroyImmediate(sky);
// the v1 icon set is retired
var keep = new HashSet<string>(Icons().Keys);
foreach (var old in Directory.GetFiles(OutDir, "icon_*.png"))
if (!keep.Contains(Path.GetFileNameWithoutExtension(old))) AssetDatabase.DeleteAsset(old.Replace('\\', '/'));
AssetDatabase.Refresh();
foreach (var f in Directory.GetFiles(OutDir, "icon_*.png")) ConfigureImporter(f.Replace('\\', '/'), false);
Debug.Log($"[IconStudio] rendered {n} icons");
}
// ───────────────────────── staging ─────────────────────────
static Camera MakeCamera()
{
var go = new GameObject("IconCam");
var cam = go.AddComponent<Camera>();
cam.orthographic = true;
cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = Color.black;
cam.cullingMask = 1 << Layer;
cam.allowHDR = false;
cam.allowMSAA = false;
cam.nearClipPlane = 0.01f;
cam.farClipPlane = 100f;
cam.enabled = false;
var data = go.AddComponent<UniversalAdditionalCameraData>();
data.renderPostProcessing = false;
data.antialiasing = AntialiasingMode.None;
data.renderShadows = false;
go.transform.rotation = Quaternion.Euler(24f, 215f, 0f);
return cam;
}
static List<GameObject> MakeLights()
{
var list = new List<GameObject>();
void L(string n, Vector3 euler, Color c, float i)
{
var g = new GameObject(n);
var l = g.AddComponent<Light>();
l.type = LightType.Directional;
l.color = c; l.intensity = i;
l.shadows = LightShadows.None;
l.cullingMask = 1 << Layer;
g.transform.rotation = Quaternion.Euler(euler);
list.Add(g);
}
L("Key", new Vector3(42f, 160f, 0f), new Color(1f, 0.95f, 0.86f), 1.55f);
L("Fill", new Vector3(18f, 290f, 0f), new Color(0.62f, 0.75f, 1f), 0.55f);
L("Rim", new Vector3(-10f, 20f, 0f), new Color(1f, 1f, 1f), 0.9f);
return list;
}
static bool Spawn(Part p, Transform root, Transform cam)
{
var model = ProjectBuilder.Model(p.model);
if (!model) return false;
var holder = new GameObject(p.model).transform;
holder.SetParent(root, false);
var inst = (GameObject)PrefabUtility.InstantiatePrefab(model);
inst.transform.SetParent(holder, false);
holder.rotation = Quaternion.Euler(p.euler);
if (p.mirror) holder.localScale = new Vector3(-1f, 1f, 1f);
Material over = p.mat != null ? AssetDatabase.LoadAssetAtPath<Material>(Mats + p.mat + ".mat") : null;
foreach (var r in inst.GetComponentsInChildren<Renderer>())
{
r.gameObject.layer = Layer;
r.shadowCastingMode = ShadowCastingMode.Off;
if (over) { var arr = r.sharedMaterials; for (int i = 0; i < arr.Length; i++) arr[i] = over; r.sharedMaterials = arr; }
{
// full metals go murky without a real environment: render them as bright glossy paint instead
var arr = r.sharedMaterials;
for (int i = 0; i < arr.Length; i++)
{
if (!arr[i] || !arr[i].HasProperty("_Metallic") || arr[i].GetFloat("_Metallic") < 0.5f) continue;
var m = new Material(arr[i]);
m.SetFloat("_Metallic", 0.25f);
m.SetFloat("_Smoothness", 0.78f);
arr[i] = m;
}
r.sharedMaterials = arr;
}
if (p.tint is Color tint)
{
var arr = r.sharedMaterials;
for (int i = 0; i < arr.Length; i++)
{
if (!arr[i] || !arr[i].HasProperty("_BaseColor")) continue;
var m = new Material(arr[i]);
var bc = m.GetColor("_BaseColor");
// tint only the coloured parts (keeps soles / metal neutral)
float sat = Mathf.Max(bc.r, bc.g, bc.b) - Mathf.Min(bc.r, bc.g, bc.b);
if (sat > 0.15f) m.SetColor("_BaseColor", new Color(tint.r, tint.g, tint.b, bc.a));
arr[i] = m;
}
r.sharedMaterials = arr;
}
}
// normalise: biggest extent = size, then centre on the screen-plane position
var b = BoundsOf(holder.gameObject);
float ext = Mathf.Max(b.size.x, Mathf.Max(b.size.y, b.size.z));
if (ext < 1e-4f) return false;
holder.localScale *= p.size / ext;
b = BoundsOf(holder.gameObject);
var target = cam.right * p.pos.x + cam.up * p.pos.y;
holder.position += target - b.center;
return true;
}
static Bounds BoundsOf(GameObject go)
{
var rs = go.GetComponentsInChildren<Renderer>();
if (rs.Length == 0) return new Bounds(go.transform.position, Vector3.zero);
var b = rs[0].bounds;
foreach (var r in rs) b.Encapsulate(r.bounds);
return b;
}
/// <summary>Fits the ortho camera tightly around the composition (projected corners), with room for the outline.</summary>
static void Frame(Camera cam, GameObject root)
{
var b = BoundsOf(root);
var t = cam.transform;
float minX = float.MaxValue, maxX = float.MinValue, minY = float.MaxValue, maxY = float.MinValue;
// corners of every renderer's bounds give a tighter projected box than the global AABB
foreach (var r in root.GetComponentsInChildren<Renderer>())
{
var rb = r.bounds;
for (int i = 0; i < 8; i++)
{
var c = rb.center + Vector3.Scale(rb.extents, new Vector3((i & 1) == 0 ? -1 : 1, (i & 2) == 0 ? -1 : 1, (i & 4) == 0 ? -1 : 1));
var l = c - b.center;
float x = Vector3.Dot(l, t.right), y = Vector3.Dot(l, t.up);
minX = Mathf.Min(minX, x); maxX = Mathf.Max(maxX, x); minY = Mathf.Min(minY, y); maxY = Mathf.Max(maxY, y);
}
}
var mid = b.center + t.right * ((minX + maxX) * 0.5f) + t.up * ((minY + maxY) * 0.5f);
float half = Mathf.Max(maxX - minX, maxY - minY) * 0.5f;
cam.orthographicSize = half * 1.16f;
cam.aspect = 1f;
t.position = mid - t.forward * (b.extents.magnitude * 2f + 5f);
}
// ───────────────────────── capture ─────────────────────────
/// <summary>Renders over black and over white and recovers straight colour + alpha (works whatever the pipeline does with alpha).</summary>
static Color[] RenderAlpha(Camera cam, int w, int h)
{
var rt = RenderTexture.GetTemporary(new RenderTextureDescriptor(w, h, RenderTextureFormat.ARGB32, 24) { sRGB = true, msaaSamples = 1 });
var read = new Texture2D(w, h, TextureFormat.RGBA32, false, false);
Color[] Shot(Color bg)
{
cam.backgroundColor = bg;
cam.targetTexture = rt;
cam.Render();
var prev = RenderTexture.active;
RenderTexture.active = rt;
read.ReadPixels(new Rect(0, 0, w, h), 0, 0, false);
read.Apply();
RenderTexture.active = prev;
return read.GetPixels();
}
var black = Shot(Color.black);
var white = Shot(Color.white);
cam.targetTexture = null;
RenderTexture.ReleaseTemporary(rt);
Object.DestroyImmediate(read);
var outPx = new Color[w * h];
for (int i = 0; i < outPx.Length; i++)
{
var k = black[i]; var wt = white[i];
float a = 1f - ((wt.r - k.r) + (wt.g - k.g) + (wt.b - k.b)) / 3f;
a = Mathf.Clamp01(a);
if (a < 0.004f) { outPx[i] = new Color(0, 0, 0, 0); continue; }
outPx[i] = new Color(Mathf.Clamp01(k.r / a), Mathf.Clamp01(k.g / a), Mathf.Clamp01(k.b / a), a);
}
return outPx;
}
/// <summary>Outline + drop shadow around the alpha shape, then box-downscale by <paramref name="down"/>.</summary>
static Texture2D Sticker(Color[] px, int w, int h, int radius, int down, Color? outline = null, bool shadow = true)
{
var ol = outline ?? Navy;
var dist = Distance(px, w, h);
int sh = Mathf.RoundToInt(radius * 0.7f);
var comp = new Color[w * h];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
{
int i = y * w + x;
float oa = Mathf.Clamp01(radius + 1f - dist[i]);
float sa = 0f;
if (shadow)
{
int sy = y + sh;
if (sy < h) sa = Mathf.Clamp01(radius + 1f - dist[sy * w + x]) * 0.32f;
}
// shadow (black) → outline → object, all straight-alpha "over"
var c = new Color(0, 0, 0, sa);
c = Over(new Color(ol.r, ol.g, ol.b, oa), c);
c = Over(px[i], c);
comp[i] = c;
}
int fw = w / down, fh = h / down;
var tex = new Texture2D(fw, fh, TextureFormat.RGBA32, false, false);
var outPx = new Color[fw * fh];
float inv = 1f / (down * down);
for (int y = 0; y < fh; y++)
for (int x = 0; x < fw; x++)
{
// premultiplied average so edges don't fringe
float r = 0, g = 0, b = 0, a = 0;
for (int dy = 0; dy < down; dy++)
for (int dx = 0; dx < down; dx++)
{
var c = comp[(y * down + dy) * w + x * down + dx];
r += c.r * c.a; g += c.g * c.a; b += c.b * c.a; a += c.a;
}
outPx[y * fw + x] = a > 0 ? new Color(r / a, g / a, b / a, a * inv) : new Color(0, 0, 0, 0);
}
tex.SetPixels(outPx);
tex.Apply();
return tex;
}
static Color Over(Color top, Color bottom)
{
float a = top.a + bottom.a * (1f - top.a);
if (a <= 0f) return new Color(0, 0, 0, 0);
float k = bottom.a * (1f - top.a);
return new Color((top.r * top.a + bottom.r * k) / a, (top.g * top.a + bottom.g * k) / a, (top.b * top.a + bottom.b * k) / a, a);
}
/// <summary>Two-pass chamfer distance (px) to the nearest solid pixel.</summary>
static float[] Distance(Color[] px, int w, int h)
{
const float Inf = 1e6f, D = 1.4142f;
var d = new float[w * h];
for (int i = 0; i < d.Length; i++) d[i] = px[i].a > 0.45f ? 0f : Inf;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
{
int i = y * w + x;
float v = d[i];
if (x > 0) v = Mathf.Min(v, d[i - 1] + 1f);
if (y > 0)
{
v = Mathf.Min(v, d[i - w] + 1f);
if (x > 0) v = Mathf.Min(v, d[i - w - 1] + D);
if (x < w - 1) v = Mathf.Min(v, d[i - w + 1] + D);
}
d[i] = v;
}
for (int y = h - 1; y >= 0; y--)
for (int x = w - 1; x >= 0; x--)
{
int i = y * w + x;
float v = d[i];
if (x < w - 1) v = Mathf.Min(v, d[i + 1] + 1f);
if (y < h - 1)
{
v = Mathf.Min(v, d[i + w] + 1f);
if (x < w - 1) v = Mathf.Min(v, d[i + w + 1] + D);
if (x > 0) v = Mathf.Min(v, d[i + w - 1] + D);
}
d[i] = v;
}
return d;
}
static void Write(Texture2D t, string path)
{
File.WriteAllBytes(path, t.EncodeToPNG());
Object.DestroyImmediate(t);
}
static void ConfigureImporter(string path, bool sign)
{
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
if (AssetImporter.GetAtPath(path) is not TextureImporter ti) return;
ti.textureType = TextureImporterType.Default;
ti.alphaIsTransparency = true;
ti.sRGBTexture = true;
ti.mipmapEnabled = sign;
ti.wrapMode = TextureWrapMode.Clamp;
ti.textureCompression = TextureImporterCompression.Uncompressed;
ti.SaveAndReimport();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 669c4cf902cff9e4bb3432bc2a7ae780

View File

@ -0,0 +1,120 @@
using UnityEditor;
using UnityEngine;
namespace GrassCutter.EditorTools
{
/// <summary>Import settings for Blender FBX, UI art, textures and audio.</summary>
public class ImportRules : AssetPostprocessor
{
void OnPreprocessModel()
{
bool pack = assetPath.StartsWith("Assets/Art/Pack/");
if (!pack && !assetPath.StartsWith("Assets/Art/Models/")) return;
var mi = (ModelImporter)assetImporter;
mi.bakeAxisConversion = true;
mi.useFileScale = true;
mi.globalScale = 1f;
mi.importCameras = false;
mi.importLights = false;
mi.importVisibility = false;
mi.importAnimation = false;
mi.animationType = assetPath.Contains("SM_Crew") || assetPath.Contains("SM_Dir_") ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
mi.addCollider = false;
// runtime MeshColliders (seabed rocks and wrecks) need CPU-readable meshes in the player
mi.isReadable = assetPath.Contains("SM_Spire") || assetPath.Contains("SM_Wreck") || (pack && !assetPath.Contains("SM_Veh_") && !assetPath.Contains("Hay_Bale"));
mi.meshCompression = ModelImporterMeshCompression.Off;
mi.importNormals = ModelImporterNormals.Import;
mi.importTangents = ModelImporterTangents.CalculateMikk;
mi.materialImportMode = ModelImporterMaterialImportMode.ImportViaMaterialDescription;
mi.materialLocation = ModelImporterMaterialLocation.InPrefab;
mi.materialSearch = ModelImporterMaterialSearch.Everywhere;
mi.materialName = ModelImporterMaterialName.BasedOnMaterialName;
}
/// <summary>
/// The Blender exports land rotated 180° about Y (fronts face −Z). Turn every model around so the manifest's
/// convention holds in Unity: front = +Z, N flap = +Z, E = +X.
/// </summary>
void OnPostprocessModel(GameObject g)
{
if (!assetPath.StartsWith("Assets/Art/Models/")) return;
g.transform.localRotation = Quaternion.AngleAxis(180f, Vector3.up) * g.transform.localRotation;
}
/// <summary>Use our hand-made URP materials (Assets/Art/Materials/M_*.mat) instead of the FBX ones.</summary>
Material OnAssignMaterialModel(Material material, Renderer renderer)
{
// the pack's atlas, and its glass as far as a name tells
if (assetPath.StartsWith("Assets/Art/Pack/"))
return AssetDatabase.LoadAssetAtPath<Material>(material.name.Contains("Glass") || renderer.name.Contains("Glass") ? "Assets/Art/Materials/M_PackGlass.mat" : "Assets/Art/Materials/M_Pack.mat");
if (!assetPath.StartsWith("Assets/Art/Models/")) return null;
var name = material.name;
int dot = name.IndexOf('.');
if (dot > 0) name = name.Substring(0, dot); // Blender duplicates: M_Foo.001
var path = "Assets/Art/Materials/" + name + ".mat";
return AssetDatabase.LoadAssetAtPath<Material>(path);
}
void OnPreprocessTexture()
{
var ti = (TextureImporter)assetImporter;
if (assetPath.StartsWith("Assets/Art/UI/"))
{
ti.textureType = TextureImporterType.Default;
ti.alphaIsTransparency = true;
ti.mipmapEnabled = false;
ti.sRGBTexture = true;
ti.wrapMode = TextureWrapMode.Clamp;
ti.maxTextureSize = 2048;
ti.textureCompression = TextureImporterCompression.CompressedHQ;
ti.npotScale = TextureImporterNPOTScale.None;
}
else if (assetPath.StartsWith("Assets/Art/Textures/"))
{
ti.textureType = TextureImporterType.Default;
ti.mipmapEnabled = true;
ti.anisoLevel = 4;
ti.wrapMode = TextureWrapMode.Repeat;
bool crew = assetPath.Contains("T_Crew_");
ti.maxTextureSize = assetPath.Contains("PolygonFarm") || crew ? 2048 : 1024;
ti.textureCompression = crew ? TextureImporterCompression.Compressed : TextureImporterCompression.CompressedHQ;
}
else if (assetPath.StartsWith("Assets/Art/Generated/"))
{
ti.textureType = TextureImporterType.Default;
ti.alphaIsTransparency = true;
ti.mipmapEnabled = true;
ti.wrapMode = TextureWrapMode.Clamp;
ti.textureCompression = TextureImporterCompression.Uncompressed;
}
}
void OnPreprocessAudio()
{
if (!assetPath.StartsWith("Assets/Audio/")) return;
var ai = (AudioImporter)assetImporter;
var s = ai.defaultSampleSettings;
bool music = assetPath.Contains("music_");
bool loop = assetPath.Contains("_loop");
if (music)
{
s.loadType = AudioClipLoadType.Streaming;
s.compressionFormat = AudioCompressionFormat.Vorbis;
s.quality = 0.75f;
}
else if (loop)
{
s.loadType = AudioClipLoadType.CompressedInMemory;
s.compressionFormat = AudioCompressionFormat.Vorbis;
s.quality = 0.8f;
}
else
{
s.loadType = AudioClipLoadType.DecompressOnLoad;
s.compressionFormat = AudioCompressionFormat.ADPCM;
}
ai.defaultSampleSettings = s;
ai.loadInBackground = music;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 12cf276c41bdddb40a3fa2a8a66e4b2f

View File

@ -0,0 +1,36 @@
using System.Text;
using UnityEditor;
using UnityEngine;
namespace GrassCutter.EditorTools
{
/// <summary>Logs root/child rotations and world-space bounds of every imported model (to catch axis problems).</summary>
public static class ModelAudit
{
[MenuItem("GrassCutter/Audit Models")]
public static void Run()
{
var sb = new StringBuilder("[Audit]\n");
foreach (var guid in AssetDatabase.FindAssets("t:Model", new[] { "Assets/Art/Models" }))
{
var path = AssetDatabase.GUIDToAssetPath(guid);
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
var go = (GameObject)Object.Instantiate(prefab);
var rs = go.GetComponentsInChildren<Renderer>();
Bounds b = rs.Length > 0 ? rs[0].bounds : new Bounds();
foreach (var r in rs) b.Encapsulate(r.bounds);
sb.Append($"{prefab.name}: rootRot={go.transform.localEulerAngles} size={b.size:F2} center={b.center:F2}\n");
foreach (Transform c in go.transform)
sb.Append($" - {c.name} pos={c.localPosition:F2} rot={c.localEulerAngles:F0} scale={c.localScale:F2}\n");
Object.DestroyImmediate(go);
}
Debug.Log(sb.ToString());
}
public static void BatchRun()
{
Run();
EditorApplication.Exit(0);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: be91b7867106442448599858b5adc914

View File

@ -0,0 +1,586 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
namespace GrassCutter.EditorTools
{
/// <summary>Network prefabs: crew, cargo, mowers and every buildable piece (the depot, belts).</summary>
public static partial class ProjectBuilder
{
static readonly List<GameObject> NetPrefabs = new List<GameObject>();
static PhysicsMaterial _propPhys, _slick, _beltPhys, _hullPhys;
static void BuildPrefabs()
{
System.IO.Directory.CreateDirectory(Prefabs);
NetPrefabs.Clear();
_propPhys = PhysMat("PM_Prop", 0.6f, 0.5f, 0.15f);
_slick = PhysMat("PM_Slick", 0.05f, 0.05f, 0f);
_beltPhys = PhysMat("PM_Belt", 0.25f, 0.2f, 0f);
_hullPhys = PhysMat("PM_Hull", 0.2f, 0.15f, 0.05f);
// Crew member
Net("Player", Layers.Player, go =>
{
// whoever leaves takes their body with them; everything else stays in the world
go.GetComponent<NetworkObject>().DontDestroyWithOwner = false;
var cap = go.AddComponent<CapsuleCollider>();
cap.height = 1.3f; cap.radius = 0.38f; cap.center = new Vector3(0, 0.65f, 0);
go.AddComponent<CrewBody>();
var nt = go.AddComponent<NetworkTransform>();
nt.AuthorityMode = NetworkTransform.AuthorityModes.Owner;
nt.UseQuaternionSynchronization = true; // on a ball people lean every way
NoScale(nt);
var head = new GameObject("Head").transform;
head.SetParent(go.transform, false);
head.localPosition = new Vector3(0, 1.12f, 0);
var avatar = new GameObject("Avatar");
avatar.transform.SetParent(go.transform, false);
avatar.AddComponent<CrewAvatar>(); // it puts on whoever the player chose
var pa = go.AddComponent<PlayerAgent>();
pa.head = head;
go.AddComponent<PlayerTools>();
go.AddComponent<PlayerGrab>();
go.AddComponent<PlayerBuild>();
}, rigidbody: false);
Net("TeamState", 0, go => go.AddComponent<TeamState>(), rigidbody: false, transformSync: false);
// Cargo: a grass bundle, hay, a pressed brick
CargoPrefab("Cargo_Grass", "SM_Prop_Hay_Bale_Square_01_Green", CargoKind.Grass, 1f, "Grass bundle", 1f, 0.3f);
CargoPrefab("Cargo_Hay", "SM_Prop_Hay_Bale_Square_01", CargoKind.Hay, 1f, "Hay", 1f, 0.3f);
CargoPrefab("Cargo_Brick", "SM_Prop_Hay_Bale_Square_Plastic_01", CargoKind.Brick, 2f, "Pressed brick", 1f, 0.3f);
// Mowers
VehiclePrefab("Vehicle_Push", "SM_PushMower", VehicleKind.Push, 90f);
VehiclePrefab("Vehicle_Rider", "SM_RiderMower", VehicleKind.Rider, 260f);
VehiclePrefab("Vehicle_Pickup", "SM_Veh_Pickup_01", VehicleKind.Pickup, 900f, PackVehicle);
VehiclePrefab("Vehicle_Tractor", "SM_Veh_Tractor_01", VehicleKind.Tractor, 700f, PackVehicle);
VehiclePrefab("Vehicle_Combine", "SM_Veh_Harvester_01", VehicleKind.Combine, 1400f, PackVehicle);
// stage 17: built from the pack's parts in gc_stage17.py, already at their size and facing forward
VehiclePrefab("Vehicle_Hauler", "SM_HaulTractor", VehicleKind.Hauler, 1100f);
VehiclePrefab("Vehicle_Mulcher", "SM_WideMulcher", VehicleKind.Mulcher, 1000f);
VehiclePrefab("Vehicle_Baler", "SM_BalerTractor", VehicleKind.Baler, 900f);
BuildPiecePrefabs();
// Network prefab list
const string listPath = Prefabs + "NetworkPrefabs.asset";
var list = AssetDatabase.LoadAssetAtPath<NetworkPrefabsList>(listPath);
if (!list) { list = ScriptableObject.CreateInstance<NetworkPrefabsList>(); AssetDatabase.CreateAsset(list, listPath); }
foreach (var p in list.PrefabList.ToList()) list.Remove(p);
foreach (var p in NetPrefabs) if (p.name != "Player") list.Add(new NetworkPrefab { Prefab = p });
EditorUtility.SetDirty(list);
AssetDatabase.SaveAssets();
}
static void CargoPrefab(string name, string modelName, CargoKind kind, float mass, string display, float hold, float scale)
{
Net(name, Layers.Prop, go =>
{
var model = Child(go.transform, modelName, Vector3.zero, Quaternion.identity, PrimitiveType.Cylinder, new Vector3(0.46f, 0.34f, 0.46f), new Vector3(0, 0.34f, 0));
model.localScale *= scale;
var b = LocalBounds(go.transform, model);
// centre the body on its pivot so it tumbles nicely
model.localPosition -= new Vector3(0f, b.center.y, 0f);
b.center = new Vector3(b.center.x, 0f, b.center.z);
var bc = go.AddComponent<BoxCollider>();
bc.center = b.center; bc.size = b.size * 0.98f;
bc.sharedMaterial = kind == CargoKind.Brick ? _slick : _propPhys;
var rb = go.GetComponent<Rigidbody>();
rb.mass = mass; rb.angularDamping = 0.4f;
var g = go.AddComponent<Grabbable>();
g.displayName = display; g.holdDistance = hold;
var c = go.AddComponent<Cargo>();
c.kind = kind;
c.halfHeight = b.extents.y;
});
}
/// <summary>The pack's machines are built for people a head taller than our crew.</summary>
const float PackVehicle = 0.75f;
/// <summary>A place on a machine that its model doesn't name: the ones from the pack only have wheels.</summary>
static Transform Spot(Transform root, Transform found, string name, Vector3 at)
{
if (found) return found;
var t = new GameObject(name).transform;
t.SetParent(root, false);
t.localPosition = at;
return t;
}
static void VehiclePrefab(string name, string modelName, VehicleKind kind, float mass, float scale = 1f)
{
Net(name, Layers.Vehicle, go =>
{
var model = Child(go.transform, modelName, Vector3.zero, Quaternion.identity, PrimitiveType.Cube, new Vector3(1.2f, 0.6f, 3f), new Vector3(0, 0.3f, 0));
model.localScale *= scale;
// the pack's vehicles look down -Z
if (modelName.StartsWith("SM_Veh_")) model.localRotation = Quaternion.AngleAxis(180f, Vector3.up) * model.localRotation;
if (kind == VehicleKind.Tractor && Model("SM_MowerBar"))
{
// no loader on this one: a mower bar instead
foreach (var t in model.GetComponentsInChildren<Transform>(true))
if (t.name.EndsWith("_Arm") || t.name.EndsWith("_Bucket")) t.gameObject.SetActive(false);
Child(go.transform, "SM_MowerBar", new Vector3(0f, 0.55f, 1.9f), Quaternion.identity, PrimitiveType.Cube, new Vector3(2.8f, 0.3f, 0.8f), Vector3.zero);
}
foreach (var r in go.GetComponentsInChildren<Renderer>()) r.shadowCastingMode = ShadowCastingMode.On;
var b = LocalBounds(go.transform, go.transform);
// hull: a box lifted off the wheel contact (the vehicle rides on its spring probes, the hull never drags)
// + a cabin box on the bigger machines
var hull = go.AddComponent<BoxCollider>();
bool small = kind == VehicleKind.Rider || kind == VehicleKind.Push;
float hullH = small ? 0.7f : 1.4f;
const float lift = 0.25f;
hull.center = new Vector3(b.center.x, b.min.y + lift + hullH * 0.5f, b.center.z);
hull.size = new Vector3(b.size.x * 0.92f, hullH, b.size.z * 0.9f);
hull.sharedMaterial = _hullPhys;
if (!small)
Box(go.transform, "Cabin", new Vector3(b.center.x, b.min.y + hullH + (b.size.y - hullH) * 0.4f, b.center.z), new Vector3(b.size.x * 0.6f, (b.size.y - hullH) * 0.8f, b.size.z * 0.45f), _hullPhys);
var rb = go.GetComponent<Rigidbody>();
rb.mass = mass;
rb.linearDamping = 0.2f;
rb.angularDamping = 1.2f;
rb.centerOfMass = new Vector3(0f, b.min.y + 0.25f, 0f);
rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
var v = go.AddComponent<Vehicle>();
v.kind = kind;
// behind the steering wheel, if the model has none of its own
var wheel = model.GetComponentsInChildren<Transform>(true).FirstOrDefault(t => t.name.EndsWith("SteeringW"));
var seatAt = wheel ? go.transform.InverseTransformPoint(wheel.position) + new Vector3(0f, -0.1f, -0.45f) : new Vector3(0f, b.center.y, b.center.z);
v.seat = Spot(go.transform, FindIn(model, "Seat"), "Seat", seatAt);
bool ownIntake = FindIn(go.transform, "Intake");
v.intake = Spot(go.transform, FindIn(go.transform, "Intake"), "Intake", new Vector3(0f, b.min.y + 0.2f, b.max.z - 0.3f));
v.wake = Spot(go.transform, FindIn(model, "Wake"), "Wake", new Vector3(0f, b.min.y + 0.2f, b.min.z));
v.bars = FindIn(model, "Bars");
v.arm = FindIn(model, "Arm");
v.fill = FindIn(model, "Fill");
v.fanL = FindIn(model, "Fan_L");
v.fanR = FindIn(model, "Fan_R");
v.reel = FindIn(go.transform, "Reel") ?? model.GetComponentsInChildren<Transform>(true).FirstOrDefault(t => t.name.EndsWith("_Reel"));
v.wheels = model.GetComponentsInChildren<Transform>(true).Where(t => t.name.Contains("Wheel_")).ToArray();
v.chute = FindIn(model, "Chute");
v.hitch = FindIn(model, "Hitch");
v.shell = model;
// the strip is cut where the cutter is, as wide as it is: a mower bar, a header's reel, a deck's blades,
// a mulcher's wings (which also fold to get through a shed door)
var cutter = FindIn(go.transform, "SM_MowerBar") ?? v.reel;
var wings = FindIn(model, "Booms");
if (cutter && kind != VehicleKind.Pickup)
{
var cb = LocalBounds(go.transform, cutter);
if (wings) cb.Encapsulate(LocalBounds(go.transform, wings));
if (!ownIntake) v.intake.localPosition = new Vector3(cb.center.x, b.min.y + 0.2f, cb.center.z);
v.barWidth = cb.size.x;
}
if (wings) v.fold = v.reel ? new[] { wings, v.reel } : new[] { wings };
v.length = b.size.z;
v.width = b.size.x * 0.5f;
});
}
// ───────────────────────── build pieces ─────────────────────────
const float BeltTop = 0.35f;
/// <summary>A solid box around the model's footprint (minus a margin) so pieces can be aimed at and walked against.</summary>
static BoxCollider Solid(Transform root, Transform model, float shrink = 0.08f, float frontCut = 0f)
{
var b = LocalBounds(root, model);
var bc = Box(root, "Solid", new Vector3(b.center.x, b.center.y, b.center.z - frontCut * 0.5f),
new Vector3(Mathf.Max(0.1f, b.size.x - shrink * 2f), b.size.y, Mathf.Max(0.1f, b.size.z - shrink * 2f - frontCut)), null);
return bc;
}
static void BuildPiecePrefabs()
{
foreach (var def in GameDefs.Pieces)
{
var d = def;
Net(d.prefab, Layers.Build, go =>
{
go.AddComponent<BuildPiece>().piece = d.id;
if (d.id == PieceId.Belt)
{
// stretched to the run when it's laid
BeltBody(go.transform, 1f, 1f);
Drive<BeltRun>(go.transform, null);
return;
}
if (GameDefs.IsDeck(d.id))
{
go.AddComponent<Foundation>();
return;
}
if (GameDefs.IsPanel(d.id))
{
go.AddComponent<SolarPanel>();
return;
}
var model = Child(go.transform, d.model, Vector3.zero, Quaternion.identity, PrimitiveType.Cube,
new Vector3(d.sizeX, 1f, d.sizeZ), new Vector3(0, 0.5f, 0));
model.localScale *= d.scale;
foreach (var r in model.GetComponentsInChildren<Renderer>()) r.shadowCastingMode = ShadowCastingMode.On;
foreach (var t in model.GetComponentsInChildren<Transform>(true))
if (t.name == "EndIn" || t.name == "EndOut") t.gameObject.SetActive(false);
switch (d.id)
{
case PieceId.Depot:
// only the rim is solid: bundles have to land in the mouth, however tall the building is
var solid = Solid(go.transform, model);
solid.transform.localPosition = new Vector3(solid.transform.localPosition.x, 0.6f, solid.transform.localPosition.z);
solid.size = new Vector3(solid.size.x, 1.2f, solid.size.z);
go.AddComponent<Depot>().mouth = FindIn(model, "Mouth");
break;
case PieceId.Intake:
{
// the model's origin is the middle of its back face, which goes against the deck: the footprint is 1.5 m deep
model.localPosition += new Vector3(0f, 0f, -0.75f);
var body = Box(go.transform, "Solid", new Vector3(0f, 0.45f, 0f), new Vector3(2.6f, 0.9f, 1.5f), null);
var mouthT = new GameObject("Mouth").transform;
mouthT.SetParent(go.transform, false);
mouthT.localPosition = new Vector3(0f, 1.0f, 0f);
var dep = go.AddComponent<Depot>();
dep.mouth = mouthT;
dep.halfX = 1.3f; dep.halfZ = 0.75f;
dep.backToDeck = true;
break;
}
case PieceId.Garage:
go.AddComponent<Garage>();
ShedParts(go, model, d.scale);
break;
case PieceId.UnloadBay:
{
// the model runs 7 m from the grate's front lip to the hatches: centre it on the footprint
model.localPosition += new Vector3(0f, 0f, -0.5f);
// the grate is a low step a mower rolls over, the bin behind it is solid
Box(go.transform, "Grate", new Vector3(0f, 0.06f, 1.5f), new Vector3(4.2f, 0.12f, 4f), null);
Box(go.transform, "Solid", new Vector3(0f, 1.2f, -2f), new Vector3(3.4f, 2.4f, 3f), null);
go.AddComponent<UnloadBay>();
break;
}
case PieceId.Binder:
Solid(go.transform, model);
go.AddComponent<Binder>();
break;
case PieceId.Catcher:
Solid(go.transform, model);
go.AddComponent<Catcher>();
break;
case PieceId.DronePad:
{
// the pad is low: a box over the planks only, so the drones aren't in it
Solid(go.transform, model);
var drone = Child(go.transform, "SM_Drone", new Vector3(0.75f, 0.68f, 0.75f), Quaternion.identity, PrimitiveType.Cube, new Vector3(0.7f, 0.3f, 0.7f), Vector3.zero);
drone.localScale *= 1.4f;
foreach (var r in drone.GetComponentsInChildren<Renderer>()) r.shadowCastingMode = ShadowCastingMode.On;
go.AddComponent<DronePad>().drone = drone;
break;
}
case PieceId.Reaper:
Solid(go.transform, model);
var reaper = go.AddComponent<Reaper>();
reaper.muzzle = FindIn(model, "Muzzle");
reaper.reel = FindIn(model, "Reel");
break;
case PieceId.RobotI:
case PieceId.RobotII:
Solid(go.transform, model);
var bot = Child(go.transform, "SM_RobotMower", Vector3.zero, Quaternion.identity, PrimitiveType.Cube, new Vector3(0.9f, 0.4f, 1.2f), new Vector3(0, 0.2f, 0));
if (d.id == PieceId.RobotII) bot.localScale *= GameDefs.Robot(d.id).width / GameDefs.Robot(PieceId.RobotI).width;
go.AddComponent<RobotDock>().bot = bot;
break;
case PieceId.Dryer:
case PieceId.Press:
var plinth = Solid(go.transform, model);
// the windmill's sails swing far outside its plinth
if (d.id == PieceId.Dryer)
{
plinth.transform.localPosition = new Vector3(0f, 1.6f, 0f);
plinth.size = new Vector3(d.sizeX - 0.2f, 3.2f, d.sizeZ - 0.2f);
}
var machine = go.AddComponent<Machine>();
machine.lamp = Part<Renderer>(model, "Lamp");
machine.spin = FindIn(model, "Spin");
break;
case PieceId.Pole:
Box(go.transform, "Solid", new Vector3(0f, 1.8f, 0f), new Vector3(0.5f, 3.6f, 0.5f), null);
go.AddComponent<PowerPole>();
break;
case PieceId.BatteryS:
case PieceId.BatteryL:
Solid(go.transform, model);
var battery = go.AddComponent<PowerBattery>();
battery.gauge = FindIn(model, "Gauge");
battery.lamp = Part<Renderer>(model, "Lamp");
break;
case PieceId.Splitter:
{
Box(go.transform, "BeltBase", new Vector3(0, BeltTop * 0.5f, 0), new Vector3(1f, BeltTop, 1f), _beltPhys);
Drive<BeltSplitter>(go.transform, model).paddle = FindIn(model, "Paddle");
go.AddComponent<Junction>().sign = Part<Renderer>(model, "Sign");
break;
}
case PieceId.Merger:
{
Box(go.transform, "BeltBase", new Vector3(0, BeltTop * 0.5f, 0), new Vector3(1f, BeltTop, 1f), _beltPhys);
Drive<BeltMerger>(go.transform, model);
go.AddComponent<Junction>().sign = Part<Renderer>(model, "Sign");
break;
}
// structures: what you walk against and on
case PieceId.Wall:
case PieceId.WindowWall:
Box(go.transform, "Solid", new Vector3(0f, 1.5f, 0f), new Vector3(3f, 3f, 0.2f), null);
break;
case PieceId.DoorWall:
Box(go.transform, "SolidL", new Vector3(-1.05f, 1.5f, 0f), new Vector3(0.9f, 3f, 0.2f), null);
Box(go.transform, "SolidR", new Vector3(1.05f, 1.5f, 0f), new Vector3(0.9f, 3f, 0.2f), null);
Box(go.transform, "Lintel", new Vector3(0f, 2.65f, 0f), new Vector3(1.2f, 0.7f, 0.2f), null);
break;
case PieceId.Railing:
Box(go.transform, "Solid", new Vector3(0f, 0.55f, 0f), new Vector3(3f, 1.1f, 0.12f), null);
break;
case PieceId.Fence:
Box(go.transform, "Solid", new Vector3(0f, 0.45f, 0f), new Vector3(3f, 0.9f, 0.1f), null);
break;
case PieceId.Roof:
{
// one slope from the eave at the front (+Z) to the ridge 1.5 m up at the back
var slope = Box(go.transform, "Slope", new Vector3(0f, 0.75f, 0f), new Vector3(3.2f, 0.16f, 3.4f), null);
slope.transform.localRotation = Quaternion.Euler(Mathf.Atan2(1.5f, 3f) * Mathf.Rad2Deg, 0f, 0f);
break;
}
case PieceId.Stairs:
// twelve treads, 0.25 m up and 0.25 m on each, climbing toward +Z from the foot at z = -1.5
for (int i = 0; i < 12; i++)
Box(go.transform, "Tread" + i, new Vector3(0f, (i + 1) * 0.125f, -1.5f + (i + 0.5f) * 0.25f), new Vector3(1.2f, (i + 1) * 0.25f, 0.25f), null);
Box(go.transform, "Landing", new Vector3(0f, 2.9f, 1.55f), new Vector3(1.2f, 0.2f, 0.1f), null);
break;
case PieceId.Steps:
for (int i = 0; i < 6; i++)
Box(go.transform, "Step" + i, new Vector3(0f, (i + 1) * 0.125f, -1.2f + (i + 0.5f) * 0.4f), new Vector3(2f, (i + 1) * 0.25f, 0.4f), null);
break;
case PieceId.Pillar:
Box(go.transform, "Solid", new Vector3(0f, 1.5f, 0f), new Vector3(0.32f, 3f, 0.32f), null);
break;
case PieceId.Lamppost:
Box(go.transform, "Solid", new Vector3(0f, 1.3f, 0f), new Vector3(0.3f, 2.6f, 0.3f), null);
go.AddComponent<Lamppost>().glow = Part<Renderer>(model, "Glow");
break;
case PieceId.Flagpole:
Box(go.transform, "Solid", new Vector3(0f, 2f, 0f), new Vector3(0.25f, 4f, 0.25f), null);
break;
case PieceId.Planter:
case PieceId.Bench:
case PieceId.Crates:
Solid(go.transform, model);
break;
}
}, rigidbody: false, transformSync: false);
}
}
static void BeltBody(Transform root, float w, float len)
{
Box(root, "BeltBase", new Vector3(0, BeltTop * 0.5f, 0), new Vector3(w, BeltTop, len), _beltPhys);
Box(root, "RailL", new Vector3(-w * 0.5f + 0.03f, BeltTop + 0.1f, 0), new Vector3(0.06f, 0.2f, len), null);
Box(root, "RailR", new Vector3(w * 0.5f - 0.03f, BeltTop + 0.1f, 0), new Vector3(0.06f, 0.2f, len), null);
}
static T Part<T>(Transform root, string name) where T : Component
{
var t = FindIn(root, name);
return t ? t.GetComponent<T>() : null;
}
/// <summary>
/// The pack garage as a shed machines drive out of: its own door swapped for ours (hinged on its top edge so it can
/// tilt up), the outlet hatches on the back wall the bundles come out of, and the spots inside and on the pad.
/// The door bay is at +X once the pack model is turned round; out is +Z.
/// </summary>
public static VehicleShed ShedParts(GameObject go, Transform model, float scale, bool outlet = true)
{
// the pack's garage has its bays on -Z: turned round, they face the pad, where our door and outlet expect them
model.localRotation = Quaternion.AngleAxis(180f, Vector3.up) * model.localRotation;
var packDoor = FindIn(model, "SM_Bld_Garage_01_Door");
var door = Model("SM_GarageDoor") ? Child(model.parent, "SM_GarageDoor", model.localPosition, Quaternion.identity, PrimitiveType.Cube, Vector3.one, Vector3.zero) : null;
if (door)
{
door.localScale *= scale;
if (packDoor) packDoor.gameObject.SetActive(false);
}
// the outlet was modelled on the back wall of the garage at 0.65: move it back onto this one's wall
// the outer ridges of the corrugated wall stand 0.08 m proud of its valleys (more at this scale): the box sits clear
// of them, or from inside the shed its hatches show through the wall's grooves
float wall = 3.18f * scale + 0.12f;
if (outlet && Model("SM_GarageOutlet")) Child(model.parent, "SM_GarageOutlet", model.localPosition + new Vector3(0f, 0f, -(wall - 2.067f)), Quaternion.identity, PrimitiveType.Cube, Vector3.one, Vector3.zero);
ShedWalls(go.transform, scale);
var shed = go.AddComponent<VehicleShed>();
shed.door = door ? FindIn(door, "Door") : packDoor;
float bay = 4.503f * scale;
shed.halfWide = 6.9f * scale;
shed.backWall = -wall + 0.3f;
shed.doorLine = 3.19f * scale;
shed.eaves = 2.75f * scale;
shed.inside = new Vector3(bay, 0f, -0.4f);
shed.outside = new Vector3(bay, 0f, shed.doorLine + 6f);
return shed;
}
/// <summary>
/// The pack garage as walls you can walk in between: back, sides, roof, and a front with its three bays open
/// (the pack's bays are 3.1 m wide and 2.86 m high at scale 1, with posts between them).
/// </summary>
static void ShedWalls(Transform root, float s)
{
float w = 6.944f * s, d = 3.19f * s, h = 2.864f * s, top = 3.3f * s, t = 0.25f;
Box(root, "WallBack", new Vector3(0f, top * 0.5f, -d + t * 0.5f), new Vector3(2f * w, top, t), null);
Box(root, "WallL", new Vector3(-w + t * 0.5f, top * 0.5f, 0f), new Vector3(t, top, 2f * d), null);
Box(root, "WallR", new Vector3(w - t * 0.5f, top * 0.5f, 0f), new Vector3(t, top, 2f * d), null);
Box(root, "Lintel", new Vector3(0f, (h + top) * 0.5f, d - t * 0.5f), new Vector3(2f * w, top - h, t), null);
Box(root, "Roof", new Vector3(0f, top + 0.15f, 0f), new Vector3(2f * w, 0.3f, 2f * d), null);
// posts between the bays: from the outer corners to 6.06, and between 2.94 and 1.56 either side
foreach (var (a, b) in new[] { (6.064f, 6.944f), (1.56f, 2.942f) })
{
float cx = (a + b) * 0.5f * s, wx = (b - a) * s;
Box(root, "Post", new Vector3(cx, h * 0.5f, d - t * 0.5f), new Vector3(wx, h, t), null);
Box(root, "Post", new Vector3(-cx, h * 0.5f, d - t * 0.5f), new Vector3(wx, h, t), null);
}
}
static Transform FindIn(Transform root, string name)
{
foreach (var t in root.GetComponentsInChildren<Transform>(true)) if (t.name == name) return t;
return null;
}
static T Drive<T>(Transform root, Transform model) where T : Conveyor
{
var go = new GameObject("Drive");
go.transform.SetParent(root, false);
var bc = go.AddComponent<BoxCollider>();
bc.isTrigger = true;
bc.center = new Vector3(0, BeltTop + 0.25f, 0);
bc.size = new Vector3(0.92f, 0.5f, 1f);
var conv = go.AddComponent<T>();
conv.usePerkSpeed = true;
var belts = new List<Renderer>();
if (model) foreach (var r in model.GetComponentsInChildren<Renderer>()) if (r.name == "Belt") belts.Add(r);
conv.belts = belts.ToArray();
return conv;
}
static BoxCollider Box(Transform parent, string name, Vector3 center, Vector3 size, PhysicsMaterial mat, float yaw = 0f)
{
var go = new GameObject(name);
go.transform.SetParent(parent, false);
go.transform.localPosition = center;
go.transform.localRotation = Quaternion.Euler(0, yaw, 0);
var bc = go.AddComponent<BoxCollider>();
bc.size = size;
if (mat) bc.sharedMaterial = mat;
return bc;
}
// ───────────────────────── helpers ─────────────────────────
static PhysicsMaterial PhysMat(string name, float stat, float dyn, float bounce)
{
var path = Prefabs + name + ".physicMaterial";
var m = AssetDatabase.LoadAssetAtPath<PhysicsMaterial>(path);
if (!m) { m = new PhysicsMaterial(name); AssetDatabase.CreateAsset(m, path); }
m.staticFriction = stat; m.dynamicFriction = dyn; m.bounciness = bounce;
m.frictionCombine = PhysicsMaterialCombine.Average;
EditorUtility.SetDirty(m);
return m;
}
static void NoScale(NetworkTransform nt)
{
nt.SyncScaleX = false; nt.SyncScaleY = false; nt.SyncScaleZ = false;
}
static GameObject Net(string name, int layer, Action<GameObject> build, bool rigidbody = true, bool transformSync = true)
{
var go = new GameObject(name);
go.layer = layer;
var no = go.AddComponent<NetworkObject>();
no.DontDestroyWithOwner = true;
if (rigidbody)
{
var rb = go.AddComponent<Rigidbody>();
rb.interpolation = RigidbodyInterpolation.Interpolate;
rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
var nt = go.AddComponent<NetworkTransform>();
nt.AuthorityMode = NetworkTransform.AuthorityModes.Owner;
nt.UseQuaternionSynchronization = true;
NoScale(nt);
go.AddComponent<NetworkRigidbody>();
}
else if (transformSync && name != "Player")
{
var nt = go.AddComponent<NetworkTransform>();
NoScale(nt);
}
build(go);
foreach (var t in go.GetComponentsInChildren<Transform>(true)) t.gameObject.layer = layer;
var path = Prefabs + name + ".prefab";
var prefab = PrefabUtility.SaveAsPrefabAsset(go, path);
UnityEngine.Object.DestroyImmediate(go);
NetPrefabs.Add(prefab);
return prefab;
}
/// <summary>Instantiates a model (or a fallback primitive) as a child. Returns the child transform.</summary>
static Transform Child(Transform parent, string model, Vector3 pos, Quaternion rot, PrimitiveType fallback, Vector3 fbScale, Vector3 fbOffset, Quaternion? fbRot = null)
{
var m = Model(model);
GameObject go;
if (m)
{
go = (GameObject)PrefabUtility.InstantiatePrefab(m);
go.transform.SetParent(parent, false);
go.transform.localPosition = pos;
go.transform.localRotation = rot * m.transform.localRotation;
}
else
{
Debug.LogWarning($"[Builder] Missing model {model}, using a primitive");
go = GameObject.CreatePrimitive(fallback);
UnityEngine.Object.DestroyImmediate(go.GetComponent<Collider>());
go.name = model;
go.transform.SetParent(parent, false);
go.transform.localPosition = pos + fbOffset;
go.transform.localRotation = (fbRot ?? Quaternion.identity) * rot;
go.transform.localScale = fbScale;
}
return go.transform;
}
static Bounds LocalBounds(Transform root, Transform model)
{
var rs = model.GetComponentsInChildren<Renderer>();
if (rs.Length == 0) return new Bounds(Vector3.up, Vector3.one);
var b = new Bounds(root.InverseTransformPoint(rs[0].bounds.center), Vector3.zero);
foreach (var r in rs)
{
var wb = r.bounds;
for (int i = 0; i < 8; i++)
{
var c = wb.center + Vector3.Scale(wb.extents, new Vector3((i & 1) == 0 ? -1 : 1, (i & 2) == 0 ? -1 : 1, (i & 4) == 0 ? -1 : 1));
b.Encapsulate(root.InverseTransformPoint(c));
}
}
return b;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 17eb96ccd9d19bf4b9d68cc11bff12ba

View File

@ -0,0 +1,461 @@
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.UIElements;
namespace GrassCutter.EditorTools
{
/// <summary>
/// The Herbaria-7 scene: sky with the ringed gas giant, the endless overgrown meadow (grass + wild hemp), the hills
/// beyond, the deck on its stilts, the static base furniture (supply wall, upgrade console, crew cabin, loading ramp and
/// the unloading yard) and the systems (cameras, networking, spawner, UI).
/// The deck tiles and everything built on them are spawned at runtime.
/// </summary>
public static partial class ProjectBuilder
{
static Transform _env;
static Transform _dockZone;
static void BuildScene()
{
System.IO.Directory.CreateDirectory("Assets/Scenes");
var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
Lighting();
_env = new GameObject("Environment").transform;
World();
RigFurniture();
Systems();
EditorSceneManager.SaveScene(scene, ScenePath);
Debug.Log("[Builder] Scene saved");
}
// ───────────────────────── lighting ─────────────────────────
static readonly Vector3 SunDir = new Vector3(0.3f, 0.55f, -0.6f).normalized; // towards the sun
static readonly Color Horizon = new Color(0.8f, 0.9f, 0.86f);
static void Lighting()
{
RenderSettings.ambientMode = AmbientMode.Trilight;
RenderSettings.ambientSkyColor = new Color(0.66f, 0.8f, 0.98f) * 1.1f;
RenderSettings.ambientEquatorColor = new Color(0.78f, 0.88f, 0.74f);
RenderSettings.ambientGroundColor = new Color(0.3f, 0.45f, 0.2f);
var sky = Mat("M_Sky");
if (sky)
{
sky.SetVector("_SunDir", SunDir);
sky.SetColor("_HorizonColor", Horizon);
EditorUtility.SetDirty(sky);
RenderSettings.skybox = sky;
}
RenderSettings.defaultReflectionMode = DefaultReflectionMode.Skybox;
RenderSettings.reflectionIntensity = 1f;
RenderSettings.fog = true;
RenderSettings.fogMode = FogMode.Linear;
RenderSettings.fogColor = Horizon;
RenderSettings.fogStartDistance = 30f;
RenderSettings.fogEndDistance = 1500f;
var sun = new GameObject("Sun");
var l = sun.AddComponent<Light>();
l.type = LightType.Directional;
l.color = new Color(1f, 0.95f, 0.86f);
l.intensity = 1.55f;
l.shadows = LightShadows.Soft;
l.shadowStrength = 0.75f;
sun.transform.rotation = Quaternion.LookRotation(-SunDir);
RenderSettings.sun = l;
var vol = new GameObject("PostFX").AddComponent<Volume>();
vol.isGlobal = true;
vol.priority = 1;
const string profPath = "Assets/Settings/MeadowPost.asset";
if (AssetDatabase.LoadAssetAtPath<VolumeProfile>(profPath)) AssetDatabase.DeleteAsset(profPath);
var prof = ScriptableObject.CreateInstance<VolumeProfile>();
AssetDatabase.CreateAsset(prof, profPath);
var bloom = prof.Add<Bloom>(true);
bloom.intensity.Override(0.7f); bloom.threshold.Override(0.95f); bloom.scatter.Override(0.7f);
var tm = prof.Add<Tonemapping>(true);
tm.mode.Override(TonemappingMode.Neutral);
var ca = prof.Add<ColorAdjustments>(true);
ca.postExposure.Override(0.15f); ca.contrast.Override(16f); ca.saturation.Override(12f);
var vig = prof.Add<Vignette>(true);
vig.intensity.Override(0.22f); vig.smoothness.Override(0.5f);
var wb = prof.Add<WhiteBalance>(true);
wb.temperature.Override(3f);
foreach (var c in prof.components) AssetDatabase.AddObjectToAsset(c, prof);
EditorUtility.SetDirty(prof);
AssetDatabase.SaveAssets();
vol.sharedProfile = prof;
}
// ───────────────────────── scene helpers ─────────────────────────
static GameObject Place(string model, Vector3 pos, float yaw, Transform parent = null, bool isStatic = true)
{
var m = Model(model);
if (!m) { Debug.LogWarning("[Builder] missing " + model); return null; }
// wrapper carries placement (so its forward is the model's front); the model keeps its imported rotation
var go = new GameObject(model);
go.transform.SetParent(parent ? parent : _env, false);
go.transform.position = pos;
go.transform.rotation = Quaternion.Euler(0, yaw, 0);
var inst = (GameObject)PrefabUtility.InstantiatePrefab(m);
inst.transform.SetParent(go.transform, false);
if (isStatic) foreach (var t in go.GetComponentsInChildren<Transform>()) t.gameObject.isStatic = true;
return go;
}
static Transform FindT(GameObject root, string child)
{
foreach (var t in root.GetComponentsInChildren<Transform>(true)) if (t.name == child) return t;
return null;
}
static void Blocker(GameObject go, Vector3 center, Vector2 size)
{
var b = go.AddComponent<GridBlocker>();
b.center = center;
b.size = size;
}
static BoxCollider SolidAt(string name, Vector3 center, Vector3 size, Transform parent, float yaw = 0f, float pitch = 0f)
{
var go = new GameObject(name);
go.transform.SetParent(parent, false);
go.transform.localPosition = center;
go.transform.localRotation = Quaternion.Euler(pitch, yaw, 0);
var bc = go.AddComponent<BoxCollider>();
bc.size = size;
go.isStatic = true;
return bc;
}
// ───────────────────────── the world ─────────────────────────
static void World()
{
new GameObject("Meadow").AddComponent<Meadow>();
var field = new GameObject("GrassField").AddComponent<GrassField>();
field.furMat = Mat("M_GrassFur");
field.strandMat = Mat("M_GrassStrand");
field.hempMat = Mat("M_Hemp");
field.hempMesh = BakedMesh("SM_Hemp");
field.flowerMat = Mat("M_Flowers");
field.flowerMesh = BakedPlant("SM_Wildflower");
// wheat and oats share their plant: baking one again would throw away the first
var ear = BakedPlant("SM_Prop_Plant_Wheat_Optimised_02");
var earFar = BakedPlant("SM_Prop_Plant_Wheat_Optimised_01");
field.crops = new[]
{
new GrassField.CropLook(),
new GrassField.CropLook { mat = Mat("M_CropWheat"), near = ear, far = earFar },
new GrassField.CropLook { mat = Mat("M_CropOats"), near = ear, far = earFar },
new GrassField.CropLook { mat = Mat("M_CropCorn"), near = BakedPlant("SM_Prop_Plant_Corn_01_M"), far = BakedPlant("SM_Crop_Corn_Far") },
new GrassField.CropLook { mat = Mat("M_CropSunflower"), near = BakedPlant("SM_Prop_Sunflower_02"), far = BakedPlant("SM_Crop_Sunflower_Far") },
};
var ground = new GameObject("Ground").AddComponent<Ground>();
ground.soil = Mat("M_Soil");
ground.spires = new[] { Model("SM_Spire_A"), Model("SM_Spire_B"), Model("SM_Spire_C") };
ground.trees = new[] { Model("SM_Generic_Tree_01"), Model("SM_Generic_Tree_02"), Model("SM_Generic_Tree_03") };
ground.bush = Model("SM_Prop_Plant_Bush_03_L");
var deck = new GameObject("Deck").AddComponent<DeckManager>();
deck.tileModel = Model("SM_DeckTile");
deck.ladderModel = Model("SM_Ladder");
deck.gaps = new[] { new Vector3(0f, 0f, -9f) }; // the ramp opening in the south railing
}
/// <summary>Company furniture that every base has: the supply wall, the console, the crew cabin, the ramp and the yard. A garage has to be bought.</summary>
static void RigFurniture()
{
var rig = new GameObject("Rig").transform;
// the supply wall: tools on a pegboard along the west railing
SupplyWallPiece(rig);
ConsolePiece(rig, new Vector3(6.2f, 0f, -1.5f));
TravelPiece(rig, new Vector3(6.2f, 0f, 2.2f));
// the two treat machines against the north railing, facing the middle of the deck
VendPiece(rig, "SM_VendBeer", TreatId.Beer, new Vector3(3.9f, 0f, 8.2f));
VendPiece(rig, "SM_VendSmoke", TreatId.Cigar, new Vector3(5.9f, 0f, 8.35f));
// crew cabin on the north-west tile
var cabin = Place("SM_CrewCabin", new Vector3(-6f, 0f, 7f), 180f, rig);
if (cabin)
{
SolidAt("CabinBox", new Vector3(0f, 1.6f, 0f), new Vector3(5.8f, 3.2f, 3.8f), cabin.transform);
Blocker(cabin, Vector3.zero, new Vector2(5.8f, 3.8f));
}
// loading ramp off the south edge, down to the meadow (1.2 m over 6 m)
float slope = Mathf.Asin(0.2f) * Mathf.Rad2Deg;
var dock = Place("SM_Dock", new Vector3(0f, 0f, -9f), 180f, rig);
if (dock)
{
SolidAt("RampDeck", new Vector3(0f, -0.66f, 3.0f), new Vector3(3f, 0.12f, 6.2f), dock.transform, 0f, slope);
SolidAt("RampCurbL", new Vector3(-1.44f, -0.5f, 3.0f), new Vector3(0.12f, 0.3f, 6.2f), dock.transform, 0f, slope);
SolidAt("RampCurbR", new Vector3(1.44f, -0.5f, 3.0f), new Vector3(0.12f, 0.3f, 6.2f), dock.transform, 0f, slope);
var gb = dock.AddComponent<GrassBlocker>();
gb.center = new Vector3(0f, 0f, 3.2f); gb.halfSize = new Vector2(1.7f, 3.4f);
}
// the unloading yard: packed earth at the foot of the ramp where machines tip what they've cut, bays marked with logs
var pad = new GameObject("UnloadYard");
pad.transform.SetParent(rig, false);
pad.transform.position = new Vector3(0f, GameDefs.WaterY, -20f);
var padBlock = pad.AddComponent<GrassBlocker>();
padBlock.halfSize = new Vector2(9f, 8f);
var slab = GameObject.CreatePrimitive(PrimitiveType.Cube);
slab.name = "PadSlab";
slab.transform.SetParent(pad.transform, false);
slab.transform.localPosition = new Vector3(0f, -0.04f, 0f);
slab.transform.localScale = new Vector3(18f, 0.1f, 16f);
slab.GetComponent<Renderer>().sharedMaterial = Mat("M_Yard");
slab.isStatic = true;
for (int i = -2; i <= 2; i++)
{
if (i == 0) continue;
var line = GameObject.CreatePrimitive(PrimitiveType.Cube);
line.name = "BayLine";
Object.DestroyImmediate(line.GetComponent<Collider>());
line.transform.SetParent(pad.transform, false);
line.transform.localPosition = new Vector3(i * 2.6f, 0.05f, -1.0f);
line.transform.localScale = new Vector3(0.22f, 0.14f, 8f);
line.GetComponent<Renderer>().sharedMaterial = Mat("M_Timber");
line.isStatic = true;
}
// no shed at the base: bought and called machines park on the yard by the dock (garages players build keep theirs)
var zone = new GameObject("DockZone").transform;
zone.SetParent(rig, false);
zone.position = new Vector3(0f, GameDefs.WaterY, -19f);
zone.rotation = Quaternion.Euler(0f, 180f, 0f);
_dockZone = zone;
// a few props from the company crate
Prop(rig, "SM_Decor_Lamp", new Vector3(-2.5f, 0f, -8.5f), 0f, 0.4f, 2.4f, true);
Prop(rig, "SM_Decor_Lamp", new Vector3(2.5f, 0f, -8.5f), 0f, 0.4f, 2.4f, true);
Prop(rig, "SM_Prop_Crate_01", new Vector3(-8.2f, 0f, -8.2f), 20f, 1f, 1f, false, 0.75f);
Prop(rig, "SM_Prop_Barrel_01", new Vector3(8.5f, 0f, 2.5f), 90f, 0.6f, 0.9f, false, 0.75f);
Prop(rig, "SM_Prop_Hay_Bale_Square_01", new Vector3(7.8f, 0f, -7.6f), 70f, 1.2f, 0.7f, false, 0.75f);
Prop(rig, "SM_Prop_Wheelbarrow_01", new Vector3(4.6f, 0f, -7.9f), 200f, 1f, 0.7f, false, 0.75f);
// where the crew spawns: south of the depot, looking north over the deck
var sp = new GameObject("SpawnPoints").transform;
for (int i = 0; i < NetSession.MaxPlayers; i++)
{
var p = new GameObject("Spawn" + i).transform;
p.SetParent(sp, false);
p.position = new Vector3(-6f + (i % 8) * 1.4f, 0.15f, -5f - (i / 8) * 1.4f);
p.rotation = Quaternion.Euler(0f, 0f, 0f);
}
}
/// <summary>GreenHaul console (the upgrade matrix).</summary>
static void ConsolePiece(Transform rig, Vector3 pos)
{
var term = Place("SM_Terminal", pos, -90f, rig, false);
if (!term) return;
SolidAt("TermBox", new Vector3(0f, 0.9f, 0f), new Vector3(1.2f, 1.8f, 0.9f), term.transform);
var st = term.AddComponent<ShopTerminal>();
var scr = FindT(term, "Screen");
st.screen = scr ? scr.GetComponent<Renderer>() : null;
foreach (var t in term.GetComponentsInChildren<Transform>()) t.gameObject.layer = Layers.Build;
Blocker(term, Vector3.zero, new Vector2(1.6f, 1.2f));
}
/// <summary>A vending machine that trades a kilo of grass for a treat: its moving parts found by name and handed to the script.</summary>
static void VendPiece(Transform rig, string model, TreatId kind, Vector3 pos)
{
var go = Place(model, pos, 180f, rig, false);
if (!go) return;
bool beer = kind == TreatId.Beer;
SolidAt("VendBox", new Vector3(0f, beer ? 1.07f : 0.95f, 0f), beer ? new Vector3(1.05f, 2.14f, 0.85f) : new Vector3(1.1f, 1.9f, 0.62f), go.transform);
var vm = go.AddComponent<VendingMachine>();
vm.kind = kind;
var sign = FindT(go, "Sign");
vm.sign = sign ? sign.GetComponent<Renderer>() : null;
var display = FindT(go, "Display");
vm.display = display ? display.GetComponent<Renderer>() : null;
// the whole model shudders while it works
vm.body = go.transform.childCount > 0 ? go.transform.GetChild(0) : null;
vm.button = FindT(go, "Button");
vm.tray = FindT(go, "Tray");
vm.drawer = FindT(go, "Drawer");
vm.hopper = FindT(go, "Hopper");
vm.dropPoint = FindT(go, "DropPoint");
var knobs = new System.Collections.Generic.List<Transform>();
for (int i = 0; i < 4; i++) { var k = FindT(go, "Knob" + i); if (k) knobs.Add(k); }
vm.knobs = knobs.ToArray();
foreach (var t in go.GetComponentsInChildren<Transform>()) t.gameObject.layer = Layers.Build;
Blocker(go, Vector3.zero, new Vector2(1.5f, 1.3f));
}
static void TravelPiece(Transform rig, Vector3 pos)
{
var dish = Place("SM_Decor_Dish", pos, -90f, rig, false);
if (!dish) return;
SolidAt("TravelBox", new Vector3(0f, 1f, 0f), new Vector3(1.2f, 2f, 1.2f), dish.transform);
dish.AddComponent<StationTerminal>();
foreach (var t in dish.GetComponentsInChildren<Transform>()) t.gameObject.layer = Layers.Build;
Blocker(dish, Vector3.zero, new Vector2(1.6f, 1.6f));
}
/// <summary>What stands around the depot of a far station: put together at the origin, then kept as a prefab.</summary>
static GameObject StationRig()
{
var rig = new GameObject("Station_Rig");
var yard = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
yard.name = "Yard";
Object.DestroyImmediate(yard.GetComponent<Collider>());
yard.transform.SetParent(rig.transform, false);
yard.transform.localPosition = Vector3.up * 0.02f;
yard.transform.localScale = new Vector3(22f, 0.04f, 22f);
yard.GetComponent<Renderer>().sharedMaterial = Mat("M_Yard");
SupplyWallPiece(rig.transform);
ConsolePiece(rig.transform, new Vector3(6.2f, 0f, -1.5f));
TravelPiece(rig.transform, new Vector3(6.2f, 0f, 2.2f));
VendPiece(rig.transform, "SM_VendBeer", TreatId.Beer, new Vector3(-2.2f, 0f, 7.6f));
VendPiece(rig.transform, "SM_VendSmoke", TreatId.Cigar, new Vector3(-0.2f, 0f, 7.7f));
var prefab = PrefabUtility.SaveAsPrefabAsset(rig, Prefabs + "Station_Rig.prefab");
Object.DestroyImmediate(rig);
return prefab;
}
static void SupplyWallPiece(Transform rig)
{
var wall = new GameObject("SupplyWall");
wall.transform.SetParent(rig, false);
wall.transform.position = new Vector3(-8.5f, 0f, -1.5f);
wall.transform.rotation = Quaternion.Euler(0f, 90f, 0f); // faces the middle of the deck
var body = Place("SM_SupplyWall", wall.transform.position, 0f, wall.transform, false);
if (body) body.transform.localRotation = Quaternion.identity;
SolidAt("WallBox", new Vector3(0f, 1.3f, 0f), new Vector3(4.54f, 2.6f, 0.34f), wall.transform);
// the tools hang with their blades up, the cheapest on the left as you face the wall
float[] sizes = { 0.5f, 0.8f, 0.24f, 0.46f, 0.52f, 0.6f, 0.7f };
for (int i = 0; i < GameDefs.Tools.Length && i < sizes.Length; i++)
{
var hung = Place(GameDefs.Tools[i].model, wall.transform.TransformPoint(new Vector3(1.8f - i * 0.6f, 0.9f, 0.14f)), 0f, wall.transform, false);
if (!hung) continue;
hung.transform.localRotation = Quaternion.Euler(-90f, 0f, 0f);
hung.transform.localScale = Vector3.one * sizes[i];
}
// the lawn mower is too big to hang: it stands on the deck at the end of the wall, handle toward you
var mower = Place(GameDefs.Tool(ToolId.LawnMower).model, wall.transform.TransformPoint(new Vector3(-2.75f, 0.95f, 1.4f)), 0f, wall.transform, false);
if (mower) mower.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
wall.AddComponent<SupplyWall>();
foreach (var t in wall.GetComponentsInChildren<Transform>()) t.gameObject.layer = Layers.Build;
Blocker(wall, new Vector3(0f, 0f, 0.2f), new Vector2(4.8f, 0.8f));
}
/// <summary>A small piece of base furniture with a box you can't walk through.</summary>
static void Prop(Transform rig, string model, Vector3 pos, float yaw, float size, float height, bool lamp, float scale = 1f)
{
var go = Place(model, pos, yaw, rig);
if (!go) return;
go.transform.localScale *= scale;
SolidAt("Solid", new Vector3(0f, height * 0.5f, 0f), new Vector3(size, height, size), go.transform);
Blocker(go, Vector3.zero, new Vector2(size + 0.4f, size + 0.4f));
if (!lamp) return;
var bulb = FindT(go, "Bulb");
var l = new GameObject("Light").AddComponent<Light>();
l.transform.SetParent(bulb ? bulb : go.transform, false);
if (!bulb) l.transform.localPosition = new Vector3(0f, 2.2f, 0f);
l.type = LightType.Point; l.range = 7f; l.intensity = 1.6f; l.color = new Color(1f, 0.85f, 0.6f); l.shadows = LightShadows.None;
}
// ───────────────────────── systems ─────────────────────────
static void Systems()
{
new GameObject("Steam").AddComponent<SteamManager>();
new GameObject("Boot").AddComponent<GameBoot>();
// ambience: wind over the meadow, crickets
new GameObject("Soundscape").AddComponent<Soundscape>();
// cameras
var rig = new GameObject("MenuRig");
var mc = rig.AddComponent<MenuCamera>();
mc.focus = new Vector3(0f, 3f, 2f);
mc.radius = 24f; mc.height = 7f; mc.speed = 0.018f;
var camGo = new GameObject("Main Camera");
camGo.tag = "MainCamera";
camGo.transform.SetParent(rig.transform, false);
var cam = camGo.AddComponent<Camera>();
cam.nearClipPlane = 0.05f; cam.farClipPlane = 14000f; cam.fieldOfView = 78f;
cam.cullingMask = ~(1 << Layers.ViewModel);
camGo.AddComponent<AudioListener>();
var data = camGo.AddComponent<UniversalAdditionalCameraData>();
data.renderPostProcessing = true;
data.antialiasing = AntialiasingMode.SubpixelMorphologicalAntiAliasing;
data.requiresDepthTexture = true;
camGo.AddComponent<CameraFx>();
mc.cam = camGo.transform;
var vmGo = new GameObject("ViewModelCamera");
vmGo.transform.SetParent(camGo.transform, false);
var vmCam = vmGo.AddComponent<Camera>();
vmCam.cullingMask = 1 << Layers.ViewModel;
vmCam.fieldOfView = 62f;
vmCam.nearClipPlane = 0.01f; vmCam.farClipPlane = 6f;
var vmData = vmGo.AddComponent<UniversalAdditionalCameraData>();
vmData.renderType = CameraRenderType.Overlay;
data.cameraStack.Add(vmCam);
var vm = new GameObject("ViewModel");
vm.transform.SetParent(vmGo.transform, false);
vm.layer = Layers.ViewModel;
vm.AddComponent<ViewModel>();
// networking
var netGo = new GameObject("NetworkManager");
var nm = netGo.AddComponent<NetworkManager>();
var utp = netGo.AddComponent<UnityTransport>();
netGo.AddComponent<SteamSocketsTransport>();
netGo.AddComponent<NetSession>();
nm.NetworkConfig = new NetworkConfig
{
NetworkTransport = utp,
PlayerPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(Prefabs + "Player.prefab"),
ConnectionApproval = true,
EnableSceneManagement = false,
TickRate = 30,
ForceSamePrefabs = true,
};
nm.NetworkConfig.Prefabs.NetworkPrefabsLists.Add(AssetDatabase.LoadAssetAtPath<NetworkPrefabsList>(Prefabs + "NetworkPrefabs.asset"));
// spawner
var sp = new GameObject("Spawner").AddComponent<Spawner>();
NetworkObject P(string n) { if (string.IsNullOrEmpty(n)) return null; var g = AssetDatabase.LoadAssetAtPath<GameObject>(Prefabs + n + ".prefab"); return g ? g.GetComponent<NetworkObject>() : null; }
sp.teamStatePrefab = P("TeamState");
sp.cargoPrefabs = new[] { P("Cargo_Grass"), P("Cargo_Hay"), P("Cargo_Brick") };
sp.vehiclePrefabs = new[] { P("Vehicle_Push"), P("Vehicle_Rider"), P("Vehicle_Pickup"), P("Vehicle_Tractor"), P("Vehicle_Combine"), P("Vehicle_Hauler"), P("Vehicle_Mulcher"), P("Vehicle_Baler") };
sp.piecePrefabs = new NetworkObject[GameDefs.Pieces.Length];
for (int i = 0; i < GameDefs.Pieces.Length; i++) sp.piecePrefabs[i] = P(GameDefs.Pieces[i].prefab);
sp.dock = _dockZone;
new GameObject("Stations").AddComponent<Stations>().rig = StationRig();
new GameObject("PowerWires").AddComponent<PowerWires>();
new GameObject("BeltSound").AddComponent<BeltSound>();
// UI
var ui = new GameObject("UI");
var doc = ui.AddComponent<UIDocument>();
doc.panelSettings = AssetDatabase.LoadAssetAtPath<PanelSettings>("Assets/UI/PanelSettings.asset");
var root = ui.AddComponent<UIRoot>();
root.style = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/GrassCutter.uss");
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 137a4d69b44db5f4b9a0c68eb9f98968

View File

@ -0,0 +1,562 @@
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
{
/// <summary>
/// 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).
/// </summary>
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
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");
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<Texture2D>("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<RenderPipelineAsset>("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<MatDef>();
foreach (var file in Directory.GetFiles("ArtSource", "materials*.json").OrderBy(f => f))
{
var json = File.ReadAllText(file);
all.AddRange(JsonUtility.FromJson<MatList>("{\"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<Texture2D>("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<Material>(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();
}
/// <summary>Tileable water normal map, foam noise and cloud noise (periodic value noise so they wrap).</summary>
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<Texture2D>(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<Texture2D>(Gen + "sky_clouds.png"));
sky.SetTexture("_PlanetTex", AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Art/UI/sky_planet.png"));
Save(sky, Mats + "M_Sky.mat");
}
static void Tex(string name, int size, Func<float, float, Color> 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<Texture2D>(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<AssetBank>(path);
if (!bank) { bank = ScriptableObject.CreateInstance<AssetBank>(); AssetDatabase.CreateAsset(bank, path); }
bank.clips = Load<AudioClip>("t:AudioClip", "Assets/Audio");
bank.textures = Load<Texture2D>("t:Texture2D", "Assets/Art/UI");
bank.fonts = Load<Font>("t:Font", "Assets/Fonts");
bank.materials = Load<Material>("t:Material", "Assets/Art/Materials");
bank.models = Load<GameObject>("t:Model", "Assets/Art/Models");
bank.models.AddRange(Load<GameObject>("t:Model", "Assets/Art/Pack"));
bank.meshes = new List<Mesh>();
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<T> Load<T>(string filter, string folder) where T : UnityEngine.Object
{
var l = new List<T>();
if (!AssetDatabase.IsValidFolder(folder)) return l;
foreach (var g in AssetDatabase.FindAssets(filter, new[] { folder }))
{
var a = AssetDatabase.LoadAssetAtPath<T>(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;
}
/// <summary>A plant from the pack's atlas, drawn by GrassField like the hemp.</summary>
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<Texture2D>(patchy ? "Assets/Art/Textures/T_Wildflower.png" : "Assets/Art/Textures/PolygonFarm_Texture_01_A.png"));
Save(m, Mats + name + ".mat");
}
/// <summary>A plant one unit tall with its foot at zero: the shader gives it its height.</summary>
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<Mesh>(path);
if (existing) AssetDatabase.DeleteAsset(path);
AssetDatabase.CreateAsset(m, path);
return m;
}
/// <summary>Copy of a model's mesh with the FBX root rotation baked into the vertices (for instanced / particle use).</summary>
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<Mesh>(path);
if (existing) AssetDatabase.DeleteAsset(path);
AssetDatabase.CreateAsset(m, path);
return m;
}
/// <summary>Our models, or a model from the POLYGON Farm pack.</summary>
public static GameObject Model(string name)
{
var m = AssetDatabase.LoadAssetAtPath<GameObject>(Models + name + ".fbx");
return m ? m : AssetDatabase.LoadAssetAtPath<GameObject>(Pack + name + ".fbx");
}
static Material Mat(string name) => AssetDatabase.LoadAssetAtPath<Material>(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<PanelSettings>(psPath);
if (!ps) { ps = ScriptableObject.CreateInstance<PanelSettings>(); AssetDatabase.CreateAsset(ps, psPath); }
ps.themeStyleSheet = AssetDatabase.LoadAssetAtPath<ThemeStyleSheet>(tss);
ps.scaleMode = PanelScaleMode.ScaleWithScreenSize;
ps.referenceResolution = new Vector2Int(1920, 1080);
ps.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
ps.match = 0.5f;
EditorUtility.SetDirty(ps);
AssetDatabase.SaveAssets();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 61766c27bf0e4c646aac442fa84a17fe