commit 635e28a30d05a08f74fc3d921bac21c3a99e7cc9
parent 5aa0792add99399bd8d10525fe8314b28fbba5b9
Author: anon <anon@example.com>
Date: Sun, 25 Oct 2026 14:33:29 +0000
Support Ice Flechette damage and timed initiative effects
The NT starter crystal now learns a complete Ice Flechette cast, including
cold damage and four signed initiative debuffs. Persist NPC active effects
with the damage outcome, refresh without stacking, replay once to observers,
checkpoint remaining time, and remove effects on expiry or death.
Verify atomic failures, ignored writes, authored requirements, NPC weapon
timing, cold recovery and clean respawn with Go and race tests. Two hardware
WASM clients confirm delivery, refresh, removal and real server restart.
Diffstat:
16 files changed, 717 insertions(+), 64 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -716,9 +716,13 @@ introduction and starting-item gameplay remain open below.
requirements, atomic outcomes, lethal/nonlethal results and cold restore.
Preserve the existing PvE/reconstruction policy limits. See
[catalog direct damage](docs/nano-direct-damage.md).
-- [ ] Complete the NT starter Ice Flechette 28612's secondary cast 144632 and
- its initiative debuff lifecycle before admitting it. Do not apply its Hit
- alone. Recover ordinary acquisition for Heat Miser 26310 and Nano Bolt 27114;
+- [x] Complete the NT starter Ice Flechette 28612's Hit and secondary cast
+ 144632 together. Verify all four signed initiative changes, refresh without
+ stacking, hostile NCU, NPC weapon timing, exact expiry, death, clean respawn,
+ atomic failures, periodic persistence, observer replay and cold restore.
+ Two WASM clients confirm the full lifecycle. See
+ [initiative debuffs](docs/nano-initiative-debuffs.md).
+- [ ] Recover ordinary acquisition for Heat Miser 26310 and Nano Bolt 27114;
the scanned original item catalog has no ordinary single-program uploader.
- [x] Apply one temporary stat buff. Check: the native effect appears, the stat
changes once, and expiration removes exactly that contribution.
@@ -781,9 +785,9 @@ introduction and starting-item gameplay remain open below.
Statement and COMMIT failures preserve the living state and item ownership.
- [ ] Verify remaining temporary nano lifecycle policies. Check:
historical offline timing, death-persistent exceptions, duration scaling,
- cross-side/team eligibility, dungeon line of sight and completion target
- gates. Exercise interrupted zoning, additional strain rules and historical
- NCU replacement admission policy. Current replacement uses the final
+ secondary landing/resistance, cross-side/team eligibility, dungeon line of
+ sight and completion target gates. Exercise interrupted zoning, additional
+ strain rules and historical NCU replacement admission policy. Current replacement uses the final
allocation after removal.
- [ ] Apply one damage-over-time effect. Check: the expected number of ticks
occurs and stopping/removing the effect prevents further ticks.
diff --git a/docs/nano-buffs.md b/docs/nano-buffs.md
@@ -187,6 +187,10 @@ player checkpoint; timer-only saves do not rewrite unchanged character data.
The saved remaining duration resumes on login. Ordinary observer updates do
not add duplicate stat snapshots or modifier streams.
+The same character-owned persistence now supports NPC active effects. Ice
+Flechette's hostile initiative child uses NPC checkpoints, observer replay and
+explicit expiry/death removal; see [initiative debuffs](nano-initiative-debuffs.md).
+
## Derived resources
The native stat getters read cached maximum HP 1 and maximum nano 221.
diff --git a/docs/nano-damage.md b/docs/nano-damage.md
@@ -3,7 +3,9 @@
The shared path now also supports 32 additional reviewed pure single-hit
programs and their complete crystal contracts. See
[catalog direct damage](nano-direct-damage.md) for admission, verification and
-the retained original-server policy limits below.
+the retained original-server policy limits below. Ice Flechette additionally
+executes its complete damage-and-child contract; see
+[initiative debuffs](nano-initiative-debuffs.md).
The QL 1 Bureaucrat startup crystal 29625 uploads program 29618, Winter's
Bite. The server supports this exact single-hit program against a visible,
diff --git a/docs/nano-direct-damage.md b/docs/nano-direct-damage.md
@@ -19,8 +19,9 @@ one selected-target immediate health Hit, 33 have the ordinary reviewed
`0x80008000` flag contract. They retain the attack/Nano Resist dictionaries,
zero defaults for those dictionaries, a single unconditional Hit 53002, and
one action-3 requirement expression. The damage types span stats 90 through 97.
-The reader rejects secondary functions, ticks, other targets/resources, unknown
-sections, metadata variants and unrecognized argument forms.
+The single-Hit contracts reject ticks, other targets/resources, unknown
+sections, metadata variants and unrecognized argument forms. The additional
+complete compound contract is described below.
Thirty-one ordinary crystals upload these programs. Heat Miser 26310 and
Nano Bolt 27114 have no ordinary single-program uploader in the scanned item
@@ -46,10 +47,11 @@ are checked independently. Raw cost is distinct from the existing native
float-based debit policy: with modifier 100, these positive integer costs debit
one point less. For example Fire Stream reserves 14 and Corrosive Spray 11.
-Ice Flechette 28612 is deliberately excluded. Its Hit is followed by
-CastNano 53051 of 144632, which applies four initiative debuffs for 6000 cs.
-Implementing only its damage would drop an authored effect. Area programs such
-as Radiation Pulse 28631 use an area-cast function and are also excluded.
+Ice Flechette 28612 additionally supports its full Hit followed by CastNano
+53051 of 144632: four initiative debuffs for 6000 cs. Its child installation,
+refresh, expiry and persistence are covered in
+[initiative debuffs](nano-initiative-debuffs.md). Other secondary contracts and
+area programs such as Radiation Pulse 28631 remain excluded.
The separate flag `0x80000` zeroes native cast/recharge deadlines; it is outside
this ordinary timing contract.
diff --git a/docs/nano-initiative-debuffs.md b/docs/nano-initiative-debuffs.md
@@ -0,0 +1,133 @@
+# Ice Flechette and hostile initiative effects
+
+Ice Flechette 28612 now executes its complete original contract: 13..17 cold
+damage and child nano 144632, which lowers Melee, Ranged, Physical and Nano
+Initiative by 6 for 6000 centiseconds. Startup crystal 28815 uploads the parent
+through the ordinary crystal path. Both upload and casting require visual
+profession 11 and Matter Creation greater than 8. Raw cost is 8; the existing
+native float debit policy reserves 7. Parent attack/recharge are 125/251 cs and
+range is 25 metres.
+
+## Complete contracts
+
+The direct-damage reader accepts one immediate health Hit, optionally followed
+by one unconditional selected-target CastNano whose entire child contract is
+supported. The child reader requires a passive hostile nano, four distinct
+negative initiative Modifies, one tick, no interval or function conditions,
+the complete attack/zero-resistance dictionaries, and no extra sections or
+casting action. Unknown or partial child effects close the parent and crystal
+as well. No program-ID dispatch or damage-only fallback is used.
+
+The original resource census finds two programs containing only negative
+initiative Modifies. Red Tape 30090 also has an area/casting contract and fails
+this passive-child reader. Only child 144632 and its parent 28612 pass. The
+ordinary supported damage family is consequently 33 single-Hit programs plus
+Ice Flechette, with 32 ordinary single-program crystal uploaders in total.
+This does not admit arbitrary CastNano chains, hostile player casting, area
+effects or other debuff families.
+
+Original payload SHA-256 identities:
+
+| Resource | ID | SHA-256 |
+| --- | --- | --- |
+| Crystal | 28815 | `5720cacb5d62ac0ca74435a79749598d59b910be4be0cf14565b32e0d8924d98` |
+| Parent | 28612 | `d3c582425ee42a26d8e997730685160b3bba148aeeb1784b9cfafcb249e0497d` |
+| Child | 144632 | `2468d892714587cda36f453b19b3cdbd501eff2ee06bc05b395b1fcbb0bcfdcc` |
+
+Decoded records and the census script/results are retained under
+`local/ice-flechette-research/`.
+
+## Native delivery and lifecycle
+
+Parent action 18/107 does not apply the child. Original completion 100654a0
+skips local execution for a SimpleChar target; the admitted CastNano executor
+100be8e0 calls empty stub 1000c340. A successful survivor receives one target
+action 177 `(53019,144632,caster,6000)` alongside the parent's completion and
+NanoAttack. The signed Modify consumer adds each -6 once. No second modifier
+packet or active-effect snapshot is sent for that installation.
+
+The omitted child strain defaults to its program identity, 144632, through
+NanoItem initialization 10098540/10098600. Native 10066010 replaces an existing
+equal-strain/equal-NCU record before applying the incoming one, so refreshing
+leaves one -6 contribution and renews its deadline. Hostile flag 0x8000 excludes
+the program from used NCU and blocks local cancellation. An authoritative
+target action 65 removes its membership and reverses the four modifiers.
+The inspected countdown and death paths do not perform that removal themselves.
+
+The retained native ledger contains 47 complete original REA records, 16 checked
+citations and 15 maintained-source extracts, bound to original KKR SHA-256
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+Principal records are
+`ev_4454e12e69f0ac994b39f2628681f4ea8b1c62dfb507addeb5761df50b4ce819`
+(parent completion),
+`ev_27c953512839b1cff0ac854ff041eb3e0813c2df061a8858060432f10da08405`
+(signed modifier arithmetic), and
+`ev_a760dfc116df1dd38b0619334130d916b7706ee29c64a535cdef16ed448295a6`
+(active add/remove). Full provenance and bounded findings are in
+`local/ice-flechette-research/native/README.md`.
+
+## Server state and reconstruction policy
+
+Active nanos belong to characters in SQLite, including NPCs. Damage, the child
+installation or refresh, contributions, caster reservation release and recharge
+commit together before any completion, child or damage result is sent. Saved
+effect contents are checked inside the transaction, including silently ignored
+inserts, updates and deletes. Failed outcomes publish cancellation/refund only;
+failed expiry retains the effect and retries.
+
+Timers advance in memory. NPC remaining duration follows its existing periodic
+world checkpoint without rewriting an otherwise unchanged actor. An orderly
+shutdown saves current remaining time; a crash can lose time since the last
+checkpoint. Loaded NPC timers start immediately, while player timers retain
+their existing pause-until-login policy. A late observer gets the NPC's raw
+combat foundations followed by one active-effect replay with remaining time.
+
+NPC weapon delays use the profile's initiative plus the relevant nano modifier;
+the native combat snapshot keeps the raw profile initiative so replay cannot
+apply -6 twice. At initiative zero and AggDef 75, Leet Bite's 1750/1750 ms cycle
+becomes 1760/1770 ms. Removal restores subsequent cycles. NPCs without recovered
+combat profiles retain their existing provisional weapon timing.
+
+Expiry explicitly sends 65. Lethal damage removes active effects atomically and
+sends 65 after the death reset; a lethal Ice hit installs no new child. Respawns
+have a new identity with no inherited effects. Clearing on death, pausing while
+the server is stopped, unconditional secondary landing and exact packet ordering
+are reconstruction choices. The original server's death-persistence, secondary
+resistance, duration-modifier and offline-time policies remain unresolved.
+The wider resistance/AC/PvP limits in [direct damage](nano-direct-damage.md)
+remain open.
+
+## Verification
+
+Go tests cover complete catalog admission, malformed child rejection, original
+crystal consumption, damage and debit, refresh without stacking, exact expiry,
+cold restore, observer replay, NPC attack deadlines and raw initiative,
+checkpoint cadence, lethal removal and clean respawn. Statement failures,
+ignored writes and failed COMMIT cannot expose partial damage, modifiers or
+cost; removal and casts can retry. Skill equality/above-threshold and wrong
+profession cases test both upload and casting independently. Three
+race-detector repetitions passed for the lifecycle and requirements cases.
+The full Go suite passed 5072 tests and subtests (server 749.964 seconds;
+game data 7.634 seconds). The additional requirements boundaries and strengthened
+respawn assertion each passed three race repetitions; vet passed.
+
+Two owned GPU WASM clients uploaded the startup crystal and observed four
+Ice casts through native mouse controls. Matching cold damage results were
+14, 17, 14 and 13, each with a 7-point admission debit. At the first 107 receipt,
+SQLite already contained the child with 60 seconds, committed HP, zero reserved
+nano and recharge. Both native modifier maps showed exactly -6 for all four
+initiatives and one active child; refresh and an observer reload retained one
+contribution and zero used NCU. Explicit expiry restored all four to zero in
+both clients. A lethal Radioactive Cloud follow-up cleared the child in the
+same outcome; owner modifiers returned to zero and both observers received 65.
+
+After closing both clients, a true server restart retained the second NPC's
+51.829 seconds of saved effect time. A fresh WASM process received one replay
+with 3756 cs remaining, showed all four -6 modifiers once, and received removal
+37.743 seconds later. Its modifiers returned to zero. No page or adapter errors
+occurred. The read-only probes and transport/database checks are retained in
+`local/ice-flechette-smoke/verification.json`.
+
+Cleanup removed only owned fixtures. Hashes of every unrelated table row were
+unchanged, foreign keys and SQLite integrity passed, and unrelated players
+remained. The shared preview remains a single process on the default ports.
diff --git a/server/combat.go b/server/combat.go
@@ -88,7 +88,12 @@ func weaponDelays(weapon *gamedata.Item, initiative, aggDef int32) (time.Duratio
func (character *character) attackDelays() (time.Duration, time.Duration) {
if character.npc {
if character.combatProfile != nil {
- return weaponDelays(character.attackWeapon(), character.combatProfile.Initiative, character.combatProfile.AggDef)
+ weapon := character.attackWeapon()
+ initiative := uint32(119)
+ if weapon != nil && itemStat(weapon, 440) != 0 {
+ initiative = itemStat(weapon, 440)
+ }
+ return weaponDelays(weapon, character.combatProfile.Initiative+character.nanoBonus(initiative), character.combatProfile.AggDef)
}
return time.Second, time.Second
}
@@ -420,13 +425,15 @@ func prepareDamage(attacker, target *character, damage uint32, now time.Time) ch
// Work on detached mutable state until the outcome's transaction succeeds.
candidate := *target
candidate.health -= damage
+ if candidate.health == 0 {
+ candidate.activeNanos = nil
+ }
if candidate.health == 0 && !candidate.npc {
// Classic insurance cannot remove a level; the shipped scanner protects levels below 20.
if candidate.level >= 20 {
lower, _ := candidate.experienceBounds()
candidate.experience = max(lower, candidate.insuredExperience) - lower
}
- candidate.activeNanos = nil
candidate.nano = min(candidate.nano+candidate.nanoReserved, candidate.maximumNano())
candidate.nanoReserved = 0
candidate.collectReclaim(now)
@@ -492,13 +499,15 @@ func (server *server) finishDamageEffects_locked(attacker, target *character, pr
updates[owner] = append(updates[owner], n3Packet(0x2b333d6e, 50000, target.id, body))
}
}
- if !target.npc && len(previous.activeNanos) != 0 {
+ if len(previous.activeNanos) != 0 {
// StopFight drains queued weapon hits before modifiers and maxima change.
for _, effect := range previous.activeNanos {
server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{65, 0, 0, effect.caster, effect.program}))
}
- previous.position = target.position
- server.finishResourceChange_locked(updates, target, previous, now)
+ if !target.npc {
+ previous.position = target.position
+ server.finishResourceChange_locked(updates, target, previous, now)
+ }
}
monster := gamedata.MonsterTemplates[target.monsterData]
if target.npc && monster != nil && len(monster.DeathAnimations) != 0 {
diff --git a/server/initiative_debuff_test.go b/server/initiative_debuff_test.go
@@ -0,0 +1,371 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "slices"
+ "testing"
+ "time"
+)
+
+func newIceFlechetteWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ world, conn := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: 28815, Profession: 11})
+ if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(world.characters[1].inventory.LearnedNanos, []uint32{28612}) || len(world.characters[1].inventory.Items) != 0 {
+ t.Fatal("starter crystal did not upload exactly its complete program")
+ }
+ conn.packets = nil
+ return world, conn
+}
+
+func castIceFlechette(t *testing.T, world *server) time.Time {
+ t.Helper()
+ client := world.clients[1]
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 28612})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if client.nanoCast == nil {
+ t.Fatal("qualified Ice Flechette was rejected")
+ }
+ at := client.nanoCast.readyAt.Add(time.Nanosecond)
+ world.advanceNanos(at)
+ return at
+}
+
+func TestInitiativeDebuffCatalogAdmitsOnlyTheCompletePassiveChild(t *testing.T) {
+ var children, parents []uint32
+
+ for program := range gamedata.NanoTemplates {
+ if initiativeDebuffNano(program) {
+ children = append(children, program)
+ }
+ if directDamageNano(program) != nil && damageNanoSecondary(program) != 0 {
+ parents = append(parents, program)
+ }
+ }
+
+ if !slices.Equal(children, []uint32{144632}) || !slices.Equal(parents, []uint32{28612}) || nanoCrystalProgram(28815) != 28612 ||
+ statBuffNano(144632) || directDamageNano(144632) != nil || nanoStat(144632, 75) != 144632 || nanoStat(144632, 8) != 6000 || nanoStat(144632, 54) != 1 {
+ t.Fatal("compound admission or passive child defaults changed", children, parents)
+ }
+ for _, stat := range []uint32{118, 119, 120, 149} {
+ if nanoProgramBonus(144632, stat) != -6 {
+ t.Fatal("original signed initiative modifier changed", stat)
+ }
+ }
+}
+
+func TestIceFlechetteUploadAndCastEnforceItsAuthoredRequirements(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ profession uint16
+ skill uint16
+ accepted bool
+ }{
+ {"skill equality", 11, 8, false},
+ {"skill above", 11, 9, true},
+ {"other profession", 8, 9, false},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ world, _ := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: 28815, Profession: 11})
+ player, client := world.characters[1], world.clients[1]
+ player.profession, player.stats.NanoAiding.MatterCreation = scenario.profession, scenario.skill
+
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ learned := slices.Equal(player.inventory.LearnedNanos, []uint32{28612})
+ // Possession of the learned entry cannot bypass the cast's own requirements.
+ player.inventory.LearnedNanos = []uint32{28612}
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 28612})[20:]); err != nil {
+ t.Fatal(err)
+ }
+
+ if learned != scenario.accepted || (client.nanoCast != nil) != scenario.accepted ||
+ scenario.accepted && (len(player.inventory.Items) != 0 || player.nano != 49993 || player.nanoReserved != 7) ||
+ !scenario.accepted && (len(player.inventory.Items) != 1 || player.nano != 50000 || player.nanoReserved != 0) ||
+ world.characters[1000000].health != 100 || len(world.characters[1000000].activeNanos) != 0 {
+ t.Fatal("upload or casting ignored Ice Flechette's authored requirements")
+ }
+ })
+ }
+}
+
+func TestIceFlechetteDamageRefreshExpiryAndColdRestore(t *testing.T) {
+ world, conn := newIceFlechetteWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ target.nano = 10
+
+ at := castIceFlechette(t, world)
+ firstHealth := target.health
+ cold := newTestInventoryServer(t).characters[1000000]
+ firstDeadline := target.activeNanos[0].expiresAt
+ player.nanoRechargeUntil = time.Time{}
+ refreshed := castIceFlechette(t, world)
+ deadline := target.activeNanos[0].expiresAt
+ world.advanceNanos(deadline.Add(-time.Nanosecond))
+ if len(target.activeNanos) != 1 || target.nanoBonus(119) != -6 {
+ t.Fatal("effect expired before its deadline or stacked")
+ }
+ before := len(conn.packets)
+ world.advanceNanos(deadline)
+ world.advanceNanos(deadline.Add(time.Second))
+ restored := newTestInventoryServer(t).characters[1000000]
+
+ if at.IsZero() || firstHealth < 83 || firstHealth > 87 || firstHealth-target.health < 13 || firstHealth-target.health > 17 ||
+ player.nano != 49986 || player.nanoReserved != 0 || len(cold.activeNanos) != 1 || cold.activeNanos[0].remaining != time.Minute ||
+ cold.activeNanos[0].expiresAt.IsZero() || cold.nanoBonus(149) != -6 || cold.usedNCU() != 0 ||
+ !deadline.Equal(refreshed.Add(time.Minute)) || !deadline.After(firstDeadline) || len(target.activeNanos) != 0 || len(restored.activeNanos) != 0 ||
+ target.nano != 10 || restored.nano != 10 || target.nanoBonus(119) != 0 || len(conn.packets) != before+1 ||
+ binary.BigEndian.Uint32(conn.packets[before][29:33]) != 65 || binary.BigEndian.Uint32(conn.packets[before][45:49]) != 144632 {
+ t.Fatal("damage, refresh, hostile NCU, explicit expiry or persistence changed")
+ }
+}
+
+func TestIceFlechetteSlowsTheNPCWeaponClockAndRestoresIt(t *testing.T) {
+ world, _ := newIceFlechetteWorld(t)
+ player, target := world.characters[1], world.characters[1000000]
+ healthBefore := player.health
+
+ at := castIceFlechette(t, world)
+ attack, recharge := target.attackDelays()
+ world.advanceCombat(at.Add(1760*time.Millisecond - time.Nanosecond))
+ if player.health != healthBefore {
+ t.Fatal("NPC swing ignored the debuffed attack delay")
+ }
+ world.advanceCombat(at.Add(1760 * time.Millisecond))
+ health := player.health
+ world.advanceNanos(at.Add(time.Minute))
+ restoredAttack, restoredRecharge := target.attackDelays()
+
+ if attack != 1760*time.Millisecond || recharge != 1770*time.Millisecond || health >= healthBefore ||
+ !target.rechargeUntil.Equal(at.Add(3530*time.Millisecond)) || !target.nextAttack.Equal(at.Add(5290*time.Millisecond)) ||
+ restoredAttack != 1750*time.Millisecond || restoredRecharge != 1750*time.Millisecond || target.combatProfile.Initiative != 0 ||
+ binary.BigEndian.Uint32(targetPacket(npcCombatPacket(target))[49:53]) != 0 {
+ t.Fatal("NPC effective initiative, weapon deadline or raw snapshot initiative changed", attack, recharge, target.rechargeUntil.Sub(at), target.nextAttack.Sub(at))
+ }
+}
+
+func TestIceFlechetteReplaysOnceWhenAnObserverEnters(t *testing.T) {
+ world, _ := newIceFlechetteWorld(t)
+ at := castIceFlechette(t, world)
+ cold := newTestInventoryServer(t)
+ observer := &worldClient{id: 1, npcs: make(map[uint32]bool)}
+
+ packets := cold.updateNPCInterest_locked(observer, cold.characters[1000000].activeNanos[0].expiresAt.Add(-30*time.Second))
+ repeated := cold.updateNPCInterest_locked(observer, at)
+
+ count := 0
+ for _, packet := range packets {
+ packet = targetPacket(packet)
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 177 {
+ count++
+ if binary.BigEndian.Uint32(packet[24:28]) != 1000000 || binary.BigEndian.Uint32(packet[37:41]) != 144632 ||
+ binary.BigEndian.Uint32(packet[41:45]) != 1 || binary.BigEndian.Uint32(packet[45:49]) != 3000 {
+ t.Fatal("replay lost child identity, caster or remaining duration")
+ }
+ }
+ }
+ if count != 1 || len(repeated) != 0 {
+ t.Fatal("observer replay repeated or omitted the passive child", count, len(repeated))
+ }
+}
+
+func TestIceFlechetteTimerUsesNPCCheckpointsWithoutRewritingStillActors(t *testing.T) {
+ world, _ := newIceFlechetteWorld(t)
+ world.clockStarted = time.Now()
+ at := castIceFlechette(t, world)
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ saved := world.savedNPCs[1000000]
+ saved.NextSave = at.Add(20 * time.Second)
+ world.savedNPCs[1000000] = saved
+ world.npcZones = map[uint32]bool{world.characters[1000000].playfield: true}
+ auditCheckpointWrites(t, world)
+ if _, err := world.db.Exec("CREATE TRIGGER audit_nano AFTER UPDATE ON active_nanos BEGIN INSERT INTO checkpoint_writes VALUES ('active_nanos', 'UPDATE'); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ for second := 1; second < 20; second++ {
+ world.advanceNanos(at.Add(time.Duration(second) * time.Second))
+ if err := world.checkpointWorld(at.Add(time.Duration(second) * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if writes := checkpointWrites(t, world); len(writes) != 0 {
+ t.Fatal("routine effect ticks wrote state", writes)
+ }
+ if err := world.checkpointWorld(at.Add(20 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+
+ if cold.characters[1000000].activeNanos[0].remaining != 40*time.Second || cold.characters[1000000].activeNanos[0].expiresAt.IsZero() ||
+ checkpointWrites(t, world)["active_nanos/UPDATE"] != 1 || checkpointWrites(t, world)["characters/UPDATE"] != 0 {
+ t.Fatal("NPC timer checkpoint or actor write cadence changed", checkpointWrites(t, world))
+ }
+}
+
+func TestIceFlechetteFailuresCannotPublishPartialDamageOrModifiers(t *testing.T) {
+ for _, failure := range []struct{ name, operation, statement string }{
+ {"add", "add", "CREATE TRIGGER fail_ice BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(FAIL, 'add'); END"},
+ {"ignored add", "add", "CREATE TRIGGER fail_ice BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(IGNORE); END"},
+ {"refresh", "refresh", "CREATE TRIGGER fail_ice BEFORE UPDATE ON active_nanos BEGIN SELECT RAISE(FAIL, 'refresh'); END"},
+ {"ignored refresh", "refresh", "CREATE TRIGGER fail_ice BEFORE UPDATE ON active_nanos BEGIN SELECT RAISE(IGNORE); END"},
+ {"expiry", "expiry", "CREATE TRIGGER fail_ice BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(FAIL, 'expiry'); END"},
+ {"ignored expiry", "expiry", "CREATE TRIGGER fail_ice BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(IGNORE); END"},
+ {"death", "death", "CREATE TRIGGER fail_ice BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(FAIL, 'death'); END"},
+ {"ignored death", "death", "CREATE TRIGGER fail_ice BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(IGNORE); END"},
+ {"commit", "add", "CREATE TABLE pending_ice (id INTEGER REFERENCES characters(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_ice AFTER INSERT ON active_nanos BEGIN INSERT INTO pending_ice VALUES (999999); END"},
+ } {
+ t.Run(failure.name, func(t *testing.T) {
+ world, conn := newIceFlechetteWorld(t)
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ at := time.Now()
+ if failure.operation != "add" {
+ at = castIceFlechette(t, world)
+ target.activeNanos[0].expiresAt = at.Add(50 * time.Second)
+ if err := world.saveActiveNanos_locked(target, at); err != nil {
+ t.Fatal(err)
+ }
+ if failure.operation == "death" {
+ target.health = 1
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ health, nano, effects := target.health, player.nano, len(target.activeNanos)
+ if failure.operation == "expiry" {
+ at = target.activeNanos[0].expiresAt
+ } else {
+ player.nanoRechargeUntil = time.Time{}
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 28612})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ at = client.nanoCast.readyAt.Add(time.Nanosecond)
+ }
+ if _, err := world.db.Exec(failure.statement); err != nil {
+ t.Fatal(err)
+ }
+ conn.packets = nil
+
+ world.advanceNanos(at)
+ cold := newTestInventoryServer(t)
+
+ if target.health != health || player.nano != nano || player.nanoReserved != 0 || len(target.activeNanos) != effects ||
+ cold.characters[1000000].health != health || len(cold.characters[1000000].activeNanos) != effects || cold.characters[1].nano != nano {
+ t.Fatal("failed transaction published a partial damage, modifier, cost or death")
+ }
+ for _, packet := range conn.packets {
+ key := binary.BigEndian.Uint32(packet[16:20])
+ if key != 0x2b333d6e && (key != 0x5e477770 || binary.BigEndian.Uint32(packet[29:33]) != 108) {
+ t.Fatalf("failed outcome published success %x", packet)
+ }
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_ice"); err != nil {
+ t.Fatal(err)
+ }
+ if failure.operation == "expiry" {
+ world.advanceNanos(at.Add(time.Second))
+ if len(target.activeNanos) != 0 {
+ t.Fatal("failed expiry did not retry")
+ }
+ } else {
+ castIceFlechette(t, world)
+ if target.health >= health || player.nano != nano-7 {
+ t.Fatal("cast could not retry exactly once after rollback")
+ }
+ }
+ })
+ }
+}
+
+func TestIceFlechetteDeathRemovesTheChildAndRespawnsWithoutIt(t *testing.T) {
+ world, conn := newIceFlechetteWorld(t)
+ castIceFlechette(t, world)
+ target := world.characters[1000000]
+ target.health = 1
+ world.characters[1].nanoRechargeUntil = time.Time{}
+ conn.packets = nil
+
+ at := castIceFlechette(t, world)
+ cold := newTestInventoryServer(t)
+ world.advanceNPCRespawns(at.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second))
+
+ removed := 0
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 {
+ switch binary.BigEndian.Uint32(packet[29:33]) {
+ case 177:
+ t.Fatal("lethal hit installed a new debuff on the corpse")
+ case 65:
+ removed++
+ }
+ }
+ }
+ if target.health != 0 || len(target.activeNanos) != 0 || len(cold.characters[1000000].activeNanos) != 0 || removed != 1 {
+ t.Fatal("death retained or failed to remove the native modifier")
+ }
+ respawn := world.characters[1000001]
+ if respawn == nil || respawn.health != 100 || len(respawn.activeNanos) != 0 || respawn.nanoBonus(119) != 0 {
+ t.Fatal("respawn did not create a clean new life")
+ }
+}
+
+func TestIceFlechetteRejectsIncompleteSecondaryContracts(t *testing.T) {
+ for _, scenario := range []string{"missing modifier", "duplicate initiative", "other stat", "positive", "periodic", "conditional", "self", "area", "other function", "opaque", "other flags", "unknown section"} {
+ t.Run(scenario, func(t *testing.T) {
+ original := gamedata.NanoTemplates[144632]
+ child := *original
+ child.Stats, child.Sections = slices.Clone(child.Stats), slices.Clone(child.Sections)
+ functions := slices.Clone(*child.Sections[2].Functions)
+ functions[0].Arguments = slices.Clone(functions[0].Arguments)
+ child.Sections[2].Functions = &functions
+ value := int32(0)
+ switch scenario {
+ case "missing modifier":
+ functions = functions[:3]
+ case "duplicate initiative":
+ value = 118
+ functions[0].Arguments[0].Integer = &value
+ case "other stat":
+ value = 156
+ functions[0].Arguments[0].Integer = &value
+ case "positive":
+ value = 6
+ functions[0].Arguments[1].Integer = &value
+ case "periodic":
+ functions[0].TickCount = 2
+ case "conditional":
+ functions[0].Requirements = []gamedata.ItemRequirement{{Stat: 54, Value: 20, Operator: 2}}
+ case "self":
+ functions[0].Target = 2
+ case "area", "other flags":
+ for index, stat := range child.Stats {
+ if scenario == "area" && stat[0] == 405 || scenario == "other flags" && stat[0] == 0 {
+ child.Stats[index][1] = 4
+ }
+ }
+ case "other function":
+ functions[0].ID = 53051
+ case "opaque":
+ functions[0].Arguments[1].Integer = nil
+ case "unknown section":
+ child.Sections = append(child.Sections, gamedata.ItemSection{Type: 99})
+ }
+ gamedata.NanoTemplates[144632] = &child
+ t.Cleanup(func() { gamedata.NanoTemplates[144632] = original })
+
+ accepted, parent, crystal := initiativeDebuffNano(144632), directDamageNano(28612), nanoCrystalProgram(28815)
+
+ if accepted || parent != nil || crystal != 0 {
+ t.Fatal("incomplete secondary allowed a partial Ice Flechette upload or cast", scenario)
+ }
+ })
+ }
+}
diff --git a/server/interest.go b/server/interest.go
@@ -46,6 +46,7 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim
if other.combatProfile != nil {
updates = append(updates, npcCombatPacket(other))
}
+ updates = append(updates, activeNanoPackets(other, now)...)
if other.health == 0 {
updates = append(updates, deathPacket(other))
}
diff --git a/server/nano_buffs.go b/server/nano_buffs.go
@@ -167,7 +167,10 @@ func (player *character) nanoBonus(stat uint32) int32 {
func (player *character) usedNCU() uint32 {
var used uint32
for _, effect := range player.activeNanos {
- used += nanoStat(effect.program, 54)
+ // Native active-list accounting excludes hostile programs.
+ if nanoStat(effect.program, 0)&0x8000 == 0 {
+ used += nanoStat(effect.program, 54)
+ }
}
return used
}
@@ -200,19 +203,47 @@ func writeActiveNanos(tx *sql.Tx, player *character, now time.Time) error {
programs := []any{player.id}
for _, effect := range player.activeNanos {
programs = append(programs, effect.program)
- if _, err := tx.Exec(`INSERT INTO active_nanos (player_id, program_id, caster_id, remaining_ns) VALUES (?, ?, ?, ?)
- ON CONFLICT(player_id, program_id) DO UPDATE SET caster_id=excluded.caster_id, remaining_ns=excluded.remaining_ns
+ if _, err := tx.Exec(`INSERT INTO active_nanos (character_id, program_id, caster_id, remaining_ns) VALUES (?, ?, ?, ?)
+ ON CONFLICT(character_id, program_id) DO UPDATE SET caster_id=excluded.caster_id, remaining_ns=excluded.remaining_ns
WHERE (caster_id, remaining_ns) IS NOT (excluded.caster_id, excluded.remaining_ns)`,
player.id, effect.program, effect.caster, effect.remainingAt(now)); err != nil {
return err
}
}
- remove := "DELETE FROM active_nanos WHERE player_id=?"
+ remove := "DELETE FROM active_nanos WHERE character_id=?"
if len(programs) > 1 {
remove += " AND program_id NOT IN (" + strings.TrimSuffix(strings.Repeat("?,", len(programs)-1), ",") + ")"
}
- _, err := tx.Exec(remove, programs...)
- return err
+ if _, err := tx.Exec(remove, programs...); err != nil {
+ return err
+ }
+
+ // A trigger that ignores a write must not publish a partial cast or removal.
+ rows, err := tx.Query("SELECT program_id, caster_id, remaining_ns FROM active_nanos WHERE character_id=?", player.id)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ count := 0
+ for rows.Next() {
+ var program, caster uint32
+ var remaining time.Duration
+ if err := rows.Scan(&program, &caster, &remaining); err != nil {
+ return err
+ }
+ index := slices.IndexFunc(player.activeNanos, func(effect activeNano) bool { return effect.program == program })
+ if index < 0 || player.activeNanos[index].caster != caster || player.activeNanos[index].remainingAt(now) != remaining {
+ return fmt.Errorf("character %d active nano %d was not saved", player.id, program)
+ }
+ count++
+ }
+ if err := rows.Err(); err != nil {
+ return err
+ }
+ if count != len(player.activeNanos) {
+ return fmt.Errorf("character %d saved %d of %d active nanos", player.id, count, len(player.activeNanos))
+ }
+ return nil
}
func (server *server) loadActiveNanos() error {
@@ -220,19 +251,23 @@ func (server *server) loadActiveNanos() error {
if err != nil {
return err
}
- rows, err := db.Query("SELECT player_id, program_id, caster_id, remaining_ns FROM active_nanos ORDER BY player_id, program_id")
+ rows, err := db.Query("SELECT character_id, program_id, caster_id, remaining_ns FROM active_nanos ORDER BY character_id, program_id")
if err != nil {
return err
}
defer rows.Close()
+ now := time.Now()
for rows.Next() {
var id uint32
var effect activeNano
if err := rows.Scan(&id, &effect.program, &effect.caster, &effect.remaining); err != nil {
return err
}
- if !statBuffNano(effect.program) || effect.remaining < 0 {
- return fmt.Errorf("player %d has an unsupported active nano %d", id, effect.program)
+ if !statBuffNano(effect.program) && !initiativeDebuffNano(effect.program) || effect.remaining < 0 || server.characters[id] == nil {
+ return fmt.Errorf("character %d has an unsupported active nano %d", id, effect.program)
+ }
+ if server.characters[id].npc {
+ effect.expiresAt = now.Add(effect.remaining)
}
server.characters[id].activeNanos = append(server.characters[id].activeNanos, effect)
}
@@ -271,14 +306,18 @@ func (server *server) removeNano_locked(player *character, index int, now time.T
candidate := *player
effect := candidate.activeNanos[index]
candidate.activeNanos = slices.Delete(slices.Clone(candidate.activeNanos), index, index+1)
- candidate.health, candidate.nano = min(candidate.health, candidate.maximumHealth()), min(candidate.nano, candidate.maximumNano())
+ if !candidate.npc {
+ candidate.health, candidate.nano = min(candidate.health, candidate.maximumHealth()), min(candidate.nano, candidate.maximumNano())
+ }
if err := server.saveActiveNanos_locked(&candidate, now); err != nil {
return err
}
previous := *player
*player = candidate
server.queueCombat_locked(updates, player, player, characterActionPacket(player.id, [5]uint32{65, 0, 0, effect.caster, effect.program}))
- server.finishResourceChange_locked(updates, player, previous, now)
+ if !player.npc {
+ server.finishResourceChange_locked(updates, player, previous, now)
+ }
return nil
}
@@ -335,7 +374,7 @@ func (server *server) handleNanoRemoval(client *worldClient, body []byte) error
}
player := server.characters[client.id]
index := slices.IndexFunc(player.activeNanos, func(effect activeNano) bool { return effect.program == binary.BigEndian.Uint32(body[32:36]) })
- if index < 0 {
+ if index < 0 || nanoStat(player.activeNanos[index].program, 0)&0x8000 != 0 {
return nil
}
updates := make(map[*worldClient][][]byte)
@@ -347,11 +386,7 @@ func (server *server) handleNanoRemoval(client *worldClient, body []byte) error
}
func (server *server) advanceNanoBuffs_locked(now time.Time, updates map[*worldClient][][]byte) {
- for id := uint32(1); id <= server.nextCharacter; id++ {
- player := server.characters[id]
- if player == nil {
- continue
- }
+ for _, player := range server.characters {
for index := len(player.activeNanos) - 1; index >= 0; index-- {
if player.activeNanos[index].remainingAt(now) == 0 {
if err := server.removeNano_locked(player, index, now, updates); err != nil {
diff --git a/server/nano_casting.go b/server/nano_casting.go
@@ -220,23 +220,28 @@ func (server *server) advanceNanos(now time.Time) {
}
var damage uint32
hit := directDamageNano(program)
+ effectProgram := program
removedHealthBonus := false
if hit != nil {
minimum, maximum := uint32(-*hit.Arguments[1].Integer), uint32(-*hit.Arguments[2].Integer)
damage = min(minimum+rand.Uint32N(maximum-minimum+1), target.health)
victim = prepareDamage(player, target, damage, now)
- } else {
+ effectProgram = damageNanoSecondary(program)
+ }
+ if effectProgram != 0 && victim.health != 0 {
// A strain has one contribution; a refresh replaces its deadline and caster.
victim.activeNanos = slices.DeleteFunc(slices.Clone(victim.activeNanos), func(effect activeNano) bool {
- if nanoStat(effect.program, 75) != nanoStat(program, 75) {
+ if nanoStat(effect.program, 75) != nanoStat(effectProgram, 75) {
return false
}
removedHealthBonus = removedHealthBonus || nanoProgramBonus(effect.program, 1) != 0
return true
})
- duration := time.Duration(nanoStat(program, 8)) * 10 * time.Millisecond
- victim.activeNanos = append(victim.activeNanos, activeNano{program: program, caster: player.id, remaining: duration, expiresAt: now.Add(duration)})
- victim.health = min(victim.health, victim.maximumHealth())
+ duration := time.Duration(nanoStat(effectProgram, 8)) * 10 * time.Millisecond
+ victim.activeNanos = append(victim.activeNanos, activeNano{program: effectProgram, caster: player.id, remaining: duration, expiresAt: now.Add(duration)})
+ if !victim.npc {
+ victim.health = min(victim.health, victim.maximumHealth())
+ }
}
award, err := server.saveNanoOutcome_locked(&caster, &victim, now)
@@ -248,9 +253,11 @@ func (server *server) advanceNanos(now time.Time) {
previous := *target
*player, *target = caster, victim
client.nanoCast = nil
+ server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, program}))
+ if effectProgram != 0 && target.health != 0 {
+ server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{177, 53019, effectProgram, player.id, nanoStat(effectProgram, 8)}))
+ }
if hit == nil {
- server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, program}))
- server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{177, 53019, program, player.id, nanoStat(program, 8)}))
server.finishResourceChange_locked(updates, target, previous, now)
if removedHealthBonus && target.health == previous.health {
// Native removal can clamp HP before adding the replacement or refresh.
@@ -260,7 +267,6 @@ func (server *server) advanceNanos(now time.Time) {
}
body := binary.BigEndian.AppendUint32(nil, uint32(-int32(damage)))
body = binary.BigEndian.AppendUint32(body, uint32(*hit.Arguments[3].Integer))
- server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, program}))
server.queueCombat_locked(updates, target, target, n3Packet(0x4727213e, 50000, target.id, body))
server.finishDamageEffects_locked(player, target, previous, now, updates)
server.applyExperienceAward_locked(award, now, updates)
diff --git a/server/nano_damage.go b/server/nano_damage.go
@@ -39,9 +39,9 @@ func directDamageNano(program uint32) *gamedata.ItemFunction {
return nil
}
- // Admit the whole OnUse contract; secondary casts, areas and ticks stay closed.
+ // Admit the whole OnUse contract, including a fully supported secondary effect.
effects, requirements := definition.Sections[2], definition.Sections[3]
- if effects.Type != 2 || effects.Subtype != 0 || effects.Functions == nil || len(*effects.Functions) != 1 ||
+ if effects.Type != 2 || effects.Subtype != 0 || effects.Functions == nil || len(*effects.Functions) < 1 || len(*effects.Functions) > 2 ||
requirements.Type != 22 || requirements.Subtype != 36 || requirements.Actions == nil || len(*requirements.Actions) != 1 || (*requirements.Actions)[0].Type != 3 {
return nil
}
@@ -59,5 +59,83 @@ func directDamageNano(program uint32) *gamedata.ItemFunction {
*hit.Arguments[3].Integer < 90 || *hit.Arguments[3].Integer > 97 {
return nil
}
+ if len(*effects.Functions) == 2 {
+ secondary := (*effects.Functions)[1]
+ if secondary.ID != 53051 || secondary.HeaderWords != [2]uint32{0, 4} || secondary.ArgumentHeader != 9 || secondary.Target != 3 ||
+ len(secondary.Requirements) != 0 || secondary.TickCount != 1 || secondary.TickInterval != 0 || len(secondary.Arguments) != 1 ||
+ secondary.Arguments[0].Integer == nil || !initiativeDebuffNano(uint32(*secondary.Arguments[0].Integer)) {
+ return nil
+ }
+ }
return hit
}
+
+func damageNanoSecondary(program uint32) uint32 {
+ // Called only after admission of the complete direct-damage contract.
+ functions := *gamedata.NanoTemplates[program].Sections[2].Functions
+ if len(functions) == 2 {
+ return uint32(*functions[1].Arguments[0].Integer)
+ }
+ return 0
+}
+
+func initiativeDebuffNano(program uint32) bool {
+ definition := gamedata.NanoTemplates[program]
+ if definition == nil || definition.RecordType != 1040005 || definition.HeaderWords[0] != 51051 || definition.Undecoded != nil ||
+ itemStat(definition, 0) != 0x80018000 || itemStat(definition, 30) != 0 || itemStat(definition, 76) != 0 ||
+ itemStat(definition, 405) != 1 || len(definition.Sections) != 3 {
+ return false
+ }
+ for _, stat := range []uint32{8, 54, 75} {
+ if value := nanoStat(program, stat); value == 0 || value >= 0x80000000 {
+ return false
+ }
+ }
+
+ // Passive hostile children have no resistance roll or player casting action.
+ weights, defaults := definition.Sections[0], definition.Sections[1]
+ if weights.Type != 4 || weights.Subtype != 4 || weights.Entries == nil || len(*weights.Entries) != 2 ||
+ defaults.Type != 6 || defaults.Subtype != 27 || defaults.Stats == nil || !slices.Equal(*defaults.Stats, [][2]uint32{{12, 0}, {13, 0}}) {
+ return false
+ }
+ attack, defense := (*weights.Entries)[0], (*weights.Entries)[1]
+ if attack.Type == nil || *attack.Type != 12 || attack.Stats == nil || defense.Type == nil || *defense.Type != 13 || defense.Stats == nil ||
+ !slices.Equal(*defense.Stats, [][2]uint32{{168, 0}}) {
+ return false
+ }
+ var total uint32
+ for _, weight := range *attack.Stats {
+ if weight[0] < 100 || weight[0] > 168 || weight[1] == 0 || weight[1] > 100 {
+ return false
+ }
+ total += weight[1]
+ }
+ section := definition.Sections[2]
+ if total != 100 || section.Type != 2 || section.Subtype != 0 || section.Functions == nil || len(*section.Functions) != 4 {
+ return false
+ }
+
+ // One signed Modify for each initiative; reject partial or repeated effects.
+ var seen uint32
+ for _, function := range *section.Functions {
+ if function.ID != 53045 || function.HeaderWords != [2]uint32{0, 4} || function.ArgumentHeader != 9 || function.Target != 3 ||
+ len(function.Requirements) != 0 || function.TickCount != 1 || function.TickInterval != 0 || len(function.Arguments) != 2 ||
+ function.Arguments[0].Integer == nil || function.Arguments[1].Integer == nil || *function.Arguments[1].Integer >= 0 {
+ return false
+ }
+ var bit uint32
+ switch *function.Arguments[0].Integer {
+ case 118, 119, 120:
+ bit = 1 << (*function.Arguments[0].Integer - 118)
+ case 149:
+ bit = 8
+ default:
+ return false
+ }
+ if seen&bit != 0 {
+ return false
+ }
+ seen |= bit
+ }
+ return seen == 15
+}
diff --git a/server/nano_damage_test.go b/server/nano_damage_test.go
@@ -70,12 +70,12 @@ func TestDirectDamageNanoCatalogMatchesCompleteOriginalContracts(t *testing.T) {
}
for program := range gamedata.NanoTemplates {
- if directDamageNano(program) != nil {
+ if directDamageNano(program) != nil && damageNanoSecondary(program) == 0 {
programs = append(programs, program)
}
}
for crystal := range gamedata.ItemTemplates {
- if directDamageNano(nanoCrystalProgram(crystal)) != nil {
+ if program := nanoCrystalProgram(crystal); directDamageNano(program) != nil && damageNanoSecondary(program) == 0 {
crystals = append(crystals, crystal)
}
}
diff --git a/server/npc_outcome.go b/server/npc_outcome.go
@@ -15,7 +15,10 @@ func writeNPCOutcome_locked(tx *sql.Tx, target *character, now time.Time) (npcSt
state.RespawnAt = now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second)
}
}
- return state, writeNPCState_locked(tx, target, &state)
+ if err := writeNPCState_locked(tx, target, &state); err != nil {
+ return state, err
+ }
+ return state, writeActiveNanos(tx, target, now)
}
func writeNPCState_locked(tx *sql.Tx, target *character, state *npcState) error {
diff --git a/server/player_death.go b/server/player_death.go
@@ -19,7 +19,7 @@ func (server *server) writePlayerDeath_locked(tx *sql.Tx, player *character) err
if changed != 1 {
return fmt.Errorf("player %d death update affected %d rows", player.id, changed)
}
- result, err = tx.Exec("DELETE FROM active_nanos WHERE player_id=?", player.id)
+ result, err = tx.Exec("DELETE FROM active_nanos WHERE character_id=?", player.id)
if err != nil {
return err
}
diff --git a/server/world.sql b/server/world.sql
@@ -152,11 +152,11 @@ CREATE TABLE IF NOT EXISTS learned_nanos (
PRIMARY KEY (player_id, nano_id)
);
CREATE TABLE IF NOT EXISTS active_nanos (
- player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
+ character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
program_id INTEGER NOT NULL,
caster_id INTEGER NOT NULL,
remaining_ns INTEGER NOT NULL CHECK (remaining_ns >= 0),
- PRIMARY KEY (player_id, program_id)
+ PRIMARY KEY (character_id, program_id)
);
CREATE TABLE IF NOT EXISTS npcs (
id INTEGER PRIMARY KEY REFERENCES characters(id) ON DELETE CASCADE CHECK (id >= 1000000),
diff --git a/server/world_store.go b/server/world_store.go
@@ -116,20 +116,25 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui
nextSave = now.Add(20 * time.Second)
}
saved[id] = savedNPC{state, maps.Clone(npc.damageContributors), nextSave}
- if exists && previous.State == state && maps.Equal(previous.Contributors, npc.damageContributors) {
- continue
- }
- if _, err := characterWrite.Exec(append([]any{id}, state.Character.fields()...)...); err != nil {
- return nil, err
- }
- if _, err := npcWrite.Exec(append([]any{id}, state.fields()...)...); err != nil {
- return nil, err
- }
- if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", id); err != nil {
- return nil, err
+ if !exists || previous.State != state || !maps.Equal(previous.Contributors, npc.damageContributors) {
+ if _, err := characterWrite.Exec(append([]any{id}, state.Character.fields()...)...); err != nil {
+ return nil, err
+ }
+ if _, err := npcWrite.Exec(append([]any{id}, state.fields()...)...); err != nil {
+ return nil, err
+ }
+ if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", id); err != nil {
+ return nil, err
+ }
+ for contributor, damage := range npc.damageContributors {
+ if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, team_id, damage) VALUES (?, ?, ?, ?)", id, contributor.player, contributor.team, damage); err != nil {
+ return nil, err
+ }
+ }
}
- for contributor, damage := range npc.damageContributors {
- if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, team_id, damage) VALUES (?, ?, ?, ?)", id, contributor.player, contributor.team, damage); err != nil {
+ // Effect time follows the same periodic checkpoint even when the NPC is still.
+ if len(npc.activeNanos) != 0 {
+ if err := writeActiveNanos(tx, npc, now); err != nil {
return nil, err
}
}