Skip to content

Reimpl/TribesState development - #279

Draft
gynt wants to merge 205 commits into
sourcehold:mainfrom
gynt:reimpl/TribesState
Draft

gynt wants to merge 205 commits into
sourcehold:mainfrom
gynt:reimpl/TribesState

Conversation

@gynt

@gynt gynt commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

No description provided.

gynt and others added 30 commits October 19, 2026 22:55
Brings in every remaining TribesState method from origin/development so the
branch covers all 113 resolvers. Adapted to this branch's generated headers:

- Tribe field numbering differs between the branches (field19_0x1c here is
  field20_0x1e there and so on for 13 fields); renamed the references rather
  than touching the generated header.
- processDeerMoving kept a ushort* walker over
  unknownAttackRelatedUpdateCounter, which is short in this branch's header.
  Resolved the pointer into the field and unnested the comma operator.

syntax_check.py: 0 errors over 113 files. build_quiet.py: BUILD_OK.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
unptr.py over the namespace. updateCamelTribeBehavior 49.9% -> 50.3% and
updateLionWolfTribeBehavior 59.3% -> 59.6%; addUnitToTribe and updateTribes
unchanged. No function got worse.

Measured and reverted, so the next reader does not retry them:

- unmod.py's signed-remainder rewrite costs here. removeUnitFromTribe
  43.4% -> 14.1% and unitIsSelectedByPlayer 50.0% -> 33.3%: the original
  keeps the bare mask, so the dividend is not signed in these two.
- unptr.py plus docount.py on updateTribeCombatStanceBehavior
  53.4% -> 45.5% (norm 44.5% -> 38.2%); the original compiled that counted
  loop as a do-while.

Also fixes a deparen.py bug this pass uncovered: `<` was scanned as a
comparison inside `<<`, so `1 << n` was rewritten to `1 < < n`, which does
not compile. Two regression cases added to test_deparen.py (10/10 pass).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Ports ffea6d2 from origin/development, whose field numbering differs from
this branch's. diff_types.py reports EXTEND on five fields across
TribesState: the original zero-extends the 16-bit read where our `int local =
short field` sign-extends it. Tribe::{unknownAttackRelatedUpdateCounter,
initialMoveOrderGiven, predatorNearby, field138_0x284, countdown}.

spawnDeerLionOrRabbit 66.4% -> 67.2%, updateCamelTribeBehavior 50.3% -> 50.9%,
updateLionWolfTribeBehavior 59.6% -> 60.1%, updateRabbitTribeBehavior
31.8% -> 32.8%, processDeerMoving 24.1% -> 23.9%. Nothing else moved.

Tribe::size and Tribe::rallyPointCount carry the same hint and are
deliberately left signed: both are loop bounds, so `i < size` is a signed
compare that ushort would silently flip (see the upstream commit, where that
cost 35 functions).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…ian 69.6%

clearAllTribes 95.2% -> 100%. diff_signed.py: the original ends the loop with
`jl` where we had `jb`, so the undefined4 counter is compared as a signed int.
Also substituted sizeof(Tribe) for the 0x334 byte count (they are equal) and
turned the do-while into a for loop, which measured an exact tie.

getMajorityArcherTypeEuropeanOrArabian: diff_jcc.py ORDER. Written as
`arabArcherCount > europeanArcherCount`, which is the operand order the
original's `cmp`/`jg` shows; quick_diff 0.9247 -> 0.9462. reccmp does not move
on it. Still off by one `jmp`: the original falls through from the A_ARCHER
arm into the E_ARCHER test and we jump over it. Testing E_ARCHER first was
measured and is worse (0.9032), and hoisting the UnitTypeShort local to the
top of the function is an exact tie, so it stays declared at its use.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
diff_types.py reports EXTEND on it in unitIsSelectedByPlayer, and the same
field is read with movzx in removeUnitFromTribe where our `(int)` on the
declared short gives movsx. The evidence agrees: the array holds `1 << n` for
n in 0..15, so element 15 is 0x8000, which a signed short cannot represent.

Free on its own (same underlying width) and it lets the reads be widened:
unitIsSelectedByPlayer 50.0% -> 56.2%.

BitMaskHelper2 is left alone. It is only ever written back through a 16-bit
`and`, so no read site extends it and there is no evidence either way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Namespace average 71.15% -> 73.31%, nothing worse.

