diff --git a/AGENTS.md b/AGENTS.md index a7faa81e71..3065bcc664 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -177,6 +177,19 @@ restyling anything large: - a jump table - Ghidra usually renders the dispatch as a call through an unnamed pointer array and drops the arms, so rebuild the `switch` from the byte and jump tables instead of restyling the decompiler output. +`quick_diff.py` is a triage tool and it misranks two things. It prints the **wrong immediates for the +original side** (`0x51eb851f` where the binary holds `0x66666667` or `0x10624dd3`), so never read a constant +out of its output - use `orig_asm.py` or Ghidra. And its difflib ratio can invert the reccmp ranking even well +above the 0.6 the README warns about, because a changed base anchor makes every displacement differ textually +while the opcodes still line up: on `updateCrowding` it preferred a variant that measured 25.5% over one that +measured 33.3%. Rank with it, then settle small functions with `try_styles.py`, which narrows the build list to +one file and therefore costs about a minute per variant. + +reccmp symbolizes an immediate that happens to coincide with a data address, and it does so per binary. The +thirty `push 0xffffff` of `renderDebugDataCurrentPlayerData` come out as +`push I::instance+424671` on the original side and as the plain immediate on ours, which caps +that function at ~96% with no source change possible. Check for that before chasing a stable few percent. + `diff_triage.py` gives one line per function in the build list and says whether more source work can pay at all: it flags a `sub esp` frame-size mismatch (`FRAME`), byte-sized stack slots we have and the original does not (`BYTE`), a cold return block we inline where the original outlines it (`RET`), and the case where only register and stack-slot @@ -200,6 +213,40 @@ than a preference the source could state. That is a hypothesis, not a decoded ru `tools/compiler-internals/msvc-backend.md` has what is actually established about the compiler's allocator and the debugger recipe that can settle it per function. +### Switching the reimplementation on before measuring + +There are **two** switches, and both are deliberately uncommitted, so a rebase, a fresh clone or a +`git checkout -- src/OpenSHC` turns both off at once: + +- `tools/reimplementation-control/enable_reimplemented_data.py` - the `MACRO_STRUCT_RESOLVER` flags in + `src/OpenSHC/Globals/*.hpp`. +- `tools/reimplementation-helper/batch/enable_local_functions.py` - the `MACRO_FUNCTION_RESOLVER` flags for + exactly the files in `cmake/openshc-sources.txt.local`. The repository-wide + `tools/reimplementation-control/Enable-Reimplemented-Functions.ps1` flips every resolver that has a .cpp + anywhere in the tree, which does not link while the build list is a subset: each enabled resolver whose + .cpp is not compiled becomes an unresolved external. + +With the function resolvers off, every call leaves the module for the original game address, so **`/GL` +buys nothing**: LTCG cannot see a callee it does not compile. `getSalesPrice` sat at 68.4% for as long as +`getSellResourceAmount`'s resolver was `false`, and reached 100% the moment it was `true` - the original +keeps `this` in the volatile EDX across that call, which is exactly what LTCG provides. `clearEnemyRelatedStructures` +went 97.7% -> 100% the same way. So to chase a "volatile register survives a call" diff: put the callee's .cpp in +the build list, enable its resolver, and add **both** files to `cmake/compiler-flags-gl.txt`. + +**`/GL` can also make a function worse, and not only through the LTCG unit.** LTCG lets MSVC see that a +callee does not touch a given struct, so it starts hoisting loads the original's compiler had to repeat: +`spawnPoisonCloudsAroundBuilding` fell 92.4% -> 69.6% because LTCG hoisted +`buildings[buildingID].x`/`.y` out of the retry loop across `nextRandomNumber2`, which the original +re-reads every iteration. So add `/GL` for a pair only when the *original* shows the cross-call knowledge - +a volatile register still live after a `call`, or a missing `mov ecx, ` reload. A reimplemented +callee is not a reason on its own. + +`/GL` is whole-program, so the list is not a free-for-all. Adding files that are not part of the pair under +test re-codegens everything in the LTCG unit: one such round cost `processFoodConsumption` 20 points and +`spawnPoisonCloudsAroundBuilding` 23 while gaining 1.3 elsewhere. Add one caller/callee pair at a time and +keep only what measures better. A callee that is not itself at 100% is worse than useless here, because +LTCG then propagates *our* register use rather than the original's. + ### Binary Comparison (`reccmp`) Compares generated binaries against the original executable. diff --git a/IMPLEMENTATION_CHEAT_SHEET.md b/IMPLEMENTATION_CHEAT_SHEET.md index f653e9b519..990c7bccfa 100644 --- a/IMPLEMENTATION_CHEAT_SHEET.md +++ b/IMPLEMENTATION_CHEAT_SHEET.md @@ -665,3 +665,418 @@ Naturally, the stack reserved for the function indicated by `sub esp, ` At best, not only the stack fits, but variables are also at the correct positions and sizes within. If the stack usage shows a proper order in the function (i.e. the initial array occupies the first part in the allocated function stack, which means it requires the highest `[esp + ]` to reach), it might be sometimes good to fit one "side" of the stack first and then experiment with the rest of the function that has a non-fitting stack usage. + +### A constant that reaches a field through a register was a local in the source + +Where several arms of a chain each store the *same* literal both into a field and into an +arithmetic expression, the original loads the literal into a register first: + +```asm +mov eax, -0x96 ; the constant, in a register +add ebp, eax ; popularity = popularityAfterFear + penalty +mov dword ptr [ebx], ebp +mov word ptr [esi + 0x32ff8], ax ; someCount54 = penalty, from the SAME register +``` + +Writing the constants out per arm (`popularity = snapshot - 150; someCount54 = -150;`) gives +`mov word ptr [...], -0x96` with an *immediate* instead, because the two uses then share nothing. +The source assigned one local in each arm and used it after the chain; MSVC then duplicated the +two statements into every arm, which is why the stores look per-arm in the asm: + +```cpp +int siegePenalty; +if (c <= 0) { siegePenalty = -150; } else if (c <= 5) { siegePenalty = -125; } /* ... */ +this->...popularity = popularityAfterFear + siegePenalty; +this->...someCount54 = (short)siegePenalty; +``` + +This single change took `updatePopularity` from 68.3% to 93.2%; it also fixed the register +allocation of the whole surrounding function, which had looked like an unrelated allocator gap. +The tell is an *immediate* on our side where the original uses a byte/word register (`ax`, `cx`) +that was just loaded with the same constant. + +### The struct/loop base anchor moves when a field loses its stores + +MSVC picks one address as the base for a run of accesses into the same object +(`lea esi, [ecx + 0x367e4]`, then `[esi - 0x10]`, `[esi + 0xe0]`, ...). Which field lands at +offset 0 is not the most-used one and is not controllable from the source, but it *does* change +when the source changes: introducing a local for a field that was previously stored in several +arms moved the anchor by 0xe0 in `processFoodConsumption` and by 0x10 in +`processPeasantSpawnAndDespawnCycle`, and every displacement in the function then differs. + +Both of those locals are provably present in the original (a value survives a call in a +callee-saved register), yet the anchor shift cost more than the local gained: +81.7% -> 61.7% and 85.3% -> 69.0%. So when a `FRAME`-free function regresses by a large, +suspiciously uniform amount after a one-line change, compare the `lea`/`add` that sets up the +base before looking anywhere else, and keep the form with the matching anchor. + +### A function that looks huge may be a tail call + +`nof_fpoints_locationFinder` had been reimplemented with a 40-line `do/while` body; the original +is eleven instructions ending in `mov ecx, ; jmp 0x4a6940`, a tail call to +`PathFindingState::searchCertainPathLayer`, whose body Ghidra had folded into the caller's +decompilation. Check the original's last instruction for a `jmp` to another function's entry +before reproducing a long body: 35.6% -> normalized 100% here. + +### The join block of a long if/else-if chain moves with the size of the first arm + +In `computeBuildingCategoryEntryPointAndDestroyEarlierBuilding` the chain order, every arm's body and the +shared tail all match the original, yet the original ends +`[prologue][first arm][else chain][tail][epilogue]` and this toolchain emits +`[prologue][first arm][tail][epilogue][else chain]` - the `ret` lands at 51% of the function instead of 99%, +and because reccmp aligns instruction streams, almost the whole function then counts as differing (33.5%). + +The flip is a threshold on the **first arm**, not a source shape. Thirteen source forms (switch, fully +nested `else`, combined guard, empty trailing `else`, nested early returns, `__forceinline` helpers for the +tail and for the chain, parameter copies, casts, declaration order) all produced byte-identical code. +Shrinking the first arm does move the tail to the end, and three unrelated shrinks did it: dropping one arm +of its inner `orientation` chain, dropping its three early returns, or dropping its nested +`currentMenuViewType` block. The threshold sits between 168 and 175 instructions for that function, and the +original is 178, so it is not reachable by trimming anything the original actually contains. + +`#pragma optimize("s", on)` also produces the original's layout, which is a useful diagnosis - but it is not +the explanation: measured over the thirteen functions still short of 100% in `Game::GameStateStructures`, +`/Os` lost ground on **every single one** (e.g. `showPopAndGoldPopup` 0.93 -> 0.20, +`renderDebugDataCurrentPlayerData` 0.96 -> 0.17). The original was built for speed; only its block layout +differs, which points at a different compiler build rather than a different flag. `/G5`, `/G6` and `/G7` +change nothing in this toolchain (they are deprecated no-ops in VS2005). + +### The struct base anchor is coupled to the transformation you are trying to make + +MSVC bases a run of accesses into one object on a single address (`lea esi, [ecx + 0x367e4]`, then +`[esi - 0x10]`, `[esi + 0xe0]`, ...). Which field lands at offset 0 is not a size or frequency decision - +with the right anchor `processFoodConsumption` gets 30 byte-sized displacements and with the wrong one 3, +and MSVC still picks the wrong one - and it cannot be steered from an *indexed* source (an explicit pointer to the +anchor field does pin it, see the section near the end): the global vs `this->` +spelling of a field, an extra read of it, the index's cast, the statement order and the number of stores to +other fields all leave it unchanged (probed with a `/FA` compile per variant, about ten seconds each). + +What *does* move it is the very change you want: + +- `processFoodConsumption`: the original keeps `currentPopulation * 3` in a callee-saved register across the + `isAIPlayer` call, so a local is provably right. Writing that local - or getting the same CSE for free by + enabling LTCG over the callee - moves the anchor by 0xe0 and costs 20 points, more than the local gains. +- `processPeasantSpawnAndDespawnCycle`: the original stores `vclockIncrement` once after the chain rather + than in each arm. Hoisting the store moves the anchor by 0x10 and costs 15 points. + +Both originals have the local *and* the matching anchor, so the combination is simply not reachable here. +When a one-line change costs a large and suspiciously uniform amount, read the `lea`/`add` that sets up the +base before looking anywhere else. + +One narrow rule did hold, for a condition that reads two arrays of the same struct: MSVC anchors the +induction variable on the **second** array mentioned in the source, while the comparison order follows the +source. `showPopAndGoldPopup` and `createStatsPopUpEntities` need `currentPlayerFullIDArray` tested first +*and* used as the anchor, so the two requirements conflict and the faithful form (the one the asm's +comparison order shows) is the one that loses the anchor. + +### Check whether the original shares a tail before duplicating a call + +Ghidra renders a cross-jumped tail as a `goto` into the middle of another branch, and the shared part can be +a single instruction. In `processPeasantSpawnAndDespawnCycle` the two `playSpeechSFX` sites are one call +reached from both paths with the speech ID in a register (`speechID = SEID_POP_EMIGRATE; goto LAB_0045b684;`), +and in `updatePopularity` the six siege arms share `popularity = snapshot + penalty; someCount54 = penalty;`. + +The two need opposite treatment, so read the asm rather than the decompiler's shape: + +- `updatePopularity` had to *gain* the variable: MSVC then duplicated the two statements into each arm by + itself, which is what the original does, and the function went 68.3% -> 93.2%. +- `processPeasantSpawnAndDespawnCycle` already emits one call site - MSVC cross-jumped the two identical + tails on its own - so routing the ID through a `SpeechEffectID` local changed nothing (MSVC propagates the + constant straight back into the push). Count the call sites in a `/FA` compile before restructuring. + +A merged tail can still be worth writing once even when our `/FA` already shows one copy, because MSVC +cross-jumps *after* register allocation: the allocator still counts every source copy as a use. In +`computeBuildingCategoryEntryPointAndDestroyEarlierBuilding` nine arms each read +`buildings[buildingID].buildingEntryX/Y` (and five call `destroyBuilding`). Both compiles end with one shared +block, but with nine source copies `buildingID` scored high enough to take `ebx`, where the original reloads it +from the stack every time. Writing the read once, behind `goto readEntry` from the arms that share it, took +the function 33.5% -> 64.0%. A goto-free form (an outer `||` over the nine categories around the inner +chain) measured worse, 52.1 against 71.8 quick, because the categories are then tested twice. + +### Declaration order decides stack slots, and two swapped locals cost a whole function + +MSVC assigns stack slots in declaration order. Two locals declared the wrong way round therefore sit +in each other's slots and, because the slot drives the spill and reload, usually end up in each +other's registers as well. The damage spreads over every instruction that touches either of them, +while `diff_triage.py` still calls the function register-naming only - `assignSelectionToKey` read +95.9% with a `norm` of 1.000. + +`diff_slots.py` is the detector: the same number of slots on both sides with a different use count +per slot. For `assignSelectionToKey` the original spills +`mov [esp+0x18], edi; mov [esp+0x1c], ebx; mov [esp+0x20], esi` and reloads in the same order, so the +local in the lowest slot is declared first. Our source had + +```cpp +int slotID = 0; // -> [esp+0x20] +int tribeIndex = 0; // -> [esp+0x18] +``` + +and swapping the two declarations put both the slots and the registers back: **95.9% -> 100%**, one +line moved. `perm_decls.py` automates the search over a short run of declarations. It also found a +field store that belonged after the declarations in `updatePopularity` (93.2% -> 93.9%), and nothing +on seven other functions - so run it on anything `diff_slots.py` flags, but do not expect a hit +everywhere. + +### `lea` where the original has `add` means a snapshot local the original did not keep + +`field = snapshotLocal + delta` has to preserve the snapshot, so MSVC emits +`lea ecx, [eax + ebp]; mov [field], ecx`. `field = field + delta` lets it update the register that +already caches the field read: `add ebp, eax; mov [field], ebp`. The two differ by one byte per site +and by the register the result lands in, which looks exactly like allocator noise in the diff. + +`updatePopularity` spent the whole pass at 93% on six such sites: + +```cpp +int popularityAfterFear = this->playerDataArray[playerID].popularity; // the original has no such local +... +this->playerDataArray[playerID].popularity = popularityAfterFear + siegePenalty; // -> lea +this->playerDataArray[playerID].popularity = this->playerDataArray[playerID].popularity + siegePenalty; // -> add +``` + +Dropping the local took it to **100%** (and the six `lea`s were also why every jump offset after them +was 6 bytes off). The snapshot was redundant anyway: nothing between the read and the use writes +`popularity`, which is the condition to check before removing one. The original still loads the field +into a register early - that is MSVC hoisting the read, not evidence of a local. + +Note that the sibling line in the same function, `popularity = popularityAfterTax + popularityChange`, +*does* match with its local, because there the original really does keep a separate snapshot. Decide +per site from the `lea`/`add` in the original, not from the shape of the neighbouring code. + +### Two arrays of one struct in a condition: the original reaches the second off a pointer to the first + +`showPopAndGoldPopup` and `createStatsPopUpEntities` both guard their player loop with + +```cpp +if ((currentPlayerFullIDArray[playerID] == -1) && (currentAIArray[playerID] == 0)) { continue; } +``` + +and both sat at 87-89% because MSVC based the loop's induction variable on `currentAIArray` while the +original based it on `currentPlayerFullIDArray` - four instructions, but they are the pointer set-up, +both guard reads and the loop's end compare, so they carry the whole loop with them. No spelling of +the condition moves it: swapping the operands fixes the base and breaks the comparison order, and +nine other forms (nested `if`, De Morgan, casts, `ptr->`, a local for either read) compile identically. + +The decompilation says why. The original walks one pointer and reaches the second array off it: + +```c +_currentPlayer = DAT_GameSynchronyState.currentPlayerFullIDArray + 1; +... +if (*_currentPlayer != -1 || _currentPlayer[0x1b] != 0) { ... } +_currentPlayer = _currentPlayer + 1; +``` + +`0x1b` is the distance between the two arrays in ints. Writing that - a pointer local for the first +array with the second read as `currentPlayerFullID[0x1b]` - took **both functions to 100%**. A pointer +local for the first read *alone*, with the second still by name, changes nothing: both reads have to +go through the one pointer. Keep the magic index, with a comment; it is the only form that matches. + +### Three shared-tail rewrites that the decompilation justifies and that still measure worse + +The decompilation shows a shared tail for all three of these, and reproducing it without `goto` lost +every time. Read them before spending a day on the same idea: + +- `processFoodConsumption` has **one** `processResourceLoss` call with the type in a variable where we + write four calls with literal types. Setting a `ResourceType` and calling once after the loop is + exactly the original's shape and measured **83.7% -> 59.7%**: the extra local swaps the zero + constant and the loop counter between `ebp` and `ebx`, renaming twenty lines. +- `computeBuildingCategoryEntryPointAndDestroyEarlierBuilding` has one `destroyBuilding` call shared by + five arms and one `buildingEntry` read shared by nine. Hoisting both (an `existingBuildingID` + variable plus one `category != CAMPGROUND` re-test) lands within one instruction of the original's + length, 177 against 178, and still loses: the join block stays in the middle, so the alignment does + not recover. +- `resetVariousCountsAndStatisticsAndStartGoodsAndResources` has one `startResources[0xf] = gold * + multiplier` store shared by the human and AI arms. Writing the table value into a local in each arm + so the tails are identical text does not get MSVC to cross-jump them (92.4% -> 91.0%). + +A pointer local is not a general fix for the base anchor either: `PlayerData*` locals leave +`processPeasantSpawnAndDespawnCycle`'s anchor to move with the shared store exactly as before, and in +`spawnMotherOrChild` they remove the three `global - this` slots the original has, taking the frame +further from `sub esp, 0x18` rather than closer. + +### Read the decompilation, not only the disassembly, before calling a function allocator-bound + +Four of the finds above came from `decompile_function`, not from the interleaved reccmp diff, and two +of them were worth 100%. The decompiler names the original's locals and pointers, which is exactly the +information the asm hides. `updateCrowding`'s pointer is anchored at `currentPopulation`, which is +why its base is 0x2100 away from the field it stores to - and writing that pointer out is what took it +to 100% (see *A loop base the original anchors on one field* below). Do not over-read the decompiler's +arithmetic, though: it renders `processFoodConsumption`'s AI branch as `(currentPopulation * 0xb4) / 100`, +but the binary keeps `currentPopulation * 3` in `edi` and multiplies that by 60 (`shl 4; sub; add; add`), +so `(clockSpeed * 60) / 100` with `clockSpeed` as the local is the form that matches. + +## reccmp can score a byte-identical function below 100% + +`renderDebugDataCurrentPlayerData` scores 96.0% and every single one of the 41 diff lines is this: + + -push I::instance+424671 (OFFSET) + +push 0xffffff + +Both sides are the same four bytes. `0xffffff` is opaque white, a colour argument to the text calls, +and reccmp renders it as an address because in the *original* image that value lands inside +BuildingsState; in ours it does not. Verified with `disassemble_function 0x0045A060`, which shows +`PUSH 0xffffff` throughout. The function is byte-identical to the original and no source change can +raise its score. `tools/reimplementation-helper/batch/diff_falsesym.py` finds this class; it is the +only function in GameStateStructures affected, so nothing else below 100% is a tooling artifact. + +The reverse mistake looks the same in the diff and *is* a real bug: an operand that should be an +address, written as a literal in our source. Always confirm against the original disassembly. + +## spawnMotherOrChild: ebx goes to the anchor instead of the loop counter (54.6%, closed) + +The whole gap is one allocator decision. The original keeps `spawnBudget` in `ebx` and the +`playerDataArray` anchor in scratch `edx`, reloading it after calls. Ours does the opposite: the +anchor takes `ebx` (callee-saved, so it survives `spawnUnit` without a reload - arguably better +code) and `spawnBudget` spills, which is the 7th stack slot and the `sub esp, 0x1c` against the +original's `0x18`. Use that frame size as a free oracle: `0x18` means the counter stayed in a +register. + +Measured and ineffective - all four produce a *byte-identical* instruction stream to the current +form, so the shape is canonicalised before allocation: + +* `int buildingID = 0;` before the budget, as the decompilation has it, with an empty `for` init +* `spawnBudget` declared outside the `playerID` loop (a longer live range does not buy a register) +* both of the above +* both, with `buildingID` also at function scope + +Spelling the inner-loop `popularity` read as `this->` instead of `DAT_GameState::instance` *does* +reach the original's `sub esp, 0x18`, because it drops the `0xfffcf0ec` base to one register instead +of two - but that base exists in the original, so the frame matches by compensation and reccmp +measured 54.5%, a slight regression. quick_diff ranked it 0.751 over 0.739; trust reccmp. + +## spawnPoisonCloudsAroundBuilding: the memory decrement is a decrement in each failure branch (100%) + +The original ends its retry loop with a read-modify-write and a fresh compare: + + sub dword ptr [esp + 0x10], 1 + cmp dword ptr [esp + 0x10], 0 + jg + +A `for (...; attemptsLeft > 0; attemptsLeft--)` with two `continue`s compiles to a register load, `sub`, `test` and +store instead, and every spelling of the header (`--x`, `x -= 1`, `0 < x`, `x >= 1`, `short`, a count-up loop) +gives the same or worse. `!= 0` and `>= 0` do give `sub dword ptr`, but fused with its own flags (`jne`/`jns`), not +the separate `cmp`. What matches is a `while (attemptsLeft > 0)` with `attemptsLeft--;` written before **each** +`continue`: the two decrements are cross-jumped into one block, which is the shape the peephole folds into +`sub [mem], 1`, and the loop test then re-reads memory. 92.4% -> 100%. + +## processPeasantSpawnAndDespawnCycle: do not hoist the popularity read (84.0%, closed) + +The original computes `popularity / 500` twice, once per arm. Hoisting it into one local and taking +the shared `vclockIncrement` store - the `processFoodConsumption` fix, applied here - moves the base +anchor from `0x347a4` to `0x36978` and drops the score from 0.92 to 0.68. The duplicated division is +load-bearing: it is what keeps the anchor on `vclockIncrement`. + +## A per-file /Os does not reach the block layout (disproven) + +`cmake/compiler-flags-gl.txt` sets `/GL` per file, so the same mechanism can carry any flag: + + file_dependent_read_list(".../compiler-flags-os.txt" COMPILER_FLAG_OS_FILES) + set_source_files_properties(${COMPILER_FLAG_OS_FILES} PROPERTIES COMPILE_OPTIONS /Os) + +That looked like the way to give `computeBuildingCategoryEntryPointAndDestroyEarlierBuilding` the +original's basic-block layout without the cost a global `/Os` was measured to have. It does not +work. With `/O2 /Os`, and then with `/O2 /O1`, the reccmp diff for that function is identical to +`/O2` alone - all 297 lines, 33.5% / 32.8% every time. The `.obj` hash does change, which is +misleading; it is the command line recorded in the debug section, not the code. MSVC resolves the +trailing size flag to nothing more than `/Os` over `/O2`'s `/Ot`, and that bit does not move this +function's layout. + +So the earlier "`/Os` reproduces the layout" note was a whole-build effect (different inlining +elsewhere), not something a per-file flag can reach. The layout difference - the common tail of the +if/else-if chain laid out after the first arm, which turns the leading `jne` into +0x136 where the +original has +0xb4 and so changes every displacement after it - remains unreachable from the source +or from per-file flags. + +## /GL does nothing for a function that makes no reimplemented member call + +`computeBuildingCategoryEntryPointAndDestroyEarlierBuilding`, +`processPeasantSpawnAndDespawnCycle`, `spawnMotherOrChild`, `spawnPoisonCloudsAroundBuilding` and +`updateCrowding` were never in `cmake/compiler-flags-gl.txt`. Adding all five changes nothing: every +score in the build list is identical to the digit and the average stays at 97.76%. `/GL` earns its +place by removing the redundant `mov ecx, offset` before a call into another reimplemented method, +so it can only pay where such a call exists and the callee's resolver is on. `updateCrowding` has no +calls at all, and the others call out to methods that are not in the build list. It does not +re-roll register allocation inside a function, which is what these five actually need. Do not add +entries to that list speculatively - measure, and leave it out when the number does not move. + +## resetVariousCountsAndStatisticsAndStartGoodsAndResources: a one-byte encoding (92.2%, closed) + +The original loads the current player's slot into `edx`, we use `eax`: + + -mov edx, dword ptr [GameSynchronyState::instance+1089140] imul edx, edx, 0x39f4 + +mov eax, dword ptr [GameSynchronyState::instance+1089140] imul eax, eax, 0x39f4 + +`mov eax, [abs]` is the one-byte-shorter `A1` form, so our version of that line is a byte shorter, +which moves the alignment padding before the `startResources` copy loop (the original pads with a +three-byte `lea esp, [esp]`, we emit `jmp 0x3` over a `lea ecx, [ecx]`) and renames a register in +the `_memset` call set-up. One encoding choice, three diff hunks. Spelling the index as its own +local, taking a `const PlayerData*` to the source player, and reading through `this->` instead of +the global all produce a byte-identical function (the `this->` form measures worse, 0.819 against +0.924). MSVC picks the destination register for a load it is about to overwrite, and the source +cannot name it. + +## The /GS security cookie is a permanent ~4% floor + +`playWAVSFX` (96.2%) and `playSpeechSFX` (96.4%) are finished. Their entire remaining diff is the +`/GS` stack-cookie code that MSVC adds around a function with a large local buffer: + + -mov eax, dword ptr [StructResolver::Instance::instance (DATA)] + +mov eax, dword ptr [__security_cookie (DATA)] + -call + +call __security_check_cookie (FUNCTION) + +Each module gets its own cookie, so the original reads the game's at 0x00B94220 and we read our +DLL's. The `__security_check_cookie` call normalizes away; the cookie *load* does not, which is why +both sit at normalized 96.0% and cannot go higher. Any reimplemented function with a stack buffer +big enough to trigger `/GS` carries the same floor. + +The project already declares the game's cookie - `Globals/MSVC_SecurityCookie.hpp`, address +0x00B94220 - and `src/symbols/data.asm` can publish absolute symbols (`SYM EQU 00B94220h`), so +redirecting the compiler's reference looks like it should work. It does not: + + PUBLIC ___security_cookie + ___security_cookie EQU 00B94220h + + LIBCMT.lib(gs_cookie.obj) : error LNK2005: ___security_cookie already defined in data.asm.obj + +The CRT owns that symbol. Getting past it needs `/FORCE:MULTIPLE` on the whole link, with undefined +symbol selection, and the `OpenSHC.exe` target would then read a cookie at an address that only +exists inside the game's process. Not worth 4% on two functions - but note `/GS-` is *not* the +answer either, because the original has the cookie code and dropping it loses more than it gains. + +`playSFXAtLocation` is likewise done at 98.1% / normalized 100%: its only diff is the call targets +of the CRT helpers `_CIsqrt` and `_ftol2_sse`. + +## A loop base the original anchors on one field: walk a pointer to that field (100%, three functions) + +MSVC strength-reduces a `playerDataArray[playerID].field` loop into one base register plus displacements, and +which field sits at displacement 0 is the anchor discussed above. It cannot be steered while the source indexes +the array, but it **can** be pinned by writing the induction pointer yourself, aimed at the field the decompiler +names (`_currentPopulationAddr = &DAT_GameState.playerDataArray[1].currentPopulation`, `ADJ(...)->field`), and +reaching the other fields by their offset from it: + +```cpp +#define PLAYER_FIELD(type, field) (*(type*)((char*)currentPopulation + offsetof(PlayerData, field) - offsetof(PlayerData, currentPopulation))) + +int* currentPopulation = &this->playerDataArray[1].currentPopulation; +for (...; currentPopulation += sizeof(PlayerData) / sizeof(int)) { PLAYER_FIELD(int, crowding) = 0; ... } +``` + +A `PlayerData*` (or a `PlayerData&` per iteration) is canonicalised back to the indexed form and does not help; +the pointer has to point at the field itself. Once the anchor is pinned, the changes that used to "move the +anchor" become free and the function matches: + +- `updateCrowding` 37.7% -> 100%: with the anchor right, the four per-arm `crowding` stores take their zero + from a register as the original does. It also needed the pointer advance written in both exits (an early + `continue` arm and the end of the body) rather than once in the `for` header, which swapped two registers. +- `processFoodConsumption` 96.8% -> 100%: anchor on `foodClockSpeed`; `leftover` read back from + `foodStorageLevel` instead of a local; `LastLastMonth = LastMonth` copied field to field and compared through + the field (that gives the original's 16-bit `mov cx`); `int playerID = 1;` declared before the pointer, for + the order of the two loop initialisers. The `this` it keeps in `edx` across `updateFoodTypesInStockForAllPlayers` + is LTCG over that callee, which therefore had to be reimplemented (0x00458A70, matched first try) and put in + `cmake/compiler-flags-gl.txt` next to its caller. +- `processPeasantSpawnAndDespawnCycle`: anchored on `vclockIncrement`, the shared store after the increment + chain no longer moves the base, but what is left (two register names, and `x * 8` as `lea` against three + `add`s) still measures below the indexed form in reccmp, so it was not kept. + +Keep the macro local to the .cpp and `#undef` it at the end of the file. + diff --git a/cmake/compiler-flags-gl.txt b/cmake/compiler-flags-gl.txt index 17882af542..0b7dcb9820 100644 --- a/cmake/compiler-flags-gl.txt +++ b/cmake/compiler-flags-gl.txt @@ -20,6 +20,7 @@ src/OpenSHC/Input/MouseState/updateRightDragCameraControl.cpp src/OpenSHC/Text/FontSizeClass/setupFontSizeClassObject.cpp src/OpenSHC/Text/TextManager/setupFontSizeClassObjects.cpp src/OpenSHC/Game/GameStateStructures/updateFoodTypesInStockForAllPlayers.cpp +src/OpenSHC/Game/GameStateStructures/processFoodConsumption.cpp src/OpenSHC/Game/GameStateStructures/clearEnemyRelatedStructures.cpp src/OpenSHC/Game/GameStateStructures/fillWith0xFF.cpp src/OpenSHC/Game/GameStateStructures/computeSignPostEntryData.cpp diff --git a/src/OpenSHC/Game/GameStateStructures/computeBuildingCategoryEntryPointAndDestroyEarlierBuilding.cpp b/src/OpenSHC/Game/GameStateStructures/computeBuildingCategoryEntryPointAndDestroyEarlierBuilding.cpp new file mode 100644 index 0000000000..c6173066f1 --- /dev/null +++ b/src/OpenSHC/Game/GameStateStructures/computeBuildingCategoryEntryPointAndDestroyEarlierBuilding.cpp @@ -0,0 +1,143 @@ +#include "../GameStateStructures.func.hpp" + +#include "OpenSHC/Map/Buildings/BuildingsState.func.hpp" +#include "OpenSHC/Game/Player/Enums/BuildingEntryInfoEnum.hpp" +#include "OpenSHC/Game/Player/PlayerDataBuildingCategoryEnum.hpp" +#include "OpenSHC/UI/Enums/MenuViewType.hpp" + +#include "OpenSHC/Globals/DAT_BuildingsState.hpp" +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" + +namespace OpenSHC { +namespace Game { + + using Player::PlayerDataBuildingCategoryEnum; + using UI::Enums::MenuViewType; + + // FUNCTION: STRONGHOLDCRUSADER 0x00456FD0 + void GameStateStructures::computeBuildingCategoryEntryPointAndDestroyEarlierBuilding( + uint buildingID, int playerID, PlayerDataBuildingCategoryEnum category) + { + int entryX = 0; + int entryY = 0; + DAT_TileMapState::instance.showNoRubbleWhenDestroyingBuilding = 1; + if (category == Player::PDBCE_KEEP) { + if (this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_KEEP].id > 0 + && this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_KEEP].id != buildingID) { + MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::destroyBuilding, DAT_BuildingsState::ptr)( + this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_KEEP].id); + } + short orientation = DAT_BuildingsState::instance.buildings[buildingID].orientation; + entryX = DAT_BuildingsState::instance.buildings[buildingID].x; + entryY = DAT_BuildingsState::instance.buildings[buildingID].y; + if (orientation == 4) { + entryX += 3; + --entryY; + } else if (orientation == 2) { + --entryX; + entryY += 3; + } else if (orientation == 6) { + entryX += 7; + entryY += 3; + } else { + entryX += 3; + entryY += 7; + } + if (DAT_GameCore::instance.currentMenuViewType == UI::Enums::MVT_MAP_EDITOR_LANDSCAPING) { + DAT_TileMapState::instance.showNoRubbleWhenDestroyingBuilding = 1; + if (this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_STOCKPILE].id != 0) { + MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::destroyBuilding, DAT_BuildingsState::ptr)( + this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_STOCKPILE].id); + } + } + } else { + // The original reads the building entrance once for all of these categories and jumps to it, the + // same goes for the destroy call. Writing the read out in every arm (MSVC merges the copies only after + // register allocation) makes buildingID look hot enough to keep in a register: 33.5% instead of 64.0%. + int existingID; + if (category == Player::PDBCE_MARKETPLACE) { + existingID = this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_MARKETPLACE].id; + } else if (category == Player::PDBCE_ENGINEERSGUILD) { + existingID = this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_ENGINEERSGUILD].id; + } else if (category == Player::PDBCE_TUNNELERSGUILD) { + existingID = this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_TUNNELERSGUILD].id; + } else if (category == Player::PDBCE_STOCKPILE) { + // a storage building of this kind already exists, keep the old entry + if (this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_STOCKPILE].id > 0) { + return; + } + goto readEntry; + } else if (category == Player::PDBCE_ARMORY) { + // a storage building of this kind already exists, keep the old entry + if (this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_ARMORY].id > 0) { + return; + } + goto readEntry; + } else if (category == Player::PDBCE_GRANARY) { + // a storage building of this kind already exists, keep the old entry + if (this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_GRANARY].id > 0) { + return; + } + goto readEntry; + } else if (category == Player::PDBCE_BARRACKS) { + existingID = this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_BARRACKS].id; + } else if (category == Player::PDBCE_MERCENARYPOST) { + existingID = this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_MERCENARYPOST].id; + } else if (category == Player::PDBCE_OILSMELTER) { + goto readEntry; + } else if (category == Player::PDBCE_CAMPGROUND) { + short orientation = DAT_BuildingsState::instance.buildings[buildingID].orientation; + entryX = DAT_BuildingsState::instance.buildings[buildingID].x; + entryY = DAT_BuildingsState::instance.buildings[buildingID].y; + if (orientation == 4) { + entryX += 3; + entryY += 6; + } else if (orientation == 2) { + entryY += 3; + } else if (orientation == 6) { + entryX += 6; + entryY += 3; + } else { + entryX += 3; + } + goto checkEntry; + } else { + goto checkEntry; + } + if (existingID > 0) { + MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::destroyBuilding, DAT_BuildingsState::ptr)( + existingID); + } + readEntry: + entryX = DAT_BuildingsState::instance.buildings[buildingID].buildingEntryX; + entryY = DAT_BuildingsState::instance.buildings[buildingID].buildingEntryY; + } + checkEntry: + if (entryX < 0) { + return; + } + if (entryX >= 400) { + return; + } + if (entryY < 0) { + return; + } + if (entryY >= 400) { + return; + } + if (DAT_ViewportRenderState::instance.DAT_BinaryTileMap400x400[entryY * 400 + entryX] != 0) { + int const tile = DAT_ViewportRenderState::instance.translationMatrix[entryY].addXgetTile + entryX; + this->playerDataArray[playerID].buildingEntryInfos[category].id = buildingID; + this->playerDataArray[playerID].buildingEntryInfos[category].yEntry = entryY; + this->playerDataArray[playerID].buildingEntryInfos[category].xEntry = entryX; + this->playerDataArray[playerID].buildingEntryInfos[category].tileEntry = tile; + this->playerDataArray[playerID].buildingEntryInfos[category].areaEntry + = DAT_TileMapState::instance.PathConnectionLayer[tile]; + DAT_TileMapState::instance.showNoRubbleWhenDestroyingBuilding = 0; + } + } + +} +} diff --git a/src/OpenSHC/Game/GameStateStructures/processFoodConsumption.cpp b/src/OpenSHC/Game/GameStateStructures/processFoodConsumption.cpp new file mode 100644 index 0000000000..e16c68505e --- /dev/null +++ b/src/OpenSHC/Game/GameStateStructures/processFoodConsumption.cpp @@ -0,0 +1,166 @@ +#include "../GameStateStructures.func.hpp" + +#include "OpenSHC/Audio/MSS/SoundSystem.func.hpp" +#include "OpenSHC/Audio/SFX/SFXState.func.hpp" +#include "OpenSHC/Game/GameStateStructures.func.hpp" +#include "OpenSHC/Map/Buildings/BuildingsState.func.hpp" +#include "OpenSHC/Synchrony/GameSynchronyState.func.hpp" +#include "OpenSHC/Game/GameMode.hpp" +#include "OpenSHC/Game/GameMode2.hpp" +#include "OpenSHC/Game/Player/Enums/BuildingEntryInfoEnum.hpp" +#include "OpenSHC/Game/Resources/ResourceType.hpp" +#include "OpenSHC/Map/MapType2.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" +#include "OpenSHC/string-literals.hpp" + +#include "OpenSHC/Globals/DAT_BuildingsState.hpp" +#include "OpenSHC/Globals/DAT_CounterFoodWarningInterval.hpp" +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameState.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_MapPropertiesState.hpp" +#include "OpenSHC/Globals/DAT_SFXState.hpp" +#include "OpenSHC/Globals/DAT_SoundSystemState.hpp" + +namespace OpenSHC { +namespace Game { + + using Map::MapType2; + using Resources::ResourceType; + using WindowsHelper::Enums::BOOLEnum; + + // The original walks a pointer to foodClockSpeed and reaches every other PlayerData field by its distance from it. + // Indexing playerDataArray[playerID] instead makes MSVC base the loop on another field, which shifts every + // displacement, and reading foodStorageLevel back from the field (as the original does) then costs 20 points. +#define PLAYER_FIELD(type, field) \ + (*(type*)((char*)foodClockSpeed + offsetof(PlayerData, field) - offsetof(PlayerData, foodClockSpeed))) + + // FUNCTION: STRONGHOLDCRUSADER 0x00458AD0 + void GameStateStructures::processFoodConsumption() + { + if (DAT_GameCore::instance.gameMode_2 == GM_EDITOR) { + return; + } + if (DAT_GameCore::instance.gameMode_2 == GM_SIEGE_THAT) { + return; + } + if (DAT_GameCore::instance.gameMode_2 == GM_BUILDERUnk + && DAT_MapPropertiesState::instance.SEC_U3_MapType2_1 == Map::MT_SIEGE) { + return; + } + MACRO_CALL_MEMBER(GameStateStructures_Func::updateFoodTypesInStockForAllPlayers, this)(); + int playerID = 1; + int* foodClockSpeed = &this->playerDataArray[1].foodClockSpeed; + for (; playerID < 9; ++playerID, foodClockSpeed += sizeof(PlayerData) / sizeof(int)) { + if (PLAYER_FIELD(int, buildingEntryInfos[Player::Enums::BEIE_KEEP].id) <= 0 + || PLAYER_FIELD(int, buildingEntryInfos[Player::Enums::BEIE_CAMPGROUND].id) <= 0) { + continue; + } + PLAYER_FIELD(int, foodStorageLevel) = -1; + if (PLAYER_FIELD(int, foodTypesInStock) <= 0) { + PLAYER_FIELD(int, foodTypesCurrentlyEaten) = 0; + continue; + } + int clockSpeed = PLAYER_FIELD(int, currentPopulation) * 3; + PLAYER_FIELD(int, foodClockSpeed) = clockSpeed; + if (DAT_GameSynchronyState::instance.currentGameMode != GM_SOLITARY + && MACRO_CALL_MEMBER(Synchrony::GameSynchronyState_Func::isAIPlayer, DAT_GameSynchronyState::ptr)( + playerID) + != FALSE) { + PLAYER_FIELD(int, foodClockSpeed) = (clockSpeed * 60) / 100; + } + switch (PLAYER_FIELD(int, rationsSetting)) { + case 0: + PLAYER_FIELD(int, foodClockSpeed) = 0; + PLAYER_FIELD(int, foodTypesCurrentlyEaten) = 0; + break; + case 1: + PLAYER_FIELD(int, foodClockSpeed) = PLAYER_FIELD(int, foodClockSpeed) / 2; + break; + case 3: + PLAYER_FIELD(int, foodClockSpeed) = (PLAYER_FIELD(int, foodClockSpeed) * 3) / 2; + break; + case 4: + PLAYER_FIELD(int, foodClockSpeed) = PLAYER_FIELD(int, foodClockSpeed) * 2; + } + if (PLAYER_FIELD(int, foodClockSpeed) != 0) { + PLAYER_FIELD(int, foodStorageLevel) + = ((15000 / PLAYER_FIELD(int, foodClockSpeed)) * PLAYER_FIELD(int, totalFood)) / 800; + } + if (DAT_GameState::instance.mapAndTime.monthChanged != 0) { + short leftover = (short)PLAYER_FIELD(int, foodStorageLevel); + PLAYER_FIELD(short, foodStorageLevelLastLastMonth) = PLAYER_FIELD(short, foodStorageLevelLastMonth); + PLAYER_FIELD(short, foodStorageLevelLastMonth) = leftover; + if (playerID == DAT_GameSynchronyState::instance.currentPlayerSlotID + && DAT_GameState::instance.mapAndTime.singlePlayerHasKeepAndGranary != FALSE) { + if (PLAYER_FIELD(int, totalFood) == 0) { + if (DAT_CounterFoodWarningInterval::instance == 0 + && MACRO_CALL_MEMBER( + Audio::MSS::SoundSystem_Func::shouldSoundXNotBePlaying, DAT_SoundSystemState::ptr)() + == FALSE) { + // "No food distributed this month" + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playWAVSFX, DAT_SFXState::ptr)( + s_food_warning4_wav_005a509c); + } + ++DAT_CounterFoodWarningInterval::instance; + if (DAT_CounterFoodWarningInterval::instance > 2) { + DAT_CounterFoodWarningInterval::instance = 0; + } + } else if (leftover < 2 && leftover != PLAYER_FIELD(short, foodStorageLevelLastLastMonth) + && PLAYER_FIELD(int, rationsSetting) != 0) { + if (leftover == 1) { + if (MACRO_CALL_MEMBER( + Audio::MSS::SoundSystem_Func::shouldSoundXNotBePlaying, DAT_SoundSystemState::ptr)() + == FALSE) { + // "Granary stocks are very low sire" + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playWAVSFX, DAT_SFXState::ptr)( + s_food_warning2_wav_005a5088); + } + } else if (MACRO_CALL_MEMBER(Audio::MSS::SoundSystem_Func::shouldSoundXNotBePlaying, + DAT_SoundSystemState::ptr)() + == FALSE) { + // "We are almost out of food sire" + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playWAVSFX, DAT_SFXState::ptr)( + s_food_warning3_wav_005a5074); + } + } + } + } + PLAYER_FIELD(int, foodClock) += PLAYER_FIELD(int, foodClockSpeed); + if (PLAYER_FIELD(int, foodClock) > 15000) { + PLAYER_FIELD(int, foodClock) = 0; + PLAYER_FIELD(int, foodTypesCurrentlyEaten) = PLAYER_FIELD(int, foodTypesInStock); + for (;;) { + ++PLAYER_FIELD(int, foodTypeToBeEatenNext); + if (PLAYER_FIELD(int, foodTypeToBeEatenNext) > 3) { + PLAYER_FIELD(int, foodTypeToBeEatenNext) = 0; + } + if (PLAYER_FIELD(int, foodTypeToBeEatenNext) == 0 && PLAYER_FIELD(int, breadCount) > 0) { + MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::processResourceLoss, + DAT_BuildingsState::ptr)(playerID, Resources::RT_BREAD, 1, 0); + break; + } + if (PLAYER_FIELD(int, foodTypeToBeEatenNext) == 1 && PLAYER_FIELD(int, cheeseCount) > 0) { + MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::processResourceLoss, + DAT_BuildingsState::ptr)(playerID, Resources::RT_CHEESE, 1, 0); + break; + } + if (PLAYER_FIELD(int, foodTypeToBeEatenNext) == 2 && PLAYER_FIELD(int, meatCount) > 0) { + MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::processResourceLoss, + DAT_BuildingsState::ptr)(playerID, Resources::RT_MEAT, 1, 0); + break; + } + if (PLAYER_FIELD(int, foodTypeToBeEatenNext) == 3 && PLAYER_FIELD(int, appleCount) > 0) { + MACRO_CALL_MEMBER(Map::Buildings::BuildingsState_Func::processResourceLoss, + DAT_BuildingsState::ptr)(playerID, Resources::RT_APPLE, 1, 0); + break; + } + } + } + } + } + +#undef PLAYER_FIELD + +} +} diff --git a/src/OpenSHC/Game/GameStateStructures/processPeasantSpawnAndDespawnCycle.cpp b/src/OpenSHC/Game/GameStateStructures/processPeasantSpawnAndDespawnCycle.cpp new file mode 100644 index 0000000000..0547275559 --- /dev/null +++ b/src/OpenSHC/Game/GameStateStructures/processPeasantSpawnAndDespawnCycle.cpp @@ -0,0 +1,138 @@ +#include "../GameStateStructures.func.hpp" + +#include "OpenSHC/Audio/MSS/SoundSystem.func.hpp" +#include "OpenSHC/Audio/SFX/SFXState.func.hpp" +#include "OpenSHC/Game/GameStateStructures.func.hpp" +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/UI/Helpers.func.hpp" +#include "OpenSHC/Audio/SFX/SpeechEffectID.hpp" +#include "OpenSHC/Game/GameMode.hpp" +#include "OpenSHC/Game/GameMode2.hpp" +#include "OpenSHC/Game/Player/Enums/BuildingEntryInfoEnum.hpp" +#include "OpenSHC/Map/Buildings/BuildingType.hpp" +#include "OpenSHC/Map/MapType2.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" +#include "OpenSHC/WindowsHelper/Enums/BOOLEnum.hpp" + +#include "OpenSHC/Globals/DAT_BuildingsState.hpp" +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_MapPropertiesState.hpp" +#include "OpenSHC/Globals/DAT_SFXState.hpp" +#include "OpenSHC/Globals/DAT_SoundSystemState.hpp" +#include "OpenSHC/Globals/DAT_TroopDefinedData.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" + +namespace OpenSHC { +namespace Game { + + using Audio::SFX::SpeechEffectID; + using Map::MapType2; + using Map::Buildings::BuildingType; + using Map::Units::UnitType; + using WindowsHelper::Enums::BOOLEnum; + + // FUNCTION: STRONGHOLDCRUSADER 0x0045B4A0 + void GameStateStructures::processPeasantSpawnAndDespawnCycle() + { + // handle peasant (de)spawning + if (DAT_GameCore::instance.gameMode_2 == GM_BUILDERUnk + && DAT_MapPropertiesState::instance.SEC_U3_MapType2_1 == Map::MT_SIEGE) { + return; + } + for (int playerID = 1; playerID < 9; ++playerID) { + if (this->playerDataArray[playerID].lordKilledByPlayerID != 0) { + continue; + } + if (this->playerDataArray[playerID].playerDeathRelated != 0 + && DAT_GameSynchronyState::instance.currentGameMode == GM_SOLITARY) { + continue; + } + if (DAT_GameSynchronyState::instance.currentGameMode != GM_SOLITARY) { + this->playerDataArray[playerID].vclockIncrement + = DAT_TroopDefinedData::instance + .PeasantSpawnClockIncrementSkirmish[this->playerDataArray[playerID].popularity / 500]; + } else { + int popularityIndex = this->playerDataArray[playerID].popularity / 500; + if (this->playerDataArray[playerID].currentPopulation > 100) { + this->playerDataArray[playerID].vclockIncrement + = DAT_TroopDefinedData::instance + .PeasantSpawnClockIncrementSolitaryPopMoreThan100[popularityIndex]; + } else { + this->playerDataArray[playerID].vclockIncrement + = DAT_TroopDefinedData::instance + .PeasantSpawnClockIncrementSolitaryPopLessThan101[popularityIndex]; + } + } + this->playerDataArray[playerID].vclock + = this->playerDataArray[playerID].vclockIncrement + this->playerDataArray[playerID].vclock; + if (this->playerDataArray[playerID].vclock >= 4000) { + this->playerDataArray[playerID].vclock = 4000; + } else if (this->playerDataArray[playerID].vclock < 0) { + this->playerDataArray[playerID].vclock = 0; + } + if (this->playerDataArray[playerID].vclockIncrement == 0) { + this->playerDataArray[playerID].vclock = 2000; + } + if (this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_KEEP].id <= 0) { + continue; + } + int campgroundID = this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_CAMPGROUND].id; + if (campgroundID <= 0) { + continue; + } + if (this->playerDataArray[playerID].vclock >= 4000) { + if (this->playerDataArray[playerID].currentPopulation < this->playerDataArray[playerID].populationCap + && this->playerDataArray[playerID].availablePeasantsOrHousedPeasants < 24) { + // Havent reached peasant limit. + int x = this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_CAMPGROUND].xEntry; + int y = this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_CAMPGROUND].yEntry; + this->playerDataArray[playerID].vclock = 2000; + int peasantUnitID = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::spawnUnit, DAT_UnitsState::ptr)( + playerID, playerID, x * 8, y * 8, + DAT_BuildingsState::instance.buildings[campgroundID].terrainHeightUnk, Map::Units::UT_PEASANT); + if (peasantUnitID != 0) { + // Successfully spawned peasant. + DAT_UnitsState::instance.units[peasantUnitID].animationCycleNumber + = DAT_UnitsState::instance.units[peasantUnitID].fixedRng & 0xf; + DAT_UnitsState::instance.units[peasantUnitID].isDisappearingUnk = 1; + if (DAT_GameCore::instance.gameMode_2 == GM_CRUSADER_TUTORIAL) { + MACRO_CALL(UI::Helpers_Func::SetTutorialBuildingActionState)(9, Map::Buildings::BT_HOVEL); + } + } + if (this->playerDataArray[playerID].field_0x42 == 1) { + this->playerDataArray[playerID].field_0x42 = 0; + if (playerID == DAT_GameSynchronyState::instance.currentPlayerSlotID + && MACRO_CALL_MEMBER( + Audio::MSS::SoundSystem_Func::shouldSoundXNotBePlaying, DAT_SoundSystemState::ptr)() + == FALSE) { + // people are coming to the castle + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSpeechSFX, DAT_SFXState::ptr)( + Audio::SFX::SEID_POP_IMMIGRATE); + } + } + } + } else if (this->playerDataArray[playerID].vclock <= 0 + && this->playerDataArray[playerID].availablePeasantsOrHousedPeasants + + this->playerDataArray[playerID].populationRelatedCrowdingCountUnk + > 4) { + this->playerDataArray[playerID].vclock = 2000; + // let a peasant disappear? + MACRO_CALL_MEMBER(GameStateStructures_Func::despawnPeasantOrWorker, this)(playerID); + if (this->playerDataArray[playerID].field_0x42 == 0) { + this->playerDataArray[playerID].field_0x42 = 1; + if (playerID == DAT_GameSynchronyState::instance.currentPlayerSlotID + && MACRO_CALL_MEMBER( + Audio::MSS::SoundSystem_Func::shouldSoundXNotBePlaying, DAT_SoundSystemState::ptr)() + == FALSE) { + // sound is probably about peasants leaving the castle + MACRO_CALL_MEMBER(Audio::SFX::SFXState_Func::playSpeechSFX, DAT_SFXState::ptr)( + Audio::SFX::SEID_POP_EMIGRATE); + } + } + } + } + } + +} +} diff --git a/src/OpenSHC/Game/GameStateStructures/spawnMotherOrChild.cpp b/src/OpenSHC/Game/GameStateStructures/spawnMotherOrChild.cpp new file mode 100644 index 0000000000..62adf01142 --- /dev/null +++ b/src/OpenSHC/Game/GameStateStructures/spawnMotherOrChild.cpp @@ -0,0 +1,145 @@ +#include "../GameStateStructures.func.hpp" + +#include "OpenSHC/Map/Units/UnitsState.func.hpp" +#include "OpenSHC/Game/GameMode.hpp" +#include "OpenSHC/Game/GameMode2.hpp" +#include "OpenSHC/Game/Player/Enums/BuildingEntryInfoEnum.hpp" +#include "OpenSHC/Map/Buildings/BuildingLogicalState.hpp" +#include "OpenSHC/Map/Buildings/BuildingType.hpp" +#include "OpenSHC/Map/Units/UnitType.hpp" + +#include "OpenSHC/Globals/DAT_BuildingsState.hpp" +#include "OpenSHC/Globals/DAT_GameCore.hpp" +#include "OpenSHC/Globals/DAT_GameState.hpp" +#include "OpenSHC/Globals/DAT_GameSynchronyState.hpp" +#include "OpenSHC/Globals/DAT_TileMapState.hpp" +#include "OpenSHC/Globals/DAT_UnitsState.hpp" +#include "OpenSHC/Globals/DAT_ViewportRenderState.hpp" + +namespace OpenSHC { +namespace Game { + + using Map::Buildings::BuildingLogicalState; + using Map::Buildings::BuildingType; + using Map::Units::UnitType; + + // FUNCTION: STRONGHOLDCRUSADER 0x00458280 + void GameStateStructures::spawnMotherOrChild() + { + if (DAT_GameCore::instance.gameMode_2 == GM_EDITOR) { + return; + } + if (DAT_GameCore::instance.gameMode_2 == GM_SIEGE_THAT) { + return; + } + for (int playerID = 1; playerID < 9; ++playerID) { + // if has keep and campground + if (this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_KEEP].id <= 0 + || this->playerDataArray[playerID].buildingEntryInfos[Player::Enums::BEIE_CAMPGROUND].id <= 0) { + continue; + } + // Only spawn in non-multiplayer + if (DAT_GameSynchronyState::instance.currentGameMode == GM_SKIRMISH_SINGLE_PLAYER) { + if (DAT_GameState::instance.playerDataArray[playerID].someCount46 != 0) { + // if total enemy troop value < 101 + if (DAT_GameState::instance.playerDataArray[playerID].totalEnemyTroopValue > 100) { + DAT_GameState::instance.playerDataArray[playerID].someCount46 = 0; + continue; + } + } else { + // if total enemy troop value < 41 + if (DAT_GameState::instance.playerDataArray[playerID].totalEnemyTroopValue > 40) { + continue; + } + DAT_GameState::instance.playerDataArray[playerID].someCount46 = 1; + } + } else if (this->playerDataArray[playerID].sumOfTotalEnemyUnitsCount > 0) { + continue; + } + int spawnBudget + = (75 - this->playerDataArray[playerID].someCount03) - this->playerDataArray[playerID].someCount02; + for (int buildingID = 0; buildingID < DAT_BuildingsState::instance.maxBuildingsCount; ++buildingID) { + if (DAT_BuildingsState::instance.buildings[buildingID].logicalState == (BuildingLogicalState)0 + || DAT_BuildingsState::instance.buildings[buildingID].logicalState == Map::Buildings::BLS_REMOVE + || DAT_BuildingsState::instance.buildings[buildingID].owner != playerID + || DAT_BuildingsState::instance.buildings[buildingID].fireDuration != 0 + || (DAT_BuildingsState::instance.buildings[buildingID].buildingType != Map::Buildings::BT_HOVEL + && DAT_BuildingsState::instance.buildings[buildingID].buildingType + != Map::Buildings::BT_HOUSE)) { + continue; + } + if (spawnBudget <= 0) { + break; + } + // if building has no unit + if (DAT_BuildingsState::instance.buildings[buildingID].unitRefID == 0) { + short motherEntryX = DAT_BuildingsState::instance.buildings[buildingID].buildingEntryX; + if (motherEntryX > 0) { + short motherEntryY = DAT_BuildingsState::instance.buildings[buildingID].buildingEntryY; + if (motherEntryY > 0) { + int motherTile + = DAT_ViewportRenderState::instance.translationMatrix[motherEntryY].addXgetTile + + motherEntryX; + int motherUnitID = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::spawnUnit, + DAT_UnitsState::ptr)(playerID, playerID, motherEntryX * 8, motherEntryY * 8, + DAT_TileMapState::instance.HeightLayer[motherTile], Map::Units::UT_MOTHER); + if (motherUnitID != 0) { + // store in unitRef + DAT_BuildingsState::instance.buildings[buildingID].unitRefID = (short)motherUnitID; + DAT_BuildingsState::instance.buildings[buildingID].unitRefUID + = DAT_UnitsState::instance.units[motherUnitID].uid; + DAT_UnitsState::instance.units[motherUnitID].workplaceBuildingUID + = DAT_BuildingsState::instance.buildings[buildingID].uid; + DAT_UnitsState::instance.units[motherUnitID].workplaceBuildingID_1 = (short)buildingID; + --spawnBudget; + DAT_BuildingsState::instance.buildings[buildingID].childSpawnCountdown + = (char)((DAT_BuildingsState::instance.buildings[buildingID].fireRelatedRNG1 >> 10) + % 3) + + 1; + } + } + } + } else if (DAT_GameState::instance.playerDataArray[playerID].popularity / 100 >= 50) { + // if popularity is higher than 49 + --DAT_BuildingsState::instance.buildings[buildingID].childSpawnCountdown; + if (DAT_BuildingsState::instance.buildings[buildingID].childSpawnCountdown <= 0 + && DAT_BuildingsState::instance.buildings[buildingID].maxOccupants + != DAT_BuildingsState::instance.buildings[buildingID].currentEmployeeCount) { + short childEntryX = DAT_BuildingsState::instance.buildings[buildingID].buildingEntryX; + DAT_BuildingsState::instance.buildings[buildingID].childSpawnCountdown + = (char)((DAT_BuildingsState::instance.buildings[buildingID].fireRelatedRNG1 >> 10) % 3) + + 1; + if (childEntryX > 0) { + short childEntryY = DAT_BuildingsState::instance.buildings[buildingID].buildingEntryY; + if (childEntryY > 0) { + int childTile + = DAT_ViewportRenderState::instance.translationMatrix[childEntryY].addXgetTile + + childEntryX; + int childUnitID = MACRO_CALL_MEMBER(Map::Units::UnitsState_Func::spawnUnit, + DAT_UnitsState::ptr)(playerID, playerID, childEntryX * 8, childEntryY * 8, + DAT_TileMapState::instance.HeightLayer[childTile], Map::Units::UT_CHILD); + if (childUnitID != 0) { + --spawnBudget; + DAT_BuildingsState::instance.buildings[buildingID] + .workerID[DAT_BuildingsState::instance.buildings[buildingID] + .currentEmployeeCount] = (short)childUnitID; + DAT_BuildingsState::instance.buildings[buildingID].workerUID + [DAT_BuildingsState::instance.buildings[buildingID].currentEmployeeCount] + = DAT_UnitsState::instance.units[childUnitID].uid; + int workplaceUID = DAT_BuildingsState::instance.buildings[buildingID].uid; + // increment currentEmployeeCount of building + ++DAT_BuildingsState::instance.buildings[buildingID].currentEmployeeCount; + DAT_UnitsState::instance.units[childUnitID].workplaceBuildingID_1 + = (short)buildingID; + DAT_UnitsState::instance.units[childUnitID].workplaceBuildingUID = workplaceUID; + } + } + } + } + } + } + } + } + +} +} diff --git a/src/OpenSHC/Game/GameStateStructures/updateCrowding.cpp b/src/OpenSHC/Game/GameStateStructures/updateCrowding.cpp new file mode 100644 index 0000000000..fa9e0f688d --- /dev/null +++ b/src/OpenSHC/Game/GameStateStructures/updateCrowding.cpp @@ -0,0 +1,38 @@ +#include "../GameStateStructures.func.hpp" + +namespace OpenSHC { +namespace Game { + + // The original walks a pointer to currentPopulation and reaches the other PlayerData fields by their distance + // from it. Indexing playerDataArray[playerID] instead makes MSVC base the loop on populationCap. +#define PLAYER_FIELD(type, field) \ + (*(type*)((char*)currentPopulation + offsetof(PlayerData, field) - offsetof(PlayerData, currentPopulation))) + + // FUNCTION: STRONGHOLDCRUSADER 0x00458E60 + void GameStateStructures::updateCrowding() + { + int* currentPopulation = &this->playerDataArray[1].currentPopulation; + for (int playerID = 1; playerID != 9; ++playerID) { + int populationCap = PLAYER_FIELD(int, populationCap); + int population = PLAYER_FIELD(int, currentPopulation); + // The pointer advance is written in both exits: with it in the loop header MSVC swaps two registers. + if (population <= populationCap) { + PLAYER_FIELD(int, crowding) = 0; + currentPopulation += sizeof(PlayerData) / sizeof(int); + continue; + } + if (population <= 0) { + PLAYER_FIELD(int, crowding) = 0; + } else if (populationCap <= 0) { + PLAYER_FIELD(int, crowding) = 150; + } else { + PLAYER_FIELD(int, crowding) = (population * 100) / populationCap; + } + currentPopulation += sizeof(PlayerData) / sizeof(int); + } + } + +#undef PLAYER_FIELD + +} +} diff --git a/status/addresses-SHC-3BB0A8C1.txt b/status/addresses-SHC-3BB0A8C1.txt index 47b2ecfdf6..ba05a65068 100644 --- a/status/addresses-SHC-3BB0A8C1.txt +++ b/status/addresses-SHC-3BB0A8C1.txt @@ -17155,7 +17155,7 @@ SHC_3BB0A8C1_0x00456C50 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00456EF0 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00456FD0 | 0.0% | Pending +SHC_3BB0A8C1_0x00456FD0 | 84.8% | this/entry ptr ebx-ebp swap SHC_3BB0A8C1_0x004572A0 | 100.0% | Reimplemented @@ -17685,7 +17685,7 @@ SHC_3BB0A8C1_0x004580C0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x004580F0 | 0.0% | Pending -SHC_3BB0A8C1_0x00458280 | 0.0% | Pending +SHC_3BB0A8C1_0x00458280 | 54.6% | Budget spilled, base in EBX SHC_3BB0A8C1_0x00458360 | 0.0% | Pending @@ -17733,7 +17733,7 @@ SHC_3BB0A8C1_0x00458A70 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00458A80 | 0.0% | Pending -SHC_3BB0A8C1_0x00458AD0 | 0.0% | Pending +SHC_3BB0A8C1_0x00458AD0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00458D38 | 0.0% | Pending @@ -17749,7 +17749,7 @@ SHC_3BB0A8C1_0x00458D50 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00458E20 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x00458E60 | 0.0% | Pending +SHC_3BB0A8C1_0x00458E60 | 100.0% | Reimplemented SHC_3BB0A8C1_0x00458EC0 | 100.0% | Reimplemented @@ -18037,7 +18037,7 @@ SHC_3BB0A8C1_0x0045B3E0 | 100.0% | Reimplemented SHC_3BB0A8C1_0x0045B460 | 100.0% | Reimplemented -SHC_3BB0A8C1_0x0045B4A0 | 0.0% | Pending +SHC_3BB0A8C1_0x0045B4A0 | 85.3% | orig keeps increment in a reg SHC_3BB0A8C1_0x0045B6B0 | 100.0% | Reimplemented diff --git a/tools/reimplementation-helper/batch/README.md b/tools/reimplementation-helper/batch/README.md index b6e5ef8793..daafe756e2 100644 --- a/tools/reimplementation-helper/batch/README.md +++ b/tools/reimplementation-helper/batch/README.md @@ -44,7 +44,7 @@ functions and the traps - is in [../../compiler-internals/finding-mismatches.md] | `diff_anchor.py [--run] [NAME]` | Functions whose struct/loop base anchor differs from the original's (`lea esi, [ecx + 0x367e4]` against a different constant). Every displacement in the function then differs while the opcodes still line up, which reads as allocator noise - it is the whole gap between 83.7% and 61.7% on `processFoodConsumption`. The delta is the distance between the two fields MSVC chose; the decompilation names the original's as the pointer it starts the loop with. | | `diff_lea.py [--run] [NAME]` | `lea reg, [a + b]` on our side where the original has the destructive `add a, b`: `field = snapshotLocal + delta` has to keep the snapshot, `field = field + delta` updates the cached read in place. Drop the local when nothing between the read and the use writes the field - that was `updatePopularity`'s last 6.1%. `RLEA` is the reverse, a local the original keeps and we do not. | | `diff_signed.py [NAME-SUBSTRING]` | Comparisons the original makes signed and we make unsigned (or the reverse): `jg/jge/jl/jle` against our `ja/jae/jb/jbe` over the same `cmp`. Fix it by comparing through `(int)` in the source, not by editing the generated header, and re-run the tool to confirm - one instruction barely moves the percentage. | -| `quick_diff.py FILE.cpp... [-q] [--name FUNCTION]` | Compile one file with `/FA` and diff it against the original function disassembled straight from `_original/` - about 6 seconds, no link and no reccmp, so a dozen source variants can be tried in the time of one build. Handles free functions (the mangled scope is the innermost namespace), x87 operand spellings (`fmulp ST(2), ST(0)` vs `fmulp st(2)`, `__real@` constants) and indexed local-array slots (`_arr$[esp+edi*8+112]`); before those three fixes every floating-point instruction and every local-array element access on our side mismatched and `structural_diff.py` reported duplicates that did not exist. Shows the whole original function, which reccmp's diff does not when ours is shorter. A triage loop: confirm a 1.0 with `reccmp_report.py --run`, and do not trust a *rise* of its ratio below about 0.6 - on a badly matching function difflib rewards a different alignment, and one such "gain" was a 10-point loss in reccmp. | +| `quick_diff.py FILE.cpp... [-q] [--structural] [--name FUNCTION]` | Compile one file with `/FA` and diff it against the original function disassembled straight from `_original/` - about 6 seconds, no link and no reccmp, so a dozen source variants can be tried in the time of one build. Handles free functions (the mangled scope is the innermost namespace), x87 operand spellings (`fmulp ST(2), ST(0)` vs `fmulp st(2)`, `__real@` constants) and indexed local-array slots (`_arr$[esp+edi*8+112]`); before those three fixes every floating-point instruction and every local-array element access on our side mismatched and `structural_diff.py` reported duplicates that did not exist. Shows the whole original function, which reccmp's diff does not when ours is shorter. A triage loop: confirm a 1.0 with `reccmp_report.py --run`, and do not trust a *rise* of its ratio below about 0.6 - on a badly matching function difflib rewards a different alignment, and one such "gain" was a 10-point loss in reccmp. `--structural` adds `structural_diff.py`'s `kind`/`shape`/`delta` for the same compile, lists the mismatched mnemonics (`add 12/13` is original/ours), and prints the diff on register- and constant-anonymised lines; unlike `structural_diff.py` it takes any file, not only the build list. | | `quick_gl.py FILE.cpp [CALLEE.cpp...] [-q] [-s]` | `quick_diff.py` for a file in `cmake/compiler-flags-gl.txt`: compiles it with `/GL` and LTCG-links it into a throw-away DLL with the `/GL` objects of the callees it calls through `X_Func::` (found in the build list and the GL list), then diffs the function against the original. quick_diff strips `/GL`, so it cannot show an `ecx`/`edx` kept across a call; this does, in about 6 seconds. Needs a full build first (for the callee objects) and the callees' resolvers enabled (`enable_local_functions.py`). `aiFindBuildingToAttack` reads 0.7027 in quick_diff and 1.0000 here, as in reccmp. | | `push_pattern.py FILE.cpp...` | Per call, the argument-push run as `pushes/interleaved` for both sides. A neat run (`0` interleaved) means every argument was already in a register or slot, i.e. the source had a **local**; a mixed run is what writing the expression inline at the call produces. A starred row is a call where the two sides disagree - add the local, or drop it, accordingly. Counts only calls whose set-up it can see, so a differing call *total* means our source has an extra call (a duplicated block), not that the tool failed. | | `perm_decls.py FILE FIRST LAST` | Permute one short run of declarations and keep the order that matches best, scored by `quick_diff.py -s`. Declaration order does **not** decide stack slots - the colorer sorts by reference weight per byte and leaves only *ties* to the order the symbols arrive in, so this pays exactly when two locals of equal weight are declared the wrong way round (`assignSelectionToKey` 95.9% -> 100% from one swapped line) and does nothing otherwise. Run `slot_weight.py` first to see whether the weights tie at all. For initialised declarations the order does decide which *register* each one gets, which is a separate effect worth permuting for. | @@ -58,7 +58,7 @@ functions and the traps - is in [../../compiler-internals/finding-mismatches.md] | `rank_functions.py [filter] [--top N]` | Rank by source lines x (1 - match), so the big badly-matching functions come first instead of the small ones with a low percentage. | | `scan_dispatch.py [filter]` | Functions whose dispatch form disagrees with the original (jump table on one side, if/else-if chain on the other), and which way to fix each. | | `scan_chains.py [filter] [--min N]` | `if/else if` chains comparing one expression against several constants: the candidates to convert when `scan_dispatch.py` says the original has a table we do not. | -| `quick_styles.py FUNC [-s] [style...]` | `try_styles.py` scored by `quick_diff.py` instead of a build: about a second per variant against roughly half a minute for an incremental build plus a reccmp run, so a dozen source forms cost less than one build cycle. Same variant directory (`build-RelWithDebInfo/batch/variants/FUNC/*.cpp`), same table, same winner-restore; `-s` keeps `[esp + N]` offsets, for declaration order. It never touches the source list or the DLL, so it leaves no stale `diff.json` behind. The score is difflib's ratio, not the reccmp percentage - rank the forms here, then confirm the winner with `reccmp_report.py --run`, and mind `quick_diff`'s warning about ratio rises below about 0.6. | +| `quick_styles.py FUNC [-s] [--structural] [style...]` | `try_styles.py` scored by `quick_diff.py` instead of a build: about a second per variant against roughly half a minute for an incremental build plus a reccmp run, so a dozen source forms cost less than one build cycle. Same variant directory (`build-RelWithDebInfo/batch/variants/FUNC/*.cpp`), same table, same winner-restore; `-s` keeps `[esp + N]` offsets, for declaration order. It never touches the source list or the DLL, so it leaves no stale `diff.json` behind. The score is difflib's ratio, not the reccmp percentage - rank the forms here, then confirm the winner with `reccmp_report.py --run`, and mind `quick_diff`'s warning about ratio rises below about 0.6. `--structural` ranks by fewest mismatched mnemonics, then `kind`, then the ratio: on `processPeasantSpawnAndDespawnCycle` the plain ratio preferred the old form (94.2, delta 7) over the committed one (82.9, delta 2), which is the wrong way round once structure is what you are fixing. | | `try_styles.py FUNC [style...]` | Compile and measure several hand-written variants of one function, restore the winner, print the table. Variants live in `build-RelWithDebInfo/batch/variants/FUNC/*.cpp`. | ### Readability passes diff --git a/tools/reimplementation-helper/batch/diff_falsesym.py b/tools/reimplementation-helper/batch/diff_falsesym.py new file mode 100644 index 0000000000..590611a384 --- /dev/null +++ b/tools/reimplementation-helper/batch/diff_falsesym.py @@ -0,0 +1,99 @@ +"""Find diff lines that are only a reccmp *symbolization* difference, not a codegen difference. + +usage: diff_falsesym.py [--run] [NAME-SUBSTRING] + +reccmp compares the symbolized disassembly text, so it renders an operand as `SYMBOL+N (OFFSET)` +whenever the value happens to land inside a known object. A plain integer constant that is large +enough can land inside one by coincidence - and because the two images lay their data out +differently, it lands inside an object in the original and not in ours. The same instruction then +reads as a mismatch: + + -push I::instance+424671 (OFFSET) + +push 0xffffff + +Those two lines are the same four bytes. `0xffffff` is opaque white, a colour argument to a text +call, and it sits inside BuildingsState in the original image only. This was the *entire* remaining +gap of `renderDebugDataCurrentPlayerData`: 41 lines, all of them that one constant, scoring 96.0% +for code that is byte-identical to the original. + +FALSESYM pairs an orig line carrying a symbol with a recomp line carrying a bare immediate when the +mnemonic and the rest of the operands are identical. It cannot prove the bytes match - it does not +know the object's base address - so confirm each hit by disassembling the original: + + ghidra-mcp disassemble_function # or tools/.../orig_asm.py + +and checking that the original really is a plain immediate. If it is, the function is finished and +no source change can raise its score; record it rather than chasing it. Beware the reverse mistake +too: a constant that *should* be an address, spelled as a literal in our source, produces the same +diff and is a real bug. + +--run re-runs reccmp first (otherwise reccmp/dll/diff.json from the last run is used). +""" + +import re +import sys + +import common + +IMM_RE = re.compile(r"^(0x[0-9a-f]+|\d+)$") +SYM_RE = re.compile(r"[A-Za-z_<>:]") + + +def op(line): + return line.split("\t")[0].strip() + + +def split(line): + parts = line.split(None, 1) + return (parts[0], parts[1].strip() if len(parts) > 1 else "") + + +def hints_for(entry): + hits = {} + for hunk in entry.get("diff") or []: + for block in hunk[1]: + o = [op(r[1]) for r in block.get("orig", [])] + r = [op(r[1]) for r in block.get("recomp", [])] + if not o or len(o) != len(r): + continue + for a, b in zip(o, r): + if a == b: + continue + ma, oa = split(a) + mb, ob = split(b) + # same mnemonic, ours a bare immediate, theirs carrying a symbol + if ma == mb and IMM_RE.match(ob) and SYM_RE.search(oa) and int(ob, 0) >= 0x10000: + hits[(a, b)] = hits.get((a, b), 0) + 1 + return sorted(hits.items(), key=lambda kv: -kv[1]) + + +def main(): + args = sys.argv[1:] + if args and args[0] == "--run": + common.run_reccmp() + args = args[1:] + want = args[0] if args else "" + byaddr = common.load_diff() + shown = total = 0 + for f, e, a in common.entries(byaddr): + if e is None or float(e["matching"]) >= 1 or want not in e["name"]: + continue + total += 1 + hits = hints_for(e) + if not hits: + continue + shown += 1 + lines = sum(n for _, n in hits) + print("### %s %.1f%% norm %.1f%% (%d line(s) look like symbolization only)" + % (e["name"], float(e["matching"]) * 100, common.normalized_ratio(e) * 100, lines)) + for (a, b), n in hits[:10]: + print(" FALSESYM x%-4d orig: %s" % (n, a)) + print(" %14s ours: %s - confirm the original is a plain immediate" % ("", b)) + if not total: + print("nothing below 100% in the current list") + else: + print("\n%d of %d function(s) below 100%% have a symbolization-only hint" % (shown, total)) + + +if __name__ == "__main__": + main() diff --git a/tools/reimplementation-helper/batch/quick_diff.py b/tools/reimplementation-helper/batch/quick_diff.py index 91428df2ff..a83705325f 100644 --- a/tools/reimplementation-helper/batch/quick_diff.py +++ b/tools/reimplementation-helper/batch/quick_diff.py @@ -1,6 +1,6 @@ """Compile ONE source file and diff its code against the original function, in seconds. -usage: quick_diff.py FILE.cpp... [-q] [-s] [-d] [--name FUNCTION] +usage: quick_diff.py FILE.cpp... [-q] [-s] [-d] [--structural] [--name FUNCTION] Compiles each file with a DLL compile command plus /FA (no link, no reccmp), disassembles the original function at the file's `// FUNCTION:` address straight from `_original/` with capstone, normalizes both streams (globals, @@ -10,6 +10,13 @@ (forward/backward) instead of `L`: a layout where the same block copy exists on both sides but the jumps reach a different one scores 1.0000 without it and ~97% in reccmp. +`--structural` adds `structural_diff.py`'s tiers for the same compile - `kind` (mnemonics only), `shape` +(registers and constants anonymised) and `delta` (per-mnemonic count mismatches, listed) - and prints the diff on +the anonymised `shape` lines, so what is left reads as instructions rather than as register names. Unlike +`structural_diff.py`, which only scores files in the build list, this takes any file, so it scores a variant +before it replaces the source. Rank by delta first and kind second: the ratio is dominated by register naming and +can rise while the structure gets worse. + This is a triage loop, not the score: it is stricter than reccmp about register names and looser about stack offsets and constants, so confirm a 1.0000 with `reccmp_report.py --run`. Unlike reccmp it shows the *whole* original function - reccmp cuts the original stream at the length of our function, which hides the original's @@ -30,10 +37,11 @@ quiet = '-q' in sys.argv keep_slots = '-s' in sys.argv +structural = '--structural' in sys.argv keep_direction = '-d' in sys.argv # --name NAME: diff that function of a file holding several `// FUNCTION:` markers (default: the first) want = sys.argv[sys.argv.index('--name') + 1] if '--name' in sys.argv else None -_skip = {'-q', '-s', '-d', '--name'} | ({want} if want else set()) +_skip = {'-q', '-s', '-d', '--structural', '--name'} | ({want} if want else set()) files = [os.path.abspath(f) for f in sys.argv[1:] if f not in _skip] if not files and __name__ == "__main__": sys.exit(__doc__) @@ -224,6 +232,14 @@ def main(): continue ratio = difflib.SequenceMatcher(None, a, b, autojunk=False).ratio() print('##### %s ratio %.4f orig %d ours %d' % (os.path.basename(f), ratio, len(a), len(b))) + if structural: + # imported here: structural_diff imports this module in turn, through asm_streams + import structural_diff + m = structural_diff.measure(f, os.path.basename(f), None, pair=(a, b)) + print('kind %.4f shape %.4f delta %d %s' % ( + m['kind'], m['shape'], m['delta'], + ' '.join('%s %d/%d' % (k, n, o) for k, n, o in m['deltas']))) + a, b = [structural_diff.shape(l) for l in a], [structural_diff.shape(l) for l in b] if not quiet: for l in difflib.unified_diff(a, b, lineterm='', n=2): if not l.startswith(('---', '+++')): diff --git a/tools/reimplementation-helper/batch/quick_styles.py b/tools/reimplementation-helper/batch/quick_styles.py index be2ac35fc4..7b714bd000 100644 --- a/tools/reimplementation-helper/batch/quick_styles.py +++ b/tools/reimplementation-helper/batch/quick_styles.py @@ -12,11 +12,16 @@ variants. The winner is left in the source tree; on a tie with the original, the original stays. usage: - quick_styles.py FunctionName [-s] [style ...] + quick_styles.py FunctionName [-s] [--structural] [style ...] `-s` scores with `[esp + N]` offsets kept (quick_diff -s), which is what makes declaration order and slot assignment visible; use it once everything else matches. +`--structural` ranks by structure instead (quick_diff --structural): fewest mismatched mnemonics +(`delta`) first, then the mnemonic-sequence ratio (`kind`), and the plain ratio only to break what +is left. The ratio is mostly register naming, so it can prefer a variant with the wrong instruction +mix; on processPeasantSpawnAndDespawnCycle the structurally better form (delta 7 -> 2) scored lower. + The score is quick_diff's difflib ratio, which is NOT the reccmp percentage: it is stricter about register names and looser about stack offsets and constants. Use it to rank the forms, then confirm the winner with `reccmp_report.py --run`. Ties are printed rather than broken for you - prefer the @@ -38,20 +43,32 @@ BATCH = Path(__file__).resolve().parent VARIANTS = common.TMP / "variants" RATIO = re.compile(r"ratio\s+([0-9.]+)") +STRUCTURE = re.compile(r"kind ([0-9.]+) shape ([0-9.]+) delta (\d+) *(.*)") -def measure(target, keep_slots, out_dir): +def measure(target, keep_slots, out_dir, structural=False): + """(score, label, error output). Scores compare with `>`; a structural one is (-delta, kind, ratio).""" env = dict(os.environ) env["QD_OUT"] = out_dir argv = [sys.executable, str(BATCH / "quick_diff.py"), str(target), "-q"] if keep_slots: argv.append("-s") + if structural: + argv.append("--structural") proc = subprocess.run(argv, capture_output=True, text=True, env=env) out = proc.stdout + proc.stderr found = RATIO.search(out) if not found: - return None, out - return float(found.group(1)) * 100, None + return None, None, out + ratio = float(found.group(1)) * 100 + if not structural: + return ratio, "%.4f%%" % ratio, None + st = STRUCTURE.search(out) + if not st: + return None, None, out + kind, delta = float(st.group(1)), int(st.group(3)) + label = "delta %-3d kind %.4f ratio %.4f%% %s" % (delta, kind, ratio, st.group(4)) + return (-delta, kind, ratio), label, None def main(): @@ -60,7 +77,8 @@ def main(): sys.exit(__doc__) func = argv.pop(0) keep_slots = "-s" in argv - styles = [a for a in argv if a != "-s"] + structural = "--structural" in argv + styles = [a for a in argv if a not in ("-s", "--structural")] vdir = VARIANTS / func if not vdir.is_dir(): @@ -85,17 +103,17 @@ def main(): # the committed source is a candidate too: a variant that merely ties it must not # replace it (that happened: an identical-scoring variant was left in the tree) shutil.copy(backup, target) - ratio, err = measure(target, keep_slots, out_dir) + ratio, label, err = measure(target, keep_slots, out_dir, structural) results.append((ratio, '_original')) - print("%-32s %s" % ('_original', "COMPILE FAIL" if ratio is None else "%.4f%%" % ratio)) + print("%-32s %s" % ('_original', "COMPILE FAIL" if ratio is None else label)) for style in styles: shutil.copy(vdir / (style + ".cpp"), target) common.format_file(target) - ratio, err = measure(target, keep_slots, out_dir) + ratio, label, err = measure(target, keep_slots, out_dir, structural) results.append((ratio, style)) # four decimals: a variant printing the same first decimal as the baseline has # repeatedly turned out to be slightly below it, which is one instruction - print("%-32s %s" % (style, "COMPILE FAIL" if ratio is None else "%.4f%%" % ratio)) + print("%-32s %s" % (style, "COMPILE FAIL" if ratio is None else label)) if err: for line in err.splitlines(): if "error" in line: @@ -112,8 +130,12 @@ def main(): sys.exit("every variant failed to compile; original restored") best = ranked[0][0] - tied = [s for r, s in ranked if abs(r - best) < 1e-9] - print("\nbest %.4f%% achieved by: %s" % (best, ", ".join(tied))) + tied = [s for r, s in ranked if r == best] + if structural: + print("\nbest delta %d, kind %.4f, ratio %.4f%% achieved by: %s" + % (-best[0], best[1], best[2], ", ".join(tied))) + else: + print("\nbest %.4f%% achieved by: %s" % (best, ", ".join(tied))) keep = '_original' if '_original' in tied else tied[0] if len(tied) > 1: print("(tied -- keeping %s; pick whichever reads best)" % keep) diff --git a/tools/reimplementation-helper/batch/structural_diff.py b/tools/reimplementation-helper/batch/structural_diff.py index a216a2d6e5..e1d9db79a6 100644 --- a/tools/reimplementation-helper/batch/structural_diff.py +++ b/tools/reimplementation-helper/batch/structural_diff.py @@ -121,8 +121,9 @@ def ratio(a, b): return difflib.SequenceMatcher(None, a, b, autojunk=False).ratio() -def measure(path, name, raw): - orig, ours = asm_streams.streams(path) +def measure(path, name, raw, pair=None): + # `pair` takes streams the caller already has, so `quick_diff.py --structural` does not compile twice + orig, ours = pair or asm_streams.streams(path) if ours is None: return None mo, mu = asm_streams.mnemonics(orig), asm_streams.mnemonics(ours)