709 lines
32 KiB
C#
709 lines
32 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// The ship as a mobile bone pile. Skeleton_BoneShip.txt, sections 5.3-5.7.
|
|
///
|
|
/// Bone fragments are offered at the altar, twenty to a PLACE, and a place is paid for once and refills
|
|
/// itself for ever - exactly the bone pile's economy (SkeletonBonePileBehaviour), because it is the same
|
|
/// design: nothing is created or consumed when a skeleton falls, the place simply stands up again.
|
|
///
|
|
/// What is different is where the troops are. UNDERWAY they are DATA: a count per kind in the ship's own
|
|
/// ZDO ("aboard"), no creature, no AI, nothing to fall in the water. When the ship has been stopped for a
|
|
/// few seconds with land in reach they come ashore one at a time, real tamed skeletons that follow whoever
|
|
/// built the ship; when it moves off again, the ones that are following and close enough go back aboard,
|
|
/// one at a time, and become a number again.
|
|
///
|
|
/// The rest of the world is COUNTED, never tallied. A troop's ZDO carries the id of its ship; "how many
|
|
/// are out" is however many loaded troops carry it. A death, a despawn, a player killing his own
|
|
/// skeleton all correct themselves, as on the pile. The known price is the pile's too: a troop in an
|
|
/// unloaded zone is not counted, so its place can refill while it is away.
|
|
///
|
|
/// Troops are NOT bound to a point (no RaisedThrall anchor): a ship moves, and the anchor logic would
|
|
/// read the empty water it sailed from as a fallen station and wither them. They are bound to the ship by
|
|
/// id, and die with it. Only the owner of the ship's ZDO runs any of this.
|
|
/// </summary>
|
|
public class BoneShipRoster : MonoBehaviour
|
|
{
|
|
// ZDO keys, on the ship.
|
|
private const string KeyBones = "RoV_bshBones";
|
|
private const string KeySlotsMelee = "RoV_bshSlotsM";
|
|
private const string KeySlotsRanged = "RoV_bshSlotsR";
|
|
private const string KeyAboardMelee = "RoV_bshAbM";
|
|
private const string KeyAboardRanged = "RoV_bshAbR";
|
|
|
|
/// <summary>
|
|
/// Set when a troop that was told to go home boards a ship that is standing still: they have been
|
|
/// called back on purpose, so nobody should be sent straight out again. Cleared the moment the ship
|
|
/// moves, so the next stop lands the crew as usual.
|
|
/// </summary>
|
|
private const string KeyHold = "RoV_bshHold";
|
|
|
|
/// <summary>A recalled troop further than BoardRange but within this many metres is walked to the ship.</summary>
|
|
private const float RecallReach = 80f;
|
|
|
|
/// <summary>How many rowers should show: everyone aboard. Read by the rowers when they exist.</summary>
|
|
public const string KeyRowers = "RoV_bshRowers";
|
|
|
|
/// <summary>ZDO key on a TROOP: the id of the ship it belongs to.</summary>
|
|
public const string KeyShip = "RoV_bshShip";
|
|
|
|
// ─── Balance. Same numbers as the pile where the idea is the same. ───
|
|
private const float TickSeconds = 0.5f;
|
|
private const float DockedSeconds = 2.5f; // stopped this long before anyone comes ashore
|
|
private const float UnderwaySeconds = 1.0f; // moving this long before anyone goes back aboard
|
|
private const float StepSeconds = 0.8f; // one troop at a time, this far apart
|
|
private const float StillSpeed = 0.6f; // m/s: slower than this counts as stopped
|
|
private const float BoardRange = 20f; // decided with the orders: same as the pile's home check
|
|
private const float LandingBand = 10f; // how far past the hull to look for shore
|
|
private const float LandingMargin = 0.25f; // metres above the water for it to count as land
|
|
|
|
private ZNetView m_nview;
|
|
private Ship m_ship;
|
|
private Rigidbody m_body;
|
|
|
|
// The archers are not troops and are not counted with them: their own key, their own check.
|
|
private const float ArcherCheckSeconds = 2f;
|
|
private const float ArcherGraceSeconds = 4f; // a post whose registered archer is gone this long gets a new one
|
|
|
|
private float m_archerTimer;
|
|
private float[] m_postEmptyFor = new float[0];
|
|
|
|
private float m_stillTime;
|
|
private float m_movingTime;
|
|
private float m_stepTimer;
|
|
private float m_refillTimer;
|
|
private int m_deployIndex;
|
|
private bool m_toldNoShore;
|
|
|
|
private readonly List<Vector3> m_recentLandings = new List<Vector3>();
|
|
|
|
private void Awake()
|
|
{
|
|
m_nview = GetComponent<ZNetView>();
|
|
m_ship = GetComponent<Ship>();
|
|
m_body = GetComponent<Rigidbody>();
|
|
|
|
if (m_nview == null || m_nview.GetZDO() == null) return; // a placement ghost
|
|
|
|
m_nview.Register<string, int>("RoV_BshFeed", RPC_Feed);
|
|
|
|
WearNTear wear = GetComponent<WearNTear>();
|
|
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
|
|
|
|
InvokeRepeating("Tick", 2f, TickSeconds);
|
|
}
|
|
|
|
/// <summary>The altar's Switch, once the fittings have built it.</summary>
|
|
public void Bind(Switch altar)
|
|
{
|
|
if (altar == null) return;
|
|
altar.m_onUse = OnUse;
|
|
altar.m_onHover = Hover;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- interaction
|
|
|
|
// With an item in hand every outcome counts as handled, refusals included: false makes
|
|
// Humanoid.UseItem cover our own message with the generic one. Same as the pile.
|
|
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
|
|
{
|
|
return Use(user, item) || item != null;
|
|
}
|
|
|
|
private bool Use(Humanoid user, ItemDrop.ItemData item)
|
|
{
|
|
Player player = user as Player;
|
|
if (player == null || item == null) return false;
|
|
|
|
Inventory inventory = player.GetInventory();
|
|
if (inventory == null) return false;
|
|
|
|
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
|
|
if (prefabName != SkeletonBonePile.BonePrefab)
|
|
{
|
|
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
|
|
return false;
|
|
}
|
|
|
|
// Bone is measured in fragments, not places: what is left to buy, minus what is already part-paid
|
|
// towards the next place. Taken from the player only if the ship will actually keep it.
|
|
int room = (TotalCap() - PaidSlots()) * SkeletonBonePile.BonesPerSlot - m_nview.GetZDO().GetInt(KeyBones);
|
|
if (room <= 0)
|
|
{
|
|
player.Message(MessageHud.MessageType.Center, "$msg_itsfull");
|
|
return false;
|
|
}
|
|
|
|
int taken = Mathf.Min(Mathf.Max(1, item.m_stack), room);
|
|
player.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{taken}");
|
|
inventory.RemoveItem(item, taken);
|
|
|
|
m_nview.InvokeRPC("RoV_BshFeed", prefabName, taken);
|
|
return true;
|
|
}
|
|
|
|
private void RPC_Feed(long sender, string prefabName, int count)
|
|
{
|
|
if (!m_nview.IsOwner()) return;
|
|
if (prefabName != SkeletonBonePile.BonePrefab) return;
|
|
if (count < 1) count = 1;
|
|
|
|
int bones = m_nview.GetZDO().GetInt(KeyBones) + count;
|
|
|
|
// Melee places fill first, then the archers'. A loop, so a whole stack cannot overflow into bones
|
|
// that are never counted.
|
|
while (bones >= SkeletonBonePile.BonesPerSlot && PaidSlots() < TotalCap())
|
|
{
|
|
bones -= SkeletonBonePile.BonesPerSlot;
|
|
|
|
if (Slots(SkeletonBonePile.KindMelee) < MeleeCap()) SetSlots(SkeletonBonePile.KindMelee, Slots(SkeletonBonePile.KindMelee) + 1);
|
|
else SetSlots(SkeletonBonePile.KindRanged, Slots(SkeletonBonePile.KindRanged) + 1);
|
|
}
|
|
|
|
m_nview.GetZDO().Set(KeyBones, bones);
|
|
}
|
|
|
|
private string Hover()
|
|
{
|
|
int outM = CountDeployed(SkeletonBonePile.KindMelee);
|
|
int outR = CountDeployed(SkeletonBonePile.KindRanged);
|
|
int aboard = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
|
|
|
|
string body = ModText.Get("rov_hover_boneship_roster",
|
|
outM + Aboard(SkeletonBonePile.KindMelee), Slots(SkeletonBonePile.KindMelee), MeleeCap(),
|
|
outR + Aboard(SkeletonBonePile.KindRanged), Slots(SkeletonBonePile.KindRanged), RangedCap(),
|
|
aboard);
|
|
|
|
int bonesToward = m_nview.GetZDO().GetInt(KeyBones);
|
|
int placesLeft = TotalCap() - PaidSlots();
|
|
body += placesLeft > 0
|
|
? ModText.Get("rov_hover_skeleton_bone_toward_next_places", bonesToward, SkeletonBonePile.BonesPerSlot, placesLeft)
|
|
: ModText.Get("rov_hover_skeleton_every_place_bought");
|
|
|
|
if (m_refillTimer > 0f)
|
|
{
|
|
int left = Mathf.Max(1, Mathf.CeilToInt(SkeletonBonePile.RespawnSeconds - m_refillTimer));
|
|
body += ModText.Get("rov_hover_skeleton_next_rises_s", left);
|
|
}
|
|
|
|
body += ModText.Get("rov_hover_boneship_bone_hand");
|
|
return Localization.instance.Localize($"{BoneShip.AltarName} ({body})");
|
|
}
|
|
|
|
// ---------------------------------------------------------------- the tick
|
|
|
|
private void Tick()
|
|
{
|
|
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
|
|
if (m_ship == null) return;
|
|
|
|
Refill();
|
|
PublishRowers();
|
|
|
|
m_archerTimer += TickSeconds;
|
|
if (m_archerTimer >= ArcherCheckSeconds)
|
|
{
|
|
TickArchers(m_archerTimer);
|
|
m_archerTimer = 0f;
|
|
}
|
|
|
|
bool stopped = m_ship.GetSpeedSetting() == Ship.Speed.Stop &&
|
|
(m_body == null || m_body.velocity.magnitude < StillSpeed);
|
|
|
|
if (stopped)
|
|
{
|
|
m_stillTime += TickSeconds;
|
|
m_movingTime = 0f;
|
|
}
|
|
else
|
|
{
|
|
m_movingTime += TickSeconds;
|
|
m_stillTime = 0f;
|
|
m_toldNoShore = false;
|
|
m_recentLandings.Clear();
|
|
}
|
|
|
|
// Moving off ends any hold: the next stop lands the crew as usual.
|
|
if (!stopped && m_movingTime >= UnderwaySeconds && m_nview.GetZDO().GetBool(KeyHold, false))
|
|
{
|
|
m_nview.GetZDO().Set(KeyHold, false);
|
|
}
|
|
|
|
WalkRecalled();
|
|
|
|
m_stepTimer -= TickSeconds;
|
|
if (m_stepTimer > 0f) return;
|
|
|
|
// A troop sent home boards whether the ship is moving or not; the ones merely following only
|
|
// when it is underway. Whichever is first takes the step.
|
|
bool underway = !stopped && m_movingTime >= UnderwaySeconds;
|
|
string boarded = BoardOne(underway);
|
|
if (boarded != null)
|
|
{
|
|
m_stepTimer = StepSeconds;
|
|
|
|
// Anyone who boards while the ship is standing still came aboard on purpose - called back, or
|
|
// walked up the plank - and must not be sent straight out again. Held until the ship moves.
|
|
if (stopped) m_nview.GetZDO().Set(KeyHold, true);
|
|
return;
|
|
}
|
|
|
|
if (stopped && m_stillTime >= DockedSeconds && !m_nview.GetZDO().GetBool(KeyHold, false))
|
|
{
|
|
if (TryDeploy()) m_stepTimer = StepSeconds;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// A paid place with nobody in it - not aboard and not standing somewhere - fills after a while, as
|
|
/// the pile's does. Melee first. It fills ABOARD, so on a stopped ship it is then the next to come
|
|
/// ashore by the ordinary route.
|
|
/// </summary>
|
|
private void Refill()
|
|
{
|
|
string empty = FirstEmptyKind();
|
|
if (empty == null)
|
|
{
|
|
m_refillTimer = 0f;
|
|
return;
|
|
}
|
|
|
|
m_refillTimer += TickSeconds;
|
|
if (m_refillTimer < SkeletonBonePile.RespawnSeconds) return;
|
|
m_refillTimer = 0f;
|
|
|
|
SetAboard(empty, Aboard(empty) + 1);
|
|
}
|
|
|
|
private string FirstEmptyKind()
|
|
{
|
|
if (Slots(SkeletonBonePile.KindMelee) - CountDeployed(SkeletonBonePile.KindMelee) - Aboard(SkeletonBonePile.KindMelee) > 0)
|
|
return SkeletonBonePile.KindMelee;
|
|
if (Slots(SkeletonBonePile.KindRanged) - CountDeployed(SkeletonBonePile.KindRanged) - Aboard(SkeletonBonePile.KindRanged) > 0)
|
|
return SkeletonBonePile.KindRanged;
|
|
return null;
|
|
}
|
|
|
|
private void PublishRowers()
|
|
{
|
|
int rowers = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
|
|
if (m_nview.GetZDO().GetInt(KeyRowers, -1) != rowers) m_nview.GetZDO().Set(KeyRowers, rowers);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- coming ashore
|
|
|
|
private bool TryDeploy()
|
|
{
|
|
int melee = Aboard(SkeletonBonePile.KindMelee);
|
|
int ranged = Aboard(SkeletonBonePile.KindRanged);
|
|
if (melee + ranged == 0) return false;
|
|
|
|
Vector3 landing;
|
|
if (!FindLanding(out landing))
|
|
{
|
|
// Open water or a cliff: they stay at the oars. Said once per stop, to whoever is looking.
|
|
if (!m_toldNoShore && Player.m_localPlayer != null &&
|
|
Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 40f)
|
|
{
|
|
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_no_shore"));
|
|
}
|
|
m_toldNoShore = true;
|
|
return false;
|
|
}
|
|
|
|
// Whichever kind has more waiting goes first, so the line comes ashore mixed, not all spears then all bows.
|
|
string kind = melee >= ranged ? SkeletonBonePile.KindMelee : SkeletonBonePile.KindRanged;
|
|
string prefabName = kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.ThrallRangedName : SkeletonBonePile.ThrallMeleeName;
|
|
|
|
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
|
|
if (prefab == null)
|
|
{
|
|
Jotunn.Logger.LogWarning($"[BoneShip] No '{prefabName}' in ZNetScene; nothing can come ashore.");
|
|
return false;
|
|
}
|
|
|
|
GameObject spawned = Instantiate(prefab, landing, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
|
|
|
|
// Tamed, so it never turns on its master: the two calls RaisedThrall.Bind makes, without the anchor.
|
|
MonsterAI ai = spawned.GetComponent<MonsterAI>();
|
|
if (ai != null) ai.MakeTame();
|
|
Character character = spawned.GetComponent<Character>();
|
|
if (character != null) character.SetTamed(true);
|
|
|
|
ZNetView troopView = spawned.GetComponent<ZNetView>();
|
|
if (troopView != null && troopView.GetZDO() != null) troopView.GetZDO().Set(KeyShip, m_nview.GetZDO().m_uid);
|
|
|
|
// Out and following their master. NOT through RaisedThrall.SetFollowing: that refuses anyone who is
|
|
// not a Skeleton, and the ship is open to every race - a non-Skeleton's crew would come ashore, stand
|
|
// there, and never be able to come back aboard, because boarding is for the ones that follow. So the
|
|
// follow target is set directly, as the ship's own right.
|
|
Player master = Master();
|
|
if (ai != null && master != null) ai.SetFollowTarget(master.gameObject);
|
|
|
|
SetAboard(kind, Aboard(kind) - 1);
|
|
m_recentLandings.Add(landing);
|
|
if (m_recentLandings.Count > 12) m_recentLandings.RemoveAt(0);
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Dry land near the hull. Looks on rings around the ship, nearest first, from just past the hull out
|
|
/// to LandingBand metres beyond it; a point is land if the terrain there is above the water. The first
|
|
/// ring angle moves on with each troop, and a point near one already used is skipped, so they do not
|
|
/// all stack on one spot.
|
|
/// </summary>
|
|
private bool FindLanding(out Vector3 landing)
|
|
{
|
|
landing = Vector3.zero;
|
|
if (ZoneSystem.instance == null) return false;
|
|
|
|
float hull = Mathf.Max(BoneShip.HalfLengthOf(this), 4f);
|
|
float water = ZoneSystem.instance.m_waterLevel + LandingMargin;
|
|
|
|
for (float radius = hull + 1.5f; radius <= hull + 1.5f + LandingBand; radius += 1.5f)
|
|
{
|
|
for (int step = 0; step < 24; step++)
|
|
{
|
|
float angle = (m_deployIndex * 47f + step * 15f) * Mathf.Deg2Rad;
|
|
Vector3 point = transform.position + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
|
|
|
|
float ground = ZoneSystem.instance.GetGroundHeight(point);
|
|
if (ground < water) continue;
|
|
if (NearRecent(point)) continue;
|
|
|
|
landing = new Vector3(point.x, ground + 0.5f, point.z);
|
|
m_deployIndex++;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private bool NearRecent(Vector3 point)
|
|
{
|
|
foreach (Vector3 used in m_recentLandings)
|
|
{
|
|
Vector3 d = used - point;
|
|
d.y = 0f;
|
|
if (d.sqrMagnitude < 1.4f * 1.4f) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- going back aboard
|
|
|
|
/// <summary>
|
|
/// Takes ONE troop back aboard: it vanishes and the count goes up. Which: the nearest, within
|
|
/// BoardRange, that was SENT HOME (a "go home" order, the troop's RoV_bshRecall flag) - or, when the
|
|
/// ship is underway, that is following its master. Ones told to wait, and followers when the ship is
|
|
/// standing still, stay where they are: an outpost, still counted, still this ship's.
|
|
/// Returns "recalled" or "following" for what it took, null for nothing.
|
|
/// </summary>
|
|
private string BoardOne(bool underway)
|
|
{
|
|
Player master = Master();
|
|
|
|
Character nearest = null;
|
|
RaisedThrall nearestThrall = null;
|
|
bool nearestRecalled = false;
|
|
float best = BoardRange * BoardRange;
|
|
|
|
foreach (Character character in Character.GetAllCharacters())
|
|
{
|
|
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
|
|
|
|
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
|
|
if (thrall == null) continue;
|
|
|
|
bool recalled = IsRecalled(character);
|
|
|
|
// A troop that follows its master and has WALKED ONTO THE DECK is aboard, whatever the ship is
|
|
// doing: standing about on the planks as a creature is not what a crew is. The first version
|
|
// only took followers once the ship was underway, so stepping off and back on left the crew
|
|
// standing on deck, never at the oars, until the ship moved.
|
|
bool followingMaster = master != null && thrall.IsFollowing(master);
|
|
bool following = followingMaster && (underway || OnDeck(character));
|
|
if (!recalled && !following) continue;
|
|
|
|
float distance = (character.transform.position - transform.position).sqrMagnitude;
|
|
if (distance >= best) continue;
|
|
|
|
best = distance;
|
|
nearest = character;
|
|
nearestThrall = thrall;
|
|
nearestRecalled = recalled;
|
|
}
|
|
|
|
if (nearest == null) return null;
|
|
|
|
string kind = nearestThrall.Kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
|
|
|
|
ZNetView troopView = nearest.GetComponent<ZNetView>();
|
|
if (troopView != null) troopView.ClaimOwnership(); // it may belong to another client's zone
|
|
ZNetScene.instance.Destroy(nearest.gameObject);
|
|
|
|
SetAboard(kind, Aboard(kind) + 1);
|
|
return nearestRecalled ? "recalled" : "following";
|
|
}
|
|
|
|
/// <summary>
|
|
/// A recalled troop out of boarding range walks to the ship: its patrol point is pinned on the ship
|
|
/// every tick, because the ship may be moving. Past RecallReach it is not chased - out of earshot.
|
|
/// </summary>
|
|
private void WalkRecalled()
|
|
{
|
|
foreach (Character character in Character.GetAllCharacters())
|
|
{
|
|
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
|
|
if (!IsRecalled(character)) continue;
|
|
|
|
float distance = Vector3.Distance(character.transform.position, transform.position);
|
|
if (distance <= BoardRange || distance > RecallReach) continue;
|
|
|
|
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
|
|
if (thrall != null) thrall.WalkTo(transform.position);
|
|
}
|
|
}
|
|
|
|
/// <summary>Standing inside the hull's boarding volume: the same box the game uses to decide who is aboard.</summary>
|
|
private bool OnDeck(Character character)
|
|
{
|
|
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
|
|
Bounds hull;
|
|
if (fittings == null || !fittings.TryHullExtent(out hull)) return false;
|
|
|
|
return hull.Contains(transform.InverseTransformPoint(character.transform.position));
|
|
}
|
|
|
|
private static bool IsRecalled(Character character)
|
|
{
|
|
ZNetView view = character.GetComponent<ZNetView>();
|
|
return view != null && view.GetZDO() != null && view.GetZDO().GetBool(RaisedThrall.KeyRecall, false);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- the archers
|
|
|
|
/// <summary>
|
|
/// Keeps the ship's archers standing. Counted from the world, like the troops: a loaded archer
|
|
/// carrying this ship's id and a post number holds that post. A post nobody holds for a while gets a
|
|
/// new archer - not at once, because after a reload the ship is loaded a moment before the archers
|
|
/// that were standing on it, and spawning then would double them. A second archer found on a post
|
|
/// that is already held is removed.
|
|
/// </summary>
|
|
private void TickArchers(float elapsed)
|
|
{
|
|
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
|
|
if (fittings == null || fittings.ArcherPosts == null) return; // the hull is not measured yet
|
|
|
|
int posts = fittings.ArcherPosts.Count;
|
|
if (m_postEmptyFor.Length != posts) m_postEmptyFor = new float[posts];
|
|
|
|
ZDO shipZdo = m_nview.GetZDO();
|
|
ZDOID mine = shipZdo.m_uid;
|
|
|
|
// ---- 1. the archers that are in the world now: adopt the first of each post, remove the rest.
|
|
//
|
|
// The ship keeps a REGISTER of who holds each post (its own ZDO, one id per post). The first
|
|
// version only counted the archers it could see and spawned one for any post it saw nobody on -
|
|
// and "can see" is only what is loaded, so a ship that woke before its archers did, or a post
|
|
// whose archer sat in a zone the owner had not loaded, got a second archer on top of the first,
|
|
// again at every reload. The register does not depend on what is loaded. Archers made before the
|
|
// register existed have no entry: the first found is adopted, the others are the duplicates.
|
|
foreach (Character character in Character.GetAllCharacters())
|
|
{
|
|
if (character == null) continue;
|
|
|
|
ZNetView view = character.GetComponent<ZNetView>();
|
|
if (view == null || view.GetZDO() == null) continue;
|
|
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
|
|
|
|
int post = view.GetZDO().GetInt(ShipMount.KeyArcherPost, -1);
|
|
if (post < 0 || post >= posts)
|
|
{
|
|
RemoveArcher(character, view, "a post this ship no longer has");
|
|
continue;
|
|
}
|
|
|
|
ZDOID registered = shipZdo.GetZDOID(SlotKey(post));
|
|
ZDOID self = view.GetZDO().m_uid;
|
|
|
|
if (registered == ZDOID.None) shipZdo.Set(SlotKey(post), self);
|
|
else if (registered != self) RemoveArcher(character, view, "a duplicate on post " + post);
|
|
}
|
|
|
|
// ---- 2. posts whose registered archer is gone: a new one, after a short grace.
|
|
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(BoneShipArcher.Name) : null;
|
|
|
|
for (int i = 0; i < posts; i++)
|
|
{
|
|
ZDOID registered = shipZdo.GetZDOID(SlotKey(i));
|
|
bool exists = registered != ZDOID.None && ZDOMan.instance != null && ZDOMan.instance.GetZDO(registered) != null;
|
|
|
|
if (exists)
|
|
{
|
|
m_postEmptyFor[i] = 0f;
|
|
continue;
|
|
}
|
|
|
|
m_postEmptyFor[i] += elapsed;
|
|
if (m_postEmptyFor[i] < ArcherGraceSeconds) continue;
|
|
m_postEmptyFor[i] = 0f;
|
|
|
|
if (prefab == null)
|
|
{
|
|
Jotunn.Logger.LogWarning($"[BoneShip] No '{BoneShipArcher.Name}' in ZNetScene; the ship has no archer at post {i}.");
|
|
continue;
|
|
}
|
|
|
|
SpawnArcher(prefab, i, fittings.ArcherPosts[i]);
|
|
}
|
|
}
|
|
|
|
private static string SlotKey(int post) => "RoV_bshArcher" + post;
|
|
|
|
private void RemoveArcher(Character character, ZNetView view, string why)
|
|
{
|
|
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': removing an archer - {why}.");
|
|
view.ClaimOwnership();
|
|
ZNetScene.instance.Destroy(character.gameObject);
|
|
}
|
|
|
|
private void SpawnArcher(GameObject prefab, int post, BoneShipFittings.ArcherPost at)
|
|
{
|
|
Vector3 world = transform.TransformPoint(at.Local);
|
|
GameObject archer = Instantiate(prefab, world, transform.rotation);
|
|
|
|
// The ship's id and the place on it go into the archer's own ZDO at once, before its mount first
|
|
// runs, so it knows where it stands from its first physics step - and again after any reload.
|
|
ZNetView view = archer.GetComponent<ZNetView>();
|
|
if (view != null && view.GetZDO() != null)
|
|
{
|
|
ZDO zdo = view.GetZDO();
|
|
zdo.Set(ShipMount.KeyArcherShip, m_nview.GetZDO().m_uid);
|
|
zdo.Set(ShipMount.KeyArcherPoint, at.Local);
|
|
zdo.Set(ShipMount.KeyArcherBust, at.Bust);
|
|
zdo.Set(ShipMount.KeyArcherPost, post);
|
|
|
|
// Signed into the ship's register straight away, so the very next check already knows.
|
|
m_nview.GetZDO().Set(SlotKey(post), zdo.m_uid);
|
|
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer raised on post {post} at local " +
|
|
$"({at.Local.x:F2}, {at.Local.y:F2}, {at.Local.z:F2}).");
|
|
}
|
|
|
|
// Tamed, so it never turns on whoever is aboard: the two calls the sentry's seed makes.
|
|
MonsterAI ai = archer.GetComponent<MonsterAI>();
|
|
if (ai != null) ai.MakeTame();
|
|
Character character = archer.GetComponent<Character>();
|
|
if (character != null) character.SetTamed(true);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- the ship falls
|
|
|
|
/// <summary>
|
|
/// The ship going down takes its troops with it, those that are loaded. Same as the pile's immediate
|
|
/// off switch: a garrison that refills for free needs something that ends it. Any in an unloaded zone
|
|
/// outlive the ship - the known gap, noted in the design.
|
|
/// </summary>
|
|
private void OnDestroyed()
|
|
{
|
|
if (m_nview == null || !m_nview.IsOwner()) return;
|
|
|
|
int lost = 0;
|
|
foreach (Character character in Character.GetAllCharacters())
|
|
{
|
|
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
|
|
|
|
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
|
|
if (thrall != null) thrall.Kill();
|
|
lost++;
|
|
}
|
|
|
|
// The archers go down with it as well; they are not counted among the troops that are lost.
|
|
ZDOID mine = m_nview.GetZDO().m_uid;
|
|
foreach (Character character in Character.GetAllCharacters())
|
|
{
|
|
if (character == null) continue;
|
|
|
|
ZNetView view = character.GetComponent<ZNetView>();
|
|
if (view == null || view.GetZDO() == null) continue;
|
|
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
|
|
|
|
view.ClaimOwnership();
|
|
ZNetScene.instance.Destroy(character.gameObject);
|
|
}
|
|
|
|
if (lost > 0 && Player.m_localPlayer != null)
|
|
{
|
|
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_sunk", lost));
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- state
|
|
|
|
private Player Master()
|
|
{
|
|
Piece piece = GetComponent<Piece>();
|
|
long creator = piece != null ? piece.GetCreator() : 0L;
|
|
|
|
if (creator != 0L)
|
|
{
|
|
foreach (Player player in Player.GetAllPlayers())
|
|
{
|
|
if (player != null && player.GetPlayerID() == creator) return player;
|
|
}
|
|
}
|
|
|
|
// Its builder is not here: whoever is nearest, so a ship found abandoned is still crewed.
|
|
return Player.GetClosestPlayer(transform.position, 40f);
|
|
}
|
|
|
|
private bool BelongsHere(Character character)
|
|
{
|
|
ZNetView view = character.GetComponent<ZNetView>();
|
|
if (view == null || view.GetZDO() == null) return false;
|
|
return view.GetZDO().GetZDOID(KeyShip) == m_nview.GetZDO().m_uid;
|
|
}
|
|
|
|
private int CountDeployed(string kind)
|
|
{
|
|
int count = 0;
|
|
foreach (Character character in Character.GetAllCharacters())
|
|
{
|
|
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
|
|
|
|
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
|
|
string troopKind = thrall != null && thrall.Kind == SkeletonBonePile.KindRanged
|
|
? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
|
|
if (troopKind == kind) count++;
|
|
}
|
|
return count;
|
|
}
|
|
|
|
private int Slots(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee) : 0;
|
|
|
|
private void SetSlots(string kind, int value)
|
|
{
|
|
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee, Mathf.Max(0, value));
|
|
}
|
|
|
|
private int Aboard(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee) : 0;
|
|
|
|
private void SetAboard(string kind, int value)
|
|
{
|
|
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee, Mathf.Max(0, value));
|
|
}
|
|
|
|
private int PaidSlots() => Slots(SkeletonBonePile.KindMelee) + Slots(SkeletonBonePile.KindRanged);
|
|
|
|
private int MeleeCap() => BoneShip.MeleeCapOf(this);
|
|
|
|
private int RangedCap() => BoneShip.RangedCapOf(this);
|
|
|
|
private int TotalCap() => MeleeCap() + RangedCap();
|
|
}
|
|
}
|