updatePeasantSeatingAtBuilding 36.7% -> 100%. Three changes: the `short*`
walker with offsets like psVar3[-0x10a] is a `Unit*` walker with named fields
(the original really does walk a pointer, so the walk stays - only the magic
offsets go); the `param_2 < 2 / < 4 / < 8 / < 0x10` chain is written as
`<= 1 / <= 3 / <= 7 / <= 0xf`, which is the `cmp N; jg` the original has; and
the goto out of the nested chain is gone, flattened to else-if. The owner
local is `int`, not `short`, because the original sign-extends the read.

spawnWildlifeOrMercAtAvailableSlot 23.5% -> 100%. The import had two guards
with empty bodies, `if (notSolitary || tooMuchWildlife) {}` and
`if (0xb < iVar2) {}`, so the function looped forever; and it was missing the
`return` after a successful spawn - the original spawns at one slot and
returns, which is what the name says.

hasAvailableSpawnSlotForWildlifeOrMercs 26.9% -> 96.0% (norm 93.3%). The
shared tail through `bool bVar4` cost a `sete`/`test` pair; two plain
`return 1` arms recover the original's flags-live `jmp` into the shared block.

removeUnitFromTribe 43.4% -> 67.1%. unitID is divided and taken modulo as a
*signed* int - the original biases the dividend and repairs the negative
remainder, which unsigned operands never need - and the selection-bit test is
a 32-bit `test` of a movsx'd field against a movzx'd mask, not the
decompiler's 16-bit `(ushort)(a & b)`. The goto is gone. What is left is
allocator: the original keeps &tribes[tribeID] in a register where we spill
it.

isTribePathToDestinationClear 13.9% -> 18.8%. `2 - (uVar1 & 0x100)` subtracts
the mask; the binary's `and/neg/sbb/add 2` is 2 minus a 0/1 flag, and it is
computed once before the search is seeded. Bounds are `<= 399`, the tile-index
limit is a signed `>= 500`, and the one `&&` chain is the two early-return
guards the original's inline cold block shows. Still low: the original keeps
the unit index in a stack slot and we keep it in a register.

spawnDeerLionOrRabbit 67.2% -> 68.0%. `((_unknown <= _tribeSize) - 1 &
0xffffffb5) + 100` is `_tribeSize < _unknown ? 25 : 100`; written that way
round it beats the opposite polarity (quick_diff 0.7295 against 0.7049).
Resolving the field-walking pointer beside it costs one instruction, so it
stays, with its type corrected to ushort and the measurement recorded.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
94 lines updated from the current reccmp run: the 93 imported functions had no
status line yet, and clearAllTribes, spawnWildlifeOrMercAtAvailableSlot and
updatePeasantSeatingAtBuilding have reached 100%.

Namespace average 73.31% over 113 functions, 41 of them at 100%.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Namespace average 73.31% -> 74.78%, nothing worse.

Thirteen pointer walks were stepped by the *element index* stride instead of
one element, so they ran far past the end of their array: `Unit* + 0x248` in
seven files and `Tribe* + 0x19a` (and `+ 0xcd`) in four. 0x248 is sizeof(Unit)
in shorts and 0x19a sizeof(Tribe) in shorts, which is what the decompiler
printed for a `short*` cursor; typing the cursor and keeping the stride made
every one of them a different array walk.

The tribe loops are now index loops over a reference local rather than a
cursor compared against an absolute end address (style guide 10 and 11), which
reproduces the original's `add 0x334` / `cmp <end>` without the literal:

- applyTribeBehaviorType 67.8% -> 100%
- consumeFlaggedTribesOfType 25.0% -> 100% (it also had an
  `if (param_2 <= 0) {}` with an empty body where the original leaves the loop)
- flagTribesOfType 72.2% -> 100%
- swapTribeOwnership 80.0% -> 100%

applyTribeBehaviorType and swapTribeOwnership walk the *global* instance, not
`this`: the original loads the tribe address as an absolute. Using
DAT_TribesState::instance is what moved the loop anchor onto the original's
field and was worth most of their gain.

Partial, by the stride fix alone: clearTribesOfUnitType and
clearTribesNotOfUnitType 97.1%, removeSelectedUnitsFromTheirCurrentTribes
96.8% (one `[esp + N]` displacement for the cleared-tribes array; swapping it
with the cookie local is an exact tie, so the declaration order stands),
getMajoritySelectedUnitType 71.8%, addUnitsToTribeAndComputeMovementSpeed
64.1%, addUnitToTribeAndUpdateTribeMovementSpeed 57.9%.
snapshotSelectionTribeAndComputeStance had the same stride bug and did not
move; its gap is elsewhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Namespace average 74.78% -> 76.43%.

