All files / js o_init.js

95.78% Statements 318/332
81.39% Branches 70/86
100% Functions 10/10
95.78% Lines 318/332

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 33373x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 294x 294x 294x 294x 223x 223x 223x 223x 223x 223x 223x 223x 294x 71x 71x 294x 294x 294x 294x 294x 294x 294x       294x 294x 294x 294x 294x 294x 294x 294x 294x 294x 73x 73x 73x 71x 71x 71x 126x 126x 126x 126x 126x 126x 71x 71x 32x 32x 71x 40x 40x 71x 71x 17x 71x 21x 21x 71x 21x 21x 71x 12x 12x 71x 71x 73x 73x 73x 73x 73x 73x 73x 781x 781x 781x 781x 781x 781x 781x 13845x 781x 781x 781x 781x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 13845x 12496x 12496x 12496x 12496x 13845x 781x 73x 73x 73x 73x 73x 781x 781x 781x 781x 781x 284x 284x 213x 213x 142x 142x 71x 71x 284x 781x 71x 71x 71x 71x 781x 781x 781x 213x 213x 213x 213x 6816x 213x 213x 781x 781x 781x 213x 213x 213x 213x 781x 781x 781x 781x 781x 781x 781x 781x 73x 73x 73x 73x 73x 71x 71x 71x 71x 1278x 1278x 32873x 32873x 1278x 1278x               1278x 1278x 71x 73x 73x 73x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 497x 497x 497x 71x 71x 284x 284x 284x 71x 73x 73x 73x 73x 73x 73x 73x 73x 73x 71x 71x 71x 71x 71x 71x 1349x 1349x         1349x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 1136x 1136x 1136x 1136x 1136x 1136x 1136x 1136x 1136x 1136x 1136x 71x 71x 71x 1136x 1136x 1136x 71x 71x 71x 71x 71x 71x 1278x 71x 71x 71x 71x 71x 71x 71x 71x 32873x 32873x 32873x 32873x 32873x 213x 213x 213x 32873x 32873x 32873x 32873x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 73x 73x 73x 73x 223x 223x 223x 73x 73x 72x 72x 72x 72x 34632x 34632x 34632x 72x 72x 72x 72x 72x  
// o_init.js — Object initialization (port of o_init.c)
// C ref: nethack-c/patched/src/o_init.c
//
// This is one of the most RNG-critical files: init_objects() consumes ~198
// RNG calls during startup through object description shuffling.
 
import { objectData, normalizeObjectFields, MAXOCLASSES, NUM_OBJECTS, ILLOBJ_CLASS, ARMOR_CLASS, POTION_CLASS, AMULET_CLASS, SCROLL_CLASS, SPBOOK_CLASS, RING_CLASS, WAND_CLASS, VENOM_CLASS, GEM_CLASS, HELMET, HELM_OF_TELEPATHY, LEATHER_GLOVES, GAUNTLETS_OF_DEXTERITY, CLOAK_OF_PROTECTION, CLOAK_OF_DISPLACEMENT, SPEED_BOOTS, LEVITATION_BOOTS, POT_WATER, WAN_NOTHING, LAST_REAL_GEM, TURQUOISE, AQUAMARINE, FLUORITE, SAPPHIRE, DIAMOND, EMERALD, NODIR, IMMEDIATE } from './objects.js';
import { rn2, pushRngLogEntry } from './rng.js';
import { game } from './gstate.js';
 
// C ref: o_init.c:53 setgemprobs()
// Sets gem probabilities based on dungeon level.
// Called with dlev=null during init_objects() (lev=0).
function setgemprobs(dlev) {
    let j, first, lev, sum = 0;
 
    if (dlev) {
        const dnum = dlev.dnum ?? 0;
        const dlevel = dlev.dlevel ?? 1;
        const ledgerStart = game.dungeons?.[dnum]?.ledger_start ?? 0;
        const ledgerNo = dlevel + ledgerStart;
        const dungeons = game.dungeons || [];
        const last = dungeons[dungeons.length - 1];
        const maxLedger = last ? ((last.ledger_start ?? 0) + (last.num_dunlevs ?? 0)) : 1;
        lev = (ledgerNo > maxLedger) ? maxLedger : ledgerNo;
    } else {
        lev = 0;
    }
    first = game.bases[GEM_CLASS];
 
    for (j = 0; j < 9 - Math.trunc(lev / 3); j++)
        game.objects[first + j].oc_prob = 0;
    first += j;
    if (first > LAST_REAL_GEM || game.objects[first].oc_class !== GEM_CLASS
        || !game.objects[first].oc_name) {
        // C: raw_printf("Not enough gems? - first=%d j=%d LAST_GEM=%d", ...)
        console.error(`Not enough gems? - first=${first} j=${j} LAST_GEM=${LAST_REAL_GEM}`);
    }
    for (j = first; j <= LAST_REAL_GEM; j++)
        game.objects[j].oc_prob = Math.trunc((171 + j - first) / (LAST_REAL_GEM + 1 - first));
 
    // recompute GEM_CLASS total oc_prob - including rocks/stones
    for (j = game.bases[GEM_CLASS]; j < game.bases[GEM_CLASS + 1]; j++)
        sum += game.objects[j].oc_prob;
    game.oclass_prob_totals[GEM_CLASS] = sum;
 
    // Diagnostic-only parity aid: emit effective gem table state.
}
 
