Compare commits

...

2 Commits

Author SHA1 Message Date
bbf73a6b96 Frame time on a big farm, round two: riding layer, instanced bundles
- Bundles on a belt move to a Riding layer that ignores the belts and the
  static world: every belt's catch trigger called OnTriggerStay (with a
  GetComponent) for each bundle riding it, every physics step.
- Bundles draw as instanced batches from CargoTick (their own renderers off,
  one in someone's hands draws itself), not as 2000 renderers to cull, sort
  and draw in the view and every shadow cascade.
- The main camera skips front-to-back sorting: the GPU has time to spare.
- BeltNet.Belted and DronePad.Belted are cached until the build changes;
  splitters on the host look only at their own items.

On the player's Mommy save, 2560x1440: base 14-15 ms -> 7.7 ms (~130 fps),
meadow 11.5-12 ms -> 6.8-7.5 ms (~135-145 fps).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:35:35 +06:00
57d0f4d31a Frame time on a big farm: batched grass, sleeping bundles, no light probes
Measured in a real 2560x1440 window on the player's Mommy save (RTX 4090):
the GPU took ~5 ms, the main thread the rest.

- Grass: a fully mown sector draws only its floor (one draw, not up to six);
  untouched and fully mown sectors share a mow map look, so the fur pile
  draws them all in one instanced call per pile (GC_SECTOR_BUFFER, sector
  frames from a structured buffer). Grass draws 1112 -> 337 at the base,
  876 -> 439 in the meadow.
- Bundles: loose ones sleep when they come to rest (our gravity kept ~600
  bodies awake), ones on belts skip the ground checks, and all of them are
  stepped from one CargoTick instead of two Unity messages each.
- Belts leave a jammed line alone and only look every few steps whether it
  can move; splitters test distance before transforming every bundle.
- Light probes off on everything (the planet has none) and the GPU Resident
  Drawer off: both cost CPU per moving renderer for nothing.
- -demogpu N -onscreen measures frame time with one feature off at a time.

Base view 17-19 ms -> 14-15 ms, meadow 14-16 ms -> 11.5-12 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:01:02 +06:00
22 changed files with 544 additions and 36 deletions

View File

@ -61,6 +61,8 @@ namespace GrassCutter.EditorTools
PlayerSettings.SetUseDefaultGraphicsAPIs(BuildTarget.StandaloneWindows64, false); PlayerSettings.SetUseDefaultGraphicsAPIs(BuildTarget.StandaloneWindows64, false);
PlayerSettings.SetGraphicsAPIs(BuildTarget.StandaloneWindows64, new[] { UnityEngine.Rendering.GraphicsDeviceType.Direct3D11 }); 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 // GC_BUILD_DIR builds somewhere else, so a copy of the game that is running doesn't lock the build
// a development build also reports GPU and render-thread frame times (FrameTimingManager), for -demoperf
PlayerSettings.enableFrameTimingStats = CommandLineHas("-devbuild");
var dir = Environment.GetEnvironmentVariable("GC_BUILD_DIR") is string d && d.Length > 0 ? d : "Builds/GrassCutter"; var dir = Environment.GetEnvironmentVariable("GC_BUILD_DIR") is string d && d.Length > 0 ? d : "Builds/GrassCutter";
var opts = new BuildPlayerOptions var opts = new BuildPlayerOptions
{ {
@ -91,7 +93,7 @@ namespace GrassCutter.EditorTools
var tm = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]); var tm = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
var layers = tm.FindProperty("layers"); var layers = tm.FindProperty("layers");
void L(int i, string n) { layers.GetArrayElementAtIndex(i).stringValue = n; } void L(int i, string n) { layers.GetArrayElementAtIndex(i).stringValue = n; }
L(6, "Player"); L(7, "Cargo"); L(8, "Prop"); L(9, "Vehicle"); L(10, "Held"); L(11, "ViewModel"); L(12, "LocalPlayer"); L(13, "Build"); L(6, "Player"); L(7, "Cargo"); L(8, "Prop"); L(9, "Vehicle"); L(10, "Held"); L(11, "ViewModel"); L(12, "LocalPlayer"); L(13, "Build"); L(14, "Riding");
tm.ApplyModifiedPropertiesWithoutUndo(); tm.ApplyModifiedPropertiesWithoutUndo();
PlayerSettings.companyName = "GreenHaul"; PlayerSettings.companyName = "GreenHaul";

View File

@ -219,7 +219,7 @@ namespace GrassCutter
var cam = CameraFx.Cam ? CameraFx.Cam.transform : Me.head; var cam = CameraFx.Cam ? CameraFx.Cam.transform : Me.head;
var dir = cam.forward; var dir = cam.forward;
float d = ahead; float d = ahead;
if (Physics.Raycast(cam.position, dir, out var hit, ahead + 0.5f, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Prop), QueryTriggerInteraction.Ignore)) if (Physics.Raycast(cam.position, dir, out var hit, ahead + 0.5f, (1 << Layers.Default) | (1 << Layers.Build) | Layers.CargoMask, QueryTriggerInteraction.Ignore))
d = Mathf.Max(0.6f, hit.distance - 0.6f); d = Mathf.Max(0.6f, hit.distance - 0.6f);
var p = cam.position + dir * d; var p = cam.position + dir * d;
float above = Vector3.Dot(p - Me.transform.position, Me.transform.up); float above = Vector3.Dot(p - Me.transform.position, Me.transform.up);

View File