Six functions carried an `if (...) {}` with an empty body where the original
leaves a loop or returns, which made them either loop forever or run on with
stale values:

- applyLadderDestructionToTribeUnits 27.8% -> 93.1%. Four of the six unit
  tests had been dropped to empty bodies; the original skips the unit on each,
  so they belong in the one condition. The climb call is also two calls with
  constant arguments, not one call with `(uint)(flag == 0)`, which costs a
  `sete` - and the `!= 0` arm is the one the original places first
  (quick_diff 0.9138 with the arms the other way round, 1.0000 as written).
- respawnDeer 57.1% -> 100%. One `for` over five candidates where the import
  had a `while (true)` that could only be left by its `break`, so a run with
  no valid tile fell through to the spawn with the last candidate's
  coordinates. The spawn and its `return` now sit inside the loop, the
  candidate choice is an if/else (the original branches, it does not
  overwrite), and the organism ID is an `int` local, which is the `movsx` the
  original has.
- moveTribeToNearbyClearTile 77.2% -> 98.4%. Same shape: with no reachable
  candidate the import issued a move order anyway. 0xb4df44 is one past
  field1608_0xcc4[39].y, so the cursor and its magic end address are a plain
  40-entry loop. The unit-ID local is `int`, not `short`.
- removeUnitFromThisTribeIfInTribe 30.5% -> 79.5%, the same corrections as its
  twin removeUnitFromTribe. Introducing a `Tribe&` for the repeated
  `tribes[tribeID]` was measured and reverted: 0.7945 -> 0.6620 here and
  0.6709 -> 0.6144 there.
- updateTribes 80.2% -> 91.2%. The loop ran one tribe past the end:
  the original's `cmp 0x4e2; jl` is `< 1250`, not `<= 1250`.
- updateTribeUnitAssignments 60.0% -> 57.1%, which is the one regression and
  is accepted. Its loop could not terminate either; the two gotos are
  `continue`s, so the increment has to move into a `for` header, and that
  entry test is the cost. The alternative, a `clearTribe` call in each arm
  with the do-while kept, measures worse (0.6076 against 0.6250).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Declared `byte[400]`, but both of its users already had to cast it: one
through `(short*)` and one through `*(ushort*)(.. + i * 2)`. The original
reads it as `movsx edx, word ptr [eax*2 + ..]`, so it is `short[200]`.

unitIsSelectedByPlayer 56.2% -> 100% once the read is written without the
cast; addUnitToSelected stays at 100%.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Namespace average 76.43% -> 76.90%.

unitIsSelectedByPlayer 56.2% -> 100%. With selectedUnitsBitFlags correctly
typed the whole body is one expression: the `& 0x8000000f` plus negative
repair is `% 16`, the mask-and-negate tail is `!= 0` on a BOOLEnum return, and
both operands widen to int, which is the movsx/movzx pair the original has.
addUnitToSelected keeps its 100% and loses its `(short*)` cast.

predictUnitInterceptPosition 22.9% -> 30.9%. Two guards had empty bodies. The
first is load-bearing: the original jumps 0x1dd bytes to the epilogue, so the
entire body runs only when the unit has finished digging. The second, inside
the path-plan loop, is the loop's own exit. currentIndexInPathPlan is read as
a signed int (`movsx`), not `(uint)`.

updateTribeUnitAssignments 57.1% -> 58.4%. diff_types.py EXTEND: the original
zero-extends its reads of tribeState and size here, so both locals take a
`(ushort)` cast at the read site. The fields stay signed - size is a signed
loop bound elsewhere in the namespace.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Namespace average 76.90% -> 77.66%, nothing worse.

getSpecificUnitFromTribe 16.5% -> 53.5% (norm 55.1%). Three corrections, all
from the asm: the 200 bound is a signed compare on the undefined4 global, the
`param_2 == 0` test is against the immediate rather than a zeroed register,
and `1 << ((byte)i & 0x1f)` is decompiler noise for `1 << i` - x86 masks the
shift count anyway, and spelling it out costs three instructions. Both globals
are also read before the bound test, which is the order the original loads
them in.

