commit bcc82dbb58016faa53f8cb49d7d938ebc59ab839
parent 702448e6bb248a3ac068c798a2b03578606c5240
Author: anon <anon@example.com>
Date: Tue, 27 Oct 2026 01:20:48 +0000
Add reusable tools and QL 1 Blood Plasma crafting
Declare fixed-QL recipes, effective skill gates and input consumption in
game data. Preserve reusable tool ownership in the existing atomic inventory
transaction and add the original QL 1 Bio-Comminutor to basic pharmacy stock.
Cover rejection, full inventory, replay, tool reuse, lost output, persistence
failures, production loot and sales. Verify an earned part through native
purchase, conversion, cancelled sale, cold recovery and sale/reconnect using
controlled tool funds. Keep canonical quality, crafting XP and funding gaps
explicit and promote the observed HP display discrepancy to P0.
Select a level-1 Leet for the level-1 packet golden instead of an arbitrary
mixed-level actor. Full suite: 1384 roots / 14708 results. Targeted race:
115 / 446; gamedata, eleven Python checks and Go vet passed.
Diffstat:
12 files changed, 546 insertions(+), 28 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -52,6 +52,11 @@ and sold it through the training shop. See [starter progression](docs/starter-pr
Omni clothing terminals now also sell the seven period-documented Omni-Med
designs through shared purchase/wear rules. These useful skill upgrades have
been checked with controlled funds; normal loot funding remains unverified.
+QL 1 Monster Parts can now become saleable Blood Plasma using a reusable
+Bio-Comminutor from basic pharmacy stock. Native crafting, cancelled sale,
+cold recovery and accepted sale passed with an earned part and controlled
+tool funds; ordinary funding and higher-QL recipe rules remain open. See
+[Blood Plasma](docs/blood-plasma.md).
Quest and mission checkboxes below
are still open; they have not been implemented by the shop or dialogue work.
@@ -808,13 +813,18 @@ replay/failure tests and WASM checks are recorded in [IP training](docs/ip-train
but retained all three charges. The current resource-kit admission explicitly
excludes health stims, including the complete startup health/nano contract;
this is not resolved by adjusting the UI click or lowering enemy health.
-- [ ] [P1] Reconcile player HP across native observers during incoming combat and
+- [ ] [P0] Reconcile player HP across native observers during incoming combat and
target switches. Check: correlate authoritative HP, weapon queues and recovery
with ordinary and increased Body Development, before/after StopFight, zoning
and reconnect. The two-client taunt smoke agreed at Body Development80 after
a switch, but inflated Body Development5000 fixtures showed larger observer
differences. Separate prediction phase and invalid fixture inputs from a
delivery/recovery bug; do not assume the threat fix resolves healing delivery.
+ The ordinary Plasma Atrox run also left the Stats HUD at 0/84 after its
+ second level-1 Leet kill while both clients' native stat 27 and persisted
+ health agreed at 8. Check displayed health as well as the native stat store;
+ the mismatch survived idle time and zoning. Evidence:
+ `local/plasma/runtime/owner/pair-earned-part-stable.png` and the paired probe.
- [x] Use one nano-restoring item. Check: nano recovery, consumption and its lock
match that item rather than inheriting the health item's behavior.
- [x] Use one sitting treatment kit. Check: it works in the permitted posture
@@ -1734,6 +1744,22 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah
profession requirement still need target-era evidence. Keep this milestone
open until those canonical recipe rules are established. See
[inventory combinations](docs/tradeskills.md).
+- [x] Support reusable tools in data-driven inventory recipes and verify a
+ QL 1 Monster Parts-to-Blood Plasma baseline. Check: the purchased
+ Bio-Comminutor retains its instance/slot, only the earned part is consumed,
+ and the result survives cancelled sale and cold recovery before one accepted
+ sale. Reversed order, insufficient skill, unsupported qualities/lookalikes,
+ full inventory, concurrent replay, lost output, tool reuse and SQL failures
+ preserve ownership. Two hardware WASM clients verified the native flow;
+ controlled tool funds do not close the normal economy milestone. Output QL,
+ skill rounding and absent creation XP remain explicit reconstruction policies.
+ See [Blood Plasma](docs/blood-plasma.md).
+- [ ] [P1] Establish canonical Monster Parts conversion beyond the QL 1
+ baseline: tool/part quality compatibility, output QL bumps and caps, exact
+ Pharmacy rounding and creation XP. Verify endpoint and boundary qualities,
+ repeated use of one tool, failed requirements and persistence without losing
+ either ingredient. Keep unsupported qualities rejected until their rules are
+ supported by target-period evidence. See [Blood Plasma](docs/blood-plasma.md).
- [ ] [P2] Support the NCU Hacker Interface's original manual level upgrades.
Recover FINC/53130 behavior, level/QL selection, upgrade cash costs and
result delivery. Verify use while carried/worn, wrong profession,
diff --git a/docs/blood-plasma.md b/docs/blood-plasma.md
@@ -0,0 +1,120 @@
+# Reusable tools and QL 1 Blood Plasma
+
+The shared inventory-combination handler converts QL 1 Monster Parts 42640
+with QL 1 Basic Bio-Comminutor 154331 into one QL 1 Blood Plasma 154358.
+It preserves the tool's instance, slot and quantity, consumes only the part,
+and commits the result before sending native deletion/delivery messages.
+The ordered recipe, effective Pharmacy requirement and consumed inputs are
+declared in `server/gamedata/item_combinations.yaml`, alongside the NCU recipe.
+There is no Bio-Comminutor branch in the handler.
+
+## Evidence and limits
+
+The original 14.9.1 records define these items as nonstacking type 51005
+objects at QL 1. Their base price values are 420 for the tool, 100 for the
+part and 1240 for plasma. The tool's authored description names plasma
+extraction. Plasma is a crafting component and saleable item; it is not a
+direct healing consumable.
+
+A [January 2002 firsthand exchange](https://archives.jeuxonline.info/fils/58091.html)
+confirms the direction: pick up the tool and Shift-right-click the part.
+The [Anarchy Arcanum pharmacy guide](https://web.archive.org/web/20030910134725id_/http://home.c2i.net:80/ellusion/pharmacy_treatment.html)
+says that the tool is reusable, identifies its Pharmacy and Chemistry Tools
+and Bases booth, and specifies Pharmacy equal to 2.5 times the parts' QL.
+Its footer dates the last update to 27 June 2003; the retained capture is
+10 September 2003, after the target version. The earlier firsthand exchange
+and shipped definitions corroborate the process, but not every numeric rule.
+
+The current fixed-QL baseline requires three effective Pharmacy points: two
+does not satisfy 2.5, and three does. Exact original integer rounding is not
+independently recovered. Output remains QL 1, and crafting grants no XP.
+These are explicit reconstruction policies. The guide mentions quality bumps
+with higher skill but does not provide their formula. Higher input qualities,
+tool-to-parts quality thresholds, output bumps/caps and creation XP remain
+open; unsupported qualities are not silently converted to QL 1.
+
+Pelted Monster Parts 42639 and Monster Parts with Ivory 42643 are distinct
+definitions and do not acquire this recipe by their names or icons. The tool
+is not consumed for an unknown input. No later daily mission, island quest or
+tool-destruction recipe is imported into this contract.
+
+## Acquisition, value and ownership
+
+Original basic pharmacy-tools terminal 155287 exposes the QL 1 tool through
+the existing stock, quote, purchase and delivery rules. The period guide
+establishes the booth family. Selecting this original QL 1 definition for its
+basic terminal is a bounded stock policy, not a recovered complete inventory
+or stock-generation algorithm. Advanced, superior and startup shops do not
+inherit the entry.
+
+At low Computer Literacy the original tool costs 420 credits. The existing
+Omni starter sale contract pays 62 for QL 1 plasma, compared with five for
+the unprocessed part. The basic pharmacy terminal's authored sale modifier
+is four, giving a 49-credit plasma sale at low Computer Literacy. These
+different terminal prices follow the shared sale rules. No authored value or
+terminal modifier was raised to fund purchases. Tool acquisition with ordinary
+earned funds remains separate
+from controlled purchase/crafting checks and the larger starter progression
+acceptance scenario.
+
+Each recipe declares consumption for both input roles. At least one must be
+consumed, so even a full inventory can replace an input without overflowing.
+Only consumed inputs receive native Delete112 acknowledgements. AddTemplate
+then uses the first free slot. Reusable tool identity and placement remain
+unchanged, including when held on the native mouse cursor.
+
+All changes use the existing detached inventory transaction. Missing or
+ignored deletes/inserts, allocation failure and failed COMMIT preserve both
+inputs and publish no result. Replayed requests cannot convert the resulting
+plasma again. A fresh part can use the same tool; the protocol has no nonce
+to distinguish a legitimate new combine after the referenced slots again
+contain eligible inputs. Lost output after commit cannot reverse ownership.
+
+`server/plasma_test.go` covers the exact effective-skill boundary, input order,
+lookalikes, unsupported type/quality/count, full inventory, concurrent replay,
+tool reuse, lost output, eleven persistence failures and successful retries.
+It also follows a production-generated part through pickup, crafting, cold
+loading, cancelled sale and accepted/repeated sale, and purchases the tool
+from its actual basic terminal. These controlled setups do not prove ordinary
+funding or a completed starter economy.
+
+Eleven complete original item/vendor records are independently reparsed and
+compared with maintained data in `local/plasma/catalog/verification.json`.
+That report retains payload bytes, hashes, guide provenance and open rules.
+
+## Native verification
+
+Two headed GPU WASM clients followed a normally created Atrox Enforcer
+through skill purchases, issued equipment, two level-1 Leet kills and recovery
+with its issued laboratory. It earned 200 XP and six credits, and picked up
+production-generated Monster Part 601 into slot 67. No combat stats, enemies,
+items or rewards were provisioned for these steps.
+
+For the isolated crafting check, the control panel then increased the owned
+wallet from six to 1000 credits and placed both owned characters near actual
+basic pharmacy terminal 3225093279 in playfield 1183. These controlled funds
+and locations do not establish ordinary travel, affordable tool acquisition
+or the complete starter economy. The native purchase cost 420 and created
+tool 602 in slot 70. Reversed input order returned failure 2 and preserved
+both inputs. Tool-on-part consumed only 601 and created plasma 603 in slot 67;
+Escape returned the same tool to its slot. Another tool-on-plasma attempt
+returned failure 2 without creating an item or consuming the tool.
+
+The terminal quoted 49 for the plasma. Decline restored it with no cash
+change. Both clients closed, and a cold restart of the sole server retained
+tool 602, plasma 603, all fourteen issued instances, 200 XP and 580 credits.
+After reconnecting, Accept sold only 603 and raised cash to 629. A repeated
+click and an accepted empty basket added nothing; another reconnect retained
+the tool, issued items and cash. Neither run recorded a page error.
+
+The same run exposed a separate HP-display issue: after the second fight the
+Stats HUD showed 0/84 while both native stat stores and persisted health were
+8. Idle time and zoning did not repair the label; cold reconnect did. The
+player-HP milestone is now P0 and remains open. Crafting does not resolve it.
+
+The full server suite passed 1,384 top-level tests / 14,708 results. The
+targeted race run passed 115 / 446; all 18 gamedata tests, eleven Python
+population/parser tests and `go vet ./server/...` passed. Source manifests,
+packet streams, screenshots, cold ownership checks and owned-fixture cleanup
+are retained in `local/plasma/source-verification.json` and
+`local/plasma/runtime-verification.json`.
diff --git a/docs/shops.md b/docs/shops.md
@@ -3,9 +3,9 @@
The server restores the original vending-machine placements and accepts staged
sales from ordinary inventory. An offer remains owned by the player until
Accept commits its removal and the credit award in one SQLite transaction.
-Cancel and removing an offer restore the same item. Tools, Devices and General
-Tools and Bases expose documented fixed entries. Basic medical terminals offer
-a supported QL1 subset with authored charges. Complete historical
+Cancel and removing an offer restore the same item. Tools, Devices, General
+Tools and Bases, and basic Pharmacy Tools expose documented fixed entries.
+Basic medical terminals offer a supported QL1 subset with authored charges. Complete historical
stock membership, random generation and stock rotation remain unresolved.
Map terminals offer the five supported reader upgrades described below.
@@ -85,6 +85,7 @@ Lock Pick, fixed QL 1, type 51005, price stat 74 equal to 230.
| Devices | 9 | Nano Programming Interface 161699 | 51022 | 1 | 900 |
| General Tools and Bases | 3 | Expendable Hologram Camera 156054 | 51005 | 1 | 1300 |
| General Tools and Bases | 3 | ID-extractor 156339 | 51005 | 1 | 9500 |
+| Basic Pharmacy and Chemistry Tools and Bases | 1 | Basic Bio-Comminutor 154331 | 51005 | 1 | 420 |
| Basic medical supplies | 3 | Treatment Laboratory 25812 | 51005 | 1 | 150 |
| Basic medical supplies | 3 | Simple Nano Kit 85366 | 51005 | 1 | 20 |
| Basic medical supplies | 3 | Basic Nano Recharger 25820 | 51005 | 1 | 250 |
@@ -95,6 +96,13 @@ garment records. Purchases, two separate sleeves, wear bonuses and laboratory
eligibility use the shared item rules. See [Omni-Med suit stock](shop-med-suit.md)
for the evidence, exact prices and acceptance boundaries.
+The pharmacy guide updated 27 June 2003 places the reusable Bio-Comminutor
+in Pharmacy and Chemistry Tools and Bases. Basic terminal 155287 now offers
+original QL 1 definition 154331. This is a bounded stock subset; the guide
+does not recover an exact quality distribution or complete inventory. Its
+capture date and the supported conversion of production Monster Parts are
+recorded in [Blood Plasma](blood-plasma.md).
+
The original Personal Lockpick guide, updated 28 August 2002 and
[captured 7 March 2003](https://web.archive.org/web/20030307031410id_/http://home.c2i.net:80/ellusion/gadgets_personallockpick.html),
places the camera and ID-extractor in General Tools and Bases. Applying the
diff --git a/docs/tradeskills.md b/docs/tradeskills.md
@@ -1,11 +1,15 @@
# Original inventory combinations
-The server handles ordinary inventory combinations through the original
-14.9.1 CharacterAction81 request. Its first recipe combines a regular Lock Pick
+The server handles fixed-QL inventory combinations through the original
+14.9.1 CharacterAction81 request. `item_combinations.yaml` declares ordered
+inputs, result, effective skills and consumption for both input roles.
+The NCU recipe combines a regular Lock Pick
95577 with Nano Programming Interface161699, requiring effective Nano Programming
25 and Breaking & Entering60. The current result is QL1 NCU Hacker Interface
158416. Both ingredients commit as consumed in the same transaction that creates
one new durable result. Failed requirements or persistence preserve the inputs.
+The [Blood Plasma recipe](blood-plasma.md) retains its reusable tool and
+consumes only the Monster Part through the same handler and transaction.
## Evidence and reconstruction limits
@@ -60,10 +64,10 @@ Bit0 selects a different preview wording; successful quality-grading variants
also exist. Their historical server selection remains unproven and is not
invented here. Creation delivers the resulting item without a guessed grade.
-After the atomic save, two original Delete112 messages remove the exact input
+After the atomic save, original Delete112 messages remove only consumed input
template pairs. AddTemplate delivers one result into the first free ordinary
-slot. This sequence also works with a full inventory because consuming two
-inputs frees space. IDs are server-owned; the temporary native template proxy
+slot. This sequence also works with a full inventory because consuming an
+input frees space. IDs are server-owned; the temporary native template proxy
receives its persistent instance identity on reconnect.
## Ownership and verification
@@ -73,12 +77,12 @@ ordinary slots, recipe order, input type/QL/count and effective skills. Pending
equipment blocks combinations. An open player/shop basket cancels first and
returns without acting on slots whose contents may have changed on restoration.
-Detached candidates remove both ingredients and allocate one result before one
+Detached candidates remove consumed ingredients and allocate one result before one
existing inventory transaction. SQLite failure publishes neither ownership nor
deletion/result messages; retry creates once. A lost postcommit reply cannot
reverse consumption or allocate the result again. The protocol has no operation
-nonce: an old request cannot be distinguished from a new request after both slots
-are deliberately reused with a fresh matching pair.
+nonce: an old request cannot be distinguished from a new request after the
+referenced slots again contain eligible matching inputs.
Tests cover effective-skill boundaries, wrong order/Personal Lock Pick,
missing/equipped/banked/contained/foreign references, stale sessions, loading,
diff --git a/server/gamedata/item_combinations.yaml b/server/gamedata/item_combinations.yaml
@@ -0,0 +1,16 @@
+# Fixed-QL inventory recipes. Input order and consumption are explicit.
+# Evidence and unresolved quality/creation-XP rules: docs/tradeskills.md.
+95577:
+ 161699:
+ result: 158416
+ skills: [[160, 25], [165, 60]]
+ consume: [true, true]
+
+# Reusable QL1 Bio-Comminutor + QL1 Monster Parts -> QL1 Blood Plasma.
+# Arcanum pharmacy guide: reuse the tool, require Pharmacy >= 2.5 * parts QL.
+# Three whole points satisfy QL1; output remains QL1 without an invented bump.
+154331:
+ 42640:
+ result: 154358
+ skills: [[159, 3]]
+ consume: [false, true]
diff --git a/server/gamedata/load.go b/server/gamedata/load.go
@@ -31,6 +31,7 @@ var (
Playfields map[uint32]Playfield
ShopMachines map[uint32]ShopMachine
ShopStock map[uint32][]uint32
+ ItemCombinations map[uint32]map[uint32]ItemCombination
PlayerAppearances struct {
Heads []PlayerHead `yaml:"heads"`
Bodies []PlayerBody `yaml:"bodies"`
@@ -160,6 +161,21 @@ func init() {
}
}
+ // Fixed-QL recipes identify both inputs and which ones their result replaces.
+ loadYAML("item_combinations.yaml", &ItemCombinations)
+ for first, targets := range ItemCombinations {
+ for second, recipe := range targets {
+ for _, template := range []uint32{first, second, recipe.Result} {
+ if item := ItemTemplates[template]; item == nil || item.Quality == nil || *item.Quality == 0 {
+ panic(fmt.Errorf("item combination %d/%d has invalid template %d", first, second, template))
+ }
+ }
+ if !recipe.Consume[0] && !recipe.Consume[1] {
+ panic(fmt.Errorf("item combination %d/%d consumes no input", first, second))
+ }
+ }
+ }
+
// Combat profiles bind exact creature levels to catalog weapon endpoints.
loadYAML("npc_combat.yaml", &NPCCombatProfiles)
for monster, levels := range NPCCombatProfiles {
diff --git a/server/gamedata/shop_stock.yaml b/server/gamedata/shop_stock.yaml
@@ -30,6 +30,10 @@
155285: [156054, 156339]
155286: [156054, 156339]
+# Basic Pharmacy and Chemistry Tools and Bases: reusable Bio-Comminutor.
+# Arcanum's pharmacy guide establishes this booth; QL1 is a bounded stock subset.
+155287: [154331]
+
# Basic medical supplies: supported QL1 subset. Original medical-family
# descriptions and package definitions; full generation is unresolved.
# See docs/shops.md for the reconstruction policy and evidence bounds.
diff --git a/server/gamedata/types.go b/server/gamedata/types.go
@@ -8,6 +8,12 @@ type ShopMachine struct {
Stats [][2]uint32 `yaml:"stats,omitempty"`
}
+type ItemCombination struct {
+ Result uint32 `yaml:"result"`
+ Skills [][2]uint32 `yaml:"skills,flow"`
+ Consume [2]bool `yaml:"consume,flow"`
+}
+
// Evidence retains provenance and uncertainty as searchable data.
type Evidence struct {
Confidence string `yaml:"confidence"`
diff --git a/server/main_test.go b/server/main_test.go
@@ -367,9 +367,11 @@ func TestWorldCookieThenPing(t *testing.T) {
t.Fatalf("original named hand texture: %x", updates[1][173:229])
}
var leet []byte
+ // The golden packet below describes a level-1 member of the mixed-level population.
for _, update := range updates {
- if binary.BigEndian.Uint32(update[20:24]) == 0x271b3a6b && binary.BigEndian.Uint32(update[37:41])&1 != 0 && string(update[70:75]) == "Leet\x00" {
+ if binary.BigEndian.Uint32(update[20:24]) == 0x271b3a6b && binary.BigEndian.Uint32(update[37:41])&1 != 0 && string(update[70:75]) == "Leet\x00" && update[75] == 1 {
leet = update
+ break
}
}
if len(leet) < 94 || hex.EncodeToString(leet[36:45]) != "0100000241000003b6" || hex.EncodeToString(leet[67:94]) != "00e5054c65657400010000006400000064000044f700640000001c" {
diff --git a/server/plasma_test.go b/server/plasma_test.go
@@ -0,0 +1,314 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "bytes"
+ "encoding/binary"
+ "slices"
+ "sync"
+ "testing"
+)
+
+func newPlasmaWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ world, conn := newEquipmentWorld(t)
+ player := world.characters[1]
+ // Ten in each ability contributes two Pharmacy points.
+ player.stats.TradeRepair.PharmaceuticalTechnology = 1
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ for _, template := range []uint32{154331, 42640} {
+ if granted, err := world.grantItem_locked(player, template); err != nil || !granted {
+ t.Fatal("plasma input", granted, err)
+ }
+ }
+ conn.packets = nil
+ return world, conn
+}
+
+func TestPlasmaCombinationRejectsUnsafeInputsWithoutConsumingTool(t *testing.T) {
+ for _, scenario := range []string{"pharmacy", "reverse", "pelted parts", "ivory parts", "tool quality", "part quality", "tool count", "part count", "tool type"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, conn := newPlasmaWorld(t)
+ player := world.characters[1]
+ request := combinationRequest(1, 65, 66)
+ switch scenario {
+ case "pharmacy":
+ player.stats.TradeRepair.PharmaceuticalTechnology = 0
+ case "reverse":
+ request = combinationRequest(1, 66, 65)
+ case "pelted parts":
+ player.inventory.Items[2].Template = 42639
+ case "ivory parts":
+ player.inventory.Items[2].Template = 42643
+ case "tool quality":
+ player.inventory.Items[1].Quality = 2
+ case "part quality":
+ player.inventory.Items[2].Quality = 2
+ case "tool count":
+ player.inventory.Items[1].Count = 2
+ case "part count":
+ player.inventory.Items[2].Count = 2
+ case "tool type":
+ player.inventory.Items[1].Type = 51022
+ }
+ items := slices.Clone(player.inventory.Items)
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ err = world.handleItemCombination(world.clients[1], request)
+ after, readErr := readTestItemStore(world)
+
+ if err != nil || readErr != nil || !bytes.Equal(before, after) || !slices.Equal(player.inventory.Items, items) || world.nextItem != 3 {
+ t.Fatal("rejected plasma conversion changed ownership or allocation", err, readErr)
+ }
+ if scenario == "pharmacy" {
+ if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][33:37]) != 32 ||
+ binary.BigEndian.Uint32(conn.packets[0][41:45]) != 159 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 3 {
+ t.Fatal("Pharmacy failure did not report the effective QL1 threshold")
+ }
+ }
+ })
+ }
+}
+
+func TestPlasmaCombinationFailureRollsBackAndRetriesWithoutDeletingTool(t *testing.T) {
+ for _, failure := range []struct{ name, sql string }{
+ {"part", "CREATE TRIGGER fail_plasma BEFORE DELETE ON items WHEN OLD.id=3 BEGIN SELECT RAISE(FAIL,'part'); END"},
+ {"ignored part", "CREATE TRIGGER fail_plasma BEFORE DELETE ON items WHEN OLD.id=3 BEGIN SELECT RAISE(IGNORE); END"},
+ {"part placement", "CREATE TRIGGER fail_plasma BEFORE DELETE ON item_locations WHEN OLD.item_id=3 BEGIN SELECT RAISE(FAIL,'part placement'); END"},
+ {"ignored part placement", "CREATE TRIGGER fail_plasma BEFORE DELETE ON item_locations WHEN OLD.item_id=3 BEGIN SELECT RAISE(IGNORE); END"},
+ {"result", "CREATE TRIGGER fail_plasma BEFORE INSERT ON items WHEN NEW.id=4 BEGIN SELECT RAISE(FAIL,'result'); END"},
+ {"ignored result", "CREATE TRIGGER fail_plasma BEFORE INSERT ON items WHEN NEW.id=4 BEGIN SELECT RAISE(IGNORE); END"},
+ {"result placement", "CREATE TRIGGER fail_plasma BEFORE INSERT ON item_locations WHEN NEW.item_id=4 BEGIN SELECT RAISE(FAIL,'result placement'); END"},
+ {"ignored result placement", "CREATE TRIGGER fail_plasma BEFORE INSERT ON item_locations WHEN NEW.item_id=4 BEGIN SELECT RAISE(IGNORE); END"},
+ {"allocation", "CREATE TRIGGER fail_plasma BEFORE UPDATE OF last_item_id ON world BEGIN SELECT RAISE(FAIL,'allocation'); END"},
+ {"ignored allocation", "CREATE TRIGGER fail_plasma BEFORE UPDATE OF last_item_id ON world BEGIN SELECT RAISE(IGNORE); END"},
+ {"commit", "CREATE TABLE pending_plasma (id INTEGER REFERENCES characters(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_plasma AFTER INSERT ON items WHEN NEW.id=4 BEGIN INSERT INTO pending_plasma VALUES(999999); END"},
+ } {
+ t.Run(failure.name, func(t *testing.T) {
+ world, conn := newPlasmaWorld(t)
+ if _, err := world.db.Exec("CREATE TRIGGER protect_tool BEFORE DELETE ON items WHEN OLD.id=2 BEGIN SELECT RAISE(FAIL,'reusable tool'); END; " + failure.sql); err != nil {
+ t.Fatal(err)
+ }
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ items := slices.Clone(world.characters[1].inventory.Items)
+
+ failed := world.handleItemCombination(world.clients[1], combinationRequest(1, 65, 66))
+ after, err := readTestItemStore(world)
+
+ if failed == nil || err != nil || !bytes.Equal(before, after) || !slices.Equal(world.characters[1].inventory.Items, items) || world.nextItem != 3 || len(conn.packets) != 0 {
+ t.Fatal("failed plasma conversion leaked an item, consumption, allocation or acknowledgement", failed, err)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_plasma"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleItemCombination(world.clients[1], combinationRequest(1, 65, 66)); err != nil {
+ t.Fatal("retry tried to delete the protected tool or failed to create plasma", err)
+ }
+ cold := newTestInventoryServer(t).characters[1].inventory.Items
+ if !slices.Contains(cold, ownedItem{ID: 2, Type: 51005, Template: 154331, Quality: 1, Slot: 65, Count: 1}) ||
+ !slices.Contains(cold, ownedItem{ID: 4, Type: 51005, Template: 154358, Quality: 1, Slot: 66, Count: 1}) {
+ t.Fatal("successful retry did not retain one tool and one plasma")
+ }
+ })
+ }
+}
+
+func TestPlasmaCombinationFullInventoryAndConcurrentReplayCreateOnce(t *testing.T) {
+ world, conn := newPlasmaWorld(t)
+ for range 27 {
+ if granted, err := world.grantItem_locked(world.characters[1], 95577); err != nil || !granted {
+ t.Fatal("fill inventory", granted, err)
+ }
+ }
+ conn.packets = nil
+
+ var requests sync.WaitGroup
+ for range 8 {
+ requests.Go(func() {
+ if err := world.handleItemCombination(world.clients[1], combinationRequest(1, 65, 66)); err != nil {
+ t.Error(err)
+ }
+ })
+ }
+ requests.Wait()
+ cold := newTestInventoryServer(t)
+
+ items := cold.characters[1].inventory.Items
+ if len(items) != 30 || world.nextItem != 31 ||
+ !slices.Contains(items, ownedItem{ID: 2, Type: 51005, Template: 154331, Quality: 1, Slot: 65, Count: 1}) ||
+ !slices.Contains(items, ownedItem{ID: 31, Type: 51005, Template: 154358, Quality: 1, Slot: 66, Count: 1}) {
+ t.Fatal("full inventory lost its reusable tool or replay duplicated the plasma", items)
+ }
+ results, deletions := 0, 0
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x052e2f0c {
+ results++
+ } else if binary.BigEndian.Uint32(packet[29:33]) == 112 {
+ deletions++
+ }
+ }
+ if results != 1 || deletions != 1 {
+ t.Fatal("concurrent requests published repeated consumption or result delivery", results, deletions)
+ }
+}
+
+func TestPlasmaCombinationLostReplyRetainsToolForAnotherPart(t *testing.T) {
+ world, _ := newPlasmaWorld(t)
+ world.clients[1].conn = &failingCombatConn{}
+
+ failed := world.handleItemCombination(world.clients[1], combinationRequest(1, 65, 66))
+ cold := newTestInventoryServer(t)
+ cold.clients[1] = &worldClient{id: 1, conn: &combatTestConn{}, target: true, ready: true}
+ if err := cold.handleItemCombination(cold.clients[1], combinationRequest(1, 65, 66)); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := cold.grantItem_locked(cold.characters[1], 42640); err != nil || !granted {
+ t.Fatal("next part", granted, err)
+ }
+ if err := cold.handleItemCombination(cold.clients[1], combinationRequest(1, 65, 67)); err != nil {
+ t.Fatal(err)
+ }
+ final := newTestInventoryServer(t).characters[1].inventory.Items
+
+ expected := []ownedItem{
+ {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1},
+ {ID: 2, Type: 51005, Template: 154331, Quality: 1, Slot: 65, Count: 1},
+ {ID: 4, Type: 51005, Template: 154358, Quality: 1, Slot: 66, Count: 1},
+ {ID: 6, Type: 51005, Template: 154358, Quality: 1, Slot: 67, Count: 1},
+ }
+ if failed == nil || !slices.Equal(final, expected) || cold.nextItem != 6 {
+ t.Fatal("lost reply or reuse lost the tool, reversed consumption or repeated plasma", failed, final)
+ }
+}
+
+func TestPlasmaProductionLootCraftAndSaleRetainToolAndKillRewards(t *testing.T) {
+ world, _ := newKillExperienceWorld(t, "unarmed")
+ player := world.characters[1]
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ if granted, err := world.grantItem_locked(player, 154331); err != nil || !granted {
+ t.Fatal("tool", granted, err)
+ }
+
+ attackForExperience(t, world, "unarmed")
+ if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleItemCombination(world.clients[1], combinationRequest(1, 64, 65)); err != nil {
+ t.Fatal(err)
+ }
+ world = newTestInventoryServer(t)
+ player = world.characters[1]
+ player.appearance, player.position = 0x515, [3]float32{60, 14.75, 53}
+ client := &worldClient{id: 1, conn: &combatTestConn{}, target: true, ready: true}
+ world.clients[1] = client
+ if err := world.handleShopUse(client, shopUseRequest(1)); err != nil {
+ t.Fatal(err)
+ }
+ for _, request := range [][]byte{
+ shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})[20:],
+ shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:],
+ } {
+ if err := world.handleTrade(client, request); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if !slices.Contains(newTestInventoryServer(t).characters[1].inventory.Items, ownedItem{ID: 5, Type: 51005, Template: 154358, Quality: 1, Slot: 65, Count: 1}) {
+ t.Fatal("cancelled sale lost crafted plasma")
+ }
+ if err := world.handleShopUse(client, shopUseRequest(2)); err != nil {
+ t.Fatal(err)
+ }
+ for _, request := range [][]byte{
+ shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})[20:],
+ shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:],
+ shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:],
+ } {
+ if err := world.handleTrade(client, request); err != nil {
+ t.Fatal(err)
+ }
+ }
+ cold := newTestInventoryServer(t)
+
+ expected := []ownedItem{{ID: 3, Type: 51005, Template: 154331, Quality: 1, Slot: 64, Count: 1}}
+ if !slices.Equal(cold.characters[1].inventory.Items, expected) || cold.characters[1].inventory.Credits != 63 ||
+ cold.characters[1].experience != 100 || cold.nextItem != 5 || len(cold.characters[1000000].corpse.items) != 0 {
+ t.Fatal("loot/craft/sale lost the reusable tool or changed kill rewards", cold.characters[1].inventory, cold.characters[1].experience, cold.nextItem)
+ }
+}
+
+func TestPlasmaToolPurchaseUsesOriginalBasicPharmacyStock(t *testing.T) {
+ world, _ := newEquipmentWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ machine := gamedata.ShopMachines[3225093279]
+ player.playfield, player.position = machine.Playfield, machine.Position
+ player.inventory.Credits = 420
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 42640); err != nil || !granted {
+ t.Fatal("part", granted, err)
+ }
+ request := shopUseRequest(1)
+ binary.BigEndian.PutUint32(request[44:48], 3225093279)
+ if err := world.handleShopUse(client, request); err != nil {
+ t.Fatal(err)
+ }
+
+ for _, request := range [][]byte{
+ shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3225093279}, [2]uint32{111, 0})[20:],
+ shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:],
+ } {
+ if err := world.handleTrade(client, request); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := world.handleItemCombination(client, combinationRequest(1, 66, 65)); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+
+ if cold.characters[1].inventory.Credits != 0 || !slices.Contains(cold.characters[1].inventory.Items, ownedItem{ID: 3, Type: 51005, Template: 154331, Quality: 1, Slot: 66, Count: 1}) ||
+ !slices.Contains(cold.characters[1].inventory.Items, ownedItem{ID: 4, Type: 51005, Template: 154358, Quality: 1, Slot: 65, Count: 1}) {
+ t.Fatal("purchased tool did not retain its price, identity or reuse behavior", cold.characters[1].inventory)
+ }
+ for _, template := range []uint32{155288, 155289, 100034, 100035, 99481} {
+ if slices.Contains(gamedata.ShopStock[template], 154331) {
+ t.Fatal("basic pharmacy subset leaked into another stock family", template)
+ }
+ }
+}
+
+func TestPlasmaCombinationRetainsReusableToolAndOneColdResult(t *testing.T) {
+ world, conn := newPlasmaWorld(t)
+
+ if err := world.handleItemCombination(world.clients[1], combinationRequest(1, 65, 66)); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+
+ expected := []ownedItem{
+ {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1},
+ {ID: 2, Type: 51005, Template: 154331, Quality: 1, Slot: 65, Count: 1},
+ {ID: 4, Type: 51005, Template: 154358, Quality: 1, Slot: 66, Count: 1},
+ }
+ for _, current := range []*server{world, cold} {
+ if !slices.Equal(current.characters[1].inventory.Items, expected) || current.nextItem != 4 || len(current.items) != 3 {
+ t.Fatal("plasma conversion lost the tool, unrelated item or durable result", current.characters[1].inventory.Items)
+ }
+ }
+ if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 112 ||
+ binary.BigEndian.Uint32(conn.packets[0][37:41]) != 50 || binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x052e2f0c {
+ t.Fatal("native conversion deleted the reusable tool or omitted first-free result delivery")
+ }
+}
diff --git a/server/shop_stock_test.go b/server/shop_stock_test.go
@@ -16,6 +16,7 @@ func TestShopDocumentedStockUsesTerminalBindings(t *testing.T) {
{3221488799, []uint32{95577}},
{3221816479, []uint32{161699}},
{3225158815, []uint32{156054, 156339}},
+ {3225093279, []uint32{154331}},
{3221292199, nil},
} {
t.Run(fmt.Sprint(scenario.machine), func(t *testing.T) {
diff --git a/server/tradeskills.go b/server/tradeskills.go
@@ -7,13 +7,6 @@ import (
"slices"
)
-var itemCombinations = map[[2]uint32]struct {
- result uint32
- skills [][2]uint32
-}{
- {95577, 161699}: {158416, [][2]uint32{{160, 25}, {165, 60}}},
-}
-
func (server *server) handleItemCombination(client *worldClient, body []byte) error {
if len(body) != 36 {
return fmt.Errorf("invalid item combination length")
@@ -45,7 +38,7 @@ func (server *server) handleItemCombination(client *worldClient, body []byte) er
return nil
}
first, second := player.inventory.Items[source], player.inventory.Items[target]
- recipe, exists := itemCombinations[[2]uint32{first.Template, second.Template}]
+ recipe, exists := gamedata.ItemCombinations[first.Template][second.Template]
if !exists {
return client.send(characterActionPacket(client.id, [5]uint32{84, 2, 0, 0, 0}))
}
@@ -55,7 +48,7 @@ func (server *server) handleItemCombination(client *worldClient, body []byte) er
return nil
}
}
- for _, requirement := range recipe.skills {
+ for _, requirement := range recipe.Skills {
actual, known := player.effectiveStat(requirement[0])
if !known || actual < int32(requirement[1]) {
return client.send(characterActionPacket(client.id, [5]uint32{84, 32, 0, requirement[0], requirement[1]}))
@@ -65,11 +58,16 @@ func (server *server) handleItemCombination(client *worldClient, body []byte) er
return fmt.Errorf("item identities exhausted")
}
- // Replace both ingredients with one result in a detached, atomic candidate.
+ // Preserve reusable tools while replacing consumed inputs atomically.
inventory := player.inventory
- inventory.Items = slices.DeleteFunc(slices.Clone(inventory.Items), func(item ownedItem) bool { return item.ID == first.ID || item.ID == second.ID })
- definition := gamedata.ItemTemplates[recipe.result]
- item := ownedItem{ID: server.nextItem + 1, Type: definition.HeaderWords[0], Template: recipe.result, Quality: *definition.Quality, Slot: 64, Count: 1}
+ inventory.Items = slices.Clone(inventory.Items)
+ for index, ingredient := range []ownedItem{first, second} {
+ if recipe.Consume[index] {
+ inventory.Items = slices.DeleteFunc(inventory.Items, func(item ownedItem) bool { return item.ID == ingredient.ID })
+ }
+ }
+ definition := gamedata.ItemTemplates[recipe.Result]
+ item := ownedItem{ID: server.nextItem + 1, Type: definition.HeaderWords[0], Template: recipe.Result, Quality: *definition.Quality, Slot: 64, Count: 1}
for slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.Slot == item.Slot }) {
item.Slot++
}
@@ -80,8 +78,11 @@ func (server *server) handleItemCombination(client *worldClient, body []byte) er
}
server.nextItem = max(server.nextItem, inventory.LastID)
- // Native AddTemplate chooses first-free after both deletion acknowledgements.
- for _, ingredient := range []ownedItem{first, second} {
+ // Native AddTemplate chooses first-free after consumed-input deletion acknowledgements.
+ for index, ingredient := range []ownedItem{first, second} {
+ if !recipe.Consume[index] {
+ continue
+ }
low, high := ingredient.templateIDs()
if err := client.send(characterActionPacket(client.id, [5]uint32{112, 104, ingredient.Slot, low, high})); err != nil {
return err