@ -0,0 +1,98 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace GrassCutter
{
public partial class DemoBot
{
/// <summary>
/// -demogpu N -onscreen: save slot N in a real window, vsync off, and the frame time with one thing switched off at
/// a time (grass, MSAA, SSAO, shadows, post, lights, bundles...), at the base and out in the meadow. The CPU side
/// takes about 7 ms, so anything slower is the GPU. Writes gpu.txt.
/// </summary>
IEnumerator Gpu(int slot)
{
SaveSlots.Current = slot - 1;
yield return new WaitForSeconds(2f);
NetSession.Instance.HostLocal();
while (!Me || !Ts) yield return null;
yield return new WaitForSeconds(6f);
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = -1;
var asset = GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
var datas = asset ? typeof(UniversalRenderPipelineAsset).GetField("m_RendererDataList", BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(asset) as ScriptableRendererData[] : null;
var features = datas != null && datas.Length > 0 && datas[0] ? datas[0].rendererFeatures : new List<ScriptableRendererFeature>();
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
var camData = cam ? cam.GetUniversalAdditionalCameraData() : null;
var sun = FindObjectsByType<Light>(FindObjectsSortMode.None).Where(l => l.type == LightType.Directional).OrderByDescending(l => l.intensity).FirstOrDefault();
var outp = new StringBuilder();
outp.AppendLine($"screen {Screen.width}x{Screen.height}, {SystemInfo.graphicsDeviceName}, msaa {asset?.msaaSampleCount}, hdr {asset?.supportsHDR}, shadows {asset?.shadowDistance} m x{asset?.shadowCascadeCount}, features {string.Join(",", features.Select(f => f ? f.name + (f.isActive ? "" : "(off)") : "null"))}");
outp.AppendLine($"{BuildPiece.All.Count} pieces, {Cargo.All.Count} cargo, {FindObjectsByType<Renderer>(FindObjectsSortMode.None).Length} renderers, {FindObjectsByType<Light>(FindObjectsSortMode.None).Length} lights");
void Toggle(IEnumerable<Renderer> rs, bool on) { foreach (var r in rs) if (r) r.enabled = on; }
List<Renderer> Of(IEnumerable<Component> cs) => cs.Where(c => c).SelectMany(c => c.GetComponentsInChildren<Renderer>()).ToList();
var tests = new List<(string name, Action off, Action on)>
{
("base", () => { }, () => { }),
("grass off", () => { if (GrassField.Instance) GrassField.Instance.enabled = false; }, () => { if (GrassField.Instance) GrassField.Instance.enabled = true; }),
("msaa 1x", () => asset.msaaSampleCount = 1, () => asset.msaaSampleCount = 4),
("hdr off", () => asset.supportsHDR = false, () => asset.supportsHDR = true),
("post off", () => { if (camData) camData.renderPostProcessing = false; }, () => { if (camData) camData.renderPostProcessing = true; }),
("shadows off", () => asset.shadowDistance = 0f, () => asset.shadowDistance = 90f),
("shadows 2 casc 60 m", () => { asset.shadowCascadeCount = 2; asset.shadowDistance = 60f; }, () => { asset.shadowCascadeCount = 4; asset.shadowDistance = 90f; }),
("hard shadows", () => { if (sun) sun.shadows = LightShadows.Hard; }, () => { if (sun) sun.shadows = LightShadows.Soft; }),
("other lights off", () => { foreach (var l in FindObjectsByType<Light>(FindObjectsSortMode.None)) if (l != sun) l.enabled = false; }, () => { foreach (var l in FindObjectsByType<Light>(FindObjectsInactive.Include, FindObjectsSortMode.None)) if (l != sun) l.enabled = true; }),
("bundles hidden", () => Toggle(Of(Cargo.All), false), () => Toggle(Of(Cargo.All), true)),
("pieces hidden", () => Toggle(Of(BuildPiece.All), false), () => Toggle(Of(BuildPiece.All), true)),
("bundles not instanced", () => CargoTick.Instanced = false, () => CargoTick.Instanced = true),
("distance sort on", () => { if (cam) cam.opaqueSortMode = OpaqueSortMode.Default; }, () => { if (cam) cam.opaqueSortMode = OpaqueSortMode.NoDistanceSort; }),
("render scale 0.75", () => asset.renderScale = 0.75f, () => asset.renderScale = 1f),
};
foreach (var f in features)
if (f && f.isActive) { var ff = f; tests.Add(($"feature {ff.name} off", () => ff.SetActive(false), () => ff.SetActive(true))); }
tests.Add(("base again", () => { }, () => { }));
var views = new (string name, Vector3 at, Vector3 look)[]
{
("base", Planet.FromBase(0f, -14f), Planet.FromBase(0f, 6f)),
("meadow", Planet.FromBase(140f, 120f), Planet.FromBase(260f, 220f)),
};
foreach (var v in views)
{
Me.Teleport(Planet.OnSurface(v.at) + v.at * 0.2f);
yield return new WaitForSeconds(2f);
Me.LookAt(Planet.OnSurface(v.look));
yield return new WaitForSeconds(1.5f);
double baseMs = 0;
foreach (var (name, off, on) in tests)
{
off();
yield return new WaitForSeconds(0.6f);
var dts = new List<float>();
float until = Time.realtimeSinceStartup + 4f;
while (Time.realtimeSinceStartup < until) { yield return null; dts.Add(Time.unscaledDeltaTime * 1000f); }
on();
dts.Sort();
double ms = dts.Count > 0 ? dts[dts.Count / 2] : 0;
if (name == "base") baseMs = ms;
if (name == "base") outp.AppendLine($"{v.name}: grass draws {(GrassField.Instance ? GrassField.Instance.Draws : -1)}");
outp.AppendLine($"{v.name,-7} {name,-34} {ms,6:0.0} ms {1000.0 / Math.Max(0.1, ms),5:0} fps {(name == "base" ? "" : $"{ms - baseMs:+0.0;-0.0} ms")}");
yield return new WaitForSeconds(0.3f);
}
yield return Shot($"gpu_{v.name}");
}
File.WriteAllText(Path.Combine(folder, "gpu.txt"), outp.ToString());
Log("gpu done");
Application.Quit();
}
}
}

View File

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

View File

@ -29,6 +29,12 @@ namespace GrassCutter
foreach (var rb in FindObjectsByType<Rigidbody>(FindObjectsSortMode.None)) { bodies++; if (!rb.isKinematic && !rb.IsSleeping()) awake++; } foreach (var rb in FindObjectsByType<Rigidbody>(FindObjectsSortMode.None)) { bodies++; if (!rb.isKinematic && !rb.IsSleeping()) awake++; }
outp.AppendLine($"rigidbodies {bodies}, awake {awake}, renderers {FindObjectsByType<Renderer>(FindObjectsSortMode.None).Length}"); outp.AppendLine($"rigidbodies {bodies}, awake {awake}, renderers {FindObjectsByType<Renderer>(FindObjectsSortMode.None).Length}");
if (CommandLine.Has("-tune"))
{
foreach (var r in FindObjectsByType<Renderer>(FindObjectsSortMode.None)) r.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
if (UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline is UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset ua) ua.gpuResidentDrawerMode = UnityEngine.Rendering.GPUResidentDrawerMode.Disabled;
outp.AppendLine("tuned: light probes off, resident drawer off");
}
var home = Planet.FromBase(0f, -12f); var home = Planet.FromBase(0f, -12f);
Me.Teleport(Planet.OnSurface(home) + home * 0.2f); Me.Teleport(Planet.OnSurface(home) + home * 0.2f);
yield return new WaitForSeconds(1f); yield return new WaitForSeconds(1f);

View File

@ -3003,6 +3003,11 @@ namespace GrassCutter
yield return Sizes(); yield return Sizes();
yield break; yield break;
} }
if (CommandLine.Get("-demogpu") is string gpuSlot)
{
yield return Gpu(int.Parse(gpuSlot));
yield break;
}
if (CommandLine.Get("-demoperf") is string perfSlot) if (CommandLine.Get("-demoperf") is string perfSlot)
{ {
yield return Perf(int.Parse(perfSlot)); yield return Perf(int.Parse(perfSlot));

View File

@ -18,11 +18,34 @@ namespace GrassCutter
void Start() void Start()
{ {
NoProbes();
// dev bots render off-screen so they can run with -batchmode without touching the user's desktop // dev bots render off-screen so they can run with -batchmode without touching the user's desktop
if (CommandLine.Has("-screenshot") || CommandLine.Has("-autodemo")) // (-onscreen: a real window instead, for measuring what the screen really costs)
if ((CommandLine.Has("-screenshot") || CommandLine.Has("-autodemo")) && !CommandLine.Has("-onscreen"))
BotCapture.Setup(int.TryParse(CommandLine.Get("-shotw", "1600"), out var w) ? w : 1600, int.TryParse(CommandLine.Get("-shoth", "900"), out var h) ? h : 900); BotCapture.Setup(int.TryParse(CommandLine.Get("-shotw", "1600"), out var w) ? w : 1600, int.TryParse(CommandLine.Get("-shoth", "900"), out var h) ? h : 900);
if (CommandLine.Get("-screenshot") is string path) gameObject.AddComponent<AutoScreenshot>().path = path; if (CommandLine.Get("-screenshot") is string path) gameObject.AddComponent<AutoScreenshot>().path = path;
if (CommandLine.Get("-autodemo") is string demo) gameObject.AddComponent<DemoBot>().folder = demo; if (CommandLine.Get("-autodemo") is string demo) gameObject.AddComponent<DemoBot>().folder = demo;
} }
/// <summary>
/// The planet has no light probes, so interpolating them for every moving thing (two thousand bundles on the belts
/// of a big farm) is work for nothing: the ambient light is the same. Off on every networked prefab and everything
/// in the scene, once at boot.
/// </summary>
static void NoProbes()
{
if (LightmapSettings.lightProbes != null && LightmapSettings.lightProbes.count > 0) return;
void Off(GameObject go)
{
if (!go) return;
foreach (var r in go.GetComponentsInChildren<Renderer>(true)) r.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
}
var nm = Unity.Netcode.NetworkManager.Singleton;
// (not in the editor: there the prefab is the asset on disk)
if (!Application.isEditor && nm && nm.NetworkConfig?.Prefabs?.Prefabs != null)
foreach (var p in nm.NetworkConfig.Prefabs.Prefabs) Off(p.Prefab);
foreach (var r in Object.FindObjectsByType<Renderer>(FindObjectsInactive.Include, FindObjectsSortMode.None))
r.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
}
} }
} }