snapshotSelectionTribeAndComputeStance 14.5% -> 47.1%. The tail had three
unconditional stores to unitStance, so the first two were dead; the original
is a three-way chain ending in `setge`. The tribe snapshot is a whole-struct
assignment, which is the original's `rep movsd` of 0xcd dwords - the import's
int-by-int loop compiles to a loop. The two decompiler variables tracking the
last tribe ID are one variable, and the "at least two tribes" flag is a dword,
not a `bool`. Reading _stanceCount[] at the end instead of keeping the three
counters was measured and is worse (0.5806 -> 0.4725).

applyUnitTopSpeedDelayBasedOnTribeSize 25.6% -> 39.8%. The original puts the
big-tribe branch first - it tests the size and jumps away when it is below 40.
Also: a typed `UnitIDMovementDistancePair*` cursor instead of a `short*` with
`((Pair*)(p - 1))->unitID`, sizeof for the 4004 byte count (they are equal),
the sort's two misnamed locals (`_distance` held the unit ID and `_unitID` the
distance) swapped back, and the reused `tribeID` parameter replaced by a
counter.

playUnitCombatSpeechForTarget 26.1% -> 28.1%. Five `if (sVar1 < 0xf) {}` with
empty bodies, where the original jumps to the epilogue. Retyping its int
out-parameter, which the decompiler had as `TribesState*`, was measured
separately and costs 8 points, so it stays wrong for now: this function is 284
original instructions against our 244 and needs rebuilding from the jump
table before the type can be fixed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Namespace average 77.66% -> 78.35%, nothing worse.

clearAnimalSpawnLocationsUnk 40.0% -> 100%. The cursor walked
deerSpawnLocationsXY and reached the other three arrays through offsets from
it (0x3ae to lionLocationsXY, 0x1d3e to rabbitSpawnXY, 0x1d52 to
camelSpawnXY), ending on the absolute address 0x117d1de. All four hold four XY
pairs, so it is one four-entry loop over named fields.

setRabbitSpawnXY 92.9% -> 100%. Same shape: 0x117ef1c is one past
rabbitSpawnXY[3].

importStoredInfoFromSlot0 32.2% -> 42.7%. The rally-point copy is a loop over
the two coordinates with the nine points left to the compiler, which is what
the original's nine stores plus `add edx, 2` outer step are. The import wrote
ten stores, one past the nine-entry array.

createTribe: the loop bound is a signed compare on the undefined4 global and
the 820 byte count is sizeof(Tribe). The percentage does not move - we are 56
instructions against the original's 64, and the original puts the whole claim
block out of line behind a shared `return 0`. Writing the claim as the
cold-last arm with a `Tribe&` for the repeated subscript is an exact tie, and
is kept because it reads better.

Also marks the C4700 in giveTribeAnInstruction: `id | x | id != 0` reads a
local nothing assigns. That function has thirteen jump tables and needs
rebuilding from the original's branches; the comment is there so the warning
is not mistaken for noise.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
25 lines updated from the current reccmp run.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
…tionSound

Namespace average 78.35% -> 78.53%, nothing worse.

getUnitIDForIndexInTribe 36.7% -> 58.0%. `1 << ((byte)i & 0x1f)` is decompiler
noise for `1 << i` - x86 masks the shift count itself, and spelling the mask
out costs three instructions. Same fix as getSpecificUnitFromTribe. What is
left is register allocation: the original shrink-wraps its pushes into the
branches and we push up front, and neither declaration order nor
declare-at-use moves it.

aiAssignNewUnitToTribe: the nested if/else chain is flattened to else-if,
which compiles byte-identically, and the monk arm's tribe ID is scoped to the
arm. The percentage does not move - the original keeps the array index in a
register where we spill it to the frame, and sharing one tribe-ID local across
the arm and the tail (which is what the original does) is an exact tie.

playUnitSelectionSound carries a fixme instead of a rewrite. Its decompilation
is wrong in two ways - the UT_E_SWORD arm reaches `iVar5 = 0xad`
unconditionally, so a two-unit selection plays three effects where the
original plays one, and every `param_1 = <id>` in front of a speech call is
MSVC writing a tail call's argument - but correcting the arms separately costs
32 points of raw match (46.5% -> 14.5%) while the normalized match rises
(34.4% -> 40.8%), because the original shares those calls through its tail
calls. The comment records what the branches say so the next pass can
reproduce the sharing too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Two more guards with empty bodies, both of which changed behaviour:

