Skip to content

One more UI function at 100%: Actions::PlaceUnit - #458

Open
kotijekriv wants to merge 4 commits into
sourcehold:mainfrom
kotijekriv:reimpl/UI-A-placeunit-100
Open

kotijekriv wants to merge 4 commits into
sourcehold:mainfrom
kotijekriv:reimpl/UI-A-placeunit-100

Conversation

@kotijekriv

@kotijekriv kotijekriv commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

One more function at 100%, with one header change (TileMapState::unitPlacementCount is an int, below; the PR waits for it to reach main) and no line for cmake/compiler-flags-gl.txt. One behaviour fix against the draft (below). Actions::PlaceUnit handles the mapper commands that place units (270 to 286 and the Arab units 350 to 357): while the mouse is dragged it puts the unit's pictures on the floating layer, and once the drag has stopped it spawns the units, paying for them in a siege. It is from gynt's draft on his fork's reimpl/UI-Core-development (10280b1, 39.4%, from after he closed #256; #256's reimpl/UI-Core has the function at 39.0%, 1b11452), and the commit credits him as co-author.

Function Address Before After
Actions::PlaceUnit 0x004381D0 gynt's draft 39.4% (10280b1; 36.4% at e584164 and a05c452, 39.0% at 1b11452) 100.0%, off the /GL list