View File

@ -96,10 +96,19 @@ namespace GrassCutter
bool seen = false; bool seen = false;
Cargo inJunction = null; Cargo inJunction = null;
float side = 0f; float side = 0f;
foreach (var c in Cargo.All) var here = transform.position;
// the host has its own items in a list; a joined peer looks round every few frames
bool mine = Server;
if (!mine && (Time.frameCount + _phase) % 4 != 0) { Paddle(); return; }
int count = mine ? Items.Count : Cargo.All.Count;
for (int k = 0; k < count; k++)
{ {
var c = mine ? Items[k].c : Cargo.All[k];
if (!c) continue; if (!c) continue;
var l = transform.InverseTransformPoint(c.transform.position); var at = c.transform.position;
// most of a farm's bundles are nowhere near: the cheap test first
if ((at - here).sqrMagnitude > 4f) continue;
var l = transform.InverseTransformPoint(at);
if (Mathf.Abs(l.x) > 0.55f || Mathf.Abs(l.z) > 0.55f || l.y < -0.2f || l.y > 1.4f) continue; if (Mathf.Abs(l.x) > 0.55f || Mathf.Abs(l.z) > 0.55f || l.y < -0.2f || l.y > 1.4f) continue;
if (l.z < -0.2f) continue; if (l.z < -0.2f) continue;
inJunction = c; inJunction = c;
@ -113,11 +122,17 @@ namespace GrassCutter
_paddleTarget = -side * 38f; _paddleTarget = -side * 38f;
Sfx.PlayAt("splitter_flip", transform.position + transform.up * 0.4f, 0.55f, 1f, 0.08f); Sfx.PlayAt("splitter_flip", transform.position + transform.up * 0.4f, 0.55f, 1f, 0.08f);
} }
if (paddle) Paddle();
{ }
_paddleAngle = Mathf.MoveTowards(_paddleAngle, _paddleTarget, Time.deltaTime * 260f);
paddle.localRotation = Quaternion.AngleAxis(_paddleAngle, paddle.parent ? paddle.parent.InverseTransformDirection(transform.up) : Vector3.up) * _paddleRest; static int s_phases;
} readonly int _phase = s_phases++;
void Paddle()
{
if (!paddle) return;
_paddleAngle = Mathf.MoveTowards(_paddleAngle, _paddleTarget, Time.deltaTime * 260f);
paddle.localRotation = Quaternion.AngleAxis(_paddleAngle, paddle.parent ? paddle.parent.InverseTransformDirection(transform.up) : Vector3.up) * _paddleRest;
} }
} }
} }

View File

