using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// Builds and updates the base's deck from the synced tile list; new tiles drop onto their stilts with a thump.
public class DeckManager : MonoBehaviour
{
public static DeckManager Instance { get; private set; }
public GameObject tileModel, ladderModel;
/// How far along each open edge from its middle the ladder hangs: clear of the intakes at the middle of
/// the edge tiles, in the opening the fence model leaves for it.
public const float LadderAt = 2.0f;
/// Deck-edge points that must stay open (the dock): the railing on that side of the tile is left out.
public Vector3[] gaps;
readonly Dictionary _views = new Dictionary();
/// Packed tile keys currently shown (the menu rig included): the grass never grows under them.
public IEnumerable TileKeys => _views.Keys;
void Awake()
{
Instance = this;
TeamState.TilesChanged += Rebuild;
}
void OnDestroy() { TeamState.TilesChanged -= Rebuild; }
void Update()
{
// the session ended: clear the deck so the menu shows the bare starter base in the meadow
if (!TeamState.Instance && _views.Count > 0 && !(NetSession.Instance && NetSession.Instance.Current == NetSession.State.InGame)) Clear();
if (!TeamState.Instance && _views.Count == 0) ShowMenuRig();
}
bool _menuRig;
/// Main menu backdrop: the 3x3 starter deck without anything on it.
void ShowMenuRig()
{
if (_menuRig) return;
_menuRig = true;
for (int x = -1; x <= 1; x++)
for (int z = -1; z <= 1; z++)
Make(TeamState.PackTile(x, z), false);
RefreshEdges(p => Mathf.Abs(TeamState.UnpackTile(p).x) <= 1 && Mathf.Abs(TeamState.UnpackTile(p).y) <= 1);
}
void Clear()
{
foreach (var v in _views.Values) if (v) Destroy(v.gameObject);
_views.Clear();
_menuRig = false;
}
void Rebuild()
{
var ts = TeamState.Instance;
if (!ts || ts.Tiles == null) return;
if (_menuRig) { Clear(); }
var want = new HashSet();
foreach (var t in ts.Tiles) want.Add(t);
var dead = new List();
foreach (var k in _views.Keys) if (!want.Contains(k)) dead.Add(k);
foreach (var k in dead) { if (_views[k]) Destroy(_views[k].gameObject); _views.Remove(k); }
bool animate = Time.timeSinceLevelLoad > 3f && _views.Count > 0;
foreach (var t in want) if (!_views.ContainsKey(t)) Make(t, animate);
RefreshEdges(p => want.Contains(p));
}
void RefreshEdges(System.Func has)
{
foreach (var kv in _views)
{
var c = TeamState.UnpackTile(kv.Key);
var ctr = TeamState.TileCenter(c.x, c.y);
float h = GameDefs.TileSize * 0.5f;
kv.Value.SetEdges(
!has(TeamState.PackTile(c.x, c.y + 1)) && !Gap(ctr + new Vector3(0f, 0f, h)),
!has(TeamState.PackTile(c.x, c.y - 1)) && !Gap(ctr + new Vector3(0f, 0f, -h)),
!has(TeamState.PackTile(c.x + 1, c.y)) && !Gap(ctr + new Vector3(h, 0f, 0f)),
!has(TeamState.PackTile(c.x - 1, c.y)) && !Gap(ctr + new Vector3(-h, 0f, 0f)));
}
}
bool Gap(Vector3 edgeMid)
{
if (gaps == null) return false;
foreach (var g in gaps) if (new Vector2(g.x - edgeMid.x, g.z - edgeMid.z).sqrMagnitude < 1f) return true;
return false;
}
void Make(int packed, bool animate)
{
var c = TeamState.UnpackTile(packed);
var go = new GameObject($"Deck_{c.x}_{c.y}");
go.transform.SetParent(transform, false);
go.transform.position = TeamState.TileCenter(c.x, c.y);
var v = go.AddComponent();
v.tile = c;
float S = GameDefs.TileSize;
if (tileModel)
{
var m = Instantiate(tileModel, go.transform);
m.transform.localPosition = Vector3.zero;
foreach (var t in m.GetComponentsInChildren(true))
{
if (t.name == "Rail_N") v.railN = t.gameObject;
else if (t.name == "Rail_S") v.railS = t.gameObject;
else if (t.name == "Rail_E") v.railE = t.gameObject;
else if (t.name == "Rail_W") v.railW = t.gameObject;
}
}
else
{
var p = GameObject.CreatePrimitive(PrimitiveType.Cube);
Destroy(p.GetComponent());
p.transform.SetParent(go.transform, false);
p.transform.localPosition = new Vector3(0, -0.22f, 0);
p.transform.localScale = new Vector3(S, 0.45f, S);
}
var slab = go.AddComponent();
slab.center = new Vector3(0f, -0.23f, 0f);
slab.size = new Vector3(S, 0.46f, S);
BoxCollider Rail(string n, Vector3 center, Vector3 size)
{
// Ignore Raycast: the rail still stops bodies but never blocks aiming the suction over it
var r = new GameObject(n) { layer = Physics.IgnoreRaycastLayer };
r.transform.SetParent(go.transform, false);
r.transform.localPosition = center;
var bc = r.AddComponent();
bc.size = size;
return bc;
}
float h = 1.0f, e = S * 0.5f - 0.12f;
// each railing stops either side of its ladder: the opening the fence model leaves there. The part of the rail
// beside the opening (the short piece out to the corner) is its own child of the main one, so SetEdges toggles both
float gapMid = LadderAt, gapHalf = 0.48f;
float lenA = S * 0.5f + gapMid - gapHalf, lenB = S * 0.5f - gapMid - gapHalf;
BoxCollider Split(string n, Vector3 normal, Vector3 along)
{
// `along` points from the corner at -S/2 to the one at +S/2; the ladder sits at +gapMid along it
var a = Rail(n, normal * e + Vector3.up * h * 0.5f + along * (-S * 0.5f + lenA * 0.5f), Abs(along * lenA) + Abs(normal) * 0.1f + Vector3.up * h);
var b = new GameObject(n + "_b") { layer = Physics.IgnoreRaycastLayer };
b.transform.SetParent(a.transform, false);
b.transform.position = a.transform.parent.TransformPoint(normal * e + Vector3.up * h * 0.5f + along * (S * 0.5f - lenB * 0.5f));
b.AddComponent().size = Abs(along * lenB) + Abs(normal) * 0.1f + Vector3.up * h;
return a;
}
static Vector3 Abs(Vector3 v) => new Vector3(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z));
// ladder spots: N at x = -LadderAt, S at x = +LadderAt, E at z = +LadderAt, W at z = -LadderAt
v.colN = Split("RailN", Vector3.forward, Vector3.left);
v.colS = Split("RailS", Vector3.back, Vector3.right);
v.colE = Split("RailE", Vector3.right, Vector3.forward);
v.colW = Split("RailW", Vector3.left, Vector3.back);
// ladders down to the meadow on every open edge (shown by SetEdges)
if (ladderModel)
{
var lr = new GameObject("Ladders").transform;
lr.SetParent(go.transform, false);
v.ladderRoot = lr;
void L(Vector3 pos, float yaw)
{
var l = Instantiate(ladderModel, lr);
l.transform.localPosition = pos;
l.transform.localRotation = Quaternion.Euler(0, yaw, 0) * ladderModel.transform.localRotation;
}
// front of the ladder model hangs toward -Y Blender = +Z Unity (yaw 0 → toward +Z)
L(new Vector3(-LadderAt, 0f, S * 0.5f), 0f);
L(new Vector3(LadderAt, 0f, -S * 0.5f), 180f);
L(new Vector3(S * 0.5f, 0f, LadderAt), 90f);
L(new Vector3(-S * 0.5f, 0f, -LadderAt), 270f);
}
foreach (var t in go.GetComponentsInChildren(true)) t.gameObject.isStatic = false;
_views[packed] = v;
if (animate)
{
var start = go.transform.position + Vector3.up * 6f;
var end = go.transform.position;
go.transform.position = start;
Tween.Run(go, 0.9f, k => { if (go) go.transform.position = Vector3.LerpUnclamped(start, end, k); }, Ease.OutBack);
Fx.Splash(end + Vector3.down * 1.1f, 2.2f);
Fx.Dust(end + Vector3.down * 1f, 1.2f, 18);
Sfx.PlayAt("splash_big", end, 1f, 0.8f);
Sfx.PlayAt("build_place", end, 1f, 0.7f);
CameraFx.Shake(0.2f);
}
}
public DeckTileView ViewAt(Vector3 world)
{
_views.TryGetValue(TeamState.PackTile(TeamState.TileOf(world.x), TeamState.TileOf(world.z)), out var v);
return v;
}
}
}