// C ref: o_init.c:84 randomize_gem_colors()
// Exactly 3 RNG calls: rn2(2), rn2(2), rn2(4) — in that order.
function randomize_gem_colors() {
    // C macro: COPY_OBJ_DESCR(o_dst, o_src) copies oc_descr_idx and oc_color
    function copyObjDescr(dst, src) {
        // JS uses direct description strings (oc_descr) where C uses
        // oc_descr_idx into obj_descr[]; keep both fields in sync.
        dst.oc_descr = src.oc_descr;
        dst.oc_descr_idx = src.oc_descr_idx;
        dst.oc_color = src.oc_color;
    }
 
    if (rn2(2)) { // change turquoise from green to blue?
        copyObjDescr(game.objects[TURQUOISE], game.objects[SAPPHIRE]);
    }
    if (rn2(2)) { // change aquamarine from green to blue?
        copyObjDescr(game.objects[AQUAMARINE], game.objects[SAPPHIRE]);
    }
    switch (rn2(4)) { // change fluorite from violet?
    case 0:
        break;
    case 1: // blue
        copyObjDescr(game.objects[FLUORITE], game.objects[SAPPHIRE]);
        break;
    case 2: // white
        copyObjDescr(game.objects[FLUORITE], game.objects[DIAMOND]);
        break;
    case 3: // green
        copyObjDescr(game.objects[FLUORITE], game.objects[EMERALD]);
        break;
    }
}
 
// C ref: o_init.c:112 shuffle()
// NOTE: differs from canonical sp_lev.js — this shuffle(o_low, o_high, domaterial) swaps
// object description fields within a range, skipping known items; sp_lev.js shuffle(arr) is
// a generic array Fisher-Yates shuffle.
// MANY RNG calls: rn2(o_high - j + 1) per non-name_known item.
// This is the primary RNG consumer (~198 calls total across all shuffle_all ranges).
function shuffle(o_low, o_high, domaterial) {
    let i, j, num_to_shuffle;
    let sw;
    let color;
 
    for (num_to_shuffle = 0, j = o_low; j <= o_high; j++)
        if (!game.objects[j].known)
            num_to_shuffle++;
    if (num_to_shuffle < 2)
        return;
 
    for (j = o_low; j <= o_high; j++) {
        if (game.objects[j].known)
            continue;
        do
            i = j + rn2(o_high - j + 1);
        while (game.objects[i].known);
        // swap oc_descr (JS uses description strings directly, not C's oc_descr_idx)
        sw = game.objects[j].oc_descr;
        game.objects[j].oc_descr = game.objects[i].oc_descr;
        game.objects[i].oc_descr = sw;
        // swap oc_tough
        sw = game.objects[j].tough;
        game.objects[j].tough = game.objects[i].tough;
        game.objects[i].tough = sw;
        // swap oc_color
        color = game.objects[j].oc_color;
        game.objects[j].oc_color = game.objects[i].oc_color;
        game.objects[i].oc_color = color;
        // swap oc_material
        if (domaterial) {
            sw = game.objects[j].oc_material;
            game.objects[j].oc_material = game.objects[i].oc_material;
            game.objects[i].oc_material = sw;
        }
    }
}
 
