Compare commits

..

306 commits

Author SHA1 Message Date
b1f3a6d666 Merge remote-tracking branch 'origin/main' into localisation 2026-11-13 17:08:48 +01:00
2f8f399b43 docs: v1.6.11 changelog and version bump, debug key in its own config section; Dagaz credit 2026-11-13 17:08:33 +01:00
eb793cfb57 Merge branch 'debug-config-section' 2026-11-13 17:07:45 +01:00
0668d59a9b feat(debug): Debug config section; debug key rebindable and off by default; Log Form Hits moved from Fenrir; dead Skeleton F8 helpers removed
Requested by Dagaz.
2026-11-13 17:07:45 +01:00
555830351d Merge remote-tracking branch 'origin/main' into localisation 2026-11-11 18:43:56 +01:00
b431bb9d1f docs: v1.6.10 adds the Skrid roof fix; Joacwoo credit 2026-11-11 18:43:43 +01:00
a5d3b54dd6 Merge branch 'fix-alfar-blink-floor' 2026-11-11 18:43:42 +01:00
ffed6fd33e fix(alfar): Skrid lands on the floor under its end, never on a roof; cancelled in a dungeon with no floor 2026-11-11 18:43:42 +01:00
1954867385 Merge remote-tracking branch 'origin/main' into localisation 2026-11-11 15:57:25 +01:00
088d969323 docs: v1.6.10 changelog and version bump, Skadi drake forms hit the dummy, Ravager damage on Unarmed, Alfar hair flash 2026-11-11 15:57:02 +01:00
91f2a8bc0a Merge branch 'fix-alfar-hair-flicker' 2026-11-11 15:56:01 +01:00
0b90201368 Merge branch 'fix-form-attacks' 2026-11-11 15:56:01 +01:00
caaa233392 fix(forms): Skadi melee hits the training dummy on the clip's hit frame, Ravager attacks get Brute sounds and scale with Unarmed 2026-11-11 15:56:01 +01:00
842af2fd4f fix(alfar): hair and beard never attach, no flash on equipment change 2026-11-11 14:57:38 +01:00
b4a6432617 Merge remote-tracking branch 'origin/main' into localisation 2026-11-06 21:45:31 +01:00
2d865f5bb0 docs: v1.6.9 changelog and version bump, hitting your own faction, grudges in multiplayer, race attacks train their skills 2026-11-06 21:45:11 +01:00
6ddca72144 Merge branch 'fix-grudge-multiplayer' 2026-11-06 21:28:13 +01:00
7a618936f2 fix(factions): grudges survive an owner change and reach kin owned elsewhere
The grudge was a dictionary in the owner's memory: when another client
took over the creature mid-fight, its copy made peace on the next
UpdateTarget. Grudge spreads to kin also skipped kin owned by another
client. The grudge now lives on the creature's ZDO (attacker ZDOID and
an end time in network time), written only by the owner; kin owned
elsewhere get an RPC that their owner handles.
2026-11-06 21:28:13 +01:00
811e4cac34 Merge branch 'fix-aswid-puke-stomach' 2026-11-06 21:21:20 +01:00
cae18b440d Merge branch 'fix-faction-grudge' 2026-11-06 21:21:20 +01:00
c1c1c76360 fix(aswid): pukeberries empty the fourth stomach too
SE_Puke calls RemoveOneFood, which only picks from vanilla's three
slots, so the Aswid's fourth meal survived the berries. It now joins
the same random draw, the way the Trol's extra slots do.
2026-11-06 21:21:20 +01:00
4ee98d90cb fix(factions): the player can strike allied creatures again
Valheim 1.0's hit filters (Attack melee/area, Projectile OnHit/DoAOE/
IsValidTarget, Aoe.ShouldHit) skip a target when BaseAI.IsEnemy says
false and the attacker is a player without PvP. The truce said false
for every allied creature, so the blow passed through: no damage, no
grudge, nothing for kin to join. RaceGrudge.StrikeScope opens a scope
around those six methods in which both truce patches stand down for
the player's own hit; everything else keeps the truce.
2026-11-06 21:21:20 +01:00
fdc5d9fab7 Merge branch 'fix-form-skill-xp' 2026-11-06 21:21:11 +01:00
d9bca1934f fix(skills): hand-built attacks level the skill they scale with
Form attacks and powers called Damage directly, and vanilla only raises
a skill inside Attack and Projectile.OnHit, so the skill never moved.
FormMelee.RaiseSkill pays once per swing or tick that hit a creature.

- Fenrir forms' claws and bites: Unarmed; Cultist fire: Elemental Magic
- Skadi drake melee and Trenta stomp: Unarmed
- Aswid aura: Blood Magic, 0.1 per second like the Frost Aura
- Alfar Geisli and Ljosstorm: Elemental Magic; Sameining pulse 0.1/s
- Trenta Purple Rain scales with Blood Magic (two new bonus keys) and
  levels it once per cast that reaches someone besides the caster
2026-11-06 21:21:11 +01:00
b8ddcfd1d5 Merge remote-tracking branch 'origin/main' into localisation 2026-11-05 13:21:49 +01:00
eeebfd4d06 docs: v1.6.8 New-in block mentions the faction changes 2026-11-05 13:21:41 +01:00
064708d844 Merge branch 'feat-faction-group-grudge'
# Conflicts:
#	README.md
2026-11-05 13:05:45 +01:00
0008e0b34e Merge branch 'fix-faction-new-skeletons' 2026-11-05 13:05:34 +01:00
5530f7dc3d feat(factions): optional group grudge, kin within 20 m join the fight
Joacwoo's request. With "Grudge spreads to kin" on (off by default),
hitting a creature at peace with you gives the same grudge to every
creature of that faction within "Grudge spread radius" (20 m) and
alerts them, like vanilla's Dvergr with a human. Only creatures whose
AI runs on this machine are told, since that is where a grudge is
read.
2026-11-05 13:05:03 +01:00
bb1769b876 fix(factions): Valheim 1.0's regional skeletons join the swamp faction
Valheim 1.0 places Skeleton_Meadows, _Swamps, _Mountains and
_DeepNorth (and the _noarcher twins) instead of the plain Skeleton,
and none of them were in the faction lists, so they attacked the
races the old skeletons left alone. Added to the swamp faction set,
the Skeleton's own enemy check and the faction shop map, with
Skeleton_NoArcher in the shop map too. Reported by Joacwoo.
2026-11-05 12:59:57 +01:00
2b1064025a Merge remote-tracking branch 'origin/main' into localisation 2026-11-05 12:44:24 +01:00
ceb0d0e35a docs: v1.6.8 changelog and version bump, Skeleton Mortal Habits, bat combat lock and cheap Dvergar marble 2026-11-05 12:44:03 +01:00
446fcc7327 Merge branch 'feat-dvergar-cheap-pieces' 2026-11-05 12:42:22 +01:00
a538e3d5e4 Merge branch 'main' into feat-dvergar-cheap-pieces 2026-11-05 12:15:13 +01:00
19281e31ce Merge branch 'feat-skeleton-mortal-options' 2026-11-05 11:07:18 +01:00
2ac22d7d86 Merge branch 'feat-aswid-bat-combat-lock' 2026-11-05 11:07:17 +01:00
71721caa8d feat(aswid): bat form waits until 2.5 s after the last hit
An Aswid could take wing in the middle of a fight. Taking bat form is
now refused until Combat Lock seconds (default 2.5, 0 turns it off)
after the local player last lost health. Health is compared around
Character.ApplyDamage, so direct hits and fire, poison and bleeding
ticks all count, and a fully blocked or absorbed hit does not.
Turning back from bat form is never blocked.
2026-11-05 11:06:33 +01:00
9204dc96a2 feat(dvergar): build black marble and Yggdrasil pieces with stone and fine wood
Wargles' suggestion. A Dvergar pays 3 stone per black marble and 2 fine
wood per Yggdrasil wood on structural hammer pieces; stations,
furniture, containers and fires keep their cost. The swap is made on
the piece prefabs of the Dvergar's own client, so the menu, the known
piece check and the cost paid all follow it, and the pieces show once
stone or fine wood is known.

Vanilla refunds whatever m_resources says on the machine that destroys
a piece, so a cheap piece is tagged on its ZDO with the ratios paid,
and DropResources gets the matching cost on every client: a cheap wall
never refunds black marble, and a vanilla wall still does.

Swapped pieces carry the Dvergar race icon on their button in the 1.0
build menu (BuildUiPieceButton). The startup log lists every swapped
piece with its station and both costs.

Config: "Dvergar - Cheap Building" (Enabled, Stone per Black Marble,
Fine Wood per Yggdrasil Wood).
2026-11-05 10:34:04 +01:00
9ed606a9aa feat(skeleton): per-player options to eat real food and spend stamina
Two options in "Skeleton - Mortal Habits", both off and not synced by
the server, since each only gives up an advantage.

Eats Mortal Food: the Skeleton eats like the living. The max health
override and the fake foods step aside, so meals decide health and
stamina and the tier's health bonus, which stood in for food, no longer
applies. The food HUD shows again.

Feels Fatigue: the Skeleton spends stamina. Without eating, its max
stamina is base plus the stamina of the tier's stand-in meals, because
the fake foods sit at m_time 0 and give none.

The compendium builds its diet line from four new keys (English,
Italian, Russian) when either option is on.
2026-11-02 23:31:58 +01:00
4c7e0ec16d docs: the README changelog starts at v1.5.0, and packaging stops on a README Thunderstore would refuse 2026-11-02 17:47:38 +01:00
42c1e7ddd3 Merge remote-tracking branch 'origin/main' into localisation 2026-11-02 17:33:22 +01:00
aa252c86ca docs: v1.6.7 changelog and version bump, a job for every Skadi and Fenrir form 2026-11-02 17:32:06 +01:00
93d5b5424e Merge branch 'fenrir-form-roles' 2026-11-02 17:31:18 +01:00
94b66f29ee Merge branch 'skadi-form-flight' 2026-11-02 17:31:18 +01:00
ec3775a304 Merge branch 'fix-drone-kiln-alert' 2026-11-02 17:31:18 +01:00
af58fcec0d feat(fenrir): each form has a job once all three are unlocked
The Fenring and the Cultist ran at +100% while the Ulv, the form that
looks made for travel, ran at +50%. Now the Ulv is the travel form at
+100%, and the Fenring and the Cultist drop to +50%.

The Fenring holds the line: every hit on it lands 30% lighter. The
Cultist keeps its damage and pays for it: every hit lands 25% harder.
The scale sits in a new SE_FenrirFormBuff.OnDamaged, which runs on the
player's own machine before armor, so it covers hits from any client.

Speed and the damage factor are set on the live effect each time a form
is taken, so the Wolf and the Ulv can share SE_WolfForm with different
speeds, and a changed value applies without a relog. The speed keys
were renamed (Ulv Speed Bonus, Wolf Speed Bonus, Fenring And Cultist
Speed Bonus) so a saved .cfg cannot keep the old order. Suggested by
Lexsonn.
2026-11-02 16:23:35 +01:00
0f5b5e4868 feat(skadi): each dragon form flies and cools down on its own terms
The Drake and the Moder shared one set of flight numbers, so once the
Moder lost its time limit at the Queen the Drake had no reason left.
Now the Drake is the scout: quick to turn, fast, free to fly, but it
will not take off while encumbered. The Moder is the freighter: slow to
turn, 3 stamina a second to beat its wings, and it lifts a heavy pack at
25% extra cost.

"Skadi - Directed Flight" becomes "Skadi - Dragon Forms", with every
flight number per form plus the bat's Flight Stamina, While Encumbered,
Encumbered Extra Stamina Cost, Max Duration, Duration Per State and
Cooldown. Duration and cooldown default to -1, which keeps the
boss-tier table.

Each form also gets its own cooldown effect and icon, so a cooldown on
one form no longer blocks another. Suggested by Dissolution.
2026-11-02 15:58:17 +01:00
038d827991 fix: drones fly beside a station instead of into it
A flyer's goal is lifted to m_flyAltitudeMin over the ground under the
point, and under a charcoal kiln's origin that is inside the dome. The
drone never came within reach, timed out on the collect job and put the
kiln in the penalty box, so no wood was loaded for three minutes at a
time (snakey's second log: penalty True, 'Could not reach collect').

Station jobs now aim a metre past the station's colliders on the side
the drone comes from. Loading and the drop sweep still use the
station's own position.
2026-10-31 02:37:00 +01:00
85c7af6d05 fix: drones no longer freeze with a load after a slow trip or a fight
Plan() returned early for a delivery and kept the deadline of the job
before it, so a delivery that started late timed out on its first tick,
was planned again with the same stale deadline, and looped every frame.
snakey's log shows 10790 deposit_station timeouts in a row: the drone
hung by the kiln with the wood, and a fight mid-trip did the same.

Every job now gets a fresh clock. A station that is in the penalty box
is not asked again for a delivery; the Alfar drone takes the load back
to the chest it came from, so fuel stays in the Eldividarkista. The
Butler's servant had the same early return and gets the same fix.
2026-10-31 02:10:32 +01:00
9bd98c68c3 debug: F8 shows why a drone feeds a station or not, and what holds its fight
For the nearest worker drone F8 now lists the Eldividarkista and its
wood, every station in the radius (operable, free slots, takes wood,
penalty, claim, fuel, what a load would bring), and stations just past
the edge with the distance. Each drone also reports the 12 m enemy
sweep and how long the fight linger has left.
2026-10-31 01:58:40 +01:00
78d75a4a84 Merge remote-tracking branch 'origin/main' into localisation 2026-10-30 23:46:51 +01:00
b16d1775d8 docs: v1.6.6 changelog and version bump, Shrink Hammer and the Alfar base's new look 2026-10-30 23:43:56 +01:00
b25548280c Merge branch 'feat-trol-sounds' 2026-10-30 23:42:58 +01:00
106dc22bc1 Merge branch 'feat-scale-hammer'
# Conflicts:
#	JotunnModStub/Translations/English/messages.json
#	JotunnModStub/Translations/Italian/messages.json
#	JotunnModStub/Translations/Russian/messages.json
2026-10-30 23:42:58 +01:00
4cf95fa8c7 Merge branch 'feat-alfar-nexus' 2026-10-30 23:42:50 +01:00
56edb02eab Merge branch 'fix-grafvaettir-centre' 2026-10-30 23:42:49 +01:00
ec533fdbd9 fix: the Shrink Hammer's badge points in, at a small square
The resize badge's arrow ran from the small square to the big one and read as
growing. Four arrows closing in on a small square read as shrinking.
2026-10-30 23:41:57 +01:00
2125e71682 feat: a rare Trol surprise 2026-10-30 23:37:19 +01:00
0d1f655598 feat: Shrink Hammer, and Alt + scroll to size pieces with both hammers
A player asked to build below vanilla size for small details. The new
Shrink Hammer, craftable by any race, builds from 0.25 to 1; Trol's Hammer
keeps 1 to 3. With either hammer, Alt + scroll in build mode changes the
size in steps of 0.05, an Alt: Size row joins the build hints, and the size
floats over the ghost when it is not the default. With the repair tool, the
aimed piece shows the size it was built at. Both hammers get icons of their
own.
2026-10-30 22:49:27 +01:00
38bb8f1813 feat: the Ljoskjarne floats 0.8 m above the ground 2026-10-30 21:56:36 +01:00
036596b80d feat: the Ljoskjarne's faces become riveted steel panels
Each face is three brushed panels split by straight seams, framed by a
seam along the sloping edges and riveted along them. Straight lines and
streaks replace the grain that read as rock.
2026-10-30 20:10:31 +01:00
778451bed8 fix: the Ljoskjarne's seam is painted into a glow map, the plates look forged
The cyan bars stood on the faces and lost part of their length to the face
on one side of the world, lit or unlit. The seam is now a line in the faces'
own glow map, with a shallow channel in a new normal map. The plates take
grain and blotches from the black metal and iron beam textures, and shine
less.
2026-10-30 19:46:55 +01:00
06cc1d8c88 feat: the Ljoskjarne becomes a floating steel pyramid
A 2 m pyramid of dark steel, carved with Valheim's runes, hovers 0.5 m
above the ground, bobs and turns slowly. A cyan rib runs down each face;
it breathes and burns brighter while crystals wait. One still collider
keeps building, support and the E key as before. New hammer icon.
2026-10-30 18:48:32 +01:00
b661fa6516 feat: Alfar chests get bodies of their own
Players mistook a plain Wood chest for the Eldividarkista, so neither
Alfar chest looks like a buildable vanilla chest any more.

Eldividarkista: the Mistlands dvergr crate stretched to 1.6 x 0.8 m,
blackened iron with a bronze frame and an iron grate on the front. The
grate glows and throws sparks only while the chest holds wood the drones
may burn.

Inngangskista: the dvergr town loot chest, navy steel with silver trim. A
cyan line in the lid shines while it holds anything but the sigil.

Both have new hammer icons, and their hover names say their role (input,
fuel) in English, Italian and Russian. If a borrowed vanilla model is
missing, the chest falls back to the old tinted wood chest.

scripts/paint_*_chest.py repaint the textures and render previews and
icons offline with scripts/render_obj.py.
2026-10-30 18:20:13 +01:00
97e25dabe9 fix: Alfar drones go back to work after a fight, and say what they skip
A tamed MonsterAI never drops a target for distance, so an enemy that ran
off but stayed loaded kept the drone fighting forever. The drone now drops
a target past its leash and clears vanilla's target and alert when the
fight ends.

Drones now talk over their heads and in chat (40 m): an item in the
Inngangskista with nowhere to go, an item kept there for a station, and an
idle kiln whose wood is in a plain chest instead of the Eldividarkista.
Texts in English, Italian and Russian.

F8 lists each worker drone's state and why each entry-chest item stays or
moves.
2026-10-30 17:41:37 +01:00
46805836f3 Merge remote-tracking branch 'origin/main' into localisation 2026-10-29 21:10:19 +01:00
16cacde532 docs: v1.6.5 changelog, the Grafvaettir drones dig copper and tin 2026-10-29 21:09:46 +01:00
e87b85597d Merge branch 'fix-grafvaettir-centre': drones break copper and tin 2026-10-29 21:09:35 +01:00
b870dc65b0 fix: Grafvaettir drones break copper and tin
The F8 readout showed each hit entering Destructible.Damage with every gate open, this machine owning the deposit and ZRoutedRpc's id equal to the owner, and the RPC handler never running, with nothing in the log. When the drone's machine owns the deposit and the routed hit did not arrive, the drone now calls the deposit's own handler (Destructible.RPC_Damage, MineRock.RPC_Hit, MineRock5.RPC_Damage) directly: the same resistance, tier and break logic, without the routing. Why the local routing drops it is still open; a remote owner still gets the routed hit, untested.

A broken copper vein (rock4_copper_frac) never matched Mining Targets: MineRock5 renames its own object to "___MineRock5 m_meshFilter" in Awake. Deposit names now come from the ZDO's prefab. Drones also drop a target another drone just broke instead of striking a dead view.

F8 prints how far each drone's last hit got: Damage entered (and its gates), the RPC with health before and after, or the direct call.
2026-10-29 21:09:34 +01:00
dc24cbbacd docs: v1.6.5 changelog carries the Grafvaettir job and cooldown fixes 2026-10-29 20:37:44 +01:00
1420db796b chore: F8 shows what each Grafvaettir hit did on arrival
Patches on Destructible.RPC_Damage, MineRock.RPC_Hit and MineRock5.DamageArea record, for hits from a miner, the health before and after, the damage left after resistances, the pickaxe damage and the tool tier against the rock's minimum. 'sent, no RPC' means the hit never reached the deposit's owner.
2026-10-29 20:37:31 +01:00
9da27b64d3 Merge branch 'fix-grafvaettir-centre': F8 hit readout for the drones 2026-10-29 20:37:31 +01:00
a7cb4b45a7 Merge branch 'fix-grafvaettir-centre': Grafvaettir drones keep their job 2026-10-29 20:04:29 +01:00
ecf6e1bedb fix: Grafvaettir drones keep their job when their zone reloads
The F8 readout showed every miner with centre (0,0,0) and no target: Valheim destroys a creature when its zone unloads and builds a fresh one from the ZDO when it comes back, and the miner's centre, radius and lifetime were plain fields, so the rebuilt drone searched for ore around the world origin and stood still. They now live in the ZDO, the birth time in network time so a rebuilt drone does not get a fresh two minutes. A drone with no job in its ZDO digs around where it stands.

The throw on cooldown returned without a word, which looked like copper refusing the cast. It now says how many seconds are left (English, Italian, Russian).
2026-10-29 20:04:28 +01:00
2147c892b0 Merge remote-tracking branch 'origin/main' into localisation 2026-10-29 19:35:45 +01:00
172ed331e5 chore(release): v1.6.5 - Free Bat Flight and Fenrir senses
Version 1.6.5 in the manifests and PluginVersion. README: the New in v1.6.5 block and the changelog, Free Bat Flight in the Aswid section and progression, Hunter's Senses in the Fenrir section and progression, crediting MrBiffty, his friend and snakey.
2026-10-29 19:34:50 +01:00
0fe91dd52f Merge branch 'feat-free-bat-flight': Free Bat Flight as a choice 2026-10-29 19:34:07 +01:00
578ecbb591 Merge branch 'feat-fenrir-senses': Fenrir forms sense nearby creatures 2026-10-29 19:34:07 +01:00
00a30d9b34 Merge branch 'fix-grafvaettir-mining': Grafvaettir miners reach the deposit 2026-10-29 19:34:07 +01:00
7ec4a14ed4 fix: Free Flight texts name Left Ctrl, the key vanilla hard-wires for sinking 2026-10-29 19:33:38 +01:00
6f439f37c3 feat: Free Bat Flight, the old bat flight as a choice
The old bat flight is back as Free Flight: vanilla debug fly, up to 50 m/s, no stamina and no weight limit, Jump rises and Left Ctrl sinks. Each player picks it with Aswid - Bat Form / Free Bat Flight (local, never synced). The synced Bat Flight Rule (PlayerChoice, AlwaysStaminaFlight, AlwaysFreeFlight) lets the host or server decide for everyone. The mode is read when the form goes up, so a change counts from the next transform.

Debug fly makes vanilla treat the player as absent: no monster sees, hears or wakes for them, and hits are dropped. The six patches removed in v1.6.1 are back in AswidBatForm, for bats only and with no switch, so a free bat is fast but not invisible or immortal. Turning flight off now clears both flags, so death and reset end either flight. The compendium shows the Free Flight line when it is the active mode.

Asked for by MrBiffty, who builds tall with the bat.
2026-10-29 19:33:30 +01:00
fc5d6b8abc feat: Fenrir forms sense nearby creatures like the Aswid
Every Fenrir form (Wolf, Ulv, Fenring, Cultist) now lights each untamed creature within 100 m with the Aswid's green glow; the human does not. The glow moved out of AswidRace into a shared HunterSenses, which the Aswid now calls too, unchanged. New setting Fenrir - Superhuman Senses / Detection Radius; the light follows the Aswid's Marker Light settings. Compendium line in English, Italian and Russian.

Asked for by a friend of MrBiffty.
2026-10-29 19:33:21 +01:00
be8c7c59d3 fix: Grafvaettir miners fly low enough to strike deposits
Vanilla's flying MoveTo lifts the goal to m_flyAltitudeMin above whatever solid lies under it, the rock top included, so the miners hovered over a deposit just out of the 3.5 m reach and never struck. The Grafvaettir now flies 0.5-2 m up and strikes within 4 m.

Mining Targets is read again when the config line changes, so an edit in game counts without a restart. F8 also prints what the camera looks at (deposit kind, on the list or not) and each live miner's target, distance and strikes.
2026-10-29 19:33:08 +01:00
9117c0b251 Merge remote-tracking branch 'origin/main' into localisation 2026-10-29 16:22:58 +01:00
1c4d1c7b6a chore(release): v1.6.4 - staggering forms and Skeleton helmets
Version 1.6.4 in the manifests and PluginVersion. README: the New in
v1.6.4 block and the changelog, the Skeleton Show Helmet switch, Purple
Rain healing the caster and the Trenta's swim stamina, crediting lexsonn,
snakey and Jondar Korric.
2026-10-29 16:21:30 +01:00
a2737dc245 Merge branch 'fix-cultist-fire': Cultist fire from the hands, forms stagger 2026-10-29 15:46:33 +01:00
c5387421d4 fix: Cultist breath pose holds, roar loops, Cultist stands still
The creature's CharacterAnimEvent resets Animator.speed to 1 every physics step
outside a vanilla attack, so the speed-0 pin never held: the pose is now replayed
at the pin each frame. The flame ZSFX loops without its fade-out. While breathing
the player is held still through FenrirForms.LocalAttacking (no walking cast clip
exists); the howl waits for the breath to end.
2026-10-29 14:24:04 +01:00
a6df7a47f8 fix: Cultist breath holds the throw pose and keeps its flames
Pin at 1.3 s, the throw, instead of 2.6 s, where the vanilla Cultist has already
lowered its arms. fx_fenring_flames is a one-throw effect (2 s non-looping
emitters, 5 s TimedDestruction): loop the emitters and drop the timer so the
flames last the whole hold.
2026-10-29 14:14:24 +01:00
d142fad330 fix: Cultist fire from the hands, tied to its clip, facing the camera
The breath waits for the flame clip's Hit point (1.245 s), holds the casting pose
while the button is held and blends back to Movement on release, so a short click
no longer leaves the arms raised for the clip's 3.5 s. Eitr drains from the
flames on. Each fx_fenring_flames emitter follows its hand bone. While breathing,
Player.AlwaysRotateCamera answers true, so the body turns to the camera as when
blocking. Onlookers' copies follow the same clip.
2026-10-29 14:00:26 +01:00
beffd0bee6 fix: a stagger cancels the form's attack
A form swing waits for its clip's hit event and lands on a timeout if none comes,
so a stagger that cut the clip short still dealt the blow. Attacks are marked as
they start (TrySpendStamina, Ravager AttackRoutine) and their hits are dropped if
a stagger began since. No attack or Cultist breath starts while staggered.
2026-10-29 13:53:04 +01:00
dd92bdf345 fix: forms play their own stagger animation
The player's stagger trigger only reached the hidden human's Animator. FormStagger
fires the form's own vanilla stagger as it starts, for every form whose controller
has one (Trol True Form, the Fenrir forms, Ravager, Aswid bat), on every client.
2026-10-29 13:28:01 +01:00
a3d4f4ca02 Merge branch 'fix-grafvaettir-drone': drones mine and work instead of wandering 2026-10-29 13:23:43 +01:00
62ebc13116 Merge branch 'feat-form-attack-stamina': Form attacks cost stamina 2026-10-29 13:22:45 +01:00
162f71c39d Merge branch 'fix-cultist-attacks': Cultist claws on the hit events, flames from the jaw 2026-10-29 13:22:45 +01:00
788e226372 Merge branch 'fix-purple-rain-caster': Purple Rain heals the caster 2026-10-29 13:22:45 +01:00
84aba227eb Merge branch 'fix-trenta-swim-regen': Bonemass Trenta regains stamina while swimming 2026-10-29 13:22:45 +01:00
ed7483568c Merge branch 'fix-form-headlamp': Lights follow the form's head 2026-10-29 13:22:45 +01:00
3b194eaec9 Merge branch 'fix-trol-log-grab-gamepad': Trol Grab Log on the Use key 2026-10-29 13:22:44 +01:00
4cb9b7788d Merge branch 'fix-form-adrenaline': Form hits build adrenaline 2026-10-29 13:22:44 +01:00
7a43ced3fb Merge branch 'fix-muspell-weapon': Muspell blocks the hidden human's attack 2026-10-29 13:22:44 +01:00
3dae107b85 fix(fenrir): the Cultist's flames leave its mouth
The breath effect was placed 1.5 m above the player's feet and 1 m
ahead, chest height on a Cultist and the same whatever the form's size.

It now sits on the form's Jaw bone (fenring_cultist rig: Neck/Head/Jaw,
read from the game files), 0.3 m ahead, Head as the second choice and
the old fixed point if neither exists. A small follower places it every
LateUpdate, facing where the player faces, on the owner's copy and on
every onlooker's. The burn area is unchanged.
2026-10-29 02:30:05 +01:00
ac4ce4c636 feat(forms): Trol True Form and Fenrir form attacks cost stamina
Every form swing was free. FormMelee.TrySpendStamina charges a form
attack the way Attack.GetAttackStamina charges a weapon: equipment
modifier, status effects, up to a third off with the skill. Short of
stamina, the attack does not start and the bar flashes.

Trol True Form (Clubs skill), priced by the troll's damage, the slam
dearer for hitting all around: punch 10, side log swing 10, overhead
log 12, ground slam 18.

Fenrir forms (Unarmed), cheaper than weapons: Fenring 6/10/16, Wolf
4/6/10, Ulv 5/8/14, Cultist claw 6 and double claw 12. In exchange each
form hit gives 1.5x adrenaline (Fenrir - Form Buffs / Form Adrenaline
Multiplier), in Fenrir forms only.

Every cost is its own config entry beside the attack's damage.
2026-10-29 02:28:23 +01:00
ffb45d1c1c fix(fenrir): Cultist claws land on the clip's own hits
The single claw dealt its damage at a fixed 0.4 s, before the swing in
ClawAttackCultist (Hit event at 0.64 s of 1.33 s), and released the lock
at 0.5 s, so clicking again started a new claw mid-swing. The double
claw dealt one hit at 0.6 s although DoubleClawAttackCultist swipes
twice (Hit events at 0.64 s and 1.21 s).

BlockPlayerAttackTriggerPatch now counts the form's Hit events
(FenrirForms.AttackEvents) instead of only swallowing them. Both claws
wait for their events, with a timeout, and hold the lock until the clip
ends. Each double-claw swipe deals 60% of Double Claw Damage, 120% in
all for a slower swing that can be cut short.
2026-10-29 02:23:27 +01:00
87db3e03a6 fix(trenta): Purple Rain heals the Trenta who casts it
The heal skipped the caster, so a lone Trenta cast a heal that touched
no one. The caster now gets the same flat heal as its allies; the
compendium line and the config description say so.
2026-10-29 02:21:49 +01:00
fdc0fdcedc fix(trenta): stamina trickles back while a Bonemass Trenta swims
Vanilla Player.UpdateStats stops stamina regen while swimming off the
ground, and drowning starts at 0 stamina. The Bonemass unlock only
waived the stroke cost, so a Trenta who went into the water empty never
got a point back and drowned in water it swims for free.

A postfix on UpdateStats adds the regen vanilla held back, with the same
formula, times the new Trenta - Bonemass / Swim Stamina Regen (0.1, slow
on purpose). The compendium line says so in all three languages.
2026-10-29 02:21:24 +01:00
3c81b8f130 fix: Alfar drones and Sverm workers work instead of wandering
HandsToVanilla gave the tick to MonsterAI whenever BaseAI.FindClosestEnemy returned someone. Vanilla takes its first match at any distance and only checks maxDistance after that, so any wild creature in the loaded zones counted. The tamed MonsterAI then idled around and the work loop never ran. Check the distance ourselves.
2026-10-29 01:55:48 +01:00
504e6e83ed fix(forms): a worn headlamp follows the form's head
A form hides the human body and leaves it where it stood, and a Light is
not a renderer, so the Dvergr circlet's lamp (or a torch in hand) kept
shining from the hidden human's head: at a person's height inside the
troll, from the Muspell's feet.

While the body is hidden, every Light under it is put just ahead of the
form's head bone. A form without a bone called head gets the top front
of its own model, and with no form model at all the light sits
centre-forward at head height. The lights go back once the body shows.
Runs for every player, so onlookers see the lamp in the right place too.
2026-10-29 01:54:50 +01:00
4862f47e73 fix(trol): Grab Log works on the game's Use button, gamepad included
A log carries only vanilla's HoverText, which is not an Interactable, so
the game's Use on a log did nothing. Grab Log was read off the keyboard
alone (and the radial menu), and a gamepad had no button for it.

A prefix on Player.Interact grabs the log for a True Form Trol at tier
7+, the way the Aswid's Dominate rides the same button. The Grab Log key
still works on top of it, with a short debounce so the two readers of an
E press grab once. The hover prompt now shows the Use key, which resolves
to the pad's own button.
2026-10-29 01:53:32 +01:00
b7b9cbcbd5 fix(forms): Trol, Skadi, Sverm and Muspell form hits build adrenaline
The same bug the Fenrir forms had until d8dcecb. Vanilla grants a hit's
adrenaline inside Attack; these forms skip Attack and call Damage
directly, so only the stagger bonus in Character.Damage ever reached the
player.

FormMelee.GrantAdrenaline now runs after each hit of the True Form
troll's punch and log swings, the drake's maul, the Ravager's swings and
the Muspell's stomp. The troll's ground slam hits through an Aoe, which
never touches Attack either: the slam marks its Aoe, and a postfix on
Aoe.OnHit grants the adrenaline for each creature it lands on.

Projectiles (Throw Rock, the Muspell spike, drake breath) were never
affected: Projectile grants its own adrenaline on a hit.
2026-10-29 01:52:10 +01:00
99ec4134be fix(trenta): the Muspell no longer swings the weapon in hand
The Muspell was the one form without the attack blocks every other form
has. Each stomp and spike also started the hidden human's attack, and the
Elder clone's CharacterAnimEvent fired a held bow or crossbow through
OnAttackTrigger, several shots a swing.

StartAttack, PlayerAttackInput and OnAttackTrigger are shut while the
Muspell is up, and the guard is cleared after SetControls, since the
spike sits on Right Mouse, which is also Block.
2026-10-29 01:50:33 +01:00
bba81cbbf0 fix: Grafvaettir drones mine copper, scrap and tin
The default Mining Targets list named MineRock_Copper, but Black Forest copper is rock4_copper, so drones thrown at copper found no target and hovered where they spawned. Add rock4_copper and mudpile, and move configs still on the old default.

Drones now measure and aim at the nearest live hit area instead of the deposit root, which sits inside big rocks. Hits carry the drone as attacker: vanilla MineRock reads the attacker's ZDOID without a null check and threw on every tin hit.
2026-10-29 01:26:46 +01:00
373b0069dd Merge branch 'skeleton-show-helmet': Skeletons can show their helmet 2026-10-29 01:23:53 +01:00
e972ca5ea4 feat: Skeletons can show their helmet
New "Show Helmet" option under Skeleton - Visuals, off by default. The owner's
choice is written to the ZDO, so other players see the helmet the way its owner
picked.

On a skull the helmet moves up and back and grows to fit, since the skull is
bigger than the viking head the helmet hangs for. Hoods and the other skinned
helmets can't be moved by their transform: their Head bone is swapped for a
fitted child bone, so the head part follows the skull and the shoulder parts
stay put. A viking body gets the vanilla placement and bones back.
2026-10-29 01:08:07 +01:00
356e0f44d8 Merge remote-tracking branch 'origin/main' into localisation 2026-10-28 13:57:19 +01:00
1aa55984d6 chore(release): v1.6.3 - Trol guard and dressed stations
Version 1.6.3 in the manifests and PluginVersion. README: the New in
v1.6.3 block and the changelog, the True Form controls, the Bone Servant
tables' and the Race Menu Ward's new looks, crediting lexsonn and
sistermilker.
2026-10-28 13:55:36 +01:00
38160d1fa1 Merge branch 'kitbash-race-stations': new looks for the Race Menu Ward, Contract Bank and Bone Servant tables 2026-10-28 13:53:45 +01:00
2e40d45f04 Merge branch 'trol-true-form-block': Trol True Form blocks and rolls 2026-10-28 13:53:44 +01:00
3cc1bee2c0 feat: Trol True Form can block and roll
Right click blocks in True Form with a raised-arms guard, rooted in place.
Block + jump rolls at half distance with the troll's jump animation at
double speed. The slam moves to middle click (secondary attack on a pad).
trolpose is a debug command for trying guard and roll states live.
2026-10-28 13:53:35 +01:00
35476eb8ef feat: chainmail over the map on the Smith's Table
The smith goes back to the cartography table, like the cook. Its map is
painted over with 4-in-1 mail by scripts/paint_smith_mail.py at 512 px:
colour, rusted worn colour, a normal map from the rings' height and a
metallic map so they shine. Both tables now share one Dress/LayCover path.
2026-10-28 13:47:49 +01:00
069e098cf0 feat: red and white tablecloth on the Cook's Table
The cook goes back to the cartography table with its map painted over
offline (scripts/paint_cook_cloth.py from textures pulled by
scripts/extract_carto.py). The three PNGs are embedded in the DLL and
swapped onto copied materials by PieceLook.Retexture. The smith stays on
the black marble table.
2026-10-28 13:38:28 +01:00
b3edb2aed1 feat: marble Bone Servant tables, bigger centred props, fix table hover name
The Smith's and Cook's Tables clone the black marble table: the
cartography table's map is baked into its texture. Anvil or meal and a
skull sit near the centre at the table's measured height. The bank loses
its lantern and its tankard grows. The servant table hover localizes its
title, which showed as a raw token once a servant stood there.
2026-10-28 13:22:56 +01:00
f3d3c0ebb5 feat: new looks for the Race Menu Ward, Contract Bank and Bone Servant tables
Recolour and kitbash from vanilla parts, no new assets. PieceLook copies
materials before tinting so vanilla pieces keep their colours. ModelBorrow
gains activeOnly, which drops hidden snow, fire and broken meshes before
a borrowed piece is measured.
2026-10-28 12:40:33 +01:00
4fe7a9787d Merge remote-tracking branch 'origin/main' into localisation 2026-10-27 19:36:18 +01:00
cb29f54a28 chore(release): v1.6.2 - race eyes and controller fixes
Version 1.6.2 in the manifests and PluginVersion. README: the New in
v1.6.2 block and the changelog, crediting lexsonn's reports; the Aswid
eyes, Alfar levitation and Geisli lines follow the changes.
2026-10-27 19:36:02 +01:00
4cf9f6bee0 Merge branch 'fix-draugh-bear-alfar-gamepad': Draugh meats, Alfar levitation and Geisli on gamepad, rebindable flight keys 2026-10-27 19:35:25 +01:00
db9aac2bf6 fix: Draugh Ashlands meats, rebindable flight keys, Geisli on gamepad
Draugh: add AsksvinMeat and BoneMawSerpentMeat to the shared raw-to-cooked
table; the Aswid blood refinery no longer adds them on its own copy.

DirectedFlight (drake, bat): read ZInput Forward/Backward/Run instead of
raw W, S and Shift, so keys rebound in the settings work.

Geisli: the pad has no free button in vanilla's Classic layout, so the
beam is held on the pad's secondary attack, bare-handed or in the
Archon form, as Skadi's Cold Spell does. The unarmed kick is swallowed
while it fires. RaceInput.EmptyHanded is shared with Skadi. Compendium
text mentions the pad in English, Italian and Russian.
2026-10-27 19:33:17 +01:00
b9ec452e72 fix: Draugh eats Bjorn and Volture meat, Alfar levitation on gamepad
Draugh: add BjornMeat -> CookedBjornMeat to the raw-to-cooked table and
correct VoltureMeat's cooked name (RoastedVoltureMeat does not exist,
CookedVoltureMeat does), so neither raw meat got an EdibleUncooked_ item.
Names checked against the SoftRef manifests.

Alfar: ZInput "Jump" is the keyboard binding only. Read "JoyJump" and
"JoyCrouch" too, as PlayerController does, for levitation and the
Archon's climb and descent.

Reported by lexsonn.
2026-10-27 19:25:03 +01:00
45248acd74 Merge branch 'fix-race-eyes': race eyes on female faces, smaller Dvergar/Aswid eyes, grey Alfar eyes 2026-10-27 17:48:24 +01:00
5b3b2ac88d refactor(eyes): bake the tuned eye corrections in, drop the sliders
The Eyes Position sections were a tuning tool. Their per-body, per-eye values
from playtest now live in RaceEyeTuning as constants, so every player gets
the tuned faces and Configuration Manager loses four sections. The Aswid -
Eyes section stays for now.
2026-10-27 17:46:36 +01:00
f7a4494b39 feat(eyes): male per-eye defaults from playtest
Male Aswid, Alfar and Dvergar eye values dialled in on screen become the
defaults of their Eyes Position sections, so male faces no longer start from
the untuned code placement.
2026-10-27 17:44:49 +01:00
06b7fc165c feat(eyes): Dvergar female right-eye defaults from playtest 2026-10-27 16:17:03 +01:00
a214a604e1 feat(eyes): Aswid and Alfar female per-eye defaults from playtest 2026-10-27 16:16:46 +01:00
132d7e034f feat(eyes): per-eye sliders, Aswid female defaults from playtest
Each Eyes Position section now has a set per body and per eye (the
character's own left and right), because the face is not symmetric enough for
one set to fit both eyes. The Aswid female defaults are the per-eye values
dialled in on screen; Alfar and Dvergar copy their female values to both eyes.
The old shared keys are dropped: they only ever existed in test builds.
2026-10-27 16:03:24 +01:00
ffba40650e fix(aswid): eye position sliders rotate on the face's axes
The Eyes Position rotation was added to the Aswid's own twist, which works on
the head bone's raw axes: bone X points out of the face and bone Z sideways,
so Rotation X rolled the eyes and the mirrored Rotation Z tipped one eye up
and the other down. The slider rotation is now conjugated by the face frame,
so X tips, Y turns toward the temple and Z raises the outer corner on both
eyes alike. The female rotation defaults go back to 0, since the old numbers
meant other axes.
2026-10-27 15:40:52 +01:00
20c12724fd feat(eyes): female eye defaults from playtest
The female slider values dialled in on screen for the Dvergar, Alfar and Aswid
become the defaults of their Eyes Position sections, so a fresh install lands
on the tuned faces. The Sverm keeps zeros: its helmet hides the eyes.
2026-10-27 15:38:52 +01:00
8b2b5180ed feat(eyes): per-race eye position sliders in Configuration Manager
One 'Eyes Position - <race>' section each for the Alfar, Aswid, Dvergar and
Sverm, with a female and a male set: forward, height, separation and size,
plus rotation X/Y/Z for the Alfar and Aswid. All are deltas on the computed
placement (0 and size 1 change nothing), read live, and left local by
ConfigSync because they only change how this client draws faces.
2026-10-27 15:21:19 +01:00
a7e9996441 fix(eyes): lower female eyes further, push Alfar/Dvergar out, enlarge Aswid points
Playtest on female characters: every race's eyes still sat about an eye-height
above the painted ones. Female height shift goes from -6 to -14 mm. Alfar and
Dvergar centres move 4 mm forward out of the face, and the Aswid socket goes
from 0.5 to 0.75 of the borrowed size so it covers the painted eye.
2026-10-27 15:15:10 +01:00
026def2fde fix(eyes): female face placement, smaller Dvergar/Aswid eyes, grey Alfar eyes
The female body maps the painted eyes about 6 mm lower and a quarter closer
together than the male one (read from bodymale/bodyfem and the skin UVs), so
every race's male-tuned eyes sat on the female brow. PlayerFace moves them for
the Dvergar, Aswid, Sverm and Alfar.

Dvergar eyes shrink to an 18 mm radius. The Aswid's borrowed sockets are
halved before the config multiplier and the smoke is off by default.

Alfar eyes become slanted, wrapped black almonds with a wet sheen. They are
placed in fixed head-local units: the live lossyScale under the non-uniform
Alfar body drifted as the head turned, and the 0.5 s cosmetic pass made the
eyes trail the face.
2026-10-27 15:01:44 +01:00
76085f14b0 Merge remote-tracking branch 'origin/main' into localisation 2026-10-26 16:09:04 +01:00
a927a6d4b3 chore(release): v1.6.1 - the Aswid rebalance
Version 1.6.1 in the manifests and PluginVersion. README: the New in
v1.6.1 block and the changelog, crediting the Discord reports.
2026-10-26 16:08:55 +01:00
876309e85c Merge branch 'fix-readme-texts': README matches the code; stale copies removed 2026-10-26 16:06:05 +01:00
04e540a89d Merge branch 'balance-aswid': the Aswid rebalance - stamina, devour, bat flight, weaknesses 2026-10-26 16:06:05 +01:00
1051324b56 chore: drop the stale README copies in JotunnModStub
The root README is the one players get: package.ps1 and nexus-readme.py
read it. JotunnModStub/README.md and Package/README.md had drifted for
versions, and edits kept landing in them by mistake. Both are gone. The
csproj links the root README, the publish scripts copy it into Package/
at release, and that generated copy is ignored.
2026-10-26 16:04:26 +01:00
cb546ee5e3 docs(readme): describe the Aswid rebalance and match other races to the code
The rebalance's README edits had gone into JotunnModStub/README.md and
Package/README.md, stale copies the build does not ship; the root README
is the one package.ps1 and nexus-readme.py read. It now has them.

Checked every race section against the code and fixed what drifted:
Draugh (unlocks rewritten from the code: no Wet immunity or faster swim,
Rotting Edge instead of Toxic Trace, poison and frost immunity tiers,
no skill loss rather than Corpse Run), Skadi (Freezing immunity at
Yagluth, frost immunity and Frost Aura at the Queen), Furling (+10%
speed), Trenta (camouflage covers six creature families, not everything)
and the Aswid (Auspex is a Moder unlock, the Queen line no longer claims
a fire/frost/spirit weakness).
2026-10-26 16:02:45 +01:00
c76341af0d feat(aswid): running water covers rivers and lakes; sway on boats
Open water now means any water: swimming in it, or flying over a metre
or more of it, sea, river or lake. Standing on anything solid stays safe,
so docks, bridges and wading do not count. On a boat there is still no
burn or drain, but the camera keeps swaying. 'Ocean Only' restores the
sea-only behaviour, and the settings say Open Water instead of Open Sea.

Also rewrites the README's per-boss Aswid section from the code: it
listed stats, unlocks and an aura that no longer exist.
2026-10-26 15:49:05 +01:00
a00db24ebd fix(aswid): name the food in the full-stomach devour message
$msg_nomore carries a $1 for the food's name, and the devour sent it
bare, so players read "can't eat more $1". Filled in the same way
vanilla's CanEat and the Trol do.
2026-10-26 15:30:01 +01:00
5c41d80cae feat(aswid): running water weakness and a seasick camera
Swimming costs double stamina, scaled on vanilla's own swim charge so
its drowning check does the rest at high settings. Over deep water in
the Ocean, swimming or flying, the Aswid loses health and stamina each
second; a boat protects. A gentle camera roll plays while the sea hurts,
kept local through ConfigSync so a server cannot force it on anyone.
2026-10-26 15:26:25 +01:00
9149d3f0b5 feat(aswid): sunlight, fire and pierce weaknesses
Each has its own switch under 'Aswid - Weaknesses'. Sunlight: by day
under open sky, slower regen and movement and a slow burn that stops at
30% health; roofs, dungeons, Swamp, Mistlands, night and Eclipse shield
you. Fire +25% until Fader, pierce +20%; both applied after resistances
and armor, so meads still help and Mist Form stays pierce-immune.
2026-10-26 15:12:05 +01:00
77cdc67e97 feat(aswid): bat flies on the Skadi's directed flight
The bat flew on vanilla's debug-fly flag: 50 m/s, free, blind to carry
weight, and invisible to monsters until six patches lied about the flag.
It now flies on m_flying with the drake's controls, moved out of
SkadiPatches into a shared DirectedFlight core that both forms feed
their own numbers into. Powered flight and the sprint cost stamina; out
of stamina the bat glides. Encumbered flight costs 15% more, or is
blocked with 'While Encumbered'. Optional duration and cooldown, off by
default. The aggro/damage patches, the debug-fly speed patch and their
three settings are removed; the drake's behaviour is unchanged.
2026-10-26 14:26:42 +01:00
824ddd8956 feat(aswid): Vampiric Aura is off in bat form until The Queen
A bat could glide over enemies that cannot reach it and drain them the
whole way. The aura now stays silent in bat form until the configurable
unlock state (7, The Queen), or always if 'Active In Bat Form' is on.
Also corrects the README's aura and Mist Form lines, which still
described the old block-to-channel aura and a weakness the code lacks.
2026-10-26 14:20:10 +01:00
83cd49c753 feat(aswid): devour feeds less health and some stamina
Devoured creatures feed 10% less health, and a share of it becomes
stamina: 60% for Meadows and Black Forest prey, 10% past them. Foods made
by the half-health formula are capped per biome, so a Troll no longer
feeds 150. The foods are rebuilt from their base values whenever a
setting changes or the server's values arrive.
2026-10-26 13:57:41 +01:00
ab0a21244d feat(aswid): replace infinite stamina with a boss-scaled pool
The Aswid shared the Skeleton's UseStamina skip, so stamina mods, foods
and skills did nothing for it. It now spends stamina, scaled by a cost
multiplier, and gets +25 max stamina plus 10 per boss added on top of its
food. The stamina bar shows again. Draugh and Skeleton are unchanged.
2026-10-26 13:54:44 +01:00
68b87d181a Merge remote-tracking branch 'origin/main' into localisation 2026-10-25 18:25:22 +01:00
7cd0aa234d Merge branch 'fix-alfar-texts': Kall, Utsog and the Nexus limit described as coded 2026-10-25 18:25:10 +01:00
40202d4793 fix(alfar): the compendium and README describe Kall, Utsog and the Nexus limit the code has
Kall pulls dropped items to you; it is not a lightning wave. Utsog gives
back 15% of any damage dealt, and the compendium printed it as 1500%.
One Ljoskjarne stands in every 1.6 square kilometers, not one per
square kilometer. EN/IT/RU.
2026-10-25 18:25:10 +01:00
4fcfe6fd7c Merge remote-tracking branch 'origin/main' into localisation 2026-10-25 17:58:37 +01:00
3c7b2d5f79 chore(release): v1.6.0 - the Alfar
Manifest description counts eleven races and names the Alfar. The v1.6.0
changelog picks up the Summon on Kill line change from after v1.5.15.
2026-10-25 17:58:23 +01:00
8e5f4916c2 Merge branch 'alfar': the Alfar, an eleventh race 2026-10-25 17:57:33 +01:00
Ferdinando
3f8cf1ee27 feat(alfar): v1.6.0 - the Alfar, an eleventh race
Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield,
diet, soft fall, levitation), Heimkall sends a lethal blow home at one
health every 20 minutes. Caster powers from Skrid to the archon
Sameining, with on-screen cooldowns. Automated base around the
Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard.
Compendium page in EN/IT/RU.

README: New in block, race section, progression, station line, changelog.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 17:38:28 +01:00
9e9790d1e9 docs(readme): the v1.5.15 entry quotes the line that shipped
The new line goes out in v1.5.16 and is listed for that release.
2026-10-24 23:55:26 +02:00
6eb8348363 Merge branch 'fix-skeleton-raise-quote': Summon on Kill line is "Thy shall raise again." 2026-10-24 23:53:53 +02:00
0a843bad41 fix(skeleton): the Summon on Kill "on" line is "Thy shall raise again."
As written by the author; Italian "Tu rialzerai ancora.", Russian
"Ты вновь поднимешь.". README changelog line too.
2026-10-24 23:53:53 +02:00
d689834070 Merge remote-tracking branch 'origin/main' into localisation 2026-10-24 18:28:28 +02:00
20dec64fa0 chore(release): v1.5.15 - Skeleton health rebalance, Auto-Resurrect fix, Summon on Kill toggle
Skeleton max health is lower in the early and middle game, from 75 to
50 at the start and unchanged at Fader. Auto-Resurrect triggers only
on a hit that would really kill, dedicated servers included. Summon on
Kill toggles with G and shows a Raise the Dead icon while on.

README: New in block, Queen line, changelog entry.
2026-10-24 18:28:17 +02:00
de10b1795b Merge branch 'balance-skeleton-hp': lower Skeleton max-health bonus in the early and middle game 2026-10-24 16:52:50 +02:00
18593ae1d3 balance(skeleton): lower max-health bonus in the early and middle game
+25/+45/+65/+90/+125/+165/+215/+275 from no bosses to Fader, was
+50/+80/+110/+140/+170/+200/+230/+275. A fresh Skeleton starts at 50
max health instead of 75; Fader stays at 300. Asked for by several
players over three months, last by Jondar Korric. A Skeleton never eats
and never spends stamina, so it ran well ahead of a fed viking.

The hidden foods that carry its regeneration are picked to match the
new totals, so early-tier regen drops with them. README progression
updated; the compendium reads the value from code.
2026-10-24 16:36:52 +02:00
9308ce062c Merge branch 'fix-skeleton-resurrect-summon-toggle': Auto-Resurrect on the real deathblow, Summon on Kill toggle 2026-10-24 15:50:51 +02:00
e41f7b610e revert(skeleton): drop the Summon on Kill aura, keep the icon
Neither the Draugr's evil_smoke nor the torch smoke showed in game once
tinted dark. The Raise the Dead icon stays, with its per-player switch.
2026-10-24 15:50:05 +02:00
3591b7e375 fix(skeleton): the Summon on Kill aura borrows the torch smoke
The Draugr's evil_smoke is on 'Lux Lit Particles/ Bumped' and showed
nothing in game once tinted dark. The torch's own Smoke, from the
prefab the head flame burns from, is the grey everyone sees above a
torch; darkened to (0.08, 0.08, 0.09) at 0.45 alpha.
2026-10-24 15:44:16 +02:00
98b1a1b5f3 feat(skeleton): dark aura while Summon on Kill is on, archaic toggle messages
Beside the Raise the Dead icon, a faint near-black smoke now rises off
the whole body while Summon on Kill is on: the Draugr's looping smoke,
borrowed like the Draugh aura, emitted from a body-sized box in world
space. The owner writes the switch to the ZDO, so other players see
it. "Raise the Dead Icon" and "Raise the Dead Aura" under Skeleton -
Visuals let each player keep either or both, for a community vote.

The toggle now says "Thy dead shall rise again." / "Raising...
nevermore.", in English, Italian and Russian.
2026-10-24 15:38:42 +02:00
53f6fb71a2 fix(skeleton): Auto-Resurrect on the real deathblow; Summon on Kill toggle
Auto-Resurrect was decided in the Character.Damage prefix on the raw
hit: before armour, blocking and resistances, with poison and fire
counted in full. With good armour it fired on almost any hit. Damage
also runs on the attacker's owner, so on a dedicated server a mob
owned by the server or another player skipped the check entirely. It
now runs in an ApplyDamage prefix, on the victim's own client, against
the damage that is about to land. The rising-from-the-ground immunity
is checked there too.

Summon on Kill gets a toggle key (G, Skeleton - Keybinds) and a
gamepad radial entry. The choice is saved on the character, on by
default. A "Raise the Dead" status icon with the Dead Raiser's
picture shows while it is on. Texts in English, Italian and Russian.
2026-10-24 15:28:04 +02:00
fe8b3ea270 Merge remote-tracking branch 'origin/main' into localisation 2026-10-23 22:27:37 +02:00
7411680553 chore(release): v1.5.14 - Fenrir night eyes, form adrenaline, full-stomach eating
Fenrir eyes glow at night, brighter when a form is ready and yellow when
the Cultist is back. Form hits build adrenaline like a weapon hit. Race
foods replace a worn-down meal when the stomach is full. The stamina bar
comes back after leaving Aswid or Draugh. Other players see a Furling at
Furling size, and a Legacy True Form Trol hits as far as it reaches.

README: New in block, Fenrir night eyes, changelog entry, new Discord
link (also in the old JotunnModStub README).
2026-10-23 22:27:26 +02:00
e37084ac33 Merge branch 'fix-fenrir-form-adrenaline': Fenrir form hits build adrenaline like a weapon hit 2026-10-23 22:23:20 +02:00
d8dcecb573 fix(fenrir): form hits build adrenaline like a weapon hit
Vanilla grants a hit's adrenaline inside Attack. The forms skip Attack
and call Damage directly, so only the stagger bonus in Character.Damage
reached the player: meadow mobs, quick to stagger, filled the bar, while
Lox, Tar, Brutes and Furlings gave nothing until staggered.

FormMelee.GrantAdrenaline adds the player's unarmed attack adrenaline
times the target's multiplier after each claw or bite, and a fifth of
it per 0.2s tick of the Cultist's fire.
2026-10-23 22:17:17 +02:00
e5a9dc0046 Merge branch 'feat-fenrir-eye-glow': Fenrir eyes glow at night, bright when a form is ready 2026-10-23 22:08:57 +02:00
8b7e88e077 fix(fenrir): faint night glow at 0.675, as tuned in game 2026-10-23 22:08:05 +02:00
418d2462bd fix(fenrir): a softer ready glow
1.2 read too strong in game; 0.9 by default. The faint glow stays at 0.6.
2026-10-23 20:12:30 +02:00
c2bc73b3a0 feat(fenrir): eyes turn the Cultist's yellow when it is back from cooldown
The ready flag becomes an int: none, a form, or the Cultist. The Cultist
wins only while its rules give it a cooldown (Yagluth and Queen), since
that is the one return worth announcing. Its body shares the Fenring's
material and its breath is white flame tinted by texture, so the colour
comes from its death effect: FlameRoundYellowParticle's emission,
(2.691, 1.797, 0.455), bundle c4210710.
2026-10-23 20:06:49 +02:00
2becb81b6f fix(fenrir): the faint night glow is bright enough to see
At 0.35 the red channel stayed under 1, so bloom never picked it up and
a Fenrir with no form ready looked like it had no glow at all. 0.6 puts
it just over.
2026-10-23 19:58:35 +02:00
d1f328a496 feat(fenrir): eyes glow at night, bright when a form is ready
A community suggestion: an indicator on the character instead of the
"<form> is Ready!" text. FenrirVisuals borrows the Skeleton's eye_l and
eye_r the way AswidVisuals does, with the Aswid's playtested placement,
and tints them with the Fenring's own emission colour (2.0, 0.372, 0),
read from bundle c4210710.

Dark by day and in a beast form. At night they glow faintly, and
brightly while one of the three keys would transform. That uses the
same gates as TryTransformWithRules: tier, night, sun sickness,
cooldown. The owner writes it to the ZDO only on a change, so remote
players see the same.

New local section "Fenrir - Appearance": Ready Message (on by
default), Eye Glow, and the night and ready strengths.
2026-10-23 19:33:00 +02:00
f1f8ed245c Merge branch 'fix-stamina-bar-return': the stamina bar comes back after leaving the Aswid or the Draugh 2026-10-23 19:23:43 +02:00
1b1dae5f0b Merge branch 'fix-full-food-slots': race foods replace a worn-down meal when the stomach is full 2026-10-23 19:23:43 +02:00
f1597dd646 fix(hud): the stamina bar comes back after leaving the Aswid or the Draugh
Both races hide the stamina bar root from a Hud.UpdateStamina prefix.
Vanilla activates that root once, when the HUD is built, so after a
race change the bar stayed hidden until relog. The prefix now switches
it back on for every other race.
2026-10-23 19:22:31 +02:00
eba537fa07 fix(food): race foods replace a worn-down meal when the stomach is full
Trenta seeds, Draugh raw flesh and Aswid meals each go through an
EatFood prefix that, with three slots full and none holding the same
food, answered false. Vanilla would replace the most depleted meal past
half its time. The UseItem callers also never showed why: EatFood says
nothing on a refusal, so the click did nothing at all. That is the
Reddit report of a Trenta who could not eat any seeds.

The prefixes now hand that case to native EatFood, the Aswid's
CanConsumeItem postfix keeps vanilla's answer instead of forcing false,
and the Trenta and Draugh callers ask CanEat(item, true) for vanilla's
own message when a meal is refused.
2026-10-23 19:18:53 +02:00
cacc8ead4a Merge branch 'main' into localisation 2026-10-23 19:07:23 +02:00
557664c41f Merge branch 'fix-furling-remote-scale': other players see a Furling at Furling size 2026-10-23 19:07:14 +02:00
e125c6bc67 Merge branch 'fix-trol-legacy-weapon-reach': a resized player's weapon hits as far as it is drawn 2026-10-23 19:07:14 +02:00
95c8a7b1b6 fix(furling): other players see a Furling at Furling size
The 0.81 scale was applied from a Player.Update postfix that returned for
anyone but the local player and read the race from the local m_customData.
Scale is not replicated, so a Furling was small only on their own screen.
The postfix now sizes every player, with the race read off the ZDO the way
the Dvergar and the Trol already do it.
2026-10-23 19:03:58 +02:00
691ccc211b fix(visuals): a resized player's weapon hits as far as it is drawn
Attack.DoMeleeAttack and DoAreaAttack measure range and ray width from
the unscaled root, so a Legacy True Form Trol at 2.5 still hit at a
human's 2 m while the drawn mace reached five. Both now grow by the
Visual's world scale (never below 1), the factor HeldItemScaleFix sizes
the weapon by. Height stays at the feet so a flat swing does not pass
over small enemies. F8 toggles an in-game readout of the stretched
numbers and what a cast straight ahead passes through.
2026-10-20 03:17:08 +02:00
99f409c8be Merge remote-tracking branch 'origin/main' into localisation 2026-10-19 14:30:42 +02:00
9dd6600287 chore(release): v1.5.13 - no faction AI freeze, Dvergar build discount
With factions on, destroying a piece a mob was targeting froze every AI in
the area on servers. Dvergar pieces now build at the discounted metal cost
the menu shows, and refund what was paid.

README: New in block and changelog entry. Compendium: the Dvergar smithing
discount also covers building, in English, Italian and Russian.
2026-10-19 14:30:35 +02:00
b3bdb0f75a Merge remote-tracking branch 'origin/main' into localisation 2026-10-19 14:26:56 +02:00
64fbd66987 Merge branch 'fix-static-target-null': no AI freeze when a targeted piece is destroyed 2026-10-19 14:24:31 +02:00
faea08901c Merge branch 'fix-dvergr-build-discount': build pieces accept the Dvergar smithing discount 2026-10-19 14:20:40 +02:00
32c49a8af0 fix(dvergar): build pieces accept the smithing discount
The build menu showed the discounted metal cost, but Player.HaveRequirements(Piece)
read m_amount directly, so placing a piece still needed the full vanilla amount.
It now goes through GetAmount like the rest of the cost path.

Piece.DropResources also read m_amount, which would have refunded 10 tin for a
cauldron that cost 6. A piece placed by a Dvergar now stores the discount paid,
and dismantling it drops that amount.
2026-10-19 14:20:28 +02:00
6d9f07217e fix(factions): no AI freeze when a targeted piece is destroyed
FactionStaticTargetPatch read m_targetStatic as a boxed object, so the
null check missed Unity's destroyed-object state. A piece destroyed
while a mob targeted it passed the check, and reading its gameObject
threw. The throw escaped into MonoUpdaters.FixedUpdate and stopped
every AI after that mob, every frame, until the field changed.

Cast to Component and use Unity's null check; clear a dead target.
2026-10-18 13:33:21 +02:00
92c80e3b87 Merge branch 'main' into localisation 2026-10-18 00:19:25 +02:00
9d459fbc99 chore(release): v1.5.12 - hair back after a form with Valkyr
With the Valkyr body replacer, leaving any monster form brought the body back
without its hair. Fixed in PlayerVisualHider.

README: New in block and changelog entry.
2026-10-18 00:18:36 +02:00
b028a309d2 Merge branch 'fix-valkyr-hair': hair comes back after a form with Valkyr 2026-10-18 00:17:16 +02:00
5dff5e1b84 fix(forms): hair comes back after a form with Valkyr
Valkyr sets its hair's forceRenderingOff on every visual update. The hider
read that flag as "not hidden yet", recorded the hair a second time with
enabled already false, and the revert left it off. Track hidden renderers
in a set instead of trusting the flag.
2026-10-18 00:09:14 +02:00
589127b7df Merge branch 'main' into localisation 2026-10-17 20:30:37 +02:00
f1d00f6eff chore(release): v1.5.11 - True Form troll, race stations, Ravager attacks
Trol True Form wears the vanilla forest troll, with a per-player Legacy
switch for model mods. Race stations show and require their race and go on
floors and in caves. Fenrir forms sneak and stand still to attack; the Ulv
sleeps when the player sits. The Ravager attacks on the Brute's own clips.
Fixes: ResetRace, troll cave collapse, [msg_] texts, build-mode attacks,
War Vulture startup error.

README: New in block, changelog entry, Trol/Fenrir/Sverm feature lines and
the stations section.
2026-10-17 20:30:37 +02:00
174e615ed9 Merge branch 'main' into localisation 2026-10-17 20:28:54 +02:00
7e6d3d0936 Merge branch 'fix-ravager-attacks': Ravager attacks follow the Brute's clips, ram lunges, slam digs per claw; War Vulture startup error gone 2026-10-17 20:28:54 +02:00
63e252d9e9 feat(sverm): the Ravager's ram lunges with the clip's root motion
Vanilla only takes root motion during a native attack, which this form never
starts, so a relay on the costume's Animator collects it and a prefix on
Character.ApplyRootMotion applies it to the player the same way (x55).
2026-10-17 20:24:43 +02:00
d05cea7f08 fix(warvulture): strip dependents first, no more Can't remove Humanoid at startup
The startup error came from WarVultureVisual.BuildTemplate, not from the
Ravager costume: its passes tried Humanoid before CharacterDrop. Components
another one still requires now wait for a later pass.
2026-10-17 20:24:43 +02:00
61a74320c5 fix(sverm): Ravager attacks follow the Brute's clips; the slam hits once per claw
Hits land on the clip's own Hit events and the hold-still lasts until the
animator leaves the attack state, instead of fixed delays. The slam has two
Hit events, one per claw: each one hits and digs under the claw that came down.
2026-10-17 20:05:36 +02:00
1c2da77603 fix(sverm): the Ravager stands still to attack and its slam digs
The hidden player kept walking under the costume, so every swing slid
toward whatever WASD held. A SetControls prefix holds it still while an
attack runs, as Fenrir and the True Form troll do. The middle-click slam
now digs a crater on bare terrain (digg_v3), never inside a ward without
access, behind a new Ground Slam Crater option.
2026-10-17 19:51:33 +02:00
5cf1ae7fb0 fix(sverm): the Ravager costume no longer keeps a live Humanoid
The BepInEx log showed "Can't remove Humanoid (Script) because
CharacterDrop (Script) depends on it" right after the Ravager template
was built from SeekerBrute. The strip was one pass in component order,
and Unity refuses to destroy a component another still requires, so
the Brute's Humanoid survived on the costume and on every copy a
player wore: the leftover that once broke the hammer for every piece.

ModelBorrow.StripBehaviours destroys only what nothing remaining
requires through [RequireComponent], round after round, and logs any
survivor by name. Used by the Ravager template, by ModelBorrow.Attach
and by the Skeleton's rise costume, which had the same single pass.
2026-10-17 19:42:14 +02:00
20e08432b8 Merge branch 'main' into localisation 2026-10-17 19:39:13 +02:00
ee154ccab4 Merge branch 'fix-form-build-gate-chair' 2026-10-17 19:39:13 +02:00
ba7f56550d fix(forms): no form attacks in build mode; chair pose 1 m out, turned
RaceInput.AttackDown and AttackHeld now return false while the player
is in place mode (hammer, hoe, cultivator). Right click removes a piece
there and middle click picks a snap point, and every form read both as
its own attacks. Allowed only covered the piece selection panel. Every
form reads the mouse through RaceInput, so all of them are covered.

On a chair the form now settles 1 m in front of the seat and turns a
quarter counter-clockwise, at the player's request after the first try.
2026-10-17 19:34:51 +02:00
a28fb19845 Merge branch 'main' into localisation 2026-10-17 19:33:39 +02:00
9662ec6b38 Merge branch 'feat-form-sleep-sneak': Ulv sleeps when the player sits 2026-10-17 19:33:39 +02:00
5c0f092c89 fix(fenrir): a form on a chair settles in front of the seat
On a chair the player sits on the seat, and the form stood inside the
chair at seat height. The form's root now goes 0.5 m in front of the
seat, on whatever is under that point, skipping the seat's own
colliders. The seat is found by a short raycast under the player, so
it works for onlookers too, who have no attach point. Back to zero on
standing up; the sit key is untouched.
2026-10-17 19:28:42 +02:00
e83c3c5d74 fix(fenrir): enter the Ulv's sleep by its real state path
scripts/dump_controller.py reads an AnimatorController's states and
transitions offline from Valheim's bundles with UnityPy. On
ulv_animator it shows the entry state "check sleeping" picks Sleep only
at start-up and Movement has no way back into it, so the bool alone
could never work. The cross-fade now targets "Base Layer.Sleep".
2026-10-17 19:22:34 +02:00
fb354c2387 fix(fenrir): enter the Ulv's Sleep state by hand when the player sits
A vanilla Ulv is born asleep: its controller only knows the way out
of Sleep, so setting the bool from Idle did nothing. The state is now
cross-faded into when the player sits; standing drops the bool and the
controller's own 'Sleep to Idle' plays. The log names the state found.
2026-10-17 19:13:47 +02:00
9cf3f5386c fix(fenrir): the Ulv sleeps when the player sits
Sitting now zeroes the form's speed. The seated player's Animator keeps
a forward_speed above zero, which kept the Ulv in its Walk clip on the
spot and out of reach of its Sleep state, which leaves from idle. The
debug log showed it: sitting, sleeping=true, clip 'Walk'.
2026-10-17 19:09:50 +02:00
4cb6da801b Revert "debug: log the Ulv's sleep state while the player sits (temporary)"
This reverts commit 2df8264c42.
2026-10-17 19:09:38 +02:00
d28f9e353a Merge branch 'main' into localisation 2026-10-17 19:07:01 +02:00
727338c400 Merge branch 'main' into feat-form-sleep-sneak 2026-10-17 19:07:01 +02:00
1592282a46 Merge branch 'feat-form-sleep-sneak': sneak at a walk, stand still to attack 2026-10-17 19:07:00 +02:00
2df8264c42 debug: log the Ulv's sleep state while the player sits (temporary) 2026-10-17 19:06:08 +02:00
96dc8e4158 fix(fenrir): Ulv sleeps on the sit key; forms stand still to attack
Humanoid.IsSitting asks about the "sitting" animator tag, which belongs
to chairs. The sit key is an emote that Player.StartEmote writes on the
ZDO as "sit", so the Ulv never saw the player sit down. FormLocomotion
now reads the ZDO emote too, which every client sees. Of the four
forms only ulv_animator has a sleeping state.

The hidden player kept walking under the form through an attack, so a
bite slid toward whatever WASD held. Each form's isAttacking now also
sets FenrirForms.LocalAttacking, and a SetControls prefix holds the
player still while it is set, as the True Form troll does. The leaps
move the body directly and are untouched. Cleared on every revert.
2026-10-17 19:01:03 +02:00
580ef6d468 feat(fenrir): forms sneak at a walk and sleep when the player sits
FormLocomotion zeroed the speed whenever the player crouched, so a
sneaking form slid across the ground in its idle pose. Only airborne
reads as still now: crouched, the player moves at sneaking speed and
the creature's controller picks its walk.

Sitting sets the "sleeping" bool the creature's own MonsterAI uses,
when its controller has one; the log says once per controller which do.
IsSitting reads the replicated animator state, so onlookers' copies
sleep too. Covers every Fenrir form, local and remote, and the True
Form troll, which share FormLocomotion. Mirror now takes the Player.

Requested by a player on Discord.
2026-10-17 18:51:14 +02:00
d120ec8dc2 Merge branch 'main' into localisation 2026-10-17 17:15:54 +02:00
8843e773b1 Merge branch 'fix-race-requirement-first' 2026-10-17 17:15:54 +02:00
7647b66aa0 fix(stations): the race requirement comes first in the build panel
The race took the first free row after the materials and the crafting
station. Each of those rows now moves one to the right and the race
takes row 0: it decides whether the rest matters at all.
2026-10-17 16:39:56 +02:00
a2a4bcf451 Merge branch 'main' into localisation 2026-10-17 16:24:09 +02:00
ce21036373 Merge branch 'feat-race-station-requirement' 2026-10-17 16:24:09 +02:00
5b2e5f4f86 feat(stations): the race is a build requirement, shown in the panel
Every race station is listed in RaceStationLock with the race (or
races) that may build it. The build panel shows it in the requirement
row after the materials and the crafting station, with the race's icon
from the race menu and its translated name, blinking red when the
player is not of that race, the way vanilla flags a missing station.
Player.HaveRequirements answers false for CanBuild, so the piece is
greyed and a click gets vanilla's "Missing requirements". IsKnown and
CanAlmostBuild stay vanilla, so every station is still listed.

Seven stations had no race lock at all and are now locked too: Cursed
Body Pile, Pack Trough, Bone Pile, Bound Sentry, Blood Refinery,
Composter and Heartwood Grove. The stations' own placement gates stay
for their boss-tier checks and for no-cost debug building.
2026-10-17 16:24:09 +02:00
b6e085e378 Merge branch 'main' into localisation 2026-10-17 16:22:29 +02:00
cf5c9ef3ce Merge branch 'fix-totem-ghost' 2026-10-17 16:22:29 +02:00
0cc10b437e Revert "debug: F8 dumps the build ghost and the placement ray (temporary)"
This reverts commit edc7fd33b7.
2026-10-17 16:21:50 +02:00
e1bd3b66e1 fix(trol): War Totem ghost invisible everywhere
The totem borrowed its look from the GoblinTotem item, whose root holds
a ParticleSystem while the mesh sits in its attach child.
Player.SetupPlacementGhost switches off every GameObject with a
ParticleSystem, so it took the root and the mesh with it: the F8 dump
showed TotemModel/model/attach/model active=False on the ghost. The
Yagluth head (TrophyGoblinKing) is built the same way.

Both now borrow the item's attach child, which is the mesh itself.
ModelBorrow switches the copy on, since an item's attach is stored
inactive in its prefab.
2026-10-17 16:19:03 +02:00
edc7fd33b7 debug: F8 dumps the build ghost and the placement ray (temporary) 2026-10-17 16:11:16 +02:00
268ed47589 Merge branch 'main' into localisation 2026-10-17 15:59:09 +02:00
ea1efef56e Merge branch 'fix-placement-ghost' 2026-10-17 15:59:08 +02:00
916ba5bd6f fix(pieces): placement ghost vanished off terrain for most stations
Eleven pieces set m_groundPiece. Player.UpdatePlacementGhost switches
the ghost off outright and returns whenever the aim is not on a
Heightmap, which vanilla means for hoe and cultivator pieces. Floors,
rocks and a troll cave's mesh floor are not a Heightmap, so players
saw no ghost at all there, and with either flag Valheim never shows
the blue placement marker. Reported for the Trol War Totem.

m_groundPiece is off everywhere now. The stations (War Totem, Cursed
Body Pile, Dvergar Bank, Rune Barrel, Pack Trough, Skadi Golem, Bone
Servants) drop m_groundOnly too and go on floors, foundations and in
caves, like the Bone Pile since 1.5.8. The living pieces (Furling
bushes, Sverm nest and Hive Market, Trenta Elder Root) keep
m_groundOnly: terrain only, and the ghost shows red elsewhere.
2026-10-17 15:59:08 +02:00
03cca64a48 Merge branch 'main' into localisation 2026-10-17 15:51:54 +02:00
b8661b78f3 Merge branch 'fix-missing-msg-texts' 2026-10-17 15:51:54 +02:00
e86e1e3da5 Merge branch 'fix-faction-pieces' 2026-10-17 15:51:54 +02:00
87d0f2642c fix(texts): four messages showed as [msg_...]
Four tokens the mod printed exist in no vanilla table (checked on
Valheim 1.0.20) and were never registered by the mod, so players saw
the raw name in brackets.

- $msg_eatanother (Trol, a food still being digested): vanilla's
  $msg_nomore, "You can't eat more $1", called as Player.CanEat calls it.
- $msg_canteatanymore (Trol, every stomach full): vanilla's $msg_isfull.
- $msg_ate (Aswid, Vae Victis): vanilla's $msg_consumed.
- $msg_notenoughmoney (Dvergar bank, Trol totem): a new mod text,
  rov_msg_not_enough_coins, in English, Italian and Russian.
2026-10-17 15:51:53 +02:00
b566adbfb9 fix(factions): allied mobs spare a race's buildings with nobody home
FactionStaticTargetPatch only vetoed a mob's piece target while an
allied player stood within 100 m. Inside a troll cave that was the
collapse bug: the Trol walks out, the resident Troll (its prefab has
m_attackPlayerObjects) finds nobody to stop it, and the cooking station
built there is in pieces when the Trol comes back.

Every piece now carries the race of its builder on its ZDO, stamped in
Piece.SetCreator at placement, and in Piece.Awake for older pieces the
first time their builder loads them, so no timer and no scan. An
allied mob of that race can't pick the piece as a target and its blows
do it no damage, which also covers a swing at a foreign wall that
would have hit the Trol's workbench next to it. A mob holding a grudge
against the builder gets no such truce.
2026-10-17 15:50:41 +02:00
e38df0b7e0 Merge branch 'main' into localisation 2026-10-17 15:32:06 +02:00
d16524beec Merge branch 'feat-trol-true-form-model' 2026-10-17 15:32:06 +02:00
b2346c1437 feat(trol): Legacy True Form switch, chosen per player
The Troll Model option becomes Legacy True Form, off by default. On,
True Form is the old one: the player's own Trol grown bigger, weapons
in hand, body untouched, which player model mods such as VRM need.

It is a local preference, not a synced one, so a server cannot force
the troll costume on a VRM user. The owner publishes the choice on the
ZDO and every other client reads it from there, so onlookers see each
Trol the way that Trol's owner picked.
2026-10-17 15:32:06 +02:00
a9e66aeeb7 fix(trol): True Form log visible, slam reaches the ground, skin tint
The log in the troll's fist was there but switched off: an item's
attach child is stored inactive in its prefab and VisEquipment turns
it on after the Instantiate. It is now switched on, hung with the
item's equipoffset, and sized to the costume, since AttachItem keeps
an attach at its world size and the costume is not at scale 1.

The slam never ran its slam code. troll_groundslam is a Vertical
attack in vanilla, not Area, so asking the attack type sent every slam
down the punch's sweep: damage, but no AoE, no dust and no crater. The
slam now goes by the key that was pressed.

The tint multiplied _Color, which the creature shader does not read.
It now shifts _Hue, _Saturation and _Value, as LevelEffects does for
starred creatures, by the distance from the vanilla troll's colour to
the player's skin colour.
2026-10-14 17:17:20 +02:00
db29f868ea fix(trol): True Form troll size, log, reach, root during attacks, slam
The troll pulsed several times a second and stayed small because
PlayerVisualHider.Hide put the hidden Visual back to scale 1 every
frame while Trol_PlayerUpdate_Patch grew it back, and the troll follows
that scale. Hide and Show take keepScale now, and the Trol calls pass
it. The camera height, which reads the same scale, stops jumping too.

The log in the troll's hand is the troll's own log model, hung the way
VisEquipment does it, instead of the Trol's, which was built for a
person's hand and came out huge and sideways.

Punch and slam reach further and hit wider, with a new Troll Attack
Reach option (1.3). The player is held still through every attack
clip, throw included.

The ground slam spawns the troll's own troll_groundslam_aoe with the
player's damage, kept off friends, plus its trigger and terrain
effects. It carries chop and pickaxe at least equal to its blunt, so
it breaks trees and rocks, and with Ground Slam Crater on it digs into
the terrain where it lands, never inside a ward without access.
2026-10-14 17:08:20 +02:00
c64cb393c7 feat(trol): True Form wears Valheim's own troll
True Form now hides the Trol's body and puts the vanilla forest troll's
model in its place, on the owner's client and on every other player's.
The costume stands as tall as the old True Form did: it follows the
Visual scale Trol_PlayerUpdate_Patch already grows and publishes, so
the grow-in, the shrink back and the size others see come for free.
It takes the Trol skin colour from Trol - Appearance.

Weapons are out while it is up. Left click is the troll's punch, right
click its ground slam, and with a log in hand they become its two log
swings, which wear the log down per hit as a club swing did. Throw
Rock plays the troll's throw. The attacks, their triggers and reach are
read off the troll's own weapons at runtime, and each hit lands on the
troll's OnAttackTrigger event rather than a fixed delay.

Damage is a share of the troll's own (Troll Attack Damage, 0.5), scaled
by the Clubs skill like a club and hit as Clubs, so the True Form and
tier melee bonuses still add on top.

Other players see the troll from the existing True Form ZDO flag, with
attacks replayed from a new trigger key. New options in Trol - True
Form: Troll Model (on/off), Troll Model Size, Troll Attack Damage.
2026-10-14 16:56:34 +02:00
bf63b790f1 Merge branch 'main' into localisation 2026-10-14 16:41:52 +02:00
927bda1bbc Merge branch 'fix-resetrace-cleanup' 2026-10-14 16:41:52 +02:00
d5c2d58636 fix(resetrace): drop every form and every mod status effect on reset
ResetRace now undoes each race's form on the spot before it touches
status effects: Aswid bat and mist, Fenrir, Skadi drake, Trol True
Form, Trenta Muspell and Sverm Ravager. Each race gets a
HardResetForReset that stops the form's coroutine, so a transform
caught mid-gesture can't finish after the reset and a revert can't
hand out its cooldown after the sweep.

The hand-written status effect list is gone. The reset now removes
everything the mod registers through Jotunn (ModRegistry), which
covers the True Form and its cooldowns, Bat and Mist Form, the
Skeleton resurrect cooldown and Skadi's ability cooldowns.

It also puts the player and the Visual back to scale 1, clears the
Sverm's static Ravager cooldown and the Trol's wasTrueFormActive flag,
and prints what it removed to the console and the BepInEx log.
2026-10-14 16:40:27 +02:00
65b488b5dc feat(trol): skin and hair colour pickers in Trol - Appearance
Two Color entries, Skin Color and Hair Color (hair and beard), defaulting
to the old peacock blue and golden blonde so no Trol changes on update.
Each Trol publishes its choice on its own ZDO and every client paints
that player with it; a Trol on an older build publishes nothing and shows
the defaults. The menu preview, with no ZDO, reads the local config.
The section is kept local by ConfigSync.

README: New in block, Trol features line and a 1.5.10 changelog entry.
2026-10-14 14:14:06 +02:00
bb1ca57924 chore(release): v1.5.10 - Skeleton body switch for player model mods
New client-side option Skeleton - Visuals -> Body Model Enabled. Off,
a Skeleton takes the human branch of the VisEquipment postfix: vanilla
body on, no bone meshes, eye glow, jaw correction or skull flame, and
the helmet is left alone. Requested by players using EnhancedValheimVRM,
where the bones floated around the replacement model.

README: New in block for v1.5.10, changelog entry (also the Russian
fixes since 1.5.9), and a line under the Skeleton features.
2026-10-13 20:00:03 +02:00
358b537cef Merge branch 'main' into localisation 2026-10-08 18:22:13 +02:00
aca3eabb2f Merge branch 'localisation' 2026-10-08 18:22:13 +02:00
fb32a49576 Merge remote-tracking branch 'origin/localisation-russian' into localisation 2026-10-08 18:22:05 +02:00
f1fbebb8c7 Обновить JotunnModStub/Translations/Russian/items.json 2026-10-08 08:14:18 +02:00
d86609acef Обновить JotunnModStub/Translations/Russian/hover.json 2026-10-08 08:13:43 +02:00
a1261af0f1 Обновить JotunnModStub/Translations/Russian/compendium.json 2026-10-08 08:12:25 +02:00
a75655d3e5 Обновить JotunnModStub/Translations/Russian/messages.json 2026-10-08 08:05:10 +02:00
875024e649 Обновить JotunnModStub/Translations/Russian/messages.json 2026-10-08 07:58:42 +02:00
3c86d48aad Обновить JotunnModStub/Translations/Russian/merchants.json 2026-10-08 07:57:46 +02:00
9f11cab70d Обновить JotunnModStub/Translations/Russian/hover.json 2026-10-08 07:57:09 +02:00
c45ca80d99 Обновить JotunnModStub/Translations/Russian/compendium.json 2026-10-08 07:52:10 +02:00
8bad4092be Обновить JotunnModStub/Translations/Russian/races.json
по канону Valheim 
Драуг - Драугр
2026-10-08 07:45:13 +02:00
Ferdinando
0159f1e8c4 bugfix 07/10/26 + evil laugh 2026-10-07 17:31:29 +02:00
b63f810a8f Merge branch 'localisation' into localisation-russian 2026-10-07 04:11:26 +02:00
3815f2bf53 Merge remote-tracking branch 'origin/main' into localisation 2026-10-07 04:11:24 +02:00
eaa87f892a Merge branch 'fix-skeleton-revive-bonepile' 2026-10-07 04:11:08 +02:00
68cdbd6de6 chore(release): v1.5.8 - Skeleton rise, truce for bound troops
README: the New in block is v1.5.8 only, a changelog entry for the three
fixes, and the Skeleton stations line says the pile and the Sentry go on
floors too.
2026-10-07 04:11:08 +02:00
1848725f2a fix(skeleton): rise on resurrect, truce for bound troops, pile and sentry on floors
The Yagluth auto-resurrect now plays the crypt rise. The player rig has no
rise state, so the body is hidden and the skeleton model is worn for the
length of the clip with "wakeup" set; the start time goes on the ZDO so
other clients play it too. The player takes no damage and does not move
until it is out.

Wild faction mobs left the player alone but attacked the player's thralls,
which are tamed and so in the Players faction. IsEnemy now gives a thrall
the same truce through its m_commandingRace, broken by a grudge against
any player. Covers every race with thralls.

The Bound Bone Pile and the Bound Sentry seed drop m_groundPiece and
m_groundOnly, so both can be built on floors and foundations.
2026-10-07 04:11:08 +02:00
19e6a3ce50 Merge branch 'main' into localisation-russian 2026-10-06 14:20:25 +02:00
41020a0fab Merge branch 'main' into localisation 2026-10-06 14:20:23 +02:00
02c640e1d9 chore(release): v1.5.7 - Bone Ships and the Russian translation
README: the stack of "New in" blocks at the top is down to the latest
release, a languages line with flags sits under the intro, Bone Ships gets
its own section, and the Translations section credits Rudra and Axibed for
the Russian. nexus-readme.py keeps an image inside a line of text inline,
so the flags do not come out as 350 px pictures on Nexus.
2026-10-06 14:20:22 +02:00
8cad29f5a1 Merge branch 'localisation' into localisation-russian
# Conflicts:
#	JotunnModStub/Translations/Russian/compendium.json
#	JotunnModStub/Translations/Russian/hover.json
#	JotunnModStub/Translations/Russian/items.json
#	JotunnModStub/Translations/Russian/merchants.json
#	JotunnModStub/Translations/Russian/messages.json
#	JotunnModStub/Translations/Russian/races.json
#	JotunnModStub/Translations/Russian/status_effects.json
2026-10-06 14:00:02 +02:00
04053d64cc Merge branch 'main' into localisation 2026-10-06 13:59:54 +02:00
60e9b0ab72 localisation(ru): add Russian translation
Merged from two community translations (Rudra and Axibed). Axibed's set is
the base; Rudra's lines replace it where they read better or are more
faithful, mostly the merchant jokes. Boss, creature and resource names follow
vanilla Valheim's own Russian (Матерь, Прародитель, Драугр, Эйтр,
Быкоящер, Пеплозавр, Масса костей). Ability names that are quotes or song
titles stay in English, as in Italian. The bone-ship and thrall-order keys
that neither translation had are translated here.
2026-10-06 13:59:52 +02:00
e331708682 Merge branch 'localisation' into localisation-russian 2026-10-06 13:46:53 +02:00
9e943d5442 Merge remote-tracking branch 'origin/main' into localisation 2026-10-06 13:46:51 +02:00
2f744cf3b3 scripts: add sync-localisation.sh to carry main into the translation branches 2026-10-06 13:46:46 +02:00
f4652de7e5 Merge branch 'localisation' into localisation-russian 2026-10-06 13:46:01 +02:00
c5eef16dc2 docs: add translator guide 2026-10-06 13:46:00 +02:00
b9dc72fdd0 localisation(ru): add Russian skeleton from English 2026-10-06 13:36:31 +02:00
Ferdinando
553303d0fd bugfix 06/10/26 + bone ship 2026-10-06 11:36:18 +02:00
Ferdinando
7a863b07a6 bugfix 05/10/26 2026-10-05 11:39:38 +02:00
Ferdinando
9690d4d2a1 docs: drop the 'not tested in game yet' notes from the public changelog
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 07:34:11 +02:00
Ferdinando
5113225981 chore(release): v1.5.5 - Sverm Gjall bombs spare the player and the ticks they hatch are tame
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 07:31:16 +02:00
Ferdinando
9a3ab78666 chore(release): v1.5.4 - Sverm troops keep their own place around the player and the boat
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 08:11:05 +02:00
Ferdinando
a047ea45cf bugfix 01/10/26 + deepnorth food 2026-10-01 08:21:50 +02:00
Ferdinando
b9ac02fe50 chore(release): v1.5.3
Version bumped in manifest.json, the packaging manifest and PluginVersion.
Valheim 1.0's new creatures for the Aswid and the Draugh (seal, moose,
Elaking, Jotun, Barka, Deep North Goblin and every Dvergr), the Elaking
Hair Bundle in the blood refinery, and the Skeleton choosing its look at
the barber.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 08:19:47 +02:00
c5ff57530d Merge branch 'release-v1.5.2' 2026-09-30 22:43:45 +02:00
fa0e2cbb06 chore(release): v1.5.2
Version bumped in manifest.json, the packaging manifest and PluginVersion.
The one change is the Thunderstore package keeping the mod under plugins/,
so mod managers no longer take the Translations folders apart. The
changelog explains why 1.5.1's zip fix was not enough, and the README
leads with it.
2026-09-30 22:43:44 +02:00
2f7401099e Merge branch 'fix-thunderstore-plugins-folder' 2026-09-30 22:42:59 +02:00
d866f137fb fix(package): the Thunderstore package keeps the mod under plugins/
Mod managers (r2modman, the Thunderstore Mod Manager, Gale) copy what is
inside a top-level plugins/ folder into BepInEx/plugins/<Author-Mod>/
with its structure, and flatten folders they do not recognise. 1.5.1's
Translations/English/items.json landed as a loose items.json beside the
DLL, the Italian copy of each file overwrote the English one, and Jotunn
found no translations. Reproduced in a clean r2modman profile; with the
DLL and Translations under plugins/ the import keeps both language
folders and the texts show.
2026-09-30 22:42:59 +02:00
46df449c82 Merge branch 'fix-thunderstore-readme-anchors' 2026-09-30 19:52:12 +02:00
2ccb09e67a fix(package): the Thunderstore README has no in-page anchor links
Thunderstore renders the README on the mod page but does not resolve
anchors, so links like [changelog](#v151) went nowhere. The package now
gets a copy with those links turned into plain text, as nexus-readme.py
already does for Nexus. The repo README keeps them, since they work on
the wiki and the git host.
2026-09-30 19:03:06 +02:00
22237d647d Merge branch 'release-v1.5.1' 2026-09-30 16:04:17 +02:00
ecc238a728 chore(release): v1.5.1
Version bumped in manifest.json, the packaging manifest and PluginVersion.
The Unreleased changelog becomes v1.5.1 with the "TO BE TESTED" tags
removed, the translation entry now covers mod-manager installs and says
to reinstall if keys still show, and the lead section describes 1.5.1.
2026-09-30 16:04:17 +02:00
c5fb99fbbd docs(changelog): reach grows with height 2026-09-30 14:00:47 +02:00
782d49e0eb Merge branch 'fix-interact-range-scale' 2026-09-30 14:00:46 +02:00
d502eda748 fix(visuals): a taller player reaches as far as they are tall
Vanilla only takes a hover target within m_maxInteractDistance (5 m) of
the eye, and RaceEyeHeight raises the eye with the model. A True Form
Trol's eye stands about 4 m up, so a log at its feet was already out of
reach and Grab Log worked on one small spot under the camera. The range
now grows by the same ratio as the eye (10-12.5 m in True Form, the
Muspell by its own eye), and never drops below vanilla for smaller races.
2026-09-30 13:57:51 +02:00
be1c676c2f docs(changelog): Sverm dorsal spines off for now 2026-09-30 13:51:12 +02:00
74363e12ee Merge branch 'fix-sverm-spines-off' 2026-09-30 13:51:12 +02:00
215 changed files with 24492 additions and 1838 deletions

27
.claude/launch.json Normal file
View file

@ -0,0 +1,27 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "nandor-museum",
"runtimeExecutable": "npm",
"runtimeArgs": [
"--prefix",
"C:/Users/FERDINANDO/Desktop/JotunnModStub-master/NandorMuseum",
"run",
"dev"
],
"port": 5190
},
{
"name": "nandor-museum-build",
"runtimeExecutable": "npm",
"runtimeArgs": [
"--prefix",
"C:/Users/FERDINANDO/Desktop/JotunnModStub-master/NandorMuseum",
"run",
"preview"
],
"port": 5191
}
]
}

1
.gitattributes vendored Normal file
View file

@ -0,0 +1 @@
*.sh text eol=lf

4
.gitignore vendored
View file

@ -27,4 +27,6 @@ Thumbs.db
*.lnk *.lnk
# How to setup Configuration Manager # How to setup Configuration Manager
CONFIGURATION-MANAGER-HOWTO.md CONFIGURATION-MANAGER-HOWTO.md
# Written by scripts/publish.* on a Release build from the root README; never edit or commit it.
/JotunnModStub/Package/README.md

View file

@ -0,0 +1,179 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// SAMEINING, the archon (Alfar_Progettazione.txt sec. 13.8): Fader's power, an all-or-nothing form.
///
/// - needs 75% of the maximum eitr and a READY Heimkall, and spends ALL the eitr;
/// - lasts up to three minutes: bigger (x1.5), glowing, +20% speed;
/// - instead of armour there is a POOL of points, three per eitr spent: every blow lands on it,
/// and when it is gone the form ends early;
/// - no weapons: a psionic pulse strikes everything hostile around the body, once a second;
/// - Ljosstorm and Geisli cost nothing in the form, but wait a few seconds between uses;
/// - it ENDS (time up, pool gone) with a teleport home at one hit point, eitr at zero, and the
/// Heimkall wait starting. The form IS a Heimkall spent on purpose.
///
/// The form is published in the ZDO so other players see the size and the glow.
/// </summary>
public static class AlfarArchon
{
public const string ZdoKey = "Alfar_Archon";
public static bool Active { get; private set; }
public static float Pool { get; private set; }
public static float EndsAt { get; private set; }
public static float StartedAt { get; private set; }
private static float nextPulse;
/// <summary>True for any player in range: the form is read off the ZDO, not local state.</summary>
public static bool IsArchon(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
return nview != null && nview.IsValid() && nview.GetZDO().GetInt(ZdoKey, 0) == 1;
}
public static bool IsLocalActive => Active && Player.m_localPlayer != null;
private static void Publish(Player player, bool on)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(ZdoKey, on ? 1 : 0);
}
// ─── Entering ────────────────────────────────────────────────────────
public static bool TryActivate(Player player)
{
if (Active || player == null) return false;
float max = player.GetMaxEitr();
float eitr = player.GetEitr();
if (max <= 0f || eitr < max * AlfarPowerConfig.ArchonThreshold.Value)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_charged"));
return false;
}
if (!AlfarHeimkall.IsReady(player))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_ready"));
return false;
}
// Everything goes in: the strength of the form is what the Alfr had eaten.
Pool = eitr * AlfarPowerConfig.ArchonPoolPerEitr.Value;
AlfarEitr.Spend(player, eitr);
Active = true;
StartedAt = Time.time;
EndsAt = Time.time + AlfarPowerConfig.ArchonSeconds.Value;
AlfarStatusEffects.ShowTimer("archon", AlfarPowerConfig.ArchonSeconds.Value);
nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value;
Publish(player, true);
Jotunn.Logger.LogInfo($"[Alfar] Sameining on: pool {Pool:0} for {AlfarPowerConfig.ArchonSeconds.Value:0}s.");
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_on"));
return true;
}
// ─── In the form ─────────────────────────────────────────────────────
/// <summary>
/// Takes a blow into the pool. Called from the shield prefix before anything else, because in
/// the form the pool IS the defence: every type of damage, drowning and the edge of the world
/// included, since nothing else can end the form but the pool and the clock.
/// </summary>
public static void Absorb(Player player, HitData hit)
{
if (!Active || hit == null) return;
float total = hit.m_damage.GetTotalDamage();
hit.m_damage = default(HitData.DamageTypes);
if (total <= 0f) return;
Pool -= total;
// The exit itself is done in Tick, outside the damage call.
}
public static void Tick(Player player)
{
if (!Active) return;
if (player == null || player.IsDead())
{
// The body is gone (or the world is): nothing to teleport, only the state to drop.
Active = false;
if (player != null) Publish(player, false);
return;
}
if (Pool <= 0f || Time.time >= EndsAt)
{
Exit(player, Pool <= 0f ? "pool gone" : "time up");
return;
}
if (Time.time >= nextPulse)
{
nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value;
// The pulse fires on its own while the form lasts, so it earns what an aura does:
// a tenth of a hit per second, once per pulse that struck something.
if (AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value))
FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, 0.1f * AlfarPowerConfig.ArchonPulseInterval.Value);
}
}
// ─── Leaving ─────────────────────────────────────────────────────────
public static void Exit(Player player, string reason)
{
if (!Active) return;
Active = false;
Pool = 0f;
Publish(player, false);
AlfarStatusEffects.ClearTimer("archon");
// Eitr to zero, then the Heimkall: the form spends the one that was ready.
AlfarEitr.Spend(player, player.GetEitr());
AlfarHeimkall.TryTrigger(player, "Sameining " + reason, force: true);
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_off"));
Jotunn.Logger.LogInfo($"[Alfar] Sameining off ({reason}).");
}
/// <summary>The cooldown Ljosstorm and Geisli wait in the form, instead of costing eitr.</summary>
public static float FreePowerCooldown => AlfarPowerConfig.ArchonFreePowerCooldown.Value;
/// <summary>
/// NO WEAPONS in the form: the psionic pulse is the attack. Humanoid.StartAttack is the one
/// door every swing, shot and draw goes through (verified, doc sec. 16B); returning false
/// with a false result is "nothing started".
/// </summary>
[HarmonyLib.HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Alfar_Archon_NoWeapons_Patch
{
public static bool Prefix(Humanoid __instance, ref bool __result)
{
if (Active && __instance == Player.m_localPlayer)
{
__result = false;
return false;
}
return true;
}
}
/// <summary>Clears the state without teleporting (used by the reset command).</summary>
public static void ForceClear(Player player)
{
Active = false;
Pool = 0f;
if (player != null) Publish(player, false);
AlfarStatusEffects.ClearTimer("archon");
}
}
}

View file

@ -0,0 +1,79 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The light on the two Alfar chests, which says whether the drones have work there: the fire
/// chest's grate burns while it holds wood they may burn, the entry chest's inlay shines while it
/// holds anything but the sigil. Every client asks its own copy of the inventory, which Container
/// keeps in step with the ZDO, so nothing travels over the network for it.
/// </summary>
public class AlfarChestGlow : MonoBehaviour
{
public Renderer[] Glows;
public ParticleSystem Embers;
public Color GlowColor;
public bool WoodOnly;
private Container m_container;
private Material m_lit;
private Material m_cold;
private bool? m_shown;
private float m_nextCheck;
private void Awake()
{
m_container = GetComponent<Container>();
if (Glows == null || Glows.Length == 0 || Glows[0] == null) return;
m_cold = Glows[0].sharedMaterial;
m_lit = new Material(m_cold) { name = m_cold.name + "_lit" };
m_lit.color = Color.black;
m_lit.EnableKeyword("_EMISSION");
m_lit.SetColor("_EmissionColor", GlowColor);
}
private void Update()
{
if (Time.time < m_nextCheck) return;
m_nextCheck = Time.time + 1f;
bool lit = HasWork();
if (m_shown == lit) return;
m_shown = lit;
if (m_lit != null)
{
foreach (Renderer glow in Glows)
{
if (glow != null) glow.sharedMaterial = lit ? m_lit : m_cold;
}
}
if (Embers != null)
{
if (lit) Embers.Play(true);
else Embers.Stop(true, ParticleSystemStopBehavior.StopEmitting);
}
}
private bool HasWork()
{
Inventory inventory = m_container != null ? m_container.GetInventory() : null;
if (inventory == null) return false;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name;
if (WoodOnly ? AlfarDroneAI.IsWood(name) : name != AlfarSigil.PrefabName) return true;
}
return false;
}
private void OnDestroy()
{
if (m_lit != null) Destroy(m_lit);
}
}
}

View file

@ -0,0 +1,148 @@
using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The EIRINNSIGLI, the verdigris seal (Alfar_Progettazione.txt sec. 9.2c): a bronze nail turned at
/// the forge. Put inside a chest it tells the drones NOT to look there - the inverse of the
/// Butler's, where the seal says "this one is yours". Only the colour differs from the nail: a model
/// recolour does not touch the inventory icon (guide 5.2), so in the pack it looks like a bronze
/// nail and only the name tells it apart.
/// </summary>
public static class AlfarSigil
{
public const string PrefabName = "AlfarSigil";
public const string DisplayName = "$rov_item_alfar_sigil_name";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, "BronzeNails");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Alfar] Could not clone BronzeNails: no verdigris seal.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "$rov_item_alfar_sigil_desc";
AlfarConstructs.Tint(prefab, new Color(0.36f, 0.68f, 0.58f, 1f));
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Forge,
MinStationLevel = 1,
Requirements = new[] { new RequirementConfig("BronzeNails", 1, 0, true) },
}));
}
}
/// <summary>
/// The two special chests (sec. 9.2c): built like an ordinary chest with Greydwarf eyes added to
/// the price. The ENTRY chest is where everything is thrown and where the drones sort from; the
/// WOOD chest holds the wood the drones may burn - the only wood they ever consume.
/// </summary>
public static class AlfarChests
{
public const string EntryName = "AlfarInngangskista";
public const string WoodName = "AlfarEldividarkista";
public static void Register()
{
RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc",
"$rov_hover_alfar_inngangskista", new Color(0.62f, 0.80f, 1f, 1f),
AlfarInputChest.Build, "AlfarInputChest_icon.png");
RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc",
"$rov_hover_alfar_eldividarkista", new Color(0.85f, 0.62f, 0.36f, 1f),
AlfarFireChest.Build, "AlfarFireChest_icon.png");
}
private static void RegisterOne(string pieceName, string display, string description, string hoverName, Color tint,
System.Func<GameObject, bool> build, string iconResource)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_chest_wood");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No 'piece_chest_wood': the chest " + pieceName + " is not registered.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, source);
if (prefab == null) return;
// The price of a plain chest, read from the game (guide 3.2), plus the eyes.
var requirements = new List<RequirementConfig>();
Piece vanilla = source.GetComponent<Piece>();
if (vanilla != null && vanilla.m_resources != null)
{
foreach (Piece.Requirement r in vanilla.m_resources)
{
if (r.m_resItem == null) continue;
requirements.Add(new RequirementConfig(r.m_resItem.gameObject.name, r.m_amount, 0, true));
}
}
requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true));
// The hover and the chest window say what the chest is for, not only its name.
Container container = prefab.GetComponent<Container>();
if (container != null) container.m_name = hoverName;
Piece piece = prefab.GetComponent<Piece>();
if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; }
piece.m_name = display;
piece.m_description = description;
// Each chest has a body of its own; the tint stays as the fallback if it cannot be built.
Sprite icon = piece.m_icon;
if (!build(prefab)) AlfarConstructs.Tint(prefab, tint);
else icon = IconFrom(iconResource) ?? icon;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = display,
Description = description,
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = icon,
Requirements = requirements.ToArray(),
}));
// One of each inside the reach of a Ljoskjarne, and only for the Alfar, and only where a core stands.
PieceDensityLimit.Register(pieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_chest");
PieceDensityLimit.RegisterGate(pieceName, (player, position) =>
{
if (!AlfarRace.IsLocalAlfar())
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
}
if (AlfarNexusBehaviour.Covering(position) == null)
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_chest_needs_nexus"));
return false;
}
return true;
});
AlfarPieces.Extra.Add(pieceName);
}
internal static Sprite IconFrom(string resource)
{
Texture2D texture = PieceLook.LoadTexture(resource);
if (texture == null) return null;
return Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
}
}

View file

@ -0,0 +1,110 @@
using Jotunn.Entities;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Test helpers for the Alfar, in the F5 console. They exist so the phases of Alfar_Test.txt can
/// be walked through without waiting twenty minutes between steps.
///
/// alfarstatus what the race is doing right now (eitr, Heimkall timer, SE, form...)
/// alfarreset clears every Alfar timer and cooldown
/// alfareitr <n|full|0> sets the eitr pool: a number, "full", or 0
/// alfarhp <n> sets the current health, to try the lethal-blow case without dying
/// </summary>
public class AlfarStatusCommand : ConsoleCommand
{
public override string Name => "alfarstatus";
public override string Help => "[DEBUG] Prints the Alfar's eitr, health, Heimkall timer and passive.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null) { Console.instance.Print("No local player."); return; }
string race = AlfarVisuals.GetPlayerRace(player);
Print($"race={race} progression state={BossProgressionManager.GetCurrentProgressionState()}");
Print($"health={player.GetHealth():0}/{player.GetMaxHealth():0} eitr={player.GetEitr():0.0}/{player.GetMaxEitr():0}");
float left = AlfarHeimkall.Remaining(player);
Print($"Heimkall: {(left <= 0f ? "READY" : (left / 60f).ToString("0.0") + " min left")} " +
$"(cooldown now {AlfarHeimkall.CooldownSeconds() / 60f:0} min)");
bool se = player.GetSEMan().HaveStatusEffect(SE_AlfarStats.EffectName.GetStableHashCode());
Print($"passive status effect: {(se ? "on" : "OFF")}");
}
private static void Print(string text)
{
Console.instance.Print("[Alfar] " + text);
Jotunn.Logger.LogInfo("[Alfar] " + text);
}
}
public class AlfarResetCommand : ConsoleCommand
{
public override string Name => "alfarreset";
public override string Help => "[DEBUG] Clears the Alfar's Heimkall timer and every power cooldown.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null) return;
AlfarHeimkall.ResetTimer(player);
AlfarHeimkall.InvulnerableUntil = 0f;
AlfarPowers.ResetCooldowns(player);
Console.instance.Print("[Alfar] Heimkall timer and power cooldowns cleared.");
}
}
public class AlfarEitrCommand : ConsoleCommand
{
public override string Name => "alfareitr";
public override string Help => "[DEBUG] alfareitr <number|full|0> - sets the Alfr's current eitr.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null || args.Length == 0) { Console.instance.Print("alfareitr <number|full|0>"); return; }
float target;
if (args[0].ToLower() == "full") target = player.GetMaxEitr();
else if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out target))
{
Console.instance.Print("alfareitr <number|full|0>");
return;
}
target = Mathf.Clamp(target, 0f, player.GetMaxEitr());
float delta = target - player.GetEitr();
if (delta > 0f) player.AddEitr(delta);
else if (delta < 0f) AlfarEitr.Spend(player, -delta);
Console.instance.Print($"[Alfar] eitr = {player.GetEitr():0.0}/{player.GetMaxEitr():0}");
}
}
public class AlfarHpCommand : ConsoleCommand
{
public override string Name => "alfarhp";
public override string Help => "[DEBUG] alfarhp <number> - sets the current health, to test the lethal-blow case.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null || args.Length == 0) { Console.instance.Print("alfarhp <number>"); return; }
if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out float hp))
{
Console.instance.Print("alfarhp <number>");
return;
}
player.SetHealth(Mathf.Clamp(hp, 1f, player.GetMaxHealth()));
Console.instance.Print($"[Alfar] health = {player.GetHealth():0}/{player.GetMaxHealth():0}");
}
}
}

View file

@ -0,0 +1,168 @@
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every number the Alfar use. Nothing numeric lives in the logic files (guide 3.4), and every
/// value here is a STARTING value: Alfar_Progettazione.txt sec. 19 says they will all be
/// corrected in play.
///
/// Only the look is bound so far. The shield, the powers and the base add their own sections as
/// they are written.
/// </summary>
public static class AlfarConfig
{
/// <summary>
/// Written into m_customData["Race"] and the ZDO. Chosen once and never changed: renaming it
/// later leaves every saved Alfar character unrecognised and back to human (the Brandr
/// lesson, design doc sec. 2).
/// </summary>
public const string RaceId = "Alfar";
// ─── Look ────────────────────────────────────────────────────────────
/// <summary>The tint written into _SkinColor. Ash grey: low saturation, a hair cool.</summary>
public static ConfigEntry<Color> SkinColor;
/// <summary>
/// Height against a normal Viking: +5%, design doc sec. 7.1. Applied to the Visual child's Y,
/// never the root (RaceEyeHeight explains why).
/// </summary>
public static ConfigEntry<float> HeightScale;
/// <summary>
/// Width and depth: "barely visibly thinner", about -8%. Together with HeightScale this is a
/// NON-UNIFORM scale, which is where held weapons and the first-person camera tend to look
/// squashed - doc sec. 7.2. If it does, raise this toward 1 before touching anything else.
/// </summary>
public static ConfigEntry<float> WidthScale;
/// <summary>
/// Scales the almond eyes (EyeExtent). The default 0.8 is the tuned grey look; raise it for
/// bigger eyes.
/// </summary>
public static ConfigEntry<float> EyeSizeMultiplier;
// A grey's eyes, on the Sverm's eye spot: offsets are metres in the head bone's OWN frame
// at human scale, so they land on the same part of the face at any body scale.
// Pushed apart and forward of the Sverm's, because an almond this wide would otherwise
// meet its twin over the nose and sink into the cheek.
public const float EyeSeparation = 0.037f;
public const float EyeForward = 0.090f;
public const float EyeHeight = 0.183f;
// Full width, height and depth of one eye in metres at Eye Size Multiplier 1. The saved
// default of 0.8 makes that 50 x 28 x 18 mm.
public static readonly Vector3 EyeExtent = new Vector3(0.0625f, 0.035f, 0.0225f);
// Degrees. Slant raises the outer corner; wrap turns each eye out toward its temple.
public const float EyeSlant = 22f;
public const float EyeWrap = 20f;
// ─── Eitr: diet, shield, soft fall ───────────────────────────────────
/// <summary>
/// What each food adds to the maximum eitr besides its own: min(hp, stamina) times this.
/// 1 is the design (sec. 3): native eitr plus the lower of hp and stamina.
/// </summary>
public static ConfigEntry<float> DietMultiplier;
/// <summary>
/// Eitr spent per point of damage. 1:1, FIXED, for ever (sec. 4.1): progression comes from
/// the food raising the pool, not from a better rate.
/// </summary>
public static ConfigEntry<float> ShieldRate;
/// <summary>Lightning and spirit cost this many times the rate (sec. 5.1: the double cost).</summary>
public static ConfigEntry<float> ConductiveMultiplier;
/// <summary>
/// Falls cost nothing while there is any eitr (sec. 4.5: soft fall). Off, a fall is shielded
/// like any other blow.
/// </summary>
public static ConfigEntry<bool> SoftFall;
/// <summary>
/// The fastest an Alfr falls while there is eitr, in metres per second. The vanilla Feather
/// Cape caps at 5; a little under that reads as floating.
/// </summary>
public static ConfigEntry<float> FeatherFallSpeed;
// ─── Heimkall: the death that costs a wait ───────────────────────────
/// <summary>Minutes before a second Heimkall is possible, before Yagluth (sec. 6).</summary>
public static ConfigEntry<float> HeimkallMinutes;
/// <summary>The same, once Yagluth is down.</summary>
public static ConfigEntry<float> HeimkallMinutesAfterYagluth;
/// <summary>The same, once Fader is down.</summary>
public static ConfigEntry<float> HeimkallMinutesAfterFader;
/// <summary>
/// Seconds of invulnerability on arrival, so a lethal blow does not simply repeat at the
/// bed. Without it a burning or drowning death would loop.
/// </summary>
public static ConfigEntry<float> HeimkallInvulnerableSeconds;
public static void Bind(ConfigFile config)
{
const string heimkall = "Alfar - Heimkall";
HeimkallMinutes = config.Bind(heimkall, "Cooldown Minutes", 20f,
new ConfigDescription("Minutes between two Heimkalls (the lethal-blow teleport to the bed). Inside this wait, a lethal blow kills normally.",
new AcceptableValueRange<float>(0f, 120f)));
HeimkallMinutesAfterYagluth = config.Bind(heimkall, "Cooldown Minutes After Yagluth", 15f,
new ConfigDescription("The cooldown once Yagluth is defeated.",
new AcceptableValueRange<float>(0f, 120f)));
HeimkallMinutesAfterFader = config.Bind(heimkall, "Cooldown Minutes After Fader", 10f,
new ConfigDescription("The cooldown once Fader is defeated.",
new AcceptableValueRange<float>(0f, 120f)));
HeimkallInvulnerableSeconds = config.Bind(heimkall, "Invulnerable Seconds", 5f,
new ConfigDescription("Seconds nothing can hurt the Alfr after arriving.",
new AcceptableValueRange<float>(0f, 30f)));
const string eitr = "Alfar - Eitr";
DietMultiplier = config.Bind(eitr, "Diet Multiplier", 1f,
new ConfigDescription("Each food adds its native eitr plus min(hp, stamina) times this to the maximum eitr.",
new AcceptableValueRange<float>(0f, 3f)));
ShieldRate = config.Bind(eitr, "Shield Rate", 1f,
new ConfigDescription("Eitr spent per point of damage absorbed (1 = 1:1).",
new AcceptableValueRange<float>(0.1f, 5f)));
ConductiveMultiplier = config.Bind(eitr, "Lightning And Spirit Multiplier", 2f,
new ConfigDescription("Lightning and spirit damage cost this many times the shield rate.",
new AcceptableValueRange<float>(1f, 5f)));
SoftFall = config.Bind(eitr, "Soft Fall", true,
new ConfigDescription("Falling does no damage, and is slowed, while the Alfr has any eitr."));
FeatherFallSpeed = config.Bind(eitr, "Feather Fall Speed", 4f,
new ConfigDescription("Maximum falling speed (m/s) while the Alfr has eitr. Lower floats more.",
new AcceptableValueRange<float>(1f, 20f)));
const string look = "Alfar - Look";
SkinColor = config.Bind(look, "Skin Color", new Color(0.86f, 0.88f, 0.88f, 1f),
new ConfigDescription("How light the ash-grey skin is. The skin texture itself is made grey; this only sets its brightness."));
HeightScale = config.Bind(look, "Height Scale", 1.05f,
new ConfigDescription("Body height against a normal Viking (1.05 = +5%).",
new AcceptableValueRange<float>(0.8f, 1.3f)));
WidthScale = config.Bind(look, "Width Scale", 0.92f,
new ConfigDescription("Body width and depth against a normal Viking (0.92 = 8% thinner).",
new AcceptableValueRange<float>(0.7f, 1.2f)));
EyeSizeMultiplier = config.Bind(look, "Eye Size Multiplier", 0.8f,
new ConfigDescription("Scales the black almond eyes. 0.8 is the default look; raise it for bigger eyes.",
new AcceptableValueRange<float>(0.5f, 3f)));
}
}
}

View file

@ -0,0 +1,397 @@
using System.Collections.Generic;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The three constructs, the Alfar's only troops (Alfar_Progettazione.txt sec. 8.5):
///
/// Neistvordr a Surtling: hp 60 and a shield of 60 (the vanilla Surtling has 20), fire thrower
/// Steinvordr the StoneGolem: hp 800, the tank, ONE per Nexus
/// Eldingvordr a smaller Abomination at half its hp, which fires a lightning sphere every 8 s
///
/// Everything that makes them the Alfar's is done by what is added, not by rewriting attacks:
/// AlfarMark turns whatever they deal into lightning and keeps it off friends and buildings,
/// AlfarCreatureShield gives them a shield that returns by itself, and RaisedThrall gives them
/// the follow and stay orders every other race's troops already have.
///
/// They are NOT repaired and do not heal: the damage to the body is permanent. RaisedThrall's
/// sentinel regeneration (SkeletonSentryBehaviour) is therefore left off, and the creature's own
/// slow vanilla regeneration is switched off too.
/// </summary>
public static class AlfarConstructs
{
public const string Neistvordr = "AlfarNeistvordr";
public const string Steinvordr = "AlfarSteinvordr";
public const string Eldingvordr = "AlfarEldingvordr";
public const string SphereProjectile = "AlfarLightningSphere";
public const string SphereWeapon = "AlfarSphereAttack";
public class Kind
{
public string PrefabName;
public string Display;
public string Source;
public float Health; // 0 = keep the vanilla creature's
public float HealthFactor; // applied after Health when Health is 0
public float Scale; // 1 = the vanilla size
}
public static readonly Kind[] Roster =
{
new Kind { PrefabName = Neistvordr, Display = "$rov_creature_alfar_neistvordr_name", Source = "Surtling", Health = 60f, Scale = 1f },
new Kind { PrefabName = Steinvordr, Display = "$rov_creature_alfar_steinvordr_name", Source = "StoneGolem", Health = 0f, HealthFactor = 1f, Scale = 0.6f },
new Kind { PrefabName = Eldingvordr, Display = "$rov_creature_alfar_eldingvordr_name", Source = "Abomination", Health = 0f, HealthFactor = 0.5f, Scale = 0.4f },
};
public static Kind Find(string prefabName)
{
foreach (Kind kind in Roster) if (kind.PrefabName == prefabName) return kind;
return null;
}
// ─── Registration ────────────────────────────────────────────────────
public static void Register()
{
// The sphere first: the Eldingvordr's weapon needs it.
bool sphere = RegisterSphere();
foreach (Kind kind in Roster)
{
if (kind.PrefabName == Eldingvordr && !sphere)
{
Jotunn.Logger.LogWarning("[Alfar] No lightning sphere: the Eldingvordr keeps the Abomination's melee.");
}
RegisterOne(kind, sphere);
}
}
private static void RegisterOne(Kind kind, bool sphere)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(kind.Source);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{kind.Source}' to build {kind.Display} from.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source);
if (prefab == null) return;
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = kind.Display;
character.m_faction = Character.Faction.Players;
if (kind.Health > 0f) character.m_health = kind.Health;
else character.m_health *= kind.HealthFactor;
// The damage to the body is permanent: no slow regeneration either.
character.m_regenAllHPTime = 0f;
}
if (!Mathf.Approximately(kind.Scale, 1f))
{
prefab.transform.localScale = Vector3.one * kind.Scale;
ZNetView nview = prefab.GetComponent<ZNetView>();
if (nview != null) nview.m_syncInitialScale = true;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = AlfarNexusConfig.ConstructLeash.Value;
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
// The vanilla creatures attack player-built objects. Ours never touch a building.
monster.m_attackPlayerObjects = false;
monster.m_alertRange = AlfarNexusConfig.ConstructAlertRange.Value;
monster.m_maxChaseDistance = AlfarNexusConfig.ConstructAlertRange.Value;
}
// A construct that dropped Coal, a Surtling core or a trophy would be a loot farm.
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
if (kind.PrefabName == Eldingvordr && sphere) GiveSphereWeapon(prefab);
if (kind.PrefabName == Neistvordr) BlueFlames(prefab);
else Tint(prefab, new Color(0.85f, 0.52f, 0.2f, 1f));
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = "construct";
// What a destroyed construct gives back: the METAL it was built from, and nothing else - the
// crystals and the refined eitr are spent for good (design sec. 8.5).
AlfarRefund refund = prefab.AddComponent<AlfarRefund>();
refund.Item = kind.PrefabName == Neistvordr ? "Bronze" : kind.PrefabName == Eldingvordr ? "Iron" : "BlackMetal";
refund.Amount = kind.PrefabName == Neistvordr ? AlfarNexusConfig.NeistMetal.Value
: kind.PrefabName == Eldingvordr ? AlfarNexusConfig.EldingMetal.Value
: AlfarNexusConfig.SteinMetal.Value;
AlfarCreatureShield shield = prefab.AddComponent<AlfarCreatureShield>();
shield.MaxShield = character != null ? character.m_health : 0f;
shield.Shield = shield.MaxShield;
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = kind.PrefabName;
thrall.m_commandingRace = AlfarConfig.RaceId;
thrall.m_maxFollowers = -1; // the cap is the Nexus's, per type, counted at the Nexus
thrall.m_witherSeconds = AlfarNexusConfig.WitherSeconds.Value;
thrall.m_homeCheckRange = AlfarNexusConfig.NexusRadius.Value;
thrall.m_refusalMessage = "$rov_msg_thrall_refusal_alfar";
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Alfar] Registered '{kind.PrefabName}' from '{kind.Source}'.");
}
// ─── The lightning sphere ────────────────────────────────────────────
/// <summary>
/// The Eldingvordr's shot: a sphere that bursts in a small area, hurts only enemies, and never
/// touches a building (doc sec. 8.5 and 16B V12). Cloned from the Dverger ice projectile, the
/// clean base the probe found: an area burst and NO lingering effect spawned on impact (the
/// fire one drops a fire field and also spawns on buildings).
/// </summary>
private static bool RegisterSphere()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("DvergerStaffIce_projectile");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] DvergerStaffIce_projectile not found: no lightning sphere.");
return false;
}
GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(SphereProjectile, source);
if (projectile == null) return false;
Projectile settings = projectile.GetComponent<Projectile>();
if (settings == null) return false;
settings.m_gravity = 0f;
settings.m_ttl = 4f;
settings.m_aoe = 3f;
settings.m_aoeSkipWearNTear = true;
settings.m_hitFriendly = false;
settings.m_noDamageFriendly = true;
settings.m_hitOwner = false;
settings.m_statusEffect = "";
Tint(projectile, new Color(0.55f, 0.85f, 1f, 1f));
PrefabManager.Instance.AddPrefab(projectile);
// The weapon that fires it: the Surtling's own fireball weapon, because a creature that
// shoots needs an item with a projectile attack, and that is the one that exists.
GameObject surtling = PrefabManager.Cache.GetPrefab<GameObject>("Surtling");
Humanoid surtlingHumanoid = surtling != null ? surtling.GetComponent<Humanoid>() : null;
GameObject fireball = surtlingHumanoid != null && surtlingHumanoid.m_defaultItems != null &&
surtlingHumanoid.m_defaultItems.Length > 0
? surtlingHumanoid.m_defaultItems[0]
: null;
if (fireball == null)
{
Jotunn.Logger.LogWarning("[Alfar] The Surtling's fireball weapon was not found: no sphere weapon.");
return false;
}
GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(SphereWeapon, fireball);
if (weapon == null) return false;
ItemDrop drop = weapon.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_sphere_name";
// One shot every eight seconds (design): the AI waits this long between uses.
shared.m_aiAttackInterval = AlfarNexusConfig.SphereIntervalSeconds.Value;
shared.m_aiAttackRange = AlfarNexusConfig.SphereRange.Value;
shared.m_aiAttackRangeMin = 4f;
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.SphereDamage.Value;
shared.m_damages = damage;
if (shared.m_attack != null)
{
shared.m_attack.m_attackProjectile = projectile;
// The Abomination's right hand: where the sphere leaves from.
shared.m_attack.m_attackOriginJoint = "r.hand";
}
ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false));
return true;
}
private static void GiveSphereWeapon(GameObject prefab)
{
Humanoid humanoid = prefab.GetComponent<Humanoid>();
GameObject weapon = PrefabManager.Instance.GetPrefab(SphereWeapon);
if (humanoid == null || weapon == null) return;
humanoid.m_defaultItems = new[] { weapon };
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomArmor = new GameObject[0];
humanoid.m_randomShield = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
}
// ─── Colour ──────────────────────────────────────────────────────────
/// <summary>
/// A tint on every mesh, through renderer.materials (an instanced copy) and NEVER .material or
/// sharedMaterial: the vanilla creature uses the same asset and must stay as it is (guide 3.5).
/// This is a recolour and not a retexture: a true repaint of the golem and the Abomination is
/// still to do (test file, phase 6).
/// </summary>
public static void Tint(GameObject prefab, Color color)
{
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer is ParticleSystemRenderer || renderer is TrailRenderer || renderer is LineRenderer) continue;
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.color = color;
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", color * 0.08f);
material.EnableKeyword("_EMISSION");
}
}
renderer.materials = materials;
}
foreach (Light light in prefab.GetComponentsInChildren<Light>(true)) light.color = color;
}
/// <summary>
/// The Surtling is made of particles and lights, not textures, and the vanilla prefab ALREADY
/// carries blue variants of its flames, switched off (probe, doc 16C P2): turn those on, turn
/// the red ones off, and recolour the glow of the body and the point light.
/// </summary>
private static void BlueFlames(GameObject prefab)
{
foreach (Transform child in prefab.GetComponentsInChildren<Transform>(true))
{
if (child.name == "flames_world_BLUE") child.gameObject.SetActive(true);
else if (child.name == "flames" || child.name == "flames_world" || child.name == "flames_world_Purple")
{
child.gameObject.SetActive(false);
}
}
Color blue = new Color(0.25f, 0.55f, 1f, 1f);
foreach (Light light in prefab.GetComponentsInChildren<Light>(true)) light.color = blue;
foreach (Renderer renderer in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
if (material != null && material.HasProperty("_EmissionColor"))
{
// The vanilla emission is white-hot (73): keep the strength, change the hue.
material.SetColor("_EmissionColor", new Color(0.25f, 0.55f, 1f, 1f) * 30f);
}
}
renderer.materials = materials;
}
}
// ─── Counting and spawning (called by the Nexus) ─────────────────────
/// <summary>
/// A destroyed construct drops the metal it cost, on the ground where it fell. Only a DEATH:
/// a zone unloading destroys the object too and must not pay anyone (the same rule as the
/// Butler's payload).
/// </summary>
public class AlfarRefund : MonoBehaviour
{
public string Item = "";
public int Amount;
}
[HarmonyLib.HarmonyPatch(typeof(Character), "OnDeath")]
public static class Alfar_Refund_Patch
{
public static void Postfix(Character __instance)
{
AlfarRefund refund = __instance != null ? __instance.GetComponent<AlfarRefund>() : null;
if (refund == null || refund.Amount <= 0 || ObjectDB.instance == null) return;
GameObject prefab = ObjectDB.instance.GetItemPrefab(refund.Item);
ItemDrop template = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (template == null || template.m_itemData == null) return;
int left = refund.Amount;
int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize);
Vector3 at = __instance.transform.position + Vector3.up * 0.5f;
while (left > 0)
{
int stack = Mathf.Min(left, max);
ItemDrop.ItemData clone = template.m_itemData.Clone();
clone.m_dropPrefab = prefab;
ItemDrop.DropItem(clone, stack, at + Random.insideUnitSphere * 0.3f, Quaternion.identity);
left -= stack;
}
refund.Amount = 0; // once only
}
}
public static int CountAlive(Vector3 anchor, string prefabName)
{
int count = 0;
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(anchor))
{
if (thrall != null && thrall.Kind == prefabName) count++;
}
return count;
}
public static bool Spawn(Vector3 anchor, string prefabName)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{prefabName}' in ZNetScene: it cannot be built.");
return false;
}
Vector3 where = SpawnSpot(anchor);
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f));
RaisedThrall thrall = spawned != null ? spawned.GetComponent<RaisedThrall>() : null;
if (thrall != null) thrall.Bind(anchor);
return spawned != null;
}
/// <summary>A free spot on a ring around the Nexus, on the ground, or due south as a last resort.</summary>
public static Vector3 SpawnSpot(Vector3 centre)
{
const float radius = 3.5f;
int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle");
float start = Random.Range(0f, 360f);
for (int i = 0; i < 12; i++)
{
float angle = (start + i * 30f) * Mathf.Deg2Rad;
Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate);
if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue;
return candidate + Vector3.up * 0.3f;
}
Vector3 fallback = centre + new Vector3(0f, 0f, -radius);
if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback);
return fallback + Vector3.up * 0.3f;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,710 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The LJOSVAETTIR, the Alfar's drones (Alfar_Progettazione.txt sec. 9): a Deathsquito without legs,
/// stinger or buzz, bronze, with blue light. One kind of drone does every job (the work itself is
/// AlfarDroneWork); the only thing apart is the GRAFVAETTIR, the same creature thrown like a
/// grenade to dig the precious ores around a point for two minutes and then vanish.
///
/// What a drone is by itself: 25 hp and a shield of 25, tamed, tied to its Ljoskjarne, and able to
/// defend itself with a lightning zap of 1 damage every two seconds. It never attacks anything
/// outside the Nexus's radius and never goes after anything: it is a worker, not a soldier.
///
/// The Deathsquito is ONE skinned mesh with one material (probe, doc 16C P1): the legs are bones, so
/// they are hidden by scaling the bones to zero, and the blue is an emission on a bronze body, not
/// separate eyes and wings - a true repaint is still to do.
/// </summary>
public static class AlfarDrones
{
public const string DroneName = "AlfarDrone";
public const string MinerName = "AlfarGrafvaettir";
public const string ZapWeapon = "AlfarDroneZap";
private static readonly Color Bronze = new Color(1f, 0.62f, 0.25f, 1f);
private static readonly Color ElectricBlue = new Color(0.25f, 0.65f, 1f, 1f);
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("Deathsquito");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No 'Deathsquito' to build the drones from.");
return;
}
bool zap = RegisterZap(source);
RegisterOne(source, DroneName, "$rov_creature_alfar_drone_name", zap, miner: false);
RegisterOne(source, MinerName, "$rov_creature_alfar_grafvaettir_name", zap, miner: true);
}
/// <summary>The Deathsquito's sting turned into a zap: 1 lightning, every two seconds.</summary>
private static bool RegisterZap(GameObject deathsquito)
{
Humanoid humanoid = deathsquito.GetComponent<Humanoid>();
GameObject sting = humanoid != null && humanoid.m_defaultItems != null && humanoid.m_defaultItems.Length > 0
? humanoid.m_defaultItems[0]
: null;
if (sting == null) return false;
GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(ZapWeapon, sting);
if (weapon == null) return false;
ItemDrop drop = weapon.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_zap_name";
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.DroneZapDamage.Value;
shared.m_damages = damage;
shared.m_aiAttackInterval = AlfarNexusConfig.DroneZapInterval.Value;
ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false));
return true;
}
private static void RegisterOne(GameObject source, string prefabName, string display, bool zap, bool miner)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null) return;
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = display;
character.m_faction = Character.Faction.Players;
character.m_health = AlfarNexusConfig.DroneHealth.Value;
}
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid != null)
{
GameObject weapon = zap ? PrefabManager.Instance.GetPrefab(ZapWeapon) : null;
// A miner does not fight at all; the worker only defends itself.
humanoid.m_defaultItems = !miner && weapon != null ? new[] { weapon } : new GameObject[0];
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomArmor = new GameObject[0];
humanoid.m_randomShield = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
}
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
monster.m_attackPlayerObjects = false;
monster.m_alertRange = AlfarNexusConfig.NexusRadius.Value;
monster.m_maxChaseDistance = AlfarNexusConfig.NexusRadius.Value;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = 5f;
// A flyer's MoveTo lifts its goal to m_flyAltitudeMin above whatever solid is under it,
// the rock top included: at the vanilla height the miners hovered over a deposit out of
// reach and never struck.
if (ai != null && miner) { ai.m_flyAltitudeMin = 0.5f; ai.m_flyAltitudeMax = 2f; }
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// The buzz: the continuous sound child, and the flying loop effect.
foreach (Transform child in prefab.GetComponentsInChildren<Transform>(true))
{
if (child != null && child.name == "SFX") Object.DestroyImmediate(child.gameObject);
}
if (character != null) character.m_flyingContinuousEffect = new EffectList { m_effectPrefabs = new EffectList.EffectData[0] };
HideLegs(prefab);
Look(prefab);
prefab.AddComponent<AlfarDroneLook>();
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = miner ? "miner" : "drone";
AlfarCreatureShield shield = prefab.AddComponent<AlfarCreatureShield>();
shield.MaxShield = AlfarNexusConfig.DroneHealth.Value;
shield.Shield = shield.MaxShield;
if (miner)
{
// The mining drone has no anchor and no leash: it lives two minutes and vanishes.
prefab.AddComponent<AlfarMiner>();
}
else
{
// The worker is NOT a RaisedThrall: that brings the follow command on E, and a drone
// that can be walked out of the base stops working (the Butler's reasoning, Butler 9).
// AlfarDroneAI keeps its own anchor to the Nexus and its own wither.
AlfarDroneAI work = prefab.AddComponent<AlfarDroneAI>();
work.m_fightsBack = true; // it defends itself with the zap
work.m_homeDistance = 4f;
}
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Alfar] Registered '{prefabName}'.");
}
/// <summary>
/// No legs: the mesh is one skinned body, so the leg bones are scaled to zero and take their
/// part of the mesh with them. The stinger has no bone of its own and is left (doc 16C P1).
/// </summary>
private static void HideLegs(GameObject prefab)
{
foreach (Transform bone in prefab.GetComponentsInChildren<Transform>(true))
{
string n = bone.name;
if (n == "L.leg1" || n == "R.leg1") bone.localScale = Vector3.zero;
}
}
private static void Look(GameObject prefab)
{
foreach (Renderer renderer in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.color = Bronze;
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", ElectricBlue * 0.15f);
material.EnableKeyword("_EMISSION");
}
}
renderer.materials = materials;
}
foreach (Light light in prefab.GetComponentsInChildren<Light>(true)) light.color = ElectricBlue;
}
/// <summary>
/// The same look, applied to the LIVE body at spawn and re-applied after the animator every
/// frame for the bones: edits made on the registered clone may not reach the instance, and the
/// animator can write the leg scale back.
/// </summary>
public class AlfarDroneLook : MonoBehaviour
{
private Transform[] legs;
private void Awake()
{
var list = new System.Collections.Generic.List<Transform>();
foreach (Transform bone in GetComponentsInChildren<Transform>(true))
{
if (bone.name == "L.leg1" || bone.name == "R.leg1") list.Add(bone);
}
legs = list.ToArray();
Look(gameObject);
}
private void LateUpdate()
{
foreach (Transform leg in legs) if (leg != null) leg.localScale = Vector3.zero;
}
}
// ─── Counting and spawning ───────────────────────────────────────────
public static int CountAlive(Vector3 anchor)
{
int count = 0;
foreach (AlfarDroneAI drone in AlfarDroneAI.All)
{
if (drone != null && drone.IsBoundTo(anchor)) count++;
}
return count;
}
public static bool Spawn(Vector3 anchor)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(DroneName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{DroneName}' in ZNetScene: no drone can be made.");
return false;
}
Vector3 where = AlfarConstructs.SpawnSpot(anchor) + Vector3.up * 1.5f;
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
AlfarDroneAI work = spawned != null ? spawned.GetComponent<AlfarDroneAI>() : null;
if (work != null) work.Bind(anchor);
return spawned != null;
}
}
/// <summary>
/// A MINING DRONE: thrown to a point, it digs the precious ores around that point for a fixed time
/// and then vanishes (design sec. 9.3). It takes over its own AI tick like the Butler's servants do
/// (a prefix on MonsterAI.UpdateAI), flies to the nearest deposit on the list and strikes it with
/// pickaxe damage at a tool tier high enough for any of them. The ore falls where it stands.
///
/// Whatever it breaks is on the list in AlfarMiner.Deposits; a name list in the config so a
/// wrong or missing name is a config edit, not a rebuild.
/// </summary>
public class AlfarMiner : MonoBehaviour
{
public Vector3 Centre;
public float Radius = 12f;
public float LiveSeconds = 120f;
// The job lives in the drone's ZDO, not only in these fields: Valheim destroys a creature
// when its zone unloads and builds a fresh one when the zone comes back, and the fresh
// one had a zero Centre, so it searched around the world origin and stood idle. The
// birth time is network time, so a rebuilt drone does not get a new two minutes either.
private static readonly int CentreKey = "rov_graf_centre".GetStableHashCode();
private static readonly int RadiusKey = "rov_graf_radius".GetStableHashCode();
private static readonly int LifeKey = "rov_graf_life".GetStableHashCode();
private static readonly int BornKey = "rov_graf_born".GetStableHashCode();
private const float Reach = 4f;
private bool loaded;
private double bornAt;
private float nextStrike;
private Component target;
private float lastDistance = -1f;
private int strikes;
private string lastHit = "none";
public static readonly List<AlfarMiner> All = new List<AlfarMiner>();
private void OnEnable() { All.Add(this); }
private void OnDisable() { All.Remove(this); }
private static readonly System.Reflection.MethodInfo MoveToMethod =
AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) });
private static double Now => ZNet.instance != null ? ZNet.instance.GetTimeSeconds() : Time.time;
/// <summary>Called by the throw right after the drone is made: the job, into the ZDO.</summary>
public void Assign(Vector3 centre, float radius, float liveSeconds)
{
Centre = centre;
Radius = radius;
LiveSeconds = liveSeconds;
bornAt = Now;
loaded = true;
ZNetView nview = GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
ZDO zdo = nview.GetZDO();
zdo.Set(CentreKey, centre);
zdo.Set(RadiusKey, radius);
zdo.Set(LifeKey, liveSeconds);
zdo.Set(BornKey, (long)(bornAt * 1000.0));
}
/// <summary>
/// A drone rebuilt from its ZDO reads its job back. One with no job at all (thrown by an
/// older build) digs around where it stands, which is where it was thrown.
/// </summary>
private void Load()
{
loaded = true;
ZNetView nview = GetComponent<ZNetView>();
ZDO zdo = nview != null && nview.IsValid() ? nview.GetZDO() : null;
long born = zdo != null ? zdo.GetLong(BornKey, 0L) : 0L;
if (born == 0L)
{
Centre = transform.position;
bornAt = Now;
return;
}
Centre = zdo.GetVec3(CentreKey, transform.position);
Radius = zdo.GetFloat(RadiusKey, Radius);
LiveSeconds = zdo.GetFloat(LifeKey, LiveSeconds);
bornAt = born / 1000.0;
}
public bool Tick(MonsterAI ai, float dt)
{
if (!loaded) Load();
if (Now - bornAt >= LiveSeconds)
{
ZNetView nview = GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject);
return true;
}
// A deposit another drone just broke is still there until the end of the frame, with a
// dead network view: drop it and look again.
if (target == null || !target.gameObject.activeInHierarchy || !Live(target)) target = FindDeposit();
Vector3 point = Vector3.zero;
Collider area = target != null ? NearestArea(target, out point) : null;
if (area == null) { target = null; ai.StopMoving(); return true; }
// Measured to the closest point of the rock, not to its root: a copper deposit's root
// sits at its base inside the mesh, so a drone aiming there stopped on top of the rock
// and never came within reach.
float distance = Vector3.Distance(transform.position, point);
lastDistance = distance;
if (distance > Reach)
{
if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true });
return true;
}
ai.StopMoving();
if (Time.time < nextStrike) return true;
nextStrike = Time.time + 1f;
Strike(target, area, point);
strikes++;
return true;
}
private static string[] names;
private static string namesSource;
// Read again when the config line changes, so an edit in game counts without a restart.
private static string[] Deposits
{
get
{
string value = AlfarNexusConfig.MinerDeposits.Value;
if (names == null || namesSource != value)
{
namesSource = value;
names = value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
}
return names;
}
}
private static bool IsPrecious(string prefabName)
{
foreach (string wanted in Deposits)
{
if (prefabName.IndexOf(wanted.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true;
}
return false;
}
private Component FindDeposit()
{
Component best = null;
float bestDistance = float.MaxValue;
foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore))
{
Component deposit = DepositOf(collider);
if (deposit == null) continue;
if (!Live(deposit)) continue;
string prefabName = DepositName(deposit);
if (!IsPrecious(prefabName)) continue;
float distance = Vector3.Distance(transform.position, deposit.transform.position);
if (distance < bestDistance) { best = deposit; bestDistance = distance; }
}
return best;
}
/// <summary>
/// The live hit area of the deposit closest to the drone, and the closest point on it.
/// MineRock and MineRock5 only take a hit on one of their own areas; a MineRock with an area
/// root (tin) keeps its base model collider apart, and a hit on that one is thrown away.
/// Broken areas are switched off, so only active colliders count.
/// </summary>
private Collider NearestArea(Component deposit, out Vector3 point)
{
point = Vector3.zero;
MineRock rock = deposit as MineRock;
GameObject root = rock != null && rock.m_areaRoot != null ? rock.m_areaRoot : deposit.gameObject;
Collider best = null;
float bestDistance = float.MaxValue;
foreach (Collider collider in root.GetComponentsInChildren<Collider>())
{
if (collider == null || !collider.enabled) continue;
Vector3 closest = collider.bounds.ClosestPoint(transform.position);
float distance = Vector3.Distance(transform.position, closest);
if (distance < bestDistance) { best = collider; bestDistance = distance; point = closest; }
}
return best;
}
private void Strike(Component deposit, Collider area, Vector3 point)
{
IDestructible destructible = deposit as IDestructible;
if (destructible == null) { lastHit = $"{deposit.GetType().Name} is not IDestructible"; return; }
HitData hit = new HitData();
hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value;
hit.m_toolTier = 100;
hit.m_dodgeable = false;
hit.m_blockable = false;
hit.m_hitCollider = area;
hit.m_point = point;
hit.m_dir = (area.bounds.center - transform.position).normalized;
// Vanilla MineRock (tin) reads the attacker's ZDOID for its hit effects without a null
// check: a hit with no attacker throws before the area can break.
hit.SetAttacker(GetComponent<Character>());
// Overwritten by the patches below at each step the hit gets through. Vanilla runs the
// RPC on this machine at once when we own the deposit, so `striking` is still set then.
lastHit = "Damage not entered";
striking = this;
rpcRan = false;
try
{
destructible.Damage(hit);
// The F8 readout showed the hit entering Damage with every gate open and this
// machine owning the deposit, and the RPC handler never running: the routed call
// left for the network instead of being handled here. When we own the deposit,
// call its own handler directly - the same resistance, tier and break logic, only
// without the routing.
if (!rpcRan && OwnsDeposit(deposit)) StrikeDirect(deposit, area, hit);
}
finally { striking = null; }
}
private static bool rpcRan;
private static readonly System.Reflection.MethodInfo DestructibleRpc = AccessTools.Method(typeof(Destructible), "RPC_Damage");
private static readonly System.Reflection.MethodInfo MineRockRpc = AccessTools.Method(typeof(MineRock), "RPC_Hit");
private static readonly System.Reflection.MethodInfo MineRockArea = AccessTools.Method(typeof(MineRock), "GetAreaIndex");
private static readonly System.Reflection.MethodInfo MineRock5Rpc = AccessTools.Method(typeof(MineRock5), "RPC_Damage");
private static readonly System.Reflection.MethodInfo MineRock5Area = AccessTools.Method(typeof(MineRock5), "GetAreaIndex");
private static readonly System.Reflection.FieldInfo RpcIdField = AccessTools.Field(typeof(ZRoutedRpc), "m_id");
private static bool OwnsDeposit(Component deposit)
{
ZNetView nview = deposit.GetComponent<ZNetView>();
return nview != null && nview.IsValid() && nview.IsOwner();
}
private void StrikeDirect(Component deposit, Collider area, HitData hit)
{
long sender = ZDOMan.GetSessionID();
string entry = lastHit;
try
{
if (deposit is Destructible && DestructibleRpc != null)
{
DestructibleRpc.Invoke(deposit, new object[] { sender, hit });
}
else if (deposit is MineRock && MineRockRpc != null && MineRockArea != null)
{
int index = (int)MineRockArea.Invoke(deposit, new object[] { area });
if (index < 0) { lastHit = "direct: collider is not a MineRock area"; return; }
MineRockRpc.Invoke(deposit, new object[] { sender, hit, index });
}
else if (deposit is MineRock5 && MineRock5Rpc != null && MineRock5Area != null)
{
int index = (int)MineRock5Area.Invoke(deposit, new object[] { area });
if (index < 0) { lastHit = "direct: collider is not a MineRock5 area"; return; }
MineRock5Rpc.Invoke(deposit, new object[] { sender, hit, index });
}
else
{
lastHit = $"direct: no handler for {deposit.GetType().Name}";
return;
}
lastHit = $"direct, {lastHit} | before: {entry}";
}
catch (System.Exception ex)
{
System.Exception inner = ex.InnerException ?? ex;
lastHit = $"direct failed: {inner.GetType().Name}: {inner.Message}";
Jotunn.Logger.LogWarning($"[Alfar] Grafvaettir direct hit failed: {inner}");
}
}
// ─── F8 diagnostics: what each hit did on arrival ──────────────────────
private static AlfarMiner striking;
private static AlfarMiner MinerOf(HitData hit)
{
if (striking != null) return striking;
Character attacker = hit != null ? hit.GetAttacker() : null;
return attacker != null ? attacker.GetComponent<AlfarMiner>() : null;
}
private static readonly System.Reflection.FieldInfo FirstFrameField = AccessTools.Field(typeof(Destructible), "m_firstFrame");
/// <summary>The gates in front of the RPC: whose deposit it is and whether the view is live.</summary>
private static void RecordEntry(Component deposit, string extra)
{
if (striking == null) return;
ZNetView nview = deposit.GetComponent<ZNetView>();
bool valid = nview != null && nview.IsValid();
long owner = valid ? nview.GetZDO().GetOwner() : -1L;
long me = ZDOMan.GetSessionID();
Character attacker = striking.GetComponent<Character>();
object rpcId = RpcIdField != null && ZRoutedRpc.instance != null ? RpcIdField.GetValue(ZRoutedRpc.instance) : null;
striking.lastHit = $"Damage entered{extra} valid={valid} owner={owner} session={me} rpcId={rpcId} " +
$"attackerZdo={(attacker != null ? attacker.GetZDOID().ToString() : "none")}, no RPC";
}
[HarmonyPatch(typeof(Destructible), nameof(Destructible.Damage))]
public static class Alfar_Miner_DestructibleEnter_Patch
{
public static void Prefix(Destructible __instance)
{
object first = FirstFrameField != null ? FirstFrameField.GetValue(__instance) : null;
RecordEntry(__instance, $" firstFrame={first}");
}
}
[HarmonyPatch(typeof(MineRock), nameof(MineRock.Damage))]
public static class Alfar_Miner_MineRockEnter_Patch
{
public static void Prefix(MineRock __instance) => RecordEntry(__instance, "");
}
[HarmonyPatch(typeof(MineRock5), nameof(MineRock5.Damage))]
public static class Alfar_Miner_MineRock5Enter_Patch
{
public static void Prefix(MineRock5 __instance) => RecordEntry(__instance, "");
}
private static void Record(HitData hit, string kind, float before, float after, int minTier)
{
AlfarMiner miner = MinerOf(hit);
if (miner == null) return;
if (miner == striking) rpcRan = true;
miner.lastHit = $"{kind} hp {before:0.#}->{after:0.#} dmg {hit.GetTotalDamage():0.#} " +
$"pick {hit.m_damage.m_pickaxe:0.#} tier {hit.m_toolTier}/{minTier}";
}
[HarmonyPatch(typeof(Destructible), "RPC_Damage")]
public static class Alfar_Miner_DestructibleHit_Patch
{
private static float Health(Destructible d)
{
ZNetView nview = d.GetComponent<ZNetView>();
return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat(ZDOVars.s_health, d.m_health) : -1f;
}
public static void Prefix(Destructible __instance, HitData hit, out float __state)
{
__state = MinerOf(hit) != null ? Health(__instance) : -1f;
}
public static void Postfix(Destructible __instance, HitData hit, float __state)
{
if (MinerOf(hit) == null) return;
Record(hit, "Destructible", __state, Health(__instance), __instance.m_minToolTier);
}
}
[HarmonyPatch(typeof(MineRock), "RPC_Hit")]
public static class Alfar_Miner_MineRockHit_Patch
{
private static float Health(MineRock rock, int area)
{
ZNetView nview = rock.GetComponent<ZNetView>();
return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat("Health" + area, rock.GetHealth()) : -1f;
}
public static void Prefix(MineRock __instance, HitData hit, int hitAreaIndex, out float __state)
{
__state = MinerOf(hit) != null ? Health(__instance, hitAreaIndex) : -1f;
}
public static void Postfix(MineRock __instance, HitData hit, int hitAreaIndex, float __state)
{
if (MinerOf(hit) == null) return;
Record(hit, $"MineRock area {hitAreaIndex}", __state, Health(__instance, hitAreaIndex), __instance.m_minToolTier);
}
}
[HarmonyPatch(typeof(MineRock5), "DamageArea")]
public static class Alfar_Miner_MineRock5Hit_Patch
{
public static void Postfix(MineRock5 __instance, int hitAreaIndex, HitData hit, bool __result)
{
if (MinerOf(hit) == null) return;
Record(hit, $"MineRock5 area {hitAreaIndex} damaged={__result}", -1f, -1f, __instance.m_minToolTier);
}
}
private static bool Live(Component deposit)
{
ZNetView nview = deposit.GetComponent<ZNetView>();
return nview != null && nview.IsValid();
}
/// <summary>
/// The deposit's prefab name, read from its ZDO. Not from the GameObject: MineRock5 renames
/// its own object to "___MineRock5 m_meshFilter" in Awake, so a broken copper vein
/// (rock4_copper_frac) never matched the list and the drones stopped after the first blow.
/// </summary>
private static string DepositName(Component deposit)
{
ZNetView nview = deposit.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && ZNetScene.instance != null)
{
GameObject prefab = ZNetScene.instance.GetPrefab(nview.GetZDO().GetPrefab());
if (prefab != null) return prefab.name;
}
return Utils.GetPrefabName(deposit.gameObject);
}
private static Component DepositOf(Collider collider)
{
Component deposit = collider.GetComponentInParent<MineRock5>();
if (deposit == null) deposit = collider.GetComponentInParent<MineRock>();
if (deposit == null) deposit = collider.GetComponentInParent<Destructible>();
return deposit;
}
/// <summary>
/// F8 readout: what the camera looks at (is it a deposit, of which kind, on the list?) and
/// what each live miner is doing (its target, how far, how many strikes).
/// </summary>
public static void DebugReport(Player player)
{
var lines = new List<string>();
Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
if (Physics.Raycast(aim.position, aim.forward, out RaycastHit hit, 50f, ~0, QueryTriggerInteraction.Ignore))
{
Component deposit = DepositOf(hit.collider);
string prefabName = deposit != null ? DepositName(deposit) : Utils.GetPrefabName(hit.collider.transform.root.gameObject);
lines.Add($"[RoV graf] look: {hit.collider.name} on {prefabName} " +
(deposit != null ? $"{deposit.GetType().Name} listed={IsPrecious(prefabName)}" : "not a deposit"));
}
else lines.Add("[RoV graf] look: nothing within 50m");
foreach (AlfarMiner miner in All)
{
if (miner == null) continue;
string targetName = miner.target != null ? DepositName(miner.target) : "none";
lines.Add($"[RoV graf] miner {Vector3.Distance(miner.transform.position, player.transform.position):0}m away: " +
$"target {targetName} dist {miner.lastDistance:0.0} strikes {miner.strikes} " +
$"age {Now - miner.bornAt:0}s centre {miner.Centre} r {miner.Radius:0} | last hit: {miner.lastHit}");
}
foreach (string line in lines)
{
Debug.Log(line);
player.Message(MessageHud.MessageType.TopLeft, line);
}
}
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
public static class Alfar_Miner_UpdateAI_Patch
{
public static bool Prefix(MonsterAI __instance, float __0, ref bool __result)
{
if (__instance == null) return true;
AlfarMiner miner = __instance.GetComponent<AlfarMiner>();
if (miner == null) return true;
__result = miner.Tick(__instance, __0);
return false;
}
}
}
}

View file

@ -0,0 +1,166 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar's one resource (Alfar_Progettazione.txt sec. 3, 4 and 5.1): food becomes eitr, and
/// eitr is the shield.
///
/// Every signature and call order here was read from assembly_valheim.dll (doc sec. 16B V1-V4),
/// not remembered:
/// - Character.ApplyDamage is the single final stage for direct hits, burning and poison
/// ticks AND falls, so one prefix on it covers all three;
/// - Player.RPC_UseEitr spends eitr and arms the vanilla regeneration delay, which is the
/// only brake the shield has - writing m_eitr by hand would skip the delay;
/// - Player.GetTotalFoodValue is what UpdateFood hands to SetMaxEitr.
/// </summary>
public static class AlfarEitr
{
private static readonly MethodInfo UseEitrRpc =
AccessTools.Method(typeof(Player), "RPC_UseEitr", new[] { typeof(long), typeof(float) });
/// <summary>
/// Spends eitr WITHOUT Game.m_eitrRate scaling, so the rate is exactly the configured one.
/// UseEitr would multiply by the world modifier first; the RPC does not, and it is what
/// arms the regeneration delay (V3).
/// </summary>
public static void Spend(Player player, float amount)
{
if (player == null || amount <= 0f) return;
if (UseEitrRpc == null)
{
Jotunn.Logger.LogWarning("[Alfar] Player.RPC_UseEitr not found: the shield cannot spend eitr.");
return;
}
UseEitrRpc.Invoke(player, new object[] { 0L, amount });
}
// ─── Diet ────────────────────────────────────────────────────────────
/// <summary>
/// Each food adds min(hp, stamina) to the maximum eitr, on top of the eitr it already has.
/// Clarified by the user: the minimum is between hp and stamina ONLY, so a plain cooked
/// meat (40 / 30 / 0) is worth +30 eitr and a balanced food is better than a lopsided one.
///
/// Locally only: GetTotalFoodValue is the owner's own bookkeeping. Positional parameters
/// (guide 5.16): __0 hp, __1 stamina, __2 eitr.
/// </summary>
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Alfar_FoodValue_Patch
{
public static void Postfix(Player __instance, ref float __2)
{
if (__instance == null || !AlfarVisuals.IsAlfarPlayer(__instance)) return;
float bonus = 0f;
foreach (Player.Food food in __instance.GetFoods())
{
bonus += Mathf.Min(food.m_health, food.m_stamina);
}
__2 += bonus * AlfarConfig.DietMultiplier.Value;
}
}
// ─── Shield and soft fall ────────────────────────────────────────────
/// <summary>
/// Blows land on the eitr first, 1 for 1.
///
/// - No cooldown: the shield absorbs for as long as one point of eitr remains.
/// - Lightning and spirit cost double (the cost, not the damage: DamageModifier.Weak is a
/// flat +50% and cannot be made to double anything).
/// - A blow bigger than the pool is shared out: the eitr takes the share it can, the body
/// takes the rest.
/// - Drowning and the edge of the world skip the shield altogether; falls are free while
/// there is eitr and shielded like anything else once there is none left.
///
/// The prefix edits the HitData and lets ApplyDamage run: with nothing left in it,
/// ApplyDamage returns at once ("took no damage"). Positional parameters, and the argument
/// types are in the attribute so the patch binds to the real overload (guide 5.16).
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_ApplyDamage_Patch
{
public static void Prefix(Character __instance, HitData __0)
{
Player player = __instance as Player;
if (player == null || __0 == null) return;
if (!AlfarVisuals.IsAlfarPlayer(player)) return;
// The shield belongs to whoever owns the body: ApplyDamage runs on the owner, and a
// remote copy must not spend eitr it does not hold.
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
// The same early exits ApplyDamage has: nothing to absorb, nothing to spend.
if (player.IsDead() || player.IsTeleporting() || player.InCutscene() || player.InGodMode()) return;
// Just arrived by Heimkall: nothing hurts for a few seconds, or a burning death would
// simply repeat at the bed.
if (Time.time < AlfarHeimkall.InvulnerableUntil)
{
__0.m_damage = default(HitData.DamageTypes);
return;
}
// In the archon form the pool IS the defence: it takes every blow, drowning and the
// edge of the world included, and the eitr is already spent (AlfarArchon).
if (AlfarArchon.Active)
{
AlfarArchon.Absorb(player, __0);
return;
}
HitData.HitType type = __0.m_hitType;
if (type == HitData.HitType.Drowning || type == HitData.HitType.EdgeOfWorld) return;
float available = player.GetEitr();
if (type == HitData.HitType.Fall && AlfarConfig.SoftFall.Value)
{
// Soft fall: free while there is eitr, a normal fall once there is none.
if (available > 0f) __0.m_damage = default(HitData.DamageTypes);
return;
}
float cost = Cost(__0.m_damage);
if (cost <= 0f || available <= 0f) return;
if (available >= cost)
{
Spend(player, cost);
__0.m_damage = default(HitData.DamageTypes);
return;
}
// Shared out: the eitr absorbs the fraction it can pay for, the body takes the rest.
float covered = available / cost;
HitData.DamageTypes remaining = __0.m_damage;
remaining.Modify(1f - covered);
__0.m_damage = remaining;
Spend(player, available);
}
/// <summary>
/// The eitr a blow costs. Every damage type that wounds a person counts; chop and
/// pickaxe are tool damage (trees, rocks) and do not. Lightning and spirit are doubled.
/// </summary>
private static float Cost(HitData.DamageTypes damage)
{
float rate = AlfarConfig.ShieldRate.Value;
float conductive = AlfarConfig.ConductiveMultiplier.Value;
float ordinary = damage.m_damage + damage.m_blunt + damage.m_slash + damage.m_pierce +
damage.m_fire + damage.m_frost + damage.m_poison;
float double_ = damage.m_lightning + damage.m_spirit;
return (ordinary + double_ * conductive) * rate;
}
}
}
}

View file

@ -0,0 +1,166 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Eldividarkista's own body. Players kept mistaking a plain "Wood chest" for it, so it must
/// not look like any chest they can build: the box and lid are the Mistlands dvergr crate (a prop
/// nobody can place), repainted as blackened iron with an aged-bronze frame
/// (scripts/paint_fire_chest.py), with an iron grate on the front.
///
/// Behind the grate the fire shows only while the chest holds wood the drones may burn: a dark
/// grate means empty. No light source, on purpose - a base full of chests must not glow.
/// </summary>
public static class AlfarFireChest
{
private const string CrateName = "dvergrprops_crate";
private const string EmbersSource = "fx_Torch_Carried";
// The crate is a 1.02 m cube, stretched into a chest about the size of the vanilla one:
// 1.6 m wide, 0.8 m deep. Its front face (+z, away from the lid's hinge) ends up here.
private static readonly Vector3 Stretch = new Vector3(1.6f, 1f, 0.8f);
private const float FrontZ = 0.515f * 0.8f;
private const float LidY = 0.81f;
private const float GrateWidth = 0.62f * 1.6f;
private const int GrateGaps = 10;
private const float GrateHeight = 0.36f;
private const float GrateY = 0.42f;
private static readonly Color Ember = new Color(1f, 0.42f, 0.1f);
/// <summary>Swaps the cloned wood chest's meshes for the fire chest. False leaves the wood
/// chest's look in place, with a warning, rather than an invisible chest.</summary>
public static bool Build(GameObject prefab)
{
GameObject crate = PrefabManager.Cache.GetPrefab<GameObject>(CrateName);
Transform crateNew = crate != null ? crate.transform.Find("new") : null;
Transform visual = prefab.transform.Find("New");
if (crateNew == null || crateNew.childCount < 3 || visual == null)
{
Jotunn.Logger.LogWarning("[Alfar] No dvergr crate to build the Eldividarkista from; it keeps the wood chest's look.");
return false;
}
// The wood chest's box, lids and LOD group go; "New" itself stays, because WearNTear
// switches it as the piece's healthy look.
for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject);
LODGroup lod = visual.GetComponent<LODGroup>();
if (lod != null) Object.DestroyImmediate(lod);
// The crate's high meshes, in the order the prefab keeps them: box, contents, lid. The
// contents are the glowing dvergr cargo and stay behind.
GameObject body = Object.Instantiate(crateNew.GetChild(0).gameObject, visual, false);
body.name = "body";
body.transform.localScale = Vector3.Scale(body.transform.localScale, Stretch);
GameObject lidClosed = Object.Instantiate(crateNew.GetChild(2).gameObject, visual, false);
lidClosed.name = "lid_closed";
lidClosed.transform.localScale = Vector3.Scale(lidClosed.transform.localScale, Stretch);
// The open lid: the closed one turned up 100 degrees about its back edge.
GameObject lidOpen = Object.Instantiate(lidClosed, visual, false);
lidOpen.name = "lid_open";
foreach (Collider collider in lidOpen.GetComponentsInChildren<Collider>(true)) Object.DestroyImmediate(collider);
Vector3 hinge = new Vector3(0f, LidY, -FrontZ);
Quaternion turn = Quaternion.Euler(-100f, 0f, 0f);
lidOpen.transform.localPosition = hinge + turn * (lidClosed.transform.localPosition - hinge);
lidOpen.transform.localRotation = turn * lidClosed.transform.localRotation;
lidOpen.SetActive(false);
Container container = prefab.GetComponent<Container>();
if (container != null)
{
container.m_open = lidOpen;
container.m_closed = lidClosed;
}
// Only a retextured material is a copy; without the paint, writing to it would change every
// dvergr crate in the Mistlands too.
Texture2D paint = PieceLook.LoadTexture("AlfarFireChest_d.png");
if (paint != null) PieceLook.Retexture(visual, new Dictionary<string, Texture> { { "Crate_d", paint } });
Material iron = paint != null ? body.GetComponent<MeshRenderer>()?.sharedMaterial : null;
if (iron != null)
{
// The crate's normal map is wood planks; on plates it would draw seams that are not there.
if (iron.HasProperty("_BumpMap")) iron.SetTexture("_BumpMap", null);
if (iron.HasProperty("_Metallic")) iron.SetFloat("_Metallic", 0.6f);
if (iron.HasProperty("_Glossiness")) iron.SetFloat("_Glossiness", 0.45f);
}
Transform grate = BuildGrate(visual, iron, out Renderer glow);
ParticleSystem embers = AddEmbers(grate);
AlfarChestGlow look = prefab.AddComponent<AlfarChestGlow>();
look.Glows = new[] { glow };
look.Embers = embers;
look.GlowColor = Ember * 2f;
look.WoodOnly = true;
return true;
}
/// <summary>The grate: a glowing plate just off the front face, a frame and bars in front of it.</summary>
private static Transform BuildGrate(Transform visual, Material iron, out Renderer glow)
{
Transform grate = new GameObject("grate").transform;
grate.SetParent(visual, false);
grate.gameObject.layer = visual.gameObject.layer;
Material bars = iron != null ? new Material(iron) { name = "AlfarFireChest_bars" } : null;
if (bars != null)
{
bars.SetTexture("_MainTex", null);
bars.color = new Color(0.16f, 0.15f, 0.15f);
}
glow = Block(grate, "glow", new Vector3(0f, GrateY, FrontZ + 0.005f), new Vector3(GrateWidth, GrateHeight, 0.01f), bars).GetComponent<Renderer>();
const float frame = 0.035f;
foreach (float x in new[] { -GrateWidth / 2f, GrateWidth / 2f })
Block(grate, "frame", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(frame, GrateHeight + frame, 0.04f), bars);
foreach (float y in new[] { GrateY - GrateHeight / 2f, GrateY + GrateHeight / 2f })
Block(grate, "frame", new Vector3(0f, y, FrontZ + 0.02f), new Vector3(GrateWidth + frame, frame, 0.04f), bars);
for (int i = 1; i < GrateGaps; i++)
{
float x = -GrateWidth / 2f + GrateWidth * i / GrateGaps;
Block(grate, "bar", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(0.022f, GrateHeight, 0.03f), bars);
}
Block(grate, "bar", new Vector3(0f, GrateY, FrontZ + 0.022f), new Vector3(GrateWidth, 0.022f, 0.03f), bars);
return grate;
}
/// <summary>A plain box with no collider, for trim the borrowed meshes do not have.</summary>
internal static GameObject Block(Transform parent, string name, Vector3 position, Vector3 size, Material material)
{
GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
Object.DestroyImmediate(block.GetComponent<Collider>());
block.name = name;
block.layer = parent.gameObject.layer;
block.transform.SetParent(parent, false);
block.transform.localPosition = position;
block.transform.localScale = size;
if (material != null) block.GetComponent<Renderer>().sharedMaterial = material;
return block;
}
/// <summary>The carried torch's embers, rising off the top of the grate.</summary>
private static ParticleSystem AddEmbers(Transform grate)
{
GameObject torch = PrefabManager.Cache.GetPrefab<GameObject>(EmbersSource);
Transform source = torch != null ? torch.transform.Find("Embers") : null;
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No torch embers for the Eldividarkista; its grate glows without sparks.");
return null;
}
GameObject embers = Object.Instantiate(source.gameObject, grate, false);
embers.name = "embers";
embers.transform.localPosition = new Vector3(0f, GrateY + GrateHeight / 2f, FrontZ + 0.05f);
embers.transform.localRotation = Quaternion.identity;
return embers.GetComponent<ParticleSystem>();
}
}
}

View file

@ -0,0 +1,171 @@
using System.Globalization;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// HEIMKALL: a lethal blow does not kill an Alfr, it sends them to their bed with one hit point
/// (Alfar_Progettazione.txt sec. 6). Then a wait: 20 minutes, 15 after Yagluth, 10 after Fader.
/// Inside the wait a lethal blow kills like it does anyone.
///
/// HOW IT AVOIDS DEATH (read from the IL, doc sec. 16B V5):
/// Character.ApplyDamage ends with the health at zero, and the death itself is not decided
/// there but in Character.CheckDeath, which Character.CustomFixedUpdate calls on its next step.
/// So a POSTFIX on ApplyDamage that puts one hit point back, the same frame, means the check
/// finds a living body and there is no death routine, no tomb, no skill loss, no message.
///
/// The timer lives in m_customData as a world-time stamp, so it survives a logout.
/// </summary>
public static class AlfarHeimkall
{
private const string TimerKey = "Alfar_HeimkallAt";
/// <summary>Time.time until which nothing may hurt the local Alfr (the arrival grace).</summary>
public static float InvulnerableUntil;
// ─── The timer ───────────────────────────────────────────────────────
/// <summary>The cooldown for the current boss progress, in seconds.</summary>
public static float CooldownSeconds()
{
int state = BossProgressionManager.GetCurrentProgressionState();
float minutes = state >= 8 ? AlfarConfig.HeimkallMinutesAfterFader.Value
: state >= 6 ? AlfarConfig.HeimkallMinutesAfterYagluth.Value
: AlfarConfig.HeimkallMinutes.Value;
return minutes * 60f;
}
/// <summary>Seconds left before the next Heimkall; 0 when it is ready.</summary>
public static float Remaining(Player player)
{
if (player == null || player.m_customData == null || ZNet.instance == null) return 0f;
if (!player.m_customData.TryGetValue(TimerKey, out string stamp)) return 0f;
if (!double.TryParse(stamp, NumberStyles.Float, CultureInfo.InvariantCulture, out double at)) return 0f;
double elapsed = ZNet.instance.GetTimeSeconds() - at;
// A stamp from a different world (its clock is another clock) reads as the future, or as
// a wait longer than any cooldown. Either way the timer is not this world's: ready.
float cooldown = CooldownSeconds();
if (elapsed < 0d || elapsed > 1e9) return 0f;
return Mathf.Max(0f, cooldown - (float)elapsed);
}
public static bool IsReady(Player player) => Remaining(player) <= 0f;
public static void StartTimer(Player player)
{
if (player == null || ZNet.instance == null) return;
player.m_customData[TimerKey] =
ZNet.instance.GetTimeSeconds().ToString("R", CultureInfo.InvariantCulture);
}
public static void ResetTimer(Player player)
{
if (player != null && player.m_customData != null) player.m_customData.Remove(TimerKey);
AlfarStatusEffects.ClearTimer("heimkall");
}
private static float nextIconSync;
/// <summary>
/// Keeps the on-screen Heimkall countdown honest: status effects are not saved, so after a
/// reload the wait is put back on screen with what is really left of it, and removed when over.
/// </summary>
public static void SyncIcon(Player player)
{
if (Time.time < nextIconSync) return;
nextIconSync = Time.time + 2f;
float left = Remaining(player);
bool shown = AlfarStatusEffects.HasTimer("heimkall");
if (left > 0f && !shown) AlfarStatusEffects.ShowTimer("heimkall", left);
else if (left <= 0f && shown) AlfarStatusEffects.ClearTimer("heimkall");
}
// ─── The call home ───────────────────────────────────────────────────
/// <summary>
/// Teleports to the bed (or the world spawn when there is none) at one hit point, clears what
/// was killing the body, and starts the wait. Returns false when it is not ready.
/// </summary>
public static bool TryTrigger(Player player, string reason, bool force = false)
{
// force: the archon form ends with a Heimkall that it already paid for at the start.
if (player == null || (!force && !IsReady(player))) return false;
bool bed;
Vector3 destination = FindDestination(out bed);
// distantTeleport tells Valheim to stream the destination zone in first. Anything past a
// couple of zone-widths needs it.
bool distant = Vector3.Distance(player.transform.position, destination) > 100f;
bool teleported = player.TeleportTo(destination, player.transform.rotation, distant);
// Whether or not the teleport was accepted (it refuses for two seconds after another
// one), the body must not die this frame.
player.SetHealth(1f);
// What was killing the body goes with it: burning, poison, the cold, being wet. Cleared
// before the passive is put back, since RemoveAll takes that too.
player.GetSEMan().RemoveAllStatusEffects(true);
AlfarStatusEffects.Ensure(player);
InvulnerableUntil = Time.time + AlfarConfig.HeimkallInvulnerableSeconds.Value;
StartTimer(player);
AlfarStatusEffects.ShowTimer("heimkall", CooldownSeconds());
Jotunn.Logger.LogInfo($"[Alfar] Heimkall ({reason}): teleported={teleported} to {destination}; " +
$"next in {CooldownSeconds() / 60f:0} min.");
player.Message(MessageHud.MessageType.Center, ModText.Get(bed ? "rov_msg_alfar_heimkall" : "rov_msg_alfar_heimkall_nobed"));
return true;
}
/// <summary>
/// The bed the player set, else the world's original spawn. A bed point already has its height;
/// the world spawn is stored with a placeholder height (50), so its ground is worked out from the
/// world generator, which answers even when the zone there is not loaded yet - the first version
/// stood the Alfr at 50.5 m in the air or inside a hill. A bed counts only after the player has
/// SET it (sleeping in it, or interacting with it); an unused bed is not a spawn point.
/// </summary>
private static Vector3 FindDestination(out bool bed)
{
PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null;
bed = profile != null && profile.HaveCustomSpawnPoint();
if (bed) return profile.GetCustomSpawnPoint() + Vector3.up * 0.5f;
Vector3 point = PlayerProfile.m_originalSpawnPoint;
if (WorldGenerator.instance != null)
{
float ground = WorldGenerator.instance.GetHeight(point.x, point.z);
point.y = Mathf.Max(ground, 30f) + 1f; // 30 is the sea level: never under the water
}
return point;
}
// ─── The patch ───────────────────────────────────────────────────────
/// <summary>
/// After the blow has landed: if it left the body at zero, call it home instead. The shield
/// prefix has already taken what it could, so this only fires for the blow the eitr could
/// not cover (or a fall at eitr zero, a drowning, the edge of the world).
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Heimkall_Patch
{
public static void Postfix(Character __instance)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
if (!AlfarVisuals.IsAlfarPlayer(player)) return;
if (player.IsDead() || player.GetHealth() > 0f) return;
TryTrigger(player, "lethal blow");
}
}
}
}

View file

@ -0,0 +1,137 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Inngangskista's own body, the cold twin of <see cref="AlfarFireChest"/>: the dvergr loot
/// chest of the Mistlands towns (seen, never built), its panels repainted navy steel
/// (scripts/paint_input_chest.py) and its copper trim turned silver. A cyan line set into the
/// lid shines while the chest holds anything for the drones, and goes dark once they have
/// emptied it.
/// </summary>
public static class AlfarInputChest
{
private const string SourceName = "TreasureChest_dvergrtown";
// The town chest is placed at 1.2 and its meshes at 1.5 on top: 1.66 m wide, a vanilla chest's size.
private const float SourceScale = 1.2f;
private const float MeshScale = 1.5f * SourceScale;
private const float LidTop = 0.48f * MeshScale;
private const float LidHalfX = 0.42f * MeshScale;
private const float LidHalfZ = 0.24f * MeshScale;
private const float InlayInset = 0.10f;
private const float InlayWidth = 0.03f;
private static readonly Color Trim = new Color(0.9f, 0.95f, 1f);
private static readonly Color Inlay = new Color(0.35f, 0.9f, 1f);
/// <summary>Swaps the cloned wood chest's meshes for the input chest. False leaves the wood
/// chest's look in place, with a warning.</summary>
public static bool Build(GameObject prefab)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SourceName);
Transform sourceNew = source != null ? source.transform.Find("New") : null;
Transform box = sourceNew != null ? sourceNew.Find("stonechest") : null;
Transform closed = sourceNew != null ? sourceNew.Find("stonechesttop_closed") : null;
Transform open = sourceNew != null ? sourceNew.Find("stonechesttop_open") : null;
Transform visual = prefab.transform.Find("New");
if (box == null || closed == null || open == null || visual == null)
{
Jotunn.Logger.LogWarning("[Alfar] No dvergr chest to build the Inngangskista from; it keeps the wood chest's look.");
return false;
}
for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject);
LODGroup lod = visual.GetComponent<LODGroup>();
if (lod != null) Object.DestroyImmediate(lod);
GameObject body = Copy(box, visual, "body");
GameObject lidClosed = Copy(closed, visual, "lid_closed");
GameObject lidOpen = Copy(open, visual, "lid_open");
lidOpen.SetActive(false);
Container container = prefab.GetComponent<Container>();
if (container != null)
{
container.m_open = lidOpen;
container.m_closed = lidClosed;
}
Texture2D paint = PieceLook.LoadTexture("AlfarInputChest_d.png");
if (paint == null) return true; // the dvergr chest as it is: still not a vanilla chest
PieceLook.Retexture(visual, new Dictionary<string, Texture> { { "dvergrchestWorn_d", paint } });
// The trim shares the anvil's texture, so it is recoloured on a copy instead; the panels'
// material is already a copy from Retexture.
var copies = new Dictionary<Material, Material>();
Material panel = null;
foreach (Renderer renderer in visual.GetComponentsInChildren<Renderer>(true))
{
Material[] materials = renderer.sharedMaterials;
for (int i = 0; i < materials.Length; i++)
{
Material material = materials[i];
if (material == null) continue;
if (material.name.EndsWith("_rov")) { panel = panel ?? material; continue; }
if (!material.name.StartsWith("dvergr_metal_furnmiture")) continue;
if (!copies.TryGetValue(material, out Material trim))
{
trim = new Material(material) { name = material.name + "_rov" };
trim.color = Trim;
if (trim.HasProperty("_MetalColor")) trim.SetColor("_MetalColor", Trim);
copies[material] = trim;
}
materials[i] = trim;
}
renderer.sharedMaterials = materials;
}
AlfarChestGlow look = prefab.AddComponent<AlfarChestGlow>();
look.Glows = BuildInlay(lidClosed.transform, panel);
look.GlowColor = Inlay * 1.6f;
look.WoodOnly = false;
return true;
}
/// <summary>A copy of one of the town chest's parts, at the town chest's size and on the piece layer.</summary>
private static GameObject Copy(Transform part, Transform parent, string name)
{
GameObject copy = Object.Instantiate(part.gameObject, parent, false);
copy.name = name;
copy.transform.localPosition = part.localPosition * SourceScale;
copy.transform.localScale = part.localScale * SourceScale;
foreach (Transform t in copy.GetComponentsInChildren<Transform>(true)) t.gameObject.layer = parent.gameObject.layer;
return copy;
}
/// <summary>The cyan line on the lid: four thin strips just above it, inset from the edge. They
/// hang off the closed lid, so they go with it when the chest opens. The lid is scaled, so the
/// sizes are divided back out of it.</summary>
private static Renderer[] BuildInlay(Transform lid, Material panel)
{
Material cold = panel != null ? new Material(panel) { name = "AlfarInputChest_inlay" } : null;
if (cold != null)
{
cold.SetTexture("_MainTex", null);
cold.color = new Color(0.08f, 0.12f, 0.16f);
}
float k = 1f / lid.localScale.x;
float x = LidHalfX - InlayInset, z = LidHalfZ - InlayInset, y = LidTop + 0.004f;
var strips = new List<Renderer>();
foreach (float side in new[] { -z, z })
strips.Add(Strip(lid, new Vector3(0f, y, side) * k, new Vector3(2f * x + InlayWidth, 0.01f, InlayWidth) * k, cold));
foreach (float side in new[] { -x, x })
strips.Add(Strip(lid, new Vector3(side, y, 0f) * k, new Vector3(InlayWidth, 0.01f, 2f * z) * k, cold));
return strips.ToArray();
}
private static Renderer Strip(Transform lid, Vector3 position, Vector3 size, Material material)
{
return AlfarFireChest.Block(lid, "inlay", position, size, material).GetComponent<Renderer>();
}
}
}

View file

@ -0,0 +1,126 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// LEVITATION (Alfar_Progettazione.txt sec. 4.6): in the air, hold the jump key and the Alfr rises
/// slowly, burning eitr slowly. Let go and the soft fall takes over.
///
/// There is no hover in vanilla. This pushes the rigidbody's vertical speed up toward a small
/// target while the key is held, and nothing else: no horizontal speed is added, so it is a way
/// over a ledge or out of a pit and not flight (the pool of an early Alfr lasts about half a
/// minute of it).
///
/// It runs on the owner's FixedUpdate, where the rigidbody is read, and the position syncs like
/// any other movement. The eitr is spent in small batches, not every physics step: each spend arms
/// the regeneration delay and goes through an RPC call.
/// </summary>
public static class AlfarLevitation
{
// A short moment in the air before it starts, so a normal jump (a tap) is just a jump.
private const float AirDelay = 0.2f;
private const float SpendInterval = 0.25f;
private static float airTime;
private static float owed;
private static float nextSpend;
public static bool Rising { get; private set; }
[HarmonyPatch(typeof(Player), "FixedUpdate")]
public static class Alfar_Levitation_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!AlfarVisuals.IsAlfarPlayer(__instance) || __instance.IsDead()) { Reset(); return; }
// THE ARCHON FLIES for as long as the form lasts: it hovers where it is, climbs while
// jump is held and sinks while crouch is held. The eitr is already gone, so nothing is
// spent. Horizontal movement stays the normal controls.
if (AlfarArchon.Active)
{
Rigidbody flyer = Traverse.Create(__instance).Field("m_body").GetValue<Rigidbody>();
if (flyer != null)
{
float speed = AlfarPowerConfig.LevitationRise.Value * 2f;
float target = 0f;
if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off
else if (RaceInput.Allowed && JumpHeld()) target = speed;
else if (RaceInput.Allowed && CrouchHeld()) target = -speed;
Vector3 velocity = flyer.linearVelocity;
velocity.y = Mathf.Lerp(velocity.y, target, 0.25f);
flyer.linearVelocity = velocity;
}
Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y);
Rising = true;
return;
}
bool wants = RaceInput.Allowed && JumpHeld();
bool airborne = !__instance.IsOnGround() && !__instance.IsSwimming() && !__instance.IsAttached() &&
!__instance.IsFlying();
airTime = airborne ? airTime + Time.fixedDeltaTime : 0f;
float cost = AlfarPowerConfig.LevitationCostPerSecond.Value;
bool canPay = AlfarArchon.Active || __instance.GetEitr() > 0f;
if (!wants || !airborne || airTime < AirDelay || !canPay)
{
Rising = false;
FlushSpend(__instance);
return;
}
Rising = true;
Rigidbody body = Traverse.Create(__instance).Field("m_body").GetValue<Rigidbody>();
if (body != null)
{
Vector3 velocity = body.linearVelocity;
velocity.y = Mathf.Lerp(velocity.y, AlfarPowerConfig.LevitationRise.Value, 0.25f);
body.linearVelocity = velocity;
}
// Rising resets the fall: the point of the soft fall is that the way down starts at
// the top, and a long climb must not count as a long drop at eitr zero.
Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y);
// In the archon form the eitr is already gone and the pool pays for nothing here.
if (!AlfarArchon.Active) owed += cost * Time.fixedDeltaTime;
if (Time.time >= nextSpend) FlushSpend(__instance);
}
}
private static bool JumpHeld()
{
// "Jump" is the keyboard binding only; the pad's button is a separate "JoyJump", read
// the way PlayerController reads it, kept off while a radial menu has the pad.
return ZInput.GetButton("Jump") || (ZInput.GetButton("JoyJump") && !Hud.InRadial());
}
private static bool CrouchHeld()
{
// Same split as jump: PlayerController ORs "Crouch" with "JoyCrouch".
return ZInput.GetButton("Crouch") || (ZInput.GetButton("JoyCrouch") && !Hud.InRadial());
}
private static void FlushSpend(Player player)
{
nextSpend = Time.time + SpendInterval;
if (owed <= 0f) return;
AlfarEitr.Spend(player, owed);
owed = 0f;
}
private static void Reset()
{
airTime = 0f;
owed = 0f;
Rising = false;
}
}
}

View file

@ -0,0 +1,108 @@
using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The LJOSGARD, the garden of light (Alfar_Progettazione.txt sec. 8.6 and 12): the module of the
/// Nexus that mixes the two mushrooms of the Mistlands into SAP, very slowly.
///
/// It is a clone of the stone furnace with its recipe turned: MAGECAP is the "ore" and JOTUN PUFFS
/// the "fuel", one of each per sap, so mixing the two is exactly what a smelter already does with
/// its two inputs. Being a Smelter it needs no new code to be served: the drones feed it (a
/// Smelter-family station) and carry the sap away, and the refinery (vanilla, sap as fuel and soft
/// tissue as ore) is served by them too. Output falls where a furnace's does.
/// </summary>
public static class AlfarLjosgard
{
public const string PieceName = "AlfarLjosgard";
public const string PieceDisplay = "$rov_piece_alfar_ljosgard_name";
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("smelter");
ItemDrop magecap = PrefabManager.Cache.GetPrefab<ItemDrop>("MushroomMagecap");
ItemDrop puffs = PrefabManager.Cache.GetPrefab<ItemDrop>("MushroomJotunPuffs");
ItemDrop sap = PrefabManager.Cache.GetPrefab<ItemDrop>("Sap");
if (source == null || magecap == null || puffs == null || sap == null)
{
Jotunn.Logger.LogWarning("[Alfar] The Ljosgard needs the 'smelter' piece and the Magecap, Jotun Puffs and Sap items: not registered.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source);
if (prefab == null) return;
// The furnace's heat and its fire: the Ljosgard is cool to the touch (guide 5.1).
AswidBloodRefinery.StripOffensive(prefab, "Ljosgard");
Smelter smelter = prefab.GetComponent<Smelter>();
if (smelter == null)
{
Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Smelter component: no Ljosgard.");
return;
}
smelter.m_name = PieceDisplay;
smelter.m_conversion = new List<Smelter.ItemConversion>
{
new Smelter.ItemConversion { m_from = magecap, m_to = sap },
};
smelter.m_fuelItem = puffs;
smelter.m_fuelPerProduct = 1;
smelter.m_maxOre = AlfarNexusConfig.GardCapacity.Value;
smelter.m_maxFuel = AlfarNexusConfig.GardCapacity.Value;
smelter.m_secPerProduct = AlfarNexusConfig.GardSecondsPerSap.Value;
smelter.m_requiresRoof = false;
smelter.m_spawnStack = false;
smelter.m_windmill = null;
AlfarConstructs.Tint(prefab, new Color(0.55f, 0.85f, 0.7f, 1f));
Piece piece = prefab.GetComponent<Piece>();
if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Piece."); return; }
piece.m_craftingStation = null;
piece.m_name = PieceDisplay;
piece.m_description = "$rov_piece_alfar_ljosgard_desc";
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplay,
Description = "$rov_piece_alfar_ljosgard_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = piece.m_icon,
Requirements = new[]
{
new RequirementConfig("Bronze", AlfarNexusConfig.GardBronze.Value, 0, true),
new RequirementConfig("MushroomJotunPuffs", AlfarNexusConfig.GardMushrooms.Value, 0, true),
new RequirementConfig("MushroomMagecap", AlfarNexusConfig.GardMushrooms.Value, 0, true),
},
}));
// One per Ljoskjarne, inside its reach, and only for the Alfar.
PieceDensityLimit.Register(PieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_ljosgard");
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (!AlfarRace.IsLocalAlfar())
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
}
if (AlfarNexusBehaviour.Covering(position) == null)
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_gard_needs_nexus"));
return false;
}
return true;
});
AlfarPieces.Extra.Add(PieceName);
}
}
}

View file

@ -0,0 +1,149 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Marks a creature or a piece as one of the Alfar's own: a construct, a drone or a tower.
///
/// What the mark does is decided in ONE place, the patches below, instead of editing every attack
/// of every cloned creature (Alfar_Progettazione.txt sec. 8.5 and 16C P4):
/// - everything the marked thing deals becomes LIGHTNING, with the same total; chop and pickaxe
/// are tool damage and are dropped;
/// - it never hurts an ally;
/// - it never hurts a building, a tree or a rock.
/// Intercepting the hit covers melee, projectiles and area attacks alike, whatever the vanilla
/// creature does with its weapons.
/// </summary>
public class AlfarMark : MonoBehaviour
{
/// <summary>"drone", "construct" or "tower": only for logs and the status command.</summary>
public string Role = "";
/// <summary>The attacker's mark, or null when the hit is not from one of ours.</summary>
public static AlfarMark Of(HitData hit)
{
if (hit == null) return null;
Character attacker = hit.GetAttacker();
return attacker != null ? attacker.GetComponent<AlfarMark>() : null;
}
/// <summary>All the damage that can wound a person, moved into lightning. Chop and pickaxe go.</summary>
public static void ConvertToLightning(HitData hit)
{
HitData.DamageTypes d = hit.m_damage;
float total = d.m_damage + d.m_blunt + d.m_slash + d.m_pierce + d.m_fire + d.m_frost +
d.m_poison + d.m_spirit + d.m_lightning;
HitData.DamageTypes converted = default(HitData.DamageTypes);
converted.m_lightning = total;
hit.m_damage = converted;
}
}
/// <summary>The blows of an Alfar creature: lightning only, and never on a friend.</summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class AlfarMark_CharacterDamage_Patch
{
public static bool Prefix(Character __instance, HitData __0)
{
AlfarMark mark = AlfarMark.Of(__0);
if (mark == null) return true;
Character attacker = __0.GetAttacker();
if (__instance == attacker) return false;
// Nobody on our side is ever hurt by us: players, their tames, the other constructs.
if (!BaseAI.IsEnemy(attacker, __instance)) return false;
AlfarMark.ConvertToLightning(__0);
return true;
}
}
/// <summary>
/// Buildings, trees and rocks take nothing from the Alfar's creatures: the golem that razed its
/// owner's base would be a bug. One prefix on every kind of thing that can be struck.
/// </summary>
[HarmonyPatch]
public static class AlfarMark_StructureDamage_Patch
{
public static IEnumerable<MethodBase> TargetMethods()
{
System.Type[] types =
{
typeof(WearNTear), typeof(Destructible), typeof(MineRock5), typeof(MineRock),
typeof(TreeBase), typeof(TreeLog),
};
foreach (System.Type type in types)
{
MethodBase method = AccessTools.Method(type, "Damage", new[] { typeof(HitData) });
if (method != null) yield return method;
else Jotunn.Logger.LogWarning($"[Alfar] {type.Name}.Damage(HitData) not found: that structure is not protected from the Alfar's creatures.");
}
}
public static bool Prefix(HitData __0)
{
return AlfarMark.Of(__0) == null;
}
}
/// <summary>
/// A shield equal to the creature's health that comes back by itself: 1% of it per second once it
/// has gone five seconds without being hit (design sec. 8.5 and 9.6). Health does NOT come back:
/// the damage to the body is permanent, which is why a construct is rebuilt and not repaired.
///
/// Its own absorption and not SE_Shield: the blow arrives at ApplyDamage, and what is left after
/// the shield is what reaches the health (the same stage the Alfr's own eitr shield uses).
/// </summary>
public class AlfarCreatureShield : MonoBehaviour
{
public float MaxShield;
public float Shield;
public float RegenPerSecondFraction = 0.01f;
public float QuietSeconds = 5f;
private float lastHit = -999f;
private void Awake()
{
if (Shield <= 0f) Shield = MaxShield;
}
private void Update()
{
if (Shield >= MaxShield || Time.time - lastHit < QuietSeconds) return;
Shield = Mathf.Min(MaxShield, Shield + MaxShield * RegenPerSecondFraction * Time.deltaTime);
}
public void Absorb(HitData hit)
{
float total = hit.m_damage.GetTotalDamage();
if (total <= 0f) return;
lastHit = Time.time;
float absorbed = Mathf.Min(Shield, total);
Shield -= absorbed;
HitData.DamageTypes rest = hit.m_damage;
rest.Modify((total - absorbed) / total);
hit.m_damage = rest;
}
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_CreatureShield_Patch
{
public static void Prefix(Character __instance, HitData __0)
{
if (__0 == null || __instance is Player) return;
AlfarCreatureShield shield = __instance.GetComponent<AlfarCreatureShield>();
if (shield != null) shield.Absorb(__0);
}
}
}
}

View file

@ -0,0 +1,103 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// GRAFVAETTIR, the mining grenade (Alfar_Progettazione.txt sec. 9.3): unlocked at Eikthyr, thrown
/// like a grenade at a point; five drones dig the precious ores around it for two minutes and
/// vanish. The ore falls where it stands, and nothing else limits it but its cost (eitr, a little
/// stone and flint) and a five minute wait.
///
/// The thrown part is only the spawn; the digging is AlfarMiner on the drones themselves.
/// </summary>
public static class AlfarMiners
{
private static float readyAt;
public static void Tick(Player player)
{
// Nothing to tick per frame: the miners run themselves. Kept so the power loop treats
// every power the same way.
}
public static void Throw(Player player)
{
if (Time.time < readyAt)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_cooldown", Mathf.CeilToInt(readyAt - Time.time)));
return;
}
Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
Vector3 origin = aim.position;
Vector3 direction = aim.forward;
float range = AlfarPowerConfig.GrafRange.Value;
Vector3 point = origin + direction * range;
foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore))
{
if (hit.collider.GetComponentInParent<Player>() == player) continue;
if (Vector3.Distance(origin, hit.point) < Vector3.Distance(origin, point)) point = hit.point;
}
// The price: a little eitr, a little stone, a little flint.
string stone = SharedName("Stone");
string flint = SharedName("Flint");
int needStone = AlfarPowerConfig.GrafStone.Value;
int needFlint = AlfarPowerConfig.GrafFlint.Value;
float eitr = AlfarPowerConfig.GrafEitr.Value;
Inventory inventory = player.GetInventory();
if (inventory.CountItems(stone, -1, false) < needStone || inventory.CountItems(flint, -1, false) < needFlint)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_materials", needStone, needFlint));
return;
}
if (player.GetEitr() < eitr)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr"));
return;
}
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(AlfarDrones.MinerName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{AlfarDrones.MinerName}' in ZNetScene: the mining drones cannot be thrown.");
return;
}
inventory.RemoveItem(stone, needStone, -1, false);
inventory.RemoveItem(flint, needFlint, -1, false);
AlfarEitr.Spend(player, eitr);
readyAt = Time.time + AlfarPowerConfig.GrafCooldown.Value;
AlfarStatusEffects.ShowTimer("graf", AlfarPowerConfig.GrafCooldown.Value);
int count = AlfarPowerConfig.GrafCount.Value;
for (int i = 0; i < count; i++)
{
Vector2 offset = Random.insideUnitCircle * 1.5f;
Vector3 where = point + new Vector3(offset.x, 1.5f + i * 0.2f, offset.y);
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
AlfarMiner miner = spawned.GetComponent<AlfarMiner>();
if (miner != null) miner.Assign(point, AlfarPowerConfig.GrafRadius.Value, AlfarPowerConfig.GrafSeconds.Value);
// Tame at once so nothing flees them and they flee nothing; no anchor, no leash.
MonsterAI ai = spawned.GetComponent<MonsterAI>();
Character character = spawned.GetComponent<Character>();
if (ai != null) ai.MakeTame();
if (character != null) character.SetTamed(true);
}
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", point);
Jotunn.Logger.LogInfo($"[Alfar] Grafvaettir thrown: {count} at {point}.");
}
private static string SharedName(string prefabName)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null;
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
return drop != null ? drop.m_itemData.m_shared.m_name : prefabName;
}
}
}

View file

@ -0,0 +1,578 @@
using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The LJOSKJARNE, the Alfar's Nexus (Alfar_Progettazione.txt sec. 8): the one piece the whole
/// base hangs from. It makes the drones and the constructs, it keeps the crystals, and the towers
/// and the drones only work inside its radius. One per 1.6 km2 like the other races' stations.
///
/// ONE INTERACTION POINT (guide 4.7): E opens the vanilla merchant window with a row per product
/// (AlfarNexusStore), the way the Trol's war totem and the Dvergar's contract bank do. The first
/// version stepped through the products with Shift+E, which gave trouble in other races' tests, and
/// the player asked for the store. The prices are not coins: they come out of the pack, and the
/// row's tooltip lists them with how many exist and how many are allowed.
///
/// Everything is paid from the player's inventory. The crystals the Nexus makes (after the
/// Kristallvigsla) pile up inside it, a beehive's way - slowly, to a cap, and it stops when full
/// until somebody collects - and "collect" moves them to the pack.
/// </summary>
public static class AlfarNexus
{
public const string PieceName = "AlfarNexus";
public const string PieceDisplay = "$rov_piece_alfar_nexus_name";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Alfar] Could not clone piece_cartographytable; the Ljoskjarne is not registered.");
return;
}
// The MapTable trap (Butler 4.1): MapTable is Interactable AND Hoverable and takes the E
// key before our Switch sees it. Everything goes except what makes it a building.
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
Object.DestroyImmediate(behaviour);
}
// The floating pyramid; the blue table stays as the fallback if it cannot be built.
bool pyramid = AlfarNexusLook.Build(prefab);
if (!pyramid) AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f));
AlfarNexusBehaviour nexus = prefab.AddComponent<AlfarNexusBehaviour>();
nexus.m_switch = prefab.AddComponent<Switch>();
nexus.m_switch.m_name = PieceDisplay;
// A Trader with an empty catalogue: StoreGui needs one to open at all, and the rows are drawn
// by AlfarNexusStore. Disabled and with every list filled, for the reasons the Trol's totem
// spells out (Trader.Update and Start assume an animator and a look-at rig that a nucleus
// does not have, and an unfilled list sends Trader.Interact into a null Say).
Trader trader = prefab.GetComponent<Trader>() ?? prefab.AddComponent<Trader>();
trader.m_name = PieceDisplay;
trader.enabled = false;
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();
trader.m_randomGreets = new List<string>();
trader.m_randomGoodbye = new List<string>();
trader.m_randomStartTrade = new List<string>();
trader.m_randomBuy = new List<string>();
trader.m_randomSell = new List<string>();
trader.m_randomGiveItemNo = new List<string>();
trader.m_randomUseItemAlreadyRecieved = new List<string>();
trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>();
Sprite icon = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplay;
piece.m_canBeRemoved = true;
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = icon;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplay,
Description = "$rov_piece_alfar_nexus_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = icon,
Requirements = new[]
{
new RequirementConfig("Bronze", AlfarNexusConfig.NexusBronze.Value, 0, true),
new RequirementConfig("Stone", AlfarNexusConfig.NexusStone.Value, 0, true),
},
}));
PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(AlfarNexusConfig.NexusDensityKm2.Value),
1, "rov_msg_build_limit_alfar_nexus");
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (AlfarRace.IsLocalAlfar()) return true;
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
});
}
public static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
return icons != null && icons.Length > 0 ? icons[0] : null;
}
/// <summary>Teaches the player the Alfar's pieces: a piece registered after the learning pass does not reach its table alone (guide 4.4).</summary>
public static void EnsureKnown(Player player)
{
if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return;
Traverse traverse = Traverse.Create(player);
foreach (string name in AlfarPieces.AllNames())
{
GameObject prefab = PrefabManager.Instance.GetPrefab(name);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece != null) traverse.Method("AddKnownPiece", piece).GetValue();
}
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
}
/// <summary>The names of every piece the Alfar can build, in one place for the lock and for learning.</summary>
public static class AlfarPieces
{
public static readonly List<string> Extra = new List<string>();
public static IEnumerable<string> AllNames()
{
yield return AlfarNexus.PieceName;
foreach (string name in Extra) yield return name;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class AlfarKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
AlfarNexus.EnsureKnown(__instance);
}
}
public class AlfarNexusBehaviour : MonoBehaviour
{
public Switch m_switch;
public static readonly List<AlfarNexusBehaviour> All = new List<AlfarNexusBehaviour>();
private const string KeySelected = "RoV_alfarSel";
private const string KeyUpgrade = "RoV_alfarUp";
private const string KeyCrystals = "RoV_alfarCr";
private const string KeyCrystalAt = "RoV_alfarCrAt";
public enum Product { Drone = 0, Neistvordr = 1, Eldingvordr = 2, Steinvordr = 3, Upgrade = 4, Collect = 5 }
private static readonly int ProductCount = System.Enum.GetValues(typeof(Product)).Length;
private ZNetView m_nview;
private void Awake()
{
m_nview = GetComponent<ZNetView>();
All.Add(this);
RaisedThrall.RegisterStation(transform);
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
}
private void OnDestroy()
{
All.Remove(this);
RaisedThrall.UnregisterStation(transform);
}
/// <summary>The nearest Ljoskjarne whose radius covers the point, or null.</summary>
public static AlfarNexusBehaviour Covering(Vector3 point)
{
AlfarNexusBehaviour best = null;
float bestDistance = float.MaxValue;
foreach (AlfarNexusBehaviour nexus in All)
{
if (nexus == null) continue;
float distance = Vector3.Distance(nexus.transform.position, point);
if (distance <= AlfarNexusConfig.NexusRadius.Value && distance < bestDistance)
{
best = nexus;
bestDistance = distance;
}
}
return best;
}
// ─── State ───────────────────────────────────────────────────────────
private bool Upgraded => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetInt(KeyUpgrade, 0) == 1;
public int Crystals => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyCrystals, 0) : 0;
private Product Selected
{
get
{
int value = m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeySelected, 0) : 0;
return (Product)Mathf.Clamp(value, 0, ProductCount - 1);
}
}
private bool Available(Product product)
{
bool constructsOpen = Upgraded && BossProgressionManager.GetCurrentProgressionState() >= AlfarNexusConfig.ConstructState;
switch (product)
{
case Product.Drone: return true;
case Product.Neistvordr:
case Product.Eldingvordr:
case Product.Steinvordr: return constructsOpen;
case Product.Upgrade: return !Upgraded;
case Product.Collect: return Upgraded;
}
return false;
}
// ─── Crystals: a beehive's way ───────────────────────────────────────
/// <summary>
/// One crystal per Time Factor beehive-intervals of WORLD time, up to the cap, and nothing while
/// full: the clock restarts when somebody collects, like the honey. Only the owner counts.
/// The beehive's own interval is read, not copied (guide 3.2) - and only the INTERVAL, not its
/// daylight rule: the Alfar have no light mechanic (doc sec. 8.6).
/// </summary>
private void Update()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner() || !Upgraded || ZNet.instance == null) return;
ZDO zdo = m_nview.GetZDO();
int cap = AlfarNexusConfig.CrystalCap.Value;
int stored = zdo.GetInt(KeyCrystals, 0);
double now = ZNet.instance.GetTimeSeconds();
if (stored >= cap) { zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); return; }
string stamp = zdo.GetString(KeyCrystalAt, "");
if (!double.TryParse(stamp, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double at))
{
zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
return;
}
float interval = CrystalInterval();
int made = Mathf.FloorToInt((float)((now - at) / interval));
if (made <= 0) return;
stored = Mathf.Min(cap, stored + made);
zdo.Set(KeyCrystals, stored);
zdo.Set(KeyCrystalAt, (at + made * interval).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
/// <summary>Seconds per crystal: Time Factor times a vanilla beehive's seconds per honey.</summary>
public static float CrystalInterval()
{
Beehive hive = TrentaConfig.FindVanillaBeehive();
float honey = hive != null && hive.m_secPerUnit > 0f ? hive.m_secPerUnit : 1200f;
return honey * AlfarNexusConfig.CrystalTimeFactor.Value;
}
// ─── Costs ───────────────────────────────────────────────────────────
private struct Cost
{
public string Item;
public int Amount;
public Cost(string item, int amount) { Item = item; Amount = amount; }
}
private static List<Cost> CostOf(Product product)
{
switch (product)
{
case Product.Drone:
return new List<Cost> { new Cost("Bronze", AlfarNexusConfig.DroneBronze.Value) };
case Product.Neistvordr:
return new List<Cost>
{
new Cost("Bronze", AlfarNexusConfig.NeistMetal.Value),
new Cost("Crystal", AlfarNexusConfig.NeistCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.NeistEitr.Value),
};
case Product.Eldingvordr:
return new List<Cost>
{
new Cost("Iron", AlfarNexusConfig.EldingMetal.Value),
new Cost("Crystal", AlfarNexusConfig.EldingCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.EldingEitr.Value),
};
case Product.Steinvordr:
return new List<Cost>
{
new Cost("BlackMetal", AlfarNexusConfig.SteinMetal.Value),
new Cost("Crystal", AlfarNexusConfig.SteinCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.SteinEitr.Value),
};
case Product.Upgrade:
return new List<Cost> { new Cost("Crystal", AlfarNexusConfig.UpgradeCrystals.Value) };
}
return new List<Cost>();
}
private static string SharedName(string prefabName)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null;
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
return drop != null ? drop.m_itemData.m_shared.m_name : prefabName;
}
private static bool CanPay(Player player, List<Cost> costs)
{
foreach (Cost cost in costs)
{
if (cost.Amount <= 0) continue;
if (player.GetInventory().CountItems(SharedName(cost.Item), -1, false) < cost.Amount) return false;
}
return true;
}
private static void Pay(Player player, List<Cost> costs)
{
foreach (Cost cost in costs)
{
if (cost.Amount > 0) player.GetInventory().RemoveItem(SharedName(cost.Item), cost.Amount, -1, false);
}
}
private static string CostText(List<Cost> costs)
{
var parts = new List<string>();
foreach (Cost cost in costs)
{
if (cost.Amount > 0) parts.Add($"{cost.Amount} {Localization.instance.Localize(SharedName(cost.Item))}");
}
return parts.Count == 0 ? "-" : string.Join(", ", parts);
}
// ─── Counts and caps ─────────────────────────────────────────────────
private int AliveOf(Product product)
{
Vector3 anchor = transform.position;
switch (product)
{
case Product.Drone: return AlfarDrones.CountAlive(anchor);
case Product.Neistvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Neistvordr);
case Product.Eldingvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Eldingvordr);
case Product.Steinvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Steinvordr);
}
return 0;
}
private static int CapOf(Product product)
{
switch (product)
{
case Product.Drone: return AlfarNexusConfig.DroneCap.Value;
case Product.Neistvordr: return AlfarNexusConfig.NeistCap.Value;
case Product.Eldingvordr: return AlfarNexusConfig.EldingCap.Value;
case Product.Steinvordr: return AlfarNexusConfig.SteinCap.Value;
}
return int.MaxValue;
}
private static string NameOf(Product product) => ModText.Get("rov_alfar_product_" + product.ToString().ToLowerInvariant());
// ─── Interaction ─────────────────────────────────────────────────────
private string Hover()
{
var sb = new StringBuilder();
sb.AppendLine(Localization.instance.Localize(AlfarNexus.PieceDisplay));
sb.AppendLine($"[<color=yellow><b>$KEY_Use</b></color>] {ModText.Get("rov_alfar_nexus_open")}");
if (Upgraded) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value));
else sb.AppendLine(ModText.Get("rov_alfar_nexus_no_upgrade"));
return Localization.instance.Localize(sb.ToString());
}
private bool OnUse(Switch sw, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null || m_nview == null || !m_nview.IsValid()) return false;
if (!AlfarVisuals.IsAlfarPlayer(player))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return item != null;
}
// Holding something is not a way to use the nucleus: it only opens the store.
if (item != null)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return true;
}
Trader trader = GetComponent<Trader>();
if (trader == null || StoreGui.instance == null)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_store"));
return false;
}
// The store reads the nucleus back out of StoreGui's own m_trader when it repaints.
StoreGui.instance.Show(trader);
return true;
}
// ─── What the store window uses ──────────────────────────────────────
/// <summary>The products on offer right now, in the order the rows are drawn.</summary>
public List<Product> OnOffer()
{
var list = new List<Product>();
foreach (Product product in System.Enum.GetValues(typeof(Product)))
{
if (Available(product)) list.Add(product);
}
return list;
}
/// <summary>Builds a product from the row the player clicked. Every check Build makes still applies.</summary>
public void BuildFromStore(Product product)
{
Player player = Player.m_localPlayer;
if (player == null || m_nview == null || !m_nview.IsValid() || !Available(product)) return;
m_nview.ClaimOwnership();
Build(player, product);
}
/// <summary>The short number on a row: the metal (or the crystals of the upgrade) it costs.</summary>
public static string PriceShort(Product product)
{
foreach (Cost cost in CostOf(product))
{
if (cost.Amount > 0) return cost.Amount.ToString();
}
return "-";
}
/// <summary>The full terms for the row's tooltip: the price, how many exist, how many are allowed.</summary>
public string Terms(Product product)
{
var sb = new StringBuilder();
sb.AppendLine(CostText(CostOf(product)));
int cap = CapOf(product);
if (cap != int.MaxValue) sb.AppendLine(ModText.Get("rov_alfar_store_count", AliveOf(product), cap));
if (product == Product.Collect) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value));
sb.Append(ModText.Get("rov_alfar_store_terms"));
return sb.ToString();
}
public static string ProductName(Product product) => NameOf(product);
private void Build(Player player, Product product)
{
List<Cost> costs = CostOf(product);
if (product == Product.Collect)
{
Collect(player);
return;
}
if (AliveOf(product) >= CapOf(product))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cap"));
return;
}
if (!CanPay(player, costs))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cannot_pay", CostText(costs)));
return;
}
bool done;
switch (product)
{
case Product.Drone: done = AlfarDrones.Spawn(transform.position); break;
case Product.Neistvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Neistvordr); break;
case Product.Eldingvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Eldingvordr); break;
case Product.Steinvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Steinvordr); break;
case Product.Upgrade: done = true; break;
default: done = false; break;
}
if (!done) return;
Pay(player, costs);
if (product == Product.Upgrade)
{
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeyUpgrade, 1);
zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture));
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_upgraded"));
}
else
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_built", NameOf(product)));
}
}
private void Collect(Player player)
{
int stored = Crystals;
if (stored <= 0)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_crystals"));
return;
}
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab("Crystal") : null;
if (prefab == null) return;
// Whatever fits goes in the pack; the rest stays in the Nexus.
int taken = 0;
for (int i = 0; i < stored; i++)
{
if (!player.GetInventory().CanAddItem(prefab, 1)) break;
if (!player.GetInventory().AddItem(prefab, 1)) break;
taken++;
}
if (taken > 0)
{
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeyCrystals, stored - taken);
// Collecting restarts the clock, like emptying a hive.
zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_collected", taken));
}
/// <summary>Crystals a drone may carry away from the Nexus, and the call that does it (used by the drone's work).</summary>
public int TakeCrystals(int wanted)
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return 0;
int stored = Crystals;
int taken = Mathf.Min(stored, wanted);
if (taken <= 0) return 0;
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeyCrystals, stored - taken);
zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture));
return taken;
}
}
}

View file

@ -0,0 +1,149 @@
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The numbers of the Alfar's base: the Nexus, its drones, the constructs, the towers and the
/// crystals (Alfar_Progettazione.txt sec. 8, 9 and 19). All starting values, all to be corrected
/// in play, none in the logic files.
/// </summary>
public static class AlfarNexusConfig
{
// The progression state the constructs open at (BossProgressionManager: 6 = Yagluth down).
public const int ConstructState = 6;
// ─── The Nexus ───────────────────────────────────────────────────────
public static ConfigEntry<float> NexusRadius;
public static ConfigEntry<float> NexusDensityKm2;
public static ConfigEntry<int> NexusBronze;
public static ConfigEntry<int> NexusStone;
// ─── Drones ──────────────────────────────────────────────────────────
public static ConfigEntry<int> DroneBronze;
public static ConfigEntry<int> DroneCap;
public static ConfigEntry<float> DroneHealth;
public static ConfigEntry<float> DroneZapDamage;
public static ConfigEntry<float> DroneZapInterval;
// ─── Mining drones ───────────────────────────────────────────────────
public static ConfigEntry<string> MinerDeposits;
public static ConfigEntry<float> MinerDamage;
public static ConfigEntry<string> WildPickables;
// ─── Constructs ──────────────────────────────────────────────────────
public static ConfigEntry<int> NeistMetal;
public static ConfigEntry<int> NeistCrystal;
public static ConfigEntry<int> NeistEitr;
public static ConfigEntry<int> NeistCap;
public static ConfigEntry<int> EldingMetal;
public static ConfigEntry<int> EldingCrystal;
public static ConfigEntry<int> EldingEitr;
public static ConfigEntry<int> EldingCap;
public static ConfigEntry<int> SteinMetal;
public static ConfigEntry<int> SteinCrystal;
public static ConfigEntry<int> SteinEitr;
public static ConfigEntry<int> SteinCap;
public static ConfigEntry<float> ConstructLeash;
public static ConfigEntry<float> ConstructAlertRange;
public static ConfigEntry<float> WitherSeconds;
public static ConfigEntry<float> SphereDamage;
public static ConfigEntry<float> SphereIntervalSeconds;
public static ConfigEntry<float> SphereRange;
// ─── Crystals ────────────────────────────────────────────────────────
public static ConfigEntry<int> UpgradeCrystals;
public static ConfigEntry<int> CrystalCap;
public static ConfigEntry<float> CrystalTimeFactor;
// ─── Towers ──────────────────────────────────────────────────────────
public static ConfigEntry<int> TowerBronze;
public static ConfigEntry<int> TowerCrystal;
public static ConfigEntry<float> TowerHealthFactor;
public static ConfigEntry<float> TowerDamage;
public static ConfigEntry<float> TowerScale;
// ─── Ljosgard (sap) and chests ───────────────────────────────────────
public static ConfigEntry<int> GardBronze;
public static ConfigEntry<int> GardMushrooms;
public static ConfigEntry<float> GardSecondsPerSap;
public static ConfigEntry<int> GardCapacity;
public static ConfigEntry<int> ChestEyes;
public static void Bind(ConfigFile config)
{
const string nexus = "Alfar - Nexus";
NexusRadius = config.Bind(nexus, "Radius", 40f, new ConfigDescription("Metres around a Ljoskjarne where its drones work and its towers run.", new AcceptableValueRange<float>(10f, 150f)));
NexusDensityKm2 = config.Bind(nexus, "Density Km2", 1.6f, new ConfigDescription("At most one Ljoskjarne per this many square kilometres.", new AcceptableValueRange<float>(0.1f, 20f)));
NexusBronze = config.Bind(nexus, "Bronze Cost", 40, new ConfigDescription("Bronze to build a Ljoskjarne.", new AcceptableValueRange<int>(0, 500)));
NexusStone = config.Bind(nexus, "Stone Cost", 30, new ConfigDescription("Stone to build a Ljoskjarne.", new AcceptableValueRange<int>(0, 500)));
const string drone = "Alfar - Drones";
DroneBronze = config.Bind(drone, "Bronze Cost", 8, new ConfigDescription("Bronze for each Ljosvaettir.", new AcceptableValueRange<int>(0, 200)));
DroneCap = config.Bind(drone, "Cap Per Nexus", 6, new ConfigDescription("Most drones one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
DroneHealth = config.Bind(drone, "Health", 25f, new ConfigDescription("A drone's health and shield (a Deathsquito has 10).", new AcceptableValueRange<float>(1f, 1000f)));
DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange<float>(0f, 100f)));
DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange<float>(0.2f, 30f)));
// Copper deposits are rock4_copper (and rock4_copper_frac once hit), crypt scrap is mudpile;
// the first default missed both, so a config still holding it is moved to the new one.
const string oldTargets = "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain";
const string targets = "rock4_copper,MineRock_Copper,MineRock_Tin,MineRock_Iron,mudpile,silvervein,rock3_silver,giant_brain";
MinerDeposits = config.Bind(drone, "Mining Targets", targets,
new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain."));
if (MinerDeposits.Value == oldTargets) MinerDeposits.Value = targets;
MinerDamage = config.Bind(drone, "Mining Damage", 40f, new ConfigDescription("Pickaxe damage each mining drone does per second to a deposit.", new AcceptableValueRange<float>(1f, 1000f)));
WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush",
new ConfigDescription("Comma separated parts of prefab names of WILD plants the drones pick without replanting (mushrooms, berry bushes, flowers). Trees are never touched. Cultivated crops are always replanted."));
const string construct = "Alfar - Constructs";
NeistMetal = config.Bind(construct, "Neistvordr Bronze", 20, new ConfigDescription("Bronze for a Neistvordr.", new AcceptableValueRange<int>(0, 500)));
NeistCrystal = config.Bind(construct, "Neistvordr Crystal", 3, new ConfigDescription("Crystals for a Neistvordr.", new AcceptableValueRange<int>(0, 50)));
NeistEitr = config.Bind(construct, "Neistvordr Refined Eitr", 3, new ConfigDescription("Refined eitr for a Neistvordr.", new AcceptableValueRange<int>(0, 50)));
NeistCap = config.Bind(construct, "Neistvordr Cap", 4, new ConfigDescription("Most Neistvordr one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
EldingMetal = config.Bind(construct, "Eldingvordr Iron", 20, new ConfigDescription("Iron for an Eldingvordr.", new AcceptableValueRange<int>(0, 500)));
EldingCrystal = config.Bind(construct, "Eldingvordr Crystal", 5, new ConfigDescription("Crystals for an Eldingvordr.", new AcceptableValueRange<int>(0, 50)));
EldingEitr = config.Bind(construct, "Eldingvordr Refined Eitr", 4, new ConfigDescription("Refined eitr for an Eldingvordr.", new AcceptableValueRange<int>(0, 50)));
EldingCap = config.Bind(construct, "Eldingvordr Cap", 4, new ConfigDescription("Most Eldingvordr one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
SteinMetal = config.Bind(construct, "Steinvordr Black Metal", 20, new ConfigDescription("Black metal for a Steinvordr.", new AcceptableValueRange<int>(0, 500)));
SteinCrystal = config.Bind(construct, "Steinvordr Crystal", 8, new ConfigDescription("Crystals for a Steinvordr.", new AcceptableValueRange<int>(0, 50)));
SteinEitr = config.Bind(construct, "Steinvordr Refined Eitr", 6, new ConfigDescription("Refined eitr for a Steinvordr.", new AcceptableValueRange<int>(0, 50)));
SteinCap = config.Bind(construct, "Steinvordr Cap", 1, new ConfigDescription("Most Steinvordr one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
ConstructLeash = config.Bind(construct, "Leash Range", 12f, new ConfigDescription("How far a construct wanders from its Ljoskjarne when not following.", new AcceptableValueRange<float>(2f, 80f)));
ConstructAlertRange = config.Bind(construct, "Alert Range", 25f, new ConfigDescription("How far a construct notices and chases enemies.", new AcceptableValueRange<float>(5f, 100f)));
WitherSeconds = config.Bind(construct, "Wither Seconds", 60f, new ConfigDescription("How long creatures last after their Ljoskjarne falls.", new AcceptableValueRange<float>(0f, 600f)));
SphereDamage = config.Bind(construct, "Sphere Damage", 80f, new ConfigDescription("Lightning damage of the Eldingvordr's sphere.", new AcceptableValueRange<float>(1f, 1000f)));
SphereIntervalSeconds = config.Bind(construct, "Sphere Interval", 8f, new ConfigDescription("Seconds between the Eldingvordr's shots.", new AcceptableValueRange<float>(0.5f, 60f)));
SphereRange = config.Bind(construct, "Sphere Range", 30f, new ConfigDescription("How far the Eldingvordr shoots.", new AcceptableValueRange<float>(5f, 80f)));
const string crystal = "Alfar - Crystals";
UpgradeCrystals = config.Bind(crystal, "Upgrade Cost", 20, new ConfigDescription("Crystals the player must find for the Kristallvigsla.", new AcceptableValueRange<int>(0, 200)));
CrystalCap = config.Bind(crystal, "Stored Cap", 20, new ConfigDescription("Most crystals the Ljoskjarne holds before it stops making them.", new AcceptableValueRange<int>(1, 200)));
CrystalTimeFactor = config.Bind(crystal, "Time Factor", 2f, new ConfigDescription("A crystal takes this many times a vanilla beehive's time for one honey.", new AcceptableValueRange<float>(0.1f, 20f)));
const string tower = "Alfar - Towers";
TowerBronze = config.Bind(tower, "Bronze Cost", 25, new ConfigDescription("Bronze for a Prismavard.", new AcceptableValueRange<int>(0, 500)));
TowerCrystal = config.Bind(tower, "Crystal Cost", 2, new ConfigDescription("Crystals for a Prismavard.", new AcceptableValueRange<int>(0, 50)));
TowerHealthFactor = config.Bind(tower, "Health Factor", 0.5f, new ConfigDescription("A Prismavard's health against the charred ballista's 400.", new AcceptableValueRange<float>(0.05f, 3f)));
TowerDamage = config.Bind(tower, "Bolt Damage", 40f, new ConfigDescription("Lightning damage of a Prismavard's bolt.", new AcceptableValueRange<float>(1f, 1000f)));
TowerScale = config.Bind(tower, "Scale", 0.6f, new ConfigDescription("Size of a Prismavard against the charred ballista.", new AcceptableValueRange<float>(0.2f, 2f)));
const string gard = "Alfar - Ljosgard";
GardBronze = config.Bind(gard, "Bronze Cost", 40, new ConfigDescription("Bronze for a Ljosgard.", new AcceptableValueRange<int>(0, 500)));
GardMushrooms = config.Bind(gard, "Mushrooms Cost", 10, new ConfigDescription("Jotun Puffs AND Magecap, this many of each, to build a Ljosgard.", new AcceptableValueRange<int>(0, 100)));
GardSecondsPerSap = config.Bind(gard, "Seconds Per Sap", 600f, new ConfigDescription("Seconds to turn one Jotun Puffs and one Magecap into a Sap.", new AcceptableValueRange<float>(10f, 7200f)));
GardCapacity = config.Bind(gard, "Sap Capacity", 10, new ConfigDescription("Sap the Ljosgard holds before it stops.", new AcceptableValueRange<int>(1, 200)));
ChestEyes = config.Bind(gard, "Chest Greydwarf Eyes", 3, new ConfigDescription("Greydwarf eyes in the price of the entry chest and the wood chest.", new AcceptableValueRange<int>(0, 50)));
}
}
}

View file

@ -0,0 +1,217 @@
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Ljoskjarne's body: a stone pyramid, 2 m to a side and 2 m tall, floating 0.8 m above the
/// ground. Dark steel carved with Valheim's own runes (the Ashlands rune tile's glyphs, laid out by
/// scripts/paint_nexus.py), and a cyan seam down the middle of each face.
///
/// The seam is painted into the faces' glow map, not built. Bars standing on the faces, lit or
/// unlit, lost part of their length to the face on whichever side looked one way in the world,
/// as the pyramid turned; a line in the face's own pixels has nothing to hide behind.
///
/// Only the look moves. The piece keeps one still collider from the ground up, so building on it,
/// support, hovering and the E key behave as before; the pyramid bobs and turns on each client by
/// itself, nothing over the network. The seam breathes, and burns brighter while crystals wait.
/// </summary>
public static class AlfarNexusLook
{
private const float Height = 2f;
private const float HalfBase = 1f;
private const float Lift = 0.8f;
private const string SourceMaterialPrefab = "piece_cartographytable";
private const string EmbersSource = "fx_Torch_Carried";
private static readonly Color Seam = new Color(0.35f, 0.75f, 1f);
/// <summary>Strips the cartography table's body and puts the pyramid in its place. False leaves
/// the table, with a warning, so the Nexus is never invisible.</summary>
public static bool Build(GameObject prefab)
{
Texture2D face = PieceLook.LoadTexture("AlfarNexus_face.png");
Texture2D glow = PieceLook.LoadTexture("AlfarNexus_glow.png");
Texture2D bumps = PieceLook.LoadTexture("AlfarNexus_n.png", true);
Renderer tableRenderer = prefab.transform.Find("new/high")?.GetComponent<Renderer>();
if (face == null || glow == null || tableRenderer == null || tableRenderer.sharedMaterial == null)
{
Jotunn.Logger.LogWarning("[Alfar] Could not build the Ljoskjarne's pyramid; it keeps the cartography table's look.");
return false;
}
Material stone = new Material(tableRenderer.sharedMaterial) { name = "AlfarNexus_stone" };
stone.color = Color.white;
stone.SetTexture("_MainTex", face);
// Forged, not polished: the plate's own grain in the normal map, and a dull sheen.
stone.SetTexture("_BumpMap", bumps);
if (bumps != null) stone.EnableKeyword("_NORMALMAP");
else stone.DisableKeyword("_NORMALMAP");
if (stone.HasProperty("_MetallicGlossMap")) stone.SetTexture("_MetallicGlossMap", null);
if (stone.HasProperty("_Metallic")) stone.SetFloat("_Metallic", 0.6f);
if (stone.HasProperty("_Glossiness")) stone.SetFloat("_Glossiness", 0.3f);
// Custom/Piece samples its noise in world space unless told the object moves, as boats and
// carts do; on a turning pyramid the blotches would slide across the faces.
stone.EnableKeyword("_MOVEABLEOBJECT_ON");
if (stone.HasProperty("_MoveableObject")) stone.SetFloat("_MoveableObject", 1f);
stone.SetTexture("_EmissionMap", glow);
stone.EnableKeyword("_EMISSION");
stone.SetColor("_EmissionColor", Seam);
// The table goes whole: its meshes, its damage states, its fragments and its four colliders.
for (int i = prefab.transform.childCount - 1; i >= 0; i--)
Object.DestroyImmediate(prefab.transform.GetChild(i).gameObject);
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null)
{
wear.m_new = null;
wear.m_worn = null;
wear.m_broken = null;
wear.m_fragmentRoots = new GameObject[0];
}
// One still collider, from the ground to the tip, a little inside the faces.
GameObject solid = new GameObject("collider") { layer = prefab.layer };
solid.transform.SetParent(prefab.transform, false);
BoxCollider box = solid.AddComponent<BoxCollider>();
box.center = new Vector3(0f, (Lift + Height) / 2f, 0f);
box.size = new Vector3(HalfBase * 1.4f, Lift + Height, HalfBase * 1.4f);
Transform floating = new GameObject("float").transform;
floating.SetParent(prefab.transform, false);
floating.gameObject.layer = prefab.layer;
MeshRenderer pyramid = Part(floating, "pyramid", PyramidMesh(), stone).GetComponent<MeshRenderer>();
NexusLook look = prefab.AddComponent<NexusLook>();
look.Float = floating;
look.SeamRenderer = pyramid;
look.Motes = AddMotes(prefab.transform);
return true;
}
private static GameObject Part(Transform parent, string name, Mesh mesh, Material material)
{
GameObject part = new GameObject(name) { layer = parent.gameObject.layer };
part.transform.SetParent(parent, false);
part.AddComponent<MeshFilter>().sharedMesh = mesh;
part.AddComponent<MeshRenderer>().sharedMaterial = material;
return part;
}
private static Vector3 Apex => new Vector3(0f, Lift + Height, 0f);
private static Vector3[] BaseCorners => new[]
{
new Vector3(-HalfBase, Lift, -HalfBase), new Vector3(HalfBase, Lift, -HalfBase),
new Vector3(HalfBase, Lift, HalfBase), new Vector3(-HalfBase, Lift, HalfBase),
};
/// <summary>Four faces, each with its own three corners so the shading stays flat and every face
/// shows the whole carving (u along the base, v = 1 at the tip), and the underside.</summary>
private static Mesh PyramidMesh()
{
Vector3[] c = BaseCorners;
var vertices = new Vector3[16];
var uvs = new Vector2[16];
var triangles = new int[18];
for (int i = 0; i < 4; i++)
{
// Wound clockwise seen from outside, which is Unity's front face.
vertices[i * 3] = c[(i + 1) % 4];
vertices[i * 3 + 1] = c[i];
vertices[i * 3 + 2] = Apex;
uvs[i * 3] = new Vector2(1f, 0f);
uvs[i * 3 + 1] = new Vector2(0f, 0f);
uvs[i * 3 + 2] = new Vector2(0.5f, 1f);
triangles[i * 3] = i * 3;
triangles[i * 3 + 1] = i * 3 + 1;
triangles[i * 3 + 2] = i * 3 + 2;
}
for (int i = 0; i < 4; i++) { vertices[12 + i] = c[i]; uvs[12 + i] = new Vector2(0.1f, 0.02f); }
int[] under = { 12, 13, 14, 12, 14, 15 };
System.Array.Copy(under, 0, triangles, 12, 6);
Mesh mesh = new Mesh { name = "AlfarNexus_pyramid", vertices = vertices, uv = uvs, triangles = triangles };
mesh.RecalculateNormals();
mesh.RecalculateBounds();
return mesh;
}
/// <summary>A few cyan motes drifting up from the ground under it: the torch's embers, recoloured,
/// spread over the pyramid's shadow and slowed down.</summary>
private static ParticleSystem AddMotes(Transform root)
{
GameObject torch = PrefabManager.Cache.GetPrefab<GameObject>(EmbersSource);
Transform source = torch != null ? torch.transform.Find("Embers") : null;
if (source == null) return null;
GameObject motes = Object.Instantiate(source.gameObject, root, false);
motes.name = "motes";
motes.transform.localPosition = new Vector3(0f, 0.05f, 0f);
motes.transform.localRotation = Quaternion.identity;
PieceLook.Rehue(motes.transform, Seam * 2f);
ParticleSystem particles = motes.GetComponent<ParticleSystem>();
if (particles != null)
{
ParticleSystem.ShapeModule shape = particles.shape;
shape.enabled = true;
shape.shapeType = ParticleSystemShapeType.Circle;
shape.radius = HalfBase;
shape.rotation = new Vector3(-90f, 0f, 0f);
ParticleSystem.MainModule main = particles.main;
main.simulationSpeed = 0.5f;
}
return particles;
}
/// <summary>The motion and the seam's light, per client.</summary>
public class NexusLook : MonoBehaviour
{
public Transform Float;
public Renderer SeamRenderer;
public ParticleSystem Motes;
private const float BobHeight = 0.08f;
private const float BobSeconds = 4.5f;
private const float TurnSeconds = 40f;
private const float BreathSeconds = 3.5f;
private AlfarNexusBehaviour m_nexus;
private Material m_seam;
private float m_phase;
private float m_ready; // eases between 0 (no crystals) and 1, so the brightening is not a jump
private void Awake()
{
m_nexus = GetComponent<AlfarNexusBehaviour>();
if (SeamRenderer != null) m_seam = SeamRenderer.material; // this one's own copy, to animate
// Two Nexuses side by side must not bob in step.
m_phase = (Mathf.Abs(transform.position.x * 0.37f + transform.position.z * 0.71f)) % 10f;
}
private void Update()
{
float t = Time.time + m_phase;
if (Float != null)
{
Float.localPosition = new Vector3(0f, Mathf.Sin(t * 2f * Mathf.PI / BobSeconds) * BobHeight, 0f);
Float.localRotation = Quaternion.Euler(0f, t * 360f / TurnSeconds, 0f);
}
if (m_seam == null) return;
bool ready = m_nexus != null && m_nexus.Crystals > 0;
m_ready = Mathf.MoveTowards(m_ready, ready ? 1f : 0f, Time.deltaTime * 0.5f);
float breath = 0.75f + 0.25f * Mathf.Sin(t * 2f * Mathf.PI / BreathSeconds);
Color glow = Seam * breath * Mathf.Lerp(1f, 2.2f, m_ready);
m_seam.SetColor("_EmissionColor", glow);
}
private void OnDestroy()
{
if (m_seam != null) Destroy(m_seam);
}
}
}
}

View file

@ -0,0 +1,171 @@
using System.Collections.Generic;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// The Ljoskjarne's window: the merchant's own store with a column of products in it - the drone,
/// the three constructs, the crystal upgrade, and the crystals to collect.
///
/// It is the Trol war totem's window (TrolTotemStore) cloned for another trader, and for the same
/// reasons: same three patch points (Awake to build, FillList to repaint, Hide to clear), same trick
/// of instantiating StoreGui.m_listElement for the rows. The empty-catalogue guard that keeps vanilla
/// FillList from throwing is already on every trader with no wares (StoreGuiEmptyCatalogueGuardPatch),
/// so this one needs none of its own.
///
/// What is different from the totem: a row's price is a number out of the pack and not coins, so the
/// short figure on the row is the metal or the crystals, and the tooltip carries the whole price.
/// </summary>
public static class AlfarNexusStore
{
private static RectTransform _list;
private static readonly List<GameObject> _rows = new List<GameObject>();
public static AlfarNexusBehaviour ActiveNexus(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
return trader != null ? trader.GetComponent<AlfarNexusBehaviour>() : null;
}
// ─── build ───────────────────────────────────────────────────────────
public static void Create(StoreGui gui)
{
if (gui == null || gui.m_listRoot == null || _list != null) return;
GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent);
clone.name = "AlfarProductList";
_list = clone.GetComponent<RectTransform>();
_list.anchoredPosition = gui.m_listRoot.anchoredPosition;
// The clone carries whatever rows the vanilla list held at Awake: it starts empty.
foreach (Transform child in _list) Object.Destroy(child.gameObject);
_list.gameObject.SetActive(false);
}
public static void Clear()
{
foreach (GameObject row in _rows) if (row != null) Object.Destroy(row);
_rows.Clear();
if (_list != null) _list.gameObject.SetActive(false);
}
// ─── fill ────────────────────────────────────────────────────────────
public static void Refresh(StoreGui gui)
{
Clear();
AlfarNexusBehaviour nexus = ActiveNexus(gui);
if (nexus == null) return; // an ordinary merchant: not ours
if (_list == null)
{
Jotunn.Logger.LogWarning("[Alfar] The Ljoskjarne's column was never built (did the patch on StoreGui.Awake fail?).");
return;
}
_list.gameObject.SetActive(true);
int row = 0;
foreach (AlfarNexusBehaviour.Product product in nexus.OnOffer())
{
BuildRow(gui, nexus, product, row++);
}
float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue<float>();
_list.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing));
}
private static string IconOf(AlfarNexusBehaviour.Product product)
{
switch (product)
{
case AlfarNexusBehaviour.Product.Drone: return "TrophyDeathsquito";
case AlfarNexusBehaviour.Product.Neistvordr: return "TrophySurtling";
case AlfarNexusBehaviour.Product.Eldingvordr: return "TrophyAbomination";
case AlfarNexusBehaviour.Product.Steinvordr: return "TrophySGolem";
default: return "Crystal";
}
}
private static void BuildRow(StoreGui gui, AlfarNexusBehaviour nexus, AlfarNexusBehaviour.Product product, int rowIndex)
{
GameObject element = Object.Instantiate(gui.m_listElement, _list);
element.SetActive(true);
RectTransform rt = (RectTransform)element.transform;
float offset = (_list.rect.width - rt.rect.width) / 2f;
rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset);
Sprite icon = Icon(IconOf(product));
Image iconImage = element.transform.Find("icon").GetComponent<Image>();
if (icon != null) iconImage.sprite = icon;
string name = AlfarNexusBehaviour.ProductName(product);
element.transform.Find("name").GetComponent<TMP_Text>().text = Localization.instance.Localize(name);
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null) price.text = AlfarNexusBehaviour.PriceShort(product);
// The coin that sits beside the number on a vanilla row is the wrong picture here.
foreach (Image image in element.GetComponentsInChildren<Image>(true))
{
if (image != null && image.gameObject.name.ToLowerInvariant().Contains("coin")) image.gameObject.SetActive(false);
}
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null) tooltip.Set(Localization.instance.Localize(name), nexus.Terms(product), gui.m_tooltipAnchor, default(Vector2));
AlfarNexusBehaviour.Product chosen = product;
element.GetComponent<Button>().onClick.AddListener(() =>
{
nexus.BuildFromStore(chosen);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the column
});
_rows.Add(element);
}
// ─── helpers ─────────────────────────────────────────────────────────
private static Sprite Icon(string prefabName)
{
ItemDrop drop = Jotunn.Managers.PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
return icons != null && icons.Length > 0 ? icons[0] : null;
}
private static T FindDescendant<T>(Transform root, string childName) where T : Component
{
foreach (T candidate in root.GetComponentsInChildren<T>(true))
{
if (candidate.gameObject.name == childName) return candidate;
}
return null;
}
}
[HarmonyPatch(typeof(StoreGui), "Awake")]
public static class AlfarNexusStoreSetupPatch
{
public static void Postfix(StoreGui __instance) => AlfarNexusStore.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class AlfarNexusStoreFillPatch
{
public static void Postfix(StoreGui __instance) => AlfarNexusStore.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class AlfarNexusStoreHidePatch
{
public static void Postfix() => AlfarNexusStore.Clear();
}
}

View file

@ -0,0 +1,180 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The hooks that keep an Alfr looking like one. Only the look so far; the shield, the death
/// timer and the powers add their own patches as they are written.
/// </summary>
public static class AlfarPatches
{
/// <summary>
/// The only thing that actually colours a player.
///
/// SetSkinColor followed by UpdateColors does nothing, because UpdateColors is what REBUILDS
/// the body material from Valheim's own values and throws any earlier write away
/// (DvergarPatches documents the dead end). Writing _SkinColor here, after it has run, is the
/// only order that survives.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class Alfar_UpdateColors_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || __instance.m_bodyModel == null) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return;
AlfarVisuals.ApplyGreyTexture(__instance, true);
Material material = __instance.m_bodyModel.material;
if (material != null && material.HasProperty("_SkinColor"))
{
material.SetColor("_SkinColor", AlfarVisuals.SkinFor(player));
}
}
}
/// <summary>
/// Hair and beard never attach to an Alfr. Every equipment change makes the game write the
/// profile's hair back (Humanoid.SetupVisEquipment), and ApplyHairless only clears it on its
/// 0.5s pass, so players saw the hair flash in for a moment. Zeroing the hash here, where
/// VisEquipment spawns the model, means it never appears. Covers remote players too, since
/// their visuals go through the same call.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "SetHairEquipped")]
public static class Alfar_SetHairEquipped_Patch
{
public static void Prefix(VisEquipment __instance, ref int hash)
{
if (hash != 0 && IsAlfarVis(__instance)) hash = 0;
}
}
[HarmonyPatch(typeof(VisEquipment), "SetBeardEquipped")]
public static class Alfar_SetBeardEquipped_Patch
{
public static void Prefix(VisEquipment __instance, ref int hash)
{
if (hash != 0 && IsAlfarVis(__instance)) hash = 0;
}
}
private static bool IsAlfarVis(VisEquipment vis)
{
Player player = vis.GetComponent<Player>();
return player != null && AlfarVisuals.IsAlfarPlayer(player);
}
/// <summary>
/// The character preview on the main menu is a Player too, with the saved race in its custom data
/// and no ZNetView. Its Update may never run, so a small driver on it keeps the look: skin, hair,
/// scale and eyes, twice a second, for as long as the preview exists. The existing menu hook only
/// pushes ONE colour refresh and knows nothing of eyes or texture.
/// </summary>
public class AlfarPreviewDriver : MonoBehaviour
{
private Player player;
private float next;
private void Awake() { player = GetComponent<Player>(); }
private void Update()
{
if (player == null || Time.time < next) return;
next = Time.time + 0.5f;
bool isAlfar = AlfarVisuals.IsAlfarPlayer(player);
AlfarVisuals.ApplyScale(player, isAlfar);
AlfarVisuals.ApplyEyes(player);
if (isAlfar) AlfarVisuals.ApplyHairless(player);
AlfarVisuals.SyncSkin(player, isAlfar);
}
}
public static void AttachPreviewDriver(FejdStartup instance)
{
Player preview = instance.GetType()
.GetMethod("GetPreviewPlayer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public)
?.Invoke(instance, null) as Player;
if (preview != null && preview.GetComponent<AlfarPreviewDriver>() == null)
{
preview.gameObject.AddComponent<AlfarPreviewDriver>();
}
}
[HarmonyPatch(typeof(FejdStartup), "SetupCharacterPreview")]
public static class Alfar_Preview_Setup_Patch
{
[HarmonyPriority(Priority.Last)]
public static void Postfix(FejdStartup __instance) => AttachPreviewDriver(__instance);
}
[HarmonyPatch(typeof(FejdStartup), "SetSelectedProfile")]
public static class Alfar_Preview_Profile_Patch
{
[HarmonyPriority(Priority.Last)]
public static void Postfix(FejdStartup __instance) => AttachPreviewDriver(__instance);
}
/// <summary>
/// Scale every frame, the cosmetics on a throttle.
///
/// On Player.Update because that is the one place body scale survives: the Trol's postfix
/// forces every other player's visual back to 1 on the same frame, so a scale written
/// anywhere else is simply overwritten. RaceScale keeps the two from undoing each other.
/// This runs for every player in range, not just the local one, so other clients see an
/// Alfr as one.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Alfar_PlayerUpdate_Patch
{
private static readonly Dictionary<Player, float> nextCosmeticPass = new Dictionary<Player, float>();
private const float CosmeticInterval = 0.5f;
public static void Postfix(Player __instance)
{
if (__instance == null) return;
bool isAlfar = AlfarVisuals.IsAlfarPlayer(__instance);
AlfarVisuals.ApplyScale(__instance, isAlfar);
// The passive carrier belongs to the local body only; status effects are re-added
// because they do not survive a reload or a death.
if (__instance == Player.m_localPlayer)
{
if (isAlfar && !__instance.IsDead())
{
AlfarStatusEffects.Ensure(__instance);
AlfarPowers.Tick(__instance);
}
else
{
AlfarStatusEffects.Remove(__instance);
if (AlfarArchon.Active) AlfarArchon.ForceClear(__instance);
}
}
if (!nextCosmeticPass.TryGetValue(__instance, out float due) || Time.time >= due)
{
nextCosmeticPass[__instance] = Time.time + CosmeticInterval;
// Unconditional, like the other races': the eyes have to be able to remove
// themselves from whoever stops being an Alfr, and they cannot do that from
// behind an `if (isAlfar)`.
AlfarVisuals.ApplyEyes(__instance);
AlfarVisuals.ApplyArchonGlow(__instance);
if (isAlfar) AlfarVisuals.ApplyHairless(__instance);
AlfarVisuals.SyncSkin(__instance, isAlfar);
}
}
}
}
}

View file

@ -0,0 +1,170 @@
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The numbers and the keys of the Alfar's powers (Alfar_Progettazione.txt sec. 13 and 19.6).
/// Every value is a STARTING value to be corrected in play. Nothing numeric lives in the logic.
///
/// Keys follow the mod's habit: letters the other races also use (G, H, I, J, K, O, U), because a
/// character has exactly one race, so the same letter never means two things at once.
/// </summary>
public static class AlfarPowerConfig
{
// Progression states a power unlocks at (BossProgressionManager: 2 Eikthyr ... 8 Fader).
public const int SkridState = 2;
public const int GrafvaettirState = 2;
public const int UtsogState = 3;
public const int KallState = 4;
public const int LjosstormState = 5;
public const int GeisliState = 6;
public const int KyrrState = 7;
public const int SameiningState = 8;
// ─── Keys ────────────────────────────────────────────────────────────
public static ConfigEntry<KeyboardShortcut> SkridKey;
public static ConfigEntry<KeyboardShortcut> GrafvaettirKey;
public static ConfigEntry<KeyboardShortcut> KallKey;
public static ConfigEntry<KeyboardShortcut> LjosstormKey;
public static ConfigEntry<KeyboardShortcut> GeisliKey;
public static ConfigEntry<KeyboardShortcut> KyrrKey;
public static ConfigEntry<KeyboardShortcut> SameiningKey;
// ─── Skrid: the blink ────────────────────────────────────────────────
public static ConfigEntry<float> SkridDistance;
public static ConfigEntry<float> SkridCost;
public static ConfigEntry<float> SkridCooldown;
// ─── Utsog: damage dealt comes back as eitr ──────────────────────────
public static ConfigEntry<float> UtsogPercent;
// ─── Kall: telekinesis ───────────────────────────────────────────────
public static ConfigEntry<float> KallRadius;
public static ConfigEntry<float> KallSpeed;
public static ConfigEntry<float> KallCost;
public static ConfigEntry<float> KallCooldown;
// ─── Ljosstorm: the psionic storm ────────────────────────────────────
public static ConfigEntry<float> StormRange;
public static ConfigEntry<float> StormRadius;
public static ConfigEntry<float> StormSeconds;
public static ConfigEntry<float> StormDps;
public static ConfigEntry<float> StormCost;
public static ConfigEntry<float> StormCooldown;
// ─── Geisli: the beam ────────────────────────────────────────────────
public static ConfigEntry<float> BeamRange;
public static ConfigEntry<float> BeamDps;
public static ConfigEntry<float> BeamCostPerSecond;
public static ConfigEntry<float> BeamMaxSeconds;
public static ConfigEntry<float> BeamCooldown;
// ─── Kyrr: stasis ────────────────────────────────────────────────────
public static ConfigEntry<float> StasisRange;
public static ConfigEntry<float> StasisSeconds;
public static ConfigEntry<float> StasisBossSeconds;
public static ConfigEntry<float> StasisCost;
public static ConfigEntry<float> StasisCooldown;
// ─── Sameining: the archon ───────────────────────────────────────────
public static ConfigEntry<float> ArchonThreshold;
public static ConfigEntry<float> ArchonSeconds;
public static ConfigEntry<float> ArchonScale;
public static ConfigEntry<float> ArchonSpeedBonus;
public static ConfigEntry<float> ArchonPoolPerEitr;
public static ConfigEntry<float> ArchonPulseRadius;
public static ConfigEntry<float> ArchonPulseDamage;
public static ConfigEntry<float> ArchonPulseInterval;
public static ConfigEntry<float> ArchonFreePowerCooldown;
public static ConfigEntry<Color> ArchonColor;
// ─── Grafvaettir: the mining grenade ─────────────────────────────────
public static ConfigEntry<float> GrafRange;
public static ConfigEntry<float> GrafRadius;
public static ConfigEntry<float> GrafSeconds;
public static ConfigEntry<int> GrafCount;
public static ConfigEntry<float> GrafEitr;
public static ConfigEntry<int> GrafStone;
public static ConfigEntry<int> GrafFlint;
public static ConfigEntry<float> GrafCooldown;
// ─── Levitation ──────────────────────────────────────────────────────
public static ConfigEntry<float> LevitationRise;
public static ConfigEntry<float> LevitationCostPerSecond;
public static void Bind(ConfigFile config)
{
const string keys = "Alfar - Keybinds";
SkridKey = config.Bind(keys, "Skrid (Blink)", new KeyboardShortcut(KeyCode.G));
GrafvaettirKey = config.Bind(keys, "Grafvaettir (Mining Drones)", new KeyboardShortcut(KeyCode.H));
KallKey = config.Bind(keys, "Kall (Telekinesis)", new KeyboardShortcut(KeyCode.J));
LjosstormKey = config.Bind(keys, "Ljosstorm (Psionic Storm)", new KeyboardShortcut(KeyCode.K));
GeisliKey = config.Bind(keys, "Geisli (Beam, hold)", new KeyboardShortcut(KeyCode.O));
KyrrKey = config.Bind(keys, "Kyrr (Stasis)", new KeyboardShortcut(KeyCode.U));
SameiningKey = config.Bind(keys, "Sameining (Archon)", new KeyboardShortcut(KeyCode.I));
const string skrid = "Alfar - Skrid";
SkridDistance = config.Bind(skrid, "Distance", 8f, new ConfigDescription("Blink length in metres.", new AcceptableValueRange<float>(1f, 30f)));
SkridCost = config.Bind(skrid, "Eitr Cost", 10f, new ConfigDescription("Eitr spent per blink.", new AcceptableValueRange<float>(0f, 200f)));
SkridCooldown = config.Bind(skrid, "Cooldown", 3f, new ConfigDescription("Seconds between blinks.", new AcceptableValueRange<float>(0f, 120f)));
const string utsog = "Alfar - Utsog";
UtsogPercent = config.Bind(utsog, "Return Percent", 15f, new ConfigDescription("Percent of the damage you deal that comes back as eitr.", new AcceptableValueRange<float>(0f, 100f)));
const string kall = "Alfar - Kall";
KallRadius = config.Bind(kall, "Radius", 15f, new ConfigDescription("Metres around you whose dropped items are pulled in.", new AcceptableValueRange<float>(1f, 60f)));
KallSpeed = config.Bind(kall, "Pull Speed", 12f, new ConfigDescription("Speed items fly toward you, in metres per second.", new AcceptableValueRange<float>(1f, 40f)));
KallCost = config.Bind(kall, "Eitr Cost", 5f, new ConfigDescription("Eitr spent per pull.", new AcceptableValueRange<float>(0f, 200f)));
KallCooldown = config.Bind(kall, "Cooldown", 2f, new ConfigDescription("Seconds between pulls.", new AcceptableValueRange<float>(0f, 120f)));
const string storm = "Alfar - Ljosstorm";
StormRange = config.Bind(storm, "Range", 30f, new ConfigDescription("How far you can place the storm.", new AcceptableValueRange<float>(5f, 80f)));
StormRadius = config.Bind(storm, "Radius", 6f, new ConfigDescription("Radius of the storm in metres.", new AcceptableValueRange<float>(1f, 30f)));
StormSeconds = config.Bind(storm, "Duration", 6f, new ConfigDescription("Seconds the storm lasts.", new AcceptableValueRange<float>(1f, 60f)));
StormDps = config.Bind(storm, "Damage Per Second", 20f, new ConfigDescription("Lightning damage per second to each enemy inside.", new AcceptableValueRange<float>(1f, 500f)));
StormCost = config.Bind(storm, "Eitr Cost", 40f, new ConfigDescription("Eitr spent per cast.", new AcceptableValueRange<float>(0f, 400f)));
StormCooldown = config.Bind(storm, "Cooldown", 20f, new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 300f)));
const string beam = "Alfar - Geisli";
BeamRange = config.Bind(beam, "Range", 30f, new ConfigDescription("Beam length in metres.", new AcceptableValueRange<float>(5f, 80f)));
BeamDps = config.Bind(beam, "Damage Per Second", 35f, new ConfigDescription("Lightning damage per second to the target.", new AcceptableValueRange<float>(1f, 500f)));
BeamCostPerSecond = config.Bind(beam, "Eitr Per Second", 8f, new ConfigDescription("Eitr burned each second the beam is held.", new AcceptableValueRange<float>(0f, 100f)));
BeamMaxSeconds = config.Bind(beam, "Max Continuous Seconds", 8f, new ConfigDescription("The beam cuts off after this long.", new AcceptableValueRange<float>(1f, 60f)));
BeamCooldown = config.Bind(beam, "Cooldown After Release", 2f, new ConfigDescription("Seconds before the beam can start again.", new AcceptableValueRange<float>(0f, 60f)));
const string stasis = "Alfar - Kyrr";
StasisRange = config.Bind(stasis, "Range", 25f, new ConfigDescription("How far the stasis reaches.", new AcceptableValueRange<float>(5f, 80f)));
StasisSeconds = config.Bind(stasis, "Seconds", 4f, new ConfigDescription("How long an ordinary enemy is held.", new AcceptableValueRange<float>(0.5f, 30f)));
StasisBossSeconds = config.Bind(stasis, "Boss Seconds", 1.5f, new ConfigDescription("How long a boss is held.", new AcceptableValueRange<float>(0.5f, 30f)));
StasisCost = config.Bind(stasis, "Eitr Cost", 50f, new ConfigDescription("Eitr spent per cast.", new AcceptableValueRange<float>(0f, 400f)));
StasisCooldown = config.Bind(stasis, "Cooldown", 45f, new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 600f)));
const string archon = "Alfar - Sameining";
ArchonThreshold = config.Bind(archon, "Activation Threshold", 0.75f, new ConfigDescription("Fraction of the maximum eitr needed to begin. All of it is spent.", new AcceptableValueRange<float>(0f, 1f)));
ArchonSeconds = config.Bind(archon, "Duration", 180f, new ConfigDescription("Seconds the form lasts at most.", new AcceptableValueRange<float>(5f, 900f)));
ArchonScale = config.Bind(archon, "Scale", 1.5f, new ConfigDescription("Body size multiplier in the form.", new AcceptableValueRange<float>(1f, 3f)));
ArchonSpeedBonus = config.Bind(archon, "Speed Bonus", 0.2f, new ConfigDescription("Movement speed bonus in the form (0.2 = +20%).", new AcceptableValueRange<float>(0f, 1f)));
ArchonPoolPerEitr = config.Bind(archon, "Pool Per Eitr", 3f, new ConfigDescription("Points of protection per point of eitr spent to enter.", new AcceptableValueRange<float>(0.1f, 20f)));
ArchonPulseRadius = config.Bind(archon, "Pulse Radius", 4f, new ConfigDescription("Radius of the psionic pulse around you.", new AcceptableValueRange<float>(1f, 20f)));
ArchonPulseDamage = config.Bind(archon, "Pulse Damage", 60f, new ConfigDescription("Lightning damage of each pulse.", new AcceptableValueRange<float>(1f, 1000f)));
ArchonPulseInterval = config.Bind(archon, "Pulse Interval", 1f, new ConfigDescription("Seconds between pulses.", new AcceptableValueRange<float>(0.2f, 10f)));
ArchonFreePowerCooldown = config.Bind(archon, "Free Power Cooldown", 5f, new ConfigDescription("In the form, Ljosstorm and Geisli cost no eitr but wait this long.", new AcceptableValueRange<float>(0f, 60f)));
ArchonColor = config.Bind(archon, "Glow Color", new Color(0.55f, 0.85f, 1f, 1f), new ConfigDescription("Skin and light colour while in the form."));
const string graf = "Alfar - Grafvaettir";
GrafRange = config.Bind(graf, "Throw Range", 25f, new ConfigDescription("How far the drones can be thrown.", new AcceptableValueRange<float>(5f, 80f)));
GrafRadius = config.Bind(graf, "Dig Radius", 12f, new ConfigDescription("Radius around the landing point where they dig.", new AcceptableValueRange<float>(2f, 60f)));
GrafSeconds = config.Bind(graf, "Duration", 120f, new ConfigDescription("Seconds the drones dig before vanishing.", new AcceptableValueRange<float>(5f, 900f)));
GrafCount = config.Bind(graf, "Drones Per Throw", 5, new ConfigDescription("How many mining drones one throw makes.", new AcceptableValueRange<int>(1, 30)));
GrafEitr = config.Bind(graf, "Eitr Cost", 25f, new ConfigDescription("Eitr spent per throw.", new AcceptableValueRange<float>(0f, 400f)));
GrafStone = config.Bind(graf, "Stone Cost", 10, new ConfigDescription("Stone spent per throw.", new AcceptableValueRange<int>(0, 200)));
GrafFlint = config.Bind(graf, "Flint Cost", 5, new ConfigDescription("Flint spent per throw.", new AcceptableValueRange<int>(0, 200)));
GrafCooldown = config.Bind(graf, "Cooldown", 300f, new ConfigDescription("Seconds between throws; keep it well above the duration or they are permanent.", new AcceptableValueRange<float>(0f, 3600f)));
const string lev = "Alfar - Levitation";
LevitationRise = config.Bind(lev, "Rise Speed", 2f, new ConfigDescription("Climb speed (m/s) while the jump key is held in the air.", new AcceptableValueRange<float>(0.2f, 10f)));
LevitationCostPerSecond = config.Bind(lev, "Eitr Per Second", 2f, new ConfigDescription("Eitr burned each second of levitation.", new AcceptableValueRange<float>(0f, 50f)));
}
}
}

View file

@ -0,0 +1,687 @@
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar's powers (Alfar_Progettazione.txt sec. 13): caster tools, one per boss from Eikthyr.
///
/// Skrid Eikthyr blink
/// Grafvaettir Eikthyr mining drones thrown like a grenade (AlfarMiners)
/// Utsog Elder damage dealt returns as eitr (passive, below)
/// Kall Bonemass telekinesis
/// Ljosstorm Moder psionic storm on the ground
/// Geisli Yagluth continuous beam (hold the key)
/// Kyrr Queen stasis
/// Sameining Fader the archon (AlfarArchon)
///
/// Every power costs eitr from the SAME pool as the shield, which is the whole tension of the race
/// (doc sec. 4.4). Eitr is spent through AlfarEitr.Spend so the vanilla regeneration delay arms.
/// </summary>
public static class AlfarPowers
{
private static readonly Dictionary<string, float> cooldownUntil = new Dictionary<string, float>();
public static void ResetCooldowns(Player player)
{
cooldownUntil.Clear();
StopBeam();
AlfarArchon.ForceClear(player);
foreach (string id in AlfarStatusEffects.TimerIds) AlfarStatusEffects.ClearTimer(id);
}
private static bool Ready(string id) => !cooldownUntil.TryGetValue(id, out float until) || Time.time >= until;
private static void StartCooldown(string id, float seconds)
{
cooldownUntil[id] = Time.time + seconds;
AlfarStatusEffects.ShowTimer(id, seconds);
}
private static bool Unlocked(int need) => BossProgressionManager.GetCurrentProgressionState() >= need;
/// <summary>
/// The eitr a power costs: nothing for Ljosstorm and Geisli inside the archon form.
/// </summary>
private static float CostOf(float cost, bool freeInArchon) =>
freeInArchon && AlfarArchon.Active ? 0f : cost;
private static float CooldownOf(float cooldown, bool freeInArchon) =>
freeInArchon && AlfarArchon.Active ? AlfarArchon.FreePowerCooldown : cooldown;
/// <summary>Pays for a power, or says so and returns false.</summary>
private static bool Pay(Player player, float cost)
{
if (cost <= 0f) return true;
if (player.GetEitr() < cost)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr"));
return false;
}
AlfarEitr.Spend(player, cost);
return true;
}
// ─── The loop ────────────────────────────────────────────────────────
/// <summary>Called every frame for the LOCAL Alfr, from the Player.Update postfix.</summary>
public static void Tick(Player player)
{
AlfarArchon.Tick(player);
AlfarHeimkall.SyncIcon(player);
AlfarMiners.Tick(player);
TickBeam(player);
if (!RaceInput.Allowed || player.IsDead()) return;
if (Unlocked(AlfarPowerConfig.SkridState) && AlfarPowerConfig.SkridKey.Value.IsDownIgnoringHeldKeys()) Skrid(player);
if (Unlocked(AlfarPowerConfig.GrafvaettirState) && AlfarPowerConfig.GrafvaettirKey.Value.IsDownIgnoringHeldKeys()) AlfarMiners.Throw(player);
if (Unlocked(AlfarPowerConfig.KallState) && AlfarPowerConfig.KallKey.Value.IsDownIgnoringHeldKeys()) Kall(player);
if (Unlocked(AlfarPowerConfig.LjosstormState) && AlfarPowerConfig.LjosstormKey.Value.IsDownIgnoringHeldKeys()) Ljosstorm(player);
if (Unlocked(AlfarPowerConfig.KyrrState) && AlfarPowerConfig.KyrrKey.Value.IsDownIgnoringHeldKeys()) Kyrr(player);
if (Unlocked(AlfarPowerConfig.SameiningState) && AlfarPowerConfig.SameiningKey.Value.IsDownIgnoringHeldKeys()) AlfarArchon.TryActivate(player);
}
// ─── Aim ─────────────────────────────────────────────────────────────
private static Transform AimTransform(Player player)
{
return GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
}
/// <summary>
/// What the crosshair is on: the first thing the ray hits that is not the Alfr, with the
/// character under it if there is one. Triggers are ignored. With nothing hit, the point is at
/// the end of the range.
/// </summary>
private static bool Aim(Player player, float range, out Vector3 point, out Character target)
{
Transform aim = AimTransform(player);
Vector3 origin = aim.position;
Vector3 direction = aim.forward;
target = null;
point = origin + direction * range;
RaycastHit[] hits = Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore);
System.Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
foreach (RaycastHit hit in hits)
{
if (hit.collider == null) continue;
if (hit.collider.GetComponentInParent<Player>() == player) continue;
point = hit.point;
target = hit.collider.GetComponentInParent<Character>();
return true;
}
return false;
}
private static bool IsHostile(Player player, Character other)
{
return other != null && other != player && !other.IsDead() && !other.IsTamed() &&
BaseAI.IsEnemy(player, other);
}
// ─── Damage ──────────────────────────────────────────────────────────
/// <summary>
/// One lightning strike on a character. Not blockable and not dodgeable: a power that can be
/// blocked is a weapon, and these are not.
/// </summary>
public static void Strike(Player attacker, Character target, float lightning, Vector3 point)
{
if (target == null || lightning <= 0f) return;
HitData hit = new HitData();
hit.m_damage.m_lightning = lightning;
hit.m_point = point;
hit.m_dir = (target.transform.position - attacker.transform.position).normalized;
hit.m_dodgeable = false;
hit.m_blockable = false;
hit.m_hitType = HitData.HitType.PlayerHit;
hit.SetAttacker(attacker);
target.Damage(hit);
}
/// <summary>A pulse of lightning on every hostile creature within a radius of the Alfr.</summary>
/// <returns>True if it struck at least one creature.</returns>
public static bool Pulse(Player player, float radius, float damage)
{
bool struck = false;
foreach (Character character in CharactersIn(player.transform.position, radius))
{
if (!IsHostile(player, character)) continue;
Strike(player, character, damage, character.GetCenterPoint());
struck = true;
}
return struck;
}
private static IEnumerable<Character> CharactersIn(Vector3 center, float radius)
{
var seen = new HashSet<Character>();
foreach (Collider collider in Physics.OverlapSphere(center, radius, ~0, QueryTriggerInteraction.Ignore))
{
Character character = collider.GetComponentInParent<Character>();
if (character != null && seen.Add(character)) yield return character;
}
}
// ─── Skrid: blink ────────────────────────────────────────────────────
private static void Skrid(Player player)
{
if (!Ready("skrid")) return;
Transform aim = AimTransform(player);
Vector3 origin = player.transform.position + Vector3.up * 1.0f;
Vector3 direction = aim.forward;
float distance = AlfarPowerConfig.SkridDistance.Value;
// Stop short of whatever is in the way, so the blink never ends inside a wall.
Vector3 destination = origin + direction * distance;
if (NearestHit(player, origin, direction, distance, out RaycastHit wall))
{
destination = wall.point - direction * 0.6f;
}
// Back down to the player's own height: the origin was at the chest. The floor is found
// with a short ray down from the landing point, never with GetSolidHeight: that one casts
// from 1000 m up, so under any roof (a crypt, a cave, a house) it returned the roof and
// put the Alfr on top of it. A flat 1 m drop also sank the feet under the floor when the
// blink was aimed at it.
const float FloorSearch = 3f;
if (NearestHit(player, destination, Vector3.down, FloorSearch, out RaycastHit floor))
{
destination.y = floor.point.y + 0.05f;
}
else if (player.InInterior())
{
// No floor under the landing point inside a dungeon: it would end in the void the
// dungeon floats in. Cancel before paying.
return;
}
else
{
destination.y -= 1.0f;
if (ZoneSystem.instance != null)
{
// Terrain only, so a roof overhead is never mistaken for the ground.
float ground = ZoneSystem.instance.GetGroundHeight(destination);
if (destination.y < ground) destination.y = ground + 0.1f;
}
}
if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
Teleport(player, destination);
StartCooldown("skrid", AlfarPowerConfig.SkridCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", origin);
}
/// <summary>The nearest solid hit along a ray, skipping the caster's own colliders.</summary>
private static bool NearestHit(Player player, Vector3 origin, Vector3 direction, float distance, out RaycastHit nearest)
{
nearest = default;
bool found = false;
foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore))
{
if (hit.collider.GetComponentInParent<Player>() == player) continue;
if (!found || hit.distance < nearest.distance)
{
nearest = hit;
found = true;
}
}
return found;
}
/// <summary>
/// Moves the body without the teleport fade: the rigidbody is repositioned and its velocity
/// zeroed, and the fall tracker is reset so a blink up a cliff does not count as a fall.
/// </summary>
private static void Teleport(Player player, Vector3 destination)
{
Rigidbody body = Traverse.Create(player).Field("m_body").GetValue<Rigidbody>();
player.transform.position = destination;
if (body != null)
{
body.position = destination;
body.linearVelocity = Vector3.zero;
}
Traverse.Create(player).Field("m_maxAirAltitude").SetValue(destination.y);
}
// ─── Utsog: damage dealt returns as eitr ─────────────────────────────
/// <summary>
/// After a blow lands on something that is not a player: if the local Alfr struck it, a share
/// of the damage comes back as eitr. Runs only where the victim is owned, which is here for
/// anything this client owns (singleplayer and the host in practice): a monster owned by
/// another client feeds no eitr. Known limit, doc sec. 17.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Utsog_Patch
{
public static void Postfix(Character __instance, HitData __0)
{
if (__instance == null || __0 == null || __instance is Player) return;
Player local = Player.m_localPlayer;
if (local == null || __0.GetAttacker() != local) return;
if (!AlfarVisuals.IsAlfarPlayer(local) || !Unlocked(AlfarPowerConfig.UtsogState)) return;
if (__instance.IsTamed()) return;
float returned = __0.GetTotalDamage() * AlfarPowerConfig.UtsogPercent.Value / 100f;
if (returned > 0f) local.AddEitr(returned);
}
}
// ─── Kall: telekinesis ───────────────────────────────────────────────
private static void Kall(Player player)
{
if (!Ready("kall")) return;
if (!Pay(player, AlfarPowerConfig.KallCost.Value)) return;
Vector3 target = player.GetCenterPoint();
int pulled = 0;
var seen = new HashSet<ItemDrop>();
foreach (Collider collider in Physics.OverlapSphere(player.transform.position, AlfarPowerConfig.KallRadius.Value,
~0, QueryTriggerInteraction.Ignore))
{
ItemDrop item = collider.GetComponentInParent<ItemDrop>();
if (item == null || !seen.Add(item)) continue;
Rigidbody body = item.GetComponent<Rigidbody>();
ZNetView nview = item.GetComponent<ZNetView>();
if (body == null || nview == null || !nview.IsValid()) continue;
// The item's physics belong to whoever owns it; take it so the pull is not undone.
nview.ClaimOwnership();
Vector3 direction = (target - item.transform.position).normalized;
body.WakeUp();
body.linearVelocity = direction * AlfarPowerConfig.KallSpeed.Value;
pulled++;
}
StartCooldown("kall", AlfarPowerConfig.KallCooldown.Value);
Jotunn.Logger.LogInfo($"[Alfar] Kall pulled {pulled} item(s).");
}
// ─── Ljosstorm: the psionic storm ────────────────────────────────────
private static void Ljosstorm(Player player)
{
if (!Ready("storm")) return;
float cost = CostOf(AlfarPowerConfig.StormCost.Value, true);
if (!Pay(player, cost)) return;
Aim(player, AlfarPowerConfig.StormRange.Value, out Vector3 point, out Character _);
GameObject storm = new GameObject("AlfarStorm");
storm.transform.position = point;
AlfarStormZone zone = storm.AddComponent<AlfarStormZone>();
zone.Owner = player;
zone.Radius = AlfarPowerConfig.StormRadius.Value;
zone.Seconds = AlfarPowerConfig.StormSeconds.Value;
zone.DamagePerSecond = AlfarPowerConfig.StormDps.Value;
StartCooldown("storm", CooldownOf(AlfarPowerConfig.StormCooldown.Value, true));
}
// ─── Geisli: the beam ────────────────────────────────────────────────
/// <summary>
/// The pad's way to hold the beam. Every pad button is taken in vanilla's Classic layout, so,
/// like Skadi's Cold Spell, the beam borrows the secondary attack: bare-handed, or in the
/// archon form, which has no weapons anyway. The radial entry only gives a single press,
/// which cannot hold a beam.
/// </summary>
private static bool PadBeamHeld(Player player) =>
!RaceInput.RadialOpen && RaceInput.PadAttackHeld(2) &&
(AlfarArchon.Active || RaceInput.EmptyHanded(player));
/// <summary>
/// Swallows the unarmed secondary (the kick) while the pad's secondary attack is the beam,
/// the same way SkadiAttackPatch does for the Cold Spell.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Alfar_GeisliPadKick_Patch
{
public static bool Prefix(Humanoid __instance, bool secondaryAttack, ref bool __result)
{
if (!secondaryAttack || __instance != Player.m_localPlayer) return true;
Player player = (Player)__instance;
if (!AlfarVisuals.IsAlfarPlayer(player) || !Unlocked(AlfarPowerConfig.GeisliState)) return true;
if (!PadBeamHeld(player)) return true;
__result = false;
return false;
}
}
private static LineRenderer beamLine;
private static readonly List<LineRenderer> beamArcs = new List<LineRenderer>();
private static GameObject beamFx;
private static bool beamOn;
private static float beamStarted;
private static float beamNextTick;
private static float beamNextAnim;
private static float beamNextArcs;
/// <summary>
/// The beam leaves the RIGHT HAND, raised with the palm open: the borrowed "gpower" gesture (the
/// arms-raised cast the other races use too, with the real Guardian Power swallowed for a moment),
/// repeated while the key is held so the arm stays up. A quiet electric hum comes from the
/// vanilla lightning staff's charge effect hung on the hand, turned down, and a few jagged arcs
/// flicker round the line.
/// </summary>
private static void TickBeam(Player player)
{
bool wanted = RaceInput.Allowed && !player.IsDead() && Unlocked(AlfarPowerConfig.GeisliState) &&
(AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys() || PadBeamHeld(player));
if (!wanted)
{
if (beamOn) StopBeam(startCooldown: true);
return;
}
if (!beamOn)
{
if (!Ready("beam")) return;
if (player.GetEitr() <= 0f && !AlfarArchon.Active) { Pay(player, 1f); return; }
beamOn = true;
beamStarted = Time.time;
beamNextTick = Time.time;
beamNextAnim = 0f;
StartBeamFx(player);
}
if (Time.time - beamStarted > AlfarPowerConfig.BeamMaxSeconds.Value) { StopBeam(startCooldown: true); return; }
if (Time.time >= beamNextAnim)
{
beamNextAnim = Time.time + 1.6f;
RaiseHand(player);
}
Transform aim = AimTransform(player);
Transform hand = AlfarVisuals.RightHand(player);
Vector3 start = hand != null ? hand.position : player.GetEyePoint() + Vector3.down * 0.35f + aim.forward * 0.5f;
Aim(player, AlfarPowerConfig.BeamRange.Value, out Vector3 end, out Character target);
DrawBeam(start, end);
if (Time.time < beamNextTick) return;
const float tick = 0.2f;
beamNextTick = Time.time + tick;
float cost = CostOf(AlfarPowerConfig.BeamCostPerSecond.Value * tick, true);
if (cost > 0f)
{
if (player.GetEitr() < cost) { StopBeam(startCooldown: true); return; }
AlfarEitr.Spend(player, cost);
}
if (IsHostile(player, target))
{
Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end);
FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick); // a full hit per second on target
}
}
private static void RaiseHand(Player player)
{
ZSyncAnimation animation = player.GetComponent<ZSyncAnimation>();
if (animation == null) return;
RaceInput.SuppressGuardianPowerBriefly(3f);
animation.SetTrigger("gpower");
}
private static void StartBeamFx(Player player)
{
Transform hand = AlfarVisuals.RightHand(player);
if (hand == null || ZNetScene.instance == null) return;
GameObject prefab = ZNetScene.instance.GetPrefab("fx_lightningstaff_charge");
if (prefab == null) return;
beamFx = Object.Instantiate(prefab, hand.position, hand.rotation, hand);
// Not too loud: a hum, not a thunderclap.
foreach (AudioSource source in beamFx.GetComponentsInChildren<AudioSource>(true))
{
source.volume *= 0.35f;
}
}
private static LineRenderer NewLine(string name, float width)
{
GameObject go = new GameObject(name);
LineRenderer line = go.AddComponent<LineRenderer>();
line.material = new Material(Shader.Find("Sprites/Default"));
line.startWidth = width;
line.endWidth = width * 0.5f;
line.useWorldSpace = true;
return line;
}
private static void DrawBeam(Vector3 start, Vector3 end)
{
Color color = AlfarPowerConfig.ArchonColor.Value;
if (beamLine == null)
{
beamLine = NewLine("AlfarBeam", 0.12f);
beamLine.positionCount = 2;
}
beamLine.startColor = color;
beamLine.endColor = new Color(color.r, color.g, color.b, 0.4f);
beamLine.SetPosition(0, start);
beamLine.SetPosition(1, end);
// A few jagged arcs round the line, redrawn about twenty times a second.
if (beamArcs.Count == 0)
{
for (int i = 0; i < 3; i++)
{
LineRenderer arc = NewLine("AlfarBeamArc" + i, 0.04f);
arc.positionCount = 9;
beamArcs.Add(arc);
}
}
if (Time.time >= beamNextArcs)
{
beamNextArcs = Time.time + 0.05f;
Vector3 direction = end - start;
foreach (LineRenderer arc in beamArcs)
{
arc.startColor = new Color(1f, 1f, 1f, 0.9f);
arc.endColor = new Color(color.r, color.g, color.b, 0.2f);
for (int i = 0; i < arc.positionCount; i++)
{
float t = i / (float)(arc.positionCount - 1);
Vector3 point = start + direction * t;
if (i > 0 && i < arc.positionCount - 1) point += Random.insideUnitSphere * 0.35f;
arc.SetPosition(i, point);
}
}
}
}
private static void StopBeam(bool startCooldown = false)
{
if (beamLine != null) { Object.Destroy(beamLine.gameObject); beamLine = null; }
foreach (LineRenderer arc in beamArcs) if (arc != null) Object.Destroy(arc.gameObject);
beamArcs.Clear();
if (beamFx != null) { Object.Destroy(beamFx); beamFx = null; }
if (beamOn && startCooldown) StartCooldown("beam", CooldownOf(AlfarPowerConfig.BeamCooldown.Value, true));
beamOn = false;
}
// ─── Kyrr: stasis ────────────────────────────────────────────────────
private static void Kyrr(Player player)
{
if (!Ready("kyrr")) return;
Transform aim = AimTransform(player);
Character best = null;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.SphereCastAll(aim.position, 0.8f, aim.forward,
AlfarPowerConfig.StasisRange.Value, ~0, QueryTriggerInteraction.Ignore))
{
Character character = hit.collider.GetComponentInParent<Character>();
if (!IsHostile(player, character) || hit.distance >= bestDistance) continue;
best = character;
bestDistance = hit.distance;
}
if (best == null) return;
if (!Pay(player, AlfarPowerConfig.StasisCost.Value)) return;
float seconds = best.IsBoss() ? AlfarPowerConfig.StasisBossSeconds.Value : AlfarPowerConfig.StasisSeconds.Value;
AlfarStasis.Apply(best, seconds);
StartCooldown("kyrr", AlfarPowerConfig.StasisCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", best.GetCenterPoint());
}
}
/// <summary>A storm on the ground that strikes every hostile creature inside it, twice a second.</summary>
public class AlfarStormZone : MonoBehaviour
{
public Player Owner;
public float Radius;
public float Seconds;
public float DamagePerSecond;
private float born;
private float nextTick;
private Light glow;
private void Start()
{
born = Time.time;
glow = gameObject.AddComponent<Light>();
glow.color = AlfarPowerConfig.ArchonColor.Value;
glow.range = Radius * 1.5f;
glow.intensity = 2f;
}
private void Update()
{
if (Owner == null || Time.time - born >= Seconds) { Destroy(gameObject); return; }
if (Time.time < nextTick) return;
const float tick = 0.5f;
nextTick = Time.time + tick;
bool struck = false;
foreach (Collider collider in Physics.OverlapSphere(transform.position, Radius, ~0, QueryTriggerInteraction.Ignore))
{
Character character = collider.GetComponentInParent<Character>();
if (character == null || character == Owner || character.IsDead() || character.IsTamed()) continue;
if (!BaseAI.IsEnemy(Owner, character)) continue;
AlfarPowers.Strike(Owner, character, DamagePerSecond * tick, character.GetCenterPoint());
struck = true;
}
// Once per tick, not per creature: a full hit per second the storm strikes something.
if (struck && Owner == Player.m_localPlayer) FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick);
Vector2 offset = Random.insideUnitCircle * Radius;
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", transform.position + new Vector3(offset.x, 0f, offset.y));
}
}
/// <summary>
/// Holds a creature still and untouchable for a few seconds (Kyrr). Frozen means the AI is off, the
/// animator stopped and the body locked; untouchable is the prefix at the bottom, which cancels
/// every blow on a creature that carries this. Everything is put back when it runs out.
/// </summary>
public class AlfarStasis : MonoBehaviour
{
private float until;
private Animator animator;
private float animatorSpeed;
private MonoBehaviour ai;
private Rigidbody body;
private RigidbodyConstraints constraints;
public static void Apply(Character target, float seconds)
{
AlfarStasis existing = target.GetComponent<AlfarStasis>();
if (existing != null) { existing.until = Time.time + seconds; return; }
ZNetView nview = target.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.ClaimOwnership();
AlfarStasis stasis = target.gameObject.AddComponent<AlfarStasis>();
stasis.until = Time.time + seconds;
}
private void Awake()
{
animator = GetComponentInChildren<Animator>();
if (animator != null) { animatorSpeed = animator.speed; animator.speed = 0f; }
ai = GetComponent<BaseAI>();
if (ai != null) ai.enabled = false;
body = GetComponent<Rigidbody>();
if (body != null)
{
constraints = body.constraints;
body.linearVelocity = Vector3.zero;
body.constraints = RigidbodyConstraints.FreezeAll;
}
}
private void Update()
{
if (Time.time >= until) Destroy(this);
}
private void OnDestroy()
{
if (animator != null) animator.speed = animatorSpeed;
if (ai != null) ai.enabled = true;
if (body != null) body.constraints = constraints;
}
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Stasis_Patch
{
public static void Prefix(Character __instance, HitData __0)
{
if (__0 != null && __instance != null && __instance.GetComponent<AlfarStasis>() != null)
{
__0.m_damage = default(HitData.DamageTypes);
}
}
}
}
/// <summary>Spawns a vanilla effect prefab by name, and says nothing if the name is not there.</summary>
public static class AlfarFx
{
public static void Spawn(string prefabName, Vector3 position)
{
if (ZNetScene.instance == null) return;
GameObject prefab = ZNetScene.instance.GetPrefab(prefabName);
if (prefab == null) return;
Object.Instantiate(prefab, position, Quaternion.identity);
}
}
}

View file

@ -0,0 +1,434 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar probe: reads the live prefabs the design leans on, because Mono.Cecil only shows
/// field NAMES and never the values baked into a prefab (Alfar_Progettazione.txt, sec. 16B V11).
///
/// Nothing here instantiates a prefab, so no AI or Awake logic runs. Everything goes to the
/// BepInEx log under an [AlfarProbe] prefix; the console only says it finished.
///
/// alfarprobe EVERYTHING: every default target, the lightning table, and who
/// references Softtissue and Crystal
/// alfarprobe <prefab> just that prefab (names are the manifest's, case sensitive)
/// alfarprobe lightning just the table of how every creature takes lightning damage
///
/// WHAT EACH TARGET ANSWERS, so the log can be read against the design rather than around it:
/// Deathsquito are the legs and stinger separate objects (they are meant to be removed),
/// where the buzz lives, which materials the eyes and wings use
/// Surtling whether it is particles and lights or textures (decides how to recolour it)
/// StoneGolem attacks, area attacks, hp: the numbers the construct copies
/// Abomination whether it is a Humanoid with item attacks, and its hp and damage
/// piece_Charred_Balista whether it is a Piece with WearNTear and a Turret, and what it
/// needs to be built (sec. 8.6: it may only be the ballista a camp spawns)
/// ancient_skull what it is (MineRock5, Destructible...) and what it drops (soft tissue?)
/// eitrrefinery its conversion list: what really turns sap into refined eitr
/// Beehive m_secPerUnit and m_maxHoney, which the crystal timer is defined from
/// Dverger staffs the projectile the Abomination's sphere will be cloned from
/// </summary>
public class AlfarProbeCommand : ConsoleCommand
{
public override string Name => "alfarprobe";
public override string Help =>
"[DEBUG] alfarprobe [prefab|lightning] - logs the live prefab data the Alfar design needs " +
"(hierarchy, components, drops, attacks, lightning resistances) to the BepInEx log.";
private static readonly string[] DefaultTargets =
{
"Deathsquito", "Deathsquito_sting",
"Surtling", "StoneGolem", "Abomination",
"piece_Charred_Balista", "ancient_skull", "giant_skull",
"eitrrefinery", "Beehive", "piece_beehive", "piece_sapcollector",
"giant_skull_frac", "rock4_forest_frac", "giant_brain", "giant_brain_frac",
"DvergerStaffFire_fireball_projectile", "DvergerStaffIce_projectile",
"Pickable_Mushroom_Magecap", "Pickable_Mushroom_JotunPuffs", "sapling_magecap",
};
// Components whose public fields are worth printing in full. Anything else is only listed by name.
private static readonly HashSet<string> Interesting = new HashSet<string>
{
"Character", "Humanoid", "MonsterAI", "BaseAI", "CharacterDrop", "Tameable",
"Piece", "WearNTear", "Turret", "ZNetView",
"Destructible", "MineRock5", "MineRock", "DropOnDestroyed", "Pickable", "Plant",
"Beehive", "Smelter", "CookingStation", "Fermenter", "Container",
"Projectile", "Aoe", "ItemDrop", "ZSyncAnimation", "CharacterAnimEvent",
};
// For these the private fields are printed as well, because the interesting data (default
// items, attack timings) is private. Only fields declared on the type itself, to skip noise.
private static readonly HashSet<string> WithPrivate = new HashSet<string>
{
"Humanoid", "MonsterAI", "BaseAI", "Character",
};
public override void Run(string[] args)
{
if (args.Length > 0 && args[0].ToLower() == "lightning")
{
DumpLightningTable();
Console.instance.Print("[AlfarProbe] lightning table written to the BepInEx log.");
return;
}
if (args.Length > 1 && args[0].ToLower() == "whodrops")
{
WhoDrops(args[1]);
Console.instance.Print($"[AlfarProbe] whodrops {args[1]} written to the BepInEx log.");
return;
}
string[] targets = args.Length > 0 ? args : DefaultTargets;
foreach (string name in targets)
{
DumpPrefab(name);
}
if (args.Length == 0)
{
// The no-argument form is the WHOLE probe in one go: every default prefab, the
// lightning table, and who references soft tissue and crystals (the two drops the
// design could not place from the prefabs alone).
DumpLightningTable();
WhoDrops("Softtissue");
WhoDrops("Crystal");
}
Console.instance.Print($"[AlfarProbe] done, {targets.Length} prefab(s). Read BepInEx/LogOutput.log.");
}
private static void Log(string line) => Jotunn.Logger.LogInfo("[AlfarProbe] " + line);
private static GameObject Find(string name)
{
GameObject found = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(name) : null;
if (found != null) return found;
return PrefabManager.Cache.GetPrefab<GameObject>(name);
}
// ─── One prefab ──────────────────────────────────────────────────────
private static void DumpPrefab(string name)
{
GameObject prefab = Find(name);
Log($"==================== {name} ====================");
if (prefab == null)
{
Log("NOT FOUND by ZNetScene or the prefab cache. Check the spelling against the manifest, " +
"and note an _res/ prefab may not be registered at all (Alfar doc sec. 8.6).");
return;
}
Log($"root '{prefab.name}' scale={prefab.transform.localScale}");
DumpHierarchy(prefab.transform, "", 0);
foreach (Component component in prefab.GetComponentsInChildren<Component>(true))
{
if (component == null) continue;
string typeName = component.GetType().Name;
if (!Interesting.Contains(typeName)) continue;
Log($"--- {typeName} on '{PathOf(component.transform, prefab.transform)}'");
DumpFields(component, WithPrivate.Contains(typeName));
}
DumpDefaultItems(prefab);
}
private static void DumpHierarchy(Transform node, string indent, int depth)
{
if (depth > 9) { Log($"{indent}... (deeper than 9 levels)"); return; }
var parts = new List<string>();
foreach (Component c in node.GetComponents<Component>())
{
if (c == null || c is Transform) continue;
parts.Add(c.GetType().Name);
}
string pos = node.localPosition == Vector3.zero ? "" : $" pos={node.localPosition}";
string scale = node.localScale == Vector3.one ? "" : $" scale={node.localScale}";
Log($"{indent}{node.name}{(node.gameObject.activeSelf ? "" : " [INACTIVE]")}{pos}{scale}" +
(parts.Count > 0 ? " <" + string.Join(", ", parts) + ">" : ""));
Renderer renderer = node.GetComponent<Renderer>();
if (renderer != null)
{
foreach (Material m in renderer.sharedMaterials)
{
if (m == null) continue;
Log($"{indent} material '{m.name}' shader='{(m.shader != null ? m.shader.name : "null")}'" +
$" color={(m.HasProperty("_Color") ? m.GetColor("_Color").ToString() : "-")}" +
$" emission={(m.HasProperty("_EmissionColor") ? m.GetColor("_EmissionColor").ToString() : "-")}");
}
}
foreach (Transform child in node)
{
DumpHierarchy(child, indent + " ", depth + 1);
}
}
// ─── Generic field reader ────────────────────────────────────────────
private static void DumpFields(object target, bool includePrivate)
{
Type type = target.GetType();
// The first probe printed only the fields DECLARED on Humanoid and MonsterAI and so never
// showed Character's (hp, faction, flying, damage modifiers) or BaseAI's. Walk up the
// chain and print the public fields of every base too, private ones only on the leaf.
for (Type level = type; level != null && level != typeof(MonoBehaviour) && level != typeof(Behaviour); level = level.BaseType)
{
bool leaf = level == type;
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly;
if (includePrivate && leaf) flags |= BindingFlags.NonPublic;
if (!leaf) Log($" -- inherited from {level.Name}");
DumpLevel(target, level, flags);
}
}
private static void DumpLevel(object target, Type type, BindingFlags flags)
{
foreach (FieldInfo field in type.GetFields(flags))
{
// Runtime state, not prefab data: nothing there to learn and lots of it.
if (field.FieldType == typeof(ZNetView) && field.IsPrivate) continue;
object value;
try { value = field.GetValue(target); }
catch (Exception) { continue; }
string text = Describe(value, 0);
if (text == null) continue;
Log($" {field.Name} = {text}");
}
}
/// <summary>
/// A short readable form of a field value, or null when it is not worth a line (null, empty,
/// zero). Objects are shown by name only: this is a probe, not a serialiser.
/// </summary>
private static string Describe(object value, int depth)
{
if (value == null) return null;
if (value is UnityEngine.Object unityObject)
{
return unityObject == null ? null : $"'{unityObject.name}' ({unityObject.GetType().Name})";
}
if (value is string s) return s.Length == 0 ? null : "'" + s + "'";
Type t = value.GetType();
if (t.IsEnum) return value.ToString();
if (t.IsPrimitive)
{
if (value is bool b) return b ? "true" : "false";
string number = value.ToString();
return number == "0" ? null : number;
}
if (value is Vector2 || value is Vector3 || value is Color || value is Quaternion || value is Vector4)
{
return value.ToString();
}
if (depth >= 2) return $"({t.Name})";
if (value is IList list)
{
if (list.Count == 0) return null;
var items = new List<string>();
foreach (object item in list.Cast<object>().Take(24))
{
string d = Describe(item, depth + 1);
if (d != null) items.Add(d);
}
return $"[{list.Count}] " + string.Join("; ", items);
}
// A plain struct or class: print the fields that carry something.
var inner = new List<string>();
foreach (FieldInfo f in t.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
object fv;
try { fv = f.GetValue(value); }
catch (Exception) { continue; }
string d = Describe(fv, depth + 1);
if (d != null) inner.Add($"{f.Name}={d}");
}
return inner.Count == 0 ? null : "{" + string.Join(", ", inner) + "}";
}
// ─── What a creature actually attacks with ───────────────────────────
private static void DumpDefaultItems(GameObject prefab)
{
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid == null) return;
Log("--- DEFAULT ITEMS (Humanoid.m_defaultItems / m_randomWeapon / m_unarmedWeapon)");
var items = new List<GameObject>();
AddAll(items, Read<GameObject[]>(humanoid, "m_defaultItems"));
AddAll(items, Read<GameObject[]>(humanoid, "m_randomWeapon"));
ItemDrop unarmed = Read<ItemDrop>(humanoid, "m_unarmedWeapon");
if (unarmed != null) items.Add(unarmed.gameObject);
// The StoneGolem carries its weapons in random SETS (Spike, Sledge), which the first probe
// never looked at: m_defaultItems was empty and it said "none".
IList sets = Read<IList>(humanoid, "m_randomSets");
if (sets != null)
{
foreach (object set in sets)
{
GameObject[] setItems = Read<GameObject[]>(set, "m_items");
AddAll(items, setItems);
}
}
if (items.Count == 0) { Log(" (none)"); return; }
foreach (GameObject item in items.Distinct())
{
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) continue;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
Log($" weapon '{item.name}' ({shared.m_name}) damages={shared.m_damages}");
LogAttack("primary", shared.m_attack);
LogAttack("secondary", shared.m_secondaryAttack);
}
}
private static void LogAttack(string label, Attack attack)
{
if (attack == null) return;
Log($" {label}: {Describe(attack, 0)}");
}
private static T Read<T>(object target, string field) where T : class
{
FieldInfo info = target.GetType().GetField(field,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return info != null ? info.GetValue(target) as T : null;
}
private static void AddAll(List<GameObject> into, GameObject[] source)
{
if (source == null) return;
foreach (GameObject go in source) if (go != null) into.Add(go);
}
private static string PathOf(Transform node, Transform root)
{
if (node == root) return node.name;
var names = new List<string>();
for (Transform t = node; t != null && t != root; t = t.parent) names.Add(t.name);
names.Reverse();
return root.name + "/" + string.Join("/", names);
}
// ─── Who drops an item ───────────────────────────────────────────────
/// <summary>
/// Finds every prefab with a component that REFERENCES the named item: a drop table, a pickable,
/// a destructible, a creature's loot. Written for soft tissue, which the design says comes from
/// the Mistlands ancient skulls while the skull prefab itself drops nothing (probe 1): the drop
/// has to be somewhere else, probably in the fragments the skull spawns when destroyed.
/// </summary>
private static void WhoDrops(string itemName)
{
Log($"==================== WHO REFERENCES '{itemName}' ====================");
if (ZNetScene.instance == null)
{
Log("ZNetScene is not up: load a world and run it again.");
return;
}
int hits = 0;
foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
{
if (prefab == null || prefab.name == itemName) continue;
foreach (Component component in prefab.GetComponentsInChildren<Component>(true))
{
if (component == null || component is Transform || component is ItemDrop) continue;
if (References(component, itemName, 0)) { Log($"{prefab.name} :: {component.GetType().Name} on '{component.name}'"); hits++; }
}
}
Log($"{hits} reference(s) to '{itemName}'.");
}
private static bool References(object value, string itemName, int depth)
{
if (value == null || depth > 3) return false;
foreach (FieldInfo field in value.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public))
{
object fieldValue;
try { fieldValue = field.GetValue(value); }
catch (Exception) { continue; }
if (fieldValue == null) continue;
if (fieldValue is UnityEngine.Object unityObject)
{
if (unityObject != null && unityObject.name == itemName) return true;
continue;
}
Type t = fieldValue.GetType();
if (t.IsPrimitive || t.IsEnum || fieldValue is string) continue;
if (fieldValue is IList list)
{
foreach (object item in list)
{
if (item is UnityEngine.Object o) { if (o != null && o.name == itemName) return true; }
else if (item != null && !item.GetType().IsPrimitive && References(item, itemName, depth + 1)) return true;
}
}
else if (!t.IsAbstract && t.Namespace == null && References(fieldValue, itemName, depth + 1))
{
return true;
}
}
return false;
}
// ─── How every creature takes lightning ──────────────────────────────
/// <summary>
/// The constructs deal lightning, so a creature that resists or is immune to it resists the
/// constructs (Alfar doc sec. 17.13). This is the table to read before pricing them.
/// </summary>
private static void DumpLightningTable()
{
Log("==================== LIGHTNING TABLE ====================");
if (ZNetScene.instance == null)
{
Log("ZNetScene is not up (you are in the menu): load a world and run `alfarprobe lightning`.");
return;
}
var rows = new List<string>();
foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
{
if (prefab == null) continue;
Character character = prefab.GetComponent<Character>();
if (character == null) continue;
rows.Add($"{prefab.name,-28} faction={character.m_faction,-12} hp={character.m_health,7:0} " +
$"boss={(character.m_boss ? "Y" : "n")} lightning={character.m_damageModifiers.m_lightning} " +
$"fire={character.m_damageModifiers.m_fire} spirit={character.m_damageModifiers.m_spirit}");
}
rows.Sort(StringComparer.Ordinal);
foreach (string row in rows) Log(row);
Log($"{rows.Count} creatures. Anything not 'Normal' under lightning is resistant, weak or immune.");
}
}
}

View file

@ -0,0 +1,40 @@
namespace RacesOfValheim
{
/// <summary>
/// The Alfar: light-bodied casters whose one resource is eitr (Alfar_Progettazione.txt).
///
/// Only the race check lives here for now. The shield, the death timer, the powers and the
/// Nexus each get their own file as they are written; the look is AlfarVisuals and its patches.
/// </summary>
public static class AlfarRace
{
/// <summary>
/// Everything the race registers with Jotunn. Called from RacesOfValheim.CreateAllModAssets,
/// which runs on PrefabManager.OnVanillaPrefabsAvailable: the one moment Jotunn takes new
/// status effects, items and prefabs into ObjectDB. Registered later, nothing can spawn.
/// </summary>
public static void CreateModAssets()
{
AlfarStatusEffects.Register();
AlfarDrones.Register();
AlfarConstructs.Register();
AlfarSigil.Register();
AlfarNexus.Register();
AlfarChests.Register();
AlfarLjosgard.Register();
AlfarTowers.Register();
}
/// <summary>
/// The local player's race, read from m_customData like every other race's IsXxx() (guide
/// 5.4: never from the body model index, which is not a race).
/// </summary>
public static bool IsLocalAlfar()
{
Player player = Player.m_localPlayer;
return player != null &&
player.m_customData.TryGetValue("Race", out string race) &&
race == AlfarConfig.RaceId;
}
}
}

View file

@ -0,0 +1,169 @@
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar's passive carrier. For now it holds only the FEATHER FALL: with eitr in the pool the
/// body is lowered instead of dropped.
///
/// Valheim already has the mechanism (the Feather Cape): SE_Stats.m_maxMaxFallSpeed makes
/// StatusEffect.ModifyWalkVelocity clamp the downward speed (verified in the IL, doc sec. 16B).
/// So the effect is an SE_Stats with that field switched on while there is eitr and off when
/// there is none - and a fall at eitr zero is a normal, fast, damaging fall.
///
/// The fall DAMAGE is a separate matter, handled by the shield prefix (AlfarEitr): a fall is free
/// while there is eitr. This effect is what makes it look like falling softly.
///
/// Rebuilt every tick for the same reason the Sverm's is: Setup runs once, at spawn, so anything
/// written there is frozen.
/// </summary>
public class SE_AlfarStats : SE_Stats
{
public const string EffectName = "SE_AlfarStats";
public override void Setup(Character character)
{
base.Setup(character);
name = EffectName;
m_name = "$rov_se_alfar_stats_name";
m_tooltip = "$rov_se_alfar_stats_tooltip";
Rebuild();
}
public override void UpdateStatusEffect(float dt)
{
base.UpdateStatusEffect(dt);
Rebuild();
}
private void Rebuild()
{
Player player = m_character as Player;
bool charged = player != null && player.GetEitr() > 0f;
// Written on the LIVE effect, not on the registered template: SEMan clones what it is
// given, so a template edited afterwards reaches nobody.
m_maxMaxFallSpeed = charged && AlfarConfig.SoftFall.Value ? AlfarConfig.FeatherFallSpeed.Value : 0f;
// The archon form is faster. SE_Stats.m_speedModifier is added to the body's speed factor.
m_speedModifier = AlfarArchon.Active ? AlfarPowerConfig.ArchonSpeedBonus.Value : 0f;
}
}
/// <summary>
/// A marker with a countdown: the HUD prints the remaining time of any effect that has a m_ttl, so
/// the cooldowns of the powers, the Heimkall wait and the archon form all show on screen without a
/// line of UI code (the Dvergar's cooldown icons do the same).
/// </summary>
public class SE_AlfarTimer : StatusEffect
{
}
public static class AlfarStatusEffects
{
public static readonly string[] TimerIds = { "skrid", "graf", "kall", "storm", "beam", "kyrr", "heimkall", "archon" };
public static string TimerName(string id) { return "SE_AlfarTimer_" + id; }
private static string TimerIcon(string id)
{
switch (id)
{
case "graf": return "TrophyDeathsquito";
case "kall": return "Thunderstone";
case "storm": return "OrbThunderBlood";
case "beam": return "Crystal";
case "kyrr": return "FreezeGland";
case "archon": return "TrophyFader";
default: return "Eitr";
}
}
/// <summary>Starts (or restarts) the on-screen countdown of a power, the Heimkall wait or the form.</summary>
public static void ShowTimer(string id, float seconds)
{
Player player = Player.m_localPlayer;
if (player == null || seconds <= 0f) return;
int hash = TimerName(id).GetStableHashCode();
SEMan seman = player.GetSEMan();
seman.RemoveStatusEffect(hash, true);
seman.AddStatusEffect(hash, true);
StatusEffect effect = seman.GetStatusEffect(hash);
if (effect != null) effect.m_ttl = seconds;
}
public static void ClearTimer(string id)
{
Player player = Player.m_localPlayer;
if (player != null) player.GetSEMan().RemoveStatusEffect(TimerName(id).GetStableHashCode(), true);
}
public static bool HasTimer(string id)
{
Player player = Player.m_localPlayer;
return player != null && player.GetSEMan().HaveStatusEffect(TimerName(id).GetStableHashCode());
}
public static void Register()
{
foreach (string id in TimerIds)
{
Sprite timerIcon = null;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(TimerIcon(id));
ItemDrop sourceDrop = source != null ? source.GetComponent<ItemDrop>() : null;
if (sourceDrop != null && sourceDrop.m_itemData != null && sourceDrop.m_itemData.m_shared != null &&
sourceDrop.m_itemData.m_shared.m_icons != null && sourceDrop.m_itemData.m_shared.m_icons.Length > 0)
{
timerIcon = sourceDrop.m_itemData.m_shared.m_icons[0];
}
var timer = ScriptableObject.CreateInstance<SE_AlfarTimer>();
timer.name = TimerName(id);
timer.m_name = "$rov_se_alfar_timer_" + id + "_name";
timer.m_icon = timerIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(timer, fixReference: false));
}
Sprite icon = null;
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>("Eitr");
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null &&
drop.m_itemData.m_shared.m_icons != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
icon = drop.m_itemData.m_shared.m_icons[0];
}
var stats = ScriptableObject.CreateInstance<SE_AlfarStats>();
stats.name = SE_AlfarStats.EffectName;
stats.m_name = "$rov_se_alfar_stats_name";
stats.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(stats, fixReference: false));
}
/// <summary>Adds the passive to a player that lacks it: status effects do not survive death or a reload.</summary>
public static void Ensure(Player player)
{
if (player == null) return;
int hash = SE_AlfarStats.EffectName.GetStableHashCode();
if (!player.GetSEMan().HaveStatusEffect(hash))
{
player.GetSEMan().AddStatusEffect(hash, true);
}
}
/// <summary>Takes the passive off a player who stopped being an Alfr.</summary>
public static void Remove(Player player)
{
if (player == null) return;
int hash = SE_AlfarStats.EffectName.GetStableHashCode();
if (player.GetSEMan().HaveStatusEffect(hash))
{
player.GetSEMan().RemoveStatusEffect(hash, true);
}
}
}
}

View file

@ -0,0 +1,239 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The PRISMAVARD, the Alfar's towers (Alfar_Progettazione.txt sec. 8.6): the charred ballista of the
/// Ashlands, smaller and bronze, turned around to defend. Read from the live prefab (doc 16C P5):
///
/// - it is NOT a Piece: it has Turret, WearNTear and DropOnDestroyed and nothing that lets the
/// hammer place it, so a Piece is added here;
/// - it is an ENEMY tower: it targets players and tamed creatures and not enemies, so the three
/// flags are turned round;
/// - m_maxAmmo is 0 and HasAmmo() is true when it is 0 (read in the IL): the vanilla tower has
/// infinite ammunition, so "consumes nothing" is free; what is changed is the AMMO, a bolt that
/// does lightning, so the shot is ours.
///
/// It only works inside a Ljoskjarne's radius (AlfarTower switches the Turret off outside it), has a
/// shield equal to its health that returns by itself, and is repaired with the hammer and by the
/// drones like any building.
/// </summary>
public static class AlfarTowers
{
public const string PieceName = "AlfarPrismavard";
public const string PieceDisplay = "$rov_piece_alfar_prismavard_name";
public const string AmmoName = "AlfarPrismBolt";
public const string ProjectileName = "AlfarPrismProjectile";
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_Charred_Balista");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No 'piece_Charred_Balista': the Prismavard is not registered.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source);
if (prefab == null) return;
Turret turret = prefab.GetComponent<Turret>();
if (turret == null)
{
Jotunn.Logger.LogWarning("[Alfar] The charred ballista has no Turret component: no Prismavard.");
return;
}
// Turned around: it defends the base against enemies and never at players or their tames.
turret.m_targetPlayers = false;
turret.m_targetTamed = false;
turret.m_targetEnemies = true;
turret.m_returnAmmoOnDestroy = false;
// The ammunition: a bolt that does lightning, shot from a projectile that spares friends
// and buildings. m_maxAmmo stays 0, which means infinite.
GameObject ammo = RegisterAmmo(turret);
if (ammo != null)
{
ItemDrop ammoDrop = ammo.GetComponent<ItemDrop>();
turret.m_defaultAmmo = ammoDrop;
if (turret.m_allowedAmmo != null && turret.m_allowedAmmo.Count > 0)
{
var allowed = turret.m_allowedAmmo[0];
allowed.m_ammo = ammoDrop;
turret.m_allowedAmmo[0] = allowed;
}
}
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null) wear.m_health *= AlfarNexusConfig.TowerHealthFactor.Value;
// The loot of an enemy ballista: a tower of ours must not be a way to farm it.
foreach (DropOnDestroyed drop in prefab.GetComponentsInChildren<DropOnDestroyed>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
prefab.transform.localScale = Vector3.one * AlfarNexusConfig.TowerScale.Value;
ZNetView nview = prefab.GetComponent<ZNetView>();
if (nview != null) nview.m_syncInitialScale = true;
AlfarConstructs.Tint(prefab, new Color(0.85f, 0.58f, 0.28f, 1f));
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = "tower";
AlfarPieceShield shield = prefab.AddComponent<AlfarPieceShield>();
shield.Max = wear != null ? wear.m_health : 100f;
shield.Shield = shield.Max;
prefab.AddComponent<AlfarTower>();
Sprite icon = AlfarNexus.BorrowIcon("Crystal") ?? AlfarNexus.BorrowIcon("Bronze");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplay;
piece.m_canBeRemoved = true;
piece.m_icon = icon;
piece.m_groundOnly = false;
piece.m_groundPiece = false;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplay,
Description = "$rov_piece_alfar_prismavard_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Misc,
Icon = icon,
Requirements = new[]
{
new RequirementConfig("Bronze", AlfarNexusConfig.TowerBronze.Value, 0, true),
new RequirementConfig("Crystal", AlfarNexusConfig.TowerCrystal.Value, 0, true),
},
}));
// No cap on how many (the user said so), but one rule: inside a Ljoskjarne's radius.
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (!AlfarRace.IsLocalAlfar())
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
}
if (AlfarNexusBehaviour.Covering(position) == null)
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_tower_needs_nexus"));
return false;
}
return true;
});
AlfarPieces.Extra.Add(PieceName);
}
private static GameObject RegisterAmmo(Turret turret)
{
ItemDrop original = turret.m_defaultAmmo;
if (original == null)
{
Jotunn.Logger.LogWarning("[Alfar] The ballista has no default ammo to copy.");
return null;
}
GameObject ammo = PrefabManager.Instance.CreateClonedPrefab(AmmoName, original.gameObject);
if (ammo == null) return null;
ItemDrop drop = ammo.GetComponent<ItemDrop>();
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_prismbolt_name";
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.TowerDamage.Value;
shared.m_damages = damage;
// The projectile it flies as: a copy that spares friends and buildings.
GameObject originalProjectile = shared.m_attack != null ? shared.m_attack.m_attackProjectile : null;
if (originalProjectile != null)
{
GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(ProjectileName, originalProjectile);
Projectile settings = projectile != null ? projectile.GetComponent<Projectile>() : null;
if (settings != null)
{
settings.m_hitFriendly = false;
settings.m_noDamageFriendly = true;
settings.m_aoeSkipWearNTear = true;
PrefabManager.Instance.AddPrefab(projectile);
shared.m_attack.m_attackProjectile = projectile;
}
}
ItemManager.Instance.AddItem(new CustomItem(ammo, fixReference: false));
return ammo;
}
}
/// <summary>The tower runs only while a Ljoskjarne's radius covers it: outside, the Turret is off.</summary>
public class AlfarTower : MonoBehaviour
{
private Turret turret;
private float nextCheck;
private void Awake() { turret = GetComponent<Turret>(); }
private void Update()
{
if (turret == null || Time.time < nextCheck) return;
nextCheck = Time.time + 2f;
bool powered = AlfarNexusBehaviour.Covering(transform.position) != null;
if (turret.enabled != powered) turret.enabled = powered;
}
}
/// <summary>
/// A building's shield: equal to its health, back at 1% a second after five quiet seconds. Its own
/// absorption on WearNTear.ApplyDamage, the stage every blow on a building ends in; the hammer and
/// the drones repair the HEALTH, the shield returns by itself.
/// </summary>
public class AlfarPieceShield : MonoBehaviour
{
public float Max;
public float Shield;
private float lastHit = -999f;
private void Update()
{
if (Shield >= Max || Time.time - lastHit < 5f) return;
Shield = Mathf.Min(Max, Shield + Max * 0.01f * Time.deltaTime);
}
public float Absorb(float damage)
{
if (damage <= 0f) return damage;
lastHit = Time.time;
float absorbed = Mathf.Min(Shield, damage);
Shield -= absorbed;
return damage - absorbed;
}
[HarmonyPatch(typeof(WearNTear), "ApplyDamage")]
public static class Alfar_PieceShield_Patch
{
public static void Prefix(WearNTear __instance, ref float __0)
{
AlfarPieceShield shield = __instance != null ? __instance.GetComponent<AlfarPieceShield>() : null;
if (shield != null) __0 = shield.Absorb(__0);
}
}
}
}

View file

@ -0,0 +1,525 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What an Alfr looks like (Alfar_Progettazione.txt sec. 7): ash-grey skin, five percent taller
/// and a little thinner than a Viking, no hair, no beard, and two completely black eyes.
///
/// Everything here is written the way the Sverm and the Dvergar already write theirs, because
/// each of those shapes cost somebody a test session:
/// - the race is read off the ZDO, so remote players render right, falling back to
/// m_customData for the menu preview (same shape as SvermVisuals.GetPlayerRace);
/// - the skin is written AFTER Valheim rebuilds the body material (see AlfarPatches);
/// - the scale goes on the "Visual" child and never the root, and only ever undoes its own;
/// - the eyes are spheres on the head bone with every offset divided by lossyScale, because
/// the player armature is authored at scale 100.
///
/// The eyes are the Sverm's spheres with the glow taken out: same geometry, a matte black
/// material, no emission at all.
/// </summary>
public static class AlfarVisuals
{
private const string EyesName = "AlfarEyes";
private const string HeadBoneName = "Head";
// ─── Race check ──────────────────────────────────────────────────────
public static string GetPlayerRace(Player player)
{
if (player == null) return "Human";
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race)) return race;
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
{
return custom;
}
return "Human";
}
public static bool IsAlfarPlayer(Player player) => GetPlayerRace(player) == AlfarConfig.RaceId;
// ─── Scale ───────────────────────────────────────────────────────────
/// <summary>
/// +5% in height and a little less wide. NON-uniform, so the scale is a Vector3 and not the
/// single float the other races write.
///
/// The reset only ever undoes a scale that looks like ours: another race (the Trol, the
/// Dvergar) may be sizing this player and RaceScale exists so the two do not fight.
/// </summary>
public static void ApplyScale(Player player, bool isAlfar)
{
if (player == null) return;
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
if (visual == null) return;
Vector3 ours = new Vector3(AlfarConfig.WidthScale.Value, AlfarConfig.HeightScale.Value, AlfarConfig.WidthScale.Value);
// The archon form is bigger: published in the ZDO, so every client sizes it the same.
Vector3 archon = ours * AlfarPowerConfig.ArchonScale.Value;
bool inArchon = isAlfar && AlfarArchon.IsArchon(player);
Vector3 current = visual.transform.localScale;
Vector3 target = inArchon ? archon : ours;
if (!isAlfar)
{
// Undo only a scale that is one of ours, the normal one or the archon's.
if (!LooksLike(current, ours) && !LooksLike(current, archon)) return;
target = Vector3.one;
}
if (!LooksLike(current, target))
{
visual.transform.localScale = target;
}
}
private static bool LooksLike(Vector3 a, Vector3 b)
{
return Mathf.Abs(a.x - b.x) < 0.001f && Mathf.Abs(a.y - b.y) < 0.001f && Mathf.Abs(a.z - b.z) < 0.001f;
}
// ─── Hair and beard ──────────────────────────────────────────────────
/// <summary>
/// Takes the hair and the beard off the VISUAL only. The Skeleton also rewrites the saved
/// profile, which makes the loss permanent; the Alfar do not, so a reset to Human gets the
/// hair back the next time the game rebuilds the equipment visuals.
///
/// Since Valheim 1.0 these take an item hash and not a name: 0 is the empty slot.
/// </summary>
public static void ApplyHairless(Player player)
{
if (player == null) return;
VisEquipment vis = player.GetComponent<VisEquipment>();
if (vis == null) return;
vis.SetHairItem(0);
vis.SetBeardItem(0);
}
// ─── Eyes ────────────────────────────────────────────────────────────
/// <summary>
/// Which way the skull faces, measured once when the eyes are built and kept for as long as
/// they exist (RigBindPose explains why it is read from the bind pose and not live).
/// </summary>
private class EyeFrame : MonoBehaviour
{
public Vector3 LocalForward = Vector3.forward;
public Vector3 LocalUp = Vector3.up;
public Vector3 LocalRight = Vector3.right;
}
private static Shader cachedShader;
private static bool shaderResolved;
public static void ApplyEyes(Player player)
{
if (player == null) return;
Transform headBone = FindBone(player, HeadBoneName);
if (headBone == null) return; // rig not up yet; try again next pass
Transform eyes = headBone.Find(EyesName);
if (!IsAlfarPlayer(player) || player.IsDead())
{
if (eyes != null)
{
// Renamed first: Destroy is deferred to the end of the frame, and every call
// until then would otherwise find it again.
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
}
return;
}
if (eyes == null)
{
// Sitting, attached, mid-attack or asleep the head can be turned away from the
// body's forward at the instant the frame is measured, which puts the eyes behind
// the skull. Wait for a neutral moment (the same guard as the Sverm's).
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
eyes = BuildEyes(player, headBone);
}
if (eyes == null) return;
PlaceEyes(player, eyes);
}
/// <summary>
/// A grey's eyes: wide black almonds, outer corners raised, wrapping round the sides of the
/// face. Each is a sphere squashed to an ellipsoid and turned in the skull's own frame.
///
/// FIXED HEAD-LOCAL UNITS, never headBone.lossyScale. The Alfar Visual is scaled
/// non-uniformly, so the head's lossyScale is only an approximation that changes as the
/// head turns; recomputed on the 0.5s cosmetic pass it made the eyes trail the face. The
/// face is skinned to the same bone through the same matrices, so a constant local offset
/// stays glued to it at any body scale, and PlaceEyes only has to run when the eyes change.
/// </summary>
private static void PlaceEyes(Player player, Transform holder)
{
EyeFrame frame = holder.GetComponent<EyeFrame>();
if (frame == null) return;
const float toLocal = PlayerFace.MetresToHeadLocal;
float height = AlfarConfig.EyeHeight;
float separation = AlfarConfig.EyeSeparation;
float size = AlfarConfig.EyeSizeMultiplier.Value;
PlayerFace.AdjustEyes(player, ref height, ref separation, ref size);
Quaternion facing = Quaternion.LookRotation(frame.LocalForward, frame.LocalUp);
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
// Index 0 is offset against the right axis, so it is the model's left eye. The
// slant and the wrap are mirrored so both outer corners go up and back.
float side = i == 0 ? -1f : 1f;
// This eye's hand corrections (RaceEyeTuning).
float forward = AlfarConfig.EyeForward;
float eyeHeight = height;
float eyeSeparation = separation;
float eyeSize = size;
float wrap = AlfarConfig.EyeWrap;
float slant = AlfarConfig.EyeSlant;
float tilt = 0f;
RaceEyeTuning.Eye tuning = RaceEyeTuning.For(AlfarConfig.RaceId, player, side);
if (tuning != null)
{
forward += tuning.Forward;
eyeHeight += tuning.Height;
eyeSeparation += tuning.Separation;
eyeSize *= tuning.Size;
tilt = tuning.RotX;
wrap += tuning.RotY;
slant += tuning.RotZ;
}
Vector3 offset = frame.LocalForward * forward + frame.LocalUp * eyeHeight
+ frame.LocalRight * (side * eyeSeparation);
eye.localPosition = offset * toLocal;
eye.localRotation = facing * Quaternion.Euler(tilt, wrap * side, slant * side);
eye.localScale = AlfarConfig.EyeExtent * (eyeSize * toLocal);
}
}
private static Transform BuildEyes(Player player, Transform headBone)
{
Shader shader = ResolveShader(player);
if (shader == null) return null;
GameObject holder = new GameObject(EyesName);
holder.transform.SetParent(headBone, false);
holder.transform.localPosition = Vector3.zero;
holder.transform.localRotation = Quaternion.identity;
holder.transform.localScale = Vector3.one;
EyeFrame frame = holder.AddComponent<EyeFrame>();
RigBindPose.MeasureHeadFrame(player, headBone, "Alfar",
out frame.LocalForward, out frame.LocalUp, out frame.LocalRight);
for (int i = 0; i < 2; i++)
{
// Spheres, not quads: a quad seen edge-on is a line and vanishes.
GameObject eye = GameObject.CreatePrimitive(PrimitiveType.Sphere);
eye.name = "Eye" + i;
foreach (Collider collider in eye.GetComponents<Collider>())
{
Object.Destroy(collider);
}
eye.transform.SetParent(holder.transform, false);
eye.transform.localPosition = Vector3.zero;
eye.transform.localRotation = Quaternion.identity;
eye.transform.localScale = Vector3.zero; // PlaceEyes runs immediately after this
Renderer renderer = eye.GetComponent<Renderer>();
renderer.material = BlackMaterial(shader);
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
}
return holder.transform;
}
/// <summary>
/// Black with a wet sheen: no emission, but smooth enough to catch a highlight, which is
/// what makes a grey's eyes read as eyes and not as two holes punched in the face.
/// </summary>
private static Material BlackMaterial(Shader shader)
{
Material material = new Material(shader);
material.color = Color.black;
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
if (material.HasProperty("_Glossiness")) material.SetFloat("_Glossiness", 0.8f);
if (material.HasProperty("_Smoothness")) material.SetFloat("_Smoothness", 0.8f);
if (material.HasProperty("_Metallic")) material.SetFloat("_Metallic", 0f);
return material;
}
/// <summary>
/// Custom/Creature first, for the reason the Sverm's own resolver gives: Valheim dithers the
/// player away when the camera gets inside them, and only the game's own shaders know about
/// it, so eyes on an unlit shader would hang in the air while the face dissolved.
/// </summary>
private static Shader ResolveShader(Player player)
{
if (shaderResolved) return cachedShader;
// CUSTOM/CREATURE, found the one way that works in play. Two earlier attempts failed in
// opposite directions and both are on record in the log:
// 1. Shader.Find("Custom/Creature") returns null in the main-menu preview (Valheim's
// shaders are not all loaded by name until something has used them), so the code
// fell to Sprites/Default and CACHED it for the whole session;
// 2. taking the player's own body shader gave 'Custom/Player', the SKIN shader: it
// paints the skin texture, so the eyes came out white.
// So: ask Shader.Find, and failing that read the shader off a real creature's material
// (the Deathsquito's, the very prefab the drones are cloned from) once the world is up.
// A failure is never cached, and in the menu preview there are simply no eyes yet.
Shader shader = Shader.Find("Custom/Creature");
if (shader == null && ZNetScene.instance != null)
{
GameObject creature = ZNetScene.instance.GetPrefab("Deathsquito");
Renderer renderer = creature != null ? creature.GetComponentInChildren<Renderer>(true) : null;
if (renderer != null && renderer.sharedMaterial != null) shader = renderer.sharedMaterial.shader;
}
if (shader == null)
{
// The main-menu preview has no world and so no creature to read a shader from. Its eyes
// are only for show and are thrown away with the preview, so a plain unlit black will do
// there - and it is NOT cached, so the world gets the real one.
ZNetView preview = player != null ? player.GetComponent<ZNetView>() : null;
if (preview == null || !preview.IsValid()) return Shader.Find("Sprites/Default");
return null;
}
Jotunn.Logger.LogInfo($"[Alfar] Eye shader resolved to '{shader.name}'.");
shaderResolved = true;
cachedShader = shader;
return cachedShader;
}
// ─── Skin ────────────────────────────────────────────────────────────
/// <summary>Ash grey, or the glow colour while the archon form is up.</summary>
public static Color SkinFor(Player player)
{
return AlfarArchon.IsArchon(player) ? AlfarPowerConfig.ArchonColor.Value : AlfarConfig.SkinColor.Value;
}
private const string GlowName = "AlfarArchonGlow";
/// <summary>
/// A blue light on the body while the archon form is up, taken off when it is not. Every
/// client runs this for every Alfr in range, so the glow is seen by everyone.
/// </summary>
public static void ApplyArchonGlow(Player player)
{
if (player == null) return;
Transform existing = player.transform.Find(GlowName);
bool want = IsAlfarPlayer(player) && AlfarArchon.IsArchon(player) && !player.IsDead();
if (!want)
{
if (existing != null) Object.Destroy(existing.gameObject);
return;
}
if (existing == null)
{
GameObject holder = new GameObject(GlowName);
holder.transform.SetParent(player.transform, false);
holder.transform.localPosition = Vector3.up * 1.2f;
existing = holder.transform;
Light light = holder.AddComponent<Light>();
light.type = LightType.Point;
light.range = 9f;
light.intensity = 3f;
light.shadows = LightShadows.None;
}
Light glow = existing.GetComponent<Light>();
if (glow != null) glow.color = AlfarPowerConfig.ArchonColor.Value;
}
/// <summary>
/// The grey, for real. A tint on _SkinColor only MULTIPLIES the skin texture, and that texture is
/// pink: multiplied by a grey it comes out as a darker human skin, not as grey skin (the second
/// test: "the skin is the normal colour"). So the body's texture is replaced by a DESATURATED
/// copy, made once on the GPU and read back, and _SkinColor then only sets how light the grey is.
/// The original texture is remembered per material so a reset to human puts it back.
/// </summary>
private static readonly Dictionary<Texture, Texture2D> greyOf = new Dictionary<Texture, Texture2D>();
private static readonly Dictionary<Material, Texture> originalTexture = new Dictionary<Material, Texture>();
private static Texture2D Desaturated(Texture source)
{
Texture2D grey;
if (greyOf.TryGetValue(source, out grey) && grey != null) return grey;
RenderTexture target = RenderTexture.GetTemporary(source.width, source.height, 0,
RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
RenderTexture previous = RenderTexture.active;
try
{
Graphics.Blit(source, target);
RenderTexture.active = target;
grey = new Texture2D(source.width, source.height, TextureFormat.RGBA32, true);
grey.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0);
Color32[] pixels = grey.GetPixels32();
for (int i = 0; i < pixels.Length; i++)
{
Color32 c = pixels[i];
byte luma = (byte)(c.r * 0.299f + c.g * 0.587f + c.b * 0.114f);
pixels[i] = new Color32(luma, luma, luma, c.a);
}
grey.SetPixels32(pixels);
grey.Apply(true);
grey.name = source.name + "_AlfarGrey";
}
catch (System.Exception e)
{
Jotunn.Logger.LogWarning("[Alfar] Could not make the grey skin texture: " + e.Message);
grey = null;
}
finally
{
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(target);
}
if (grey != null) greyOf[source] = grey;
return grey;
}
/// <summary>
/// Puts the grey texture on every skin material of the body (or takes it off again). Runs from the
/// UpdateColors postfix, so it covers the main-menu preview and every client, and from the
/// cosmetic pass, so it survives anything that rebuilds the body.
/// </summary>
public static void ApplyGreyTexture(VisEquipment vis, bool on)
{
if (vis == null || vis.m_bodyModel == null) return;
foreach (Material material in vis.m_bodyModel.materials)
{
if (material == null || !material.HasProperty("_SkinColor") || !material.HasProperty("_MainTex")) continue;
Texture current = material.GetTexture("_MainTex");
if (on)
{
if (current == null) continue;
bool ours = false;
foreach (Texture2D grey in greyOf.Values) if (grey == current) { ours = true; break; }
if (ours) continue;
Texture2D desaturated = Desaturated(current);
if (desaturated == null) continue;
originalTexture[material] = current;
material.SetTexture("_MainTex", desaturated);
}
else
{
Texture original;
if (originalTexture.TryGetValue(material, out original) && original != null)
{
material.SetTexture("_MainTex", original);
}
originalTexture.Remove(material);
}
}
}
/// <summary>
/// Keeps the skin right for whoever it is: the grey and its tint for an Alfr, the original for
/// anyone who stopped being one. The tint is only written when it differs, and UpdateColors is
/// pushed only then, so it costs a colour compare.
/// </summary>
public static void SyncSkin(Player player, bool isAlfar)
{
if (player == null) return;
VisEquipment vis = player.GetComponent<VisEquipment>();
if (vis == null || vis.m_bodyModel == null) return;
if (!isAlfar)
{
if (originalTexture.Count > 0) ApplyGreyTexture(vis, false);
return;
}
ApplyGreyTexture(vis, true);
Material material = vis.m_bodyModel.material;
if (material == null || !material.HasProperty("_SkinColor")) return;
Color wanted = SkinFor(player);
Color current = material.GetColor("_SkinColor");
if (Mathf.Abs(current.r - wanted.r) < 0.01f && Mathf.Abs(current.g - wanted.g) < 0.01f &&
Mathf.Abs(current.b - wanted.b) < 0.01f) return;
Traverse.Create(vis).Method("UpdateColors").GetValue();
}
// ─── Hands ───────────────────────────────────────────────────────────
/// <summary>The right hand bone: where the beam leaves from.</summary>
public static Transform RightHand(Player player)
{
return player != null ? FindBone(player, "RightHand") : null;
}
private static Transform FindBone(Player player, string boneName)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null;
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name == boneName) return bone;
}
// Loose match, because rigs are not consistent about capitalisation or prefixes.
string wanted = boneName.ToLowerInvariant();
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name.ToLowerInvariant().Contains(wanted)) return bone;
}
return null;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 340 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 441 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 339 KiB

View file

@ -1,182 +0,0 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Why nothing in Valheim ever attacked the bat, and the smallest honest fix for it.
///
/// The bat flies on Player.m_debugFly - the developer no-clip flag - because that is the only
/// flight vanilla actually has, and it is what BatFormBehavior sets and WarVultureMount reuses.
/// What nobody noticed is that vanilla reads that same flag as "this player is not really
/// here". Six places, all read out of assembly_valheim with Cecil rather than guessed:
///
/// BaseAI.CanHearTarget - first line: the target is a Player in debug fly -> return false.
/// BaseAI.CanSeeTarget - the same first line, the same false.
/// BaseAI.FindEnemy - its HuntPlayer fallback throws the player away for the same reason.
/// MonsterAI.UpdateSleep - a sleeping monster refuses to wake for one, twice over.
/// Character.ApplyDamage - first line: IsDebugFlying -> return, the hit does nothing.
/// Character.RPC_Damage - the same.
///
/// So the bat was never merely ignored: it was invulnerable as well, and both facts came out of
/// the one flag. There was nothing wrong with the Aswid's own code, which is why nothing in it
/// looked wrong.
///
/// The fix keeps the flag - it IS the flight - and lies about it in exactly the places that
/// decide aggro and damage, and nowhere else:
///
/// Player.InDebugFlyMode() is forced false for a bat unconditionally. That is safe, and it is
/// the reason this file is short: a scan of the whole assembly says that method has
/// exactly three callers, and all three are the sensing paths listed above. No part of
/// flight, camera, stamina or motion goes through it.
/// Player.IsDebugFlying() is NOT forced false, because Character.UpdateMotion reads it and
/// that read is what holds the bat in the air. It is only forced false while the call
/// stack is inside one of the three vanilla methods that must not honour it, which is
/// what the depth counter below is for.
///
/// Both halves sit behind their own config toggle, so a bat can be made visible-but-immortal,
/// or put back the way it was, without touching code.
/// </summary>
public static class AswidBatForm
{
/// <summary>
/// The ZDO flag AswidRace writes when the form goes up. Replicated, so it answers for
/// remote players too - which matters here, because the machine asking "is this player a
/// bat" is whichever one owns the monster, not the bat's own.
/// </summary>
public const string BatZdoKey = "Aswid_IsBatForm";
private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
// How deep we currently are inside vanilla calls that must not see the debug-fly flag. A
// counter and not a bool: ApplyDamage runs inside RPC_Damage, so the frames nest.
private static int unmaskDepth;
public static bool Unmasked => unmaskDepth > 0;
public static void PushUnmask() { unmaskDepth++; }
public static void PopUnmask() { if (unmaskDepth > 0) unmaskDepth--; }
/// <summary>
/// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true
/// on every client, and the status effect covers the local player during the frames of the
/// transform where the ZDO write has not landed yet.
/// </summary>
public static bool IsBat(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
return player == Player.m_localPlayer &&
player.GetSEMan() != null &&
player.GetSEMan().HaveStatusEffect(BatFormHash);
}
}
/// <summary>
/// The whole of the aggro fix. See AswidBatForm for why patching this one method flat is safe,
/// and why patching IsDebugFlying flat would drop the bat out of the sky instead.
/// </summary>
[HarmonyPatch(typeof(Player), "InDebugFlyMode")]
public static class Aswid_BatIsVisibleToAI_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result) return;
if (AswidConfig.BatFormAggro != null && !AswidConfig.BatFormAggro.Value) return;
if (AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// The scoped half. Only ever fires inside the three vanilla methods that push the counter, and
/// only for a player who is a bat - so the flag still reads true everywhere flight, motion, the
/// camera and Player.UpdateStats look at it.
/// </summary>
[HarmonyPatch(typeof(Player), "IsDebugFlying")]
public static class Aswid_BatIsDebugFlying_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result || !AswidBatForm.Unmasked) return;
if (AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// A hit landing on a bat. Finalizer rather than Postfix throughout this file: the counter has
/// to come back down even when the patched method throws, and a Postfix does not run then. A
/// void Finalizer leaves the original exception alone, so nothing is swallowed either.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_BatTakesDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = (AswidConfig.BatFormVulnerable == null || AswidConfig.BatFormVulnerable.Value)
&& __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>The networked half of the same thing: a hit sent by another machine.</summary>
[HarmonyPatch(typeof(Character), "RPC_Damage")]
public static class Aswid_BatTakesRemoteDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = (AswidConfig.BatFormVulnerable == null || AswidConfig.BatFormVulnerable.Value)
&& __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>
/// Sleepers. Unlike the two above this cannot pre-check who the player is - UpdateSleep picks
/// the closest one itself, and that may be a remote bat - so the counter goes up for the whole
/// call and the per-player test happens in the IsDebugFlying postfix, where it costs nothing:
/// that postfix only runs at all for a character who is already flying.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateSleep")]
public static class Aswid_BatWakesSleepers_Patch
{
public static void Prefix(ref bool __state)
{
__state = AswidConfig.BatFormAggro == null || AswidConfig.BatFormAggro.Value;
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>
/// Dying as a bat only became possible with the patches above, and the revert path could not
/// handle it: AswidRace.Update() returns early on IsDead(), so the coroutine that takes the
/// form down never starts. The debug-fly flag would stay on and the ZDO would stay true, which
/// is a respawned player floating over the ground with a bat drawn on them.
/// </summary>
[HarmonyPatch(typeof(Player), "OnDeath")]
public static class Aswid_BatDiesAsBat_Patch
{
public static void Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (AswidRace.Instance == null) return;
AswidRace.Instance.HardResetBatForm();
}
}
}

View file

@ -1,57 +0,0 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// How fast the bat flies, as a factor on vanilla's own debug-fly speed.
///
/// The form flies on Player.m_debugFly (see AswidBatForm for why), so its speed is whatever
/// Character.UpdateDebugFly decides. Read out of assembly_valheim rather than assumed, that
/// method ends with:
///
/// m_currentVel = Vector3.Lerp(m_currentVel, b, 0.5f);
/// m_body.linearVelocity = m_currentVel;
///
/// where b is m_moveDir times m_debugFlySpeed - a public STATIC INT, 20 by default, times 2.5
/// while the run key is held.
///
/// Two ways to make that faster were rejected before this one:
///
/// Retuning m_debugFlySpeed around the call. It is shared by every character in the game and
/// it is an int, so a 1.35x multiplier would land on 27 and a 1.37x on the same 27 - the
/// slider would move in 5% steps and would be writing a global while it did it.
///
/// Scaling m_currentVel itself, which is what WarVultureMount does for the bird. That field
/// is the input to the NEXT frame's lerp, so scaling it feeds back: with a factor s the
/// velocity settles at 0.5s/(1-0.5s) times vanilla, not s times it, and at s >= 2 it does
/// not settle at all.
///
/// So only the rigidbody is scaled, and m_currentVel is left exactly as vanilla wrote it. The
/// lerp keeps smoothing the same trajectory it always did - the ramp up, the ease off, the
/// standstill at zero input - and the bat simply covers it faster. Linear in the slider, with
/// nothing to accumulate.
/// </summary>
[HarmonyPatch(typeof(Character), "UpdateDebugFly")]
public static class Aswid_BatFlightSpeed_Patch
{
public static void Postfix(Character __instance, Vector3 ___m_currentVel, Rigidbody ___m_body)
{
// Bound from RacesOfValheim.Awake(), before harmony.PatchAll() - the null check is for
// the config that failed to bind at all, not for a race between the two.
if (AswidConfig.BatFormFlightSpeed == null) return;
float multiplier = AswidConfig.BatFormFlightSpeed.Value;
if (Mathf.Approximately(multiplier, 1f)) return;
// Local player only. Every other machine's bat moves on its replicated position, and
// scaling velocity here would fight that sync rather than help it.
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
if (___m_body == null) return;
if (!AswidBatForm.IsBat(player)) return;
___m_body.linearVelocity = ___m_currentVel * multiplier;
}
}
}

View file

@ -0,0 +1,170 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Whether a player is a bat, on any client.
///
/// Stamina Flight flies on m_flying (DirectedFlight.cs), which vanilla's AI and damage never
/// look at, so monsters notice and hurt that bat with no help.
///
/// Free Flight flies on vanilla's debug-fly flag, and vanilla reads that flag as "this player
/// is not really here". Six places, read out of assembly_valheim:
///
/// BaseAI.CanHearTarget, BaseAI.CanSeeTarget and BaseAI's HuntPlayer fallback ask
/// Player.InDebugFlyMode() and drop the player.
/// MonsterAI.UpdateSleep asks IsDebugFlying() and will not wake, twice over.
/// Character.ApplyDamage and Character.RPC_Damage ask IsDebugFlying() and drop the hit.
///
/// The patches below keep the flag (it IS the flight) and lie about it in exactly those
/// places, for bats only. InDebugFlyMode() is forced false flat: those three AI paths are its
/// only callers. IsDebugFlying() cannot be: Character.UpdateMotion reads it to hold the bat in
/// the air, so it reads false only while the call stack is inside one of the methods that push
/// the counter. The patches were removed with the old flight in v1.6.1 and came back with it.
/// </summary>
public static class AswidBatForm
{
/// <summary>
/// The ZDO flag AswidRace writes when the form goes up. Replicated, so it answers for
/// remote players too.
/// </summary>
public const string BatZdoKey = "Aswid_IsBatForm";
private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
// How deep we are inside vanilla calls that must not see the debug-fly flag. A counter,
// not a bool: ApplyDamage runs inside RPC_Damage, so the frames nest.
private static int unmaskDepth;
public static bool Unmasked => unmaskDepth > 0;
public static void PushUnmask() { unmaskDepth++; }
public static void PopUnmask() { if (unmaskDepth > 0) unmaskDepth--; }
/// <summary>
/// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true
/// on every client, and the status effect covers the local player during the frames of the
/// transform where the ZDO write has not landed yet.
/// </summary>
public static bool IsBat(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
return player == Player.m_localPlayer &&
player.GetSEMan() != null &&
player.GetSEMan().HaveStatusEffect(BatFormHash);
}
}
/// <summary>Free Flight: monsters see and hear a bat. See AswidBatForm for why this one is safe flat.</summary>
[HarmonyPatch(typeof(Player), "InDebugFlyMode")]
public static class Aswid_BatIsVisibleToAI_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (__result && AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// The scoped half: false only inside the methods that push the counter, so flight, motion,
/// the camera and UpdateStats still read the flag as true.
/// </summary>
[HarmonyPatch(typeof(Player), "IsDebugFlying")]
public static class Aswid_BatIsDebugFlying_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result || !AswidBatForm.Unmasked) return;
if (AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// A hit landing on a free-flying bat. Finalizer rather than Postfix: the counter has to come
/// down even when the method throws, and a void Finalizer leaves the exception alone.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_BatTakesDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>The networked half of the same thing: a hit sent by another machine.</summary>
[HarmonyPatch(typeof(Character), "RPC_Damage")]
public static class Aswid_BatTakesRemoteDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>
/// Notes when the local player last lost health, for the bat's combat lock. ApplyDamage is the
/// one final stage for direct hits, burning, poison and bleeding, so comparing health around it
/// catches them all, and a hit fully blocked or absorbed (Alfar shield, Heimkall) is no hurt.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Aswid_BatCombatLock_Patch
{
public static void Prefix(Character __instance, ref float __state)
{
__state = __instance == Player.m_localPlayer ? __instance.GetHealth() : -1f;
}
public static void Postfix(Character __instance, float __state)
{
if (__state < 0f) return;
if (__instance.GetHealth() < __state) AswidRace.LastHurtTime = Time.time;
}
}
/// <summary>
/// Sleepers. UpdateSleep picks the closest player itself, possibly a remote bat, so the counter
/// goes up for the whole call and the bat test happens in the IsDebugFlying postfix, which only
/// runs its test for a player already debug flying.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateSleep")]
public static class Aswid_BatWakesSleepers_Patch
{
public static void Prefix() { AswidBatForm.PushUnmask(); }
public static void Finalizer() { AswidBatForm.PopUnmask(); }
}
/// <summary>
/// The revert path cannot handle a bat that dies: AswidRace.Update() returns early on IsDead(),
/// so the coroutine that takes the form down never starts. The flight flag would stay on and
/// the ZDO would stay true, which is a respawned player floating over the ground with a bat
/// drawn on them.
/// </summary>
[HarmonyPatch(typeof(Player), "OnDeath")]
public static class Aswid_BatDiesAsBat_Patch
{
public static void Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (AswidRace.Instance == null) return;
AswidRace.Instance.HardResetBatForm();
}
}
}

View file

@ -68,6 +68,7 @@ namespace RacesOfValheim
{ "AsksvinCarrionRibcage", 3 }, { "AsksvinCarrionRibcage", 3 },
{ "AsksvinCarrionSkull", 3 }, { "AsksvinCarrionSkull", 3 },
{ "UndeadBjornRibcage", 3 }, // Deep North { "UndeadBjornRibcage", 3 }, // Deep North
{ "ElakingHairBundle", 20 }, // Deep North, dropped by the Elaking
}; };
// Vanilla grills. Anything they cook counts as raw flesh, which keeps modded meat working. // Vanilla grills. Anything they cook counts as raw flesh, which keeps modded meat working.
@ -337,8 +338,6 @@ namespace RacesOfValheim
// The raw -> cooked table the Draugh already maintains is the source of truth. // The raw -> cooked table the Draugh already maintains is the source of truth.
meatToCooked = new Dictionary<string, string>(DraughFoodPatches.rawToCookedMapping); meatToCooked = new Dictionary<string, string>(DraughFoodPatches.rawToCookedMapping);
meatToCooked.Remove("GreydwarfEye"); // stew ingredient, not flesh meatToCooked.Remove("GreydwarfEye"); // stew ingredient, not flesh
meatToCooked["AsksvinMeat"] = "CookedAsksvinMeat";
meatToCooked["BoneMawSerpentMeat"] = "CookedBoneMawSerpentMeat";
foreach (string stationName in CookingStationPrefabs) foreach (string stationName in CookingStationPrefabs)
{ {

View file

@ -33,13 +33,81 @@ namespace RacesOfValheim
public static ConfigEntry<float> BloodMagicSkillGainMultiplier; public static ConfigEntry<float> BloodMagicSkillGainMultiplier;
public static ConfigEntry<float> SurtlingFormDamageBonus; public static ConfigEntry<float> SurtlingFormDamageBonus;
// ─── Stamina ─────────────────────────────────────────────────────────────
// The race used to have infinite stamina. Now it has a large pool that grows with each
// boss, on top of what its devoured food gives - added, never assigned, so stamina mods
// still stack.
public static ConfigEntry<float> BaseStaminaBonus;
public static ConfigEntry<float> StaminaBonusPerState;
public static ConfigEntry<float> StaminaCostMultiplier;
// ─── Weaknesses ──────────────────────────────────────────────────────────
// The Discord reports said the race had no real downsides. Each weakness has its own
// switch, so a single player can drop one; on a server the host's values win.
public static ConfigEntry<bool> SunlightEnabled;
public static ConfigEntry<float> SunHealthRegenPenalty;
public static ConfigEntry<float> SunStaminaRegenPenalty;
public static ConfigEntry<float> SunSpeedPenalty;
public static ConfigEntry<float> SunHealthLossPerSecond;
public static ConfigEntry<float> SunHealthFloor;
public static ConfigEntry<bool> FireWeaknessEnabled;
public static ConfigEntry<float> FireWeakness;
public static ConfigEntry<bool> FaderRemovesFireWeakness;
public static ConfigEntry<bool> PierceWeaknessEnabled;
public static ConfigEntry<float> PierceWeakness;
// ─── Running Water ─────────────────────────────────────────────────────
// Lore says a vampire cannot cross running water unaided (Dagaz's report). Swimming costs
// more, and open water - sea, river or lake - burns, swimming or flying over it; a boat
// carries you, which the lore allows, though the camera still sways on board. The camera sway is a per-player comfort choice and stays local
// (ConfigSync's "camera sway" key part).
public static ConfigEntry<bool> RunningWaterEnabled;
public static ConfigEntry<bool> WaterOceanOnly;
public static ConfigEntry<float> SwimStaminaMultiplier;
public static ConfigEntry<float> SeaHealthLossPerSecond;
public static ConfigEntry<float> SeaStaminaDrainPerSecond;
public static ConfigEntry<float> SeaHealthFloor;
public static ConfigEntry<bool> SeaCameraSway;
public static ConfigEntry<float> SeaCameraSwayStrength;
// ─── Bat Form ──────────────────────────────────────────────────────────── // ─── Bat Form ────────────────────────────────────────────────────────────
// Both of these undo something vanilla does to any player on the debug-fly flag, which is // The bat flies on the same directed flight as the Skadi's drakes (DirectedFlight.cs),
// what the bat flies on. See AswidBatAggro for the six vanilla methods involved. // with its own numbers. It used to fly on vanilla's debug-fly flag: 50 m/s, free, blind
public static ConfigEntry<bool> BatFormAggro; // to carry weight, and ignored by every monster until AswidBatAggro lied to six vanilla
public static ConfigEntry<bool> BatFormVulnerable; // methods about it. The old flight came back as Free Flight, for players who want it
// A factor on vanilla's debug-fly speed, not a speed in metres - see AswidBatFlight. // (building tall); AswidBatForm holds the aggro patches it needs.
public static ConfigEntry<float> BatFormFlightSpeed; public enum EncumberedMode { Allowed, Blocked }
public enum BatFlightRuleMode { PlayerChoice, AlwaysStaminaFlight, AlwaysFreeFlight }
public static ConfigEntry<bool> FreeBatFlight;
public static ConfigEntry<BatFlightRuleMode> BatFlightRule;
/// <summary>Which flight a bat taken now gets: the server's rule first, then the player's own pick.</summary>
public static bool UsesFreeBatFlight()
{
switch (BatFlightRule.Value)
{
case BatFlightRuleMode.AlwaysStaminaFlight: return false;
case BatFlightRuleMode.AlwaysFreeFlight: return true;
default: return FreeBatFlight.Value;
}
}
public static ConfigEntry<float> BatTurnSpeed;
public static ConfigEntry<float> BatGlideSpeed;
public static ConfigEntry<float> BatBoostSpeed;
public static ConfigEntry<float> BatSprintSpeed;
public static ConfigEntry<float> BatReverseSpeed;
public static ConfigEntry<float> BatLiftoffSpeed;
public static ConfigEntry<float> BatHoverSeconds;
public static ConfigEntry<float> BatPoweredStaminaPerSecond;
public static ConfigEntry<float> BatSprintStaminaPerSecond;
public static ConfigEntry<EncumberedMode> BatEncumbered;
public static ConfigEntry<float> BatEncumberedExtraCost;
public static ConfigEntry<float> BatMaxDuration;
public static ConfigEntry<float> BatDurationPerState;
public static ConfigEntry<float> BatCooldown;
public static ConfigEntry<float> BatCombatLock;
// ─── Vampiric Aura (passive, always active) ────────────────────────────── // ─── Vampiric Aura (passive, always active) ──────────────────────────────
public static ConfigEntry<float> AuraTickInterval; public static ConfigEntry<float> AuraTickInterval;
@ -48,6 +116,8 @@ namespace RacesOfValheim
public static ConfigEntry<float> AuraBaseDamage; public static ConfigEntry<float> AuraBaseDamage;
public static ConfigEntry<float> AuraBloodMagicScaling; public static ConfigEntry<float> AuraBloodMagicScaling;
public static ConfigEntry<float> AuraExecuteThreshold; public static ConfigEntry<float> AuraExecuteThreshold;
public static ConfigEntry<bool> AuraInBatForm;
public static ConfigEntry<int> BatAuraUnlockState;
// ─── Superhuman Senses (tier 5+ passive) ───────────────────────────────── // ─── Superhuman Senses (tier 5+ passive) ─────────────────────────────────
public static ConfigEntry<float> SensesRadius; public static ConfigEntry<float> SensesRadius;
@ -62,6 +132,12 @@ namespace RacesOfValheim
// ─── Devour ──────────────────────────────────────────────────────────── // ─── Devour ────────────────────────────────────────────────────────────
public static ConfigEntry<float> DevourCooldown; public static ConfigEntry<float> DevourCooldown;
// What a devoured creature feeds - see AswidRace.ApplyFoodBalance.
public static ConfigEntry<float> DevourHealthMultiplier;
public static ConfigEntry<float> DevourStaminaShare;
public static ConfigEntry<float> EarlyStaminaShare;
public static ConfigEntry<float> FoodCapBase;
public static ConfigEntry<float> FoodCapPerBiome;
// ─── Domination (tier 6+ ability, native Interact key) ─────────────────── // ─── Domination (tier 6+ ability, native Interact key) ───────────────────
public static ConfigEntry<float> EnslaveCooldown; public static ConfigEntry<float> EnslaveCooldown;
@ -130,13 +206,95 @@ namespace RacesOfValheim
SurtlingFormDamageBonus = config.Bind(combat, "Surtling Form Damage Bonus", 30f, SurtlingFormDamageBonus = config.Bind(combat, "Surtling Form Damage Bonus", 30f,
new ConfigDescription("Flat damage added to every attack once the tier 8 Surtling form is unlocked.", new AcceptableValueRange<float>(0f, 100f))); new ConfigDescription("Flat damage added to every attack once the tier 8 Surtling form is unlocked.", new AcceptableValueRange<float>(0f, 100f)));
const string stamina = "Aswid - Stamina";
BaseStaminaBonus = config.Bind(stamina, "Base Stamina Bonus", 25f,
new ConfigDescription("Max stamina added on top of the game's base 75 and your food, before any boss.", new AcceptableValueRange<float>(0f, 300f)));
StaminaBonusPerState = config.Bind(stamina, "Stamina Bonus Per State", 10f,
new ConfigDescription("Max stamina added per progression state (8 at Fader).", new AcceptableValueRange<float>(0f, 50f)));
StaminaCostMultiplier = config.Bind(stamina, "Stamina Cost Multiplier", 1f,
new ConfigDescription("Multiplies every stamina cost: sprinting, swimming, attacks, blocking. 1 is the normal cost, 0.5 half. There is no infinite setting on purpose; set the bonuses above high instead.", new AcceptableValueRange<float>(0.1f, 2f)));
const string weak = "Aswid - Weaknesses";
SunlightEnabled = config.Bind(weak, "Sunlight", true,
new ConfigDescription("Weakens you by day while you stand under open sky. A roof (the same test as the game's Sheltered status), a dungeon, the Swamp, the Mistlands, the night and your own Eclipse all shield you.", null));
SunHealthRegenPenalty = config.Bind(weak, "Sunlight Health Regen Penalty", 0.5f,
new ConfigDescription("Health regeneration lost in sunlight. 0.5 = half.", new AcceptableValueRange<float>(0f, 1f)));
SunStaminaRegenPenalty = config.Bind(weak, "Sunlight Stamina Regen Penalty", 0.25f,
new ConfigDescription("Stamina regeneration lost in sunlight. 0.25 = a quarter.", new AcceptableValueRange<float>(0f, 1f)));
SunSpeedPenalty = config.Bind(weak, "Sunlight Speed Penalty", 0.1f,
new ConfigDescription("Movement speed lost in sunlight. 0.1 = 10% slower.", new AcceptableValueRange<float>(0f, 0.9f)));
SunHealthLossPerSecond = config.Bind(weak, "Sunlight Health Loss Per Second", 0.5f,
new ConfigDescription("Health the sun burns away each second. 0 turns it off.", new AcceptableValueRange<float>(0f, 10f)));
SunHealthFloor = config.Bind(weak, "Sunlight Health Floor", 0.3f,
new ConfigDescription("The sun stops burning at this fraction of your max health, so it weakens you but never kills you. 0.3 = 30%.", new AcceptableValueRange<float>(0f, 1f)));
FireWeaknessEnabled = config.Bind(weak, "Fire Weakness", true,
new ConfigDescription("Fire, burning included, hurts more.", null));
FireWeakness = config.Bind(weak, "Fire Weakness Amount", 0.25f,
new ConfigDescription("Extra fire damage taken. 0.25 = 25% more. Resistance meads and armour still reduce it.", new AcceptableValueRange<float>(0f, 2f)));
FaderRemovesFireWeakness = config.Bind(weak, "Fader Removes Fire Weakness", true,
new ConfigDescription("Defeating Fader, the boss that grants the Surtling form, ends the fire weakness.", null));
PierceWeaknessEnabled = config.Bind(weak, "Pierce Weakness", true,
new ConfigDescription("Pierce damage (arrows, spears, stakes) hurts more. Mist Form's immunity still wins.", null));
PierceWeakness = config.Bind(weak, "Pierce Weakness Amount", 0.2f,
new ConfigDescription("Extra pierce damage taken. 0.2 = 20% more.", new AcceptableValueRange<float>(0f, 2f)));
const string water = "Aswid - Running Water";
RunningWaterEnabled = config.Bind(water, "Running Water", true,
new ConfigDescription("Swimming costs more stamina, and open water - the sea, rivers, lakes - hurts you while you swim in it or fly over it. Standing on, steering or sitting in a boat protects you. Wading, docks and bridges are safe.", null));
WaterOceanOnly = config.Bind(water, "Ocean Only", false,
new ConfigDescription("Limits the burn, the drain and the camera sway to the Ocean biome, leaving rivers and lakes alone. The swim stamina cost applies everywhere either way.", null));
SwimStaminaMultiplier = config.Bind(water, "Swim Stamina Multiplier", 2f,
new ConfigDescription("Multiplies the stamina swimming costs, anywhere. At 0 stamina the game's own drowning starts. Around 5 and up, swimming any distance is no longer possible.", new AcceptableValueRange<float>(1f, 10f)));
SeaHealthLossPerSecond = config.Bind(water, "Open Water Health Loss Per Second", 1f,
new ConfigDescription("Health open water burns away each second.", new AcceptableValueRange<float>(0f, 20f)));
SeaStaminaDrainPerSecond = config.Bind(water, "Open Water Stamina Drain Per Second", 2f,
new ConfigDescription("Stamina open water drains each second, on top of what swimming or flying costs.", new AcceptableValueRange<float>(0f, 30f)));
SeaHealthFloor = config.Bind(water, "Open Water Health Floor", 0.1f,
new ConfigDescription("The water's burn stops at this fraction of your max health. Drowning, once your stamina runs out, has no floor.", new AcceptableValueRange<float>(0f, 1f)));
SeaCameraSway = config.Bind(water, "Camera Sway", true,
new ConfigDescription("The camera rolls gently while you are out on the water, on a boat too, as if seasick. Local: each player chooses for themselves.", null));
SeaCameraSwayStrength = config.Bind(water, "Camera Sway Strength", 1f,
new ConfigDescription("How far the camera rolls. 1 is about 4 degrees. Local.", new AcceptableValueRange<float>(0f, 3f)));
const string batform = "Aswid - Bat Form"; const string batform = "Aswid - Bat Form";
BatFormAggro = config.Bind(batform, "Monsters Notice The Bat", true, FreeBatFlight = config.Bind(batform, "Free Bat Flight", false,
new ConfigDescription("Lets monsters see, hear and wake up for a player in Bat Form. Vanilla refuses to notice anyone flying on the debug-fly flag, which is the flag the form uses - turn this off to go back to a bat nothing ever looks at.")); new ConfigDescription("Off: Stamina Flight, the settings below. On: the old Free Flight, up to 50 m/s with no stamina cost and no weight limit; Jump rises, Left Ctrl sinks. Your own choice, unless the server's Bat Flight Rule forces one. Takes effect the next time you become a bat."));
BatFormVulnerable = config.Bind(batform, "The Bat Can Be Hurt", true, BatFlightRule = config.Bind(batform, "Bat Flight Rule", BatFlightRuleMode.PlayerChoice,
new ConfigDescription("Lets damage land on a player in Bat Form. Same cause as the setting above: vanilla drops every hit on a debug-flying character. Turn this off for a bat that is noticed and chased but cannot be killed.")); new ConfigDescription("Server rule. PlayerChoice: each player's Free Bat Flight setting decides. AlwaysStaminaFlight / AlwaysFreeFlight: every bat flies that way. On a server only the host's or the server's value counts."));
BatFormFlightSpeed = config.Bind(batform, "Flight Speed", 1f, // Same controls as the Skadi's drake: aim with the camera, W beats forward, Shift
new ConfigDescription("How fast the bat flies, as a multiplier on the game's own flight speed (20 m/s, and 2.5x that while the run key is held). 1 is untouched, 2 is twice as fast, 0.5 is half. Local only - it changes how your own bat moves, not anyone else's.", new AcceptableValueRange<float>(0.25f, 3f))); // sprints, S beats backwards, and letting go hovers briefly before gliding down.
BatTurnSpeed = config.Bind(batform, "Turn Speed", 180f,
new ConfigDescription("Degrees per second the bat turns towards where you aim.", new AcceptableValueRange<float>(30f, 720f)));
BatGlideSpeed = config.Bind(batform, "Glide Speed", 6f,
new ConfigDescription("Speed while gliding down with no key held, in m/s.", new AcceptableValueRange<float>(0f, 30f)));
// Not "Flight Speed": that key held the old debug-fly multiplier, and an existing .cfg
// would load its 1 here as one metre per second.
BatBoostSpeed = config.Bind(batform, "Boost Speed", 13f,
new ConfigDescription("Speed while holding W, in m/s. Costs the powered stamina below.", new AcceptableValueRange<float>(0f, 60f)));
BatSprintSpeed = config.Bind(batform, "Sprint Speed", 24f,
new ConfigDescription("Speed while holding W and Shift, in m/s. Costs the sprint stamina on top. The old bat flew at 50.", new AcceptableValueRange<float>(0f, 80f)));
BatReverseSpeed = config.Bind(batform, "Reverse Speed", 8f,
new ConfigDescription("Speed while holding S, in m/s. Costs the powered stamina.", new AcceptableValueRange<float>(0f, 40f)));
BatLiftoffSpeed = config.Bind(batform, "Liftoff Speed", 9f,
new ConfigDescription("Climb speed out of water, in m/s. Always free, so a bat that touches the sea can still leave it.", new AcceptableValueRange<float>(0f, 30f)));
BatHoverSeconds = config.Bind(batform, "Hover Seconds", 3f,
new ConfigDescription("How long the bat holds its height after the last powered beat before it starts to glide down.", new AcceptableValueRange<float>(0f, 30f)));
BatPoweredStaminaPerSecond = config.Bind(batform, "Flight Stamina Per Second", 3f,
new ConfigDescription("Stamina per second while holding W or S. Out of stamina, the bat can only glide. 0 makes flight free, like the drake's.", new AcceptableValueRange<float>(0f, 60f)));
BatSprintStaminaPerSecond = config.Bind(batform, "Sprint Stamina Per Second", 12f,
new ConfigDescription("Extra stamina per second while sprinting, on top of the flight cost.", new AcceptableValueRange<float>(0f, 60f)));
BatEncumbered = config.Bind(batform, "While Encumbered", EncumberedMode.Allowed,
new ConfigDescription("Allowed: the bat flies while you carry too much, at the extra stamina cost below. Blocked: you cannot take bat form while encumbered, and a bat that becomes encumbered in the air can only glide down.", null));
BatEncumberedExtraCost = config.Bind(batform, "Encumbered Extra Stamina Cost", 0.15f,
new ConfigDescription("With 'Allowed' above: how much more flight and sprint cost while encumbered. 0.15 = 15% more.", new AcceptableValueRange<float>(0f, 1f)));
BatMaxDuration = config.Bind(batform, "Max Duration", 0f,
new ConfigDescription("Seconds the bat form lasts before you turn back on your own. 0 means no limit: stamina is the limit.", new AcceptableValueRange<float>(0f, 3600f)));
BatDurationPerState = config.Bind(batform, "Duration Per State", 0f,
new ConfigDescription("Seconds added to the max duration per progression state. Does nothing while the max duration is 0.", new AcceptableValueRange<float>(0f, 600f)));
BatCooldown = config.Bind(batform, "Cooldown", 0f,
new ConfigDescription("Seconds after leaving bat form before you can take it again. 0 means none.", new AcceptableValueRange<float>(0f, 3600f)));
BatCombatLock = config.Bind(batform, "Combat Lock", 2.5f,
new ConfigDescription("Seconds after you last lost health (a hit, or a tick of fire, poison or bleeding) before you can take bat form. Turning back from bat form is never blocked. 0 means none.", new AcceptableValueRange<float>(0f, 30f)));
const string aura = "Aswid - Vampiric Aura"; const string aura = "Aswid - Vampiric Aura";
AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f, AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f,
@ -151,6 +309,10 @@ namespace RacesOfValheim
new ConfigDescription("Extra damage per tick at 100 Blood Magic skill (scales linearly from 0).", new AcceptableValueRange<float>(0f, 20f))); new ConfigDescription("Extra damage per tick at 100 Blood Magic skill (scales linearly from 0).", new AcceptableValueRange<float>(0f, 20f)));
AuraExecuteThreshold = config.Bind(aura, "Execute Threshold", 0.20f, AuraExecuteThreshold = config.Bind(aura, "Execute Threshold", 0.20f,
new ConfigDescription("Non-boss enemies at or below this fraction of max health are executed by the aura instead of merely damaged.", new AcceptableValueRange<float>(0f, 1f))); new ConfigDescription("Non-boss enemies at or below this fraction of max health are executed by the aura instead of merely damaged.", new AcceptableValueRange<float>(0f, 1f)));
AuraInBatForm = config.Bind(aura, "Active In Bat Form", false,
new ConfigDescription("Lets the aura drain while you are a bat from the start, as it did before. Off: the bat has no aura until the unlock state below.", null));
BatAuraUnlockState = config.Bind(aura, "Bat Form Unlock State", 7,
new ConfigDescription("The progression state at which the bat gets its aura back (7 = The Queen). 0 means never, so only the setting above can turn it on.", new AcceptableValueRange<int>(0, 8)));
const string senses = "Aswid - Superhuman Senses"; const string senses = "Aswid - Superhuman Senses";
SensesRadius = config.Bind(senses, "Detection Radius", 100f, SensesRadius = config.Bind(senses, "Detection Radius", 100f,
@ -173,6 +335,23 @@ namespace RacesOfValheim
const string devour = "Aswid - Devour"; const string devour = "Aswid - Devour";
DevourCooldown = config.Bind(devour, "Consume Cooldown", 5f, DevourCooldown = config.Bind(devour, "Consume Cooldown", 5f,
new ConfigDescription("How long one body stays drunk-dry, in seconds. A single death is reported to the devour more than once - by two damage patches, by the aura's execute, by a thrall's kill - and this is the window that keeps those from feeding you twice off the same corpse. It is per body, not per player: killing a whole pack at once devours every one of them. One second is used as the floor, so no corpse feeds you twice even at 0.", new AcceptableValueRange<float>(0f, 60f))); new ConfigDescription("How long one body stays drunk-dry, in seconds. A single death is reported to the devour more than once - by two damage patches, by the aura's execute, by a thrall's kill - and this is the window that keeps those from feeding you twice off the same corpse. It is per body, not per player: killing a whole pack at once devours every one of them. One second is used as the floor, so no corpse feeds you twice even at 0.", new AcceptableValueRange<float>(0f, 60f)));
DevourHealthMultiplier = config.Bind(devour, "Health Multiplier", 0.9f,
new ConfigDescription("Scales the health every devoured creature feeds you. 1 is the old amount.", new AcceptableValueRange<float>(0f, 2f)));
DevourStaminaShare = config.Bind(devour, "Stamina Share", 0.10f,
new ConfigDescription("Fraction of that health turned into stamina instead, for creatures past the Black Forest. 0.1 = 10%.", new AcceptableValueRange<float>(0f, 1f)));
EarlyStaminaShare = config.Bind(devour, "Early Creature Stamina Share", 0.60f,
new ConfigDescription("The same, for Meadows and Black Forest creatures. Above 0.5 they feed more stamina than health. Set it equal to the one above to treat every creature alike.", new AcceptableValueRange<float>(0f, 1f)));
FoodCapBase = config.Bind(devour, "Food Health Cap Base", 15f,
new ConfigDescription("Creatures with no hand-set meal feed half their health. That is capped at this plus the per-biome value times the biome's number (Meadows 1 ... Deep North 8). With the defaults: Black Forest 45, Mountains 75, Plains 90.", new AcceptableValueRange<float>(0f, 150f)));
FoodCapPerBiome = config.Bind(devour, "Food Health Cap Per Biome", 15f,
new ConfigDescription("See the base cap above.", new AcceptableValueRange<float>(0f, 50f)));
// Jotunn's server sync assigns Value, which fires SettingChanged, so the server's
// numbers reach the foods the same way a local drag does.
foreach (var entry in new[] { DevourHealthMultiplier, DevourStaminaShare, EarlyStaminaShare, FoodCapBase, FoodCapPerBiome })
{
entry.SettingChanged += (_, __) => AswidRace.ApplyAllFoodBalance();
}
const string domination = "Aswid - Domination"; const string domination = "Aswid - Domination";
EnslaveCooldown = config.Bind(domination, "Enslave Cooldown", 900f, EnslaveCooldown = config.Bind(domination, "Enslave Cooldown", 900f,
@ -297,7 +476,7 @@ namespace RacesOfValheim
new ConfigDescription("As above, around the third axis. The default half turn is what rights the borrowed socket, which arrives upside down on a player's head bone.", new ConfigDescription("As above, around the third axis. The default half turn is what rights the borrowed socket, which arrives upside down on a player's head bone.",
new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 58 })); new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 58 }));
EyeSmoke = config.Bind(eyes, "Eye Smoke", true, EyeSmoke = config.Bind(eyes, "Eye Smoke", false,
new ConfigDescription("Lights the smoke the creature carries inside its own sockets and leaves switched off. Tinted to match the eyes, so it turns with them at the last stage.", new ConfigDescription("Lights the smoke the creature carries inside its own sockets and leaves switched off. Tinted to match the eyes, so it turns with them at the last stage.",
null, new ConfigurationManagerAttributes { Order = 50 })); null, new ConfigurationManagerAttributes { Order = 50 }));
EyeFlatColorShader = config.Bind(eyes, "Eye Flat Colour Shader", false, EyeFlatColorShader = config.Bind(eyes, "Eye Flat Colour Shader", false,

View file

@ -219,6 +219,32 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// Fire and pierce hurt the Aswid more: fire for the old way vampires end, pierce for the
/// stake. A plain multiplier, like the Trol's fire weakness, rather than DamageModifier.Weak,
/// which is a fixed +50% with nothing in between. ApplyDamage runs after resistances, so a
/// fire resistance mead still helps, and Mist Form's pierce immunity has already zeroed the
/// pierce by the time this sees it.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_Weakness_Patch
{
public static void Prefix(Character __instance, ref HitData hit)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
if (AswidRace.HasFireWeakness(BossProgressionManager.GetCurrentProgressionState()) && hit.m_damage.m_fire > 0f)
{
hit.m_damage.m_fire *= 1f + AswidConfig.FireWeakness.Value;
}
if (AswidConfig.PierceWeaknessEnabled.Value && hit.m_damage.m_pierce > 0f)
{
hit.m_damage.m_pierce *= 1f + AswidConfig.PierceWeakness.Value;
}
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")] [HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Aswid_Attack_Patch public static class Aswid_Attack_Patch
{ {
@ -239,6 +265,33 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// Bat and mist form shut the rest of the human's attack loop as well as StartAttack: crossbow
/// reload and draw live in PlayerAttackInput, and the form's Animator fires the held attack
/// through OnAttackTrigger. See Fenrir's BlockPlayerAttackInputPatch.
/// </summary>
public static class AswidFormAttackLoop
{
public static bool InForm(Humanoid player)
{
if (player != Player.m_localPlayer) return false;
return player.GetComponentInChildren<BatFormBehavior>() != null
|| player.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode());
}
}
[HarmonyPatch(typeof(Player), "PlayerAttackInput")]
public static class Aswid_BlockAttackInput_Patch
{
public static bool Prefix(Player __instance) => !AswidFormAttackLoop.InForm(__instance);
}
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))]
public static class Aswid_BlockAttackTrigger_Patch
{
public static bool Prefix(Humanoid __instance) => !AswidFormAttackLoop.InForm(__instance);
}
[HarmonyPatch(typeof(Character), "SetRun")] [HarmonyPatch(typeof(Character), "SetRun")]
public static class Aswid_Run_Patch public static class Aswid_Run_Patch
{ {
@ -314,14 +367,11 @@ namespace RacesOfValheim
} }
} }
if (canRefresh) // Otherwise vanilla's answer stands: it already allows replacing the
{ // most depleted meal past half its time, and already showed its "too
__result = true; // full" message when it refused. Forcing false here used to block
} // that replacement, silently.
else if (canRefresh) __result = true;
{
__result = false; // Nessuno spazio disponibile, cibo si disintegra
}
} }
} }
else else
@ -399,9 +449,9 @@ namespace RacesOfValheim
return false; return false;
} }
// Se pieno e senza 4° slot disponibile, fallisce e disintegra // Full, no fourth slot free, no slot holding this meal. Native EatFood
__result = false; // replaces the most depleted meal past half its time, or refuses.
return false; return true;
} }
else else
{ {
@ -473,7 +523,7 @@ namespace RacesOfValheim
{ {
public static bool Prefix(Hud __instance, Player player) public static bool Prefix(Hud __instance, Player player)
{ {
if (player == Player.m_localPlayer && (AswidRace.IsAswid() || DraughRace.IsDraugh())) if (player == Player.m_localPlayer && DraughRace.IsDraugh())
{ {
if (__instance.m_staminaBar2Root != null && __instance.m_staminaBar2Root.gameObject.activeSelf) if (__instance.m_staminaBar2Root != null && __instance.m_staminaBar2Root.gameObject.activeSelf)
{ {
@ -481,6 +531,15 @@ namespace RacesOfValheim
} }
return false; return false;
} }
// Vanilla switches the bar on once, when the HUD is built, and never again. Without
// this a player who left the Draugh had no stamina bar until relog - and an Aswid
// updating from a version that still hid it would have none either.
if (player == Player.m_localPlayer && __instance.m_staminaBar2Root != null
&& !__instance.m_staminaBar2Root.gameObject.activeSelf)
{
__instance.m_staminaBar2Root.gameObject.SetActive(true);
}
return true; return true;
} }
} }
@ -565,6 +624,13 @@ namespace RacesOfValheim
{ {
bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false); bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false);
bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false); bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false);
// The bat flies on m_flying, which only the bat's own client sets. Mirror it here
// and switch gravity off for the duration, or this copy sinks to the terrain
// whatever altitude is replicated - the same fix ZdoVisualSync applies to drakes.
HarmonyLib.Traverse.Create(player).Field("m_flying").SetValue(isBat);
Rigidbody body = player.GetComponent<Rigidbody>();
if (body != null && body.useGravity == isBat) body.useGravity = !isBat;
Transform playerVisual = player.transform.Find("Visual"); Transform playerVisual = player.transform.Find("Visual");
@ -788,6 +854,104 @@ namespace RacesOfValheim
stamina += extraFood.m_stamina; stamina += extraFood.m_stamina;
eitr += extraFood.m_eitr; eitr += extraFood.m_eitr;
} }
// Added on top of whatever vanilla and other mods put here, never assigned: a mod that
// raises max stamina has to keep raising it for an Aswid too.
stamina += AswidRace.GetStaminaBonus(BossProgressionManager.GetCurrentProgressionState());
}
}
/// <summary>
/// The Aswid's stamina. It used to be infinite: the Skeleton's UseStamina skip covered the
/// Aswid too, which made every stamina mod, food and skill meaningless for the race (the Discord
/// reports that started the rebalance). The cost is now scaled rather than skipped, so the
/// call still reaches vanilla - and any other mod patching it - with a smaller number.
/// </summary>
[HarmonyPatch(typeof(Player), "UseStamina")]
public static class Aswid_UseStamina_Patch
{
public static void Prefix(Player __instance, ref float v)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
v *= AswidConfig.StaminaCostMultiplier.Value;
if (Aswid_SwimCost_Patch.Swimming && AswidConfig.RunningWaterEnabled.Value)
{
v *= AswidConfig.SwimStaminaMultiplier.Value;
}
}
}
/// <summary>
/// Marks the frames where vanilla charges for a swim stroke, so Aswid_UseStamina_Patch can
/// make that one cost dearer. Player.OnSwimming is the only place swimming spends stamina,
/// and it also runs the drowning check right after - which is what makes a high multiplier
/// play as "cannot swim" without any code of ours deciding who drowns.
/// </summary>
[HarmonyPatch(typeof(Player), "OnSwimming")]
public static class Aswid_SwimCost_Patch
{
public static bool Swimming { get; private set; }
public static void Prefix(Player __instance)
{
Swimming = __instance == Player.m_localPlayer;
}
public static void Finalizer()
{
Swimming = false;
}
}
/// <summary>
/// The seasick camera: a slow roll while the Aswid is out on the water, on a boat too. Applied after
/// vanilla has settled the camera's rotation for the frame, as a roll around the view axis,
/// so it never moves where the player aims - only how the horizon sits.
/// </summary>
[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
public static class Aswid_SeaCameraSway_Patch
{
private const float DegreesAtStrengthOne = 4f;
private static float sway;
public static void Postfix(float dt, ref Quaternion rot)
{
bool on = AswidRace.OnWater && AswidConfig.SeaCameraSway.Value && AswidRace.IsAswid() &&
Player.m_localPlayer != null && !Player.m_localPlayer.IsDead();
// Eased in and out over about a second, so leaving the sea does not snap the horizon.
sway = Mathf.MoveTowards(sway, on ? 1f : 0f, dt);
if (sway <= 0f) return;
float t = Time.time;
float roll = (Mathf.Sin(t * 0.9f) + 0.4f * Mathf.Sin(t * 2.3f)) * DegreesAtStrengthOne *
AswidConfig.SeaCameraSwayStrength.Value * sway;
rot *= Quaternion.AngleAxis(roll, Vector3.forward);
}
}
/// <summary>
/// Pukeberries empty the fourth stomach too.
///
/// SE_Puke calls RemoveOneFood once a second, and vanilla only ever picks from its own three
/// slots, so the Aswid's fourth meal survived the berries. It now goes into the same random
/// draw as the other three, the way the Trol's extra slots do.
/// </summary>
[HarmonyPatch(typeof(Player), "RemoveOneFood")]
public static class Aswid_PlayerRemoveOneFood_Patch
{
public static bool Prefix(Player __instance, System.Collections.Generic.List<Player.Food> ___m_foods, ref bool __result)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return true;
if (!AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) || extraFood == null) return true;
int vanillaCount = ___m_foods != null ? ___m_foods.Count : 0;
if (Random.Range(0, vanillaCount + 1) < vanillaCount) return true; // one of vanilla's three
AswidFoodManager.ClearFood(__instance);
__result = true;
return false;
} }
} }

View file

@ -44,7 +44,32 @@ namespace RacesOfValheim
{ "Ulv", "TrophyUlv" }, { "Ulv", "TrophyUlv" },
{ "Fenring_Cultist", "TrophyCultist" }, // the prefab is Fenring_Cultist, not "Cultist" { "Fenring_Cultist", "TrophyCultist" }, // the prefab is Fenring_Cultist, not "Cultist"
{ "Asksvin", "TrophyAsksvin" }, { "Asksvin", "TrophyAsksvin" },
{ "Volture", "TrophyVolture" } { "Volture", "TrophyVolture" },
// Valheim 1.0's seals. The baby is Seal_Pup in the prefab list - "baby" is only its
// display token ($enemy_seal_baby). Both wear the one TrophySeal icon.
// The frozen Greydwarfs have no trophy of their own; they borrow the regular one's icon.
{ "Greydwarf_Frozen", "TrophyGreydwarf" },
{ "Greydwarf_Shaman_Frozen", "TrophyGreydwarfShaman" },
{ "Elaking", "TrophyElaking" },
{ "ElakingLantern", "TrophyElaking" },
{ "Moose", "TrophyMoose" },
{ "Moose_calf", "TrophyMoose" },
{ "Barka", "TrophyBarka" },
{ "JotunWarrior", "TrophyJotunWarrior" },
{ "JotunWarriorDualWield", "TrophyJotunWarrior" },
{ "JotunWitch", "TrophyJotunWitch" },
{ "ElakingMole", "TrophyMole" },
{ "GoblinDeepNorth", "TrophyGoblin" },
{ "DvergerDeepNorth", "TrophyDvergr" },
// The Dvergr from before the Deep North, all of them: 90 HP for 25 minutes.
{ "Dverger", "TrophyDvergr" },
{ "DvergerMage", "TrophyDvergr" },
{ "DvergerMageFire", "TrophyDvergr" },
{ "DvergerMageIce", "TrophyDvergr" },
{ "DvergerMageSupport", "TrophyDvergr" },
{ "DvergerAshlands", "TrophyDvergr" },
{ "Seal", "TrophySeal" },
{ "Seal_Pup", "TrophySeal" }
}; };
private static Dictionary<string, string> mobToFoodMap = new Dictionary<string, string> private static Dictionary<string, string> mobToFoodMap = new Dictionary<string, string>
@ -65,7 +90,18 @@ namespace RacesOfValheim
{ "SeekerBrute", "CookedBugMeat" }, { "SeekerBrute", "CookedBugMeat" },
{ "SeekerBrood", "CookedBugMeat" }, { "SeekerBrood", "CookedBugMeat" },
{ "Surtling", "BloodPudding" }, { "Surtling", "BloodPudding" },
{ "Bear", "CookedBearMeat" } { "Bear", "CookedBearMeat" },
// Same meal as the Draugh's raw Seal Blubber: vanilla's Seal Meat Soup, so a seal is
// worth exactly what the soup is, adult or pup.
{ "Greydwarf_Frozen", "SealSoup" },
{ "Greydwarf_Shaman_Frozen", "SealSoup" },
// The Cooked Asksvin Tail (prefab CookedAsksvinMeat), the same meal the Asksvin gives.
{ "Elaking", "CookedAsksvinMeat" },
{ "ElakingLantern", "CookedAsksvinMeat" },
{ "Moose", "CookedMooseMeat" },
{ "Moose_calf", "CookedMooseMeat" },
{ "Seal", "SealSoup" },
{ "Seal_Pup", "SealSoup" }
}; };
public static bool BypassAswidFoodCheck = false; public static bool BypassAswidFoodCheck = false;
@ -155,7 +191,14 @@ namespace RacesOfValheim
if (c != null) if (c != null)
{ {
float foodHp = Mathf.Min(c.m_health / 2f, 150f); float foodHp = Mathf.Min(c.m_health / 2f, 150f);
float burnTime = c.m_health * 2f; // The formula alone only knows how big a creature is, not where it
// lives - a Black Forest troll came out at 150. Only these get the
// per-biome cap in ApplyFoodBalance; the hand-set values below are
// choices, not formula output, and keep theirs.
bool fromFormula = true;
// Capped at 50 minutes: a tough creature like the Barka would otherwise
// feed for over an hour.
float burnTime = Mathf.Min(c.m_health * 2f, 3000f);
// StartsWith("Fenring") already covers Fenring_Cultist. "Fuling" was // StartsWith("Fenring") already covers Fenring_Cultist. "Fuling" was
// never a prefab prefix - the family is Goblin* - so that arm of the // never a prefab prefix - the family is Goblin* - so that arm of the
// test matched nothing until now. // test matched nothing until now.
@ -163,20 +206,38 @@ namespace RacesOfValheim
{ {
burnTime = 1200f; // 20 minutes burnTime = 1200f; // 20 minutes
} }
else if (mobName == "Greyling") { foodHp = 20f; burnTime = 1200f; } else if (mobName == "JotunWitch") { foodHp = 120f; burnTime = 3600f; fromFormula = false; } // 60 minutes
else if (mobName == "Greydwarf") { foodHp = 25f; burnTime = 1200f; } else if (mobName == "ElakingMole") { foodHp = 100f; burnTime = 1800f; fromFormula = false; } // 30 minutes
else if (mobName == "Greydwarf_Shaman") { foodHp = 30f; burnTime = 1200f; } else if (mobName.StartsWith("Dverger") && mobName != "DvergerDeepNorth") { foodHp = 90f; burnTime = 1500f; fromFormula = false; } // 25 minutes
else if (mobName == "Greydwarf_Elite") { foodHp = 60f; burnTime = 1800f; } else if (mobName == "DvergerDeepNorth") { foodHp = 100f; burnTime = 1800f; fromFormula = false; } // 30 minutes
else if (mobName == "Greyling") { foodHp = 20f; burnTime = 1200f; fromFormula = false; }
else if (mobName == "Greydwarf") { foodHp = 25f; burnTime = 1200f; fromFormula = false; }
else if (mobName == "Greydwarf_Shaman") { foodHp = 30f; burnTime = 1200f; fromFormula = false; }
else if (mobName == "Greydwarf_Elite") { foodHp = 60f; burnTime = 1800f; fromFormula = false; }
customItem.ItemDrop.m_itemData.m_shared.m_food = foodHp; customItem.ItemDrop.m_itemData.m_shared.m_food = foodHp;
customItem.ItemDrop.m_itemData.m_shared.m_foodStamina = 0f; customItem.ItemDrop.m_itemData.m_shared.m_foodStamina = 0f;
customItem.ItemDrop.m_itemData.m_shared.m_foodEitr = 0f; customItem.ItemDrop.m_itemData.m_shared.m_foodEitr = 0f;
customItem.ItemDrop.m_itemData.m_shared.m_foodBurnTime = burnTime; customItem.ItemDrop.m_itemData.m_shared.m_foodBurnTime = burnTime;
customItem.ItemDrop.m_itemData.m_shared.m_foodRegen = Mathf.Max(1f, foodHp / 15f); customItem.ItemDrop.m_itemData.m_shared.m_foodRegen = Mathf.Max(1f, foodHp / 15f);
if (fromFormula) formulaFoods.Add(foodName);
} }
} }
} }
// What the item gives before any balance setting, kept so ApplyFoodBalance can be
// rerun from scratch whenever a setting changes or the server's values arrive.
var shared = customItem.ItemDrop.m_itemData.m_shared;
baseFoods[foodName] = new BaseFood
{
Mob = mobName,
Health = shared.m_food,
Stamina = shared.m_foodStamina,
Regen = shared.m_foodRegen,
Shared = shared
};
ApplyFoodBalance(foodName);
GameObject trophyPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(trophyName); GameObject trophyPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(trophyName);
if (trophyPrefab != null) if (trophyPrefab != null)
{ {
@ -192,10 +253,82 @@ namespace RacesOfValheim
} }
} }
private float m_tintCheckTimer = 0f; private class BaseFood
private float sensesCheckTimer = 0f; {
public string Mob;
public float Health;
public float Stamina;
public float Regen;
public ItemDrop.ItemData.SharedData Shared;
}
private Dictionary<Character, GameObject> activeSensesLight = new Dictionary<Character, GameObject>(); private static readonly Dictionary<string, BaseFood> baseFoods = new Dictionary<string, BaseFood>();
private static readonly HashSet<string> formulaFoods = new HashSet<string>();
/// <summary>
/// The biome each edible creature lives in, as a number from 1 (Meadows) to 8 (Deep North).
/// It decides two things: the cap on formula-made foods, and which creatures count as early
/// game (1 and 2) for the larger stamina share. A creature missing here counts as tier 8,
/// which means uncapped in practice and never early.
/// </summary>
private static readonly Dictionary<string, int> mobBiomeTier = new Dictionary<string, int>
{
{ "Boar", 1 }, { "Neck", 1 }, { "Deer", 1 }, { "Greyling", 1 },
{ "Greydwarf", 2 }, { "Greydwarf_Elite", 2 }, { "Greydwarf_Shaman", 2 }, { "Troll", 2 },
{ "Leech", 3 },
{ "Wolf", 4 }, { "Fenring", 4 }, { "Fenring_Cultist", 4 }, { "Ulv", 4 }, { "Hatchling", 4 },
{ "Lox", 5 }, { "Goblin", 5 }, { "GoblinArcher", 5 }, { "GoblinShaman", 5 }, { "GoblinBrute", 5 }, { "Deathsquito", 5 },
{ "Hare", 6 }, { "Seeker", 6 }, { "SeekerBrood", 6 }, { "SeekerBrute", 6 }, { "Gjall", 6 }, { "Tick", 6 },
{ "Dverger", 6 }, { "DvergerMage", 6 }, { "DvergerMageFire", 6 }, { "DvergerMageIce", 6 }, { "DvergerMageSupport", 6 },
{ "Asksvin", 7 }, { "Volture", 7 }, { "DvergerAshlands", 7 },
};
public const int EarlyBiomeTier = 2;
private static int GetBiomeTier(string mob) => mobBiomeTier.TryGetValue(mob, out int tier) ? tier : 8;
/// <summary>
/// Rewrites one devour food from its unbalanced base and the current settings. The Discord
/// reports said even weak kills fed too much health; Dissolution asked for about 10% less,
/// and for early creatures to feed stamina more than health. So: health is scaled first,
/// then a share of it moves over to stamina. Vanilla meals the food was cloned from keep
/// the stamina they already had, the share goes on top.
///
/// Writing the shared data is enough to reach every copy: eaten foods, the extra slot and
/// the tooltip all read the same SharedData through their ItemData.
/// </summary>
private static void ApplyFoodBalance(string foodName)
{
if (!baseFoods.TryGetValue(foodName, out BaseFood food) || food.Shared == null) return;
int tier = GetBiomeTier(food.Mob);
float health = food.Health;
if (formulaFoods.Contains(foodName))
{
health = Mathf.Min(health, AswidConfig.FoodCapBase.Value + AswidConfig.FoodCapPerBiome.Value * tier);
}
float healthMultiplier = AswidConfig.DevourHealthMultiplier.Value;
health *= healthMultiplier;
float share = tier <= EarlyBiomeTier ? AswidConfig.EarlyStaminaShare.Value : AswidConfig.DevourStaminaShare.Value;
float moved = health * share;
food.Shared.m_food = health - moved;
food.Shared.m_foodStamina = food.Stamina + moved;
// Regen follows the health the food ends up giving, cap included, so a troll capped
// to 40 health does not keep the 10 per tick its old 150 earned.
float healthRatio = food.Health > 0f ? food.Shared.m_food / food.Health : 0f;
food.Shared.m_foodRegen = Mathf.Max(1f, food.Regen * healthRatio);
}
/// <summary>Hooked to the balance settings, which also fire when the server's values arrive.</summary>
public static void ApplyAllFoodBalance()
{
foreach (string foodName in baseFoods.Keys) ApplyFoodBalance(foodName);
}
private float m_tintCheckTimer = 0f;
public static float GetEnslaveCooldown() public static float GetEnslaveCooldown()
{ {
@ -237,6 +370,7 @@ namespace RacesOfValheim
{ {
seman.RemoveStatusEffect(myHash); seman.RemoveStatusEffect(myHash);
} }
HunterSenses.Clear();
return; return;
} }
@ -245,64 +379,8 @@ namespace RacesOfValheim
seman.AddStatusEffect(myHash, true); seman.AddStatusEffect(myHash, true);
} }
sensesCheckTimer -= Time.deltaTime; int markHash = "SE_AswidSensesMark".GetStableHashCode();
if (sensesCheckTimer <= 0f) HunterSenses.Tick(AswidConfig.SensesRadius.Value, c => c.GetSEMan().AddStatusEffect(markHash, true));
{
sensesCheckTimer = AswidConfig.SensesRefreshInterval.Value; // TTL is 2s
List<Character> allChars = Character.GetAllCharacters();
Vector3 myPos = Player.m_localPlayer.transform.position;
int markHash = "SE_AswidSensesMark".GetStableHashCode();
HashSet<Character> inRangeChars = new HashSet<Character>();
foreach (var c in allChars)
{
if (c == null || c == Player.m_localPlayer || c.IsDead() || c.IsTamed()) continue;
float dist = Vector3.Distance(c.transform.position, myPos);
if (dist <= AswidConfig.SensesRadius.Value)
{
try
{
inRangeChars.Add(c);
c.GetSEMan().AddStatusEffect(markHash, true); // Keep the malus as requested
// Locally generate the visual
if (!activeSensesLight.ContainsKey(c))
{
GameObject lightObj = new GameObject("AswidSensesLight");
lightObj.transform.SetParent(c.transform);
lightObj.transform.position = c.GetCenterPoint();
Light pLight = lightObj.AddComponent<Light>();
pLight.type = LightType.Point;
pLight.color = Color.green;
pLight.range = AswidConfig.SensesLightRange.Value;
pLight.intensity = AswidConfig.SensesLightIntensity.Value;
pLight.shadows = LightShadows.None;
activeSensesLight[c] = lightObj;
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Aswid] Error processing mob {c.name}: {ex}");
}
}
}
List<Character> keysToRemove = new List<Character>();
foreach (var kvp in activeSensesLight)
{
if (kvp.Key == null || kvp.Key.IsDead() || !inRangeChars.Contains(kvp.Key))
{
if (kvp.Value != null) Destroy(kvp.Value);
keysToRemove.Add(kvp.Key);
}
}
foreach (var k in keysToRemove) activeSensesLight.Remove(k);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -310,15 +388,6 @@ namespace RacesOfValheim
} }
} }
private void ClearSuperhumanSenses()
{
foreach (var kvp in activeSensesLight)
{
if (kvp.Value != null) Destroy(kvp.Value);
}
activeSensesLight.Clear();
}
private bool? wasNight = null; private bool? wasNight = null;
private void Update() private void Update()
@ -372,6 +441,8 @@ namespace RacesOfValheim
{ {
updateTimer = 0f; updateTimer = 0f;
UpdateAswidState(); UpdateAswidState();
UpdateSunlight(UpdateInterval);
UpdateOpenSea(UpdateInterval);
} }
try try
@ -421,7 +492,7 @@ namespace RacesOfValheim
if (EnvMan.instance != null && EnvMan.IsDay() && !isTransformingSequence && if (EnvMan.instance != null && EnvMan.IsDay() && !isTransformingSequence &&
Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{ {
StartCoroutine(RevertMistFormRoutine()); RunFormRoutine(RevertMistFormRoutine());
} }
// Same rule for a night-only bat: a form the sun forbids cannot be kept through the // Same rule for a night-only bat: a form the sun forbids cannot be kept through the
@ -432,7 +503,7 @@ namespace RacesOfValheim
EnvMan.instance != null && EnvMan.IsDay()) EnvMan.instance != null && EnvMan.IsDay())
{ {
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_morning_sun_drives_bat_back")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_morning_sun_drives_bat_back"));
StartCoroutine(RevertToHumanRoutine()); RunFormRoutine(RevertToHumanRoutine());
} }
} }
@ -523,7 +594,7 @@ namespace RacesOfValheim
if (IsTransformed) if (IsTransformed)
{ {
StartCoroutine(RevertToHumanRoutine()); RunFormRoutine(RevertToHumanRoutine());
return; return;
} }
@ -538,18 +609,102 @@ namespace RacesOfValheim
return; return;
} }
StartCoroutine(TransformIntoBatRoutine(rules)); if (AswidConfig.BatEncumbered.Value == AswidConfig.EncumberedMode.Blocked && Player.m_localPlayer.IsEncumbered())
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_too_heavy_for_bat"));
return;
}
// No escaping a fight by taking wing mid-blow: the form waits until the hits stop.
float hurtLeft = AswidConfig.BatCombatLock.Value - (Time.time - LastHurtTime);
if (hurtLeft > 0f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_combat_lock", Mathf.CeilToInt(hurtLeft)));
return;
}
float cooldownLeft = AswidConfig.BatCooldown.Value - (Time.time - lastBatEndTime);
if (cooldownLeft > 0f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_cooldown", Mathf.CeilToInt(cooldownLeft)));
return;
}
RunFormRoutine(TransformIntoBatRoutine(rules));
}
// When the bat form last ended, for the optional cooldown. Starts far enough back that a
// fresh session never begins on cooldown.
private float lastBatEndTime = -100000f;
// When the local player last lost health, for the bat's combat lock. Written by
// Aswid_BatCombatLock_Patch for every race; only the Aswid reads it.
public static float LastHurtTime = -100000f;
// The one bat or mist routine in flight, if any. Kept so ResetRace can stop it: a
// TransformIntoBatRoutine left running through a reset finishes its 1.1s gesture and
// turns a freshly reset Human into a bat.
private Coroutine formRoutine;
private void RunFormRoutine(System.Collections.IEnumerator routine)
{
formRoutine = StartCoroutine(routine);
}
/// <summary>
/// Drops bat and mist form on the spot for ResetRace: no puff, no tween, nothing left
/// running. ForceRevert is no use there - it skips a form that is still mid-gesture, and
/// its coroutine would still be shrinking the body back after the reset has finished.
/// </summary>
/// <returns>True if there was a form to drop.</returns>
public bool HardResetForReset()
{
Player player = Player.m_localPlayer;
if (player == null) return false;
if (formRoutine != null)
{
StopCoroutine(formRoutine);
formRoutine = null;
}
bool hadMist = mistTransformation != null || player.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode());
bool hadBat = IsTransformed || isTransformingSequence;
// Also clears isTransformingSequence and puts the transform back to scale 1, which
// covers a reset caught halfway through the bat's shrink.
HardResetBatForm();
if (hadMist)
{
if (mistTransformation != null)
{
Destroy(mistTransformation);
mistTransformation = null;
}
Transform playerVisual = player.transform.Find("Visual");
PlayerVisualHider.Show(playerVisual, "aswid-reset-mist");
if (playerVisual != null) playerVisual.localScale = Vector3.one;
player.GetSEMan().RemoveStatusEffect("SE_MistForm".GetStableHashCode(), true);
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("Aswid_IsMistForm", false);
}
isTransformingSequence = false;
return hadBat || hadMist;
} }
public void ForceRevert() public void ForceRevert()
{ {
if (IsTransformed && !isTransformingSequence) if (IsTransformed && !isTransformingSequence)
{ {
StartCoroutine(RevertToHumanRoutine()); RunFormRoutine(RevertToHumanRoutine());
} }
if (Player.m_localPlayer != null && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()) && !isTransformingSequence) if (Player.m_localPlayer != null && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()) && !isTransformingSequence)
{ {
StartCoroutine(RevertMistFormRoutine()); RunFormRoutine(RevertMistFormRoutine());
} }
} }
@ -559,7 +714,7 @@ namespace RacesOfValheim
/// Update() has already bailed out on IsDead(), so a coroutine started here would be the /// Update() has already bailed out on IsDead(), so a coroutine started here would be the
/// only thing still running on a corpse. /// only thing still running on a corpse.
/// ///
/// Leaving the form up costs more than a missing animation: m_debugFly stays on, so the /// Leaving the form up costs more than a missing animation: m_flying stays on, so the
/// respawned player floats; Aswid_IsBatForm stays true in the ZDO, so every other client /// respawned player floats; Aswid_IsBatForm stays true in the ZDO, so every other client
/// keeps drawing a bat over a body that is walking around as a person; and the 5% scale /// keeps drawing a bat over a body that is walking around as a person; and the 5% scale
/// stays on the transform. Called from Aswid_BatDiesAsBat_Patch. /// stays on the transform. Called from Aswid_BatDiesAsBat_Patch.
@ -585,12 +740,13 @@ namespace RacesOfValheim
if (nview != null && nview.IsValid()) if (nview != null && nview.IsValid())
{ {
nview.GetZDO().Set("Aswid_IsBatForm", false); nview.GetZDO().Set("Aswid_IsBatForm", false);
nview.GetZDO().Set(ZDOVars.s_debugFly, false);
} }
Traverse.Create(player).Field("m_debugFly").SetValue(false); // Now, not when the destroyed model's OnDestroy gets round to it at the end of the frame.
BatFormBehavior.SetFlying(false);
player.transform.localScale = Vector3.one; player.transform.localScale = Vector3.one;
lastBatEndTime = Time.time;
IsTransformed = false; IsTransformed = false;
activeRules = null; activeRules = null;
isTransformingSequence = false; isTransformingSequence = false;
@ -690,6 +846,7 @@ namespace RacesOfValheim
} }
Player.m_localPlayer.transform.localScale = endScale; Player.m_localPlayer.transform.localScale = endScale;
lastBatEndTime = Time.time;
IsTransformed = false; IsTransformed = false;
activeRules = null; activeRules = null;
isTransformingSequence = false; isTransformingSequence = false;
@ -703,11 +860,11 @@ namespace RacesOfValheim
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{ {
StartCoroutine(RevertMistFormRoutine()); RunFormRoutine(RevertMistFormRoutine());
} }
else else
{ {
StartCoroutine(TransformIntoMistRoutine()); RunFormRoutine(TransformIntoMistRoutine());
} }
} }
@ -974,13 +1131,14 @@ namespace RacesOfValheim
private float damageTickTimer = 0f; private float damageTickTimer = 0f;
/// <summary> /// <summary>
/// The Vampiric Aura drains on its own, in every form, with no key to hold - but it does not /// The Vampiric Aura drains on its own, with no key to hold (as a bat only once
/// BatAuraAllowed says so) - but it does not
/// distinguish traders from monsters, so it can execute Haldor/Hildir on approach. AuraEnabled /// distinguish traders from monsters, so it can execute Haldor/Hildir on approach. AuraEnabled
/// (toggled with Devour on the same key) is the escape hatch for that. /// (toggled with Devour on the same key) is the escape hatch for that.
/// </summary> /// </summary>
private void HandleVampiricAura() private void HandleVampiricAura()
{ {
if (!AuraEnabled) if (!AuraEnabled || (IsBatForm() && !BatAuraAllowed(BossProgressionManager.GetCurrentProgressionState())))
{ {
damageTickTimer = 0f; damageTickTimer = 0f;
return; return;
@ -993,6 +1151,24 @@ namespace RacesOfValheim
PerformLifeDrain(); PerformLifeDrain();
} }
private static bool IsBatForm()
{
return Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_BatForm".GetStableHashCode());
}
/// <summary>
/// Whether the aura drains while the player is a bat. Off until the Queen by default: a bat
/// gliding over enemies that cannot reach it, draining them the whole way, was the "unfun
/// optimal way to play" Dissolution reported. The flag turns it back on for everyone; the
/// unlock state brings it back as a late-game reward, 0 meaning never.
/// </summary>
public static bool BatAuraAllowed(int state)
{
if (AswidConfig.AuraInBatForm.Value) return true;
int unlock = AswidConfig.BatAuraUnlockState.Value;
return unlock > 0 && state >= unlock;
}
/// <summary>Half damage as a human, full as a bat, double as mist.</summary> /// <summary>Half damage as a human, full as a bat, double as mist.</summary>
private float GetAuraFormMultiplier() private float GetAuraFormMultiplier()
{ {
@ -1015,6 +1191,7 @@ namespace RacesOfValheim
int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost"); int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost");
var colliders = Physics.OverlapSphere(center, radius, layerMask); var colliders = Physics.OverlapSphere(center, radius, layerMask);
bool hitCreature = false;
foreach (var col in colliders) foreach (var col in colliders)
{ {
@ -1065,10 +1242,16 @@ namespace RacesOfValheim
// kill). ApplyDamage() skipped all of that: it edited the local copy of a // kill). ApplyDamage() skipped all of that: it edited the local copy of a
// character we usually do not own, and the owner overwrote it on the next sync. // character we usually do not own, and the owner overwrote it on the next sync.
c.Damage(hd); c.Damage(hd);
hitCreature = true;
SpawnBloodVFX(c); SpawnBloodVFX(c);
} }
} }
// The aura scales with Blood Magic but called Damage directly, so it never paid
// the skill back. Passive and always on, so it earns what the Skadi's Frost Aura
// does: a tenth of a hit per second of draining, once per tick, not per victim.
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.BloodMagic, 0.1f * AswidConfig.AuraTickInterval.Value);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -1161,7 +1344,8 @@ namespace RacesOfValheim
{ {
// Show the Vae Victis message in the center of the screen // Show the Vae Victis message in the center of the screen
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_vae_victis")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_vae_victis"));
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_ate " + addedItem.m_shared.m_name); // "$msg_ate" exists in no vanilla table and players saw [msg_ate]; vanilla's "Consumed" reads the same.
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_consumed " + addedItem.m_shared.m_name);
// Vae Victis XP logic - similar to Dead Raiser // Vae Victis XP logic - similar to Dead Raiser
Player.m_localPlayer.RaiseSkill(Skills.SkillType.BloodMagic, 1f); Player.m_localPlayer.RaiseSkill(Skills.SkillType.BloodMagic, 1f);
@ -1173,7 +1357,10 @@ namespace RacesOfValheim
// up, but there used to be nothing to see either. Silence is what made // up, but there used to be nothing to see either. Silence is what made
// a refused meal indistinguishable from a devour that never fired: // a refused meal indistinguishable from a devour that never fired:
// vanilla's own "can't eat more" line, localized for free. // vanilla's own "can't eat more" line, localized for free.
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_nomore"); // The token carries a $1 for the food's name, which vanilla's CanEat
// fills in; sent bare, players read "can't eat more $1".
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft,
Localization.instance.Localize("$msg_nomore", addedItem.m_shared.m_name));
} }
} }
else else
@ -1222,6 +1409,136 @@ namespace RacesOfValheim
} }
} }
/// <summary>Fader's Surtling form ends it, unless the setting keeps it for good.</summary>
public static bool HasFireWeakness(int state)
{
if (!AswidConfig.FireWeaknessEnabled.Value) return false;
return !(AswidConfig.FaderRemovesFireWeakness.Value && state >= 8);
}
private static readonly int SunlightHash = "SE_AswidSunlight".GetStableHashCode();
/// <summary>
/// The V Rising weakness: by day, under open sky, the sun saps the Aswid. Anything that
/// keeps the sky off you counts as shade - a roof by vanilla's own shelter test, a dungeon,
/// the Swamp's and Mistlands' gloom, the night, and the Aswid's own Eclipse, which makes
/// that spell an answer to the sun rather than only a damage boost.
/// </summary>
private void UpdateSunlight(float dt)
{
Player player = Player.m_localPlayer;
SEMan seman = player.GetSEMan();
bool exposed = InSunlight(player);
bool has = seman.HaveStatusEffect(SunlightHash);
if (!exposed)
{
if (has) seman.RemoveStatusEffect(SunlightHash, true);
return;
}
if (!has) seman.AddStatusEffect(SunlightHash, true);
(seman.GetStatusEffect(SunlightHash) as SE_AswidSunlight)?.Refresh();
// SetHealth rather than Damage or UseHealth: a burn every second should not stagger,
// interrupt a swing or flash the screen red each time. Never below the floor, so
// the sun can wear you down but never be what kills you.
float floor = player.GetMaxHealth() * AswidConfig.SunHealthFloor.Value;
float health = player.GetHealth();
float loss = AswidConfig.SunHealthLossPerSecond.Value * dt;
if (loss > 0f && health > floor)
{
player.SetHealth(Mathf.Max(floor, health - loss));
}
}
private bool InSunlight(Player player)
{
if (!AswidConfig.SunlightEnabled.Value) return false;
if (EnvMan.instance == null || !EnvMan.IsDay()) return false;
if (IsEclipseActive) return false;
if (player.InInterior() || player.InShelter()) return false;
Heightmap.Biome biome = player.GetCurrentBiome();
return biome != Heightmap.Biome.Swamp && biome != Heightmap.Biome.Mistlands;
}
private static readonly int OpenSeaHash = "SE_AswidOpenSea".GetStableHashCode();
// How deep the water under an airborne Aswid has to be before it counts. Keeps a hop over
// a puddle or a swamp ditch from registering; a bat over a river or a lake still does.
private const float MinFlyOverDepth = 1f;
/// <summary>True while the local Aswid is out on the water, boat or not. Read by the camera sway.</summary>
public static bool OnWater { get; private set; }
/// <summary>
/// Dagaz's running water: open water burns and drains an Aswid in it or over it, swimming
/// or flying - a bat cannot simply cross a lake or the sea. A boat carries you across, as
/// the lore allows: on board there is no burn and no drain, but the sea still turns your
/// stomach, so the camera keeps swaying.
/// </summary>
private void UpdateOpenSea(float dt)
{
Player player = Player.m_localPlayer;
SEMan seman = player.GetSEMan();
bool onBoat = OnBoat(player);
bool exposed = !onBoat && InOpenWater(player);
OnWater = AswidConfig.RunningWaterEnabled.Value && (exposed || (onBoat && BiomeAllowed(player)));
bool has = seman.HaveStatusEffect(OpenSeaHash);
if (!exposed)
{
if (has) seman.RemoveStatusEffect(OpenSeaHash, true);
return;
}
if (!has) seman.AddStatusEffect(OpenSeaHash, true);
float drain = AswidConfig.SeaStaminaDrainPerSecond.Value * dt;
if (drain > 0f) player.UseStamina(drain);
// SetHealth for the same reasons as the sun: no stagger, no flash each second.
float floor = player.GetMaxHealth() * AswidConfig.SeaHealthFloor.Value;
float health = player.GetHealth();
float loss = AswidConfig.SeaHealthLossPerSecond.Value * dt;
if (loss > 0f && health > floor)
{
player.SetHealth(Mathf.Max(floor, health - loss));
}
}
private static bool OnBoat(Player player)
{
return player.GetStandingOnShip() != null || player.IsAttachedToShip() || player.GetControlledShip() != null;
}
/// <summary>The Ocean-only setting, if on, limits everything here to the sea.</summary>
private static bool BiomeAllowed(Player player)
{
return !AswidConfig.WaterOceanOnly.Value || player.GetCurrentBiome() == Heightmap.Biome.Ocean;
}
/// <summary>
/// In water or over it. Valheim has one water plane for the sea, the rivers and the lakes
/// alike, so "the terrain under you is below the water level" finds all three. Swimming
/// counts wherever it happens. In the air it takes a metre of water below, so a jump over
/// a puddle does not; standing on anything solid - a dock, a bridge, a shallow bank you
/// are wading on - does not count, since the ground ray only sees terrain and would
/// otherwise read a dock as open water.
/// </summary>
private static bool InOpenWater(Player player)
{
if (!AswidConfig.RunningWaterEnabled.Value) return false;
if (!BiomeAllowed(player)) return false;
if (player.IsSwimming()) return true;
if (player.IsOnGround() || ZoneSystem.instance == null) return false;
float depth = ZoneSystem.instance.m_waterLevel - ZoneSystem.instance.GetGroundHeight(player.transform.position);
return depth >= MinFlyOverDepth;
}
private void UpdateAswidState() private void UpdateAswidState()
{ {
AswidSpectralClaw.PurgeAll(Player.m_localPlayer); // feature disabled for now, see AswidSpectralClaw.cs AswidSpectralClaw.PurgeAll(Player.m_localPlayer); // feature disabled for now, see AswidSpectralClaw.cs
@ -1246,6 +1563,12 @@ namespace RacesOfValheim
} }
} }
/// <summary>Max stamina the race adds on top of food, at the given progression state.</summary>
public static float GetStaminaBonus(int state)
{
return AswidConfig.BaseStaminaBonus.Value + AswidConfig.StaminaBonusPerState.Value * state;
}
public static bool IsAswid() public static bool IsAswid()
{ {
return Player.m_localPlayer != null && return Player.m_localPlayer != null &&

View file

@ -65,6 +65,45 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// Sunlight on an exposed Aswid. Its numbers are rewritten from AswidConfig every time
/// AswidRace.UpdateSunlight runs, so a slider moves them live; the health loss is not a stat
/// and is applied by that same tick.
/// </summary>
public class SE_AswidSunlight : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_AswidSunlight";
m_name = "$rov_se_aswid_sunlight_name";
m_tooltip = "$rov_se_aswid_sunlight_tooltip";
Refresh();
}
public void Refresh()
{
m_healthRegenMultiplier = 1f - AswidConfig.SunHealthRegenPenalty.Value;
m_staminaRegenMultiplier = 1f - AswidConfig.SunStaminaRegenPenalty.Value;
m_speedModifier = -AswidConfig.SunSpeedPenalty.Value;
}
}
/// <summary>
/// Open water under an Aswid off a boat. Only a marker: the burn and the drain are applied by
/// AswidRace.UpdateOpenSea, and the camera sway reads AswidRace.OnWater.
/// </summary>
public class SE_AswidOpenSea : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_AswidOpenSea";
m_name = "$rov_se_aswid_opensea_name";
m_tooltip = "$rov_se_aswid_opensea_tooltip";
}
}
public class SE_MistForm : SE_Stats public class SE_MistForm : SE_Stats
{ {
public override void Setup(Character character) public override void Setup(Character character)
@ -124,6 +163,16 @@ namespace RacesOfValheim
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(batForm, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(batForm, fixReference: false));
var sunlight = ScriptableObject.CreateInstance<SE_AswidSunlight>();
sunlight.name = "SE_AswidSunlight";
sunlight.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySurtling")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sunlight, fixReference: false));
var openSea = ScriptableObject.CreateInstance<SE_AswidOpenSea>();
openSea.name = "SE_AswidOpenSea";
openSea.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySerpent")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(openSea, fixReference: false));
var mistForm = ScriptableObject.CreateInstance<SE_MistForm>(); var mistForm = ScriptableObject.CreateInstance<SE_MistForm>();
mistForm.name = "SE_MistForm"; mistForm.name = "SE_MistForm";
mistForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith")?.m_itemData.m_shared.m_icons[0]; mistForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith")?.m_itemData.m_shared.m_icons[0];

View file

@ -58,6 +58,12 @@ namespace RacesOfValheim
private const float BaseEyeHeight = 0.181f; private const float BaseEyeHeight = 0.181f;
private const float BaseEyeSeparation = 0.032f; private const float BaseEyeSeparation = 0.032f;
// The borrowed socket at the size the Skeleton wears it, times the config multiplier, was
// two green blocks on the face; at half it was smaller than the painted eye underneath,
// which then showed round it. Applied before the multiplier, so a saved config keeps its
// meaning as "relative to the default".
private const float BaseEyeScale = 0.75f;
// ─── Race check ───────────────────────────────────────────────────── // ─── Race check ─────────────────────────────────────────────────────
/// <summary> /// <summary>
@ -99,6 +105,10 @@ namespace RacesOfValheim
// built again rather than merely moved. // built again rather than merely moved.
public string SourceModel = ""; public string SourceModel = "";
public bool FlatShader; public bool FlatShader;
// Which body the base pose was measured for: the female face puts the eyes elsewhere
// (PlayerFace), so a change of body model is a rebuild too.
public bool Female;
} }
/// <summary>The pose an eye was authored at on the creature. Everything else is a delta on this.</summary> /// <summary>The pose an eye was authored at on the creature. Everything else is a delta on this.</summary>
@ -180,7 +190,8 @@ namespace RacesOfValheim
EyeFrame existing = eyes.GetComponent<EyeFrame>(); EyeFrame existing = eyes.GetComponent<EyeFrame>();
if (existing == null || if (existing == null ||
existing.SourceModel != AswidConfig.EyeSourceModel.Value || existing.SourceModel != AswidConfig.EyeSourceModel.Value ||
existing.FlatShader != AswidConfig.EyeFlatColorShader.Value) existing.FlatShader != AswidConfig.EyeFlatColorShader.Value ||
existing.Female != PlayerFace.IsFemale(player))
{ {
eyes.name = EyesName + "_Removed"; eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject); Object.Destroy(eyes.gameObject);
@ -309,9 +320,6 @@ namespace RacesOfValheim
float scale = GetPlayerScale(player) * toLocal; float scale = GetPlayerScale(player) * toLocal;
Vector3 shift = frame.LocalForward * (AswidConfig.EyeForwardOffset.Value * scale)
+ frame.LocalUp * (AswidConfig.EyeHeightOffset.Value * scale);
for (int i = 0; i < holder.childCount; i++) for (int i = 0; i < holder.childCount; i++)
{ {
Transform eye = holder.GetChild(i); Transform eye = holder.GetChild(i);
@ -324,6 +332,16 @@ namespace RacesOfValheim
float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight)); float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight));
if (side == 0f) side = i == 0 ? -1f : 1f; if (side == 0f) side = i == 0 ? -1f : 1f;
// This eye's hand corrections (RaceEyeTuning), on top of the race's own offsets.
RaceEyeTuning.Eye tuning = RaceEyeTuning.For("Aswid", player, side);
float forward = AswidConfig.EyeForwardOffset.Value + (tuning != null ? tuning.Forward : 0f);
float height = AswidConfig.EyeHeightOffset.Value + (tuning != null ? tuning.Height : 0f);
float separation = AswidConfig.EyeSeparationOffset.Value + (tuning != null ? tuning.Separation : 0f);
float size = AswidConfig.EyeSizeMultiplier.Value * (tuning != null ? tuning.Size : 1f);
Vector3 shift = frame.LocalForward * (forward * scale)
+ frame.LocalUp * (height * scale);
// YAW IS MIRRORED, the other two are not. Turning both eyes the same way on Y // YAW IS MIRRORED, the other two are not. Turning both eyes the same way on Y
// makes the pair look sideways - both point off the same shoulder, because a face // makes the pair look sideways - both point off the same shoulder, because a face
// is symmetric about its centre line and yaw is the axis that crosses it. Negating // is symmetric about its centre line and yaw is the axis that crosses it. Negating
@ -332,15 +350,31 @@ namespace RacesOfValheim
// //
// Pitch and roll are shared deliberately: both eyes looking up is a face looking // Pitch and roll are shared deliberately: both eyes looking up is a face looking
// up, and mirroring either of those would cross them instead of aiming them. // up, and mirroring either of those would cross them instead of aiming them.
//
// This twist is on the HEAD BONE's raw axes (it multiplies from the left), and on
// this rig those are not the face's: bone X points out of the face and bone Z
// sideways. The defaults were dialled in against that, so it stays as it is.
Quaternion twist = Quaternion.Euler( Quaternion twist = Quaternion.Euler(
AswidConfig.EyeRotationX.Value, AswidConfig.EyeRotationX.Value,
AswidConfig.EyeRotationY.Value * side, AswidConfig.EyeRotationY.Value * side,
AswidConfig.EyeRotationZ.Value); AswidConfig.EyeRotationZ.Value);
// The RaceEyeTuning corrections turn the eye on the FACE's axes instead: conjugated by
// the face frame, X tips it, Y turns it toward the temple and Z raises the outer
// corner, the same on both eyes. Added to the bone-axis twist above, X rolled the
// eyes and a mirrored Z tipped one up and the other down.
Quaternion nudge = Quaternion.identity;
if (tuning != null)
{
nudge = authored.Rotation
* Quaternion.Euler(tuning.RotX, tuning.RotY * side, tuning.RotZ * side)
* Quaternion.Inverse(authored.Rotation);
}
eye.localPosition = authored.Position + shift + eye.localPosition = authored.Position + shift +
frame.LocalRight * (side * AswidConfig.EyeSeparationOffset.Value * scale); frame.LocalRight * (side * separation * scale);
eye.localRotation = twist * authored.Rotation; eye.localRotation = nudge * twist * authored.Rotation;
eye.localScale = authored.Scale * AswidConfig.EyeSizeMultiplier.Value; eye.localScale = authored.Scale * size;
} }
} }
@ -424,6 +458,12 @@ namespace RacesOfValheim
MeasureFrame(player, headBone, frame); MeasureFrame(player, headBone, frame);
frame.SourceModel = modelName; frame.SourceModel = modelName;
frame.FlatShader = AswidConfig.EyeFlatColorShader.Value; frame.FlatShader = AswidConfig.EyeFlatColorShader.Value;
frame.Female = PlayerFace.IsFemale(player);
float baseHeight = BaseEyeHeight;
float baseSeparation = BaseEyeSeparation;
float baseSize = BaseEyeScale;
PlayerFace.AdjustEyes(player, ref baseHeight, ref baseSeparation, ref baseSize);
// canonicalToFrame turns "face forward, as authored" into "face forward, on THIS // canonicalToFrame turns "face forward, as authored" into "face forward, on THIS
// rig's own axes" - the rotation that carries the ordinary (X,Y,Z) convention onto // rig's own axes" - the rotation that carries the ordinary (X,Y,Z) convention onto
@ -458,8 +498,8 @@ namespace RacesOfValheim
float toLocal = 1f / headBone.lossyScale.x; float toLocal = 1f / headBone.lossyScale.x;
Vector3 basePosition = frame.LocalForward * (BaseEyeForward * toLocal) Vector3 basePosition = frame.LocalForward * (BaseEyeForward * toLocal)
+ frame.LocalUp * (BaseEyeHeight * toLocal) + frame.LocalUp * (baseHeight * toLocal)
+ frame.LocalRight * (side * BaseEyeSeparation * toLocal); + frame.LocalRight * (side * baseSeparation * toLocal);
// The socket's own authored tilt is skipped for the same reason its position is - // The socket's own authored tilt is skipped for the same reason its position is -
// canonicalToFrame alone (face forward, on this rig's axes) is what the config's // canonicalToFrame alone (face forward, on this rig's axes) is what the config's
@ -481,7 +521,7 @@ namespace RacesOfValheim
// this object at on a real skeleton. Divided into the new parent's scale, the pair // this object at on a real skeleton. Divided into the new parent's scale, the pair
// lands at exactly the size vanilla wears them, which is the whole point of // lands at exactly the size vanilla wears them, which is the whole point of
// borrowing them instead of drawing spheres. // borrowing them instead of drawing spheres.
Vector3 baseScale = source.lossyScale * toLocal; Vector3 baseScale = source.lossyScale * (toLocal * baseSize);
// Remembered before anything moves it, because everything the config does is // Remembered before anything moves it, because everything the config does is
// expressed as a delta on this. // expressed as a delta on this.

View file

@ -1,86 +1,169 @@
using HarmonyLib; using HarmonyLib;
using UnityEngine; using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim namespace RacesOfValheim
{ {
/// <summary> /// <summary>
/// The bat's flight, held on for as long as the worn model exists. /// The bat's flight, held on for as long as the worn model exists.
/// ///
/// Debug fly has two halves, and this used to write only one. The field Player.m_debugFly is /// The bat flies on Character.m_flying and is steered by DirectedFlightPatch, the same
/// what the local player's own physics reads; ZDOVars.s_debugFly is what every OTHER client /// controls as the Skadi's drake; this class only hands over the bat's own numbers and keeps
/// reads, because Character.IsDebugFlying consults the ZDO whenever it is not the owner. With /// the flag up. It used to fly on vanilla's debug-fly flag, which ignored carry weight, cost
/// only the field written, a bat flew on its own screen and fell, walked and swam on everyone /// nothing, moved at 50 m/s and made every monster blind to the player - the Discord reports
/// else's - the fault WarVultureMount.SetFlying already names in its own summary. Both halves /// that started the 2026 rebalance.
/// go through SetFlying below now, so there is one place that can ever get it wrong again.
/// ///
/// Writing the ZDO every frame is not network spam: ZDO.Set(int, bool) bottoms out in /// Other clients learn the bat is airborne from Aswid_IsBatForm in the ZDO, which
/// ZDOExtraData.Set, which returns false when the value is unchanged, and only a true return /// Aswid_MultiplayerVisuals_Patch mirrors into their copy's m_flying.
/// bumps the data revision. Read out of the assembly rather than assumed, because "every frame" ///
/// deserved the check. /// FREE FLIGHT. A player who picks it (or a server that forces it, AswidConfig.UsesFreeBatFlight)
/// gets the old flight back: vanilla's debug fly, both halves (the field for the local physics,
/// s_debugFly in the ZDO for everyone else), and no DirectedFlight. The mode is read once, when
/// the form goes up. AswidBatForm keeps monsters seeing and hurting a free-flying bat.
/// </summary> /// </summary>
public class BatFormBehavior : MonoBehaviour public class BatFormBehavior : MonoBehaviour, IDirectedFlyer
{ {
private static readonly System.Reflection.FieldInfo FlyingField =
AccessTools.Field(typeof(Character), "m_flying");
private static readonly System.Reflection.FieldInfo DebugFlyField = private static readonly System.Reflection.FieldInfo DebugFlyField =
AccessTools.Field(typeof(Player), "m_debugFly"); AccessTools.Field(typeof(Player), "m_debugFly");
private Animator anim; private Animator anim;
private AswidProgression.FormRules formRules; private AswidProgression.FormRules formRules;
private float startTime;
private bool warnedTooHeavy;
private bool expired;
private bool free;
public void Initialize(AswidProgression.FormRules rules) public void Initialize(AswidProgression.FormRules rules)
{ {
this.formRules = rules; this.formRules = rules;
} }
// ─── IDirectedFlyer ─────────────────────────────────────────────────────
// A bat is never grounded on purpose: it flies for as long as the form lasts.
public bool IsFlying => true;
public float LastPoweredTime { get; set; }
public float TurnSpeed => AswidConfig.BatTurnSpeed.Value;
public float GlideSpeed => AswidConfig.BatGlideSpeed.Value;
public float BoostSpeed => AswidConfig.BatBoostSpeed.Value;
public float SprintSpeed => AswidConfig.BatSprintSpeed.Value;
public float ReverseSpeed => AswidConfig.BatReverseSpeed.Value;
public float LiftoffSpeed => AswidConfig.BatLiftoffSpeed.Value;
public float HoverSeconds => AswidConfig.BatHoverSeconds.Value;
public float PoweredStaminaPerSecond => AswidConfig.BatPoweredStaminaPerSecond.Value * EncumberedCostFactor();
public float SprintStaminaPerSecond => AswidConfig.BatSprintStaminaPerSecond.Value * EncumberedCostFactor();
public bool CanPower => !(IsEncumbered() && AswidConfig.BatEncumbered.Value == AswidConfig.EncumberedMode.Blocked);
private static bool IsEncumbered()
{
return Player.m_localPlayer != null && Player.m_localPlayer.IsEncumbered();
}
private static float EncumberedCostFactor()
{
return IsEncumbered() ? 1f + AswidConfig.BatEncumberedExtraCost.Value : 1f;
}
/// <summary>
/// The form's lifetime in seconds at the current state, or 0 for no limit. The per-state
/// bonus is Dissolution's "scales with boss progression", and only means anything on top
/// of a base limit.
/// </summary>
public static float MaxDuration()
{
float max = AswidConfig.BatMaxDuration.Value;
if (max <= 0f) return 0f;
return max + AswidConfig.BatDurationPerState.Value * BossProgressionManager.GetCurrentProgressionState();
}
private void Start() private void Start()
{ {
anim = GetComponentInChildren<Animator>(); anim = GetComponentInChildren<Animator>();
SetFlying(true); startTime = Time.time;
LastPoweredTime = Time.time;
free = AswidConfig.UsesFreeBatFlight();
if (!free) DirectedFlight.Register(this);
Hold();
} }
private void Update() private void Update()
{ {
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return; Player player = Player.m_localPlayer;
if (player == null || player.IsDead()) return;
// Ensure flight remains on continuously // Held every frame rather than set once, for the same reason the debug-fly flag was:
SetFlying(true); // anything that clears it mid-form (a vanilla reset, another mod) would drop the bat
// into walking with the model still on.
Hold();
// Free Flight ignores weight, so only Stamina Flight warns about it.
if (!free)
{
if (!CanPower && !warnedTooHeavy)
{
warnedTooHeavy = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_too_heavy_to_beat"));
}
else if (CanPower)
{
warnedTooHeavy = false;
}
}
float max = MaxDuration();
if (max > 0f && !expired && Time.time - startTime >= max && AswidRace.Instance != null)
{
expired = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_form_fades"));
AswidRace.Instance.ForceRevert();
}
// Sync Animator
if (anim != null) if (anim != null)
{ {
Vector3 vel = Player.m_localPlayer.GetVelocity(); Vector3 vel = player.GetVelocity();
vel.y = 0f; vel.y = 0f;
float speed = vel.magnitude; anim.SetFloat("forward_speed", vel.magnitude);
// Bats don't necessarily have a complex animator like players,
// but if they do have a speed or flying parameter, we set it here.
anim.SetFloat("forward_speed", speed);
anim.SetBool("flying", true); anim.SetBool("flying", true);
} }
} }
private void OnDestroy() private void OnDestroy()
{ {
DirectedFlight.Unregister(this);
SetFlying(false); SetFlying(false);
} }
private void Hold()
{
if (free) SetDebugFly(true);
else SetFlying(true);
}
/// <summary> /// <summary>
/// Both halves of debug fly, always together. The field write survives a missing or invalid /// The local half of Stamina Flight. The remote half is the Aswid_IsBatForm ZDO flag
/// ZNetView on purpose: without it a bat whose networking went away mid-flight would keep /// AswidRace already writes, so there is nothing to replicate here. Turning it off also
/// flying on foot forever, which is the worse of the two failures. /// turns debug fly off, so every exit path ends both flights whichever one was up.
/// </summary> /// </summary>
private static void SetFlying(bool flying) public static void SetFlying(bool flying)
{ {
Player player = Player.m_localPlayer; Player player = Player.m_localPlayer;
if (player == null) return; if (player == null) return;
if (FlyingField != null) FlyingField.SetValue(player, flying);
if (!flying) SetDebugFly(false);
}
/// <summary>
/// Both halves of debug fly, for Free Flight. The ZDO write every frame is not network
/// spam: ZDO.Set returns early when the value is unchanged.
/// </summary>
private static void SetDebugFly(bool flying)
{
Player player = Player.m_localPlayer;
if (player == null) return;
if (DebugFlyField != null) DebugFlyField.SetValue(player, flying); if (DebugFlyField != null) DebugFlyField.SetValue(player, flying);
ZNetView nview = player.GetComponent<ZNetView>(); ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.IsOwner()) if (nview != null && nview.IsValid() && nview.IsOwner()) nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
{
nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
}
} }
} }
} }

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,368 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Bone Ship, first piece: the small one, a clone of the Karve. See Skeleton_BoneShip.txt, sections
/// 2, 10 and 11 - every number and node name below was read off the game, not remembered.
///
/// WHAT THIS STEP DOES
/// - A new buildable ship, BoneKarve, cloned from "Karve" so the vanilla one is left alone.
/// - A hull that is rotten from the first day: WearNTear is pointed at the prefab's own worn hull as
/// its "new" one, so full health shows the worn model, and a light tint goes on top. The game's
/// SetHealthVisual guards the equal case (it only turns a visual off when it differs from the new
/// one), so m_new == m_worn is a supported shape, not a trick. The fresh hull is switched off in
/// the prefab or both would show at once.
/// - It goes where the sails are not: the wind-independent push (SailK) and a sail that never
/// unfurls, in BoneShipSailForcePatch and BoneShipSailPatch below.
///
/// WHAT IS NOT HERE YET: the torn sail texture, the bones, the rowers, the figurehead, the altar, the
/// roster and the archers. Each is its own step. The archer's mount already exists (ShipMount.cs).
/// </summary>
public static class BoneShip
{
// Every vanilla ship but the Raft has a bone version (the design, 2026-10-05). The names are what
// ShipMountTest's post table and the rest of the Bone Ship know them by.
public const string KarveName = "BoneKarve";
public const string LongshipName = "BoneLongship";
public const string AshlandsName = "BoneAshlands";
/// <summary>The hover name of the altar on the deck, where bone fragments are offered.</summary>
public const string AltarName = "$rov_piece_boneship_altar_name";
/// <summary>
/// Places in the roster, melee and archers, by ship (Skeleton_BoneShip.txt 5.7). The small ship is
/// the pile's idea at half size, the Longship a pile's 4+4, and the Ashlands ship - the biggest hull,
/// three times the Karve's mass - 6+6 (decided). Constants, because the answer is a balance call.
/// The rowers' seats follow: one per place, half on each side.
/// </summary>
private const int KarveMelee = 2, KarveRanged = 2;
private const int LongshipMelee = 4, LongshipRanged = 4;
private const int AshlandsMelee = 6, AshlandsRanged = 6;
public static int MeleeCapOf(Component ship) =>
IsKarve(ship) ? KarveMelee : IsAshlands(ship) ? AshlandsMelee : LongshipMelee;
public static int RangedCapOf(Component ship) =>
IsKarve(ship) ? KarveRanged : IsAshlands(ship) ? AshlandsRanged : LongshipRanged;
private static bool IsAshlands(Component ship)
{
return ship != null && ship.name.StartsWith(AshlandsName);
}
private static bool IsKarve(Component ship)
{
return ship != null && ship.name.StartsWith(KarveName);
}
public static bool IsKarveShip(Component ship) => IsKarve(ship);
/// <summary>Half the length of the hull, read from the OnboardTrigger every ship carries.</summary>
public static float HalfLengthOf(Component ship)
{
Transform trigger = ship != null ? ship.transform.Find("OnboardTrigger") : null;
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
return box != null ? Mathf.Abs(box.size.z * trigger.localScale.z) * 0.5f : 0f;
}
/// <summary>Our prefab, the vanilla one it is cloned from, and the localisation key stem.</summary>
private struct Spec
{
public string Name;
public string Source;
public string KeyStem;
public Spec(string name, string source, string keyStem) { Name = name; Source = source; KeyStem = keyStem; }
}
private static readonly Spec[] Specs =
{
new Spec(KarveName, "Karve", "karve"),
new Spec(LongshipName, "VikingShip", "longship"),
new Spec(AshlandsName, "VikingShip_Ashlands", "ashlands"),
};
private static string DisplayKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_name";
private static string DescriptionKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_desc";
/// <summary>
/// What the oarsmen push with, as a share of what a perfect wind would. Wind direction and strength
/// no longer matter, so this is the whole sail. The vanilla factor is angle * lerp(0.25, 1, wind):
/// 1.0 is the best a real wind can ever do, and a good breeze on a good heading is about 0.7. Measured
/// on a Karve at Full: 0.46 gave 4.5 m/s. 0.75 is the proposal; to be tuned with an F8 at cruise.
/// </summary>
public const float SailK = 0.75f;
/// <summary>The key part of every bone ship's recipe: the swamp's Wishbone. One per ship.</summary>
private const string WishbonePrefab = "Wishbone";
/// <summary>
/// What each costs. The Wishbone is the decided part; the rest are PLACEHOLDERS that grow with the
/// hull, and the Ashlands one asks for the fine wood a late-game ship would. The workbench requirement
/// comes from the vanilla ship each one is cloned from. Open to every race: nothing here, or on the
/// pieces, asks who is building.
/// </summary>
private static RequirementConfig[] CostOf(string name)
{
switch (name)
{
case KarveName:
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("Wood", 30, 0, true),
new RequirementConfig("BoneFragments", 60, 0, true),
new RequirementConfig("Resin", 10, 0, true),
};
case LongshipName:
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("Wood", 60, 0, true),
new RequirementConfig("BoneFragments", 120, 0, true),
new RequirementConfig("Resin", 20, 0, true),
};
default: // the Ashlands one
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("FineWood", 60, 0, true),
new RequirementConfig("BoneFragments", 200, 0, true),
new RequirementConfig("Resin", 30, 0, true),
};
}
}
/// <summary>Multiplied into the worn hull's colour: a touch darker and greener on top of the worn one.</summary>
private static readonly Color RotTint = new Color(0.80f, 0.82f, 0.72f, 1f);
public static bool IsBoneShip(Ship ship)
{
return ship != null && ship.GetComponent<BoneShipMarker>() != null;
}
public static void Register()
{
BoneShipArcher.Register();
foreach (Spec spec in Specs)
{
RegisterShip(spec);
}
}
private static void RegisterShip(Spec spec)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(spec.Name, spec.Source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{spec.Source}'; {spec.Name} is not registered.");
return;
}
prefab.AddComponent<BoneShipMarker>();
RotHull(prefab, spec.Name);
BoneShipSail.Apply(prefab, spec.Name);
// The roster (the altar's bookkeeping and the troops) and the fittings (bones and the altar
// itself, built when the ship is in the world). The roster registers its RPC in Awake.
prefab.AddComponent<BoneShipRoster>();
prefab.AddComponent<BoneShipFittings>();
prefab.AddComponent<BoneShipRowers>(); // the oarsmen; how many show is the roster's count
Piece piece = prefab.GetComponent<Piece>();
if (piece == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] The cloned '{spec.Source}' has no Piece; {spec.Name} is not registered.");
return;
}
piece.m_name = DisplayKey(spec);
piece.m_description = DescriptionKey(spec);
Sprite icon = BorrowIcon("TrophySkeleton");
if (icon != null) piece.m_icon = icon;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = DisplayKey(spec),
Description = DescriptionKey(spec),
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Misc,
CraftingStation = CraftingStations.Workbench,
Icon = icon,
Requirements = CostOf(spec.Name),
}));
}
/// <summary>
/// Worn hull from full health. Every vanilla ship keeps its three hull visuals where WearNTear can
/// name them - m_new, m_worn, m_broken - whatever the node path (Karve: ship/visual_new,
/// Longship and Ashlands: ship/visual/hull_new), so the clone's own fields are read instead of a
/// path per ship. The fresh one is on in the prefab and has to be switched off, or both would show.
/// </summary>
private static void RotHull(GameObject prefab, string name)
{
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear == null || wear.m_new == null || wear.m_worn == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] {name}: WearNTear has no new/worn hull to swap; the hull stays as it is.");
return;
}
GameObject fresh = wear.m_new;
GameObject worn = wear.m_worn;
if (fresh == worn) return;
wear.m_new = worn;
fresh.SetActive(false);
Tint(worn, RotTint);
}
/// <summary>
/// Darkens the Piece-shader materials of a hull. COPIES them, so the vanilla ship that shares the
/// asset keeps its colour; the water mask and anything without a plain colour are left alone.
/// </summary>
private static void Tint(GameObject root, Color tint)
{
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] shared = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < shared.Length; i++)
{
Material source = shared[i];
if (source == null || source.shader == null) continue;
if (source.shader.name != "Custom/Piece" || !source.HasProperty("_Color")) continue;
Material copy;
if (!copies.TryGetValue(source, out copy))
{
copy = new Material(source) { name = source.name + "_bone" };
copy.SetColor("_Color", source.GetColor("_Color") * tint);
copies[source] = copy;
}
shared[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = shared;
}
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
Traverse traverse = Traverse.Create(player);
bool any = false;
foreach (Spec spec in Specs)
{
GameObject prefab = PrefabManager.Instance.GetPrefab(spec.Name);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) continue;
traverse.Method("AddKnownPiece", piece).GetValue();
any = true;
}
if (any) traverse.Method("UpdateAvailablePiecesList").GetValue();
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[BoneShip] Could not borrow the icon from '{prefabName}'.");
return null;
}
}
/// <summary>Marks a ship as one of ours. No logic: the patches below and the archers look for it.</summary>
public class BoneShipMarker : MonoBehaviour
{
}
/// <summary>
/// The oarsmen's push, in place of the wind's.
///
/// Ship.GetSailForce is, read off the IL: normalize(windDir + forward) * angleFactor * lerp(0.25, 1,
/// windIntensity) * m_sailForceFactor * sailSize, smoothed into m_sailForce over a second. The angle
/// factor is zero when the wind comes from ahead - that is what stops a vanilla ship dead. For a bone
/// ship the target is simply forward * m_sailForceFactor * sailSize * SailK, smoothed the same way with
/// the same two private fields, so the ship accelerates like a sailing one and the vanilla factor of
/// each hull (Karve 0.03, VikingShip 0.05, Ashlands 0.085) still scales the push.
///
/// sailSize is 0 below Half, 0.5 at Half and 1 at Full, so Slow and Back are untouched: they were
/// never the wind's.
/// </summary>
[HarmonyPatch(typeof(Ship), "GetSailForce")]
public static class BoneShipSailForcePatch
{
private static readonly FieldInfo SailForce = AccessTools.Field(typeof(Ship), "m_sailForce");
private static readonly FieldInfo WindChangeVelocity = AccessTools.Field(typeof(Ship), "m_windChangeVelocity");
public static bool Prefix(Ship __instance, float sailSize, ref Vector3 __result)
{
if (!BoneShip.IsBoneShip(__instance)) return true;
if (SailForce == null || WindChangeVelocity == null) return true; // changed under us: fall back to vanilla
Vector3 current = (Vector3)SailForce.GetValue(__instance);
Vector3 velocity = (Vector3)WindChangeVelocity.GetValue(__instance);
Vector3 target = __instance.transform.forward * (__instance.m_sailForceFactor * sailSize * BoneShip.SailK);
current = Vector3.SmoothDamp(current, target, ref velocity, 1f, 99f);
SailForce.SetValue(__instance, current);
WindChangeVelocity.SetValue(__instance, velocity);
__result = current;
return false;
}
}
/// <summary>
/// The sail never unfurls and the mast never turns to the wind: there is no sailing to show. Half and
/// Full would otherwise raise a sail that is meant to hang in rags. UpdateSail is what runs
/// UpdateSailSize (the furl animation) and then turns the mast, so skipping it skips both.
/// What the sail looks like left alone is for the game to show: the prefab's own pose.
/// </summary>
[HarmonyPatch(typeof(Ship), "UpdateSail")]
public static class BoneShipSailPatch
{
public static bool Prefix(Ship __instance)
{
return !BoneShip.IsBoneShip(__instance);
}
}
/// <summary>Makes the piece buildable without having to craft its parts first, like the bone pile.</summary>
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class BoneShipKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
BoneShip.EnsureKnown(__instance);
}
}
}

View file

@ -0,0 +1,54 @@
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// The archer a bone ship carries: the Bound Sentry, with the parts of it that make no sense on a deck
/// taken away and the ones that make it a ship's archer put in.
///
/// A PREFAB OF ITS OWN, not the sentry with a component added when it is spawned. A component added in
/// play is not saved: after a reload the archer would come back with no mount, and stand on nothing. This
/// one is built with ShipMount and ShipBust already on it, so a reloaded archer finds its ship again by the
/// id in its own ZDO (see ShipMount) and the roster, which counts archers by that id, never has to rebuild
/// one that was already there.
///
/// Taken away from the sentry:
/// - RaisedThrall. The orders (follow, wait, go home) are for troops; an archer on a mast of the ship
/// has no business following anyone, and E on it would send it after the player;
/// - CharacterDrop. The sentry gives back what it cost when it falls. This one is invulnerable while the
/// ship stands, and when the ship goes down it goes too - which must not pay out a soul stone and ten
/// bone fragments for every archer on every ship that sinks.
/// What stays is the bow, the AI and the tamed flag the spawner sets.
/// </summary>
public static class BoneShipArcher
{
public const string Name = "BoneShipArcher";
public static void Register()
{
// The sentry is registered by the bone pile, earlier in the same window.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(Name, SkeletonSentry.SentryName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{SkeletonSentry.SentryName}'; the ships have no archers.");
return;
}
foreach (RaisedThrall thrall in prefab.GetComponentsInChildren<RaisedThrall>(true))
{
if (thrall != null) Object.DestroyImmediate(thrall);
}
foreach (CharacterDrop drop in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
prefab.AddComponent<ShipMount>();
prefab.AddComponent<ShipBust>();
PrefabManager.Instance.AddPrefab(prefab);
}
}
}

View file

@ -0,0 +1,572 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What is bolted to a bone ship's hull: the bones along both rails and the bow, a few scattered on the
/// deck, and the ALTAR where bone fragments are offered (see BoneShipRoster).
///
/// Built when the ship comes into the world, on every client, and not baked into the prefab - because
/// the three hulls are different shapes (the Karve's nodes bear no relation to the Longship's, and the
/// Ashlands ship's rope nodes are in another axis altogether) and the only generic way to find "the rail"
/// and "the deck" on all of them is to ask the physics engine. So a ray is dropped from above at points
/// scanned inward from outside the hull; the first thing it lands on is the rail's top, and a ray down the
/// centre line lands on the deck. The mast, the sail and the ropes are skipped by NAME up the hierarchy,
/// because the boom of the Karve is a collider that spans the whole beam at six metres.
///
/// Everything is deterministic from the ship's own id, so every client builds the same bones.
///
/// The bones are borrowed models (ModelBorrow strips them to renderers) cached once as templates and
/// copied, so a ship coming into view is a few dozen cheap instantiates and not a few dozen strips.
/// The model names that are not certain to exist - the bigger bones - are tried in order and whatever
/// resolves is logged once.
/// </summary>
public class BoneShipFittings : MonoBehaviour
{
private const string SkullPrefab = "TrophySkeleton";
private const string FragmentsPrefab = "BoneFragments";
// The bigger bones along the rail. A pickable from the forest crypts: it is a pile of remains meant to
// be seen, and it is certain to exist (the earlier guesses - bone_stack, skull_pile, a ribcage item -
// never were). Kept as a list so a second model is one more entry.
private static readonly string[] LargeBonePrefabs = { "Pickable_ForestCryptRemains01" };
internal const float RayStartHeight = 14f;
private const float RayLength = 32f;
// The offering chest next to the cargo hatch. Both are tunable by eye: ChestSize is the borrowed chest's
// widest side in metres (the model is measured and fitted by ModelBorrow), ChestHeight the box that is
// clicked and where the skull sits.
private const string ChestPrefab = "piece_chest_wood";
private const float ChestSize = 0.85f;
private const float ChestHeight = 0.62f;
private static GameObject s_holder;
private static readonly Dictionary<string, GameObject> s_templates = new Dictionary<string, GameObject>();
private static bool s_reported;
/// <summary>Where the altar ended up, in the ship's space. The roster keeps its hover on this.</summary>
public Switch Altar { get; private set; }
/// <summary>One archer's place: where it stands on the ship (ship space) and whether it is a bust.</summary>
public struct ArcherPost
{
public Vector3 Local;
public bool Bust;
}
/// <summary>
/// Where the ship's archers stand, found by ray once the hull's colliders exist. Null until then; the
/// roster waits for it. The small ship has one, at the bow; the large ones a pair, bow and stern.
/// All are busts - only the chest and up shows, a figurehead that shoots.
/// </summary>
public List<ArcherPost> ArcherPosts { get; private set; }
private void Start()
{
StartCoroutine(Build());
}
private IEnumerator Build()
{
ZNetView nview = GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) yield break; // a placement ghost: no bones
// One physics step so the hull's colliders exist for the rays.
yield return new WaitForFixedUpdate();
yield return null;
Bounds hull;
if (!TryHullExtent(out hull))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}' has no OnboardTrigger to measure; no bones were fitted.");
yield break;
}
ReportModels();
System.Random rng = new System.Random(nview.GetZDO().m_uid.GetHashCode());
float hx = hull.extents.x;
float hz = hull.extents.z;
int rays = 0;
int placed = 0;
// ---- both rails
int slots = Mathf.Max(4, Mathf.RoundToInt(2f * 0.92f * hz / 1.3f));
for (int side = -1; side <= 1; side += 2)
{
for (int i = 0; i < slots; i++)
{
float t = slots == 1 ? 0.5f : i / (float)(slots - 1);
float z = Mathf.Lerp(-0.92f * hz, 0.92f * hz, t) + Range(rng, -0.25f, 0.25f);
Vector3 point;
if (!FindRail(side, z, hx, out point, ref rays)) continue;
if (rays >= 40) { rays = 0; yield return null; }
if (PlaceOnRail(point, side, rng)) placed++;
}
}
// ---- the bow: a cluster on the centre line at the very front
Vector3 bow;
if (FindSurface(new Vector3(0f, RayStartHeight, 0.90f * hz), out bow))
{
for (int k = 0; k < 3; k++)
{
Vector3 p = bow + new Vector3(Range(rng, -0.35f, 0.35f), 0.02f, Range(rng, -0.35f, 0.15f));
if (Place(SkullPrefab, p, Range(rng, 0.30f, 0.42f), rng, 25f)) placed++;
}
}
// ---- loose on the deck
int scatter = Mathf.Max(5, slots / 2);
for (int k = 0; k < scatter; k++)
{
float x = Range(rng, -0.55f, 0.55f) * hx;
float z = Range(rng, -0.8f, 0.8f) * hz;
if (NearHatch(x, z)) continue; // keep the cargo hatch and the offering chest beside it clear
Vector3 point;
if (!FindSurface(new Vector3(x, RayStartHeight, z), out point)) continue;
if (Place(FragmentsPrefab, point + Vector3.up * 0.02f, Range(rng, 0.22f, 0.34f), rng, 180f)) placed++;
if (++rays >= 40) { rays = 0; yield return null; }
}
BuildAltar(hz, rng);
FindArcherPosts(hz);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {placed} bones fitted, altar {(Altar != null ? "built" : "not built")}, " +
$"{ArcherPosts.Count} archer post(s).");
}
// ---------------------------------------------------------------- the archers' posts
/// <summary>
/// Bow always; the large ships a second one at the stern. A point at the very tip of a hull is often
/// past the end of its colliders and the surface there climbs steeply, so any slope counts and, if
/// nothing is under the point, the search walks back toward the middle in 30 cm steps.
/// </summary>
private void FindArcherPosts(float hz)
{
ArcherPosts = new List<ArcherPost>();
AddPost(+0.93f * hz, -1f);
if (!BoneShip.IsKarveShip(this)) AddPost(-0.88f * hz, +1f);
}
private void AddPost(float z, float towardMiddle)
{
for (float back = 0f; back <= 2.4f; back += 0.3f)
{
Vector3 point;
if (!FindSurface(new Vector3(0f, RayStartHeight, z + towardMiddle * back), out point, -1f)) continue;
// A hand's breadth INTO the stem, not on top of it: the pelvis stub the bust leaves where the legs
// were then sits in the wood instead of resting on it, which is what made it look hung in air.
ArcherPosts.Add(new ArcherPost { Local = point + Vector3.down * 0.10f, Bust = true });
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer post at local ({point.x:F2}, {point.y:F2}, {point.z:F2}) " +
(back > 0f ? $"(walked back {back:F1} m from the tip)." : "(at the tip)."));
return;
}
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull found for an archer at z {z:F1}; that post is empty.");
}
// ---------------------------------------------------------------- the altar
/// <summary>
/// The offering chest: a wooden chest standing on the deck NEXT TO THE CARGO HATCH. Every ship has
/// that hatch (the "piece_chest" Container, a flat square lid on the centre line: 0.9 m on the Karve,
/// 1.5 on the Longship, 1.8 on the Ashlands ship), so it is the one spot that is the same idea on all
/// three and the one a player already knows to look at. The first version put an altar of bones a
/// fixed distance down the centre line, which on the Karve is the stretch between the mast and the
/// helm, right where its rowers sit.
///
/// Candidate places are tried beside the hatch, then behind it, then in front, and a candidate is
/// taken only if the whole footprint of the chest lies on FLAT deck at the hatch's own height - five
/// rays, the centre and four points around it - and is clear of the mast. A Karve is narrow and its
/// hull closes in toward the bow, so beside the hatch is not always deck; the rays are what say so.
/// </summary>
private void BuildAltar(float hz, System.Random rng)
{
Vector3 spot;
string where;
if (!FindChestSpot(hz, out spot, out where))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no flat deck found for the offering chest; it was not built.");
return;
}
GameObject chest = new GameObject("BoneChest");
chest.transform.SetParent(transform, false);
chest.transform.localPosition = spot;
// Its front toward the stern, where the helm is and where a player stands when he looks around.
chest.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
chest.layer = LayerMask.NameToLayer("piece_nonsolid");
// The model: the wooden chest of the game, shut, with a skull on the lid so it reads as ours.
GameObject template = TemplateOf(ChestPrefab);
if (template != null)
{
GameObject model = Object.Instantiate(template, chest.transform, false);
model.name = ChestPrefab;
model.transform.localPosition = Vector3.zero;
model.transform.localScale = Vector3.one * ChestSize;
// A chest prefab carries both an open and a closed lid; the container switches them at run
// time and the copy has no container, so the open one is turned off here.
foreach (Transform node in model.GetComponentsInChildren<Transform>(true))
{
if (node != model.transform && node.name.ToLowerInvariant() == "open") node.gameObject.SetActive(false);
}
}
else
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{ChestPrefab}' to borrow; the offering chest is a box of fragments instead.");
Place(FragmentsPrefab, chest.transform, new Vector3(0f, 0f, 0f), 0.45f, rng, 10f);
}
Place(SkullPrefab, chest.transform, new Vector3(0f, ChestHeight, 0f), 0.26f, rng, 8f);
BoxCollider box = chest.AddComponent<BoxCollider>();
box.center = new Vector3(0f, ChestHeight * 0.5f, 0f);
box.size = new Vector3(ChestSize * 0.95f, ChestHeight, ChestSize * 0.65f);
Switch sw = chest.AddComponent<Switch>();
sw.m_name = BoneShip.AltarName;
Altar = sw;
BoneShipRoster roster = GetComponent<BoneShipRoster>();
if (roster != null) roster.Bind(sw);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': offering chest {where} the cargo hatch, at local " +
$"({spot.x:F2}, {spot.y:F2}, {spot.z:F2}).");
}
private bool FindChestSpot(float hz, out Vector3 spot, out string where)
{
spot = Vector3.zero;
where = "";
Transform hatch = transform.Find("piece_chest");
BoxCollider hatchBox = hatch != null ? hatch.GetComponent<BoxCollider>() : null;
if (hatch == null)
{
// A ship with no cargo hatch: the old rule, a fixed place down the centre line.
where = "(no hatch found, fixed spot behind the middle) of";
return FindSurface(new Vector3(0f, RayStartHeight, -0.42f * hz), out spot);
}
Vector3 centre = hatch.localPosition;
float half = hatchBox != null ? Mathf.Abs(hatchBox.size.x * hatch.localScale.x) * 0.5f : 0.6f;
float gap = half + ChestSize * 0.5f + 0.1f;
Vector3 hatchTop;
if (!FindSurface(new Vector3(centre.x, RayStartHeight, centre.z), out hatchTop)) return false;
float level = hatchTop.y;
// Beside first (the hatch is on the centre line, so beside is out toward a rail), then behind and
// in front. The mast is on the centre line too, and its collider is skipped by the ray, so it is
// kept away from by position.
Vector2[] offsets =
{
new Vector2(+gap, 0f), new Vector2(-gap, 0f), new Vector2(0f, -gap), new Vector2(0f, +gap),
};
string[] names = { "right of", "left of", "behind", "in front of" };
List<Vector2> masts = MastPositions();
for (int i = 0; i < offsets.Length; i++)
{
Vector2 c = new Vector2(centre.x + offsets[i].x, centre.z + offsets[i].y);
if (NearAny(masts, c, 0.7f)) continue;
if (!FlatDeckAround(c, level, ChestSize * 0.5f, out spot)) continue;
where = names[i];
return true;
}
return false;
}
/// <summary>
/// The chest's whole footprint is on deck: the centre and four points half a chest away all find a
/// surface that is flat and at the hatch's own height. Returns the centre's point.
/// </summary>
private bool FlatDeckAround(Vector2 c, float level, float reach, out Vector3 centre)
{
Vector2[] around = { Vector2.zero, new Vector2(reach, 0f), new Vector2(-reach, 0f), new Vector2(0f, reach), new Vector2(0f, -reach) };
centre = Vector3.zero;
for (int i = 0; i < around.Length; i++)
{
Vector3 p;
if (!FindSurface(new Vector3(c.x + around[i].x, RayStartHeight, c.y + around[i].y), out p, 0.85f)) return false;
if (Mathf.Abs(p.y - level) > 0.22f) return false;
if (i == 0) centre = p;
}
return true;
}
/// <summary>Within a couple of metres of the cargo hatch, on any side: where the chest will stand.</summary>
private bool NearHatch(float x, float z)
{
Transform hatch = transform.Find("piece_chest");
if (hatch == null) return false;
Vector2 d = new Vector2(x - hatch.localPosition.x, z - hatch.localPosition.z);
return d.sqrMagnitude < 2.2f * 2.2f;
}
private List<Vector2> MastPositions()
{
List<Vector2> masts = new List<Vector2>();
foreach (Transform t in GetComponentsInChildren<Transform>(true))
{
if (t == transform || t.name.ToLowerInvariant() != "mast") continue;
Vector3 local = transform.InverseTransformPoint(t.position);
masts.Add(new Vector2(local.x, local.z));
}
return masts;
}
private static bool NearAny(List<Vector2> points, Vector2 p, float distance)
{
foreach (Vector2 q in points)
{
if ((q - p).sqrMagnitude < distance * distance) return true;
}
return false;
}
// ---------------------------------------------------------------- placing
private bool PlaceOnRail(Vector3 point, int side, System.Random rng)
{
double roll = rng.NextDouble();
Vector3 up = point + Vector3.up * 0.02f;
if (roll < 0.38) return Place(SkullPrefab, up, Range(rng, 0.30f, 0.38f), rng, 14f);
if (roll < 0.70) return Place(FragmentsPrefab, up, Range(rng, 0.28f, 0.40f), rng, 180f);
if (roll < 0.88)
{
// The big ones lean outward over the side, like something draped there.
string large = LargestAvailable();
return Place(large ?? SkullPrefab, up + new Vector3(side * 0.05f, 0f, 0f), large != null ? Range(rng, 0.7f, 1.0f) : 0.42f, rng, 20f);
}
return false; // a gap, on purpose: a hull that is covered evenly looks decorated, not grown over
}
private bool Place(string prefabName, Vector3 localPosition, float size, System.Random rng, float tilt)
{
return Place(prefabName, transform, localPosition, size, rng, tilt);
}
private static bool Place(string prefabName, Transform parent, Vector3 localPosition, float size, System.Random rng, float tilt)
{
GameObject template = TemplateOf(prefabName);
if (template == null) return false;
GameObject copy = Object.Instantiate(template, parent, false);
copy.name = prefabName;
copy.transform.localPosition = localPosition;
copy.transform.localRotation = Quaternion.Euler(Range(rng, -tilt, tilt), (float)rng.NextDouble() * 360f, Range(rng, -tilt, tilt));
copy.transform.localScale = Vector3.one * size;
return true;
}
// ---------------------------------------------------------------- models
/// <summary>
/// One stripped, 1 m model per source prefab, kept under an inactive holder that survives scene loads.
/// Built on first use. The holder being inactive is what keeps the template from ever being drawn.
/// </summary>
private static GameObject TemplateOf(string prefabName)
{
GameObject cached;
if (s_templates.TryGetValue(prefabName, out cached)) return cached;
if (s_holder == null)
{
s_holder = new GameObject("RoV_BoneShipModels");
s_holder.SetActive(false);
Object.DontDestroyOnLoad(s_holder);
}
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
GameObject template = null;
if (source != null)
{
template = ModelBorrow.Attach(s_holder.transform, prefabName, source, Vector3.zero, Quaternion.identity, 1f, "BoneShip");
StripEffects(template);
}
s_templates[prefabName] = template;
return template;
}
/// <summary>
/// A dropped item is dressed to be seen from far away: sparkles, a glow, sometimes a light and a
/// sound. ModelBorrow removes everything that THINKS (scripts, colliders, bodies, the network
/// view) but a particle system or a light does not think, it just plays - so the first version of
/// the fittings lit every bone on the hull like a drop on the ground, and the whole ship glowed.
///
/// Only meshes are wanted. A node that carries an effect and no mesh goes with all its children;
/// otherwise just the effect components come off. A particle system cannot be removed while its
/// renderer is there, so the renderer goes first.
/// </summary>
internal static void StripEffects(GameObject template)
{
if (template == null) return;
foreach (ParticleSystem system in template.GetComponentsInChildren<ParticleSystem>(true))
{
if (system == null) continue;
GameObject node = system.gameObject;
if (node == template || node.GetComponent<MeshRenderer>() != null || node.GetComponent<SkinnedMeshRenderer>() != null)
{
ParticleSystemRenderer renderer = node.GetComponent<ParticleSystemRenderer>();
if (renderer != null) Object.DestroyImmediate(renderer);
Object.DestroyImmediate(system);
}
else
{
Object.DestroyImmediate(node);
}
}
foreach (Light light in template.GetComponentsInChildren<Light>(true))
{
if (light != null) Object.DestroyImmediate(light);
}
foreach (AudioSource audio in template.GetComponentsInChildren<AudioSource>(true))
{
if (audio != null) Object.DestroyImmediate(audio);
}
foreach (TrailRenderer trail in template.GetComponentsInChildren<TrailRenderer>(true))
{
if (trail != null) Object.DestroyImmediate(trail);
}
foreach (LineRenderer line in template.GetComponentsInChildren<LineRenderer>(true))
{
if (line != null) Object.DestroyImmediate(line);
}
}
private static string LargestAvailable()
{
foreach (string name in LargeBonePrefabs)
{
if (TemplateOf(name) != null) return name;
}
return null;
}
private static void ReportModels()
{
if (s_reported) return;
s_reported = true;
List<string> found = new List<string>();
List<string> missing = new List<string>();
foreach (string name in LargeBonePrefabs)
{
(TemplateOf(name) != null ? found : missing).Add(name);
}
Jotunn.Logger.LogInfo("[BoneShip] large bone models: found [" + string.Join(", ", found.ToArray()) +
"], missing [" + string.Join(", ", missing.ToArray()) + "].");
}
// ---------------------------------------------------------------- measuring
/// <summary>
/// The hull's footprint in the ship's own space, from the OnboardTrigger every ship has: the volume
/// the game uses to decide who is aboard is, by construction, about the hull.
/// </summary>
internal bool TryHullExtent(out Bounds bounds)
{
bounds = new Bounds();
Transform trigger = transform.Find("OnboardTrigger");
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
if (box == null) return false;
Vector3 centre = transform.InverseTransformPoint(trigger.TransformPoint(box.center));
Vector3 size = Vector3.Scale(box.size, trigger.lossyScale) ;
size = new Vector3(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z));
bounds = new Bounds(centre, size);
return true;
}
/// <summary>
/// The top of the rail on one side at one z: scanned from outside the hull inward, the first ray that
/// lands on the ship is the outer edge of the rail.
/// </summary>
internal bool FindRail(int side, float z, float hx, out Vector3 point, ref int rays)
{
for (float x = 1.15f * hx; x > 0.3f * hx; x -= 0.12f)
{
rays++;
if (FindSurface(new Vector3(side * x, RayStartHeight, z), out point)) return true;
}
point = Vector3.zero;
return false;
}
/// <summary>
/// The highest solid surface of THIS ship under a local point, in local space. Triggers, and anything
/// whose name up the hierarchy says mast, sail, cloth or rope, are not the hull.
/// </summary>
internal bool FindSurface(Vector3 localOrigin, out Vector3 localPoint, float minUp = 0.2f)
{
Vector3 origin = transform.TransformPoint(localOrigin);
RaycastHit best = default(RaycastHit);
bool found = false;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.RaycastAll(origin, -transform.up, RayLength))
{
Collider collider = hit.collider;
if (collider == null || collider.isTrigger) continue;
if (!collider.transform.IsChildOf(transform)) continue;
if (Vector3.Dot(hit.normal, transform.up) < minUp) continue;
if (IsRigging(collider.transform)) continue;
if (hit.distance >= bestDistance) continue;
best = hit;
bestDistance = hit.distance;
found = true;
}
localPoint = found ? transform.InverseTransformPoint(best.point) : Vector3.zero;
return found;
}
private bool IsRigging(Transform t)
{
for (; t != null && t != transform; t = t.parent)
{
string n = t.name.ToLowerInvariant();
if (n.Contains("mast") || n.Contains("sail") || n.Contains("cloth") || n.Contains("rope")) return true;
}
return false;
}
private static float Range(System.Random rng, float min, float max)
{
return min + (float)rng.NextDouble() * (max - min);
}
}
}

View file

@ -0,0 +1,709 @@
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();
}
}

View file

@ -0,0 +1,480 @@
using System.Collections;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The oarsmen: skeletons seated at benches along both sides, pulling oars, who are the reason a ship
/// with no wind in its sail goes anywhere. Skeleton_BoneShip.txt, sections 1 and 3.4.
///
/// PURE SCENERY. There is no creature here: no Character, no AI, no network object. Each is a copy of the
/// skeleton's MODEL, and how many are visible is one number the roster keeps in the ship's own ZDO
/// (RoV_bshRowers = how many troops are aboard), so every client draws the same crew and they come
/// ashore one at a time exactly as the roster says. How hard they pull is the ship's own gear
/// (Stop, Slow, Half, Full, Back), which every client already has, so nothing here needs to be sent.
///
/// NOTHING TO REUSE: no ship in the game has oars (the dump found none), so the oars are built here too,
/// from two stretched cubes in the ship's own wood.
///
/// SEATED WITHOUT A SEATED ANIMATION. The model stands, but is lowered until its hips are at bench
/// height: the legs go down through the deck, which hides them from above, so what shows is a body sitting
/// at a bench. The same trick as the bust at the bow, and for the same reason - the model cannot be cut.
///
/// THE ARMS follow the oar. Each arm bone is turned, in world space, to point at its grip on the handle
/// (FromToRotation from where it points now to where the grip is), after the animator has posed it, so
/// nothing depends on the rig's local axes, which were never read. The bones are found by name (the rig is
/// Mixamo-style: LeftArm, LeftForeArm, LeftHand) and, when any is missing, the whole skeleton is logged
/// once so the names can be corrected; the crew then still sits and rocks, with arms at their sides.
///
/// THE STROKE. One shared phase per ship, all oars in time. The blade sweeps aft in the water (the pull,
/// the rower leans back and the handle comes toward his chest) and forward out of it (the recovery, the
/// blade lifted). The period follows the gear; Back runs it in reverse; Stop lets the oars settle level.
/// </summary>
public class BoneShipRowers : MonoBehaviour
{
// The model, and how big the oarsmen are.
private const string SkeletonPrefab = "Skeleton";
private const float ModelHeight = 1.7f;
// Where on the hull they sit, as fractions of the half length, from the stern forward. The Karve's
// are further apart because its helm and bow seats leave less room between.
// The Karve's front pair moved from +0.22 to -0.12 of the half length: the cargo hatch is at z = +1.3
// and the offering chest stands beside it, and a bench at +1.0 was in the way.
private static readonly float[] SmallSeatsZ = { -0.40f, -0.12f };
private static readonly float[] LargeSeatsZ = { -0.50f, -0.26f, -0.02f, 0.22f };
private const float SeatHeight = 0.47f; // hips above the deck: a bench and a little
private const float OarlockLift = 0.12f; // oarlock above the rail's top
private const float OarInboard = 0.75f; // handle end, from the oarlock
private const float OarOutboard = 1.70f; // blade end
// The stroke.
private const float SweepMax = 0.45f; // radians, blade fore and aft
private const float LiftMax = 0.35f; // radians, blade up on the recovery
private const float LeanMax = 14f; // degrees, rower back and forth
private const float PeriodSlow = 2.6f;
private const float PeriodHalf = 1.9f;
private const float PeriodFull = 1.3f;
private class Seat
{
public GameObject Root; // at the hips, in the ship's space
public GameObject Bench;
public Transform Lean; // rotates about the hips
public Transform Oar;
public int Side; // +1 right, -1 left
public Vector3 Oarlock; // ship space
public Transform LeftArm, LeftFore, LeftHand, RightArm, RightFore, RightHand;
}
private readonly List<Seat> m_seats = new List<Seat>();
private ZNetView m_nview;
private Ship m_ship;
private float m_phase;
private float m_amplitude;
private bool m_built;
private static GameObject s_holder;
private static GameObject s_template;
private static bool s_templateTried;
private static Mesh s_cube;
private static bool s_loggedBones;
private void Start()
{
m_nview = GetComponent<ZNetView>();
m_ship = GetComponent<Ship>();
if (m_nview == null || !m_nview.IsValid()) return; // a placement ghost
StartCoroutine(Build());
}
// ---------------------------------------------------------------- building
private IEnumerator Build()
{
// The fittings measure the hull the same way, a physics step after the ship exists.
yield return new WaitForFixedUpdate();
yield return null;
yield return null;
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
Bounds hull;
if (fittings == null || !fittings.TryHullExtent(out hull))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull to seat rowers on.");
yield break;
}
GameObject template = Template();
if (template == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{SkeletonPrefab}' model; '{name}' has no rowers.");
yield break;
}
float hx = hull.extents.x;
float hz = hull.extents.z;
float[] zs = SeatStations((BoneShip.MeleeCapOf(this) + BoneShip.RangedCapOf(this)) / 2);
Material wood = FindWood();
int rays = 0;
for (int side = -1; side <= 1; side += 2)
{
foreach (float f in zs)
{
float z = f * hz;
Vector3 rail;
if (!fittings.FindRail(side, z, hx, out rail, ref rays)) continue;
float seatX = side * Mathf.Max(0.45f, Mathf.Abs(rail.x) - 0.55f);
Vector3 deck;
if (!fittings.FindSurface(new Vector3(seatX, BoneShipFittings.RayStartHeight, z), out deck)) continue;
m_seats.Add(MakeSeat(template, wood, side, deck, rail, z));
if (++rays >= 30) { rays = 0; yield return null; }
}
}
// Fill order: both sides at each station, from the bow back, so a short crew is balanced.
m_seats.Sort((a, b) =>
{
int byStation = b.Root.transform.localPosition.z.CompareTo(a.Root.transform.localPosition.z);
return byStation != 0 ? byStation : a.Side.CompareTo(b.Side);
});
m_built = true;
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {m_seats.Count} rowers' seats built.");
}
/// <summary>
/// Where along the hull the benches go, for this many on each side: the hand-placed lists where they
/// were tuned (two on the Karve, four on the Longship), an even spread from the stern forward for any
/// other number - the Ashlands ship has six a side.
/// </summary>
private static float[] SeatStations(int perSide)
{
if (perSide == SmallSeatsZ.Length) return SmallSeatsZ;
if (perSide == LargeSeatsZ.Length) return LargeSeatsZ;
float[] stations = new float[perSide];
for (int i = 0; i < perSide; i++)
{
float t = perSide == 1 ? 0.5f : i / (float)(perSide - 1);
stations[i] = Mathf.Lerp(-0.52f, 0.24f, t);
}
return stations;
}
private Seat MakeSeat(GameObject template, Material wood, int side, Vector3 deck, Vector3 rail, float z)
{
Seat seat = new Seat { Side = side };
// The hips, at bench height above the deck.
GameObject root = new GameObject("Rower");
root.transform.SetParent(transform, false);
root.transform.localPosition = deck + Vector3.up * SeatHeight;
seat.Root = root;
GameObject lean = new GameObject("Lean");
lean.transform.SetParent(root.transform, false);
seat.Lean = lean.transform;
// Facing the stern, as an oarsman does. The model's own front turned out to be the OTHER way from
// what a 180 degree turn assumed - the first build had the crew looking at the bow - so it is
// left as it comes: no turn.
GameObject model = Instantiate(template, lean.transform, false);
model.name = "model";
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = Vector3.one * (ModelHeight / 1.8f);
model.SetActive(true);
Animator animator = model.GetComponentInChildren<Animator>(true);
if (animator != null)
{
// The idle clip fires animation events at a receiver the strip removed: unanswered, each
// one logs an error. Switched off, the clip still poses the body.
animator.fireEvents = false;
animator.applyRootMotion = false;
}
FindBones(model.transform, seat);
SeatHips(model.transform, lean.transform, seat);
// A bench, across the beam, so nobody sits on nothing.
GameObject bench = MakeBox("Bench", transform, wood, new Vector3(0.85f, 0.07f, 0.34f));
bench.transform.localPosition = new Vector3(deck.x, deck.y + SeatHeight - 0.09f, z);
// The oar: pivot at the oarlock on the rail, a shaft and a blade along its own +z (outboard).
seat.Oarlock = new Vector3(rail.x, rail.y + OarlockLift, z);
GameObject oar = new GameObject("Oar");
oar.transform.SetParent(transform, false);
oar.transform.localPosition = seat.Oarlock;
seat.Oar = oar.transform;
float length = OarInboard + OarOutboard;
GameObject shaft = MakeBox("Shaft", oar.transform, wood, new Vector3(0.07f, 0.07f, length));
shaft.transform.localPosition = new Vector3(0f, 0f, (OarOutboard - OarInboard) * 0.5f);
GameObject blade = MakeBox("Blade", oar.transform, wood, new Vector3(0.20f, 0.03f, 0.55f));
blade.transform.localPosition = new Vector3(0f, 0f, OarOutboard - 0.27f);
root.SetActive(false);
oar.SetActive(false);
bench.SetActive(false);
seat.Root = root;
seat.Bench = bench;
return seat;
}
/// <summary>Moves the model so its hips sit on the lean pivot - or, if no hips are found, by height.</summary>
private static void SeatHips(Transform model, Transform pivot, Seat seat)
{
Transform hips = Find(model, "hips") ?? Find(model, "pelvis");
if (hips != null)
{
Vector3 hipsInPivot = pivot.InverseTransformPoint(hips.position);
model.localPosition -= hipsInPivot;
}
else
{
model.localPosition = new Vector3(0f, -0.95f * (ModelHeight / 1.8f), 0f);
}
}
// ---------------------------------------------------------------- the stroke
private void Update()
{
if (!m_built || m_ship == null || m_nview == null || !m_nview.IsValid()) return;
int crew = m_nview.GetZDO().GetInt(BoneShipRoster.KeyRowers, 0);
Ship.Speed gear = m_ship.GetSpeedSetting();
float period = gear == Ship.Speed.Full ? PeriodFull : gear == Ship.Speed.Half ? PeriodHalf : PeriodSlow;
bool rowing = gear != Ship.Speed.Stop && (crew > 0);
m_amplitude = Mathf.MoveTowards(m_amplitude, rowing ? 1f : 0f, Time.deltaTime * 1.5f);
if (rowing) m_phase = Mathf.Repeat(m_phase + Time.deltaTime / period * (gear == Ship.Speed.Back ? -1f : 1f), 1f);
float twoPi = Mathf.PI * 2f;
float sweep = -Mathf.Cos(twoPi * m_phase); // forward extreme at 0, aft at 0.5
float recovery = Mathf.Clamp01(-Mathf.Sin(twoPi * m_phase) * 2f); // 1 mid-recovery, 0 in the water
recovery = recovery * recovery * (3f - 2f * recovery);
float lift = Mathf.Lerp(-0.08f, LiftMax, recovery);
float lean = LeanMax * sweep;
for (int i = 0; i < m_seats.Count; i++)
{
Seat seat = m_seats[i];
bool shown = i < crew;
seat.Root.SetActive(shown);
seat.Oar.gameObject.SetActive(shown);
seat.Bench.SetActive(shown);
if (!shown) continue;
float psi = SweepMax * sweep * m_amplitude;
float lam = Mathf.Lerp(0.10f, lift, m_amplitude);
// The oar's outboard direction in the ship's space: out across the beam, a little fore or
// aft with the sweep (positive aft), and tilted up by the lift.
Vector3 outward = new Vector3(seat.Side * Mathf.Cos(psi) * Mathf.Cos(lam),
Mathf.Sin(lam),
-Mathf.Sin(psi) * Mathf.Cos(lam));
seat.Oar.localRotation = Quaternion.LookRotation(outward, Vector3.up);
seat.Lean.localRotation = Quaternion.AngleAxis(lean * m_amplitude, Vector3.right);
}
}
/// <summary>After the animator: the arms reach for the handle.</summary>
private void LateUpdate()
{
if (!m_built) return;
foreach (Seat seat in m_seats)
{
if (!seat.Root.activeSelf) continue;
// Two grips on the handle, near and far from the chest.
Vector3 gripNear = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.55f);
Vector3 gripFar = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.15f);
Reach(seat.LeftArm, seat.LeftFore, gripNear);
Reach(seat.LeftFore, seat.LeftHand, gripNear);
Reach(seat.RightArm, seat.RightFore, gripFar);
Reach(seat.RightFore, seat.RightHand, gripFar);
}
}
/// <summary>Turns a bone, in world space, so the line to its child points at the target.</summary>
private static void Reach(Transform bone, Transform child, Vector3 target)
{
if (bone == null || child == null) return;
Vector3 now = child.position - bone.position;
Vector3 want = target - bone.position;
if (now.sqrMagnitude < 1e-6f || want.sqrMagnitude < 1e-6f) return;
bone.rotation = Quaternion.FromToRotation(now, want) * bone.rotation;
}
// ---------------------------------------------------------------- bones
private static void FindBones(Transform model, Seat seat)
{
seat.LeftArm = Find(model, "leftarm");
seat.LeftFore = Find(model, "leftforearm");
seat.LeftHand = Find(model, "lefthand");
seat.RightArm = Find(model, "rightarm");
seat.RightFore = Find(model, "rightforearm");
seat.RightHand = Find(model, "righthand");
if (seat.LeftArm != null && seat.LeftFore != null && seat.LeftHand != null &&
seat.RightArm != null && seat.RightFore != null && seat.RightHand != null) return;
if (s_loggedBones) return;
s_loggedBones = true;
List<string> names = new List<string>();
foreach (Transform t in model.GetComponentsInChildren<Transform>(true)) names.Add(t.name);
Jotunn.Logger.LogWarning("[BoneShip] The rowers' arm bones were not all found by name; they will hang at " +
"their sides. Skeleton: " + string.Join(", ", names.ToArray()));
}
/// <summary>A bone by name, ignoring case and any "mixamorig:"-style prefix.</summary>
private static Transform Find(Transform root, string lowerName)
{
foreach (Transform t in root.GetComponentsInChildren<Transform>(true))
{
string n = t.name.ToLowerInvariant();
int colon = n.LastIndexOf(':');
if (colon >= 0) n = n.Substring(colon + 1);
if (n == lowerName) return t;
}
return null;
}
// ---------------------------------------------------------------- model, wood, boxes
/// <summary>
/// The skeleton's model with nothing that acts. Instantiated into an INACTIVE holder, so nothing wakes,
/// and then stripped in DEPENDENCY order: ModelBorrow's one pass is not safe on a creature, because
/// Unity refuses to remove a component another one requires - Humanoid under CharacterDrop - and the
/// Humanoid it leaves behind is a live creature. The Hive taught that: it broke the hammer for every
/// piece in the game. So each pass removes only what nothing still present requires, and passes repeat.
/// </summary>
private static GameObject Template()
{
if (s_templateTried) return s_template;
s_templateTried = true;
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(SkeletonPrefab);
if (source == null) return null;
s_holder = new GameObject("RoV_BoneShipRowers");
s_holder.SetActive(false);
Object.DontDestroyOnLoad(s_holder);
GameObject copy = Object.Instantiate(source, s_holder.transform);
copy.name = "RowerTemplate";
StripBehaviours(copy);
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true)) if (body != null) Object.DestroyImmediate(body);
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true)) if (collider != null) Object.DestroyImmediate(collider);
BoneShipFittings.StripEffects(copy);
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = Vector3.one;
s_template = copy;
return s_template;
}
private static void StripBehaviours(GameObject root)
{
for (int pass = 0; pass < 12; pass++)
{
bool any = false;
bool removed = false;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
any = true;
if (RequiredByAnother(behaviour)) continue;
Object.DestroyImmediate(behaviour);
removed = true;
}
if (!any) return;
if (!removed) break;
}
int left = 0;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true)) if (behaviour != null) left++;
if (left > 0) Jotunn.Logger.LogWarning($"[BoneShip] {left} component(s) of the rower model could not be removed.");
}
private static bool RequiredByAnother(MonoBehaviour behaviour)
{
System.Type type = behaviour.GetType();
foreach (Component other in behaviour.GetComponents<Component>())
{
if (other == null || other == behaviour) continue;
foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true))
{
RequireComponent need = (RequireComponent)attribute;
if (Needs(need.m_Type0, type) || Needs(need.m_Type1, type) || Needs(need.m_Type2, type)) return true;
}
}
return false;
}
private static bool Needs(System.Type required, System.Type type)
{
return required != null && required.IsAssignableFrom(type);
}
/// <summary>The ship's own rotten wood, so the oars and benches match: the first Piece-shader material on it.</summary>
private Material FindWood()
{
foreach (Renderer renderer in GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
foreach (Material material in renderer.sharedMaterials)
{
if (material != null && material.shader != null && material.shader.name == "Custom/Piece") return material;
}
}
return null;
}
private static GameObject MakeBox(string name, Transform parent, Material material, Vector3 size)
{
if (s_cube == null)
{
GameObject primitive = GameObject.CreatePrimitive(PrimitiveType.Cube);
s_cube = primitive.GetComponent<MeshFilter>().sharedMesh;
Object.Destroy(primitive);
}
GameObject box = new GameObject(name);
box.transform.SetParent(parent, false);
box.transform.localScale = size;
box.AddComponent<MeshFilter>().sharedMesh = s_cube;
MeshRenderer renderer = box.AddComponent<MeshRenderer>();
if (material != null) renderer.sharedMaterial = material;
return box;
}
}
}

View file

@ -0,0 +1,178 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The bone ships' sails: black, and torn.
///
/// Every vanilla sail is a Custom/Vegetation material - an alpha-cutout shader (it has a _Cutoff of
/// 0.5) - so a hole is simply a texel whose alpha is under that. Nothing is imported: the texture is
/// drawn here in code, one per source material (sail_white on the Karve, sail and sail_brown on the
/// Longship, ashlandshipsail_mat on the Ashlands ship), and goes onto a COPY of the material so the
/// vanilla ships keep theirs.
///
/// The holes come from value noise, not a drawing, because the sail's UV layout was not read. Two
/// scales: broad tears, and small shreds, with the top and bottom edges frayed. Whether the shader
/// actually clips on that alpha is the one thing only the game can confirm.
/// </summary>
public static class BoneShipSail
{
private const int Size = 256;
// The big tears: a share of the sail, roughly. Higher threshold = fewer, smaller holes.
private const float TearThreshold = 0.62f;
private const float ShredThreshold = 0.70f;
public static void Apply(GameObject prefab, string shipName)
{
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
int seed = shipName.GetHashCode();
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
Material[] shared = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < shared.Length; i++)
{
Material source = shared[i];
if (!IsSail(source)) continue;
Material copy;
if (!copies.TryGetValue(source, out copy))
{
copy = new Material(source) { name = source.name + "_bone" };
copy.SetTexture("_MainTex", Draw(seed + source.name.GetHashCode()));
copy.SetColor("_Color", Color.white);
copies[source] = copy;
}
shared[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = shared;
}
if (copies.Count == 0)
{
Jotunn.Logger.LogWarning($"[BoneShip] {shipName}: no sail material found, the sail is left as it is.");
}
}
private static bool IsSail(Material material)
{
if (material == null || material.shader == null) return false;
if (!material.HasProperty("_MainTex")) return false;
string name = material.name.ToLowerInvariant();
return name.Contains("sail");
}
// ---------------------------------------------------------------- the texture
private static Texture2D Draw(int seed)
{
Texture2D texture = new Texture2D(Size, Size, TextureFormat.RGBA32, true)
{
name = "boneship_sail",
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear,
};
Color32[] pixels = new Color32[Size * Size];
for (int y = 0; y < Size; y++)
{
float v = (y + 0.5f) / Size;
for (int x = 0; x < Size; x++)
{
float u = (x + 0.5f) / Size;
pixels[y * Size + x] = Pixel(u, v, seed);
}
}
texture.SetPixels32(pixels);
texture.Apply(true, false);
return texture;
}
private static Color32 Pixel(float u, float v, int seed)
{
// Cloth: near black, mottled, with a faint warp of vertical streaks.
float mottle = Fbm(u * 7f, v * 7f, seed + 3);
float streak = 0.5f + 0.5f * Mathf.Sin(u * 90f + Fbm(u * 3f, v * 3f, seed + 5) * 6f);
float shade = Mathf.Lerp(0.04f, 0.17f, mottle) * Mathf.Lerp(0.85f, 1.05f, streak);
Color cloth = new Color(shade * 1.00f, shade * 0.97f, shade * 0.93f, 1f);
// Holes. Each term is an alpha with 0.5 at its own edge; the lowest wins.
float tear = Fbm(u * 4f, v * 4f, seed + 11);
float shred = Fbm(u * 13f, v * 13f, seed + 29);
float alpha = 1f;
alpha = Mathf.Min(alpha, 0.5f + (TearThreshold - tear) * 14f);
alpha = Mathf.Min(alpha, 0.5f + (ShredThreshold - shred) * 14f);
// Fringe: the top and bottom edges are eaten away in ragged teeth, the sides a little.
float edge = Mathf.Min(v, 1f - v);
float teeth = ValueNoise(u * 22f, v * 3f, seed + 41);
alpha = Mathf.Min(alpha, 0.5f + (teeth * 0.16f - edge) * 28f);
float side = Mathf.Min(u, 1f - u);
float sideTeeth = ValueNoise(u * 3f, v * 20f, seed + 53);
alpha = Mathf.Min(alpha, 0.5f + (sideTeeth * 0.07f - side) * 28f);
// Scorched round the holes: darker where the tear is nearly through.
float burn = Mathf.Clamp01((tear - (TearThreshold - 0.10f)) * 8f);
cloth = Color.Lerp(cloth, new Color(0.015f, 0.015f, 0.015f, 1f), burn * 0.8f);
cloth.a = Mathf.Clamp01(alpha);
return cloth;
}
// ---------------------------------------------------------------- noise
private static float Hash(int x, int y, int seed)
{
unchecked
{
int h = x * 374761393 + y * 668265263 + seed * 1442695041;
h = (h ^ (h >> 13)) * 1274126177;
return ((h ^ (h >> 16)) & 0xffff) / 65535f;
}
}
private static float ValueNoise(float x, float y, int seed)
{
int xi = Mathf.FloorToInt(x);
int yi = Mathf.FloorToInt(y);
float tx = x - xi;
float ty = y - yi;
tx = tx * tx * (3f - 2f * tx);
ty = ty * ty * (3f - 2f * ty);
float a = Hash(xi, yi, seed);
float b = Hash(xi + 1, yi, seed);
float c = Hash(xi, yi + 1, seed);
float d = Hash(xi + 1, yi + 1, seed);
return Mathf.Lerp(Mathf.Lerp(a, b, tx), Mathf.Lerp(c, d, tx), ty);
}
private static float Fbm(float x, float y, int seed)
{
float value = 0f;
float amplitude = 0.5f;
for (int octave = 0; octave < 4; octave++)
{
value += amplitude * ValueNoise(x, y, seed + octave * 17);
x *= 2.03f;
y *= 2.03f;
amplitude *= 0.5f;
}
return value / 0.9375f; // 0.5 + 0.25 + 0.125 + 0.0625, so the sum stays in 0..1
}
}
}

View file

@ -0,0 +1,392 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Holds a creature to one spot of a ship's deck, however the ship moves.
///
/// The Bone Ship's archers (Skeleton_BoneShip.txt, section 6) are the Bound Sentry - a tamed archer
/// whose speeds are all zero - and zero speed alone does not keep a Character on a moving deck: it
/// is carried only as far as the game's own ground-body inheritance happens to carry it. So each
/// physics step the mount sets its position to the ship's local point and its velocity to the ship's
/// velocity at that point. Rotation is left to the archer: it turns to face what it shoots.
///
/// Runs on the OWNER of the archer only; everyone else sees the result through the creature's own
/// ZSyncTransform.
///
/// TWO WAYS TO KNOW THE SHIP. The F7 experiment sets Ship and LocalPoint directly and the mount does not
/// survive a reload (an archer that wakes without its ship is removed). The real archers are a prefab
/// of their own (BoneShipArcher) that carries this component from the start, and know their ship by its
/// id in their own ZDO: after a reload the ship is looked up again as soon as it is loaded. If the ship's
/// ZDO is gone altogether for a few seconds, the ship has sunk, and the archer goes with it - "it dies
/// with the ship", with nothing to remember.
/// </summary>
public class ShipMount : MonoBehaviour
{
/// <summary>ZDO keys on a ship's ARCHER: the ship it guards, and where it stands on it.</summary>
public const string KeyArcherShip = "RoV_bshArcherShip";
public const string KeyArcherPoint = "RoV_bshArcherPoint";
public const string KeyArcherBust = "RoV_bshArcherBust";
public const string KeyArcherPost = "RoV_bshArcherPost";
/// <summary>Seconds without the ship's ZDO before the archer decides the ship is gone.</summary>
private const float GoneAfter = 6f;
/// <summary>The ship this creature is bolted to.</summary>
public Ship Ship;
/// <summary>Where on that ship, in the ship's own space.</summary>
public Vector3 LocalPoint;
private ZNetView m_nview;
private Rigidbody m_body;
private Rigidbody m_shipBody;
private ZDOID m_shipId = ZDOID.None;
private bool m_byId;
private float m_missing;
private float m_nextResolve;
private void Awake()
{
m_nview = GetComponent<ZNetView>();
m_body = GetComponent<Rigidbody>();
// No interpolation on the archer's own body: the transform is set by hand every frame in
// LateUpdate, and a body that interpolates between physics steps would fight that and put back
// the very stutter this exists to remove.
if (m_body != null) m_body.interpolation = RigidbodyInterpolation.None;
}
private void Start()
{
if (Ship != null) { IgnoreShipColliders(); return; }
// The real archers: the ship is a number in their own ZDO. Read on EVERY client, not just the
// owner, because every client pins the visual to the ship (LateUpdate).
if (m_nview == null || !m_nview.IsValid()) return;
m_shipId = m_nview.GetZDO().GetZDOID(KeyArcherShip);
if (m_shipId == ZDOID.None) return;
LocalPoint = m_nview.GetZDO().GetVec3(KeyArcherPoint, Vector3.zero);
m_byId = true;
}
/// <summary>
/// Every frame, on every client: the archer's transform is the ship's local point, taken from the
/// ship's own (interpolated) transform at render time.
///
/// The physics pin below only moves the archer once per physics step, from where the ship was at the
/// start of that step. The ship is drawn smoothly between steps and the archer was not, so at speed
/// it jumped in 50 Hz hops against a hull that glides - "in jerks", and, trailing a step behind,
/// looking not quite attached. Setting the transform here, after everything else has moved it, makes
/// it exactly as smooth as the hull it stands on. For a remote client this also overrides the
/// position the network would give it, which is itself a few steps old.
/// </summary>
private void LateUpdate()
{
if (Ship == null)
{
if (m_byId && Time.time >= m_nextResolve)
{
m_nextResolve = Time.time + 0.5f;
TryResolveShip();
}
return;
}
transform.position = Ship.transform.TransformPoint(LocalPoint);
}
private bool TryResolveShip()
{
GameObject found = ZNetScene.instance != null ? ZNetScene.instance.FindInstance(m_shipId) : null;
Ship ship = found != null ? found.GetComponent<Ship>() : null;
if (ship == null) return false;
Ship = ship;
m_missing = 0f;
IgnoreShipColliders();
return true;
}
/// <summary>
/// Pinned inside the ship's own volume, so it must not fight the ship's colliders: with them live the
/// physics keeps trying to push it out and the mount keeps putting it back. Ignoring them costs
/// nothing - it is invulnerable, and nobody needs to bump into it.
/// </summary>
private void IgnoreShipColliders()
{
Collider[] mine = GetComponentsInChildren<Collider>(true);
Collider[] theirs = Ship.GetComponentsInChildren<Collider>(true);
foreach (Collider a in mine)
{
if (a == null) continue;
foreach (Collider b in theirs)
{
if (b != null) Physics.IgnoreCollision(a, b, true);
}
}
}
private void FixedUpdate()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (Ship == null)
{
if (m_byId) FindShip();
else if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject); // the experiment's way
return;
}
if (m_body == null) return;
if (m_shipBody == null) m_shipBody = Ship.GetComponent<Rigidbody>();
Vector3 target = Ship.transform.TransformPoint(LocalPoint);
m_body.position = target;
m_body.velocity = m_shipBody != null ? m_shipBody.GetPointVelocity(target) : Vector3.zero;
}
/// <summary>
/// Looks the ship up by id. Loaded: bolted on. Not loaded but still in the world's books: wait, it is
/// about to be (they load together). Not in the books at all, for long enough: it has sunk.
/// </summary>
private void FindShip()
{
if (TryResolveShip()) return;
if (ZDOMan.instance != null && ZDOMan.instance.GetZDO(m_shipId) != null)
{
m_missing = 0f;
return;
}
m_missing += Time.fixedDeltaTime;
if (m_missing >= GoneAfter && ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject);
}
}
/// <summary>
/// Makes an archer a BUST: the leg bones are collapsed to nothing every frame, so only the pelvis, the
/// chest and the arms show - a figurehead that shoots.
///
/// The model cannot be cut, so the legs are scaled to zero where they join the hips: everything skinned
/// to them folds into that point. A leg bone's children inherit the zero, so feet and shins go with it.
/// It is done in LateUpdate, after the animator has written its pose, so nothing animated can put them
/// back. The BONE NAMES are not verified - they are searched for ("upleg", "thigh", "upperleg") on the
/// first frame and what was found is logged. If it finds none it logs the whole skeleton, which is the
/// list the next attempt is written from.
/// </summary>
public class ShipBust : MonoBehaviour
{
private static readonly string[] LegBones = { "upleg", "thigh", "upperleg", "leg_upper" };
private readonly List<Transform> m_legs = new List<Transform>();
/// <summary>Set by the F7 experiment; the real archers say so in their ZDO instead.</summary>
public bool Force;
private void Start()
{
// On the prefab of the real archers this component is always there, and only the ones placed as a
// bust (the ZDO says so) are cut off at the waist; the deck ones keep their legs.
ZNetView nview = GetComponent<ZNetView>();
bool bust = Force || (nview != null && nview.IsValid() && nview.GetZDO().GetBool(ShipMount.KeyArcherBust, false));
if (!bust)
{
enabled = false;
return;
}
foreach (Transform t in GetComponentsInChildren<Transform>(true))
{
string n = t.name.ToLowerInvariant();
foreach (string key in LegBones)
{
if (!n.Contains(key)) continue;
// Only the topmost of a chain: a bone whose parent is already a leg is covered by it.
if (!m_legs.Contains(t.parent)) m_legs.Add(t);
break;
}
}
if (m_legs.Count > 0)
{
List<string> names = new List<string>();
foreach (Transform t in m_legs) names.Add(t.name);
Jotunn.Logger.LogInfo("[ShipBust] collapsing " + m_legs.Count + " leg bone(s): " + string.Join(", ", names.ToArray()));
return;
}
// Nothing matched: say what is there so the names can be read instead of guessed.
List<string> all = new List<string>();
foreach (Transform t in GetComponentsInChildren<Transform>(true)) all.Add(t.name);
Jotunn.Logger.LogWarning("[ShipBust] no leg bone matched. Skeleton: " + string.Join(", ", all.ToArray()));
}
private void LateUpdate()
{
foreach (Transform leg in m_legs)
{
if (leg != null) leg.localScale = Vector3.zero;
}
}
}
/// <summary>
/// A ship's archer cannot be killed - it goes down with the ship, which is the stake. Skipping
/// Character.Damage is enough: the Bound Sentry's own regeneration patch only listens to it too.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class ShipMountInvulnerablePatch
{
public static bool Prefix(Character __instance)
{
return __instance.GetComponent<ShipMount>() == null;
}
}
/// <summary>
/// The deck-finding and post table the bone ships use to place their archers.
///
/// WHERE: a local (x, z) per ship, and the height is NOT guessed - a ray is dropped from above that
/// spot and the deck is wherever it first hits the ship's own solid collider. The mast and the sail's
/// cloth collider are skipped. The point it settled on is reported, so a bad spot is fixed by editing
/// the table below, not by reading code.
/// </summary>
public static class ShipMountTest
{
private const float ShipRange = 40f;
private const float RayStartHeight = 8f;
private const float RayLength = 20f;
/// <summary>
/// One archer's place: where on the deck (local x, z), and whether it is a BUST - only the chest and
/// up shows, the legs are collapsed, and it stands on the stem as a figurehead that shoots.
/// </summary>
private struct Post
{
public Vector2 At;
public bool Bust;
public Post(float x, float z, bool bust) { At = new Vector2(x, z); Bust = bust; }
}
/// <summary>
/// The Karve's bow is at about local z = +4.8 (its WaterTrigger sits there, and the hull mesh is
/// ~10 m long); the post is a little back from the very tip so the ray finds the hull under it.
/// The large ships keep their deck posts until they get a bust of their own.
/// </summary>
private static readonly Dictionary<string, Post[]> Posts = new Dictionary<string, Post[]>
{
{ "Karve", new[] { new Post(0f, 4.3f, true) } },
{ "BoneKarve", new[] { new Post(0f, 4.3f, true) } },
{ "VikingShip", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
{ "BoneLongship", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
{ "VikingShip_Ashlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
{ "BoneAshlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
};
private static readonly Post[] DefaultPosts = { new Post(0f, 0f, false) };
/// <summary>
/// How far above the hull's surface a bust stands, in metres: the pelvis is left as a stub where the
/// legs were, and this keeps that stub inside the stem instead of above it. To be tuned by eye.
/// </summary>
private const float BustLift = 0.0f;
/// <summary>The deck under a local (x, z): the highest solid surface of THIS ship, not the mast or the sail.</summary>
private static bool FindDeck(Ship ship, Vector2 post, bool bust, out Vector3 local, out string hitName)
{
local = Vector3.zero;
hitName = "";
// A deck is flat. A bow is not: near the stem the hull's surface climbs steeply, and a flat-only
// filter (normal.y >= 0.5) found nothing there at all. A bust takes ANY surface of the ship under
// the point, and if the point is past the end of the hull it walks back toward the middle until
// something is there - the step it settled on shows in the reported local z.
float minUp = bust ? -1f : 0.5f;
float maxBack = bust ? 2.4f : 0f;
const float Step = 0.3f;
for (float back = 0f; back <= maxBack + 0.001f; back += Step)
{
Vector3 origin = ship.transform.TransformPoint(new Vector3(post.x, RayStartHeight, post.y - back));
Vector3 down = -ship.transform.up;
RaycastHit best = default(RaycastHit);
bool found = false;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.RaycastAll(origin, down, RayLength))
{
if (hit.collider == null || hit.collider.isTrigger) continue;
if (!hit.collider.transform.IsChildOf(ship.transform)) continue;
if (Vector3.Dot(hit.normal, ship.transform.up) < minUp) continue;
string n = hit.collider.name.ToLowerInvariant();
if (n.Contains("mast") || n.Contains("cloth")) continue;
if (hit.distance >= bestDistance) continue;
best = hit;
bestDistance = hit.distance;
found = true;
}
if (!found) continue;
local = ship.transform.InverseTransformPoint(best.point);
hitName = best.collider.name + (back > 0f ? " (stepped back " + back.ToString("F1") + " m)" : "");
return true;
}
return false;
}
private static Ship NearestShip()
{
Player player = Player.m_localPlayer;
if (player == null) return null;
Ship best = null;
float bestDistance = ShipRange;
foreach (Ship ship in Object.FindObjectsOfType<Ship>())
{
float distance = Vector3.Distance(ship.transform.position, player.transform.position);
if (distance >= bestDistance) continue;
best = ship;
bestDistance = distance;
}
return best;
}
private static List<ShipMount> MountsOn(Ship ship)
{
List<ShipMount> mounts = new List<ShipMount>();
foreach (Character character in Character.GetAllCharacters())
{
if (character == null) continue;
ShipMount mount = character.GetComponent<ShipMount>();
if (mount != null && mount.Ship == ship) mounts.Add(mount);
}
return mounts;
}
/// <summary>"Karve(Clone)" to "Karve".</summary>
private static string Clean(string name)
{
int paren = name.IndexOf('(');
return (paren >= 0 ? name.Substring(0, paren) : name).Trim();
}
private static void Report(string line)
{
Jotunn.Logger.LogInfo(line);
if (Console.instance != null) Console.instance.Print(line);
}
}
}

View file

@ -218,6 +218,7 @@ namespace RacesOfValheim
} }
prefab.transform.localScale = Vector3.one * TableScale; prefab.transform.localScale = Vector3.one * TableScale;
Dress(prefab, family);
ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>(); ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>();
table.m_switch = prefab.AddComponent<Switch>(); table.m_switch = prefab.AddComponent<Switch>();
@ -233,8 +234,12 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_name = displayName; piece.m_name = displayName;
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
piece.m_groundOnly = true; // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = icon; piece.m_icon = icon;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench"); Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
@ -251,6 +256,65 @@ namespace RacesOfValheim
})); }));
} }
// The look, in the table's own space BEFORE TableScale, so sizes are divided by it to come out
// in real metres. The cover lies where the map was: x -2.06 to 0.62, read off the mesh. Its top
// is the Dvergar bank's PileHeight, on the same vanilla mesh; the mesh's own height is no use
// here, since the writing desk stands taller than the map.
private const float CoverTop = 1.05f;
private static readonly Vector3 TradeSpot = new Vector3(-0.75f, CoverTop, 0.2f);
private static readonly Vector3 SkullSpot = new Vector3(-1.55f, CoverTop, 0.35f);
private const float AnvilSize = 0.75f;
private const float MealSize = 0.6f;
private const float SkullSize = 0.45f;
/// <summary>
/// The map painted over - a sheet of chainmail for the smith, a red and white tablecloth for the
/// cook - with the trade's own work on it (an anvil, a meal) and a skeleton's skull beside it.
/// </summary>
private static void Dress(GameObject prefab, ButlerFamily family)
{
bool forge = family == ButlerFamily.Forge;
LayCover(prefab, forge ? "SmithMail" : "CookCloth", metal: forge);
float metres = 1f / TableScale;
if (forge)
{
ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2",
TradeSpot, Quaternion.identity, AnvilSize * metres, "Butler", activeOnly: true);
}
else
{
ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter",
TradeSpot, Quaternion.identity, MealSize * metres, "Butler", activeOnly: true);
}
ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
SkullSpot, Quaternion.Euler(0f, -150f, 0f), SkullSize * metres, "Butler", activeOnly: true);
}
/// <summary>
/// The cartography table's own textures with the map painted over, offline:
/// scripts/paint_cook_cloth.py (CookCloth) and scripts/paint_smith_mail.py (SmithMail). Each set
/// has its own worn texture for a damaged table (a stained cloth, rusted mail) and its own normal
/// map, so the coastline's relief does not show through. The mail also brings a metallic map,
/// which is what makes the rings shine; the cloth keeps vanilla's, which is metal nowhere.
/// </summary>
private static void LayCover(GameObject prefab, string set, bool metal)
{
var cover = new System.Collections.Generic.Dictionary<string, Texture>();
AddCover(cover, "Cartographer_d", set + "_d.png", false);
AddCover(cover, "Cartographer_worn_d", set + "_worn_d.png", false);
AddCover(cover, "Cartographer_n", set + "_n.png", true);
if (metal) AddCover(cover, "Cartographer_m", set + "_m.png", true);
PieceLook.Retexture(prefab.transform, cover);
}
private static void AddCover(System.Collections.Generic.Dictionary<string, Texture> cover,
string vanilla, string resource, bool linear)
{
Texture2D texture = PieceLook.LoadTexture(resource, linear);
if (texture != null) cover[vanilla] = texture;
}
public static void EnsureKnown(Player player) public static void EnsureKnown(Player player)
{ {
if (player == null) return; if (player == null) return;

View file

@ -270,7 +270,11 @@ namespace RacesOfValheim
else if (Time.time >= m_nextFightScan) else if (Time.time >= m_nextFightScan)
{ {
m_nextFightScan = Time.time + FightScanInterval; m_nextFightScan = Time.time + FightScanInterval;
if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null) // FindClosestEnemy takes its first match at ANY distance (it only compares against
// maxDistance once it holds one), so with a deer anywhere in the loaded zones it never
// returned null and vanilla kept the tick: the worker idled about instead of working.
Character enemy = BaseAI.FindClosestEnemy(m_character, transform.position, FightRange);
if (enemy != null && Vector3.Distance(enemy.transform.position, transform.position) <= FightRange)
{ {
m_fightUntil = Time.time + FightLinger; m_fightUntil = Time.time + FightLinger;
} }
@ -359,8 +363,22 @@ namespace RacesOfValheim
Scan(anchor.Value); Scan(anchor.Value);
ExpirePenalties(); ExpirePenalties();
if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; } // A delivery gets its own clock like any other job. Returning early here left it with the
// load's deadline: a slow trip, or a fight on the way, made it late before it started, and
// it timed out and was planned again on every tick, frozen with the goods in hand.
Job job;
if (m_payload.Count > 0) job = PlanDelivery(anchor.Value);
else job = PlanWork();
if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
{
m_jobDeadline = Time.time + JobTimeout;
}
m_job = job;
}
private Job PlanWork()
{
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on // The forge has no clock: a smelter holds its ore indefinitely and puts its own output on
// the floor, so PlanRescue would ask a question whose answer is always no. The smith is a // the floor, so PlanRescue would ask a question whose answer is always no. The smith is a
// four-state machine and the cook is a five-state one, and that is the whole of the // four-state machine and the cook is a five-state one, and that is the whole of the
@ -372,13 +390,7 @@ namespace RacesOfValheim
// in return, because FuelWanted is zero for a station with no work: an empty furnace asks // in return, because FuelWanted is zero for a station with no work: an empty furnace asks
// for no coal, gets filled, and only then becomes worth stoking. // for no coal, gets filled, and only then becomes worth stoking.
Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null; Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null;
job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad(); return job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
{
m_jobDeadline = Time.time + JobTimeout;
}
m_job = job;
} }
/// <summary> /// <summary>
@ -630,8 +642,10 @@ namespace RacesOfValheim
// coal, so gating the delivery on free slots sent the servant back to the chest with // coal, so gating the delivery on free slots sent the servant back to the chest with
// the coal it had just fetched - and then PlanFuel sent it out for the same coal again, // the coal it had just fetched - and then PlanFuel sent it out for the same coal again,
// forever. AcceptsAnything already asks the right question of both doors. // forever. AcceptsAnything already asks the right question of both doors.
// A station it could not reach is in the penalty box: asking it again straight away
// is the same failed trip.
ButlerStation station = StationById(target); ButlerStation station = StationById(target);
if (station != null && station.Alive && station.Operable && AcceptsAnything(station)) if (station != null && station.Alive && station.Operable && AcceptsAnything(station) && !IsPenalised(target))
{ {
return new Job return new Job
{ {

View file

@ -143,7 +143,8 @@ namespace RacesOfValheim
string status = servant.Status; string status = servant.Status;
if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting"); if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting");
return m_title + "\n" + status; // m_title is a $token, and a hover text goes to the HUD as it is: nothing localizes it later.
return Localization.instance.Localize(m_title) + "\n" + status;
} }
/// <summary> /// <summary>

View file

@ -26,11 +26,16 @@ namespace RacesOfValheim
// Whole sections that are cosmetic or per-player. // Whole sections that are cosmetic or per-player.
private static readonly string[] LocalSections = private static readonly string[] LocalSections =
{ {
"Alfar - Look",
"Aswid - Claws", "Aswid - Claws",
"Aswid - Eyes", "Aswid - Eyes",
"Fenrir - Appearance",
"Skeleton - Visuals", "Skeleton - Visuals",
// Food and stamina for a Skeleton who wants them: each only gives up an advantage.
"Skeleton - Mortal Habits",
"Sverm - Dorsal Spines", "Sverm - Dorsal Spines",
"Sverm - Emberform", "Sverm - Emberform",
"Trol - Appearance",
"War Vulture - Model", "War Vulture - Model",
"War Vulture - Interface", "War Vulture - Interface",
}; };
@ -39,6 +44,13 @@ namespace RacesOfValheim
private static readonly string[] LocalKeyParts = private static readonly string[] LocalKeyParts =
{ {
"marker light", "tint", "colour", "color", "glow", "swarm scale", "log rounds", "debug", "marker light", "tint", "colour", "color", "glow", "swarm scale", "log rounds", "debug",
// The Aswid's seasick camera: motion makes some players ill, so a server cannot force it.
"camera sway",
// Each player picks their own True Form: a player model mod (VRM and the like) breaks
// under the troll costume, so a server cannot be allowed to force the costume on.
"legacy true form",
// The player's own pick of bat flight; the synced Bat Flight Rule can override it.
"free bat flight",
}; };
public static void Apply(ConfigFile config) public static void Apply(ConfigFile config)

View file

@ -0,0 +1,32 @@
using UnityEngine;
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The mod-wide debug switches, in one "Debug" section rather than one per race. Bound last
/// from RacesOfValheim.Awake(), so Configuration Manager lists the section at the bottom.
///
/// Every entry stays local (never synced from the server): ConfigSync leaves KeyboardShortcut
/// entries and any key containing "debug" alone, so keep "Debug" in the key names.
/// </summary>
public static class DebugConfig
{
public static ConfigEntry<bool> EnableDebugKey;
public static ConfigEntry<KeyboardShortcut> DebugKey;
public static ConfigEntry<bool> LogFormHits;
public static void Bind(ConfigFile config)
{
const string section = "Debug";
EnableDebugKey = config.Bind(section, "Debug: Enable Debug Key", false,
new ConfigDescription("Turns on the debug key below. Leave it off unless you are sending a bug report."));
DebugKey = config.Bind(section, "Debug Key", new KeyboardShortcut(KeyCode.F8),
new ConfigDescription("Toggles the melee reach readout (top left and log) and writes what the Alfar drones and the camera's target are doing to the log."));
// Was "Fenrir - Debug" / "Debug: Log Form Hits" until v1.6.10. It covers the Skadi,
// Sverm and Trol forms too (FormMelee.LogHit), so it moved here.
LogFormHits = config.Bind(section, "Debug: Log Form Hits", false,
new ConfigDescription("Writes one log line per form claw, bite or swing: what was in reach, what it hit, and why anything was skipped. For bug reports about attacks that do no damage."));
}
}
}

View file

@ -0,0 +1,263 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// A form that flies on Character's native flying-creature movement (m_flying) and is steered
/// by DirectedFlightPatch. The Skadi's drakes were the first; the Aswid's bat moved onto it from
/// vanilla's debug-fly flag in the 2026 rebalance, so the two share one set of controls and
/// differ only in the numbers each form hands back here.
/// </summary>
public interface IDirectedFlyer
{
/// <summary>False while the form is on the ground on purpose (a landed drake).</summary>
bool IsFlying { get; }
/// <summary>Time.time of the last powered or grounded moment; the hover window counts from it.</summary>
float LastPoweredTime { get; set; }
float TurnSpeed { get; }
float GlideSpeed { get; }
float BoostSpeed { get; }
float SprintSpeed { get; }
float ReverseSpeed { get; }
float LiftoffSpeed { get; }
float HoverSeconds { get; }
/// <summary>Stamina per second for powered flight (forward or reverse). 0 is free.</summary>
float PoweredStaminaPerSecond { get; }
/// <summary>Stamina per second for the sprint, charged on top of the powered cost.</summary>
float SprintStaminaPerSecond { get; }
/// <summary>False forbids powered flight outright, so the form can only glide and sink.</summary>
bool CanPower { get; }
}
public static class DirectedFlight
{
/// <summary>The local player's flying form, if any. Set and cleared by the form itself.</summary>
public static IDirectedFlyer Active { get; private set; }
public static void Register(IDirectedFlyer flyer) { Active = flyer; }
public static void Unregister(IDirectedFlyer flyer)
{
if (Active == flyer) Active = null;
}
/// <summary>The active form, only while it is actually in the air.</summary>
public static IDirectedFlyer Flying => Active != null && Active.IsFlying ? Active : null;
}
// The form flips the player into Character's native flying-creature movement (m_flying = true)
// instead of the debug-fly noclip, which lets us feed it a full 3D move direction.
// Character.UpdateFlying normally reads whatever m_moveDir the vanilla input pipeline last
// wrote (ground-plane WASD relative to camera yaw only); this patch overwrites it every frame
// with the camera's actual look direction (pitch included) so the player always glides toward
// wherever the mouse is aiming, with W powering forward, Shift spending stamina for a burst of
// speed, and S beating backwards away from whatever you are looking at.
[HarmonyPatch(typeof(Character), "UpdateFlying")]
public static class DirectedFlightPatch
{
// Tangent of the unpowered descent angle: 0.4 sinks at roughly 22 degrees below level.
private const float DESCENT_SLOPE = 0.4f;
// How much of the aim heading survives the climb out of water. Mostly up, with enough
// forward in it that the player still chooses which shore they surface towards.
private const float LIFTOFF_HEADING_BLEND = 0.35f;
// How far the left stick has to be pushed before it counts as W or S.
private const float StickThreshold = 0.5f;
/// <summary>
/// True while the local player is beating backwards this frame. Read by
/// SkadiReverseFacingPatch, which keeps the body pointed at the camera while it happens.
/// </summary>
public static bool Reversing { get; private set; }
// The September 2026 hotfix dropped the bool parameter from ZInput.GetJoyLeftStickY.
// A direct call binds to whichever signature we compiled against and throws
// MissingMethodException on the other, so resolve it at runtime and accept either.
private static readonly MethodInfo JoyLeftStickYMethod =
AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new System.Type[0]) ??
AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new[] { typeof(bool) });
private static float JoyLeftStickY()
{
if (JoyLeftStickYMethod == null) return 0f;
return (float)JoyLeftStickYMethod.Invoke(null, JoyLeftStickYArgs);
}
// Old signature: pass smooth = true, which was its default.
private static readonly object[] JoyLeftStickYArgs =
JoyLeftStickYMethod != null && JoyLeftStickYMethod.GetParameters().Length == 1 ? new object[] { true } : null;
public static void Prefix(Character __instance, float dt)
{
if (__instance != Player.m_localPlayer) return;
IDirectedFlyer form = DirectedFlight.Flying;
if (form == null)
{
Reversing = false;
return;
}
var traverse = Traverse.Create(__instance);
Vector3 lookDir = Player.m_localPlayer.GetLookDir();
bool input = RaceInput.Allowed;
// The pad's half of W/S: the left stick, read with vanilla's own sign -
// PlayerController.FixedUpdate takes forward as the NEGATED GetJoyLeftStickY.
// Flight only knows powered forward, reverse or neither, so the stick is a
// threshold, not a throttle. Steering stays on the camera, i.e. the right stick.
float stick = -JoyLeftStickY();
// The keyboard side reads vanilla's own Forward/Backward/Run actions, so a key the
// player rebound in the settings flies too, not just W, S and Shift.
bool forward = input && (ZInput.GetButton("Forward") || stick > StickThreshold);
// Forward wins a W+S mash rather than the two cancelling into a dead hover.
bool backward = input && !forward && (ZInput.GetButton("Backward") || stick < -StickThreshold);
// Sprint on a pad is vanilla's run button, wherever the chosen layout puts it.
bool sprintKey = input && (ZInput.GetButton("Run") || ZInput.GetButton("JoyRun"));
bool onGround = __instance.IsOnGround();
// IsSwimming is the exact test UpdateMotion uses to hand the frame to UpdateSwimming
// instead of UpdateFlying, so it is also the one condition DirectedFlightWaterPatch has
// to take back. Its half-second tail past leaving the water is welcome here - it
// keeps the climb going just long enough to clear the surface properly.
bool inWater = __instance.IsSwimming();
// Powered flight is paid for up front, per frame. A form that cannot pay - out of
// stamina, or barred from powering at all - falls through to the glide below rather
// than out of the sky.
if ((forward || backward) && !(form.CanPower && TrySpendStamina(form.PoweredStaminaPerSecond, dt)))
{
forward = false;
backward = false;
}
Reversing = backward;
// m_run only picks between the two fly speeds. Every mode now has its own speed, so
// leave it off and drive all of them through m_flySlowSpeed.
traverse.Field("m_run").SetValue(false);
// UpdateFlying rotates the body toward m_moveDir on its own, but at m_flyTurnSpeed,
// which sits at Character's 12 deg/s default because the Player prefab was never set
// up as a flying creature - a 90 degree turn would take over seven seconds, so the
// model reads as not turning at all. Give it a speed that suits a flying form.
traverse.Field("m_flyTurnSpeed").SetValue(form.TurnSpeed);
// Powered flight, ground contact and clawing out of water all refresh the hover
// window, so none of them can be followed by an immediate sink.
if (forward || backward || onGround || inWater) form.LastPoweredTime = Time.time;
Vector3 moveDir = lookDir;
float speed;
if (inWater)
{
// Wet wings still beat. Water used to be a trap: UpdateMotion hands a swimming
// character to UpdateSwimming before it ever looks at m_flying, so a form that
// touched the sea was stuck paddling with the flight controls doing nothing.
// DirectedFlightWaterPatch gives the frame back to flight, and this branch spends
// it climbing regardless of where the camera points, so the surface is always
// something you break out of rather than something you sit in. Free on purpose:
// a form that could not pay to leave the water would drown in it.
moveDir = (Vector3.up + FlatHeading(__instance, lookDir) * LIFTOFF_HEADING_BLEND).normalized;
speed = form.LiftoffSpeed;
}
else if (backward)
{
// Straight reverse thrust along the aim, pitch included: look down and beat back
// and you rise away from what you are looking at, which is the whole point of
// having a reverse - you can retreat without taking your eyes (or your breath
// attack, which fires along the same vector) off the target.
moveDir = -lookDir;
speed = form.ReverseSpeed;
}
else if (forward)
{
speed = form.BoostSpeed;
if (sprintKey && TrySpendStamina(form.SprintStaminaPerSecond, dt)) speed = form.SprintSpeed;
}
else if (onGround || Time.time - form.LastPoweredTime < form.HoverSeconds)
{
// Holding station: on the ground this keeps a touchdown from sliding the player
// forward forever, and in the air it gives the beats of level flight before the
// form starts to sink. m_moveDir stays full length so the body still turns to
// face the camera, and zeroing the speed (rather than the rigidbody velocity)
// avoids fighting the AddForce UpdateFlying queues, which caused visible jitter.
speed = 0f;
}
else
{
// Unpowered flight is a glide, not a hover with a joystick: drift along the
// heading the camera faces while losing height, so aiming at the sky without
// holding W no longer climbs.
moveDir = (FlatHeading(__instance, lookDir) + Vector3.down * DESCENT_SLOPE).normalized;
speed = form.GlideSpeed;
}
traverse.Field("m_moveDir").SetValue(moveDir);
traverse.Field("m_flySlowSpeed").SetValue(speed);
}
/// <summary>Aim flattened onto the ground plane, falling back to the body's own facing
/// when the player is looking straight up or down.</summary>
private static Vector3 FlatHeading(Character character, Vector3 lookDir)
{
Vector3 heading = new Vector3(lookDir.x, 0f, lookDir.z);
if (heading.sqrMagnitude < 0.0001f)
{
heading = character.transform.forward;
heading.y = 0f;
}
return heading.normalized;
}
/// <summary>
/// Charges this frame of a per-second cost. Returns false when the player cannot pay.
/// A rate of zero is always paid, so a free mode costs nothing and never fails.
/// </summary>
private static bool TrySpendStamina(float perSecond, float dt)
{
if (perSecond <= 0f) return true;
Player player = Player.m_localPlayer;
if (player == null) return false;
float cost = perSecond * dt;
if (!player.HaveStamina(cost)) return false;
player.UseStamina(cost);
return true;
}
}
/// <summary>
/// Character.UpdateMotion asks IsSwimming before it asks m_flying, so a flying form that
/// touched water was handed to UpdateSwimming every frame: the flight patch above never ran,
/// the form paddled on the surface, and there was no way back into the air short of finding
/// land. Hand those frames back to UpdateFlying, which is the only motion path the two methods
/// contend over: nothing else calls either of them, and everything that merely asks
/// IsSwimming - the Wet status, the animator, stamina - is left alone.
/// </summary>
[HarmonyPatch(typeof(Character), "UpdateSwimming")]
public static class DirectedFlightWaterPatch
{
private static readonly MethodInfo UpdateFlyingMethod = AccessTools.Method(typeof(Character), "UpdateFlying");
public static bool Prefix(Character __instance, float dt)
{
if (__instance != Player.m_localPlayer) return true;
if (DirectedFlight.Flying == null) return true;
// Fail open: if a game update ever renames the method, swim normally rather than
// freezing the player in place with no motion update at all.
if (UpdateFlyingMethod == null) return true;
UpdateFlyingMethod.Invoke(__instance, new object[] { dt });
return false;
}
}
}

View file

@ -24,10 +24,19 @@ namespace RacesOfValheim
{ "HareMeat", "CookedHareMeat" }, { "HareMeat", "CookedHareMeat" },
{ "ChickenMeat", "CookedChickenMeat" }, { "ChickenMeat", "CookedChickenMeat" },
{ "BugMeat", "CookedBugMeat" }, { "BugMeat", "CookedBugMeat" },
{ "VoltureMeat", "RoastedVoltureMeat" }, { "VoltureMeat", "CookedVoltureMeat" },
{ "GreydwarfEye", "DeerStew" }, { "GreydwarfEye", "DeerStew" },
{ "Entrails", "Sausages" }, { "Entrails", "Sausages" },
{ "Bloodbag", "BloodPudding" } { "Bloodbag", "BloodPudding" },
{ "MooseMeat", "CookedMooseMeat" },
// Bjorn, the Valheim 1.0 bear.
{ "BjornMeat", "CookedBjornMeat" },
// Ashlands.
{ "AsksvinMeat", "CookedAsksvinMeat" },
{ "BoneMawSerpentMeat", "CookedBoneMawSerpentMeat" },
// Raw blubber keeps its own name and icon (EdibleUncooked_ copies them from the raw
// item) and gives the stats of Seal Meat Soup.
{ "SealBlubber", "SealSoup" }
}; };
[HarmonyPatch(typeof(Humanoid), "UseItem")] [HarmonyPatch(typeof(Humanoid), "UseItem")]
@ -86,6 +95,11 @@ namespace RacesOfValheim
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>(); var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("eat"); if (zanim != null) zanim.SetTrigger("eat");
} }
else
{
// Vanilla's refusal message, which EatFood never shows by itself
player.CanEat(customItemDrop.m_itemData, true);
}
return false; // Skip native UseItem return false; // Skip native UseItem
} }
} }
@ -150,9 +164,10 @@ namespace RacesOfValheim
return false; // Skip native EatFood return false; // Skip native EatFood
} }
// Inventory full // Full, and no slot holds this flesh. Native EatFood replaces the most
__result = false; // depleted meal past half its time, or refuses - vanilla's own rule. This
return false; // used to refuse outright, with no message.
return true;
} }
else else
{ {

View file

@ -251,8 +251,12 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName; piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
piece.m_groundOnly = true; // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = BorrowIcon(TrophyDraugr); piece.m_icon = BorrowIcon(TrophyDraugr);
// Learned on the Furling's bushes: a Piece added to world scenery is born with no icon // Learned on the Furling's bushes: a Piece added to world scenery is born with no icon

View file

@ -76,6 +76,12 @@ namespace RacesOfValheim
private const float PileHeight = 1.05f; private const float PileHeight = 1.05f;
private const float PileSize = 0.45f; private const float PileSize = 0.45f;
// The dressing, in the same unscaled table space as the pile. The pile owns the centre, so the
// tankard stands just clear of it, on the near side.
private static readonly Color BankWoodTint = new Color(0.62f, 0.55f, 0.5f, 1f);
private static readonly Vector3 TankardSpot = new Vector3(0.45f, PileHeight, -0.25f);
private const float TankardSize = 0.38f;
public class Troop public class Troop
{ {
public string Id; public string Id;
@ -276,6 +282,12 @@ namespace RacesOfValheim
prefab.transform.localScale = Vector3.one * TableScale; prefab.transform.localScale = Vector3.one * TableScale;
// A counting table, not a map table: darker wood and a dvergr tankard beside the coin.
// Tinted BEFORE the tankard goes on, or it would be darkened too.
PieceLook.Tint(prefab.transform, BankWoodTint);
ModelBorrow.Attach(prefab.transform, "BankTankard", "Tankard_dvergr",
TankardSpot, Quaternion.identity, TankardSize, "Dvergar", activeOnly: true);
DvergarBancoBehaviour bank = prefab.AddComponent<DvergarBancoBehaviour>(); DvergarBancoBehaviour bank = prefab.AddComponent<DvergarBancoBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true)) foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
@ -335,8 +347,12 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName; piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
piece.m_groundOnly = true; // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = BorrowIcon("TrophyDvergr"); piece.m_icon = BorrowIcon("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench"); Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");

View file

@ -157,7 +157,7 @@ namespace RacesOfValheim
if (CountCoins(inventory) < price) if (CountCoins(inventory) < price)
{ {
player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney"); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_not_enough_coins"));
return; return;
} }

View file

@ -90,8 +90,12 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName; piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
piece.m_groundOnly = true; // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"); piece.m_icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench"); Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");

View file

@ -0,0 +1,275 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// A Dvergar builds the black marble and Yggdrasil wood building pieces with stone and fine
/// wood (Wargles' suggestion). Only structural pieces: stations, furniture, containers and
/// fires keep their cost, so nothing with a progression role gets cheaper.
///
/// The swap is done on the piece prefabs of the Dvergar's own client. The build menu, the
/// "known piece" check and ConsumeResources all read the prefab's m_resources, so the menu
/// lists the pieces once stone or fine wood is known, and the player pays the swapped cost.
///
/// The refund is the catch. Piece.DropResources gives back whatever m_resources says on the
/// machine that destroys the piece; vanilla never records what was paid. Without help a human
/// deconstructing a Dvergar's stone wall would get black marble, and a Dvergar deconstructing a
/// vanilla wall would get stone. So a cheap piece is tagged on its ZDO when placed, with the
/// ratios it was paid at, and DropResources is given the matching cost on every client.
/// </summary>
public static class DvergarCheapBuilding
{
// The ratios a cheap piece was paid at. Absent (0) on every piece placed at full cost.
public const string StoneRatioZdoKey = "RacesOfValheim_DvergarCheapStone";
public const string WoodRatioZdoKey = "RacesOfValheim_DvergarCheapWood";
private const string BlackMarble = "BlackMarble";
private const string YggdrasilWood = "YggdrasilWood";
private const string Stone = "Stone";
private const string FineWood = "FineWood";
private const string LabelName = "rov_dvergar_cheap";
private const Piece.UsageTagFlags StructuralTags =
Piece.UsageTagFlags.Building | Piece.UsageTagFlags.Floor | Piece.UsageTagFlags.Wall |
Piece.UsageTagFlags.Roof | Piece.UsageTagFlags.Architecture | Piece.UsageTagFlags.Stairs |
Piece.UsageTagFlags.Doors;
// Piece prefab name -> its vanilla cost. Collected once and kept: the prefabs live for the
// whole session, and the originals must survive every swap.
private static Dictionary<string, Piece.Requirement[]> originals;
private static Dictionary<string, Piece> prefabs;
private static ItemDrop stoneItem, fineWoodItem;
// "" while the prefabs carry their vanilla cost, otherwise the ratios they were swapped at.
private static string appliedKey = "";
private static bool Collect()
{
if (originals != null) return true;
if (ObjectDB.instance == null) return false;
GameObject hammer = ObjectDB.instance.GetItemPrefab("Hammer");
PieceTable table = hammer != null ? hammer.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces : null;
stoneItem = ObjectDB.instance.GetItemPrefab(Stone)?.GetComponent<ItemDrop>();
fineWoodItem = ObjectDB.instance.GetItemPrefab(FineWood)?.GetComponent<ItemDrop>();
if (table == null || stoneItem == null || fineWoodItem == null) return false;
originals = new Dictionary<string, Piece.Requirement[]>();
prefabs = new Dictionary<string, Piece>();
foreach (GameObject go in table.m_pieces)
{
Piece piece = go != null ? go.GetComponent<Piece>() : null;
if (piece == null || piece.m_resources == null || !UsesSwappedMaterial(piece) || !IsBuildingPiece(piece)) continue;
originals[go.name] = piece.m_resources;
prefabs[go.name] = piece;
// The list to read once in game: every piece that changes cost, and where it is built.
Jotunn.Logger.LogInfo($"[Dvergar] Cheap building: {go.name} at {(piece.m_craftingStation != null ? piece.m_craftingStation.name : "no station")}, {Describe(piece.m_resources)} -> {Describe(BuildCheap(piece.m_resources, 3, 2))} (at 3/2)");
}
Jotunn.Logger.LogInfo($"[Dvergar] Cheap building: {originals.Count} pieces.");
return true;
}
private static bool UsesSwappedMaterial(Piece piece)
{
foreach (Piece.Requirement req in piece.m_resources)
{
if (req.m_resItem == null) continue;
string name = req.m_resItem.name;
if (name == BlackMarble || name == YggdrasilWood) return true;
}
return false;
}
private static bool IsBuildingPiece(Piece piece)
{
bool structural = piece.m_category == Piece.PieceCategory.BuildingWorkbench
|| piece.m_category == Piece.PieceCategory.BuildingStonecutter
|| (piece.m_usage & StructuralTags) != 0;
if (!structural) return false;
if ((piece.m_usage & Piece.UsageTagFlags.Crafting) != 0) return false;
// Anything that does a job keeps its cost, whatever its tags say.
return piece.GetComponentInChildren<CraftingStation>() == null
&& piece.GetComponentInChildren<StationExtension>() == null
&& piece.GetComponentInChildren<Container>() == null
&& piece.GetComponentInChildren<Fireplace>() == null
&& piece.GetComponentInChildren<Smelter>() == null
&& piece.m_comfort <= 0;
}
/// <summary>
/// The cost with black marble and Yggdrasil wood swapped out. New Requirement objects
/// throughout: the originals are shared with the prefab and must stay untouched. A
/// material the piece already had (some marble pieces also ask for stone) is merged.
/// </summary>
private static Piece.Requirement[] BuildCheap(Piece.Requirement[] original, int stoneRatio, int woodRatio)
{
var result = new List<Piece.Requirement>();
foreach (Piece.Requirement req in original)
{
ItemDrop item = req.m_resItem;
int amount = req.m_amount;
if (item != null && item.name == BlackMarble) { item = stoneItem; amount *= stoneRatio; }
else if (item != null && item.name == YggdrasilWood) { item = fineWoodItem; amount *= woodRatio; }
Piece.Requirement same = item != null ? result.Find(r => r.m_resItem == item) : null;
if (same != null)
{
same.m_amount += amount;
continue;
}
result.Add(new Piece.Requirement
{
m_resItem = item,
m_amount = amount,
m_extraAmountOnlyOneIngredient = req.m_extraAmountOnlyOneIngredient,
m_amountPerLevel = req.m_amountPerLevel,
m_upgraderResource = req.m_upgraderResource,
m_recover = req.m_recover,
});
}
return result.ToArray();
}
private static string Describe(Piece.Requirement[] reqs)
{
var parts = new List<string>();
foreach (Piece.Requirement req in reqs)
{
if (req.m_resItem != null) parts.Add($"{req.m_amount} {req.m_resItem.name}");
}
return string.Join(", ", parts);
}
/// <summary>
/// Puts the cost the local player should see on the prefabs. Returns whether anything
/// changed, so the caller knows to refresh the build menu.
/// </summary>
private static bool Apply(bool cheap)
{
int stone = DvergarConfigManagement.CheapStonePerBlackMarble.Value;
int wood = DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value;
string key = cheap ? stone + "/" + wood : "";
if (key == appliedKey) return false;
foreach (var pair in originals)
{
if (!prefabs.TryGetValue(pair.Key, out Piece prefab) || prefab == null) continue;
prefab.m_resources = cheap ? BuildCheap(pair.Value, stone, wood) : pair.Value;
}
appliedKey = key;
return true;
}
private static bool IsSwapped(Piece piece)
{
return appliedKey != "" && piece != null && originals != null
&& originals.ContainsKey(Utils.GetPrefabName(piece.gameObject.name));
}
/// <summary>
/// Keeps the prefabs in step with the local player: a Dvergar with the option on sees the
/// cheap cost, anyone else the vanilla one. Checked every frame because the race can change
/// mid-session (resetrace) and the ratios with the server's config; the check is a string
/// compare unless something changed.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Dvergar_CheapBuildingSync_Patch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || !Collect()) return;
bool cheap = DvergarConfigManagement.CheapBuildingEnabled.Value && DvergarRace.IsDvergar();
if (Apply(cheap)) Traverse.Create(__instance).Method("UpdateAvailablePiecesList").GetValue();
}
}
/// <summary>
/// Tags a piece placed at the cheap cost. SetCreator is called once, by PlacePiece, on the
/// placing client, right after the piece was paid for from the same prefab cost.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))]
public static class Dvergar_CheapBuildingTag_Patch
{
public static void Postfix(Piece __instance)
{
if (!IsSwapped(__instance)) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
nview.GetZDO().Set(StoneRatioZdoKey, DvergarConfigManagement.CheapStonePerBlackMarble.Value);
nview.GetZDO().Set(WoodRatioZdoKey, DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value);
}
}
/// <summary>
/// Gives back what the piece cost: the cheap materials at the ratios it was paid at for a
/// tagged piece, the vanilla cost for every other one, whoever destroys it and whatever
/// cost this client's prefab carries right now.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))]
public static class Dvergar_CheapBuildingRefund_Patch
{
public static void Prefix(Piece __instance)
{
if (!Collect()) return;
if (!originals.TryGetValue(Utils.GetPrefabName(__instance.gameObject.name), out Piece.Requirement[] original)) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
ZDO zdo = nview != null && nview.IsValid() ? nview.GetZDO() : null;
int stone = zdo != null ? zdo.GetInt(StoneRatioZdoKey, 0) : 0;
int wood = zdo != null ? zdo.GetInt(WoodRatioZdoKey, 0) : 0;
__instance.m_resources = stone > 0 && wood > 0 ? BuildCheap(original, stone, wood) : original;
}
}
/// <summary>
/// The Dvergar icon on every swapped piece in the hammer menu. Valheim 1.0
/// draws that menu with BuildUi, one pooled BuildUiPieceButton per piece, and Setup is
/// where a button takes its piece. The old Hud.UpdatePieceList grid still runs but is
/// hidden, so a label there is never seen.
/// </summary>
[HarmonyPatch(typeof(BuildUiPieceButton), nameof(BuildUiPieceButton.Setup))]
public static class Dvergar_CheapBuildingLabel_Patch
{
public static void Postfix(BuildUiPieceButton __instance, Piece pieceInfo)
{
bool cheap = IsSwapped(pieceInfo);
Transform label = __instance.transform.Find(LabelName);
if (label == null)
{
if (!cheap) return;
label = CreateLabel(__instance.transform);
}
if (label.gameObject.activeSelf != cheap) label.gameObject.SetActive(cheap);
}
private static Transform CreateLabel(Transform button)
{
var obj = new GameObject(LabelName, typeof(RectTransform));
obj.transform.SetParent(button, false);
// The race's own icon in the bottom-right corner, as the race menu and the build
// panel's race requirement show it: no text, so it fits in every language.
var rect = (RectTransform)obj.transform;
rect.anchorMin = rect.anchorMax = rect.pivot = new Vector2(1f, 0f);
rect.anchoredPosition = new Vector2(-2f, 2f);
rect.sizeDelta = new Vector2(22f, 22f);
var image = obj.AddComponent<Image>();
image.sprite = RacesOfValheim.RaceIcon(DvergarConfig.RaceId);
image.preserveAspect = true;
image.raycastTarget = false;
return obj.transform;
}
}
}
}

View file

@ -124,9 +124,11 @@ namespace RacesOfValheim
// still clearing by about 2mm. Same size of eye, sitting deeper, and the cap is flatter // still clearing by about 2mm. Same size of eye, sitting deeper, and the cap is flatter
// for it - which is what reads as set into the skull rather than resting on it. // for it - which is what reads as set into the skull rather than resting on it.
public static readonly float EyeSeparation = 0.032f; // half the distance between them public static readonly float EyeSeparation = 0.032f; // half the distance between them
public static readonly float EyeForward = 0.081f; // centre ~63mm out public static readonly float EyeForward = 0.085f; // 0.081 left the smaller ball buried
public static readonly float EyeHeight = 0.181f; // ~15mm lower than before public static readonly float EyeHeight = 0.181f; // ~15mm lower than before
public static readonly float EyeSize = 0.062f; // ~48mm across, so a 24mm radius // Then cut down after playtest: at 0.062 the cap read as two lamps covering the face. An
// 18mm radius at the same depth leaves a cap of about 22mm on a 0.78 Dvergar.
public static readonly float EyeSize = 0.036f;
// How hard the eyes burn. The colours the game gives a starred dverger are HDR - one star // How hard the eyes burn. The colours the game gives a starred dverger are HDR - one star
// is (0, 4, 3.3) - and anything past 1 clips to white on the way to the bloom pass, which // is (0, 4, 3.3) - and anything past 1 clips to white on the way to the bloom pass, which

View file

@ -57,6 +57,11 @@ namespace RacesOfValheim
public static ConfigEntry<float> RunicOverchargeWindow; public static ConfigEntry<float> RunicOverchargeWindow;
public static ConfigEntry<float> RunicOverchargeCooldown; public static ConfigEntry<float> RunicOverchargeCooldown;
// ─── Cheap Building ───────────────────────────────────────────────────────
public static ConfigEntry<bool> CheapBuildingEnabled;
public static ConfigEntry<int> CheapStonePerBlackMarble;
public static ConfigEntry<int> CheapFineWoodPerYggdrasil;
public static void Bind(ConfigFile config) public static void Bind(ConfigFile config)
{ {
const string keybinds = "Dvergar - Keybinds"; const string keybinds = "Dvergar - Keybinds";
@ -106,6 +111,14 @@ namespace RacesOfValheim
new ConfigDescription("Seconds a loaded charge is held before it lapses unused.", new AcceptableValueRange<float>(1f, 60f))); new ConfigDescription("Seconds a loaded charge is held before it lapses unused.", new AcceptableValueRange<float>(1f, 60f)));
RunicOverchargeCooldown = config.Bind(overcharge, "Cooldown", 60f, RunicOverchargeCooldown = config.Bind(overcharge, "Cooldown", 60f,
new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 300f))); new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 300f)));
const string building = "Dvergar - Cheap Building";
CheapBuildingEnabled = config.Bind(building, "Enabled", true,
new ConfigDescription("A Dvergar builds the black marble and Yggdrasil wood building pieces (walls, floors, beams, roofs, arches, stairs) with stone and fine wood instead. Stations and furniture keep their cost. A deconstructed piece gives back what was paid for it."));
CheapStonePerBlackMarble = config.Bind(building, "Stone per Black Marble", 3,
new ConfigDescription("Stone a Dvergar pays for each black marble in a piece's cost.", new AcceptableValueRange<int>(1, 10)));
CheapFineWoodPerYggdrasil = config.Bind(building, "Fine Wood per Yggdrasil Wood", 2,
new ConfigDescription("Fine wood a Dvergar pays for each Yggdrasil wood in a piece's cost.", new AcceptableValueRange<int>(1, 10)));
} }
} }
} }

View file

@ -1,5 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib; using HarmonyLib;
using UnityEngine; using UnityEngine;
@ -220,9 +221,13 @@ namespace RacesOfValheim
// ─── Smithing and jewelry ──────────────────────────────────────────── // ─── Smithing and jewelry ────────────────────────────────────────────
/// <summary> /// <summary>
/// Metal saved when crafting and upgrading. Requirement.GetAmount is the single point both /// Metal saved when crafting, upgrading and building. Requirement.GetAmount is what the
/// the crafting panel and Player.ConsumeResources go through, so the figure the player is /// crafting panel, the build menu and Player.ConsumeResources all read, so the figure the
/// quoted and the figure they are charged can never drift apart. /// player is quoted and the figure they are charged can never drift apart.
///
/// Two vanilla paths read m_amount directly and skip GetAmount, both for build pieces:
/// Player.HaveRequirements(Piece) and Piece.DropResources. The two transpilers below route
/// them through the discount too.
/// ///
/// Scoped to the metals and gems in DvergarConfig.DiscountedResourceNames, which is what /// Scoped to the metals and gems in DvergarConfig.DiscountedResourceNames, which is what
/// keeps this a smithing perk rather than a blanket discount on every wooden wall. /// keeps this a smithing perk rather than a blanket discount on every wooden wall.
@ -232,26 +237,137 @@ namespace RacesOfValheim
{ {
public static void Postfix(Piece.Requirement __instance, ref int __result) public static void Postfix(Piece.Requirement __instance, ref int __result)
{ {
if (__result <= 1 || Player.m_localPlayer == null) return; if (Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return;
__result = DiscountedAmount(__instance, __result, DvergarProgression.Current.SmithingDiscount);
}
}
/// <summary>
/// The single rounding rule for the smithing discount. The price a Dvergar pays and the
/// refund their piece drops both go through here, so they can't end up one ingot apart.
/// </summary>
internal static int DiscountedAmount(Piece.Requirement requirement, int amount, float discount)
{
if (amount <= 1 || discount <= 0f) return amount;
if (requirement == null || requirement.m_resItem == null) return amount;
if (!IsDiscounted(requirement.m_resItem.gameObject.name)) return amount;
return Mathf.Max(1, Mathf.RoundToInt(amount * (1f - discount)));
}
private static bool IsDiscounted(string prefabName)
{
string lower = prefabName.ToLower();
foreach (string resource in DvergarConfig.DiscountedResourceNames)
{
if (lower == resource || lower.Contains(resource)) return true;
}
return false;
}
private static readonly FieldInfo RequirementAmountField =
AccessTools.Field(typeof(Piece.Requirement), nameof(Piece.Requirement.m_amount));
/// <summary>
/// The build check. Vanilla compares the inventory against requirement.m_amount here, so
/// the menu quoted 6 tin for a cauldron while the hammer still refused to place it with
/// fewer than 10. Every m_amount read becomes GetAmount(1), which returns m_amount for
/// everyone else and the discounted figure for a Dvergar.
/// </summary>
[HarmonyPatch(typeof(Player), nameof(Player.HaveRequirements), typeof(Piece), typeof(Player.RequirementMode))]
public static class Dvergar_HaveRequirements_Piece_Patch
{
private static readonly MethodInfo GetAmountMethod =
AccessTools.Method(typeof(Piece.Requirement), nameof(Piece.Requirement.GetAmount));
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
int replaced = 0;
foreach (CodeInstruction instruction in instructions)
{
if (instruction.LoadsField(RequirementAmountField))
{
replaced++;
yield return new CodeInstruction(OpCodes.Ldc_I4_1).MoveLabelsFrom(instruction);
yield return new CodeInstruction(OpCodes.Callvirt, GetAmountMethod);
continue;
}
yield return instruction;
}
if (replaced == 0)
Jotunn.Logger.LogWarning("[Dvergar] HaveRequirements(Piece) no longer reads m_amount; build discount check not patched.");
}
}
/// <summary>
/// ZDO key holding the discount a Dvergar paid for a piece. Stored rather than read off
/// the builder at teardown, because anyone can smash the piece and the builder's discount
/// grows with progression.
/// </summary>
private const string PaidDiscountKey = "Dvergar_PaidDiscount";
/// <summary>
/// Stamps the discount on a piece the local Dvergar just placed. Player.PlacePiece calls
/// SetCreator on the new instance right after spawning it, and ConsumeResources charges
/// the discounted price straight after.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))]
public static class Dvergar_Piece_SetCreator_Patch
{
public static void Postfix(Piece __instance, long uid)
{
Player player = Player.m_localPlayer;
if (player == null || uid != player.GetPlayerID()) return;
if (!DvergarRace.IsDvergar()) return; if (!DvergarRace.IsDvergar()) return;
float discount = DvergarProgression.Current.SmithingDiscount; float discount = DvergarProgression.Current.SmithingDiscount;
if (discount <= 0f) return; if (discount <= 0f) return;
if (__instance == null || __instance.m_resItem == null) return; ZNetView nview = __instance.GetComponent<ZNetView>();
if (!IsDiscounted(__instance.m_resItem.gameObject.name)) return; if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
nview.GetZDO().Set(PaidDiscountKey, discount);
}
}
__result = Mathf.Max(1, Mathf.RoundToInt(__result * (1f - discount))); /// <summary>
/// The refund. Vanilla drops requirement.m_amount when a piece is removed or destroyed,
/// which handed a Dvergar back 10 tin for a cauldron that cost 6: build, smash, repeat.
/// The drop now uses the discount stamped on the piece, so it returns what was paid.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))]
public static class Dvergar_Piece_DropResources_Patch
{
private static readonly MethodInfo PaidAmountMethod =
AccessTools.Method(typeof(Dvergar_Piece_DropResources_Patch), nameof(PaidAmount));
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
int replaced = 0;
foreach (CodeInstruction instruction in instructions)
{
if (instruction.LoadsField(RequirementAmountField))
{
replaced++;
yield return new CodeInstruction(OpCodes.Ldarg_0).MoveLabelsFrom(instruction);
yield return new CodeInstruction(OpCodes.Call, PaidAmountMethod);
continue;
}
yield return instruction;
}
if (replaced == 0)
Jotunn.Logger.LogWarning("[Dvergar] DropResources no longer reads m_amount; build discount refund not patched.");
} }
private static bool IsDiscounted(string prefabName) public static int PaidAmount(Piece.Requirement requirement, Piece piece)
{ {
string lower = prefabName.ToLower(); int amount = requirement.m_amount;
foreach (string resource in DvergarConfig.DiscountedResourceNames) ZNetView nview = piece.GetComponent<ZNetView>();
{ if (nview == null || !nview.IsValid()) return amount;
if (lower == resource || lower.Contains(resource)) return true;
} float discount = nview.GetZDO().GetFloat(PaidDiscountKey, 0f);
return false; return DiscountedAmount(requirement, amount, discount);
} }
} }

View file

@ -277,10 +277,11 @@ namespace RacesOfValheim
// metre was the entire drift: the offsets below are under a centimetre in local units // metre was the entire drift: the offsets below are under a centimetre in local units
// and never stood a chance of mattering next to it. // and never stood a chance of mattering next to it.
float raceScale = GetVisualScale(player); float raceScale = GetVisualScale(player);
Vector3 baseLocal = localForward * (DvergarConfig.EyeForward * raceScale * toLocal)
+ localUp * (DvergarConfig.EyeHeight * raceScale * toLocal);
float eyeLocalSize = DvergarConfig.EyeSize * raceScale * toLocal; float height = DvergarConfig.EyeHeight;
float separation = DvergarConfig.EyeSeparation;
float eyeSize = DvergarConfig.EyeSize;
PlayerFace.AdjustEyes(player, ref height, ref separation, ref eyeSize);
for (int i = 0; i < holder.childCount; i++) for (int i = 0; i < holder.childCount; i++)
{ {
@ -291,9 +292,25 @@ namespace RacesOfValheim
// curved and the two sides do not present the same surface to a ball of this // curved and the two sides do not present the same surface to a ball of this
// radius. // radius.
float side = i == 0 ? -1f : 1f; float side = i == 0 ? -1f : 1f;
float size = i == 0 ? eyeLocalSize * DvergarConfig.LeftEyeSizeMultiplier : eyeLocalSize;
eye.localPosition = baseLocal + localRight * (side * DvergarConfig.EyeSeparation * raceScale * toLocal); // This eye's hand corrections (RaceEyeTuning).
float forward = DvergarConfig.EyeForward;
float eyeHeight = height;
float eyeSeparation = separation;
float size = eyeSize * raceScale * toLocal;
RaceEyeTuning.Eye tuning = RaceEyeTuning.For(DvergarConfig.RaceId, player, side);
if (tuning != null)
{
forward += tuning.Forward;
eyeHeight += tuning.Height;
eyeSeparation += tuning.Separation;
size *= tuning.Size;
}
if (i == 0) size *= DvergarConfig.LeftEyeSizeMultiplier;
eye.localPosition = localForward * (forward * raceScale * toLocal)
+ localUp * (eyeHeight * raceScale * toLocal)
+ localRight * (side * eyeSeparation * raceScale * toLocal);
eye.localScale = Vector3.one * size; eye.localScale = Vector3.one * size;
} }
} }

View file

@ -54,9 +54,17 @@ namespace RacesOfValheim
// //
// Skeleton_Hildir stays out deliberately, on the same rule that keeps GoblinKing and the // Skeleton_Hildir stays out deliberately, on the same rule that keeps GoblinKing and the
// Hildir brothers out of the Black Forest set: a quest boss is not somebody's kin. // Hildir brothers out of the Black Forest set: a quest boss is not somebody's kin.
//
// Valheim 1.0 added a skeleton per region (the green swamp ones and the blue mountain ones
// players noticed first), each with a melee-only twin, and spawners place those instead
// of the plain Skeleton. Left out, they fought a Skeleton player the plain ones ignored.
private static readonly HashSet<string> PaludeMobs = new HashSet<string> private static readonly HashSet<string> PaludeMobs = new HashSet<string>
{ {
"Ghost", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", // Skeleton, Rancid remains "Ghost", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", // Skeleton, Rancid remains
"Skeleton_Meadows", "Skeleton_Meadows_noarcher",
"Skeleton_Swamps", "Skeleton_Swamps_noarcher",
"Skeleton_Mountains", "Skeleton_Mountains_noarcher",
"Skeleton_DeepNorth",
"Draugr", "Draugr_Elite", "Draugr_Ranged", "Draugr", "Draugr_Elite", "Draugr_Ranged",
"Wraith", "Leech", "Abomination", "Wraith", "Leech", "Abomination",
"Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth "Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth
@ -126,12 +134,47 @@ namespace RacesOfValheim
return player.m_customData.TryGetValue("Race", out string race) ? race : null; return player.m_customData.TryGetValue("Race", out string race) ? race : null;
} }
// The truce used to cover the player only. A thrall is tamed, so it sits in the Players
// faction, and a wild mob of the player's own faction still saw it as fair game: a wild
// Rancid Remains walked up to a Skeleton's bone pile, ignored the Skeleton and tore into
// the garrison. The thrall's own race is on the prefab (m_commandingRace), so the same
// faction sets answer for it without needing its owner nearby.
//
// The truce breaks the moment that wild mob holds a grudge against any player: it is
// fighting the thralls' master, and the thralls should fight back.
private static bool IsThrallTruce(Character thrallSide, Character wildSide)
{
if (wildSide.IsPlayer() || wildSide.IsTamed()) return false;
RaisedThrall thrall = thrallSide.GetComponent<RaisedThrall>();
if (thrall == null || string.IsNullOrEmpty(thrall.m_commandingRace)) return false;
if (wildSide.GetComponent<RaisedThrall>() != null) return false;
if (!IsAlliedMob(thrall.m_commandingRace, wildSide.gameObject.name)) return false;
foreach (Player player in Player.GetAllPlayers())
{
if (RaceGrudge.Holds(wildSide, player)) return false;
}
return true;
}
public static void Postfix(Character a, Character b, ref bool __result) public static void Postfix(Character a, Character b, ref bool __result)
{ {
if (!FactionsConfig.Hostility) return; if (!FactionsConfig.Hostility) return;
if (!__result) return; // already not enemies, nothing to add if (!__result) return; // already not enemies, nothing to add
if (a == null || b == null) return; if (a == null || b == null) return;
// The player's own blow. Peace is the creature's choice, not a shield. See
// RaceGrudge.StrikeScope.
if (RaceGrudge.PlayerStrikes(a)) return;
if (IsThrallTruce(a, b) || IsThrallTruce(b, a))
{
__result = false;
return;
}
Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null); Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null);
Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null);
if (!(playerCharacter is Player p) || monster == null) return; if (!(playerCharacter is Player p) || monster == null) return;
@ -176,11 +219,28 @@ namespace RacesOfValheim
{ {
if (!FactionsConfig.Hostility) return; if (!FactionsConfig.Hostility) return;
Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic"); Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic");
if (targetStatic.GetValue() == null) return; // GetValue() hands back a plain object, and object == null skips Unity's destroyed
// check: a piece smashed or removed while targeted stays non-null here, and touching
// its gameObject throws. That throw escapes into MonoUpdaters.FixedUpdate and stops
// every AI after this one for the frame, every frame, until the field changes.
Component target = targetStatic.GetValue() as Component;
if (target == null)
{
if (targetStatic.GetValue() != null) targetStatic.SetValue(null);
return;
}
Character monster = Traverse.Create(__instance).Field<Character>("m_character").Value; Character monster = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (monster == null) return; if (monster == null) return;
// A piece an allied race built is never a target, with or without anyone around.
// See FactionPieceTruce.
if (FactionPieceTruce.Protects(target.gameObject, monster))
{
targetStatic.SetValue(null);
return;
}
foreach (Player player in Player.GetAllPlayers()) foreach (Player player in Player.GetAllPlayers())
{ {
if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue; if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue;

View file

@ -337,7 +337,16 @@ namespace RacesOfValheim
{ "Draugr_Elite", DraugrShop }, { "Draugr_Elite", DraugrShop },
{ "Skeleton", SkeletonShop }, { "Skeleton", SkeletonShop },
{ "Skeleton_NoArcher", SkeletonShop },
{ "Skeleton_Poison", SkeletonShop }, { "Skeleton_Poison", SkeletonShop },
// Valheim 1.0's regional skeletons, the ones its spawners actually place.
{ "Skeleton_Meadows", SkeletonShop },
{ "Skeleton_Meadows_noarcher", SkeletonShop },
{ "Skeleton_Swamps", SkeletonShop },
{ "Skeleton_Swamps_noarcher", SkeletonShop },
{ "Skeleton_Mountains", SkeletonShop },
{ "Skeleton_Mountains_noarcher", SkeletonShop },
{ "Skeleton_DeepNorth", SkeletonShop },
{ "Ghost", GhostShop }, { "Ghost", GhostShop },
{ "Wraith", WraithShop }, { "Wraith", WraithShop },

View file

@ -0,0 +1,120 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Allied mobs leave a race's buildings alone whether or not anyone is home.
///
/// FactionStaticTargetPatch only spares a base while an allied player stands within 100 m of
/// the mob. That left the troll cave bug: a Trol builds a cooking station inside a troll cave,
/// walks out, and the cave's resident Troll - m_attackPlayerObjects is true on its prefab - finds
/// nobody to stop it and smashes the station. The player came back to the materials on the floor.
///
/// So every piece remembers the race of whoever built it (BuilderRaceKey on its ZDO), and an
/// allied mob of that race can neither pick it as a target nor damage it. The damage veto is
/// for the blows meant for something else: a Troll swinging at a Dvergar's wall must not take
/// the Trol's workbench next to it down too. The target veto is what keeps the Troll from
/// standing there forever: it never picks an allied piece, so once the foreign one is gone it
/// has nothing to swing at.
///
/// A piece built before this existed carries no race. It gets one the next time its builder
/// loads it, from Piece.Awake, which runs anyway for every piece in a zone as it loads - so
/// there is no timer and no scan. Until then it is protected only the old way.
/// </summary>
public static class FactionPieceTruce
{
public const string BuilderRaceKey = "RacesOfValheim_BuilderRace";
/// <summary>True if this piece was built by a race whose ally <paramref name="monster"/> is,
/// and the monster holds no grudge against the builder.</summary>
public static bool Protects(GameObject pieceObject, Character monster)
{
if (!FactionsConfig.Hostility || pieceObject == null || monster == null) return false;
if (monster.IsPlayer() || monster.IsTamed()) return false;
ZNetView nview = pieceObject.GetComponentInParent<ZNetView>();
if (nview == null || !nview.IsValid()) return false;
string race = nview.GetZDO().GetString(BuilderRaceKey, "");
if (string.IsNullOrEmpty(race)) return false;
if (!FactionHostilityPatch.IsAlliedMob(race, monster.gameObject.name)) return false;
// A mob fighting the builder right now is no ally of the builder's house either.
long creator = nview.GetZDO().GetLong(ZDOVars.s_creator, 0L);
if (creator != 0L)
{
foreach (Player player in Player.GetAllPlayers())
{
if (player.GetPlayerID() == creator && RaceGrudge.Holds(monster, player)) return false;
}
}
return true;
}
private static void Stamp(ZNetView nview)
{
Player local = Player.m_localPlayer;
if (local == null) return;
string race = FactionHostilityPatch.GetPlayerRace(local);
if (string.IsNullOrEmpty(race)) return;
nview.GetZDO().Set(BuilderRaceKey, race);
}
/// <summary>A new piece: stamped by its builder the moment it is placed.</summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))]
public static class Faction_PieceSetCreator_Patch
{
public static void Postfix(Piece __instance, long uid)
{
if (__instance == null || Player.m_localPlayer == null) return;
if (uid != Player.m_localPlayer.GetPlayerID()) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
Stamp(nview);
}
}
/// <summary>
/// An old piece: stamped by its builder the first time it loads for them. Only the ZDO's
/// owner writes, as everywhere else in the mod; a piece some other player owns right now
/// gets its race on a later load.
/// </summary>
[HarmonyPatch(typeof(Piece), "Awake")]
public static class Faction_PieceAwake_Patch
{
public static void Postfix(Piece __instance)
{
Player local = Player.m_localPlayer;
if (__instance == null || local == null) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
ZDO zdo = nview.GetZDO();
if (zdo.GetLong(ZDOVars.s_creator, 0L) != local.GetPlayerID()) return;
if (!string.IsNullOrEmpty(zdo.GetString(BuilderRaceKey, ""))) return;
Stamp(nview);
}
}
/// <summary>
/// Blows from an allied mob land on nothing. Patched on Damage, the attacker's side, where
/// the mob is a live object; RPC_Damage runs on the piece's owner, who may not have it.
/// </summary>
[HarmonyPatch(typeof(WearNTear), nameof(WearNTear.Damage))]
public static class Faction_PieceDamage_Patch
{
public static bool Prefix(WearNTear __instance, HitData hit)
{
if (hit == null) return true;
Character attacker = hit.GetAttacker();
return !Protects(__instance.gameObject, attacker);
}
}
}
}

View file

@ -21,6 +21,8 @@ namespace RacesOfValheim
public static ConfigEntry<bool> HostilityEnabled; public static ConfigEntry<bool> HostilityEnabled;
public static ConfigEntry<bool> MerchantsEnabled; public static ConfigEntry<bool> MerchantsEnabled;
public static ConfigEntry<float> GrudgeDuration; public static ConfigEntry<float> GrudgeDuration;
public static ConfigEntry<bool> GrudgeSpreadEnabled;
public static ConfigEntry<float> GrudgeSpreadRadius;
// Null-safe, defaulting to ON, for the same reason WarVultureConfig guards its own reads: // Null-safe, defaulting to ON, for the same reason WarVultureConfig guards its own reads:
// a patch that somehow runs before Bind() should behave like the shipped default rather // a patch that somehow runs before Bind() should behave like the shipped default rather
@ -28,6 +30,8 @@ namespace RacesOfValheim
public static bool Hostility => HostilityEnabled?.Value ?? true; public static bool Hostility => HostilityEnabled?.Value ?? true;
public static bool Merchants => MerchantsEnabled?.Value ?? true; public static bool Merchants => MerchantsEnabled?.Value ?? true;
public static float GrudgeSeconds => GrudgeDuration?.Value ?? 60f; public static float GrudgeSeconds => GrudgeDuration?.Value ?? 60f;
public static bool GrudgeSpreads => GrudgeSpreadEnabled?.Value ?? false;
public static float GrudgeSpreadMeters => GrudgeSpreadRadius?.Value ?? 20f;
public static void Bind(ConfigFile config) public static void Bind(ConfigFile config)
{ {
@ -55,11 +59,24 @@ namespace RacesOfValheim
"Without this the truce is absolute in both directions: MonsterAI.UpdateTarget " + "Without this the truce is absolute in both directions: MonsterAI.UpdateTarget " +
"throws away any target BaseAI.IsEnemy calls a non-enemy, so a truced mob could " + "throws away any target BaseAI.IsEnemy calls a non-enemy, so a truced mob could " +
"not fight back even after being struck - it stood still, or fled because it " + "not fight back even after being struck - it stood still, or fled because it " +
"was hurt and had no enemy it was allowed to have. The grudge is per attacker " + "was hurt and had no enemy it was allowed to have. Each creature holds one " +
"and per creature, on whichever machine runs that creature's AI. 0 restores the " + "grudge, against the last player who hit it, and keeps it when another player's " +
"game takes over running that creature. 0 restores the " +
"old absolute truce.", "old absolute truce.",
new AcceptableValueRange<float>(0f, 600f))); new AcceptableValueRange<float>(0f, 600f)));
// Joacwoo's request: the truce made the swamp and the crypts a walk for a Skeleton,
// since only the one creature you hit ever fought back.
GrudgeSpreadEnabled = config.Bind(factions, "Grudge spreads to kin", false,
new ConfigDescription("Off: only the creature you hit fights back. On: hit a creature of your " +
"own faction and every creature of that faction near it turns on you too, " +
"for the same Faction grudge time, the way vanilla's Dvergr treat a human. " +
"Peace still holds until you strike first."));
GrudgeSpreadRadius = config.Bind(factions, "Grudge spread radius", 20f,
new ConfigDescription("Meters around the creature you hit within which its kin join the fight, " +
"with Grudge spreads to kin on.",
new AcceptableValueRange<float>(5f, 60f)));
MerchantsEnabled = config.Bind(factions, "Faction merchants", true, MerchantsEnabled = config.Bind(factions, "Faction merchants", true,
new ConfigDescription("Certain mobs of your own faction can be traded with - 'E - Talk' opens a shop " + new ConfigDescription("Certain mobs of your own faction can be traded with - 'E - Talk' opens a shop " +
"where you sell them what their kind wants. Turn this off and they are ordinary " + "where you sell them what their kind wants. Turn this off and they are ordinary " +

View file

@ -323,17 +323,72 @@ namespace RacesOfValheim
GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames"); GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames");
if (fireVfx == null) return null; if (fireVfx == null) return null;
GameObject instance = Object.Instantiate(fireVfx, player.transform.position + Vector3.up * 1.5f + player.transform.forward, player.transform.rotation, player.transform); GameObject instance = Object.Instantiate(fireVfx, MouthPoint(player), player.transform.rotation, player.transform);
instance.AddComponent<CultistFlameFollow>().Player = player;
// The vanilla effect is one throw, not a held breath: its emitters do not loop (2 s) and
// a TimedDestruction removes it after 5 s, so a long hold went on draining eitr with no
// fire. It loops here and lives until StopFire takes it down.
TimedDestruction timer = instance.GetComponent<TimedDestruction>();
if (timer != null)
{
timer.CancelInvoke();
Object.Destroy(timer);
}
// Aumentiamo la durata delle particelle del 20% // Aumentiamo la durata delle particelle del 20%
foreach (ParticleSystem ps in instance.GetComponentsInChildren<ParticleSystem>()) foreach (ParticleSystem ps in instance.GetComponentsInChildren<ParticleSystem>())
{ {
var main = ps.main; var main = ps.main;
main.startLifetimeMultiplier *= 1.2f; main.startLifetimeMultiplier *= 1.2f;
main.loop = true;
}
// The roar of the fire, the same one-throw story: set before its ZSFX first plays.
foreach (ZSFX sfx in instance.GetComponentsInChildren<ZSFX>())
{
sfx.m_fadeOutOnAwake = false;
AudioSource source = sfx.GetComponent<AudioSource>();
if (source != null) source.loop = true;
} }
return instance; return instance;
} }
// Bone names the breath leaves from, mouth first. Matched by name anywhere under the form.
private static readonly string[] MouthBones = { "Jaw", "Head" };
/// <summary>
/// Where the Cultist's breath starts: just ahead of the form's jaw (or head), so it leaves the
/// mouth at whatever size the form stands. It used to be a fixed 1.5 m above the player's
/// feet, chest height on a Cultist, which is the "fire starts too low" report. Falls back on
/// that fixed point if the form has neither bone.
/// </summary>
public static Vector3 MouthPoint(Player player) => MouthPoint(player, FindMouth(player));
public static Vector3 MouthPoint(Player player, Transform bone)
{
Transform body = player.transform;
return bone != null
? bone.position + body.forward * 0.3f
: body.position + Vector3.up * 1.5f + body.forward;
}
public static Transform FindMouth(Player player)
{
foreach (string wanted in MouthBones)
{
foreach (Transform child in player.transform)
{
if (child.name == "Visual" || !child.gameObject.activeInHierarchy) continue;
foreach (Transform t in child.GetComponentsInChildren<Transform>())
{
if (string.Equals(t.name, wanted, System.StringComparison.OrdinalIgnoreCase)) return t;
}
}
}
return null;
}
public static void PublishFire(bool on) public static void PublishFire(bool on)
{ {
Player player = Player.m_localPlayer; Player player = Player.m_localPlayer;
@ -393,6 +448,8 @@ namespace RacesOfValheim
private ZNetView nview; private ZNetView nview;
private string lastAttack; private string lastAttack;
private GameObject flames; private GameObject flames;
private bool breathing;
private float breathStarted;
private readonly FormLocomotion locomotion = new FormLocomotion(); private readonly FormLocomotion locomotion = new FormLocomotion();
// The flames hang off the player, not this model, so they outlive it unless taken down. // The flames hang off the player, not this model, so they outlive it unless taken down.
@ -422,7 +479,7 @@ namespace RacesOfValheim
// The same helper the local behaviours use, so both views of the same wolf agree. // The same helper the local behaviours use, so both views of the same wolf agree.
// Player.IsCrouching answers off the animator's current state, which is replicated, so // Player.IsCrouching answers off the animator's current state, which is replicated, so
// it is true here too. // it is true here too.
locomotion.Mirror(formAnim, playerAnim, player.IsCrouching()); locomotion.Mirror(formAnim, playerAnim, player);
} }
// Written every frame while the flag is set, and only when the controller has the bool: a // Written every frame while the flag is set, and only when the controller has the bool: a
@ -433,18 +490,31 @@ namespace RacesOfValheim
bool fire = nview.GetZDO().GetBool(FenrirAttackSync.FireKey, false); bool fire = nview.GetZDO().GetBool(FenrirAttackSync.FireKey, false);
// The breath itself: up while the flag is, gone when it drops. Only the cultist ever // The flag is up for the whole hold, wind-up included, as on the owner's side; the
// sets the flag, so no other form can grow flames here. // flames come at the same point of the same clip (CultistBreathClip). Only the cultist
if (fire && flames == null) // ever sets the flag, so no other form can grow flames here.
if (fire && !breathing)
{ {
flames = FenrirAttackSync.SpawnFlames(player); breathing = true;
breathStarted = Time.time;
// The roar that opens the breath, once per start, the same cue the owner hears. // The roar that opens the breath, once per start, the same cue the owner hears.
// "sfx_cultist_attack_fire_start" was asked for here and there is no sfx_cultist_* // "sfx_cultist_attack_fire_start" was asked for here and there is no sfx_cultist_*
// prefab in the game at all; the fenring's own fire-claw snarl is the real one. // prefab in the game at all; the fenring's own fire-claw snarl is the real one.
FenrirCreatureSound.PlayFireRoar(player.transform.position); FenrirCreatureSound.PlayFireRoar(player.transform.position);
} }
else if (!fire && flames != null) { Destroy(flames); flames = null; } if (fire)
{
CultistBreathClip.Hold(formAnim);
if (flames == null && CultistBreathClip.FlamesDue(formAnim, breathStarted))
flames = FenrirAttackSync.SpawnFlames(player);
}
else if (breathing)
{
breathing = false;
CultistBreathClip.Release(formAnim, player);
if (flames != null) { Destroy(flames); flames = null; }
}
foreach (AnimatorControllerParameter p in formAnim.parameters) foreach (AnimatorControllerParameter p in formAnim.parameters)
{ {
@ -513,7 +583,11 @@ namespace RacesOfValheim
private Animator fenrirAnim; private Animator fenrirAnim;
private readonly FormLocomotion locomotion = new FormLocomotion(); private readonly FormLocomotion locomotion = new FormLocomotion();
private bool isAttacking = false; private float busySince = -1f;
// A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch
// holds the player still for exactly as long as an attack clip runs.
private bool attacking;
private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } }
void Start() void Start()
{ {
@ -525,6 +599,12 @@ namespace RacesOfValheim
void Update() void Update()
{ {
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (playerAnim == null || fenrirAnim == null) return; if (playerAnim == null || fenrirAnim == null) return;
// Se stiamo attaccando, l'Update smette di inviare costantemente // Se stiamo attaccando, l'Update smette di inviare costantemente
@ -532,7 +612,7 @@ namespace RacesOfValheim
// Meglio continuare a sincronizzare i movimenti base. // Meglio continuare a sincronizzare i movimenti base.
if (!isAttacking) if (!isAttacking)
{ {
bool isGrounded = locomotion.Mirror(fenrirAnim, playerAnim, Player.m_localPlayer.IsCrouching()); bool isGrounded = locomotion.Mirror(fenrirAnim, playerAnim, Player.m_localPlayer);
if (isGrounded && RaceInput.Allowed) if (isGrounded && RaceInput.Allowed)
{ {
@ -540,15 +620,15 @@ namespace RacesOfValheim
{ {
StartCoroutine(HowlRoutine()); StartCoroutine(HowlRoutine());
} }
else if (RaceInput.AttackDown(1)) // Tasto destro (Heavy Claw) else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringHeavyClawStamina.Value, Skills.SkillType.Unarmed)) // Tasto destro (Heavy Claw)
{ {
StartCoroutine(ClawRoutine("attack_claw1", FenrirConfig.FenringHeavyClawDamage.Value, 1.2f, 0.5f)); StartCoroutine(ClawRoutine("attack_claw1", FenrirConfig.FenringHeavyClawDamage.Value, 1.2f, 0.5f));
} }
else if (RaceInput.AttackDown(0)) // Tasto sinistro else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringLightClawStamina.Value, Skills.SkillType.Unarmed)) // Tasto sinistro
{ {
StartCoroutine(ClawRoutine("attack_claw0", FenrirConfig.FenringLightClawDamage.Value, 1.0f, 0.4f)); StartCoroutine(ClawRoutine("attack_claw0", FenrirConfig.FenringLightClawDamage.Value, 1.0f, 0.4f));
} }
else if (RaceInput.AttackDown(2)) // Tasto centrale else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringJumpAttackStamina.Value, Skills.SkillType.Unarmed)) // Tasto centrale
{ {
StartCoroutine(JumpAttackRoutine()); StartCoroutine(JumpAttackRoutine());
} }
@ -590,6 +670,7 @@ namespace RacesOfValheim
private IEnumerator ClawRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) private IEnumerator ClawRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{ {
isAttacking = true; isAttacking = true;
FormAnimGuard.LeaveHowl(fenrirAnim);
fenrirAnim.SetFloat("forward_speed", 0f); fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f); fenrirAnim.SetFloat("sideway_speed", 0f);
@ -624,6 +705,7 @@ namespace RacesOfValheim
private IEnumerator JumpAttackRoutine() private IEnumerator JumpAttackRoutine()
{ {
isAttacking = true; isAttacking = true;
FormAnimGuard.LeaveHowl(fenrirAnim);
fenrirAnim.SetFloat("forward_speed", 0f); fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f); fenrirAnim.SetFloat("sideway_speed", 0f);
@ -678,7 +760,7 @@ namespace RacesOfValheim
private void ExecuteClawDamage(float baseDamage) private void ExecuteClawDamage(float baseDamage)
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position; Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f; Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
@ -692,6 +774,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -740,10 +823,14 @@ namespace RacesOfValheim
if (targetObj != null) hitObjects.Add(targetObj); if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
@ -756,7 +843,11 @@ namespace RacesOfValheim
private Animator cultistAnim; private Animator cultistAnim;
private readonly FormLocomotion locomotion = new FormLocomotion(); private readonly FormLocomotion locomotion = new FormLocomotion();
private bool isAttacking = false; private float busySince = -1f;
// A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch
// holds the player still for exactly as long as an attack clip runs.
private bool attacking;
private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } }
private bool isShootingFire = false; private bool isShootingFire = false;
private float fireTimer = 0f; private float fireTimer = 0f;
@ -769,12 +860,18 @@ namespace RacesOfValheim
} }
void Update() void Update()
{ {
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (playerAnim == null || cultistAnim == null) return; if (playerAnim == null || cultistAnim == null) return;
if (!isAttacking) if (!isAttacking)
{ {
// Se tiene premuto Ctrl (Crouch), ferma il movimento per preparare l'attacco // Se tiene premuto Ctrl (Crouch), ferma il movimento per preparare l'attacco
bool isGrounded = locomotion.Mirror(cultistAnim, playerAnim, Player.m_localPlayer.IsCrouching()); bool isGrounded = locomotion.Mirror(cultistAnim, playerAnim, Player.m_localPlayer);
if (isGrounded) if (isGrounded)
{ {
@ -782,47 +879,40 @@ namespace RacesOfValheim
// still falls through to StopFire() instead of leaving the flames running. // still falls through to StopFire() instead of leaving the flames running.
bool canAct = RaceInput.Allowed; bool canAct = RaceInput.Allowed;
// Fire attack on Right Click // Fire attack on Right Click, held.
if (canAct && RaceInput.AttackHeld(1)) bool wantFire = canAct && RaceInput.AttackHeld(1) && !Player.m_localPlayer.IsStaggering();
if (wantFire && Player.m_localPlayer.GetEitr() <= 0f)
{ {
if (Player.m_localPlayer.GetEitr() > 0) // Held with an empty pool. Until now this did nothing whatsoever: no
{ // flames, no sound, no reason given - and the form's own tier is Yagluth
if (!isShootingFire) // while eitr is a Mistlands thing, so a Cultist meets this before it ever
{ // meets the fire.
StartFire(); SayNoEitr();
} wantFire = false;
else }
{
UpdateFire(); if (wantFire)
} {
} if (!isShootingFire) StartFire();
else else UpdateFire();
{
// Held with an empty pool. Until now this did nothing whatsoever: no
// flames, no sound, no reason given - and the form's own tier is Yagluth
// while eitr is a Mistlands thing, so a Cultist meets this before it ever
// meets the fire.
SayNoEitr();
if (isShootingFire) StopFire();
}
} }
else if (isShootingFire) else if (isShootingFire)
{ {
StopFire(); StopFire();
} }
if (canAct && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys()) if (canAct && !isShootingFire && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{ {
StartCoroutine(HowlRoutine()); StartCoroutine(HowlRoutine());
} }
// Attacks on Left Click // Attacks on Left Click
if (canAct && RaceInput.AttackDown(0) && !isShootingFire) if (canAct && RaceInput.AttackDown(0) && !isShootingFire && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.CultistClawStamina.Value, Skills.SkillType.Unarmed))
{ {
StartCoroutine(ClawRoutine()); // Single claw StartCoroutine(ClawRoutine()); // Single claw
} }
// Double claw on Middle Click // Double claw on Middle Click
else if (canAct && RaceInput.AttackDown(2) && !isShootingFire) else if (canAct && RaceInput.AttackDown(2) && !isShootingFire && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.CultistDoubleClawStamina.Value, Skills.SkillType.Unarmed))
{ {
StartCoroutine(DoubleClawRoutine()); StartCoroutine(DoubleClawRoutine());
} }
@ -884,30 +974,54 @@ namespace RacesOfValheim
ModText.Get("rov_msg_fenrir_only_breath_comes_out_fire")); ModText.Get("rov_msg_fenrir_only_breath_comes_out_fire"));
} }
// The breath runs on the flame clip (CultistBreathClip): pressed, the clip starts; the flames,
// the eitr drain and the damage begin at its own Hit point; released, the clip is cut.
private bool flaming;
private float fireStarted;
/// <summary>True while the local Cultist holds its breath attack, wind-up included. Read by
/// Cultist_BreathFacesCamera_Patch.</summary>
public static bool LocalBreathing { get; private set; }
private void StartFire() private void StartFire()
{ {
if (Player.m_localPlayer == null || isShootingFire) return; if (Player.m_localPlayer == null || isShootingFire) return;
isShootingFire = true; isShootingFire = true;
LocalBreathing = true;
// Planted while it breathes, as the vanilla Cultist is: its controller has no walking
// version of the cast, so a moving Cultist slid along in the casting pose.
// Fenrir_FormHoldStill_Patch holds the player; turning to the camera still works.
FenrirForms.LocalAttacking = true;
flaming = false;
fireStarted = Time.time;
fireTimer = 0f;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f);
cultistAnim.SetBool("attack_fire", true);
FenrirAttackSync.PublishFire(true); FenrirAttackSync.PublishFire(true);
// Same cue the remote mirror plays - see the fire branch in the sync behaviour above. // Same cue the remote mirror plays - see the fire branch in the sync behaviour above.
FenrirCreatureSound.PlayFireRoar(Player.m_localPlayer.transform.position); FenrirCreatureSound.PlayFireRoar(Player.m_localPlayer.transform.position);
cultistAnim.SetTrigger("attack_flames"); cultistAnim.SetTrigger("attack_flames");
FenrirAttackSync.Publish("attack_flames"); FenrirAttackSync.Publish("attack_flames");
if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer);
} }
private void UpdateFire() private void UpdateFire()
{ {
Player.m_localPlayer.UseEitr(FenrirConfig.CultistFireEitrDrainPerSecond.Value * Time.deltaTime);
cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f);
CultistBreathClip.Hold(cultistAnim);
if (!flaming)
{
if (!CultistBreathClip.FlamesDue(cultistAnim, fireStarted)) return;
flaming = true;
if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer);
}
Player.m_localPlayer.UseEitr(FenrirConfig.CultistFireEitrDrainPerSecond.Value * Time.deltaTime);
fireTimer += Time.deltaTime; fireTimer += Time.deltaTime;
if (fireTimer >= 0.2f) // Damage tick every 0.2s if (fireTimer >= 0.2f) // Damage tick every 0.2s
{ {
@ -920,14 +1034,20 @@ namespace RacesOfValheim
private void OnDestroy() private void OnDestroy()
{ {
if (isShootingFire) FenrirAttackSync.PublishFire(false); if (isShootingFire) FenrirAttackSync.PublishFire(false);
if (isShootingFire) FenrirForms.LocalAttacking = false;
LocalBreathing = false;
} }
private void StopFire() private void StopFire()
{ {
isShootingFire = false; isShootingFire = false;
LocalBreathing = false;
FenrirForms.LocalAttacking = false;
flaming = false;
cultistAnim.ResetTrigger("attack_flames"); cultistAnim.ResetTrigger("attack_flames");
FenrirAttackSync.PublishFire(false); FenrirAttackSync.PublishFire(false);
CultistBreathClip.Release(cultistAnim, Player.m_localPlayer);
if (fireEffectInstance != null) if (fireEffectInstance != null)
{ {
Destroy(fireEffectInstance); Destroy(fireEffectInstance);
@ -951,6 +1071,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -989,6 +1110,8 @@ namespace RacesOfValheim
if (targetObj != null) hitObjects.Add(targetObj); if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath
if (target is Character) hitCreature = true;
if (ZNetScene.instance != null) if (ZNetScene.instance != null)
{ {
@ -998,63 +1121,111 @@ namespace RacesOfValheim
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, 0.2f); // one 0.2s tick: a full swing's worth per second of breath
} }
private IEnumerator ClawRoutine() private IEnumerator ClawRoutine()
{ {
isAttacking = true; isAttacking = true;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f);
// Per il Cultista usiamo esplicitamente il trigger dell'artigliata // Per il Cultista usiamo esplicitamente il trigger dell'artigliata
int baseline = FenrirForms.AttackEvents;
float started = Time.time;
cultistAnim.SetTrigger("attack_claw"); cultistAnim.SetTrigger("attack_claw");
FenrirAttackSync.Publish("attack_claw", "sfx_fenring_claw_start"); FenrirAttackSync.Publish("attack_claw", "sfx_fenring_claw_start");
yield return new WaitForSeconds(0.4f); // The blow lands on the clip's own Hit event (ClawAttackCultist: 0.64 s of 1.33 s), and
// the lock holds until the clip is over. A fixed 0.4 s hit and a 0.5 s lock used to land
// the damage before the claw swung and let the next click start a new one mid-swing.
yield return null;
float length = ClipLength(1.33f);
yield return WaitForHit(baseline, started);
PlaySFX("sfx_fenring_claw_start"); PlaySFX("sfx_fenring_claw_start");
ExecuteClawDamage(FenrirConfig.CultistClawDamage.Value); ExecuteClawDamage(FenrirConfig.CultistClawDamage.Value);
float remainingTimeToIdle = 0.5f - 0.4f; yield return WaitUntilClipEnds(length, started);
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
cultistAnim.ResetTrigger("attack_claw"); cultistAnim.ResetTrigger("attack_claw");
isAttacking = false; isAttacking = false;
} }
// Each swipe of the double claw deals this share of Double Claw Damage. Two swipes give
// 120% of what the old single hit dealt: a little more, for a slower swing that can be cut short.
private const float DoubleClawHitShare = 0.6f;
private IEnumerator DoubleClawRoutine() private IEnumerator DoubleClawRoutine()
{ {
isAttacking = true; isAttacking = true;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f);
int baseline = FenrirForms.AttackEvents;
float started = Time.time;
cultistAnim.SetTrigger("attack_claw_double"); cultistAnim.SetTrigger("attack_claw_double");
FenrirAttackSync.Publish("attack_claw_double", "sfx_fenring_claw_start"); FenrirAttackSync.Publish("attack_claw_double", "sfx_fenring_claw_start");
// L'animazione double claw è più lunga, facciamo il danno un po' dopo // DoubleClawAttackCultist carries two Hit events (0.64 s and 1.21 s of 1.83 s), one per
yield return new WaitForSeconds(0.6f); // swipe. It used to deal one hit at a fixed 0.6 s, so the second swipe did nothing.
yield return null;
float length = ClipLength(1.83f);
float damage = FenrirConfig.CultistDoubleClawDamage.Value * DoubleClawHitShare;
yield return WaitForHit(baseline, started);
PlaySFX("sfx_fenring_claw_start"); PlaySFX("sfx_fenring_claw_start");
ExecuteClawDamage(damage);
ExecuteClawDamage(FenrirConfig.CultistDoubleClawDamage.Value); yield return WaitForHit(baseline + 1, started, HitEventTimeout + 0.6f);
PlaySFX("sfx_fenring_claw_start");
// Attendiamo che l'animazione finisca (locking del giocatore) ExecuteClawDamage(damage);
// L'animazione doppia del cultista dura circa 1.5 - 2 secondi
yield return new WaitForSeconds(1.2f);
yield return WaitUntilClipEnds(length, started);
cultistAnim.ResetTrigger("attack_claw_double"); cultistAnim.ResetTrigger("attack_claw_double");
isAttacking = false; isAttacking = false;
} }
// Longest a swipe waits for its Hit event before landing anyway, measured from the trigger:
// a clip that never sends one must not leave the Cultist swinging at nothing.
private const float HitEventTimeout = 1.5f;
/// <summary>Waits until the clip has sent more than <paramref name="seen"/> hit events since
/// the trigger, or until the timeout.</summary>
private IEnumerator WaitForHit(int seen, float started, float timeout = HitEventTimeout)
{
while (FenrirForms.AttackEvents <= seen && Time.time - started < timeout)
{
yield return null;
}
}
/// <summary>The attack clip's length, read a frame after its trigger, when the transition
/// into it has begun. <paramref name="fallback"/> is the clip's length in the game files.</summary>
private float ClipLength(float fallback)
{
AnimatorClipInfo[] clips = cultistAnim.IsInTransition(0)
? cultistAnim.GetNextAnimatorClipInfo(0)
: cultistAnim.GetCurrentAnimatorClipInfo(0);
if (clips != null && clips.Length > 0 && clips[0].clip != null) return clips[0].clip.length;
return fallback;
}
/// <summary>Holds the lock until the clip has played out, clamped so a wrong reading can
/// neither cut a swing short nor freeze the form.</summary>
private IEnumerator WaitUntilClipEnds(float length, float started)
{
float remaining = Mathf.Clamp(length, 0.6f, 3f) - (Time.time - started);
if (remaining > 0f) yield return new WaitForSeconds(remaining);
}
private void ExecuteClawDamage(float baseDamage) private void ExecuteClawDamage(float baseDamage)
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position; Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f; Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
@ -1068,6 +1239,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1116,10 +1288,14 @@ namespace RacesOfValheim
if (targetObj != null) hitObjects.Add(targetObj); if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
@ -1130,7 +1306,11 @@ namespace RacesOfValheim
private Animator playerAnim; private Animator playerAnim;
private Animator wolfAnim; private Animator wolfAnim;
private readonly FormLocomotion locomotion = new FormLocomotion(); private readonly FormLocomotion locomotion = new FormLocomotion();
private bool isAttacking = false; private float busySince = -1f;
// A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch
// holds the player still for exactly as long as an attack clip runs.
private bool attacking;
private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } }
void Start() void Start()
{ {
@ -1142,11 +1322,17 @@ namespace RacesOfValheim
void Update() void Update()
{ {
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (playerAnim == null || wolfAnim == null) return; if (playerAnim == null || wolfAnim == null) return;
if (!isAttacking) if (!isAttacking)
{ {
bool isGrounded = locomotion.Mirror(wolfAnim, playerAnim, Player.m_localPlayer.IsCrouching()); bool isGrounded = locomotion.Mirror(wolfAnim, playerAnim, Player.m_localPlayer);
if (isGrounded && RaceInput.Allowed) if (isGrounded && RaceInput.Allowed)
{ {
@ -1156,15 +1342,15 @@ namespace RacesOfValheim
{ {
StartCoroutine(WolfHowlRoutine()); StartCoroutine(WolfHowlRoutine());
} }
else if (RaceInput.AttackDown(0)) // Left Click else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack1Stamina.Value, Skills.SkillType.Unarmed)) // Left Click
{ {
StartCoroutine(WolfAttackRoutine("attack1", FenrirConfig.WolfAttack1Damage.Value, 0.6f, 0.2f)); StartCoroutine(WolfAttackRoutine("attack1", FenrirConfig.WolfAttack1Damage.Value, 0.6f, 0.2f));
} }
else if (RaceInput.AttackDown(1)) // Right Click else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack2Stamina.Value, Skills.SkillType.Unarmed)) // Right Click
{ {
StartCoroutine(WolfAttackRoutine("attack2", FenrirConfig.WolfAttack2Damage.Value, 0.8f, 0.3f)); StartCoroutine(WolfAttackRoutine("attack2", FenrirConfig.WolfAttack2Damage.Value, 0.8f, 0.3f));
} }
else if (RaceInput.AttackDown(2)) // Middle Click else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack3Stamina.Value, Skills.SkillType.Unarmed)) // Middle Click
{ {
StartCoroutine(WolfAttackRoutine("attack3", FenrirConfig.WolfAttack3Damage.Value, 1.0f, 0.4f)); StartCoroutine(WolfAttackRoutine("attack3", FenrirConfig.WolfAttack3Damage.Value, 1.0f, 0.4f));
} }
@ -1195,54 +1381,69 @@ namespace RacesOfValheim
{ {
isAttacking = true; isAttacking = true;
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} try
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} {
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
FenrirCreatureSound.Howl(wolfAnim, "Wolf", Player.m_localPlayer.transform.position); FenrirCreatureSound.Howl(wolfAnim, "Wolf", Player.m_localPlayer.transform.position);
// The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back // The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back
// into a bite the instant the sound ends. // into a bite the instant the sound ends.
yield return new WaitForSeconds(3.3f); yield return new WaitForSeconds(3.3f);
}
isAttacking = false; finally
{
isAttacking = false;
}
} }
private IEnumerator WolfAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) private IEnumerator WolfAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{ {
isAttacking = true; isAttacking = true;
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} // finally and not a plain assignment at the end: an exception anywhere below used to
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} // leave isAttacking true for good, and Update does nothing at all while it is.
try
wolfAnim.SetTrigger(triggerName);
FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack");
yield return new WaitForSeconds(dmgDelay);
if (ZNetScene.instance != null)
{ {
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack"); // Out of the howl first - see FormAnimGuard.
if (attackSfx != null) FormAnimGuard.LeaveHowl(wolfAnim);
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
wolfAnim.SetTrigger(triggerName);
FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack");
yield return new WaitForSeconds(dmgDelay);
if (ZNetScene.instance != null)
{ {
FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position); GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack");
if (attackSfx != null)
{
FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position);
}
}
ExecuteBiteDamage(baseDamage);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
} }
} }
finally
ExecuteBiteDamage(baseDamage);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
{ {
yield return new WaitForSeconds(remainingTimeToIdle); try { wolfAnim.ResetTrigger(triggerName); } catch {}
isAttacking = false;
} }
wolfAnim.ResetTrigger(triggerName);
isAttacking = false;
} }
private void ExecuteBiteDamage(float baseDamage) private void ExecuteBiteDamage(float baseDamage)
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position; Vector3 playerPos = Player.m_localPlayer.transform.position;
// Il lupo è basso, abbassiamo l'altezza dell'attacco // Il lupo è basso, abbassiamo l'altezza dell'attacco
@ -1257,6 +1458,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1305,10 +1507,14 @@ namespace RacesOfValheim
if (targetObj != null) hitObjects.Add(targetObj); if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
@ -1321,7 +1527,11 @@ namespace RacesOfValheim
private Animator ulvAnim; private Animator ulvAnim;
private readonly FormLocomotion locomotion = new FormLocomotion(); private readonly FormLocomotion locomotion = new FormLocomotion();
private bool isAttacking = false; private float busySince = -1f;
// A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch
// holds the player still for exactly as long as an attack clip runs.
private bool attacking;
private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } }
void Start() void Start()
{ {
@ -1332,11 +1542,17 @@ namespace RacesOfValheim
void Update() void Update()
{ {
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (Player.m_localPlayer == null || playerAnim == null || ulvAnim == null) return; if (Player.m_localPlayer == null || playerAnim == null || ulvAnim == null) return;
if (!isAttacking) if (!isAttacking)
{ {
bool isGrounded = locomotion.Mirror(ulvAnim, playerAnim, Player.m_localPlayer.IsCrouching()); bool isGrounded = locomotion.Mirror(ulvAnim, playerAnim, Player.m_localPlayer);
if (isGrounded && RaceInput.Allowed) if (isGrounded && RaceInput.Allowed)
{ {
@ -1346,16 +1562,16 @@ namespace RacesOfValheim
{ {
StartCoroutine(UlvHowlRoutine()); StartCoroutine(UlvHowlRoutine());
} }
else if (RaceInput.AttackDown(0)) // Left Click else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvBiteStamina.Value, Skills.SkillType.Unarmed)) // Left Click
{ {
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvBiteDamage.Value, 0.6f, 0.2f)); StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvBiteDamage.Value, 0.6f, 0.2f));
} }
else if (RaceInput.AttackDown(1)) // Right Click else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvHeavyBiteStamina.Value, Skills.SkillType.Unarmed)) // Right Click
{ {
// Right click uses bite but as a heavier attack since slash is moved to jump // Right click uses bite but as a heavier attack since slash is moved to jump
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvHeavyBiteDamage.Value, 0.8f, 0.3f)); StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvHeavyBiteDamage.Value, 0.8f, 0.3f));
} }
else if (RaceInput.AttackDown(2)) // Middle Click else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvJumpAttackStamina.Value, Skills.SkillType.Unarmed)) // Middle Click
{ {
StartCoroutine(UlvJumpAttackRoutine()); StartCoroutine(UlvJumpAttackRoutine());
} }
@ -1402,6 +1618,7 @@ namespace RacesOfValheim
private IEnumerator UlvAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) private IEnumerator UlvAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{ {
isAttacking = true; isAttacking = true;
FormAnimGuard.LeaveHowl(ulvAnim);
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
@ -1439,7 +1656,7 @@ namespace RacesOfValheim
private void ExecuteBiteDamage(float baseDamage) private void ExecuteBiteDamage(float baseDamage)
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position; Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f; Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f;
@ -1453,6 +1670,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1501,15 +1719,20 @@ namespace RacesOfValheim
if (targetObj != null) hitObjects.Add(targetObj); if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
private IEnumerator UlvJumpAttackRoutine() private IEnumerator UlvJumpAttackRoutine()
{ {
isAttacking = true; isAttacking = true;
FormAnimGuard.LeaveHowl(ulvAnim);
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
@ -1554,4 +1777,160 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// The Cultist's breath, timed by its own clip. fenring_cultist_animator's attack_flames state
/// plays "Flame Spell Attack" (read offline with UnityPy, bundle c4210710): 3.5 s, the hands
/// light at 1.094 s (TrailOn), the vanilla flames come at 1.245 s (Hit) and are taken down at
/// 3.193 s. The state leaves for Movement only when the clip ends, so a short click used to
/// leave the Cultist standing with its arms up for the rest of the 3.5 s, breathing nothing.
///
/// Now the flames wait for the clip's Hit point, the arms are held in the casting pose for as
/// long as the button is, and letting go blends straight back to Movement. Shared by the
/// owner's Cultist and every onlooker's copy, so both play the same breath.
/// </summary>
internal static class CultistBreathClip
{
private static readonly int State = Animator.StringToHash("Base Layer.attack_flames");
private const string MovementState = "Base Layer.Movement";
// The clip's Hit event, where the vanilla Cultist's flames come out.
private const float FlamesAt = 1.245f;
// The throw itself: the Animator stops here while held. After it the vanilla Cultist lowers
// its arms while its fire flies on alone, so a pin at 2.6 s held an idle-looking pose.
private const float PinAt = 1.3f;
private const float Fade = 0.25f;
/// <summary>Seconds into the flame clip, or -1 while the Animator is in another state.</summary>
private static float ClipTime(Animator anim)
{
AnimatorStateInfo info = anim.IsInTransition(0) ? anim.GetNextAnimatorStateInfo(0) : anim.GetCurrentAnimatorStateInfo(0);
return info.fullPathHash == State ? info.normalizedTime * info.length : -1f;
}
/// <summary>True once the clip has reached its Hit point. If the clip never started (another
/// state took the Animator), the same delay counted from the press stands in for it.</summary>
public static bool FlamesDue(Animator anim, float started)
{
float t = ClipTime(anim);
return t >= FlamesAt || (t < 0f && Time.time - started >= FlamesAt + 0.2f);
}
/// <summary>
/// Holds the arms in the casting pose: once the clip reaches PinAt it is put back there every
/// frame. Not with Animator.speed = 0, which is what the troll's pin uses: the creature's own
/// CharacterAnimEvent sits on this model and sets speed back to 1 on every physics step while
/// the player is not in a vanilla attack, so the clip ran on to its end and the Cultist went
/// back to idle with the fire still pouring out.
/// </summary>
public static void Hold(Animator anim)
{
if (anim.IsInTransition(0)) return;
AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
if (info.fullPathHash != State || info.length <= 0f) return;
if (info.normalizedTime * info.length >= PinAt) anim.Play(State, 0, PinAt / info.length);
}
/// <summary>Blends out of the clip, unless a stagger has taken over (FormStagger has fired
/// the form's own).</summary>
public static void Release(Animator anim, Player player)
{
if (anim == null) return;
if (ClipTime(anim) >= 0f && (player == null || !player.IsStaggering()))
anim.CrossFadeInFixedTime(MovementState, Fade, 0);
}
}
/// <summary>
/// Keeps the Cultist's breath in its hands, where the vanilla Cultist casts it from. fx_fenring_flames
/// has two emitters, "flames_world left" and "flames_world right", set 1.2 to 1.6 m ahead of
/// its own origin; spawned at the creature, the fire began that far in front of it. Each
/// emitter goes on its hand bone (fenring_cultist rig: .../LeftForeArm/LeftHand and the right
/// one), pointing where the player faces, so the two streams leave the palms and run forward.
/// The embers and the light sit between the hands. Placed every LateUpdate, after the form's
/// Animator has moved the arms. The same on every client's copy.
///
/// A form without hand bones keeps the whole effect at its mouth, as before.
/// </summary>
internal class CultistFlameFollow : MonoBehaviour
{
// Ahead of the palm, so the stream does not start inside the hand.
private const float AheadOfHand = 0.15f;
// The light, further ahead along the stream.
private const float LightAhead = 1.5f;
public Player Player;
private Transform mouth, leftHand, rightHand;
private Transform leftFlames, rightFlames, embers, light;
private bool partsFound;
private float nextLook;
private void LateUpdate()
{
if (Player == null) return;
if (!partsFound)
{
partsFound = true;
leftFlames = transform.Find("flames_world left");
rightFlames = transform.Find("flames_world right");
embers = transform.Find("FireEmbers");
light = transform.Find("Point light");
}
// The form can be rebuilt under the same flames; look again now and then if lost.
if ((leftHand == null || rightHand == null || mouth == null) && Time.time >= nextLook)
{
nextLook = Time.time + 0.5f;
leftHand = FindBone(Player, "LeftHand");
rightHand = FindBone(Player, "RightHand");
mouth = FenrirAttackSync.FindMouth(Player);
}
Quaternion facing = Player.transform.rotation;
transform.SetPositionAndRotation(FenrirAttackSync.MouthPoint(Player, mouth), facing);
if (leftHand == null || rightHand == null || leftFlames == null || rightFlames == null) return;
Vector3 forward = Player.transform.forward;
Vector3 left = leftHand.position + forward * AheadOfHand;
Vector3 right = rightHand.position + forward * AheadOfHand;
leftFlames.SetPositionAndRotation(left, facing);
rightFlames.SetPositionAndRotation(right, facing);
Vector3 between = (left + right) * 0.5f;
if (embers != null) embers.SetPositionAndRotation(between, facing);
if (light != null) light.position = between + forward * LightAhead;
}
private static Transform FindBone(Player player, string name)
{
foreach (Transform child in player.transform)
{
if (child.name == "Visual" || !child.gameObject.activeInHierarchy) continue;
foreach (Transform t in child.GetComponentsInChildren<Transform>())
{
if (t.name == name) return t;
}
}
return null;
}
}
/// <summary>
/// Turns the Cultist toward the camera while it breathes fire, as vanilla turns a player who
/// blocks or draws a bow: Player.AlwaysRotateCamera answers true for those, and Character then
/// turns the body to the look direction at its own turn speed. The breath is not a vanilla
/// attack, so the body stayed facing wherever the movement keys had left it.
/// </summary>
[HarmonyPatch(typeof(Player), "AlwaysRotateCamera")]
public static class Cultist_BreathFacesCamera_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result && __instance == Player.m_localPlayer && CultistFormBehavior.LocalBreathing) __result = true;
}
}
} }

View file

@ -38,15 +38,33 @@ namespace RacesOfValheim
public static ConfigEntry<float> SpeedBonusPerState; public static ConfigEntry<float> SpeedBonusPerState;
public static ConfigEntry<float> JumpBonusPerState; public static ConfigEntry<float> JumpBonusPerState;
public static ConfigEntry<float> SunSicknessDuration; public static ConfigEntry<float> SunSicknessDuration;
public static ConfigEntry<float> SensesRadius;
// ─── Form buffs (applied while transformed) ─────────────────────────── // ─── Form buffs (applied while transformed) ───────────────────────────
public static ConfigEntry<float> FullFormSpeedBonus; public static ConfigEntry<float> FullFormSpeedBonus;
public static ConfigEntry<float> FullFormJumpBonus; public static ConfigEntry<float> FullFormJumpBonus;
public static ConfigEntry<float> FullFormFallDamageReduction; public static ConfigEntry<float> FullFormFallDamageReduction;
public static ConfigEntry<float> WolfFormSpeedBonus; public static ConfigEntry<float> WolfFormSpeedBonus;
public static ConfigEntry<float> UlvFormSpeedBonus;
public static ConfigEntry<float> FenringDamageReduction;
public static ConfigEntry<float> CultistExtraDamageTaken;
public static ConfigEntry<float> WolfFormFallDamageReduction; public static ConfigEntry<float> WolfFormFallDamageReduction;
public static ConfigEntry<float> FormStaminaRegenMultiplier; public static ConfigEntry<float> FormStaminaRegenMultiplier;
public static ConfigEntry<float> FormStaminaDrainReduction; public static ConfigEntry<float> FormStaminaDrainReduction;
public static ConfigEntry<float> FormAdrenalineMultiplier;
// ─── Form attack stamina (base cost, before the Unarmed skill discount) ─
public static ConfigEntry<float> FenringLightClawStamina;
public static ConfigEntry<float> FenringHeavyClawStamina;
public static ConfigEntry<float> FenringJumpAttackStamina;
public static ConfigEntry<float> CultistClawStamina;
public static ConfigEntry<float> CultistDoubleClawStamina;
public static ConfigEntry<float> WolfAttack1Stamina;
public static ConfigEntry<float> WolfAttack2Stamina;
public static ConfigEntry<float> WolfAttack3Stamina;
public static ConfigEntry<float> UlvBiteStamina;
public static ConfigEntry<float> UlvHeavyBiteStamina;
public static ConfigEntry<float> UlvJumpAttackStamina;
// ─── Fenring form attacks ───────────────────────────────────────────── // ─── Fenring form attacks ─────────────────────────────────────────────
public static ConfigEntry<float> FenringHeavyClawDamage; public static ConfigEntry<float> FenringHeavyClawDamage;
@ -82,8 +100,11 @@ namespace RacesOfValheim
public static ConfigEntry<float> UlvAttackRadius; public static ConfigEntry<float> UlvAttackRadius;
public static ConfigEntry<float> UlvPushForce; public static ConfigEntry<float> UlvPushForce;
// ─── Debug ───────────────────────────────────────────────────────────── // ─── Appearance (per player, never synced) ──────────────────────────────
public static ConfigEntry<bool> DebugFormHits; public static ConfigEntry<bool> ReadyMessage;
public static ConfigEntry<bool> EyeGlow;
public static ConfigEntry<float> EyeNightStrength;
public static ConfigEntry<float> EyeReadyStrength;
public static void Bind(ConfigFile config) public static void Bind(ConfigFile config)
{ {
@ -111,16 +132,30 @@ namespace RacesOfValheim
SunSicknessDuration = config.Bind(combat, "Sun Sickness Duration", 60f, SunSicknessDuration = config.Bind(combat, "Sun Sickness Duration", 60f,
new ConfigDescription("Seconds of forced human form after being reverted by sunrise.", new AcceptableValueRange<float>(0f, 300f))); new ConfigDescription("Seconds of forced human form after being reverted by sunrise.", new AcceptableValueRange<float>(0f, 300f)));
const string senses = "Fenrir - Superhuman Senses";
SensesRadius = config.Bind(senses, "Detection Radius", 100f,
new ConfigDescription("Meters within which nearby creatures glow green while you are in any form. The light itself follows the Aswid's Marker Light settings.", new AcceptableValueRange<float>(10f, 300f)));
const string buffs = "Fenrir - Form Buffs"; const string buffs = "Fenrir - Form Buffs";
BindNote(config, buffs, "Note: these values need a relog to take effect."); BindNote(config, buffs, "Note: these values need a relog to take effect.");
FullFormSpeedBonus = config.Bind(buffs, "Full Form Speed Bonus", 1.0f, // Each form has a job once all three are unlocked (Lexsonn's suggestion): the Ulv
new ConfigDescription("Speed multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange<float>(0f, 3f))); // travels, the Fenring holds the line, the Cultist burns. The speed keys were renamed
// from "Full Form Speed Bonus" and "Wolf Form Speed Bonus" so a saved .cfg cannot keep
// the old order, where the Fenring outran the Ulv.
FullFormSpeedBonus = config.Bind(buffs, "Fenring And Cultist Speed Bonus", 0.5f,
new ConfigDescription("Speed multiplier bonus while in Fenring or Cultist form. 0.5 = 50% faster.", new AcceptableValueRange<float>(0f, 3f)));
FullFormJumpBonus = config.Bind(buffs, "Full Form Jump Bonus", 1.0f, FullFormJumpBonus = config.Bind(buffs, "Full Form Jump Bonus", 1.0f,
new ConfigDescription("Jump multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange<float>(0f, 3f))); new ConfigDescription("Jump multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange<float>(0f, 3f)));
FullFormFallDamageReduction = config.Bind(buffs, "Full Form Fall Damage Reduction", 1.0f, FullFormFallDamageReduction = config.Bind(buffs, "Full Form Fall Damage Reduction", 1.0f,
new ConfigDescription("Fall damage reduction while in Fenring or Cultist form (1 = immune).", new AcceptableValueRange<float>(0f, 1f))); new ConfigDescription("Fall damage reduction while in Fenring or Cultist form (1 = immune).", new AcceptableValueRange<float>(0f, 1f)));
WolfFormSpeedBonus = config.Bind(buffs, "Wolf Form Speed Bonus", 0.5f, WolfFormSpeedBonus = config.Bind(buffs, "Wolf Speed Bonus", 0.5f,
new ConfigDescription("Speed multiplier bonus while in Wolf or Ulv form.", new AcceptableValueRange<float>(0f, 3f))); new ConfigDescription("Speed multiplier bonus while in Wolf form, the G form before Moder.", new AcceptableValueRange<float>(0f, 3f)));
UlvFormSpeedBonus = config.Bind(buffs, "Ulv Speed Bonus", 1.0f,
new ConfigDescription("Speed multiplier bonus while in Ulv form. The fastest form by default: the one to travel in.", new AcceptableValueRange<float>(0f, 3f)));
FenringDamageReduction = config.Bind(buffs, "Fenring Damage Reduction", 0.3f,
new ConfigDescription("Share of every hit the Fenring shrugs off. 0.3 = 30% less damage taken.", new AcceptableValueRange<float>(0f, 0.9f)));
CultistExtraDamageTaken = config.Bind(buffs, "Cultist Extra Damage Taken", 0.25f,
new ConfigDescription("How much harder hits land on the Cultist. 0.25 = 25% more damage taken.", new AcceptableValueRange<float>(0f, 2f)));
WolfFormFallDamageReduction = config.Bind(buffs, "Wolf Form Fall Damage Reduction", 0.5f, WolfFormFallDamageReduction = config.Bind(buffs, "Wolf Form Fall Damage Reduction", 0.5f,
new ConfigDescription("Fall damage reduction while in Wolf or Ulv form.", new AcceptableValueRange<float>(0f, 1f))); new ConfigDescription("Fall damage reduction while in Wolf or Ulv form.", new AcceptableValueRange<float>(0f, 1f)));
FormStaminaRegenMultiplier = config.Bind(buffs, "Stamina Regen Multiplier", 1.3f, FormStaminaRegenMultiplier = config.Bind(buffs, "Stamina Regen Multiplier", 1.3f,
@ -148,7 +183,7 @@ namespace RacesOfValheim
CultistClawDamage = config.Bind(cultist, "Claw Damage", 85f, CultistClawDamage = config.Bind(cultist, "Claw Damage", 85f,
new ConfigDescription("Base damage of the single claw (Left Mouse), before the Unarmed skill bonus.", new AcceptableValueRange<float>(0f, 500f))); new ConfigDescription("Base damage of the single claw (Left Mouse), before the Unarmed skill bonus.", new AcceptableValueRange<float>(0f, 500f)));
CultistDoubleClawDamage = config.Bind(cultist, "Double Claw Damage", 140f, CultistDoubleClawDamage = config.Bind(cultist, "Double Claw Damage", 140f,
new ConfigDescription("Base damage of the double claw (Middle Mouse), before the Unarmed skill bonus.", new AcceptableValueRange<float>(0f, 500f))); new ConfigDescription("Base damage of the double claw (Middle Mouse), before the Unarmed skill bonus. Each of its two swipes deals 60% of it.", new AcceptableValueRange<float>(0f, 500f)));
CultistAttackRadius = config.Bind(cultist, "Claw Attack Radius", 2.5f, CultistAttackRadius = config.Bind(cultist, "Claw Attack Radius", 2.5f,
new ConfigDescription("Hit-sweep radius for both claw attacks.", new AcceptableValueRange<float>(1f, 10f))); new ConfigDescription("Hit-sweep radius for both claw attacks.", new AcceptableValueRange<float>(1f, 10f)));
CultistPushForce = config.Bind(cultist, "Claw Push Force", 30f, CultistPushForce = config.Bind(cultist, "Claw Push Force", 30f,
@ -188,9 +223,48 @@ namespace RacesOfValheim
UlvPushForce = config.Bind(ulv, "Push Force", 25f, UlvPushForce = config.Bind(ulv, "Push Force", 25f,
new ConfigDescription("Knockback applied on a hit.", new AcceptableValueRange<float>(0f, 100f))); new ConfigDescription("Knockback applied on a hit.", new AcceptableValueRange<float>(0f, 100f)));
// "debug" in the key keeps it local - see ConfigSync. // Form attack stamina, beside each form's damage. Lower than a weapon's on purpose: the
DebugFormHits = config.Bind("Fenrir - Debug", "Debug: Log Form Hits", false, // forms pay less per swing and fill the adrenaline bar faster instead (Form Adrenaline
new ConfigDescription("Writes one log line per claw or bite: what was in reach, what it hit, and why anything was skipped. For bug reports about attacks that do no damage.")); // Multiplier). For scale, vanilla fists cost 4, Bjorn claws 6, Fenris claws 10.
const string staminaNote = " Base stamina, cut by up to a third with the Unarmed skill as a weapon's is. 0 makes it free.";
FormAdrenalineMultiplier = config.Bind(buffs, "Form Adrenaline Multiplier", 1.5f,
new ConfigDescription("Adrenaline per form hit, times the bare-handed amount, in any Fenrir form.", new AcceptableValueRange<float>(0f, 5f)));
FenringLightClawStamina = config.Bind(fenring, "Light Claw Stamina", 6f,
new ConfigDescription("Stamina for the light claw (Left Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
FenringHeavyClawStamina = config.Bind(fenring, "Heavy Claw Stamina", 10f,
new ConfigDescription("Stamina for the heavy claw (Right Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
FenringJumpAttackStamina = config.Bind(fenring, "Jump Attack Stamina", 16f,
new ConfigDescription("Stamina for the leaping attack (Middle Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
CultistClawStamina = config.Bind(cultist, "Claw Stamina", 6f,
new ConfigDescription("Stamina for the single claw (Left Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
CultistDoubleClawStamina = config.Bind(cultist, "Double Claw Stamina", 12f,
new ConfigDescription("Stamina for the double claw (Middle Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
WolfAttack1Stamina = config.Bind(wolf, "Attack 1 Stamina", 4f,
new ConfigDescription("Stamina for the Left Mouse attack." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
WolfAttack2Stamina = config.Bind(wolf, "Attack 2 Stamina", 6f,
new ConfigDescription("Stamina for the Right Mouse attack." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
WolfAttack3Stamina = config.Bind(wolf, "Attack 3 Stamina", 10f,
new ConfigDescription("Stamina for the Middle Mouse attack." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
UlvBiteStamina = config.Bind(ulv, "Bite Stamina", 5f,
new ConfigDescription("Stamina for the Left Mouse bite." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
UlvHeavyBiteStamina = config.Bind(ulv, "Heavy Bite Stamina", 8f,
new ConfigDescription("Stamina for the Right Mouse bite." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
UlvJumpAttackStamina = config.Bind(ulv, "Jump Attack Stamina", 14f,
new ConfigDescription("Stamina for the leaping Middle Mouse attack." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
// The whole section stays local - see ConfigSync.LocalSections.
const string appearance = "Fenrir - Appearance";
ReadyMessage = config.Bind(appearance, "Ready Message", true,
new ConfigDescription("Shows \"<form> is Ready!\" when a form's cooldown ends. The eyes say the same thing; turn this off if they are enough."));
EyeGlow = config.Bind(appearance, "Eye Glow", true,
new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can, yellow when the Cultist is back from its cooldown. Off hides them on every Fenrir you see."));
// Above 0.5 so the red channel (2.0 x strength) passes 1 and the bloom pass picks it
// up: at 0.35 the faint state read as no glow at all. 0.675 is what looked right in game.
EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.675f,
new ConfigDescription("Glow at night while no form is ready.", new AcceptableValueRange<float>(0f, 3f)));
// Tried at 1.2 in game: the orange was too strong. 0.9 checked and kept.
EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 0.9f,
new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange<float>(0f, 3f)));
} }
/// <summary> /// <summary>

View file

@ -14,6 +14,20 @@ namespace RacesOfValheim
/// SE_FenrirForm and the Cultist SE_CultistForm. Checking only SE_FenrirForm, as the attack /// SE_FenrirForm and the Cultist SE_CultistForm. Checking only SE_FenrirForm, as the attack
/// block used to, left three of the four forms out. /// block used to, left three of the four forms out.
/// </summary> /// </summary>
/// <summary>True while the local form is inside an attack, a howl or a breath. Cleared by the
/// form's own routines, and on every revert.</summary>
public static bool LocalAttacking { get; set; }
/// <summary>
/// How many hit events the local form's clips have fired: the creature's own "Hit" event,
/// which CharacterAnimEvent hands to the player's OnAttackTrigger, and BlockPlayerAttackTriggerPatch
/// counts here instead of letting it through. A swing waits for this to move, so its damage
/// lands on the clip's own blow (TrolTrueFormModel.AttackEvents, the same idea).
/// </summary>
public static int AttackEvents { get; private set; }
public static void NotifyAttackTrigger() => AttackEvents++;
public static bool LocalInForm(Character character) public static bool LocalInForm(Character character)
{ {
if (character == null || character != Player.m_localPlayer) return false; if (character == null || character != Player.m_localPlayer) return false;
@ -40,25 +54,244 @@ namespace RacesOfValheim
private float airborneFor; private float airborneFor;
// Whether this form's controller has a "sleeping" bool, asked once per Animator: MonsterAI
// drives the creature's own sleep through it, and not every creature has one.
private Animator sleepChecked;
private bool hasSleeping;
private int sleepState;
private bool wasSitting;
// Read off ulv_animator with scripts/dump_controller.py: the entry state "check sleeping" goes
// to Sleep only at start-up, and Movement has no way back into it. "Base Layer.Sleep" is the
// real path; the short name stays as a fallback for another creature built the same way.
private static readonly string[] SleepStateNames = { "Base Layer.Sleep", "Sleep" };
private static readonly System.Collections.Generic.HashSet<string> sleepLogged = new System.Collections.Generic.HashSet<string>();
/// <summary>Copies the movement parameters, and says whether the form counts as grounded.</summary> /// <summary>Copies the movement parameters, and says whether the form counts as grounded.</summary>
public bool Mirror(Animator form, Animator player, bool crouching) public bool Mirror(Animator form, Animator playerAnim, Player player)
{ {
bool touching = player.GetBool("onGround"); bool touching = playerAnim.GetBool("onGround");
airborneFor = touching ? 0f : airborneFor + Time.deltaTime; airborneFor = touching ? 0f : airborneFor + Time.deltaTime;
bool grounded = airborneFor <= AirborneGrace; bool grounded = airborneFor <= AirborneGrace;
// try/catch as the behaviours always did it: a controller missing one of these must not // try/catch as the behaviours always did it: a controller missing one of these must not
// throw once per frame. // throw once per frame.
try { form.SetBool("onGround", grounded); } catch {} try { form.SetBool("onGround", grounded); } catch {}
try { form.SetBool("inWater", player.GetBool("inWater")); } catch {} try { form.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {}
// Airborne and crouching both read as standing still, as before. // Only airborne reads as standing still now. Crouching used to as well, so a player
bool still = !grounded || crouching; // sneaking in a form slid across the ground in the idle pose. Crouched, the player moves
try { form.SetFloat("forward_speed", still ? 0f : player.GetFloat("forward_speed")); } catch {} // at sneaking speed, and the creature's controller picks its walk for a speed that low:
try { form.SetFloat("sideway_speed", still ? 0f : player.GetFloat("sideway_speed")); } catch {} // the sneak a player asked for, from animations the creature already has.
//
// Sitting reads as still too. The seated player's own Animator keeps a forward_speed that
// is not zero, and passed through it kept the Ulv in its Walk clip - on the spot, and out
// of reach of its Sleep state, which only leaves from idle. Seen in the log: sitting,
// sleeping=true, clip 'Walk'.
bool sitting = IsSitting(player);
bool still = !grounded || sitting;
try { form.SetFloat("forward_speed", still ? 0f : playerAnim.GetFloat("forward_speed")); } catch {}
try { form.SetFloat("sideway_speed", still ? 0f : playerAnim.GetFloat("sideway_speed")); } catch {}
// Sitting puts the creature to sleep, on the "sleeping" bool its own MonsterAI uses - the
// Ulv curls up. IsSitting reads the animator's state, which is replicated, so it is right
// for an onlooker's copy too.
if (sleepChecked != form)
{
sleepChecked = form;
hasSleeping = false;
foreach (AnimatorControllerParameter p in form.parameters)
{
if (p.type == AnimatorControllerParameterType.Bool && p.name == "sleeping") { hasSleeping = true; break; }
}
// The state's name is not readable at runtime, only testable - but it is readable offline,
// see SleepStateNames.
sleepState = 0;
string found = "none";
if (hasSleeping)
{
foreach (string candidate in SleepStateNames)
{
int hash = Animator.StringToHash(candidate);
if (!form.HasState(0, hash)) continue;
sleepState = hash;
found = candidate;
break;
}
}
string controller = form.runtimeAnimatorController != null ? form.runtimeAnimatorController.name : form.name;
if (sleepLogged.Add(controller))
{
Jotunn.Logger.LogInfo($"[FenrirForm] '{controller}' {(hasSleeping ? "has" : "has no")} sleeping animation; " +
(hasSleeping ? $"sitting puts it to sleep (state '{found}')." : "sitting keeps it idle."));
}
}
if (hasSleeping)
{
form.SetBool("sleeping", sitting);
// The bool alone never put the Ulv to sleep. A vanilla Ulv is BORN asleep: its
// controller enters Sleep from the start and only knows the way out (Sleep, then
// 'Sleep to Idle' once the bool drops). Nothing leads from Idle back into Sleep, so
// the state is entered by hand when the player sits; standing up drops the bool and
// the controller's own wake-up plays.
if (sitting && !wasSitting && sleepState != 0) form.CrossFadeInFixedTime(sleepState, 0.4f, 0);
}
wasSitting = sitting;
PlaceOnChair(form, player);
return grounded; return grounded;
} }
// How far in front of the seat a creature on a chair settles, in metres.
private const float ChairForward = 1f;
// And turned a quarter left, counter-clockwise seen from above, so it lies across the front
// of the seat rather than facing out of it.
private static readonly Quaternion ChairTurn = Quaternion.Euler(0f, -90f, 0f);
private static readonly int ChairGroundMask = LayerMask.GetMask("Default", "static_solid", "terrain", "piece", "vehicle");
private static readonly RaycastHit[] chairHits = new RaycastHit[16];
private Transform placedRoot;
/// <summary>
/// On a chair the player sits on the seat itself, and a creature there stood inside the chair,
/// at seat height. It goes half a metre in front of the seat instead, standing on whatever is
/// under that point. Moves the form's own root (the child of the player), never the player.
/// The sit key is left alone: the player is on the ground already.
/// </summary>
private void PlaceOnChair(Animator form, Player player)
{
Transform root = RootUnder(form.transform, player != null ? player.transform : null);
if (root == null) return;
bool onChair = player.IsSitting();
if (!onChair)
{
if (placedRoot == root)
{
if (root.localPosition != Vector3.zero) root.localPosition = Vector3.zero;
if (root.localRotation != Quaternion.identity) root.localRotation = Quaternion.identity;
}
return;
}
placedRoot = root;
Transform body = player.transform;
Piece seat = SeatUnder(body.position);
Vector3 target = body.position + body.forward * ChairForward;
float groundY = target.y;
int count = Physics.RaycastNonAlloc(target + Vector3.up * 1.5f, Vector3.down, chairHits, 4f, ChairGroundMask);
float best = float.MaxValue;
for (int i = 0; i < count; i++)
{
Collider c = chairHits[i].collider;
if (c == null || c.transform.IsChildOf(body)) continue;
if (seat != null && c.GetComponentInParent<Piece>() == seat) continue;
if (chairHits[i].distance < best) { best = chairHits[i].distance; groundY = chairHits[i].point.y; }
}
root.localPosition = body.InverseTransformPoint(new Vector3(target.x, groundY, target.z));
root.localRotation = ChairTurn;
}
/// <summary>The chair or bench the player sits on: the first piece straight under them.</summary>
private static Piece SeatUnder(Vector3 position)
{
int count = Physics.RaycastNonAlloc(position + Vector3.up * 0.3f, Vector3.down, chairHits, 1.5f, ChairGroundMask);
Piece seat = null;
float best = float.MaxValue;
for (int i = 0; i < count; i++)
{
Piece piece = chairHits[i].collider != null ? chairHits[i].collider.GetComponentInParent<Piece>() : null;
if (piece != null && chairHits[i].distance < best) { best = chairHits[i].distance; seat = piece; }
}
return seat;
}
private static Transform RootUnder(Transform t, Transform player)
{
if (player == null) return null;
while (t != null && t.parent != player) t = t.parent;
return t;
}
/// <summary>
/// The sit key, or a chair. The sit key is an EMOTE, not the "sitting" animator tag that
/// Humanoid.IsSitting asks about - that tag belongs to chairs and benches - so IsSitting alone
/// never saw it and the Ulv stayed on its feet. Player.StartEmote writes the emote's name on the
/// ZDO, which every client reads, so this is right for an onlooker's copy as well.
/// </summary>
private static bool IsSitting(Player player)
{
if (player == null) return false;
if (player.IsSitting()) return true;
ZNetView nview = player.GetComponent<ZNetView>();
return nview != null && nview.IsValid() && nview.GetZDO().GetString(ZDOVars.s_emote, "") == "sit";
}
}
/// <summary>
/// Two ways a form's Animator and its attack lock got stuck, shared by all four forms.
///
/// The idle howl is a looping clip the attack triggers cannot leave: a click during it queued a
/// trigger the Animator never took, and the model stood frozen until the form was dropped.
/// And an exception inside an attack routine left isAttacking true for good - Update does
/// nothing at all while it is - so the watchdog gives any lock a ceiling.
/// </summary>
internal static class FormAnimGuard
{
/// <summary>Longer than the longest legitimate routine (the Ulv's howl, 3.8 s, plus a margin).</summary>
private const float MaxLockSeconds = 8f;
/// <summary>If the Animator is inside a howl clip, puts it back on its default state so the
/// trigger set next lands on the idle and not on the loop. Call after isAttacking is set.</summary>
public static void LeaveHowl(Animator animator)
{
if (animator == null) return;
try
{
foreach (AnimatorClipInfo clip in animator.GetCurrentAnimatorClipInfo(0))
{
if (clip.clip == null) continue;
string lower = clip.clip.name.ToLower();
if (!lower.Contains("hawl") && !lower.Contains("howl")) continue;
animator.Rebind();
animator.Update(0f);
return;
}
}
catch {}
}
/// <summary>True once the lock has been held longer than any routine can legitimately hold
/// it. Call every Update; <paramref name="since"/> is the caller's own field.</summary>
public static bool Stuck(bool locked, ref float since)
{
if (!locked)
{
since = -1f;
return false;
}
if (since < 0f)
{
since = Time.time;
return false;
}
if (Time.time - since <= MaxLockSeconds) return false;
since = -1f;
Jotunn.Logger.LogWarning("[FenrirForm] An attack lock held for more than " + MaxLockSeconds +
" s was released; something in a routine did not finish.");
return true;
}
} }
/// <summary> /// <summary>
@ -109,21 +342,133 @@ namespace RacesOfValheim
/// </summary> /// </summary>
public static void LogMiss(string form, Collider hit, string reason) public static void LogMiss(string form, Collider hit, string reason)
{ {
if (!FenrirConfig.DebugFormHits.Value) return; if (!DebugConfig.LogFormHits.Value) return;
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing skipped '{hit.name}' (layer {LayerMask.LayerToName(hit.gameObject.layer)}): {reason}."); Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing skipped '{hit.name}' (layer {LayerMask.LayerToName(hit.gameObject.layer)}): {reason}.");
} }
/// <summary>
/// The adrenaline vanilla gives for a weapon hit, which a form's hit never got. Vanilla
/// grants it inside Attack (m_attackAdrenaline x the enemy's m_enemyAdrenalineMultiplier);
/// the forms skip Attack and call Damage directly, so only the stagger bonus inside
/// Character.Damage reached the player. That is the report: easy-to-stagger meadow mobs
/// filled the bar, Lox, Tar, Brutes and Furlings only did when staggered.
///
/// The per-hit amount is the player's own unarmed attack's, since the forms fight
/// unarmed. scale lets a damage-over-time tick pay a fraction of a hit.
/// </summary>
public static void GrantAdrenaline(IDestructible target, float scale = 1f)
{
Player player = Player.m_localPlayer;
if (player == null || !(target is Character character) || character == player) return;
ItemDrop unarmed = player.m_unarmedWeapon;
float perHit = unarmed != null ? unarmed.m_itemData.m_shared.m_attack.m_attackAdrenaline : 1f;
// The Fenrir forms trade cheaper swings for a faster bar; the other races' forms do not.
if (FenrirForms.LocalInForm(player)) perHit *= FenrirConfig.FormAdrenalineMultiplier.Value;
player.AddAdrenaline(perHit * character.m_enemyAdrenalineMultiplier * scale);
}
/// <summary>
/// The skill experience vanilla gives for a weapon hit, which a hand-built hit never got.
/// Vanilla raises the skill inside Attack (once per swing that landed on a creature) and
/// inside Projectile.OnHit; Character.Damage never does, so a form that calls Damage
/// directly left its skill at whatever level the player brought in. Call it once per
/// swing or tick, after the loop, never once per target. amount lets a damage-over-time
/// tick pay a fraction of a swing.
/// </summary>
public static void RaiseSkill(Skills.SkillType skill, float amount = 1f)
{
Player player = Player.m_localPlayer;
if (player == null || amount <= 0f) return;
player.RaiseSkill(skill, amount);
}
/// <summary>
/// Charges a form attack's stamina the way vanilla charges a weapon's (Attack.GetAttackStamina):
/// the equipment modifier, status effects (meads, race passives), then up to a third off with
/// the attack's skill. Without enough, the attack does not start and the stamina bar flashes,
/// as it does for a weapon. A cost of 0 is free and always goes through.
/// A staggered player cannot attack at all, and an attack that may start is marked for
/// FormStagger, so a stagger before its hit cancels it.
/// </summary>
/// <returns>True if the attack may start; the stamina is already spent.</returns>
public static bool TrySpendStamina(Player player, float baseCost, Skills.SkillType skill)
{
if (player != null && player.IsStaggering()) return false;
FormStagger.MarkAttack();
if (player == null || baseCost <= 0f) return true;
float cost = baseCost * (1f + player.GetEquipmentAttackStaminaModifier());
player.GetSEMan().ModifyAttackStaminaUsage(cost, ref cost);
cost -= cost * 0.33f * player.GetSkillFactor(skill);
if (cost <= 0f) return true;
if (!player.HaveStamina(cost + 0.1f))
{
if (player == Player.m_localPlayer && Hud.instance != null) Hud.instance.StaminaBarEmptyFlash();
return false;
}
player.UseStamina(cost);
return true;
}
private static readonly System.Collections.Generic.Dictionary<string, ItemDrop.ItemData.SharedData> weapons =
new System.Collections.Generic.Dictionary<string, ItemDrop.ItemData.SharedData>();
/// <summary>
/// A creature's own attack item (dragon_bite, SeekerBrute_ram...), read once and cached,
/// null if the game has none by that name. A hand-built swing skips Attack, and Attack is
/// where vanilla plays the item's m_triggerEffect and m_hitEffect, so a form that wants the
/// creature's real swing and impact sounds plays them from here.
/// </summary>
public static ItemDrop.ItemData.SharedData CreatureWeapon(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return null;
if (weapons.TryGetValue(prefabName, out ItemDrop.ItemData.SharedData cached)) return cached;
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
ItemDrop.ItemData.SharedData shared = prefab != null ? prefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared : null;
if (shared == null) Jotunn.Logger.LogWarning($"[FormMelee] No attack item '{prefabName}'; that swing stays silent.");
weapons[prefabName] = shared;
return shared;
}
public static void LogHit(string form, IDestructible target, float damage) public static void LogHit(string form, IDestructible target, float damage)
{ {
if (!FenrirConfig.DebugFormHits.Value) return; if (!DebugConfig.LogFormHits.Value) return;
string name = target is MonoBehaviour behaviour && behaviour != null ? behaviour.name : target.ToString(); string name = target is MonoBehaviour behaviour && behaviour != null ? behaviour.name : target.ToString();
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing hit '{name}' for {damage:0}."); Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing hit '{name}' for {damage:0}.");
} }
public static void LogSwing(string form, int candidates) public static void LogSwing(string form, int candidates)
{ {
if (!FenrirConfig.DebugFormHits.Value) return; if (!DebugConfig.LogFormHits.Value) return;
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing: {candidates} collider(s) in reach."); Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing: {candidates} collider(s) in reach.");
} }
} }
/// <summary>
/// Holds the player still through a form's attack clips, the way a human stands to swing. The
/// hidden player kept walking under the creature, so the bite slid toward whatever WASD held.
/// SkeletonRiseControlsPatch's arrangement: the move direction is SetControls' first argument,
/// bound by position. The Fenring's and the Ulv's leaps move the body directly and are untouched.
/// </summary>
[HarmonyLib.HarmonyPatch(typeof(Player), "SetControls")]
public static class Fenrir_FormHoldStill_Patch
{
public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge)
{
if (__instance != Player.m_localPlayer || !FenrirForms.LocalAttacking) return;
if (!FenrirForms.LocalInForm(__instance))
{
FenrirForms.LocalAttacking = false;
return;
}
__0 = Vector3.zero;
jump = false;
crouch = false;
dodge = false;
}
}
} }

View file

@ -326,8 +326,12 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName; piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
piece.m_groundOnly = true; // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = BorrowIcon("TrophyFenring"); piece.m_icon = BorrowIcon("TrophyFenring");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench"); Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");

View file

@ -34,6 +34,34 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// The rest of the human's attack loop, shut while a form is up. StartAttack is the only door an
/// attack starts through and it is blocked above, but a crossbow also lives in the loop around it:
/// PlayerAttackInput reloads it and holds its draw, and the form's own Animator carries
/// CharacterAnimEvent, whose OnAttackTrigger event resolves to the PLAYER (its Character is the first
/// one up the hierarchy) and fires whatever attack the human still has in hand. A tester's crossbow
/// shot on all three form attacks, reloaded for free, like a semi-automatic.
/// </summary>
[HarmonyPatch(typeof(Player), "PlayerAttackInput")]
public static class BlockPlayerAttackInputPatch
{
public static bool Prefix(Player __instance)
{
return !FenrirForms.LocalInForm(__instance);
}
}
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))]
public static class BlockPlayerAttackTriggerPatch
{
public static bool Prefix(Humanoid __instance)
{
if (!FenrirForms.LocalInForm(__instance)) return true;
FenrirForms.NotifyAttackTrigger();
return false;
}
}
// --- PATCH 2: BLOCCO ANIMAZIONI ED EFFETTI SONORI NATIVI --- // --- PATCH 2: BLOCCO ANIMAZIONI ED EFFETTI SONORI NATIVI ---
// Every form now, not the Fenring alone: see BlockPlayerLogicAttackPatch. // Every form now, not the Fenring alone: see BlockPlayerLogicAttackPatch.
[HarmonyPatch(typeof(ZSyncAnimation), nameof(ZSyncAnimation.SetTrigger))] [HarmonyPatch(typeof(ZSyncAnimation), nameof(ZSyncAnimation.SetTrigger))]

View file

@ -76,7 +76,7 @@ namespace RacesOfValheim {
cultistCdSE.m_icon = fenringTrophyIcon; cultistCdSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false));
formBuffSE = ScriptableObject.CreateInstance<SE_Stats>(); formBuffSE = ScriptableObject.CreateInstance<SE_FenrirFormBuff>();
formBuffSE.name = "SE_FenrirForm"; formBuffSE.name = "SE_FenrirForm";
formBuffSE.m_name = "$rov_se_fenrir_form_name"; formBuffSE.m_name = "$rov_se_fenrir_form_name";
formBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value; formBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value;
@ -87,7 +87,7 @@ namespace RacesOfValheim {
formBuffSE.m_icon = fenringTrophyIcon; formBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(formBuffSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(formBuffSE, fixReference: false));
cultistFormBuffSE = ScriptableObject.CreateInstance<SE_Stats>(); cultistFormBuffSE = ScriptableObject.CreateInstance<SE_FenrirFormBuff>();
cultistFormBuffSE.name = "SE_CultistForm"; cultistFormBuffSE.name = "SE_CultistForm";
cultistFormBuffSE.m_name = "$rov_se_fenrir_cultistform_name"; cultistFormBuffSE.m_name = "$rov_se_fenrir_cultistform_name";
cultistFormBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value; cultistFormBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value;
@ -98,7 +98,7 @@ namespace RacesOfValheim {
cultistFormBuffSE.m_icon = fenringTrophyIcon; cultistFormBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistFormBuffSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistFormBuffSE, fixReference: false));
wolfFormBuffSE = ScriptableObject.CreateInstance<SE_Stats>(); wolfFormBuffSE = ScriptableObject.CreateInstance<SE_FenrirFormBuff>();
wolfFormBuffSE.name = "SE_WolfForm"; wolfFormBuffSE.name = "SE_WolfForm";
wolfFormBuffSE.m_name = "$rov_se_fenrir_wolfform_name"; wolfFormBuffSE.m_name = "$rov_se_fenrir_wolfform_name";
wolfFormBuffSE.m_speedModifier = FenrirConfig.WolfFormSpeedBonus.Value; wolfFormBuffSE.m_speedModifier = FenrirConfig.WolfFormSpeedBonus.Value;
@ -109,6 +109,16 @@ namespace RacesOfValheim {
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(wolfFormBuffSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(wolfFormBuffSE, fixReference: false));
} }
// Set on the live copy each time a form is taken, not on the registered template: the Wolf
// and the Ulv share SE_WolfForm but not a speed, and a changed value applies at the next
// transform instead of after a relog.
private static void SetFormBuff(StatusEffect se, float speedBonus, float damageTakenFactor)
{
if (!(se is SE_FenrirFormBuff buff)) return;
buff.m_speedModifier = speedBonus;
buff.m_damageTakenFactor = damageTakenFactor;
}
private void Update() private void Update()
{ {
if (Player.m_localPlayer == null || EnvMan.instance == null) return; if (Player.m_localPlayer == null || EnvMan.instance == null) return;
@ -150,6 +160,8 @@ namespace RacesOfValheim {
} }
wasNight = isNight; wasNight = isNight;
FenrirVisuals.SetReady(Player.m_localPlayer, GetReadyState());
if (isTransformed) if (isTransformed)
{ {
bool hasAnyForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode()) || bool hasAnyForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode()) ||
@ -162,6 +174,10 @@ namespace RacesOfValheim {
} }
} }
// The hunter's senses, shared with the Aswid: every form has them, the human does not.
if (isTransformed) HunterSenses.Tick(FenrirConfig.SensesRadius.Value);
else HunterSenses.Clear();
if (!RaceInput.Allowed) return; if (!RaceInput.Allowed) return;
int state = BossProgressionManager.GetCurrentProgressionState(); int state = BossProgressionManager.GetCurrentProgressionState();
@ -171,6 +187,42 @@ namespace RacesOfValheim {
if (FenrirConfig.CultistFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(FenrirProgression.GetJKeyRules(state)); return; } if (FenrirConfig.CultistFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(FenrirProgression.GetJKeyRules(state)); return; }
} }
/// <summary>
/// What the eyes should say right now, using the same gates as TryTransformWithRules
/// below without its messages. The Cultist wins over the other forms only while its rules
/// give it a cooldown: that is the one form whose return is worth announcing.
/// </summary>
private FenrirVisuals.ReadyState GetReadyState()
{
if (isTransformed) return FenrirVisuals.ReadyState.None;
int state = BossProgressionManager.GetCurrentProgressionState();
FenrirProgression.FormRules cultist = FenrirProgression.GetJKeyRules(state);
if (CanTake(cultist) && cultist.CooldownMinutes > 0) return FenrirVisuals.ReadyState.Cultist;
if (CanTake(FenrirProgression.GetGKeyRules(state))
|| CanTake(FenrirProgression.GetHKeyRules(state))
|| CanTake(cultist))
{
return FenrirVisuals.ReadyState.Form;
}
return FenrirVisuals.ReadyState.None;
}
private bool CanTake(FenrirProgression.FormRules rules)
{
if (rules == null || rules.Form == FenrirProgression.FormType.None) return false;
if (rules.NeedsNight && (sunSicknessTimer > 0f || !EnvMan.IsNight())) return false;
if (rules.CooldownMinutes > 0)
{
string cdName = rules.Form == FenrirProgression.FormType.Cultist ? "SE_CultistCooldown" : "SE_FenrirCooldown";
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect(cdName.GetStableHashCode())) return false;
}
return true;
}
private void TryTransformWithRules(FenrirProgression.FormRules rules) private void TryTransformWithRules(FenrirProgression.FormRules rules)
{ {
if (rules == null || rules.Form == FenrirProgression.FormType.None) return; if (rules == null || rules.Form == FenrirProgression.FormType.None) return;
@ -185,7 +237,7 @@ namespace RacesOfValheim {
if (isTransformed) if (isTransformed)
{ {
StartCoroutine(RevertToHumanRoutine()); RunFormRoutine(RevertToHumanRoutine());
return; return;
} }
@ -213,7 +265,7 @@ namespace RacesOfValheim {
} }
} }
StartCoroutine(TransformIntoWolfRoutine(rules)); RunFormRoutine(TransformIntoWolfRoutine(rules));
} }
/// <summary> /// <summary>
@ -256,11 +308,64 @@ namespace RacesOfValheim {
return "$rov_msg_fenrir_formname_fenrir"; return "$rov_msg_fenrir_formname_fenrir";
} }
// The one transform or revert routine in flight, if any, so ResetRace can stop it. A
// revert left to finish on its own lands its cooldown after the reset has already swept
// the status effects, and the next Fenrir starts locked out.
private Coroutine formRoutine;
private void RunFormRoutine(IEnumerator routine)
{
formRoutine = StartCoroutine(routine);
}
/// <summary>
/// Drops whatever form is up, immediately, for ResetRace: no poof, no message, and no
/// cooldown - ExecuteReversion hands one out, which is right for a form running out and
/// wrong for a player leaving the race.
/// </summary>
/// <returns>True if there was a form to drop.</returns>
public bool HardResetForReset()
{
Player player = Player.m_localPlayer;
if (player == null) return false;
if (formRoutine != null)
{
StopCoroutine(formRoutine);
formRoutine = null;
}
bool hadForm = isTransformed || isTransformingSequence || currentTransformation != null;
if (hadForm)
{
if (currentTransformation != null) Destroy(currentTransformation);
currentTransformation = null;
DestroyAllForms();
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_FenrirForm", "");
PlayerVisualHider.Show(player.transform.Find("Visual"), "fenrir-reset");
player.GetSEMan().RemoveStatusEffect("SE_FenrirForm".GetStableHashCode());
player.GetSEMan().RemoveStatusEffect("SE_CultistForm".GetStableHashCode());
player.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode());
}
FenrirForms.LocalAttacking = false;
isTransformed = false;
isTransformingSequence = false;
activeRules = null;
revertMessage = null;
sunSicknessTimer = 0f;
return hadForm;
}
public void ForceRevert() public void ForceRevert()
{ {
if (isTransformed && !isTransformingSequence) if (isTransformed && !isTransformingSequence)
{ {
StartCoroutine(RevertToHumanRoutine()); RunFormRoutine(RevertToHumanRoutine());
} }
} }
@ -321,6 +426,7 @@ namespace RacesOfValheim {
private IEnumerator RevertToHumanRoutine() private IEnumerator RevertToHumanRoutine()
{ {
isTransformingSequence = true; isTransformingSequence = true;
HunterSenses.Clear();
if (currentTransformation != null) if (currentTransformation != null)
{ {
@ -454,6 +560,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.UlvFormSpeedBonus.Value, 1f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_ulv")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_ulv"));
} }
else if (prefabName == "Wolf") else if (prefabName == "Wolf")
@ -462,6 +569,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.WolfFormSpeedBonus.Value, 1f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_wolf")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_wolf"));
} }
else if (prefabName == "Fenring_Cultist") else if (prefabName == "Fenring_Cultist")
@ -470,6 +578,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.FullFormSpeedBonus.Value, 1f + FenrirConfig.CultistExtraDamageTaken.Value);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_cultist")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_cultist"));
} }
else else
@ -478,6 +587,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.FullFormSpeedBonus.Value, 1f - FenrirConfig.FenringDamageReduction.Value);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_fenring")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_fenring"));
} }
@ -523,6 +633,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_CultistForm".GetStableHashCode()); Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_CultistForm".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode()); Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode());
FenrirForms.LocalAttacking = false;
isTransformed = false; isTransformed = false;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, revertMessage ?? ModText.Get("rov_msg_fenrir_returned_human_form")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, revertMessage ?? ModText.Get("rov_msg_fenrir_returned_human_form"));
revertMessage = null; revertMessage = null;

View file

@ -15,13 +15,30 @@ namespace RacesOfValheim
public override void Stop() public override void Stop()
{ {
base.Stop(); base.Stop();
if (Player.m_localPlayer != null) if (Player.m_localPlayer != null && FenrirConfig.ReadyMessage.Value)
{ {
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_ready", m_name)); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_ready", m_name));
} }
} }
} }
/// <summary>
/// A form's buff, plus a scale on the hits it takes: the Fenring holds the line on less, the
/// Cultist pays for its fire with more. SEMan.OnDamaged runs in Character.RPC_Damage on the
/// owner's machine, ahead of armor and the health loss, so the scale reaches every hit,
/// whoever's machine the attacker is on.
/// </summary>
public class SE_FenrirFormBuff : SE_Stats
{
public float m_damageTakenFactor = 1f;
public override void OnDamaged(HitData hit, Character attacker)
{
base.OnDamaged(hit, attacker);
if (!Mathf.Approximately(m_damageTakenFactor, 1f)) hit.ApplyModifier(m_damageTakenFactor);
}
}
public class SE_FenrirCurse : SE_Stats public class SE_FenrirCurse : SE_Stats
{ {
public override void Setup(Character character) public override void Setup(Character character)

View file

@ -0,0 +1,277 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Fenrir's eyes catch the light at night, the way a wolf's do: a faint glow while no form
/// can be taken, a bright one when a key would transform right now, and the Cultist's yellow
/// when that form is back from its cooldown. Dark by day and while in a
/// beast form, whose own eyes take over. A community suggestion (lexsonn), meant to say what
/// the "Ready!" text says without the text.
///
/// Built the way AswidVisuals builds the Aswid's eyes, which is where the long story lives: the
/// vanilla Skeleton's eye_l/eye_r borrowed for mesh and material, placed on the head bone the
/// body mesh is skinned to, sized from the source's world scale. The placement numbers are the
/// Aswid's playtested defaults, fixed here rather than exposed again.
///
/// The colour is the Fenring's own: its body material's _EmissionColor, (2.0, 0.372, 0.0) in
/// bundle c4210710, read offline with UnityPy rather than picked by eye.
///
/// Runs for remote players too. Night is the same for everyone; whether a form is ready is
/// only known to the owner, who writes it to the ZDO (SetReady) for everyone else to read.
/// </summary>
public static class FenrirVisuals
{
public const string RaceId = "Fenrir";
public const string ReadyKey = "RacesOfValheim_FenrirReady";
/// <summary>Written to the ZDO as an int, so the values are part of the network contract.</summary>
public enum ReadyState
{
None = 0,
Form = 1,
Cultist = 2,
}
private const string FormKey = "RacesOfValheim_FenrirForm";
private const string EyesName = "FenrirEyes";
private const string SourceModel = "Skeleton";
private static readonly string[] SourceEyeNames = { "eye_l", "eye_r" };
private static readonly Color FenringGlow = new Color(2.0f, 0.372f, 0f, 1f);
// The Cultist's body is the Fenring's material and its breath is white flame tinted by
// texture, so neither tells it apart. Its own death effect (vfx_fenring_cultist_death)
// does: FlameRoundYellowParticle's _EmissionColor, same bundle.
private static readonly Color CultistGlow = new Color(2.691f, 1.797f, 0.455f, 1f);
// AswidVisuals' base placement plus its Configuration Manager defaults, which are what
// playtesting settled on for this same pair of eyes on this same rig.
private const float EyeForward = 0.081f + 0.013f;
private const float EyeHeight = 0.181f + 0.004f;
private const float EyeSeparation = 0.032f + 0.007f;
private const float EyeSize = 1.1f;
private const float EyeYaw = 22.068f;
private const float EyeRoll = -180f;
/// <summary>Owner only, and only on a change: one ZDO write per transition, not per frame.</summary>
public static void SetReady(Player player, ReadyState ready)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
ZDO zdo = nview.GetZDO();
if (zdo.GetInt(ReadyKey, 0) != (int)ready) zdo.Set(ReadyKey, (int)ready);
}
/// <summary>
/// Keeps the eyes on a living Fenrir and takes them off anyone else. Called from
/// VisEquipment.UpdateColors, which is what notices a race change; the ticker below then
/// follows night, readiness and forms frame by frame.
/// </summary>
public static void ApplyEyes(Player player)
{
if (player == null) return;
Transform headBone = FindHeadBone(player);
if (headBone == null) return; // rig not up yet; the ticker or the next refresh retries
Transform eyes = headBone.Find(EyesName);
if (DvergarVisuals.GetPlayerRace(player) != RaceId || player.IsDead())
{
if (eyes != null)
{
// Renamed first: Destroy waits for the end of the frame.
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
}
EyeTicker ticker = player.GetComponent<EyeTicker>();
if (ticker != null) Object.Destroy(ticker);
return;
}
if (player.GetComponent<EyeTicker>() == null) player.gameObject.AddComponent<EyeTicker>();
float strength = GetGlowStrength(player, out Color hue);
if (strength <= 0f)
{
if (eyes != null && eyes.gameObject.activeSelf) eyes.gameObject.SetActive(false);
return;
}
if (eyes == null)
{
// The skull's facing is measured once, at build time. A head turned by sitting,
// an attack or sleep would measure wrong; see AswidVisuals.ApplyEyes.
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping()) return;
eyes = BuildEyes(player, headBone);
if (eyes == null) return;
}
if (!eyes.gameObject.activeSelf) eyes.gameObject.SetActive(true);
PaintEyes(eyes, hue * strength);
}
/// <summary>
/// 0 means dark: day, a beast form, or the viewer turned the glow off. Otherwise faint
/// orange with nothing ready, bright orange with a form ready, bright yellow when the
/// Cultist is back from its cooldown.
/// </summary>
private static float GetGlowStrength(Player player, out Color hue)
{
hue = FenringGlow;
if (!FenrirConfig.EyeGlow.Value) return 0f;
if (EnvMan.instance == null || !EnvMan.IsNight()) return 0f;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return 0f;
ZDO zdo = nview.GetZDO();
if (!string.IsNullOrEmpty(zdo.GetString(FormKey, ""))) return 0f;
ReadyState ready = (ReadyState)zdo.GetInt(ReadyKey, 0);
if (ready == ReadyState.None) return FenrirConfig.EyeNightStrength.Value;
if (ready == ReadyState.Cultist) hue = CultistGlow;
return FenrirConfig.EyeReadyStrength.Value;
}
public class EyeTicker : MonoBehaviour
{
private Player m_player;
private void Awake() => m_player = GetComponent<Player>();
private void LateUpdate()
{
if (m_player == null) { Destroy(this); return; }
ApplyEyes(m_player);
}
}
/// <summary>The body mesh's own Head bone, never the Animator's. See AswidVisuals.FindHeadBone.</summary>
private static Transform FindHeadBone(Player player)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null;
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name == AswidVisuals.PlayerHeadBoneName) return bone;
}
return null;
}
private static Transform BuildEyes(Player player, Transform headBone)
{
List<Transform> sources = FindSourceEyes();
if (sources.Count == 0) return null;
float lossy = headBone.lossyScale.x;
if (Mathf.Abs(lossy) < 0.0001f) return null; // rig still coming up
float toLocal = 1f / lossy;
GameObject holder = new GameObject(EyesName);
holder.transform.SetParent(headBone, false);
RigBindPose.MeasureHeadFrame(player, headBone, RaceId,
out Vector3 forward, out Vector3 up, out Vector3 right);
Quaternion facing = Quaternion.LookRotation(forward, up);
// The player's own scale cancels the rig's, as in AswidVisuals.PlaceEyes.
float scale = player.transform.localScale.x * toLocal;
foreach (Transform source in sources)
{
GameObject eye = Object.Instantiate(source.gameObject, holder.transform);
eye.name = source.name;
float side = source.name.ToLowerInvariant().Contains("_l") ? -1f : 1f;
eye.transform.localPosition = forward * (EyeForward * scale)
+ up * (EyeHeight * scale)
+ right * (side * EyeSeparation * scale);
// Yaw mirrored per eye so the pair turns in towards the nose together.
eye.transform.localRotation = Quaternion.Euler(0f, EyeYaw * side, EyeRoll) * facing;
eye.transform.localScale = source.lossyScale * toLocal * EyeSize;
// Allowlist: whatever else rode along on the skeleton goes.
foreach (Component comp in eye.GetComponentsInChildren<Component>(true))
{
if (comp is Transform || comp is MeshRenderer || comp is MeshFilter) continue;
if (comp is ParticleSystem || comp is ParticleSystemRenderer)
{
// The skeleton's eye smoke, on a child of the eye: too loud for a reflection.
if (comp.gameObject != eye) comp.gameObject.SetActive(false);
continue;
}
Object.Destroy(comp);
}
foreach (Renderer renderer in eye.GetComponentsInChildren<Renderer>(true))
{
renderer.enabled = true;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
}
eye.SetActive(true);
}
return holder.transform;
}
/// <summary>Every colour property the borrowed material has; see AswidVisuals.PaintEyes.</summary>
private static void PaintEyes(Transform holder, Color glow)
{
glow.a = 1f;
foreach (Renderer renderer in holder.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.material;
if (material == null) continue;
if (material.HasProperty("_Color")) material.SetColor("_Color", glow);
if (material.HasProperty("_TintColor")) material.SetColor("_TintColor", glow);
if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", glow);
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow);
}
}
private static bool warnedSource;
private static List<Transform> FindSourceEyes()
{
List<Transform> found = new List<Transform>();
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(SourceModel);
if (prefab != null)
{
foreach (Transform t in prefab.GetComponentsInChildren<Transform>(true))
{
string lower = t.name.ToLower();
if (lower == SourceEyeNames[0] || lower == SourceEyeNames[1]) found.Add(t);
}
}
if (found.Count == 0 && !warnedSource)
{
warnedSource = true;
Jotunn.Logger.LogWarning($"[Fenrir] No eye_l/eye_r found on '{SourceModel}' - the eyes stay dark.");
}
return found;
}
}
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class FenrirEyesPatch
{
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
FenrirVisuals.ApplyEyes(__instance.GetComponent<Player>());
}
}
}

View file

@ -0,0 +1,167 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The lights a player wears - the Dvergr circlet's headlamp, a torch in hand - follow the form
/// the player has taken.
///
/// A form hides the human body and leaves it standing where it was: PlayerVisualHider turns its
/// renderers off, the Muspell shrinks the Visual to nothing. Either way the gear stays on the
/// body's bones, and a Light is not a renderer, so the headlamp kept shining from the hidden
/// human's head: at a person's height inside a troll's chest, from the feet of a Muspell. A
/// tester saw it stuck where the head had been before the transformation.
///
/// While the body is hidden, every Light under it is put at the form's head bone, a little in
/// front of it. A form with no bone called "head" gets the top front of its own model instead,
/// and with no form model at all the light sits centre-forward at a person's head height. The
/// lights go back to their own places the moment the body shows again.
///
/// Run for every player, not only the local one: the headlamp lights the world for onlookers too.
/// </summary>
public class FormLightFollow : MonoBehaviour
{
// Lights and the form's head are looked up again this often: VisEquipment rebuilds gear,
// and a form can be built a frame after the body is hidden.
private const float RescanInterval = 0.25f;
// RaceEyeHeight's reading of a Visual this small: hidden, not small.
private const float HiddenScale = 0.05f;
// Ahead of the head bone, so the lamp does not light the skull from inside.
private const float AheadOfHead = 0.3f;
// No form model at all: centre-forward, where a person's headlamp would be.
private static readonly Vector3 FallbackOffset = new Vector3(0f, 1.6f, 0.4f);
private static readonly AccessTools.FieldRef<Character, GameObject> VisualRef =
AccessTools.FieldRefAccess<Character, GameObject>("m_visual");
// Each light moved, with the local position it goes back to.
private readonly Dictionary<Light, Vector3> moved = new Dictionary<Light, Vector3>();
private readonly List<Light> dead = new List<Light>();
private float nextScan;
private Transform head;
private Vector3 anchorOffset = FallbackOffset; // player-local, used when there is no head
public static void Tick(Player player)
{
GameObject visual = VisualRef(player);
if (visual == null) return;
bool hidden = PlayerVisualHider.IsHidden(visual.transform) || visual.transform.localScale.y < HiddenScale;
FormLightFollow follow = visual.GetComponent<FormLightFollow>();
if (!hidden)
{
if (follow != null && follow.moved.Count > 0) follow.Restore();
return;
}
if (follow == null) follow = visual.AddComponent<FormLightFollow>();
follow.Follow(player);
}
private void Follow(Player player)
{
if (Time.time >= nextScan)
{
nextScan = Time.time + RescanInterval;
Scan(player);
}
Transform body = player.transform;
Vector3 anchor = head != null
? head.position + body.forward * AheadOfHead
: body.TransformPoint(anchorOffset);
foreach (Light light in moved.Keys)
{
if (light != null) light.transform.position = anchor;
}
}
private void Scan(Player player)
{
dead.Clear();
foreach (Light light in moved.Keys)
{
if (light == null) dead.Add(light);
}
foreach (Light light in dead) moved.Remove(light);
foreach (Light light in GetComponentsInChildren<Light>(true))
{
if (!moved.ContainsKey(light)) moved.Add(light, light.transform.localPosition);
}
if (moved.Count == 0) return;
if (head == null || !head.gameObject.activeInHierarchy) FindForm(player);
}
/// <summary>
/// The form's model is a child of the player beside the Visual (every form builds it that
/// way). Its head bone, if it has one; otherwise the top front of its renderers.
/// </summary>
private void FindForm(Player player)
{
head = null;
anchorOffset = FallbackOffset;
Transform body = player.transform;
foreach (Transform child in body)
{
if (child == transform || !child.gameObject.activeInHierarchy) continue;
if (child.GetComponentInChildren<Animator>() == null) continue;
head = FindHead(child);
if (head != null) return;
Bounds bounds = default;
bool any = false;
foreach (Renderer r in child.GetComponentsInChildren<Renderer>())
{
if (!(r is SkinnedMeshRenderer) && !(r is MeshRenderer)) continue;
if (any) bounds.Encapsulate(r.bounds); else { bounds = r.bounds; any = true; }
}
if (!any) continue;
Vector3 local = body.InverseTransformPoint(bounds.center);
Vector3 size = body.InverseTransformVector(bounds.extents);
anchorOffset = new Vector3(local.x, local.y + Mathf.Abs(size.y) * 0.6f, local.z + Mathf.Abs(size.z) * 0.6f);
return;
}
}
private static Transform FindHead(Transform root)
{
foreach (Transform t in root.GetComponentsInChildren<Transform>())
{
if (string.Equals(t.name, "head", System.StringComparison.OrdinalIgnoreCase)) return t;
}
return null;
}
private void Restore()
{
foreach (KeyValuePair<Light, Vector3> entry in moved)
{
if (entry.Key != null) entry.Key.transform.localPosition = entry.Value;
}
moved.Clear();
head = null;
}
/// <summary>LateUpdate, so the form's Animator has already posed the head this frame.</summary>
[HarmonyPatch(typeof(Player), "LateUpdate")]
public static class Player_LateUpdate_FormLightFollow_Patch
{
public static void Postfix(Player __instance)
{
Tick(__instance);
}
}
}
}

View file

@ -0,0 +1,95 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// A staggered player in a form plays the form's own stagger.
///
/// Vanilla staggers a character with SetTrigger("stagger") on its own Animator (Character.RPC_Stagger),
/// and that Animator belongs to the hidden human. The form's Animator never heard of it, so the
/// True Form troll stood idle while the player could not move. A tester saw it.
///
/// Every creature worn as a form has the vanilla stagger ready to play (read offline with
/// scripts/dump_controller.py, bundle c4210710): a "stagger" trigger and an AnyState -> Stagger
/// transition in troll_animator, fenring_animator, fenring_cultist_animator, wolf_animator,
/// ulv_animator, SeekerBrute_animator (the Sverm Ravager) and bat_animator (the Aswid bat).
/// gd_king_animator (the Muspell) and hatchling_animator (the Skadi drake) have none, and are
/// left alone by the parameter check.
///
/// The cue is Character.IsStaggering(), which reads the player's Animator state. The player's
/// triggers are replicated, so this holds for onlookers' copies of the form too, with nothing
/// published of its own. Fired once, as the stagger starts.
///
/// A stagger also cancels the local form's attack, as it cancels a weapon's in vanilla. The
/// form's swing waits for its clip's hit event and lands on a timeout if none comes, so a
/// stagger that cut the clip short still dealt the blow 1.5 s later. MarkAttack is called as an
/// attack starts, and AttackInterrupted tells the hit whether a stagger began since.
/// </summary>
internal static class FormStagger
{
private const string Trigger = "stagger";
private static readonly AccessTools.FieldRef<Character, Animator> AnimatorRef =
AccessTools.FieldRefAccess<Character, Animator>("m_animator");
private static readonly HashSet<int> staggering = new HashSet<int>();
private static readonly List<Animator> animators = new List<Animator>();
// Staggers of the local player so far, and the count when the current attack started.
private static int localStaggers;
private static int attackMark;
public static void MarkAttack() => attackMark = localStaggers;
/// <summary>True if the local player has been staggered since the last MarkAttack.</summary>
public static bool AttackInterrupted => localStaggers != attackMark;
public static void Tick(Player player)
{
int id = player.GetInstanceID();
if (!player.IsStaggering())
{
staggering.Remove(id);
return;
}
if (!staggering.Add(id)) return;
if (player == Player.m_localPlayer) localStaggers++;
Animator own = AnimatorRef(player);
RuntimeAnimatorController ownController = own != null ? own.runtimeAnimatorController : null;
player.GetComponentsInChildren(false, animators);
foreach (Animator anim in animators)
{
// The human's own Animator staggers already, and so does anything driven by a copy of
// its controller (a VRM model).
if (anim == own || anim.runtimeAnimatorController == null) continue;
if (anim.runtimeAnimatorController == ownController) continue;
if (!anim.isActiveAndEnabled || !HasTrigger(anim)) continue;
anim.SetTrigger(Trigger);
}
animators.Clear();
}
private static bool HasTrigger(Animator anim)
{
foreach (AnimatorControllerParameter p in anim.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger && p.name == Trigger) return true;
}
return false;
}
[HarmonyPatch(typeof(Player), "LateUpdate")]
public static class Player_LateUpdate_FormStagger_Patch
{
public static void Postfix(Player __instance)
{
FormStagger.Tick(__instance);
}
}
}
}

View file

@ -381,7 +381,10 @@ namespace RacesOfValheim
piece.m_craftingStation = null; piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Terrain only, as a living thing should be - but through m_groundOnly alone, which shows
// the ghost red off the terrain. m_groundPiece switched the ghost off outright there
// (Player.UpdatePlacementGhost), and players saw nothing at all.
piece.m_groundPiece = false;
piece.m_groundOnly = true; piece.m_groundOnly = true;
piece.m_cultivatedGroundOnly = false; // a bush of rocks does not want tilled soil piece.m_cultivatedGroundOnly = false; // a bush of rocks does not want tilled soil
piece.m_icon = BorrowIcon(berry.YieldPrefab); piece.m_icon = BorrowIcon(berry.YieldPrefab);

View file

@ -11,9 +11,13 @@ namespace RacesOfValheim
{ {
public static void Postfix(Player __instance) public static void Postfix(Player __instance)
{ {
if (__instance == null || __instance != Player.m_localPlayer) return; if (__instance == null) return;
if (FurlingRace.IsFurling()) // Every player, not only the local one, with the race read off the ZDO. Scale is not
// replicated: each client sizes the characters it draws. When this sized only the
// local player from its own m_customData, a Furling was small on their own screen
// and full height on everybody else's.
if (DvergarVisuals.GetPlayerRace(__instance) == "Furling")
{ {
// Scale player visuals down by 19% (0.9 * 0.9 = 0.81) // Scale player visuals down by 19% (0.9 * 0.9 = 0.81)
GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue<GameObject>(); GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue<GameObject>();
@ -402,9 +406,9 @@ namespace RacesOfValheim
{ {
if (BossProgressionManager.GetCurrentProgressionState() >= 3) // The Wickerman (Elder) if (BossProgressionManager.GetCurrentProgressionState() >= 3) // The Wickerman (Elder)
{ {
// Check if it's an arrow (either by skill or by checking if a bow/ammo was used) // Check if it's an arrow or a bolt (either by skill or by checking if a bow/crossbow/ammo was used)
if ((hitData != null && hitData.m_skill == Skills.SkillType.Bows) || if ((hitData != null && (hitData.m_skill == Skills.SkillType.Bows || hitData.m_skill == Skills.SkillType.Crossbows)) ||
(ammo != null && ammo.m_shared.m_skillType == Skills.SkillType.Bows)) (ammo != null && (ammo.m_shared.m_skillType == Skills.SkillType.Bows || ammo.m_shared.m_skillType == Skills.SkillType.Crossbows)))
{ {
// If the arrow doesn't already have significant fire damage, add it // If the arrow doesn't already have significant fire damage, add it
if (hitData != null && hitData.m_damage.m_fire < 22f) if (hitData != null && hitData.m_damage.m_fire < 22f)

View file

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The hunter's senses the Aswid and the Fenrir share: every untamed creature within a radius
/// gets a green light, seen only by the local player. The Aswid has it as a passive from Moder,
/// the Fenrir in any of its four forms.
///
/// The lights are local GameObjects parented to the creature, so nothing goes on the network.
/// The light's range and strength are the Aswid's settings; each race brings its own radius.
/// </summary>
public static class HunterSenses
{
private static readonly Dictionary<Character, GameObject> lights = new Dictionary<Character, GameObject>();
private static float timer;
/// <summary>
/// Called every frame while the senses are on. Sweeps once per refresh interval;
/// onSensed runs for each creature in range (the Aswid marks them with its status effect).
/// </summary>
public static void Tick(float radius, Action<Character> onSensed = null)
{
Player player = Player.m_localPlayer;
if (player == null) return;
timer -= Time.deltaTime;
if (timer > 0f) return;
timer = AswidConfig.SensesRefreshInterval.Value;
Vector3 myPos = player.transform.position;
HashSet<Character> inRange = new HashSet<Character>();
foreach (Character c in Character.GetAllCharacters())
{
if (c == null || c == player || c.IsDead() || c.IsTamed()) continue;
if (Vector3.Distance(c.transform.position, myPos) > radius) continue;
try
{
inRange.Add(c);
onSensed?.Invoke(c);
if (!lights.ContainsKey(c))
{
GameObject lightObj = new GameObject("AswidSensesLight");
lightObj.transform.SetParent(c.transform);
lightObj.transform.position = c.GetCenterPoint();
Light pLight = lightObj.AddComponent<Light>();
pLight.type = LightType.Point;
pLight.color = Color.green;
pLight.range = AswidConfig.SensesLightRange.Value;
pLight.intensity = AswidConfig.SensesLightIntensity.Value;
pLight.shadows = LightShadows.None;
lights[c] = lightObj;
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Senses] Error processing mob {c.name}: {ex}");
}
}
List<Character> keysToRemove = new List<Character>();
foreach (var kvp in lights)
{
if (kvp.Key == null || kvp.Key.IsDead() || !inRange.Contains(kvp.Key))
{
if (kvp.Value != null) UnityEngine.Object.Destroy(kvp.Value);
keysToRemove.Add(kvp.Key);
}
}
foreach (var k in keysToRemove) lights.Remove(k);
}
/// <summary>Puts every light out, for when the senses end (a form reverts, a tier is lost).</summary>
public static void Clear()
{
if (lights.Count == 0) return;
foreach (var kvp in lights)
{
if (kvp.Value != null) UnityEngine.Object.Destroy(kvp.Value);
}
lights.Clear();
timer = 0f;
}
}
}

Some files were not shown because too many files have changed in this diff Show more