using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// Everyone sees the same wires: a sagging line from each pole to what it feeds. They're for show, the network doesn't need them.
public class PowerWires : MonoBehaviour
{
const int Points = 9, MostPerPole = 6;
const float Sag = 0.05f;
readonly List _lines = new List();
readonly List<(float dist, Vector3 at, Transform pole)> _ends = new List<(float, Vector3, Transform)>();
readonly Vector3[] _curve = new Vector3[Points];
Material _mat;
bool _dirty = true;
void OnEnable() => BuildPiece.PiecesChanged += Dirty;
void OnDisable() => BuildPiece.PiecesChanged -= Dirty;
void Dirty() => _dirty = true;
void LateUpdate()
{
if (!_dirty || !AssetBank.I) return;
_dirty = false;
if (!_mat) _mat = AssetBank.I.Mat("M_Rubber");
int used = 0;
foreach (var n in PowerNode.All)
{
if (!(n is PowerPole)) continue;
_ends.Clear();
var from = Tie(n.transform, n.WireHeight);
foreach (var o in PowerNode.All)
{
if (!o || o == n || !PowerGrid.Joined(n, o)) continue;
// two poles share one wire: the first of them draws it
if (o is PowerPole && PowerNode.All.IndexOf(o) < PowerNode.All.IndexOf(n)) continue;
_ends.Add((Vector3.Distance(from, o.transform.position), Tie(o.transform, o.WireHeight), o is PowerPole ? o.transform : null));
}
foreach (var m in Machine.All)
if (m && PowerGrid.Reaches(n, m.transform.position)) _ends.Add((Vector3.Distance(from, m.transform.position), Tie(m.transform, 1.5f), null));
_ends.Sort((a, b) => a.dist.CompareTo(b.dist));
for (int i = 0; i < _ends.Count && i < MostPerPole; i++)
{
var far = _ends[i];
if (!far.pole) { Hang(used++, from, far.at); continue; }
// pole to pole: a pair of conductors, one off each end of the crossarm
var across = Vector3.Cross(Planet.Up(from), far.at - from);
var here = Arm(n.transform, across);
var there = Arm(far.pole, across);
Hang(used++, from + here, far.at + there);
Hang(used++, from - here, far.at - there);
}
}
for (int i = used; i < _lines.Count; i++) _lines[i].enabled = false;
}
static Vector3 Tie(Transform t, float height) => t.position + t.up * height;
static Vector3 Arm(Transform pole, Vector3 across)
{
var arm = pole.right * GameDefs.PoleArm;
return Vector3.Dot(arm, across) < 0f ? -arm : arm;
}
void Hang(int i, Vector3 a, Vector3 b)
{
if (i >= _lines.Count)
{
var go = new GameObject("Wire");
go.transform.SetParent(transform, false);
var made = go.AddComponent();
made.sharedMaterial = _mat;
made.widthMultiplier = 0.035f;
made.positionCount = Points;
made.numCapVertices = 0;
made.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
_lines.Add(made);
}
var line = _lines[i];
line.enabled = true;
float sag = Vector3.Distance(a, b) * Sag;
var up = Planet.Up(a);
for (int k = 0; k < Points; k++)
{
float t = k / (Points - 1f);
_curve[k] = Vector3.Lerp(a, b, t) - up * (sag * 4f * t * (1f - t));
}
line.SetPositions(_curve);
}
}
}