// C ref: o_init.c:267 obj_shuffle_range()
// Retrieve the range of objects that otyp shares descriptions with.
// Returns { lo, hi }.
export function obj_shuffle_range(otyp) {
    let i, ocls = game.objects[otyp].oc_class;
    let lo = otyp, hi = otyp;
 
    switch (ocls) {
    case ARMOR_CLASS:
        if (otyp >= HELMET && otyp <= HELM_OF_TELEPATHY)
            lo = HELMET, hi = HELM_OF_TELEPATHY;
        else if (otyp >= LEATHER_GLOVES && otyp <= GAUNTLETS_OF_DEXTERITY)
            lo = LEATHER_GLOVES, hi = GAUNTLETS_OF_DEXTERITY;
        else if (otyp >= CLOAK_OF_PROTECTION && otyp <= CLOAK_OF_DISPLACEMENT)
            lo = CLOAK_OF_PROTECTION, hi = CLOAK_OF_DISPLACEMENT;
        else if (otyp >= SPEED_BOOTS && otyp <= LEVITATION_BOOTS)
            lo = SPEED_BOOTS, hi = LEVITATION_BOOTS;
        break;
    case POTION_CLASS:
        // potion of water has the only fixed description
        lo = game.bases[POTION_CLASS];
        hi = POT_WATER - 1;
        break;
    case AMULET_CLASS:
    case SCROLL_CLASS:
    case SPBOOK_CLASS:
        // exclude non-magic types and also unique ones
        lo = game.bases[ocls];
        for (i = lo; game.objects[i].oc_class === ocls; i++)
            if (game.objects[i].unique || !game.objects[i].magic)
                break;
        hi = i - 1;
        break;
    case RING_CLASS:
    case WAND_CLASS:
    case VENOM_CLASS:
        // entire class
        lo = game.bases[ocls];
        hi = game.bases[ocls + 1] - 1;
        break;
    }
 
    // artifact checking might ask about item which isn't part of any range
    // but fell within the classes that do have ranges specified above
    if (otyp < lo || otyp > hi)
        lo = hi = otyp;
    return { lo, hi };
}
 
// C ref: o_init.c:239 init_oclass_probs()
// Compute the total probability of each object class.
// Assumes bases[] has already been set.
export function init_oclass_probs() {
    let i;
    let sum;
    let oclass;
    for (oclass = 0; oclass < MAXOCLASSES; ++oclass) {
        sum = 0;
        for (i = game.bases[oclass]; i < game.bases[oclass + 1]; ++i) {
            sum += game.objects[i].oc_prob;
        }
        if (sum <= 0 && oclass !== ILLOBJ_CLASS
            && game.bases[oclass] !== game.bases[oclass + 1]) {
            // C: impossible("zero/negative probability total for oclass")
            console.error(`${!sum ? "zero" : "negative"} (${sum}) probability total for oclass ${oclass}`);
            for (i = game.bases[oclass]; i < game.bases[oclass + 1]; ++i) {
                game.objects[i].oc_prob = 1;
                sum++;
            }
        }
        game.oclass_prob_totals[oclass] = sum;
    }
}
 
// C ref: o_init.c:321 shuffle_all()
// Randomize object descriptions for all shuffleable classes and armor sub-ranges.
function shuffle_all() {
    // entire classes; obj_shuffle_range() handles their exceptions
    const shuffle_classes = [
        AMULET_CLASS, POTION_CLASS, RING_CLASS, SCROLL_CLASS,
        SPBOOK_CLASS, WAND_CLASS, VENOM_CLASS,
    ];
    // sub-class type ranges (one item from each group)
    const shuffle_types = [
        HELMET, LEATHER_GLOVES, CLOAK_OF_PROTECTION, SPEED_BOOTS,
    ];
 
    // do whole classes (amulets, etc.)
    for (let idx = 0; idx < shuffle_classes.length; idx++) {
        const { lo: first, hi: last } = obj_shuffle_range(game.bases[shuffle_classes[idx]]);
        shuffle(first, last, true);
    }
    // do type ranges (helms, etc.)
    for (let idx = 0; idx < shuffle_types.length; idx++) {
        const { lo: first, hi: last } = obj_shuffle_range(shuffle_types[idx]);
        shuffle(first, last, false);
    }
}
 
// C ref: o_init.c:150 init_objects()
// Master object initialization. Sets up bases[], descriptions, probabilities,
// then shuffles descriptions and sets WAN_NOTHING direction.
// Made async because it could theoretically print messages.
// Save original object data for reset between sessions.
// C starts a fresh process per game; JS reuses modules.
 