Measured.

  • Setup: the bundled MSVC1400-SP1 against the Steam Stronghold Crusader.exe (3bb0a8c1…5387ac5a), both resolver sets enabled locally (not committed), and sourcehold's reccmp with --resolve-wrapped-calls --ignore-security-cookie.
  • Full build: an all-on build of this branch on main 812d149, with main's own /GL list (this file is not on it) and with 0x004314E0 (the MapEditorLandscaping_GeneralButtons handler) left out and its resolver off, as in main's baseline: 0 failed of 2,424 compile steps, 99.58 over 2,440 functions, against 99.58 over 2,439 for main alone (built at f489b72; since then main has only added files under tools/ (3458fea) and the optional function-visibility units (cmake: optional wrapper units built from function-visibility.txt #399, cmake: function-visibility.txt, which callers must see which callees' bodies #398), off by default). PlaceUnit reads 100.0 raw and normalised there too, with no diff entry. With unitPlacementCount as an int, main's two other users of the field, InitializeBasicMap and MenuItemActionHandler_General_ToolbarButtonPressed, read 100.0 raw and normalised as before. No main function reads differently: every one reads exactly what it read before (unrounded 99.5761 against 99.5759 raw, 99.5494 against 99.5492 normalised; 2,323 against 2,322 functions at 100.0 raw).
  • Our own narrower run: the 133 files of main's /GL list that exist on main, and PlaceUnit.cpp, off the list: 144 functions, average 99.56. PlaceUnit reads 100.0% raw and normalised, with no diff entries. The same build without the file has 143 functions, and each of them reads the same. That build, and the one with the file on the list (below), had an earlier text of this file: the same statements with the masks and the tribe types as numbers, the flag as an int, the bounds test around the body, and without most comments. quick_diff gives the same 376 instructions, line for line, for that text and for this one. The sources were main's at 3458fea; main's two commits since (02fab42, 812d149) add cmake files only, with the new option off.
  • After the review (e0ade4b, the header; add0b81, the code): the same narrow run with this text, the header change, and main's two other users of the field (InitializeBasicMap, MenuItemActionHandler_General_ToolbarButtonPressed): all three read 100.0% raw and normalised, PlaceUnit off the list. quick_diff gives the same 376 instructions as before for PlaceUnit, and the same listings for the two users with the header change and without it.
  • Instructions: the original's 376 (378 with its two alignment fillers, jmp and lea ecx, [ecx] at 0x004386AB / 0x004386AD), in its order; reccmp's diff for the function is empty. The case labels pair with the original's jump table (26 entries) and index table (88 bytes), case for case.
  • Please measure with both resolver switches on (the Globals and the function resolvers), as our numbers are.
  • Checks: our local style checker gives 0 ERROR and 6 CHECK (below); our local fixer finds nothing to change.
  • Not run in game.

The behaviour fix

  • While the mouse is dragged, the original only draws the pictures, and returns. It draws one of four alternatives (allowed or refused, siege tower or not) and returns after each (0x0043851B, 0x00438559, 0x004385A3, 0x004385E7). It pays and places only once the drag has stopped (cmp [draggingStopped], 0 at 0x004384AF). In gynt's drafts the drag branch has no return. On a free tile they drew the allowed pictures and then the refused ones as well (a siege tower all four pairs), and then went on into the placement, so the units were paid for in a siege and spawned while the drag was still going.

Read case by case against the jump table, the draft's values (pictures, tribe types, unit types, masks) are the original's.

What got it to 100%

The draft has the cases' values (the pictures, the tribe types and the unit types), the calls and their arguments. Their order and the control flow are rewritten against the original instructions, in three steps on our dev branch (not public): 98.4% and 98.6% (both read with the file on the /GL list; quick_diff, which compiles it off the list, gave 0.9774 and 0.9801), then 100.0% off the list.

  • The cases are in the order of the original's code: 270 to 280, the Arab units 350 to 357, then 281, 282, 284, 283, 285, 286. The Arab ballista case, the draft's last, now ends in a break, since the catapult case follows it.
  • The four floating-layer pairs are alternatives that each return (see above).
  • The gold check is gold > the player's gold, the flag is a dword (BOOLEnum), and the loop over the engineers with pots counts with a signed compare.
  • The default case leaves the body graphic unset, and reads it from gold's stack slot (98.4% to 98.6%). For a command outside the switch the original loads gmID from the stack slot that the siege cost's gold uses (mov edi, [esp + 0x24] at 0x00438456): the variable is never set on that path. With stone and gold declared in each of the two cost blocks, not once at the top, our build puts the unset gmID on that same slot (the draft writes that read out as _gmID = local_8, local_8 being its gold).
  • int const tile = … stands between int imageID = 1; and BOOLEnum canAfford = TRUE; (98.6% to 100.0%). The two share their constant. With the tile's computation between them the constant has to stay alive across it, and eax, ecx and edx are taken there, so the compiler keeps it in edi; its two stores then sink behind the switch's range compare, with the tile's store between them. That is the original: mov edi, 1 at 0x00438223, and the stores of imageID, the tile and canAfford at 0x00438234, 0x00438238 and 0x0043823C. With both = 1 on one side of the computation the constant is in eax and has to be stored before the command is loaded. The order of the original's three stores is what gave the order of the three statements away.

quick_diff reads 0.9987: 376 instructions against 377. The one left is an alignment jmp in front of the pots loop (0x004386AB), which quick_diff does not lay out; the real build has it.

No line for cmake/compiler-flags-gl.txt

  • Off the list the file reads 100.0%, on it 90.0% (normalised 80.9, 99 differing lines), in the same build otherwise. So it has no line, and it should not get one. On the list the difference starts before the first call (the y coordinate in edx instead of ecx at 0x004381E3), and ecx and edx trade roles from there on: it is the /GL build's register choice, not a callee's body.
  • Its two callees on main's list, getBuildingCost and processResourceLoss, do not have to be visible: quick_diff gives the same instructions with and without their bodies in the unit. So it needs no line in cmake/function-visibility.txt (cmake: function-visibility.txt, which callers must see which callees' bodies #398) either.

Header change

  • TileMapState::unitPlacementCount is an int (it was undefined4; the checker's one header CHECK), in a commit of its own (e0ade4b). The original uses it as a signed 32-bit count in all six places that touch it: InitializeBasicMap (0x0042F0CD), MenuItemActionHandler_MapEditorProperties_MainButtons (0x0044309F) and MenuItemActionHandler_General_ToolbarButtonPressed (0x00444647) store 1 into it; PlaceUnit passes it to spawnUnitsIntoNewTribe as that function's int unit count (0x00438659) and loops over it with signed compares (jle at 0x004386A9, jl at 0x004386D1). With it the cast in the pots loop is gone. Its two other users on main read 100.0% with it (above).

Main's declaration check fails on any change to a header under src/OpenSHC and labels the PR, so this PR waits for the line to reach main through the Ghidra sync, as the other declaration-change PRs do. Then we merge main in, and the check passes.

Kept as they are

  • A fixme: on gmID: for a command outside the switch the original leaves it unset and still compares it and passes it on (above). The code keeps that for the match. The only caller (0x004451C0) jumps here only for 270 to 286 and 350 to 357 (0x00445B1D, 0x00445B34), so the path is never taken in the game.
  • int stone; int gold; without a value, in two blocks (the four SG 24 CHECKs): they are the out-parameters of getBuildingCost, and they are declared in both cost blocks for the stack slot above. A comment in the code says so.
  • (UnitType)-1 (one CHECK): the value unitType starts with (or esi, ebp at 0x0043822F). UnitType has no name for it; UT_NONE is 0. Every case sets the type.
  • int tribeType = -1;: the cases assign AITribeType names; -1, for the siege engines that join no tribe, has no name, and spawnUnitsIntoNewTribe takes an int.
  • The map bounds are main's MapConstants: MC_MAP_XY_LIMIT_MIN_1 for the bounds test and MC_MAP_XY_LIMIT for the row length of the tile index.
  • The blocking masks are main's Logic1 flags: sea, rocky, building, tree, river, crenel and moat (0x40501481), and for the knight and the siege engines also wall or gatehouse and keep (0x50501581).
  • 29 | (24 << 16) and 13 | (24 << 16): a variation has two halves. The low 16 bits are flags (13 is 0x01, 0x04 and 0x08; 29 adds 0x10), and the high 16 bits a signed number: without flag 0x20 and when not 0, the blend strength that renderMap's two floater loops (0x004E9EC0, 0x004EC080) pass to renderGMWithBlending. So a placement that is not allowed is the allowed one's pictures drawn blended at 24. Written so, the two halves show; the constants are 0x18001d and 0x18000d.

Proposed, not changed here

  • Two halves for Floater::variation (and createFloatingLayerElement's parameter): flags in the low half, a signed blend strength or mask-image offset in the high half. Two shorts or named flags would touch every caller of createFloatingLayerElement, so they are left for a PR of their own.
  • AITT_HOPS_FARMER_UNK (12) is also the fighting monks' tribe type: PlaceUnit's monk case (0x00438317) spawns UT_E_MONK into a tribe of type 12. A name that fits both needs a header commit.

Other PRs

  • gynt's reimplement remaining OpenSHC::UI namespaces (57 functions, 10 at 100%) #256 (reimpl/UI-Core, closed) holds PlaceUnit.cpp at 39.0%, and his fork's UI branches carry it at 36.4% to 39.4%. We know of no open PR that holds the file. A branch that does will have an add/add conflict on it and a different status line at 0x004381D0, and can take main's version once this lands.
  • The status file's entries 0x004386B0 (the pots loop's head, a jump target) and 0x00438710 to 0x004387CF (Pending; the jump table's 26 entries and its 88 index bytes) are inside this function, not functions; this PR leaves them as they are.

🤖 Generated with Claude Code

Actions::PlaceUnit, from Gynt's draft on his fork's reimpl/UI-Core-development (10280b1 at 39.4%, from after
his closed sourcehold#256, and e584164 at 36.40% before it; sourcehold#256's reimpl/UI-Core has it at 36.4% in a05c452 and
39.0% in 1b11452). The draft has the cases' values (the pictures, the tribe types and the unit types), the
calls and their arguments. His 3d17527 on reimpl/UI-MenuItems-development is another line of this file (36.4%
there); this text does not build on it. Rewritten against the original instructions are the order and the control
flow:
- the cases are in the original's jump-table order: 270 to 280, the Arab units 350 to 357, then 281, 282, 284,
  283, 285, 286; the Arab ballista case, last in the draft, gets a break, since the catapult case follows it now;
- the default case leaves the body graphic unset, as the original does. The original reads it from the stack slot
  of the siege cost's gold there (`mov edi, [esp + 0x24]` at 0x00438456), so stone and gold are declared in each
  of the two cost blocks and not once at the top;
- the four floating-layer pairs are alternatives that each return (allowed or not, siege tower or not), where the
  draft ran them one after another, and then went on into the placement, so it paid for and spawned the units
  while the drag was still going. That is the one behaviour fix against the draft;
- the gold check is gold > the player's gold, the flag a dword (BOOLEnum), and the pots loop counts with a signed
  compare;
- `int const tile = ...` stands between `int imageID = 1;` and `BOOLEnum canAfford = TRUE;`. The two share their
  constant, which then has to live across the tile's computation, where eax, ecx and edx are taken. So it is in
  edi, and its two stores sink behind the switch's range compare with the tile's store between them, as in the
  original (`mov edi, 1` at 0x00438223; the stores at 0x00438234, 0x00438238 and 0x0043823C). With both `= 1` on
  one side of the computation the constant is in eax and is stored before the command is loaded (98.6%).
The decompiler's names became tribeType, secondGmID, secondImageID, imageID, blockingLogicMask, canAfford, stone
and gold. The blocking masks are written as main's Logic1 flags and the tribe types as AITribeType names (12, the
monks', is AITT_HOPS_FARMER_UNK there). The variation of a refused placement is written 29 + (24 << 16) and
13 + (24 << 16): the allowed one's with 24 in the third byte.

No line for cmake/compiler-flags-gl.txt, and it must not get one: the file reads 100.0% off the /GL list and
90.0% (normalised 80.9) on it, in the same build otherwise. quick_diff gives the same instructions with and without
the bodies of getBuildingCost and processResourceLoss, its two callees on main's list, in the unit.

reccmp in a build of main's whole /GL list (the 133 files that exist) and the file, off the list, with every
resolver of those files on: 144 functions, average 99.56. PlaceUnit 100.0% raw and normalised, no differing line.
The same build without the file has 143 functions, and each of them reads the same. Both builds (off and on the
list) had an earlier text of this file: the same statements with the masks and the tribe types as numbers, the
flag as an int, the bounds test around the body, and without most comments. quick_diff gives the same 376
instructions, line for line, for that text and for this one. The sources are main's at 3458fea; main's two
commits since (02fab42, 812d149) add cmake files only, with the new option off.

Co-authored-by: Gynt <gynt@users.noreply.github.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Comment thread src/OpenSHC/UI/Actions/PlaceUnit.cpp Outdated
Comment on lines +37 to +40
if (DAT_TileMapState::instance.DAT_ClickedTileX > 399 || DAT_TileMapState::instance.DAT_ClickedTileY > 399
|| DAT_ViewportRenderState::instance
.DAT_BinaryTileMap400x400[DAT_TileMapState::instance.DAT_ClickedTileY * 400
+ DAT_TileMapState::instance.DAT_ClickedTileX]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please relate to the map size enums, there should be minus 1 versions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in add0b81: the bounds test uses Map::MC_MAP_XY_LIMIT_MIN_1 and the tile index Map::MC_MAP_XY_LIMIT, as computeAIVPlacementFit does. The listing is the same as before.

Comment thread src/OpenSHC/UI/Actions/PlaceUnit.cpp Outdated
if (DAT_TileMapState::instance.currentMapperCommand
== OpenSHC::Commands::M_MAPPER_PEOPLE_ENGINEERS_POTS) {
// the engineers with pots start with oil in them
for (int i = 0; i < (int)DAT_TileMapState::instance.unitPlacementCount; ++i) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So is unitPlacementCount an int?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The original uses it as a signed 32-bit count in all six places that touch it:

  • three handlers store 1 into it: InitializeBasicMap (0x0042F0CD), MenuItemActionHandler_MapEditorProperties_MainButtons (0x0044309F) and MenuItemActionHandler_General_ToolbarButtonPressed (0x00444647);
  • PlaceUnit passes it to spawnUnitsIntoNewTribe as that function's int unit count (0x00438659);
  • PlaceUnit loops over it with signed compares: jle when it is not above 0 (0x004386A9) and jl for the loop bound (0x004386D1).

e0ade4b changes the header to int unitPlacementCount, and add0b81 drops the cast. The two other users on main (InitializeBasicMap, ToolbarButtonPressed) compile to the same listing with it. With it the PR has a header change, so it waits for that line to reach main.

Comment thread src/OpenSHC/UI/Actions/PlaceUnit.cpp Outdated
if (gmID == OpenSHC::IO::Graphics::GID_BODY_SIEGE_TOWER) {
if (secondImageID > 0) {
MACRO_CALL_MEMBER(OpenSHC::Rendering::ViewportRenderState_Func::createFloatingLayerElement,
DAT_ViewportRenderState::ptr)(secondGmID, secondImageID, 0, 71, tile, 29 + (24 << 16));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So does variantion contain also flags, or is this value logically two shorts (even if contained in an int)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two halves, and the low one holds flags. createFloatingLayerElement stores the variation whole, as one dword, in the floater (Floater::variation, 0x004E64BC). renderMap (0x004E8CF0) draws the floaters in two loops, at 0x004E9EC0 and 0x004EC080 (Ghidra has the code around them as two unnamed functions, 0x004E90E0 and 0x004EC080). They read it back like this:

  • Low half: flags.
    • 0x01 and 0x02 pick which of the two loops draws the floater.
    • 0x04 sets the owner it is drawn for: DAT_RenderedUnitOwner becomes the current player's slot, or 0 when 0x10 is set too, and DAT_CurrentlyRenderedSpriteID becomes the floater's GM.
    • 0x08 (in the 0x01 loop, while a TileMapState setting at 0x01FE7ACC is on) moves it by the terrain height from getTotalHeightAt.
  • High half: a signed number (sar ecx, 0x10). With 0x20 set, the image ID plus the high half is the mask image passed to renderGMWithAlphaMask. Otherwise, when it is not 0, it is the blend strength passed to renderGMWithBlending; when it is 0, the floater is drawn with plain renderGM.

So PlaceUnit's 13 is 0x01 | 0x04 | 0x08, its 29 adds 0x10 (the siege tower is drawn for owner 0), and the 24 in the high half draws the "not allowed" preview blended. The comment said "the third byte"; in add0b81 it says the high half is a blend strength, and the values are written 13 | (24 << 16) and 29 | (24 << 16), with the same listing as before.

The header still declares int variation, in Floater and in createFloatingLayerElement. Splitting it into two shorts or naming the flags would touch every caller, so we left it out of this PR. We can do it in one of its own if you'd like that.

kotijekriv and others added 2 commits November 22, 2026 22:25
The original uses it as a signed 32-bit count in all six places that touch it. InitializeBasicMap (0x0042F0CD),
MenuItemActionHandler_MapEditorProperties_MainButtons (0x0044309F) and
MenuItemActionHandler_General_ToolbarButtonPressed (0x00444647) store 1 into it. PlaceUnit passes it to
spawnUnitsIntoNewTribe as its int unit count (0x00438659) and loops over it with signed compares: `jle` when it is
not above 0 (0x004386A9) and `jl` for the loop bound (0x004386D1). The header had it as undefined4, so PlaceUnit's
loop needed an (int) cast (TheRedDaemon's review of sourcehold#458). The two users on main, InitializeBasicMap and
ToolbarButtonPressed, compile to the same listing with it (quick_diff, ours against ours).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e variation's two halves

From TheRedDaemon's review of sourcehold#458:
- The bounds test and the tile index use Map::MC_MAP_XY_LIMIT_MIN_1 and Map::MC_MAP_XY_LIMIT in place of 399 and
  400.
- With unitPlacementCount an int (the commit before), the loop drops its (int) cast.
- The variation's high half is a blend strength, not a third byte: the comment says so, and the variations are
  written 13 | (24 << 16) and 29 | (24 << 16). createFloatingLayerElement stores the dword whole (0x004E64BC). renderMap's
  two floater loops (0x004E9EC0, 0x004EC080) test bits of its low half and take the high half as a signed number
  (sar 16): with flag 0x20 an offset added to the image ID for renderGMWithAlphaMask, otherwise, when not 0, the
  blend strength for renderGMWithBlending.

The listing is unchanged (quick_diff, ours against ours: the same 376 instructions), and a real build of main's /GL
list with this file off the list reads 100.0% raw and normalised.

Co-authored-by: Gynt <gynt@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the declaration/type change This requires changes to the generated/exported types or definitions. label Nov 22, 2026
The local unit type started as `(UnitType)-1`; main's UnitType names -1 UT_INVALID, so it is the name now. No other
change.

Measured: with the precompiled header, quick_diff gives the same listing for the pushed head's text and this one. A
narrow real build (main's /GL list and this file, with this PR's header change, the struct resolvers and the file's
function resolver on, sourcehold's reccmp with --resolve-wrapped-calls --ignore-security-cookie) reads 100.0% raw
and normalised with no differing line, and every other function reads as in the same build without the file.

Co-authored-by: Gynt <gynt@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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.

2 participants