- The aggressive-stance counter was incremented, tested against 0x3c with an
  empty body, and then reset to zero unconditionally, so the arm ran on every
  tick and the counter never reached its limit. The original's
  `cmp ax, 0x3c; jl` skips the whole arm.
- Nothing gated the rally-point advance on
  allUnitsReachedTheirDestination, so the tribe advanced its rally point
  before arriving.

53.4% -> 57.6% (norm 44.5% -> 47.3%), namespace average 78.53% -> 78.57%.

Still open on this function: the original places the rally branch first and
the aggressive branch out of line (`test eax, eax; je` jumps 0x1fb away), so
the two arms are the other way round from ours, and the rallyPointCount
comparison re-reads the field where we keep a local.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Namespace average 78.57% -> 78.58%.

moveUnitToBehaviorTarget 27.0% -> 27.1%: the tribe-ID local is `int`, which is
the movsx the original has. Its gotos stay, against the style list, because
the original really does duplicate these tails and three goto-free shapes all
measure worse - merging the two `local_c = y` tails into one block gives
quick_diff 0.2730 at 137 instructions against the original's 156, duplicating
the success tail into all eight arms gives 0.2951 at 149, and the form that is
there gives 0.4092 at 147. The measurement is recorded above the function.

updateRabbitTribeBehavior 32.8% -> 33.3% and updateLionWolfTribeBehavior
60.1% -> 60.7%: diff_types.py's EXTEND at `[esi + 0x28a]` is
Tribe::rallyPointCount read through the tribe base, and the original
zero-extends it. A `(ushort)` at the read site rather than retyping the field,
which is a signed loop bound elsewhere.

Measured and reverted: reading WildlifeGridElement::rockyTiles at its use
site instead of hoisting it with the other grid fields. The original does load
it there, and it removes the extra stack slot diff_slots.py reports, but
reccmp disagrees with quick_diff on both functions that have it -
updateRabbitTribeBehavior 32.8% -> 32.5% where quick_diff read 0.4634 ->
0.4914, and processDeerMoving 23.9% -> 23.5%.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
The original declares the path search budget at function scope - its prologue
stores 0x1f4 into that slot alongside the zeroed locals - and `_tribeUnitIndex`
is then one slot too many, so the frame only matches with both moves. All four
variants were built and measured and all of them are reverted, because raw and
normalized disagree and raw is what the function is scored on: as written
30.0%/22.5%, budget hoisted 28.0%/26.1%, both moves 27.1%/27.0%, counter
scoped alone 21.7%/21.9%. Recorded above the function so the next pass starts
from this rather than repeating the four builds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
39.8% -> 45.1%, namespace average 78.58% -> 78.63%.

diff_anchor.py: both of its cursors anchor four bytes below the original's,
and every displacement in the loop differs as a result. The original walks the
*movementDistance* member in the fill loop (`lea ebx, [esi + 0xfa412]`, with
the unit ID stored at [ebx - 2]) and the *second* element of each pair in the
sort loop (`lea eax, [esi + 0xfa414]`, with the current entry at [eax - 4] and
[eax - 2]). Writing the cursors that way costs the typed struct pointer the
earlier pass introduced, so each carries a comment saying why.

Also records the one hint that did not pay: diff_lea.py's RLEA on
removeUnitFromThisTribeIfInTribe says the original keeps &tribes[tribeID] in a
register, but a `Tribe&` for the repeated subscript is not how to get it -
79.5% -> 58.8% by reccmp, matching what quick_diff said earlier.

processDeerMoving loses a pointless local: its rallyPointCount test compiles
against the memory operand either way, which is what the original does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
…le 43.3%

Namespace average 78.63% -> 78.66%.

commandUnitsToLocation 39.8% -> 42.3%. diff_triage.py's BYTE column: the
original makes two byte-sized stack accesses and we made five. The two are its
`(char)matchUnitSpeeds` tests; the other three were a `bool` flag, which is a
dword in the original (`mov ebx, 0x1`, stored as a dword). BOOLEnum per the
style guide, since every store is 0 or 1.

moveTribeToIndexedNearbyTile 42.0% -> 43.3%. The bounds are `<= 399`, the
40-modulus is written in decimal, the unit-ID local is `int` (the original
sign-extends), and `((XYPair*)(piVar6 + -1))->x` is `piVar6[-1]` - the array's
members are ints, so the cast was reaching the same place the long way round.