@ -21,11 +21,42 @@ namespace GrassCutter
Grabbable _g; Grabbable _g;
bool _wasInGrass; bool _wasInGrass;
public bool Loaded { get; set; } public bool Loaded { get; set; }
/// <summary>Server: the belt this item is locked onto (null when loose).</summary> /// <summary>Server: the belt this item is locked onto (null when loose). On a belt it is on the Riding layer.</summary>
public Conveyor Belt { get; set; } public Conveyor Belt
{
get => _belt;
set
{
bool was = !ReferenceEquals(_belt, null), now = !ReferenceEquals(value, null);
_belt = value;
if (was != now) Ride(now);
}
}
Conveyor _belt;
Transform[] _parts;
void Ride(bool riding)
{
if (_parts == null) _parts = GetComponentsInChildren<Transform>(true);
int layer = riding ? Layers.Riding : Layers.Prop;
foreach (var t in _parts)
if (t && (t.gameObject.layer == Layers.Prop || t.gameObject.layer == Layers.Riding)) t.gameObject.layer = layer;
}
public Grabbable Grab => _g ? _g : (_g = GetComponent<Grabbable>()); public Grabbable Grab => _g ? _g : (_g = GetComponent<Grabbable>());
void Awake() { _g = GetComponent<Grabbable>(); } void Awake()
{
_g = GetComponent<Grabbable>();
// what it looks like, for CargoTick to draw it with all the others
Look = GetComponentInChildren<MeshRenderer>(true);
var mf = Look ? Look.GetComponent<MeshFilter>() : null;
LookMesh = mf ? mf.sharedMesh : null;
LookMats = Look ? Look.sharedMaterials : null;
}
public MeshRenderer Look { get; private set; }
public Mesh LookMesh { get; private set; }
public Material[] LookMats { get; private set; }
/// <summary>Server: unlock from the belt and become a loose physics body again.</summary> /// <summary>Server: unlock from the belt and become a loose physics body again.</summary>
public void ServerLeaveBelt(Vector3 velocity) public void ServerLeaveBelt(Vector3 velocity)
@ -48,6 +79,7 @@ namespace GrassCutter
public override void OnNetworkSpawn() public override void OnNetworkSpawn()
{ {
All.Add(this); All.Add(this);
CargoTick.Ensure();
if (Time.timeSinceLevelLoad > 3f) Tween.Scale(transform, Vector3.one * 0.3f, Vector3.one, 0.35f, Ease.OutBack); if (Time.timeSinceLevelLoad > 3f) Tween.Scale(transform, Vector3.one * 0.3f, Vector3.one, 0.35f, Ease.OutBack);
} }
@ -65,10 +97,15 @@ namespace GrassCutter
float _fallV; float _fallV;
void FixedUpdate() /// <summary>One physics step, called by <see cref="CargoTick"/> for every bundle at once: two thousand Unity
/// FixedUpdate messages cost more than the work in them.</summary>
internal void Step()
{ {
if (_belt) return;
if (!IsSpawned) return; if (!IsSpawned) return;
var rb = _g.Body; var rb = _g.Body;
// riding a belt or lying still: nothing below needs looking at (most of a big farm's bundles, every step)
if (Belt || (rb && !rb.isKinematic && rb.IsSleeping())) { _fallV = 0f; _wasInGrass = !Belt; return; }
var p = transform.position; var p = transform.position;
// tossed into a depot // tossed into a depot

View File

@ -0,0 +1,119 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace GrassCutter
{
/// <summary>
/// Steps every bundle and every grabbable thing from one FixedUpdate. A big farm has two thousand bundles, and a Unity
/// message per object per physics step (two scripts each) cost more than what they do, which is mostly nothing.
/// </summary>
public class CargoTick : MonoBehaviour
{
static CargoTick s_on;
public static void Ensure()
{
if (s_on) return;
var go = new GameObject("CargoTick");
DontDestroyOnLoad(go);
s_on = go.AddComponent<CargoTick>();
}
void FixedUpdate()
{
// backwards: a step can hand a bundle to a depot, which takes it off the list
var g = Grabbable.All;
for (int i = g.Count - 1; i >= 0; i--)
if (i < g.Count && g[i]) g[i].Step();
var c = Cargo.All;
for (int i = c.Count - 1; i >= 0; i--)
if (i < c.Count && c[i]) c[i].Step();
}
// ───────────────────────── drawing ─────────────────────────
//
// Two thousand bundles were two thousand renderers: culled, sorted and drawn one by one, in the main view and
// every shadow cascade. Their own renderers are off and they go down here as a few instanced draws, one per
// model. One in someone's hands draws itself as before (it may be on another layer, in first person).
/// <summary>Off: every bundle draws itself again (a switch for tests).</summary>
public static bool Instanced = true;
sealed class Group
{
public Mesh mesh;
public int sub;
public Material mat;
public Matrix4x4[] m = new Matrix4x4[256];
public int n;
public Bounds bounds;
}
readonly Dictionary<(Mesh, int, Material), Group> _groups = new Dictionary<(Mesh, int, Material), Group>();
readonly List<Group> _order = new List<Group>();
static readonly Dictionary<Material, Material> s_instanced = new Dictionary<Material, Material>();
const int Chunk = 1023;
static Material InstancedCopy(Material m)
{
if (!s_instanced.TryGetValue(m, out var copy))
{
copy = new Material(m) { name = m.name + " (instanced)", enableInstancing = true };
s_instanced[m] = copy;
}
return copy;
}
void LateUpdate()
{
foreach (var g in _order) g.n = 0;
var all = Cargo.All;
for (int i = 0; i < all.Count; i++)
{
var c = all[i];
if (!c) continue;
var r = c.Look;
if (!r) continue;
bool mine = Instanced && !c.Grab.IsHeld && c.gameObject.activeInHierarchy;
if (r.enabled == mine) r.enabled = !mine;
if (!mine) continue;
var mesh = c.LookMesh;
var mats = c.LookMats;
if (!mesh || mats == null) { r.enabled = true; continue; }
var m = r.localToWorldMatrix;
var at = new Vector3(m.m03, m.m13, m.m23);
for (int sub = 0; sub < mesh.subMeshCount && sub < mats.Length; sub++)
{
var mat = mats[sub];
if (!mat) continue;
var key = (mesh, sub, mat);
if (!_groups.TryGetValue(key, out var g))
{
g = new Group { mesh = mesh, sub = sub, mat = InstancedCopy(mat) };
_groups[key] = g;
_order.Add(g);
}
if (g.n == g.m.Length) System.Array.Resize(ref g.m, g.m.Length * 2);
if (g.n == 0) g.bounds = new Bounds(at, Vector3.one); else g.bounds.Encapsulate(at);
g.m[g.n++] = m;
}
}
foreach (var g in _order)
{
if (g.n == 0) continue;
g.bounds.Expand(2f);
var rp = new RenderParams(g.mat)
{
worldBounds = g.bounds,
layer = Layers.Prop,
shadowCastingMode = ShadowCastingMode.On,
receiveShadows = true,
lightProbeUsage = LightProbeUsage.Off,
};
for (int start = 0; start < g.n; start += Chunk)
Graphics.RenderMeshInstanced(rp, g.mesh, g.sub, g.m, Mathf.Min(Chunk, g.n - start), start);
}
}
}
}

View File

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

View File

@ -46,6 +46,9 @@ namespace GrassCutter
public float blend; public float blend;
/// <summary>Has it settled which way it's going?</summary> /// <summary>Has it settled which way it's going?</summary>
public bool set; public bool set;
/// <summary>Where it was last put, and for how many steps it hasn't moved: a jammed line is left alone.</summary>
public float placedD = -1f;
public int still;
} }
struct Link struct Link
@ -307,6 +310,7 @@ namespace GrassCutter
int i = 0; int i = 0;
while (i < Items.Count && Items[i].d > d) i++; while (i < Items.Count && Items[i].d > d) i++;
Items.Insert(i, s); Items.Insert(i, s);
_idle = 0;
} }
/// <summary>Server: take an item off this belt (a player grabbed it, it got despawned).</summary> /// <summary>Server: take an item off this belt (a player grabbed it, it got despawned).</summary>
@ -334,7 +338,10 @@ namespace GrassCutter
void FixedUpdate() void FixedUpdate()
{ {
if (!Server || !Piece || !Piece.IsSpawned || Items.Count == 0) return; if (!Server || !Piece || !Piece.IsSpawned || Items.Count == 0) return;
float dt = Time.fixedDeltaTime; // a line that hasn't moved for a while only looks again every few steps whether the front can go on
if (_idle > 40 && ++_idleSkip % 6 != 0) return;
bool moved = false;
float dt = Time.fixedDeltaTime * (_idle > 40 ? 6f : 1f);
float step = Speed * dt; float step = Speed * dt;
for (int i = 0; i < Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
@ -347,16 +354,25 @@ namespace GrassCutter
} }
float L = Length(s.route); float L = Length(s.route);
float limit = Room(i, ref L); float limit = Room(i, ref L);
if (s.d < limit) s.d = Mathf.Min(s.d + step, limit); if (s.d < limit - 1e-5f) { s.d = Mathf.Min(s.d + step, limit); moved = true; }
if ((i == 0 || RouteCount > 1) && s.d >= L - 1e-4f && HandOff(s)) if ((i == 0 || RouteCount > 1) && s.d >= L - 1e-4f && HandOff(s))
{ {
Items.RemoveAt(i--); Items.RemoveAt(i--);
moved = true;
continue; continue;
} }
// stuck behind the one ahead: once it has come square and settled there is nothing to move
if (s.blend >= 1f && Mathf.Abs(s.d - s.placedD) < 1e-5f) { if (++s.still > 40) continue; }
else s.still = 0;
Place(s, dt); Place(s, dt);
s.placedD = s.d;
if (s.blend < 1f) moved = true;
} }
_idle = moved ? 0 : _idle + 1;
} }
int _idle, _idleSkip;
/// <summary>How far an item can go: to the turn until it has chosen, then the end of its route, and never into the one ahead.</summary> /// <summary>How far an item can go: to the turn until it has chosen, then the end of its route, and never into the one ahead.</summary>
float Room(int i, ref float L) float Room(int i, ref float L)
{ {
@ -418,7 +434,7 @@ namespace GrassCutter
} }
// nothing there: drop it off the end, but only onto a free spot (one item waits there at a time) // nothing there: drop it off the end, but only onto a free spot (one item waits there at a time)
var land = WorldOnPath(L, s.route, 0f) + dir * 0.45f; var land = WorldOnPath(L, s.route, 0f) + dir * 0.45f;
int n = Physics.OverlapSphereNonAlloc(land, 0.3f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore); int n = Physics.OverlapSphereNonAlloc(land, 0.3f, s_hits, Layers.CargoMask, QueryTriggerInteraction.Ignore);
for (int k = 0; k < n; k++) for (int k = 0; k < n; k++)
{ {
var other = s_hits[k].GetComponentInParent<Cargo>(); var other = s_hits[k].GetComponentInParent<Cargo>();
@ -494,7 +510,7 @@ namespace GrassCutter
port = index; port = index;
if (belt && !belt.HasRoom) return false; if (belt && !belt.HasRoom) return false;
} }
else if (Physics.OverlapSphereNonAlloc(way.at + way.dir * 0.5f, 0.45f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore) > 0) return false; else if (Physics.OverlapSphereNonAlloc(way.at + way.dir * 0.5f, 0.45f, s_hits, Layers.CargoMask, QueryTriggerInteraction.Ignore) > 0) return false;
var made = Spawner.Instance.SpawnCargo(kind, way.at + way.dir * 0.2f + from.transform.up * 0.35f, from.transform.rotation, way.dir * 1.6f); var made = Spawner.Instance.SpawnCargo(kind, way.at + way.dir * 0.2f + from.transform.up * 0.35f, from.transform.rotation, way.dir * 1.6f);
if (!made) return false; if (!made) return false;
if (belt) belt.ServerAcceptPort(made, port); if (belt) belt.ServerAcceptPort(made, port);
@ -528,9 +544,21 @@ namespace GrassCutter
static readonly List<Port> s_belted = new List<Port>(); static readonly List<Port> s_belted = new List<Port>();
/// <summary>Does a belt leave any of this piece's hatches?</summary> /// <summary>Does a belt leave any of this piece's hatches?</summary>
static readonly Dictionary<BuildPiece, (int ver, bool on)> s_beltedAt = new Dictionary<BuildPiece, (int, bool)>();
public static bool Belted(BuildPiece piece) public static bool Belted(BuildPiece piece)
{ {
if (!piece) return false; if (!piece) return false;
// asked every frame by every pad and dock: the answer only changes when the build does
if (s_beltedAt.TryGetValue(piece, out var had) && had.ver == BuildPiece.Version) return had.on;
bool on = Look(piece);
if (s_beltedAt.Count > 512) s_beltedAt.Clear();
s_beltedAt[piece] = (BuildPiece.Version, on);
return on;
}
static bool Look(BuildPiece piece)
{
s_belted.Clear(); s_belted.Clear();
piece.Ports(s_belted); piece.Ports(s_belted);
foreach (var p in s_belted) foreach (var p in s_belted)

View File

@ -219,7 +219,17 @@ namespace GrassCutter
static readonly List<Port> s_ports = new List<Port>(); static readonly List<Port> s_ports = new List<Port>();
/// <summary>Is a belt joined to the hatch?</summary> /// <summary>Is a belt joined to the hatch?</summary>
int _beltedVer = -1;
bool _belted;
bool Belted() bool Belted()
{
if (_beltedVer == BuildPiece.Version) return _belted;
_beltedVer = BuildPiece.Version;
return _belted = LookForBelt();
}
bool LookForBelt()
{ {
s_ports.Clear(); s_ports.Clear();
Ports(s_ports); Ports(s_ports);

View File

@ -44,6 +44,7 @@ namespace GrassCutter
public override void OnNetworkSpawn() public override void OnNetworkSpawn()
{ {
CargoTick.Ensure();
All.Add(this); All.Add(this);
Holder.OnValueChanged += (_, h) => ApplyHeldLayer(h != Nobody); Holder.OnValueChanged += (_, h) => ApplyHeldLayer(h != Nobody);
Scale.OnValueChanged += (_, s) => transform.localScale = _baseScale * s; Scale.OnValueChanged += (_, s) => transform.localScale = _baseScale * s;
@ -155,15 +156,31 @@ namespace GrassCutter
if (Body && !Body.isKinematic && !IsHeld) Body.AddForce(velocity, ForceMode.VelocityChange); if (Body && !Body.isKinematic && !IsHeld) Body.AddForce(velocity, ForceMode.VelocityChange);
} }
void FixedUpdate() int _still;
Cargo _cargo;
bool _cargoLooked;
/// <summary>One physics step, from <see cref="CargoTick"/>.</summary>
internal void Step()
{ {
// riding a belt (most bundles on a big farm): nothing to do, and the managed test is the cheap one
if (!_cargoLooked) { _cargo = GetComponent<Cargo>(); _cargoLooked = true; }
if (_cargo && _cargo.Belt) return;
if (!IsSpawned || !IsOwner || !Body || Body.isKinematic) return; if (!IsSpawned || !IsOwner || !Body || Body.isKinematic) return;
// at rest it sleeps: our own gravity, pushed every step, would keep it awake for ever, and a big farm has
// hundreds of bundles lying about. A knock, a grab or a belt wakes it again.
if (Body.IsSleeping()) return;
var p = Body.position; var p = Body.position;
var up = Planet.Up(p); var up = Planet.Up(p);
if (!IsHeld) Body.AddForce(-up * GameDefs.LowGravity, ForceMode.Acceleration); if (!IsHeld) Body.AddForce(-up * GameDefs.LowGravity, ForceMode.Acceleration);
// there is no collider under the grass: the soil is a number // there is no collider under the grass: the soil is a number
var c = GetComponent<Cargo>(); if (!_cargoLooked) { _cargo = GetComponent<Cargo>(); _cargoLooked = true; }
float below = Planet.Altitude(p) - (c ? c.halfHeight : 0.3f); float below = Planet.Altitude(p) - (_cargo ? _cargo.halfHeight : 0.3f);
if (!IsHeld && Body.linearVelocity.sqrMagnitude < 0.004f && Body.angularVelocity.sqrMagnitude < 0.01f)
{
if (++_still > 25) { _still = 0; Body.Sleep(); return; }
}
else _still = 0;
if (below >= 0f) return; if (below >= 0f) return;
Body.position = p - up * below; Body.position = p - up * below;
var v = Body.linearVelocity; var v = Body.linearVelocity;
@ -193,6 +210,10 @@ namespace GrassCutter
public const int ViewModel = 11; public const int ViewModel = 11;
public const int LocalPlayer = 12; public const int LocalPlayer = 12;
public const int Build = 13; public const int Build = 13;
/// <summary>Cargo riding a belt: the belts' catch triggers (and the static world) don't see it, everything else does.</summary>
public const int Riding = 14;
/// <summary>Loose cargo and cargo on a belt, for the casts that look for either.</summary>
public const int CargoMask = (1 << Prop) | (1 << Riding);
public static void SetupCollisions() public static void SetupCollisions()
{ {
@ -202,9 +223,14 @@ namespace GrassCutter
Physics.IgnoreLayerCollision(Wrap, Vehicle); Physics.IgnoreLayerCollision(Wrap, Vehicle);
Physics.IgnoreLayerCollision(ViewModel, Default); Physics.IgnoreLayerCollision(ViewModel, Default);
for (int i = 0; i < 32; i++) Physics.IgnoreLayerCollision(ViewModel, i); for (int i = 0; i < 32; i++) Physics.IgnoreLayerCollision(ViewModel, i);
// a bundle on a belt is kinematic: against the belts and the static world it only ever made trigger calls,
// one per bundle per belt per physics step (two thousand on a big farm), all of them for nothing
Physics.IgnoreLayerCollision(Riding, Build);
Physics.IgnoreLayerCollision(Riding, Default);
Physics.IgnoreLayerCollision(Riding, Riding);
} }
/// <summary>Things the player's interaction ray can hit.</summary> /// <summary>Things the player's interaction ray can hit.</summary>
public static readonly int InteractMask = (1 << Default) | (1 << Wrap) | (1 << Prop) | (1 << Vehicle) | (1 << Player) | (1 << Build); public static readonly int InteractMask = (1 << Default) | (1 << Wrap) | (1 << Prop) | (1 << Riding) | (1 << Vehicle) | (1 << Player) | (1 << Build);
} }
} }

View File

@ -157,7 +157,7 @@ namespace GrassCutter
{ {
var at = TwisterPos(Now); var at = TwisterPos(Now);
var up = Planet.Up(at); var up = Planet.Up(at);
int n = Physics.OverlapSphereNonAlloc(at + up * 2f, TwisterRadius + 2f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore); int n = Physics.OverlapSphereNonAlloc(at + up * 2f, TwisterRadius + 2f, s_hits, Layers.CargoMask, QueryTriggerInteraction.Ignore);
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
{ {
var rb = s_hits[i].attachedRigidbody; var rb = s_hits[i].attachedRigidbody;

View File

@ -21,6 +21,8 @@ namespace GrassCutter
{ {
_i = this; _i = this;
Cam = GetComponent<Camera>(); Cam = GetComponent<Camera>();
// the GPU has time to spare, the CPU doesn't: sorting thousands of draws front to back cost more than the overdraw it saves
if (Cam) Cam.opaqueSortMode = UnityEngine.Rendering.OpaqueSortMode.NoDistanceSort;
} }
/// <summary> /// <summary>

View File

@ -12,7 +12,7 @@ namespace GrassCutter
public class CrewBody : MonoBehaviour public class CrewBody : MonoBehaviour
{ {
const float Skin = 0.03f, StepUp = 0.4f, FloorDot = 0.6f, StickDown = 0.3f; const float Skin = 0.03f, StepUp = 0.4f, FloorDot = 0.6f, StickDown = 0.3f;
const int Solid = (1 << Layers.Default) | (1 << Physics.IgnoreRaycastLayer) | (1 << Layers.Prop) | (1 << Layers.Vehicle) | (1 << Layers.Player) | (1 << Layers.Build); const int Solid = (1 << Layers.Default) | (1 << Physics.IgnoreRaycastLayer) | (1 << Layers.Prop) | (1 << Layers.Riding) | (1 << Layers.Vehicle) | (1 << Layers.Player) | (1 << Layers.Build);
public bool isGrounded { get; private set; } public bool isGrounded { get; private set; }
/// <summary>Walked into something: what was hit and which way we were going.</summary> /// <summary>Walked into something: what was hit and which way we were going.</summary>

View File

@ -97,6 +97,8 @@ namespace GrassCutter
readonly List<HexGrid.Sector> _worked = new List<HexGrid.Sector>(); readonly List<HexGrid.Sector> _worked = new List<HexGrid.Sector>();
readonly Plane[] _frustum = new Plane[6]; readonly Plane[] _frustum = new Plane[6];
int _mpbUsed, _here = -1; int _mpbUsed, _here = -1;
/// <summary>Grass draws issued last frame (for -demogpu).</summary>
public int Draws { get; private set; }
int _deckHash; int _deckHash;
/// <summary>The grass's blocks were cleared (the ball changed size): the deck goes back in next frame.</summary> /// <summary>The grass's blocks were cleared (the ball changed size): the deck goes back in next frame.</summary>
@ -119,6 +121,86 @@ namespace GrassCutter
void OnDestroy() void OnDestroy()
{ {
if (_furTex) Destroy(_furTex); if (_furTex) Destroy(_furTex);
foreach (var b in _batches) b.buffer?.Release();
if (_furBatchMat) Destroy(_furBatchMat);
}
// ───────────────────────── batches ─────────────────────────
/// <summary>One sector's frame as the fur shader reads it from <c>_GcSectorBuf</c> (GC_SECTOR_BUFFER).</summary>
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
struct SectorData { public Vector4 c, e1, e2, salt, grid, b0, b1, b2, b3, b4, b5; }
/// <summary>The sectors of one pile and one shared mow map look, drawn together at the end of the frame.</summary>
sealed class Batch
{
public Pile pile;
public bool onlyWorked;
public Texture2D mask;
public readonly List<SectorData> items = new List<SectorData>();
public Bounds bounds;
public GraphicsBuffer buffer;
public readonly MaterialPropertyBlock mpb = new MaterialPropertyBlock();
}
static readonly int SectorBufId = Shader.PropertyToID("_GcSectorBuf");
readonly List<Batch> _batches = new List<Batch>();
Material _furBatchMat;
bool Batched(Pile p, HexGrid.Sector s, Texture2D mask, bool onlyWorked)
{
if (mask != MowMap.Blank && mask != MowMap.Full) return false;
if (!_furBatchMat && furMat)
{
_furBatchMat = new Material(furMat) { name = furMat.name + " (batched)" };
_furBatchMat.EnableKeyword("GC_SECTOR_BUFFER");
}
if (!_furBatchMat) return false;
Batch b = null;
foreach (var x in _batches)
if (x.mask == mask && x.onlyWorked == onlyWorked && x.pile.shells == p.shells && x.pile.inner == p.inner && x.pile.outer == p.outer && x.pile.fadeA == p.fadeA && x.pile.fadeB == p.fadeB) { b = x; break; }
if (b == null) { b = new Batch { pile = p, onlyWorked = onlyWorked, mask = mask }; _batches.Add(b); }
if (b.items.Count == 0) b.bounds = s.bounds; else b.bounds.Encapsulate(s.bounds);
bool floor = p.shells == 1;
var bs = s.borders;
b.items.Add(new SectorData
{
c = s.c, e1 = s.e1, e2 = s.e2, salt = s.salt,
grid = new Vector4(s.half, s.half * 2f / ((floor ? FloorSide : GridSide) - 1), 0f, 0f),
b0 = bs[0], b1 = bs[1], b2 = bs[2], b3 = bs[3], b4 = bs[4], b5 = bs[5],
});
return true;
}
void DrawBatches()
{
foreach (var b in _batches)
{
int n = b.items.Count;
if (n == 0) continue;
if (b.buffer == null || b.buffer.count < n)
{
b.buffer?.Release();
b.buffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, Mathf.NextPowerOfTwo(Mathf.Max(64, n)), System.Runtime.InteropServices.Marshal.SizeOf<SectorData>());
}
b.buffer.SetData(b.items);
var p = b.pile;
b.mpb.SetBuffer(SectorBufId, b.buffer);
b.mpb.SetTexture(MaskTexId, b.mask);
b.mpb.SetVector(ShellsId, new Vector4(p.shells, b.onlyWorked ? 0f : p.inner, b.onlyWorked ? 1e6f : p.outer, SeamBand));
b.mpb.SetVector(FadeId, new Vector4(p.fadeA, b.onlyWorked ? 1e6f : p.fadeB, b.onlyWorked ? 1f : 0f, 0f));
var rp = new RenderParams(_furBatchMat)
{
worldBounds = b.bounds,
matProps = b.mpb,
shadowCastingMode = ShadowCastingMode.Off,
receiveShadows = true,
layer = 0,
};
Graphics.RenderMeshPrimitives(rp, p.shells == 1 ? _floorGrid : _grid, 0, p.shells * n);
_drawn++;
b.items.Clear();
}
} }
/// <summary>Meadow height in metres.</summary> /// <summary>Meadow height in metres.</summary>
@ -177,6 +259,7 @@ namespace GrassCutter
int here = HexGrid.SectorAt(dir); int here = HexGrid.SectorAt(dir);
if (here != _here || _gatheredReach != FurReach) { _here = here; _gatheredReach = FurReach; GatherNear(here); } if (here != _here || _gatheredReach != FurReach) { _here = here; _gatheredReach = FurReach; GatherNear(here); }
_mpbUsed = 0; _mpbUsed = 0;
_drawn = 0;
PublishFurAxes(dir); PublishFurAxes(dir);
GeometryUtility.CalculateFrustumPlanes(cam, _frustum); GeometryUtility.CalculateFrustumPlanes(cam, _frustum);
@ -187,6 +270,13 @@ namespace GrassCutter
float arc = (s.c - dir).magnitude * Planet.Radius; float arc = (s.c - dir).magnitude * Planet.Radius;
float reachable = Mathf.Max(arc - s.radius, alt); float reachable = Mathf.Max(arc - s.radius, alt);
var mask = MowMap.TextureFor(s); var mask = MowMap.TextureFor(s);
// mown to the last blade: only the floor shows (the pile's shells and every plant are cut away in the
// shader anyway), one draw instead of up to six. Near the base that is most of what is in view.
if (mask == MowMap.Full && mask)
{
if (furMat) DrawPile(FurFloor, s, mask, true);
continue;
}
if (furMat) if (furMat)
{ {
var far = FurFar; var far = FurFar;
@ -214,8 +304,12 @@ namespace GrassCutter
if (furMat) if (furMat)
foreach (var s in _worked) foreach (var s in _worked)
if (GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) DrawPile(FurFloor, s, MowMap.TextureFor(s), true); if (GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) DrawPile(FurFloor, s, MowMap.TextureFor(s), true);
DrawBatches();
Draws = _mpbUsed + _drawn;
} }
int _drawn;
/// <summary>Every sector the rings can reach from here, the one underfoot first, and the worked ones further out.</summary> /// <summary>Every sector the rings can reach from here, the one underfoot first, and the worked ones further out.</summary>
void GatherNear(int here) void GatherNear(int here)
{ {
@ -276,6 +370,7 @@ namespace GrassCutter
/// <summary>The pile over a whole sector. onlyWorked: past the grass, just the floor where something was cut.</summary> /// <summary>The pile over a whole sector. onlyWorked: past the grass, just the floor where something was cut.</summary>
void DrawPile(Pile p, HexGrid.Sector s, Texture2D mask, bool onlyWorked) void DrawPile(Pile p, HexGrid.Sector s, Texture2D mask, bool onlyWorked)
{ {
if (Batched(p, s, mask, onlyWorked)) return;
var mpb = NextMpb(); var mpb = NextMpb();
SetSector(mpb, s, mask); SetSector(mpb, s, mask);
bool floor = p.shells == 1; bool floor = p.shells == 1;

View File

@ -60,6 +60,8 @@ namespace GrassCutter
public static IEnumerable<Mask> All => s_masks.Values; public static IEnumerable<Mask> All => s_masks.Values;
/// <summary>The map of a sector with nothing on it.</summary> /// <summary>The map of a sector with nothing on it.</summary>
public static Texture2D Blank => s_none; public static Texture2D Blank => s_none;
/// <summary>The look of a sector mown to the last blade (with no rock in it): nothing is left standing on it.</summary>
public static Texture2D Full => s_full;
public static int Started { get; private set; } public static int Started { get; private set; }
public static int Finished { get; private set; } public static int Finished { get; private set; }

View File

@ -82,7 +82,7 @@ MonoBehaviour:
m_UseFastSRGBLinearConversion: 0 m_UseFastSRGBLinearConversion: 0
m_SupportDataDrivenLensFlare: 1 m_SupportDataDrivenLensFlare: 1
m_SupportScreenSpaceLensFlare: 1 m_SupportScreenSpaceLensFlare: 1
m_GPUResidentDrawerMode: 1 m_GPUResidentDrawerMode: 0
m_SmallMeshScreenPercentage: 0 m_SmallMeshScreenPercentage: 0
m_ShadowSmallMeshScreenPercentages: {x: 0, y: 0, z: 0, w: 0} m_ShadowSmallMeshScreenPercentages: {x: 0, y: 0, z: 0, w: 0}
m_GPUResidentDrawerEnableOcclusionCullingInCameras: 0 m_GPUResidentDrawerEnableOcclusionCullingInCameras: 0
@ -132,7 +132,7 @@ MonoBehaviour:
m_PrefilterScreenCoord: 1 m_PrefilterScreenCoord: 1
m_PrefilterScreenSpaceIrradiance: 1 m_PrefilterScreenSpaceIrradiance: 1
m_PrefilterNativeRenderPass: 1 m_PrefilterNativeRenderPass: 1
m_PrefilterUseLegacyLightmaps: 1 m_PrefilterUseLegacyLightmaps: 0
m_PrefilterBicubicLightmapSampling: 1 m_PrefilterBicubicLightmapSampling: 1
m_PrefilterReflectionProbeRotation: 0 m_PrefilterReflectionProbeRotation: 0
m_PrefilterReflectionProbeBlending: 0 m_PrefilterReflectionProbeBlending: 0

View File

@ -37,9 +37,26 @@ Shader "GrassCutter/GrassFur"
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN
#pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH
#pragma multi_compile_fog #pragma multi_compile_fog
// many sectors in one draw: instance = sector * shells + shell, the sector's frame from a buffer. Only for
// sectors that share a mow map look (untouched, or mown to the last blade): on a small planet there are
// hundreds of them in view, and one draw each was most of a frame's CPU.
#pragma multi_compile_local _ GC_SECTOR_BUFFER
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
#if defined(GC_SECTOR_BUFFER)
struct GcSectorData { float4 c, e1, e2, salt, grid; float4 b[6]; };
StructuredBuffer<GcSectorData> _GcSectorBuf;
static GcSectorData gcS;
#define GC_SECTOR_C gcS.c
#define GC_SECTOR_E1 gcS.e1
#define GC_SECTOR_E2 gcS.e2
#define GC_SECTOR_SALT gcS.salt
#define GC_SECTOR_BORDER(k) gcS.b[k]
#define GC_GRID gcS.grid
#else
#define GC_GRID _GcGrid
#endif
#include "Planet.hlsl" #include "Planet.hlsl"
CBUFFER_START(UnityPerMaterial) CBUFFER_START(UnityPerMaterial)
@ -77,6 +94,7 @@ Shader "GrassCutter/GrassFur"
float4 data : TEXCOORD1; // x = shell 0..1, y = pile height here, z = big patch noise, w = edge fade float4 data : TEXCOORD1; // x = shell 0..1, y = pile height here, z = big patch noise, w = edge fade
float3 root : TEXCOORD2; // undisplaced world position (strand lookup) float3 root : TEXCOORD2; // undisplaced world position (strand lookup)
float fog : TEXCOORD3; float fog : TEXCOORD3;
nointerpolation uint sid : TEXCOORD6; // which sector of the draw
float2 plane : TEXCOORD4; // the sector's flat frame (mow map) float2 plane : TEXCOORD4; // the sector's flat frame (mow map)
float2 air : TEXCOORD5; // x = sun through the clouds, y = gust passing float2 air : TEXCOORD5; // x = sun through the clouds, y = gust passing
}; };
@ -84,18 +102,23 @@ Shader "GrassCutter/GrassFur"
Varyings vert(Attributes v) Varyings vert(Attributes v)
{ {
float shells = _GcShells.x; float shells = _GcShells.x;
uint sid = v.iid / (uint)shells;
uint shell = v.iid - sid * (uint)shells;
#if defined(GC_SECTOR_BUFFER)
gcS = _GcSectorBuf[sid];
#endif
// instance 0 is the top shell; a single shell is the solid floor under the strands // instance 0 is the top shell; a single shell is the solid floor under the strands
float t = shells > 1 ? 1 - (float)v.iid / (shells - 1) : 0; float t = shells > 1 ? 1 - (float)shell / (shells - 1) : 0;
float2 plane = v.positionOS.xz * _GcGrid.x; float2 plane = v.positionOS.xz * GC_GRID.x;
float3 up = normalize(_GcC.xyz * _GcPlanet.w + _GcE1.xyz * plane.x + _GcE2.xyz * plane.y); float3 up = normalize(GC_SECTOR_C.xyz * _GcPlanet.w + GC_SECTOR_E1.xyz * plane.x + GC_SECTOR_E2.xyz * plane.y);
float3 t1, t2; float3 t1, t2;
GcTangents(up, t1, t2); GcTangents(up, t1, t2);
// a grid cuts corners over bumps: each corner stands on the highest ground within half a cell of it, and a // a grid cuts corners over bumps: each corner stands on the highest ground within half a cell of it, and a
// little over, so no bump between corners comes up through the floor // little over, so no bump between corners comes up through the floor
float hs = _GcGrid.y * 0.5 / _GcPlanet.w; float hs = GC_GRID.y * 0.5 / _GcPlanet.w;
float ground = max(GcHeight(up), max(max(GcHeight(normalize(up + t1 * hs)), GcHeight(normalize(up - t1 * hs))), float ground = max(GcHeight(up), max(max(GcHeight(normalize(up + t1 * hs)), GcHeight(normalize(up - t1 * hs))),
max(GcHeight(normalize(up + t2 * hs)), GcHeight(normalize(up - t2 * hs))))); max(GcHeight(normalize(up + t2 * hs)), GcHeight(normalize(up - t2 * hs)))));
float3 root = _GcPlanet.xyz + up * (_GcPlanet.w + ground + 0.01 + _GcGrid.y * 0.012); float3 root = _GcPlanet.xyz + up * (_GcPlanet.w + ground + 0.01 + GC_GRID.y * 0.012);
float dist = length(root - _GcCam.xyz); float dist = length(root - _GcCam.xyz);
float fade = 1 - smoothstep(_GcFade.x, _GcFade.y, dist); float fade = 1 - smoothstep(_GcFade.x, _GcFade.y, dist);
@ -148,6 +171,7 @@ Shader "GrassCutter/GrassFur"
o.plane = plane; o.plane = plane;
o.fog = ComputeFogFactor(o.positionCS.z); o.fog = ComputeFogFactor(o.positionCS.z);
o.air = float2(GcCloudSun(root, tm), gust); o.air = float2(GcCloudSun(root, tm), gust);
o.sid = sid;
return o; return o;
} }
@ -161,8 +185,11 @@ Shader "GrassCutter/GrassFur"
if ((_GcShells.y > 0 && dist < _GcShells.y + e) || dist >= _GcShells.z + e) discard; if ((_GcShells.y > 0 && dist < _GcShells.y + e) || dist >= _GcShells.z + e) discard;
// a sector's square reaches past its borders: each pixel belongs to one sector // a sector's square reaches past its borders: each pixel belongs to one sector
#if defined(GC_SECTOR_BUFFER)
gcS = _GcSectorBuf[i.sid];
#endif
float3 d = normalize(i.root - _GcPlanet.xyz); float3 d = normalize(i.root - _GcPlanet.xyz);
for (int b = 0; b < 6; b++) if (dot(d, _GcBorders[b].xyz) > 0) discard; for (int b = 0; b < 6; b++) if (dot(d, GC_SECTOR_BORDER(b).xyz) > 0) discard;
float2 mask = GcMask(i.plane); float2 mask = GcMask(i.plane);
bool solid = t < 0.001; // the bottom of the pile: the floor everything stands on bool solid = t < 0.001; // the bottom of the pile: the floor everything stands on

View File

@ -47,6 +47,15 @@ float4 _GcC, _GcE1, _GcE2;
float4 _GcSalt; // xy = seed, z = flat frame metres to mow map uv float4 _GcSalt; // xy = seed, z = flat frame metres to mow map uv
float4 _GcBorders[6]; float4 _GcBorders[6];
// a shader that draws many sectors in one go defines these first (GrassFur: GC_SECTOR_BUFFER)
#ifndef GC_SECTOR_C
#define GC_SECTOR_C _GcC
#define GC_SECTOR_E1 _GcE1
#define GC_SECTOR_E2 _GcE2
#define GC_SECTOR_SALT _GcSalt
#define GC_SECTOR_BORDER(k) _GcBorders[k]
#endif
float GcHeight(float3 d) float GcHeight(float3 d)
{ {
float3 a = abs(d); float3 a = abs(d);
@ -82,22 +91,22 @@ void GcTangents(float3 up, out float3 t1, out float3 t2)
// this sector's mow map at a spot of its flat frame: r = cut (0..1), g = nothing grows here // this sector's mow map at a spot of its flat frame: r = cut (0..1), g = nothing grows here
float2 GcMask(float2 plane) float2 GcMask(float2 plane)
{ {
return SAMPLE_TEXTURE2D_LOD(_GcMaskTex, sampler_GcMaskTex, plane * _GcSalt.z + 0.5, 0).rg; return SAMPLE_TEXTURE2D_LOD(_GcMaskTex, sampler_GcMaskTex, plane * GC_SECTOR_SALT.z + 0.5, 0).rg;
} }
// how close a cut is: the map blurred over half a metre, so the grass beside a narrow strip can stand lower than the rest // how close a cut is: the map blurred over half a metre, so the grass beside a narrow strip can stand lower than the rest
float GcMaskNear(float2 plane) float GcMaskNear(float2 plane)
{ {
return SAMPLE_TEXTURE2D_LOD(_GcMaskTex, sampler_GcMaskTex, plane * _GcSalt.z + 0.5, 1.5).r; return SAMPLE_TEXTURE2D_LOD(_GcMaskTex, sampler_GcMaskTex, plane * GC_SECTOR_SALT.z + 0.5, 1.5).r;
} }
// A spot in the flat frame of this draw's sector, on the ball. Each strand belongs to exactly one sector: the one whose // A spot in the flat frame of this draw's sector, on the ball. Each strand belongs to exactly one sector: the one whose
// borders all lie ahead of it. edge = metres to the nearest of them. // borders all lie ahead of it. edge = metres to the nearest of them.
bool GcInSector(float2 plane, out float3 dir, out float edge) bool GcInSector(float2 plane, out float3 dir, out float edge)
{ {
dir = normalize(_GcC.xyz * _GcPlanet.w + _GcE1.xyz * plane.x + _GcE2.xyz * plane.y); dir = normalize(GC_SECTOR_C.xyz * _GcPlanet.w + GC_SECTOR_E1.xyz * plane.x + GC_SECTOR_E2.xyz * plane.y);
edge = 1e5; edge = 1e5;
for (int k = 0; k < 6; k++) edge = min(edge, -dot(dir, _GcBorders[k].xyz)); for (int k = 0; k < 6; k++) edge = min(edge, -dot(dir, GC_SECTOR_BORDER(k).xyz));
return edge >= 0; return edge >= 0;
} }