OCR (src/fenigma/ocr.py):
- A "taking fire" report's reporting unit was added as a hostile Target,
not a friendly Ally -- no "Friendly"/"Hostile" prefix word exists in
that grammar for the usual inference to key off of, so it silently
defaulted to not-ally. Fixed with an explicit force_ally override
(_TAKING_FIRE_RE), and the shell/deadline (which an Ally tuple has no
fields for) now always splits into a synthetic StrikeRequest target at
the reporting position, even for the no-offset "on our position" case
that previously kept them on the entity itself.
- "Enemy <Type>#<id> Destroyed" kill-feed lines were silently dropping
for shorter/less distinctive type words (e.g. "Enemy Field Gun#1") --
_ALLY_PREFIX_RE only ever stripped "Friendly"/"Hostile", never
"Enemy", so the whole "EnemyFieldGun" token got alias/fuzzy-matched
against "Artillery" and missed by a mile. Longer type words
("Enemy Mechanized Infantry#2") only ever worked by fuzzy-match
accident. Now strips "Enemy" too (lookahead guards a BARE "Enemy#N"
report, which IS TargetType.ENEMY itself, from being stripped to an
empty, unresolvable string).
- "Field Gun" added to _TYPE_WORD_ALIASES as plain Artillery under
another name (confirmed by the user), not a missing unit type.
7 new/updated regression tests, 54 total passing.
Windows build (packaging/windows/): three real bugs found and fixed by
actually booting and driving the build VM live (VNC), not just guessing
from the README's "UNTESTED end to end" note:
- install.bat's MSYS2/WiX provisioning previously left NOTHING behind
once C:\OEM stopped existing (a 2-day-old BUILD_REQUEST sat unclaimed
the whole time) -- the build.bat/watch_build.bat persistence fix
(C:\FenigmaBuild instead of C:\OEM) is real and now confirmed live:
after a full container restart, the watcher auto-starts on login and
picks up a pending request with zero manual intervention.
- pip install pytesseract needs --break-system-packages (MSYS2's
mingw64 Python enforces PEP 668).
- mingw-w64-x86_64-opencv is the C++ library only; the actual Python
bindings are the separate mingw-w64-x86_64-python-opencv package,
never in install.bat's dependency list.
With all three, import fenigma.app succeeds and a real build attempt
gets through source copy, sanity check, dist-tree assembly, and WiX
harvest+compile -- further than this pipeline has ever gotten. Full
findings, including the still-open light.exe timeout and the OCR
multi-shell/deadline-phrasing/phantom-header gaps found along the way,
logged in TODO.md.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Auto-assignment (no real id known: a manual add, or an accepted
proposal with no confident marker-id read) must stay visually
distinct from a genuinely detected id, or a made-up number could
collide with or be mistaken for a real one. Reverts the previous
commit's switch to numeric auto-assignment (_next_free_numeric_id) --
that was wrong, caught by the user immediately. _next_free_id
(letters, rolling over to "AA"/"AB"/... past 26) is back as the
fallback, still scoped per type (that part of the previous change was
correct and stays). Plain numbers are reserved for an id
_accept_proposal is actually confident was read off the marker itself
(Proposal.detected_id), passed straight through and never touching
auto-assignment.
Also fixes detected_id's own collision pre-check in _accept_proposal,
which wasn't scoped per type either -- same bug as the Change ID
popover fix, just in a second place: a detected id could get
needlessly discarded because an unrelated type already used that
number, not because of a real collision.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The manual "Change ID" popover's collision check was never updated
when Board.add_target/add_ally's auto-id scheme changed to per-type
(commit d2f7067): it still rejected a rename if ANY target/ally in the
whole group had that id, regardless of type, so e.g. renaming an
Infantry to id "4" failed with "Another target already has id '4'"
just because an unrelated Mechanized already used it. Now scopes the
collision check to siblings of the SAME type, matching add_target/
add_ally exactly. Verified directly against the same expression run
on real Board/Target objects (a full GTK popover popup cycle needs a
real window surface, not available headlessly).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The coord was already shown right below via _draw_marker's own
coord=coord line -- repeating it in the main label too was pure
noise. Shows detected type/id instead when known ("? Mechanized#3",
same shape Target.name/Ally.name use, via TargetType.short so the
preview reads the same as what accepting it produces), falling back
to a bare "?" when neither is known.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Auto-assignment (Board.add_target/add_ally with no explicit id_) now
scopes its 1/2/3... sequence per TYPE within each group, not one
sequence shared across every type in the group -- Tank#1/Infantry#1
rather than Tank#A/Infantry#B, matching the game's own numbering.
Reverses the type-scoping half of an earlier fix in this file (see
TODO.md's "Allies and enemies seem to share indices" entry) per
explicit user direction; the targets-vs-allies namespace split that
fix also made is untouched, still correct. _next_free_id (letters,
rolling over to "AA" past 26) is replaced by _next_free_numeric_id --
a plain counter can't run out the way a fixed alphabet could, so
there's no equivalent rollover concern. test_models.py updated to
match (one test asserts the opposite of before, renamed accordingly).
detected_id (map_vision.read_marker_id) was being logged but never
shown anywhere a human could actually check it against the
screenshot before now: added to the proposal popover's heading and
the pending-proposal's own on-map label.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
detected_id (map_vision.read_marker_id) was wired into ground-truth
logging but never actually consumed when accepting a proposal --
every accepted target/ally silently got an auto-assigned A/B/C letter
regardless of what number the game itself shows for that unit.
_accept_proposal now prefers detected_id when present, falling back to
auto-assign on a collision (two markers misread to the same id, or a
real id that happens to match one already assigned) -- a duplicate id
is worse than losing traceability to the game's own number for that
one accept. Targets/allies keep their own separate id namespace, same
as auto-assignment already does elsewhere.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
read_marker_id (map_vision.py) reads each marker's own small "#<N>" id
label via template correlation, same approach as read_cell_label and
for the same documented reason (this text sits over the same aerial-
photo backdrop that defeated detection-based approaches for grid
labels). Wired end-to-end: find_markers -> Proposal.detected_id ->
save_marker_ground_truth's JSON. Reads against ScreenshotImport's
full_image when available, since the id text is tiny. Crop region and
threshold are a single-screenshot calibration, not yet validated
against real ground truth (documented as such).
Also switches save_marker_ground_truth/save_grid_correction to use
full_image over the WORK_W-downscaled image, so a human reviewing a
capture can actually read the small id text well enough to judge it.
Logs unit_score/unit_margin on every Proposal too (previously only
pass/fail `unit` was recorded), and measured current type-detection
reliability against the 6 existing ground-truth captures: 0/72 (0%)
accepted proposals had any confident detected_unit at all, not just
wrong guesses -- classify_marker never clears its own confidence floor
against real screenshots. Findings and next steps in TODO.md.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
"Accept as..." (proposal type-picker) and "Change type" (entity-edit)
opened to a visibly empty/unchanged popover with no traceback: swapping
an already-open Popover's child and re-popup()ing it reported the right
size internally but the compositor never repainted the reused surface.
Confirmed live via temporary debug instrumentation, not guessed. Fixed
by popping the old popover down and opening a genuinely new one at the
same anchor point instead of resizing in place.
Also adds a Target.underground_tier (1-3) marker: a "Mark underground"
entry in the entity-edit popover, rendered as the game's own Armor-tier
additive badge stacked directly on the unit icon. The badge is
scaled/positioned off its real opaque content (PIL bbox), not its PNG
canvas, since the additive art carries a lot of off-center transparent
padding; and overlaps down into the icon by a fixed pixel amount, since
both shapes taper to a point at the seam and exact bbox-touching still
read as a visible gap.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
BTRFS misdiagnosis in README
The build watcher was registered as a SYSTEM-context Scheduled Task
(schtasks /ru SYSTEM). Confirmed on a real run this never actually
works: Z:\ (the /shared mount) is mapped per interactive session, a
SYSTEM task has no session of its own and can't see it, so
watch_build.bat spun forever on its own "if not exist Z:\" wait -- a
build request sat unclaimed for hours with zero indication anything
was wrong. Fixed with an All-Users Startup-folder entry instead, which
runs in whichever user's session actually logs in.
Also correcting the README's earlier "BTRFS boot-loop" entry: that was
a misdiagnosis from reading the text log alone (repeated
"loading/starting Boot0004" lines). Actually looking at the noVNC
screen showed genuine, progressing Windows Setup the whole time --
Setup legitimately reboots the VM multiple times, each one re-prints
those same firmware lines. The chattr +C fix stays (real, independently
documented dockur/QEMU/BTRFS caveat) but likely wasn't fixing an actual
problem that time.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Real issue hit on a real run: dockur/windows warns about BTRFS storage
but it's not idle -- on this host it boot-looped Windows Setup for
hours (same log lines repeating forever, disk barely growing), a known
bad combination for QEMU disk images on a copy-on-write filesystem.
build_windows.sh now disables COW on storage/ itself (chattr +C,
harmless no-op on non-btrfs or an already-populated dir from a prior
run). README updated to reflect both real fixes now confirmed needed
on this host (this one, plus the earlier SELinux :Z mount fix) instead
of the original "written but never run" status.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Map screenshot reading (grid + unit detection) is working noticeably
better now; not sure exactly which of the recent fixes did it, but the
blanket "unreliable/fails often" caveat is no longer accurate enough
to keep. TODO.md still has the fuller fixed/open list.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
rerender on assign/alive/shell, add Windows build tooling
- Board.add_target/add_ally's id auto-assignment used a bare
next(c for c in string.ascii_uppercase if c not in used), which
raises StopIteration once 26 entities of a group exist -- a real
crash confirmed via a live traceback, and a direct regression from
moving that sequence from per-type to per-group. This was the actual
cause of "Accept as"/"Accept all" silently doing nothing. Fixed with
_next_free_id(), which rolls over to two-letter ids instead of
raising.
- New TargetType.STRIKE_REQUEST: the bearing/distance-offset "taking
fire" fire-support request (see the earlier two-entity split) now
creates this instead of reusing STRIKE, so a radioed-in request is
never confused with a strike the player placed themselves. Same
crosshair icon, excluded from type pickers/dedupe like STRIKE.
- The "Accept as..." popover on a detected map marker now uses the
same icon grid the entity-edit "Change type" popover does (was a
plain unfiltered text list of every TargetType, which also wrongly
offered STRIKE/STRIKE_REQUEST as pickable).
- Firing panel: _cycle_assignment/_toggle_alive/_pick_shell no longer
route through app.py's full solver+dedupe+canvas+panel refresh --
none of the three can affect the solver or dedupe, and none change
which cards exist or their order (except _toggle_alive in
hide/sort_later mode). New FiringPanel._rebuild_one() rebuilds just
the one changed card; on_visual_change is a new, lighter callback
(just a map redraw) for the two of these three that actually affect
it. This was a real, confirmed lag source with many units on the
board: every click on any of these was previously rebuilding every
card of every target.
- Map right-click entity menu: added "Mark destroyed"/"Mark alive",
reusing the same cheap-refresh path (new
FiringPanel.refresh_after_alive_change).
- packaging/windows/: a from-scratch (untested against a real boot)
MSYS2 + WiX .msi build pipeline for Windows, driven from Linux via
dockur/windows (KVM-in-container), no Windows machine or GitHub
required. See its own README for status/caveats.
- New/updated tests: id-namespace sharing + the 26-entity overflow
regression (tests/test_models.py), StrikeRequest split
(tests/test_ocr.py), warp_to_map's img_scale param
(tests/test_map_vision_warp.py). 44/44 passing.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
- Board.clear() now also drops allies; the "clear board?" guard checks
allies too. New Board.clear_units() + Clear button right-click menu
("clear enemies, units & flights", keeps Nest/spotters/RPs).
- An Ally with the ad-hoc TargetType.ENEMY showed "Enemy" on the map
popover/toast instead of "Ally" (icons.target_type_label already had
the fix for the picker, now reused everywhere else via app.py's
_display_name).
- Firing panel drag-reorder no longer triggers a full app refresh
(solver + dedupe + map redraw) on every drop, just a local rebuild.
- "Always show geo" didn't draw for Allies (missing from the overlay
candidate list); blast radius only respected selection, not the
show_geo_desc pin.
- ocr.py: added a second fire-support-request grammar ("Infantry#N
taking fire ... Requesting X Shell on our position at <coord> before
<time>", plus a bearing/distance-from-position variant), distinct
from the existing Marine Garrison one.
- New debug_capture.py: saves screenshots (+ metadata) the app handled
badly, for later tuning of map_vision/ocr against real failures:
map-read errors, user grid corrections (paired with the auto-detected
grid), screenshots that read as text but may have been a map, and
marker-detection ground truth (every proposal's accept/reject verdict
plus units added with no matching proposal) captured whenever a
screenshot stops being the active one.
- README: Known issues section (map screenshot reading, grid + unit
detection, is unreliable and fails often).
- 14 new tests (tests/test_models.py, tests/test_debug_capture.py, +
additions to tests/test_ocr.py), 38/38 passing.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
map_vision.py: marker shape test only matched diamonds, so friendly
(rectangle) markers could never be detected regardless of color match.
diamonds() now takes a per-side ideal shape (diamond for hostile, full
rectangle for friendly) with fill-ratio bands measured off real markers.
Merged tests/fixtures/map_shots/more/ into the main fixture set: 2
screenshots that solve fine (now 15.png/16.png, with hand-transcribed
ground truth) and 8 that are too low native resolution for the label
reader (same class as the existing 12.png) into too_hard/ as
17.png-24.png, with an explanatory README entry. Updated map_vision.py's
docstring numbers (9/12 solve, 104/131 points correct) to match.
TargetType: expanded from 11 to 44 members to cover every icon in
assets/icons/targets/{enemy,friendly}/, including 7 friendly-only types
(King, Police, General, Hospital, Fort, Civil-Military, Mechanized
Anti-Tank) with no enemy equivalent. UNKNOWN/ENEMY stay icon-less by
design (both are literal words the game's OCR'd text uses, confirmed via
ocr.py's _TYPE_BY_SHORT, so neither can be dropped without breaking real
parsing) and draw the same plain-dot fallback the map itself uses.
icons.py: collapsed the icon lookup into one canonical table
(_TARGET_ICON: TargetType -> (enemy_basename, friendly_basename), one
explicit row per type) instead of a basename table plus two exception
dicts layered on top -- with a startup assertion that every TargetType
has a row. Added build_target_type_grid(), an icon-grid picker (icon +
name, same idea as the existing Shell picker) that replaces the old
plain-text dropdown/list everywhere a type is chosen, and only offers
types the given side actually has real art for.
coord_dialog.py: Add/Edit Target and Add Ally now use the icon grid
instead of Adw.ComboRow. Fixed a resulting horizontal-scroll bug (an
unbreakable long word was blowing out cell width) and locked the
coordinate pickers back to 5 columns.
app.py: right-click quick-add now offers Spotter/RP alongside
Target/Ally/Strike, opens a real modal (not a Popover, which turned out
unreliable for a wide multi-row grid) to ask for a type instead of
silently defaulting to UNKNOWN, and doesn't repeat the coordinate on
every row. The type grid listens for "clicked" rather than "toggled" --
a grouped ToggleButton doesn't emit "toggled" when you click the one
that's already active, which meant confirming the pre-selected default
type silently did nothing.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
New bullet plus a figure showing a rectified screenshot on the board -- the
cell labels painted on the table land on the app's own grid lines, which is
the whole claim. Also notes OpenCV in the deps and the stack, and that this
is Linux-only.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
MIT for the code. Explicitly carved out: the icons in assets/icons/ and the
screenshots in tests/fixtures/ are the game author's work with no
redistribution permission granted, and Courier Prime is under the SIL Open
Font License 1.1 (text in assets/fonts/OFL.txt, extracted verbatim from the
font file's own name table rather than retyped).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
FEnigma contains the whole word "enigma" while still opening on Fe (iron),
matching IRON NEST; FeNigma only contained "nigma". The cost is that iron's
symbol is Fe, not FE.
Code paths are untouched: the Python package stays lowercase `fenigma`, and
the git remote URL is unchanged since the repository itself has not been
renamed. APP_ID moved too, which is safe -- it is only the GTK application
id, with no saved state derived from it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The existing clipboard button now routes images: a map-table shot goes to the
vision pipeline, anything else to the text OCR path as before. The decision
runs in a worker, since even the cheap pre-filter costs ~0.3s and solve()
takes 10-20s. solve() rejecting counts as "not a map" and falls through to
OCR, because it is the reliable verdict (0 false positives over 122 text
screenshots) where the pre-filter lets ~6% through; reporting a failure there
would mean a text screenshot never got read at all.
Grid first, units second. The one modal confirms or fixes the geometry only:
the screenshot with the reconstructed lattice drawn over it, plus four
draggable handles on one cell's corners. Four corners pin a homography
exactly (8 DOF, 2 equations each), and dragging any of them refits the whole
grid live. Detection deliberately does not run until this is accepted --
every unit position is expressed in grid coordinates, so detecting against a
grid about to be dragged would only be thrown away.
Once accepted the screenshot is rectified into board space and drawn as the
map's backdrop. Pre-warping is what makes it drawable at all: cairo has no
projective transform, but a rectified image places with a plain scale and
translate. Detected units then appear as proposals ON the map, drawn hollow
-- the same shape the map already uses for "this might be where it is", which
is exactly what a proposal is. Clicking one offers accept (with the detected
type or a corrected one) or reject; the header gains accept-all and
remove-screenshot, and removing the screenshot drops every proposal never
accepted, since they were only ever readings of it.
Separately, right-clicking any entity now opens an edit menu: change type,
change id, change position, delete. Which actions appear follows what the
entity actually has -- only Target/Ally carry a TargetType, Spotter's id is
an int, and the Nest is singular so it cannot be deleted. Changing an
existing target's type or id had no UI at all before this.
Also fixes warp_to_map, which composed only the lattice homography and
dropped the discrete (si,sj,du,dv) mapping that pins lattice indices to named
cells, so every automatically solved screenshot landed in the wrong place. It
happened to test fine because manual solutions have an identity mapping.
While there, the same routine had an off-by-one for a negative axis sign
(si*u+du runs from col+1 down to col across a cell, so floor() named the
neighbour); both now go through one shared GridSolution.grid_of.
Verified end to end through the real widgets on a fixture: grid phase yields
no proposals, four handles, a drag refits and still names cells correctly,
reset restores, a degenerate drag survives, accept warps to a 2000x1000
overlay, detection then yields proposals that hit-test, accept and reject
correctly, and removing the screenshot keeps accepted units only.
Completes the FEnigma rename in app.py (APP_ID, window title, class).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Reads a screenshot of the in-game map table and recovers where on the board
it is looking. The scene is a flat table under a perspective camera, so a
single homography describes grid<->screen exactly; that is fitted from line
evidence (LSD segments, vanishing-point RANSAC, 1-D lattice fits).
Line evidence alone cannot finish the job: the 1km cells and the 100m
subgrid are locally identical, so it fixes neither scale, axis assignment,
axis direction nor phase. Those come from the cell labels -- and the labels
are never *detected*, they are correlated where the grid says they must be
(9% in from a cell's left edge, 6% down from its top). Blob detection on
aerial-photo terrain finds texture, not glyphs; correlating a known template
at a known place has no such failure mode. The same score then ranks the
geometry hypotheses, since a wrong lattice puts the crop where no label is,
so one number resolves scale, axis assignment, direction, phase and anchor
together.
Markers are found by hostile/friendly colour plus an IoU test against an
ideal inscribed diamond, which cut a red-lit shot from 43 false positives to
2 while preserving every hand-verified count. Unit-type classification is
present but not yet reliable, and returns unknown rather than guessing.
Measured over the fixture set: 7 of 10 solve, each with 100% of its
ground-truth points in the correct cell (85/112 overall), residual spread
0.005-0.033 cells. The other three reject cleanly; none has ever produced a
plausible-but-wrong grid. Across 122 typewriter screenshots solve() accepted
none, which is what makes clipboard routing safe.
Fixtures: 10 map shots with hand-transcribed ground truth, plus 10
typewriter shots spanning 262-5366px for routing and future OCR tests. Map
shots wider than 2400px (the pipeline's own maximum working width) were
downscaled with their coordinates rescaled to match; re-measured afterwards,
the results are identical. Typewriter shots stay at native resolution
because OCR needs the text legible.
Drops docs/map_vision_plan.md and its WIP prototype: the design now lives in
the module docstring, next to the code it describes.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A real, reproducible bug reported as 'misplaced sometimes by a few
small squares': Coord.as_fraction() centers a sub-cell at x + 0.5 (so
a marker drawn at its own coord's exact pixel position round-trips
back to the same coord on click), which meant point_to_coord()'s own
rounding was landing exactly on a .5 boundary, the single worst case
for floating point, tiny representation error from the col/row math
upstream could tip round() to either side and silently return a coord
one sub-cell off from the one actually clicked.
Reproduced with zero pixel math involved at all, just feeding
Coord(...).as_fraction() straight back into point_to_coord(), ruling
out the zoom/pan refactor or the legend margin as the cause (both were
suspected first). Fixed by subtracting the 0.5 offset before rounding,
which recovers a value that's supposed to be an exact integer instead
of an exact half-integer, round() is robust to tiny float noise around
a true integer, just not around X.5.
Verified exhaustively (all 20,000 possible coordinates round-trip
correctly now, not just a handful of samples, since the original bug
was itself float-pattern-dependent) and locked in with a permanent
regression test.
The rest of the UI already adapted to system theme automatically via
libadwaita, only the hand-drawn Cairo map (grid lines, markers,
overlays, everything in grid_widget.py) was hardcoded to the dark
palette. Added a parallel light palette (first-pass guesses, same as
the Shell descriptions were, flagged for correction) and hooked
Adw.StyleManager's dark/light state, including its own live-update
signal, so switching the system theme while the app is running
repaints the map with the other palette immediately, not just at
startup.
Verified: rendered both palettes side by side with the same board
state (legible in both), and a live theme-switch test confirming the
module-level color names actually change value when the StyleManager
signal fires, not just once at construction.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Gdk.Rectangle(x=..., y=..., width=..., height=...) silently ignores
every constructor keyword argument in this PyGObject version (verified
directly: it always built a zeroed rect regardless of what was passed
in), so popover.set_pointing_to() was always pointing at the canvas's
top-left corner. Fixed by constructing the rect and assigning its
fields afterward, which does work.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
- Column/row legend labels: the one matching the hovered cell gets an
underline and a blue accent color (not yellow, which was already the
overlay/placement-preview color elsewhere on the map and would have
meant two unrelated things looked the same).
- SUBGRID_LINE (the fine per-cell lines added earlier) was accidentally
given a distinct blue hue on the first attempt at fixing its
visibility, overcorrecting: the actual ask was a shade sitting
between the background and the main grid line's white, not a
different color altogether. Now a neutral warm gray instead.
Verified with a rendered screenshot showing both together: the K/6
legend in blue with an underline, the subgrid a visibly distinct but
still neutral gray, not competing hues on the same map.
Tracks the hovered large cell (col, row) separately from marker
hit-testing, since it needs to update on any cursor motion, not just
when crossing a marker's hit radius, redrawn only when the actual cell
changes, not on every pixel of motion within the same one. Lines drawn
inside the existing clip region so they never bleed past the visible
viewport at any zoom/pan state, dimmer than the main grid lines
(0.6x alpha, tuned down further after an initial too-loud pass) so
they read as a subtle aid, not competing visual noise.
Verified with a rendered screenshot: the subdivision lines appear only
within the hovered cell, correctly clipped, and stay faint against the
main grid.
Below ICON_MIN_CELL_PX (42px cell width) everything still draws as the
plain colored dot it always has, a game icon at that size would just
be an illegible smudge. Past that threshold, Nest/Target/Ally markers
switch to the game's own unit icon for their type, drawn as a Cairo
surface (raw Cairo draw_func, not GTK widgets, so this loads PNGs
directly via cairo.ImageSurface.create_from_png(), cached per path so
a repeat draw doesn't re-hit disk).
icons.py's target_icon_path(type, is_ally) is the TargetType -> icon
file mapping, best-effort guesses the same way the Shell descriptions
were (flagged for correction): most types map onto the game's own
Enemy_*/Friendly_* unit icons (is_ally picks which set, falling back
to Enemy_ if a given type has no Friendly_ counterpart), TANK reuses
the Armor_Mechanized artwork (no dedicated tank icon exists), and
STRIKE gets its own crosshair (assets/icons/misc/Crosshair.png, not a
unit icon at all, a planned impact point) rather than a unit icon.
An ambiguous candidate (hollow, dashed-ring marker) never switches to
the icon regardless of zoom, an icon there would look more confident
about an unconfirmed position than the dashed ring is supposed to
convey.
Verified with rendered screenshots at both zoom levels: plain dots
below the threshold, real icons above it (Tank/Infantry/MarineGarrison/
Nest all confirmed showing their correct icons), and the Strike
crosshair specifically.
The quick keyboard-entry sequence (type a letter then three digits to
fill X/Y/x/y in one go) is the whole point of the Exact tab, but the
picker buttons are deliberately non-focusable (keyboard focus stays on
the dialog itself, see _make_picker's comment), so nothing was
auto-scrolling the group you're about to type into view the way a
real focused field would, on a dialog taller than its visible area
you'd end up typing digits blind past the fold. _scroll_to_stage() now
scrolls the upcoming picker group (or the Identity group, once all
four digits are in) to the top of the scroll area after each
character, and hands real keyboard focus to the id field once there's
nothing left for the digit sequence to fill.
Hit and fixed a real crash while wiring this up: translate_coordinates()
actually returns a plain (x, y) tuple on success in this PyGObject
version (not the documented (bool, x, y)) and a falsy value on
failure, unconditionally unpacking three values crashed immediately on
the very first keystroke. Verified directly against a live widget
before trusting the fix, not just against the docstring.
Verified with a GTK smoke test driving the real key-press handler
through a full X/Y/x/y sequence, confirming the scroll position
advances monotonically at each stage.
Every menu popover (Units/Spotters/Reference Points/Targets/Scout
Flights) stayed open on top of the modal dialog or map-click placement
its own 'Add <thing>' button just triggered, holding onto focus that
should have gone to the new dialog or the map instead. _add_row() now
takes a close() callback (threaded through from _make_menu_button,
which already owns the Gtk.Popover) and pops the popover down right
before calling on_click().
Verified end to end with a GTK smoke test: opens the real 'Scout
Flights' popover, clicks its real 'Add scout flight' button, confirms
the popover is no longer visible afterward.
Nest had its own single-entry popover for no strong reason, and Allies
was its own separate one right next to it, both are 'your own side of
the map'. Merged into one 'Units' popover, Nest always first (there's
only ever one), Allies listed below it, and moved to the first spot in
the header's row of menu buttons.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Two related changes:
1. TargetType.HOSTILE_ARTILLERY/HOSTILE_TANK renamed to ARTILLERY/TANK,
dropping the baked-in hostility assumption from the type name
itself (a type describes the unit kind now, not an allegiance).
Migration entries added for both, plus the already-existing
COASTAL_BATTERY one, so old save files still load.
2. A friendly contact ('FriendlyTank#1:', detected by stripping a
leading 'Friendly'/'Hostile' word off the type word before matching
it, see ocr.py's _resolve_target_type()) is NOT a Target with a flag
flipped, it's tracked as a new, entirely separate Ally
(Board.allies), with its own id namespace: an ally Tank#1 and a
hostile Target Tank#1 are two unrelated things that happen to share
an id, not a collision (verified directly, see the rendered
screenshot both coexisting). Ally intentionally has none of Target's
firing-relevant fields (shell/powder_charges/assignment/alive),
allies are never fired on. 'Hostile' and no prefix at all both mean
a regular (non-ally) Target, not-ally is the default.
Wired through: Board.add_ally/remove_ally, placed_entities_all()/
ambiguous_entities_all() (new 'ally' category, cyan on the map,
distinct from every other category's color), solver.resolve_board()
(allies' own clues resolve too), find_by_name() (an ally can be a
clue reference target), save/load round-trip, a new 'Allies' header
popover mirroring Targets' (position/hide/geo-overlay/remove, no
shell/charge/alive controls), and ParsedInfo.allies as a same-shaped
but separate dict from ParsedInfo.targets, merged by a new
_merge_allies() alongside _merge_targets() in _merge_all().
Verified: full test suite (added a dedicated OCR test for the Friendly/
Hostile/bare-prefix routing), a GTK smoke test round-tripping an ally
through save/load and the popover build, and a rendered screenshot
showing an ally Tank#1 and a hostile Target Tank#1 both on the map at
once with the same id, distinct colors, no collision.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Same pattern already established for AMMO_CACHE -> SUPPLY_CACHE: a
'Coastal Battery' is just a heavy fixed-emplacement HostileArtillery
under a different name in the game's own text, not a meaningfully
different unit type worth its own enum member. Removed the
TargetType.COASTAL_BATTERY member, added 'CoastalBattery' to
ocr.py's _TYPE_WORD_ALIASES (so 'Coastal Battery#2:' still parses,
now as a HostileArtillery), and a models.py migration entry so any
save file written before this change still loads correctly.
Verified the migration directly (COASTAL_BATTERY -> HOSTILE_ARTILLERY,
existing AMMO_CACHE -> SUPPLY_CACHE unaffected) and updated the one
test that asserted the old type.
Every fix here was verified directly (numeric checks against the view
math, rendered screenshots, GTK smoke tests), not just reasoned about,
after the previous zoom/square pass shipped with real problems still
in it.
Map fixes:
- Off-viewport entities bled through onto the canvas when zoomed in:
_km_to_px() has no inherent bound, an entity actually elsewhere on
the map still got projected and drawn if the result happened to land
within the canvas's pixel bounds. Clipped all marker/overlay/arrow/
scout-flight drawing to the grid's own visible rectangle.
- Gridlines themselves bled into the label margin above/left of the
grid: the line-drawing loop deliberately over-generated a couple of
lines past the true viewport edge (meant to cover a trailing partial
cell, which doesn't need its own line, just the whole-integer lines
already bounding it). Switched to ceil/floor bounds that only ever
produce in-range lines, verified directly against the view math for
a fractional zoom/pan (no clip needed for this half, the bug was
generating the wrong lines in the first place, not failing to hide
them).
- Square-cell letterbox padding stayed pixel-identical at every zoom
level (verified: same padding at 1x/2x/5x), which meant the fixed
bands ate a bigger and bigger share of an already-zoomed-in view.
Once actually zoomed in with square_cells on, the viewport's own
aspect now follows the canvas shape instead of staying locked to the
full map's 20:10 ratio, so cells come out square with zero
letterboxing rather than fixed padding. The whole-map view (zoom=1)
is unchanged, that's the one case that has a real reason to keep the
fixed 20:10 shape.
- Added drag-to-pan, active once actually zoomed in (at 1x the whole
map's already on screen, nothing to pan to). Guards against a drag's
release also firing as a click-select via a small pixel threshold.
Popover cleanup (Nest/Spotters/Reference Points/Targets):
- Removed each popover's own 'Load all from screenshot' bulk button
and every row's individual 'set this one from screenshot' button:
the universal clipboard button in the header already re-parses a
fresh screenshot/paste and merges it into everything it recognizes
by name, these were redundant category- and item-specific ways to
trigger the exact same merge. Deleted the now-dead
_set_*_from_screenshot_info() methods along with them.
- The trailing 'Add spotter'/'Add RP'/'Add target'/'Add scout flight'
rows are now a single full-width button (new _add_row() helper)
instead of the full two-button _row() layout, there's nothing to
screenshot into for something that doesn't exist yet.
Verified: full pytest suite, direct numeric check that no gridline
lands outside the grid rectangle at a fractional zoom/pan, a rendered
screenshot at 4x zoom confirming off-viewport entities no longer
appear and gridlines terminate cleanly at the edges, and a full-app
smoke test exercising drag-pan end to end including the post-drag
click-suppression.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Refactored GridCanvas's geometry around a single _View namedtuple
(cell_w/cell_h/grid_w/grid_h/pad_x/pad_y/viewport origin/visible
extent) instead of threading cell_w/cell_h/grid_h separately through
every draw and hit-test method, that's what makes the two new features
below tractable without a parameter explosion.
- Square-cell toggle (header button, 'view-grid-symbolic'): forces
cell_w == cell_h, letterboxing (padding) whichever axis has leftover
space instead of stretching cells to fill the widget. Off by default,
recovers the exact previous stretch-to-fill behavior.
- Scroll-wheel zoom: 1x (the whole 20x10 map, the old fixed behavior)
up to 10x, anchored at the cursor's last known position so the km
point under it stays under it as the zoom level changes, panned/
clamped so the viewport never hangs off the grid's edge. Grid lines,
column/row labels, and every marker only draw for the visible
viewport, not always the full 20x10 grid.
Also two bugs found and fixed along the way:
- The header's cursor-location readout showed AZ/distance-from-nest
numbers even when the cursor was off the map entirely:
bearing_deg_point()/distance_km_point() are happy to compute on any
raw km point, on- map or not, only the coord label itself checked
bounds. Now the whole readout is just 'off map' whenever the cursor
genuinely isn't over the grid.
- That bounds check initially reused solver.point_to_coord()'s own
tolerance, which deliberately forgives up to 0.5km past an edge
(rounding slop for noisy OCR'd coordinates), the wrong call for 'is
the mouse over the map', a cursor visibly off the drawn grid still
passed it. The cursor readout now uses a strict 0<=col<=COLS/
0<=row<=ROWS check instead.
Verified with GTK smoke tests: zoom in/out and pan-anchoring math,
square-cell letterboxing padding, hover/hit-testing, the toggle wired
end-to-end through the real header button, and the full app launching
and surviving the exact scenario that crashed it earlier in this same
session (an incomplete mid-refactor commit referenced _on_scroll before
it was defined, caught immediately by re-running the app, fixed by
finishing the refactor properly instead of patching around it).
Also, on the firing card: swapped the shell icon to come after the
powder-charge segments instead of before (per feedback), and gave the
assignment cycle button (L/R/-) the same 'image-button' style class its
icon-only siblings get automatically, it was visibly wider than them
for carrying a text label instead of an icon.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
_on_cursor_move() only checked map bounds for the coord label itself
('off map' vs a real grid ref), the AZ/distance-from-nest numbers next
to it were computed and shown regardless, bearing_deg_point()/
distance_km_point() are happy to run on any raw km point, negative or
past the 20x10 grid included, so a cursor genuinely off the map could
still show what looked like a real reading. Now the whole label is
just 'off map', no numbers, whenever point_to_coord() says there's no
real grid position there.
The previous 20px min-width/height looked like a regression (smaller
than before) once the button.<class> selector fix actually started
taking effect: before that fix, the rule was being silently ignored
entirely and the theme's own (bigger) default button min-size was what
users were actually seeing by accident. Now that the rule genuinely
applies, bumped to 28px, verified directly against the real allocated
widget size (28x28), not just the requested CSS value.
Several rounds of actually looking at the running app instead of just
the code, in order:
- The icon-only shell button on a firing card, and the popover-based
picker, both fought a genuine GTK sizing quirk: Gtk.Picture's natural
size is the source image's full native resolution (512x256) no
matter what set_size_request() says, so the button's own requested
size swung unpredictably depending on layout context (sometimes
comically wide, sometimes squeezed tiny). Fixed by pre-scaling the
actual pixel data with GdkPixbuf first (preserving real aspect ratio)
and wrapping the already-correctly-sized result, nothing left for
the surrounding layout to guess about.
- The shell icon PNGs themselves carry a lot of built-in transparent
padding around the actual artwork. Cropped all of them (except MSTD,
see below) to the same shared bounding box, computed as the union of
every file's real content so nothing gets clipped and every icon
stays aligned the same way.
- MSTD (mustard/YX blister agent) removed from the Shell enum entirely:
its own game icon is stamped 'UNAVAILABLE IN DEMO', it isn't actually
a real selectable shell in the game.
- Extra empty chrome around icon-only buttons turned out to be GTK CSS
specificity, not a missing property: GTK's CSS has no !important at
all (confirmed, its parser rejects it outright), and separately,
Gtk.MenuButton's CSS node is literally named 'menubutton', not
'button', so a 'button.<class>' selector silently matched zero
elements on it. The actual leftover padding lives on MenuButton's
internal child button node, reached with a child-combinator selector
('menubutton.<class> > button').
- The Add Strike dialog's shell picker is now an inline radio-style
grid (build_shell_grid(), Gtk.ToggleButton.set_group()) instead of a
button that opens a submenu popover: it's a 'pick one before
proceeding' dialog with room to just show every option up front,
hiding them behind an extra click didn't earn anything. The firing
card and its tighter row still use the popover version.
- Grid is 3 columns (was 4), sized bigger now that padding is real
content, not just empty canvas.
Also two unrelated but real bugs found and fixed while chasing this,
from actually reproducing what screenshots showed instead of taking
them as pure cosmetic complaints:
- Selecting a firing card shifted every icon/label inside it inward by
2px: only .firing-card-selected had a border, unselected cards had
none at all, so gaining a border on selection shifted the box's
content instead of just changing a color. Border is now reserved at
the same width on every card, always, selection only changes its
color from transparent.
- Changing a target's powder charge visibly shifted the whole card:
the charge segment buttons had no valign, so once the row got taller
(the bigger shell icon next to them), they silently inherited the
default FILL alignment and stretched into ovals instead of staying a
fixed circle. They also relied on plain 'flat'/'suggested-action' for
their off/on look, which draws no border at all when off, making an
unselected segment invisible against the card background. Both fixed
with a dedicated fixed-size, always-outlined CSS class and explicit
valign/halign=CENTER.
- The AZ column's screen position depended on the ELEV value's digit
count (elevation recalculates per charge picked), fixed with a
reserved width_chars on the elevation label.
Verified at each step by actually rendering the affected widget/dialog/
card to a PNG and looking at it (including a real FiringPanel card
before/after a charge change, pixel-diffed to confirm nothing but the
intended fill state moved), not by reasoning about the code alone.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Three real bugs from the first pass, all from actually looking at the
running app instead of just the code:
- Icons rendered tiny regardless of source resolution: Gtk.Image caps
displayed size to GTK's icon-size classes (built for symbolic
16/32px icons) no matter what you load into it. Switched to
Gtk.Picture, which sizes by the image's real dimensions.
- The popover's plain vertical list of rows squeezed down to a near-
unreadable width: ScrolledWindow sizes to its content's minimum, not
natural, size unless told otherwise, and a wrapping description
label's minimum width can shrink to almost nothing. Replaced with a
FlowBox grid (icon + blast radius under it, full description as a
tooltip) with an explicit natural width.
- That grid's column count was pinned to a fixed minimum, so a
popover that didn't have the room for that many columns overflowed
sideways and grew a horizontal scrollbar. min_children_per_line
dropped to 1 (lets it reflow to fewer columns instead) plus
hscrollbar_policy=NEVER as a hard backstop, not everyone has a
horizontal scroll wheel.
Also: the firing card's shell button now shows the icon alone (it
already has the shell's short code baked in, a text label next to it
was redundant on an already-tight row), sized to 64px wide/32px tall
to actually be legible, and a new small CSS rule trims the excess
button chrome around an icon-only face so the button isn't visibly
much larger than the icon it holds.
Both places the app asks for a shell (the Add Strike dialog's
Adw.ComboRow, and the firing panel's per-target shell popover) used to
show just the bare enum name in a plain list, nothing conveying what
the shell actually is. New icons.py builds a shared MenuButton +
popover from the game's own shell icon set (assets/icons/shells/,
already named to match Shell.name exactly): each row shows the shell's
icon, name, description, and blast radius, and the button face updates
to match whichever one gets picked.
Verified via a GTK smoke test that the button and its popover build and
open without crashing.
Pulled from the game's own GameAssets/Assets/Texture2D (gitignored as a
whole, not redistributed wholesale) into a tracked assets/icons/ so
they're actually usable in FeNigma's UI instead of us redrawing
equivalents:
- targets/enemy/, targets/friendly/: one marker per game unit type
('Enemy_*.png' / 'Friendly_*.png', the source files spell the latter
'Frendly_*.png', corrected on copy).
- reference_points/: the four lettered RP markers ('Refrence_Point_*.png'
in the source, typo corrected the same way).
- shells/: one icon per Shell enum member (shells.py), named to match
exactly so they're a direct Shell.name lookup, no mapping table
needed. A few source files don't carry the shell's short code in
their name (Mustard Gas_DemoBlocked -> MSTD, Tear Gas -> TEAR,
Propaganda -> PRPG, Phosgene -> PHGN, Nuclear -> ATMC), documented in
assets/icons/README.md.
- nest/IronNest.png: the Iron Nest/FDC unit icon.
- misc/ScoutPlane.png: fits the scout-flight planning feature.
Also commits the (already-made, previously uncommitted) .gitignore
entry for GameAssets itself, which is what makes pulling individual
icons out into a tracked directory sensible instead of contradictory.
Latent inconsistency flagged during the ocr.py refactor: solve_location()
already excludes a compass-word bearing (bearing_tolerance_deg set) from
its own bearings list before triangulating, since a toleranced bearing
names a sector, not a precise ray, and shouldn't be treated as if it
were one. explain_unresolved()'s bearings list didn't have the same
exclusion, so a toleranced-only bearing plus a distance clue could get
described as inconsistent geometry ('the bearing from X never crosses
the Ykm circle...') when the real reason nothing resolved is just that
the bearing was never usable for that math in the first place. Locked
in with a new test.
ocr.py grew through many incremental patches and had accumulated the
same two shapes copy-pasted with minor variation across the file:
- The full coordinate shape ('H3 5:5', letter + big-cell number + sub-
grid x:y) was hand-restated as a regex literal in six places
(_COORD_RE, _GRID_COORD_RE, _REQUESTED_ON_COORD_RE, the FO-report
patterns, _NAMED_AT_COORD_RE, _STATION_LINE_RE), each pairing its own
copy with its own try/except Coord(...) construction. Factored into
one _COORD_FRAGMENT regex piece and one _coord_from_groups() helper,
every call site now just embeds/calls it.
- The '<word><junk><digits>' type-id shape ('AmmoCache#3') was
similarly restated across _NAMED_HEADER_RE, _REF_NAMED_RE, and
_DESTROYED_RE. Factored into _TYPE_ID_FRAGMENT.
- Dropped _SEP, an unused leftover regex fragment.
No parsing behavior changed: every format ocr.py understands (standard
target/RP blocks, calibration line, destroyed reports, train-arrival
intel, ad-hoc Enemy installations and their destroyed reports,
Listening Post/Coastal Battery, Marine Garrison fire-support requests,
multi-word RP names, bare-name-header targets, bold-span coordinate
squashing, FO-report triangulation, the '<ref>: <value>' clue grammar,
16-point compass tolerance, grid-only coords) is still covered by the
full test suite, all 21 tests pass unchanged, plus a direct re-run of
the exact 'Enemy#name' example that prompted this session's bug report
to confirm detection by name still works.