The index loop that took moveTribeToNearbyClearTile to 100% does not work
here, because this one starts from a computed index rather than zero: 86
instructions against the original's 72 and quick_diff 0.5063, where the cursor
form gives 84 at 0.5513. Declaring the candidate coordinates in the loop body
is an exact tie, so they are declared at their use.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Namespace average 78.66% -> 78.95%, 49 of 113 at 100% -> 53.

All four were one or two comparisons written the way the decompiler printed
them rather than the way the binary does them:

- standUpAllTribeUnits 86.8% -> 100%. The cursor anchors on Tribe::size, not
  on the tribe: the original reads it as [eax] where a `Tribe*` reads
  [eax + 0x34], and every displacement in the loop differed as a result.
- getNonDyingUnit 90.2% -> 100%. The size local is `int` (the original does
  one movsx where a `short` local needs movzx plus movsx), and the loop test
  is `index >= size`, which is the operand order of the original's `cmp`.
- findRecentOrSignpostSpawnLocation 92.4% -> 100%. Bounds are `<= 399`
  (`cmp 0x18f; ja`) and the slot loop ends on `4 <= iVar4` (`cmp 4; jl`), not
  `3 < iVar4`.
- addUnitToNewTribe 98.3% -> 100%. `_tribeID < 1` is `_tribeID <= 0`:
  `test eax, eax; jle` against our `cmp eax, 1; jl`.

Tried and reverted: the same size-field cursor on five other functions that
loop over the tribe size (applyLadderDestructionToTribeUnits,
updateAnimalHerdBehaviorState, scatterTribeUnitsRandomly, updateTribeRallyFlags,
stopTribeMovementAndCheckIdle) is an exact tie on all five - MSVC already picks
that anchor when the two reads sit close together. And hoisting
hasAvailableSpawnSlotForWildlifeOrMercs' counter out of its `for` header to
match the original's `xor eax, eax` placement costs 10 points (96.0% -> 85.7%),
which is now recorded in the file.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
76.5% -> 80.7%, namespace average 78.95% -> 78.98%.

The tribe-size local is `int` - a `short` one needs movzx plus movsx where the
original does one movsx - and the loop test is `index >= size`, which is the
operand order of the original's `cmp`. scatterTribeUnitsRandomly takes the same
widening; it is code-generation neutral there but loses the same instruction
pair.

Widening every other `short local = <field read>` in the namespace was trialled
file by file and not kept: only predictUnitInterceptPosition and
sortTribePathDestinationsByCost improved at all, by 0.001 of quick_diff ratio
at ratios below 0.4 where the tool's own guidance says not to trust a rise,
and addUnitsToTribeAndComputeMovementSpeed, createAnimal,
drawFlagsAndUnitDestinations and playUnitCombatSpeechForTarget all dropped.
This namespace does not behave like Map::Units::UnitsState did, where 17 of 18
such widenings gained.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
…ics ruled out

Namespace average 78.98% -> 79.00%.

moveTribeToIndexedNearbyTile 43.3% -> 45.9%. Its bounds really are `<= 399`;
the earlier pass meant to write them that way and the edit silently did not
apply. The three remaining `*(char*)(y * 400 + (int)DAT_BinaryTileMap400x400 +
x)` casts in the namespace are now array subscripts - code-generation neutral
on createAnimal and giveTribeMoveInstruction, which is where the other two
were.

Two heuristics that pay elsewhere and cost here, both now recorded in the
files so they are not retried:

- sortTribePathDestinationsByCost: widening its `short` unit-ID local, which
  our movzx-plus-movsx pair against the original's single movsx argues for,
  costs 2.2 points (28.8% -> 26.6%).
- spawnQueuedReinforcementWaves: making its two `bool` flags BOOLEnum, which
  the original's `xor ebx, ebx` and diff_triage.py's BYTE column argue for,
  costs 6.4 points (58.5% -> 52.1%, norm 52.9% -> 44.3%).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
66.7% -> 87.2% (norm 66.7% -> 76.2%), namespace average 79.00% -> 79.19%.

Four separate guards, not two `||` chains. The original emits a `return 0` for
the first of each pair inline and jumps back to it from the second, and its
three return blocks have different `pop` sequences because they sit at
different points in its register saves - which is why it cannot merge them and
we did. Splitting the chains recovered 16 of the 20 points.

The rest: the RNG byte is read into an `int` and masked in the initialiser,
which is the original's `movzx` plus one `and`; the spawn chance is
`100 <= (rng & 0x7f)` (`cmp 0x64; jl`); and the wave counter is compared with
the field as the first operand.