export async function init_objects() {
 
    let i, first, last, prevoclass;
    let oclass;
 
    // C: for (i = 0; i <= MAXOCLASSES; i++) svb.bases[i] = 0;
    for (i = 0; i <= MAXOCLASSES; i++) {
        game.bases[i] = 0;
        if (i > 0 && i < MAXOCLASSES && game.objects[i].oc_class !== i) {
            throw new Error(
                `init_objects: class for generic object #${i} doesn't match (${game.objects[i].oc_class})`
            );
        }
    }
 
    // initialize object descriptions
    // C: for (i = 0; i < NUM_OBJECTS; i++) objects[i].oc_name_idx = objects[i].oc_descr_idx = i;
    for (i = 0; i < NUM_OBJECTS; i++)
        game.objects[i].oc_name_idx = game.objects[i].oc_descr_idx = i;
 
    // init base; compute class ranges
    // C: first = MAXOCLASSES;
    first = MAXOCLASSES;
    prevoclass = -1;
    while (first < NUM_OBJECTS) {
        oclass = game.objects[first].oc_class;
        // objects[] sanity check: must be in ascending oc_class order
        if (oclass < prevoclass)
            throw new Error(`game.objects[${first}] class #${oclass} not in order!`);
 
        last = first + 1;
        while (last < NUM_OBJECTS && game.objects[last].oc_class === oclass)
            last++;
        game.bases[oclass] = first;
 
        if (oclass === GEM_CLASS) {
            setgemprobs(null);
            randomize_gem_colors();
        }
        first = last;
        prevoclass = oclass;
    }
 
    // C: svb.bases[MAXOCLASSES] = svb.bases[MAXOCLASSES + 1] = NUM_OBJECTS;
    game.bases[MAXOCLASSES] = game.bases[MAXOCLASSES + 1] = NUM_OBJECTS;
    // fill gaps: if a class has no objects, point to next class
    for (last = MAXOCLASSES - 1; last >= 0; --last)
        if (!game.bases[last])
            game.bases[last] = game.bases[last + 1];
 
    // C ref: o_init.c:211-225 — validate oc_name_known vs description presence.
    // In C, oc_name_known is set from BITS(nmkn,...) in objects.h:
    //   nmkn=1 for items without random descriptions (foods, weapons, etc.)
    //   nmkn=0 for items with random descriptions (potions, scrolls, etc.)
    // JS must initialize oc_name_known to match C's static BITS(nmkn) value.
    // Rule: if no oc_descr (fixed name) → oc_name_known=1; if has oc_descr → oc_name_known=0.
    for (i = MAXOCLASSES; i < NUM_OBJECTS; ++i) {
        let nmkn = game.objects[i].known ? 1 : 0;
        // C: if (!OBJ_DESCR(objects[i]) ^ nmkn) — OBJ_DESCR checks if description exists
        // In JS, oc_descr is the description string (or null)
        let hasDescr = game.objects[i].oc_descr ? 1 : 0;
        if ((!hasDescr) ^ nmkn) {
            // repair the mistake and keep going
            game.objects[i].known = nmkn ? 0 : 1;
        }
        // Sync oc_name_known with the (possibly repaired) known value.
        // Items without random descriptions (known=1) start identified; others start unknown.
        game.objects[i].oc_name_known = game.objects[i].known ? 1 : 0;
    }
 
    // compute oclass_prob_totals
    init_oclass_probs();
 
    // shuffle descriptions
    shuffle_all();
 
    // CRITICAL: ends with rn2(2) for WAN_NOTHING direction
    game.objects[WAN_NOTHING].oc_dir = rn2(2) ? NODIR : IMMEDIATE;
}
 
// C ref: o_init.c:368 oinit()
// Level-dependent initialization — resets gem probabilities.
export function oinit() {
    // C: setgemprobs(&u.uz)
    setgemprobs(game.u?.uz ?? null);
}
 
export function init_o_init_globals() {
    // Fresh deep copy from immutable template — each game gets its own objects.
    // Must apply normalizeObjectFields to recreate getter/setter alias pairs
    // (spread only copies plain values, not property descriptors).
    game.objects = objectData.map(o => {
        const copy = { ...o };
        normalizeObjectFields(copy);
        return copy;
    });
    game.bases = new Array(MAXOCLASSES + 2).fill(0);
    game.oclass_prob_totals = new Array(MAXOCLASSES).fill(0);
    game.originalObjectData = null;
}