Splitting guards the same way is not a general rule - on
isTribePathToDestinationClear it measures worse (quick_diff 0.6635 -> 0.6296),
because that one merges every failure into a single `return 0` instead of
shrink-wrapping. Recorded in both files.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
`(short*)((int)this + _selectionID * 0x334 + 0x40)` is
`&this->tribes[_selectionID].tribeState`, and the 820 byte count is
sizeof(Tribe). Both are code-generation neutral - quick_diff 0.7759 before and
after - so this is readability only; the function stays at 75.2%.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
…daters

Namespace average 79.19% -> 79.30%.

All three of updateCamelTribeBehavior, updateLionWolfTribeBehavior and
processDeerMoving have the same block - "if no move order has been given yet,
give one" - and in all three the original ends it with `ret 4` after setting
the behaviour type. The import let it fall through. That is not cosmetic: the
block reassigns the variable that held initialMoveOrderGiven to a unit ID (the
original is free to reuse the register precisely because it returns), so the
`== 1` test that follows was reading a unit ID. The original's register reuse
is what gave the return away.

updateCamelTribeBehavior 50.9% -> 64.5%, processDeerMoving 23.9% -> 24.1%, and
updateLionWolfTribeBehavior 60.7% -> 59.9%. The last one is a regression and
is kept anyway: the `ret 4` at 0x52b207 is not ambiguous, and 0.8 points of
block layout is not worth leaving a wrong control flow in place.

updateRabbitTribeBehavior has the same block shape but an extra
standUpAllTribeUnits call in it, and its asm does not show the return inside
the 73 bytes the test jumps over, so it is left alone rather than guessed at.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HtKbXQ7VMMh4CsZ1MwVEVX
gynt and others added 9 commits December 4, 2026 09:35
Rewrite the target dispatch as a flat if/else chain in which each arm calls
its finder, skips the unit on failure and loads tile, y and x itself. The
unit-state gate becomes nested tests that continue the loop, and the
Ghidra gotos and the bVar7 flag are gone. With the per-arm loads, x, y and
tile take the callee-saved registers and unitID is kept on the stack, as in
the original.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Set noneCommanded after the size test, and send the empty tribe to the
shared return FALSE. The constant 1 then gets ebx and the tribe offset
is spilled, as in the original.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
The tile, x, y load order fixes the x/y register swap but lowers the
normalized match (66.2% -> 63.9%), so the code is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Return tribeID once at the end of the herd tail, so the spawn counter
gets ebx and tribeID stays in its stack slot, as in the original. The
substate is now the low two bits of fixedRng without the byte cast, the
spawn loop is guarded with 0 < count, and the casts on the x/y arguments
are gone.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Write the swordsman arm as one else-if chain with a single return, and
read the horse archer's x and y directly instead of through pointer
locals. The three swordsman calls then keep their own epilogues, and the
horse-archer calls get the field addresses in registers, as in the
original.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Load the two units' coordinates into four locals and square the
differences inline. All four values are then live at once, which pushes
unitType out of ebx onto the stack, as in the original.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Rewrite the targeting tail as one flat else-if chain on the instruction
type, giving the fill-moat and dig-moat arms their own text-marker call.
Also compute the planned-destination tile before the cursor frame, make
the rally index and the flag frame signed so the modulo uses idiv, and
read the target unit ID as an int.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Give the building and ground-tile targets their own giveTribeAnInstruction
call, test both counters through the short pointer that incremented them,
and write the rally-wrap test as index >= count. The unused short copy of
the counter is gone.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Rewritten section by section against the original: subscripted tribe, one targetArea, one defensive flag, storeAsRallyPoint reused as the fallback-search state, unitType read from the unit in each filter (no jump threading), one index for the three loops, and the move delay stored per arm for 16-bit arithmetic. Normalized 22.6 -> 47.1.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
gynt added a commit to gynt/OpenSHC that referenced this pull request Dec 4, 2026
TribesState::createAnimal from sourcehold#279, with the style pass. Measured at 96.1 / normalized 77.6 on origin/main 592a17d (full build, both resolver sets on, reccmp). Remaining: the reloads of x and y from their parameter slots for the three spawn-point calls, and their pushes, use other registers and are ordered around the store to herdMaxSize; the same values are pushed in the same order. No functional difference.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
gynt added a commit to gynt/OpenSHC that referenced this pull request Dec 4, 2026
TribesState::playAttackCommandFeedback from sourcehold#279, with the style pass. Measured at 98.0 / normalized 94.4 on origin/main 592a17d (full build, both resolver sets on, reccmp). Remaining: the tribe ID is loaded from its parameter slot into ebx before the selectionContainsCombatUnit call instead of after it; nothing writes that slot in between. No functional difference.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
gynt added a commit to gynt/OpenSHC that referenced this pull request Dec 4, 2026
TribesState::commandUnitsToLocation from sourcehold#279, with the style pass. Measured at 90.3 / normalized 87.2 on origin/main 592a17d (full build, both resolver sets on, reccmp). Remaining: this and index swap edi and ebp (a reg_scores tie), and the original stores the 1 flag and spills the tribe offset before the empty-tribe test, ours around it; that exit returns FALSE without reading either. No functional difference.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
gynt added a commit to gynt/OpenSHC that referenced this pull request Dec 4, 2026
TribesState::playUnitSelectionSound from sourcehold#279, with the style pass. Measured at 92.4 / normalized 88.5 on origin/main 592a17d (full build, both resolver sets on, reccmp). Remaining: the selected count is loaded into eax and copied to edi (an un-coalesced move) where the original loads it straight into edi; the other lines are jump offsets, the jump table and the alignment filler shifted by those 2 bytes, and tail-jump targets. No functional difference.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
gynt added a commit to gynt/OpenSHC that referenced this pull request Dec 4, 2026
TribesState::playUnitCombatSpeechForTarget from sourcehold#279, with the style pass. Measured at 94.4 / normalized 90.7 on origin/main 592a17d (full build, both resolver sets on, reccmp). Remaining: the unitID parameter is loaded once above the range chain and copied, where the original loads it twice at the merge; the two unit-position loads (and the imul that indexes one) swap order; the selected count is copied through eax to edi; the rest are jump offsets and one jump-table entry shifted by those bytes. No functional difference.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Main's upstream Ghidra sync (0701799) carries moveTribeToIndexedNearbyTile's
void return; TribesState.hpp and TribesState.func.hpp are taken from main, so
this branch no longer changes either header.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
@github-actions github-actions Bot removed the declaration/type change This requires changes to the generated/exported types or definitions. label Dec 4, 2026
gynt and others added 5 commits December 5, 2026 04:26
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
updateTribes decrements it as a signed word (0x52B961: add word ptr [ecx], bx
with bx = -1); with the ushort type the structured updateTribes emits
add word ptr [ecx], 0xffff instead. The other reimplemented users,
updateLionWolfTribeBehavior and processEntityDamageToUnit, compile to the
same code with either type.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
The skip label goes in front of the for(;;) instead of inside it: MSVC then
computes unitID * 0x490 once, as the original does. A continue (or the
label inside the loop) makes it rotate the loop or recompute the index.
Also: class include first, named parameter, no redundant casts.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Both tribe speeds are read into their own short locals before the clamps,
instead of reusing one local; that puts the second load in the original's
place. Below 95: the original reads units[unitID].tribeID ahead of the
first clamp's branch but the tribe's speed only after it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
The human-player branch gets its own switch over the four animal tribe
types instead of gotos into the AI switch's case labels; the compiler
merges the shared calls the same way. Casts on the unnamed tribe types
are plain case numbers, the countdown decrements are plain --.
Still 91.2%: the original has two identical markTribeAsAnimalTribe arms
(0x52B90A, 0x52B914) that MSVC tail-merges here.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
@github-actions github-actions Bot added the declaration/type change This requires changes to the generated/exported types or definitions. label Dec 5, 2026
gynt and others added 6 commits December 5, 2026 05:38
…ions

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
Rally point read into y then x, the flag sum in the original's order with
the animation frame signed, decompiler names replaced, redundant casts
dropped.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
The tribe is reached through one Tribe reference instead of 21 subscripts.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
The scale-point arm no longer jumps over the move-to-destination store; the
store and the wide-value tail are guarded by targetType != STBT_0x3f4.
Same code as the goto form.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
…stays 81.2%)

Dead locals removed, redundant casts dropped, labels named. A fully
structured version (flags or two calls per arm) measures 0.54-0.68 against
0.85 in quick_diff, so the gotos into the shared tails stay.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp
…unctions

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XmXCmXCVBvESeaU1djQFjp

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

declaration/type change This requires changes to the generated/exported types or definitions.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant