From f6ba05b9175e8892fc21fe984f8e0b822faeb958 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Thu, 19 Nov 2026 19:36:47 +0100 Subject: [PATCH 01/89] City screen: clicks on its plots choose the tiles worked With a city's screen up, a click on the map now goes to the game core's city screen handlers, as the original engine hands them over, instead of selecting units: - a click: CvGame::handleCityScreenPlotPicked (a plot of the city's is worked or let go; the city's own plot gives the citizens back to the governor; a plot outside closes the screen, CITY_SCREEN_CLICK_WILL_EXIT) - a right click: handleCityScreenPlotRightPicked (the forced choice taken away) - a double click: handleCityScreenPlotDoublePicked (on the city: the screen closes) Plot clicks now say whether they are the second of a double click (SDL's click count). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 17 +++++++++++++++++ src/render/MapWindow.cpp | 7 +++++++ src/render/MapWindow.h | 1 + 3 files changed, 25 insertions(+) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..a2b161a5 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1281,6 +1281,23 @@ namespace ui.clearSelectionList(); continue; } + // The city screen up: the clicks are the game core's, as the original engine hands them + // over. A plot the city can work is worked or let go (CvCity::alterWorkingPlot: the + // city's own plot gives its citizens back to the governor); a right click takes away + // the forced choice; a click outside closes the screen (CITY_SCREEN_CLICK_WILL_EXIT), + // as does a double click on the city. + if (CvCity* city = ui.isCityScreenUp() ? ui.getHeadSelectedCity() : nullptr) + { + if (log) + std::printf(" city screen %s at %d,%d\n", click.right && !click.either ? "right click" : click.twice ? "double click" : "click", plot->getX(), plot->getY()); + if (click.right && !click.either) + game.handleCityScreenPlotRightPicked(city, plot, click.alt, click.shift, click.ctrl); + else if (click.twice) + game.handleCityScreenPlotDoublePicked(city, plot, click.alt, click.shift, click.ctrl); + else + game.handleCityScreenPlotPicked(city, plot, click.alt, click.shift, click.ctrl); + continue; + } // The gamepad's plot cursor: one's own units or city there are selected, as a left click; // anywhere else the selected units go there, as a right one (an interface mode's plot is a left click). if (click.either) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..639fe334 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -203,6 +203,7 @@ namespace oc4::render std::pair screenPixelsFor{ ~0ull, ~0ull }; int downX = 0, downY = 0; bool downLeft = false; + int buttonClicks = 1; // the mouse button's clicks in a row (2: a double click) std::function plotHelp; ButtonArt art; Theme theme; @@ -1228,7 +1229,10 @@ namespace oc4::render mouseY = y; const auto figure = figureUnder(x, y); if (const auto p = figure ? *figure : hoveredPlot(); p.first >= 0) + { clicks.push_back({ p.first, p.second, !downLeft, mods.shift, mods.ctrl, mods.alt, figure.has_value() }); + clicks.back().twice = buttonClicks >= 2; + } } if (down) { @@ -2296,7 +2300,10 @@ namespace oc4::render orbiting = down; } else if (e.button.button == SDL_BUTTON_LEFT || e.button.button == SDL_BUTTON_RIGHT) + { + buttonClicks = e.button.clicks; onButton(down && e.button.button == SDL_BUTTON_LEFT, down, x, y); + } break; } case SDL_EVENT_MOUSE_WHEEL: diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..ac954b2b 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -108,6 +108,7 @@ namespace oc4::render bool onFigure = false; // on a unit's figure (the plot is the unit's) bool either = false; // (the gamepad's plot cursor: `right` is the host's to say, see PadAction::Kind::PlotAct) bool clear = false; // (the gamepad's B: no plot's click, the selection let go) + bool twice = false; // the second click of a double click }; void setPlaying(bool playing); std::vector takeClicks(); From 75bf0f8b1883fef28c8ab6d22525bc8ba3b7df42 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Thu, 19 Nov 2026 19:47:56 +0100 Subject: [PATCH 02/89] City screen: the map in its frame takes clicks The city screen's top panel (Panel_City_Top_Style) spans the whole map area, but its skin is a frame with an empty middle (GFC_BITMAPSKIN_CENTER_EMPTY): only its top and sides are drawn. The interface took every click inside its rectangle, so the city's tiles could not be clicked. A themed panel now takes a click only where its skin draws something (Theme::covers, the same pieces Theme::draw puts down). The main interface's panels take the same clicks as before. Co-Authored-By: Claude Opus 5.5 --- src/render/Theme.cpp | 25 +++++++++++++++++++++++++ src/render/Theme.h | 3 +++ src/render/UiLayer.cpp | 3 ++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 81d93bda..ef20500d 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -992,6 +992,31 @@ namespace oc4::render o.imagePart(b.picture->key, b.picture->bgra, b.picture->width, b.picture->height, 1, x0, y0, x1, y1, b.x0, b.y0, b.x1, b.y1, alpha); } + bool Theme::covers(const Skin& skin, float rx0, float ry0, float rx1, float ry1, float x, float y) + { + for (const Layer& l : skin) + { + // (the layer's place and its nine pieces, as draw puts them) + const float x0 = rx0 + l.indent[0], y0 = ry0 + l.indent[1], x1 = rx1 - l.indent[2], y1 = ry1 - l.indent[3]; + if (x1 <= x0 || y1 <= y0 || x < x0 || x >= x1 || y < y0 || y >= y1) + continue; + if (l.middle == Layer::Middle::Fill && l.fillAlpha > 0) + return true; + if (!l.image && !l.center) + continue; + if (l.middle != Layer::Middle::Empty || !l.image) + return true; + float ml = l.margin[0], mt = l.margin[1], mr = l.margin[2], mb = l.margin[3]; + if (ml + mr > x1 - x0) + ml = mr = (x1 - x0) / 2; + if (mt + mb > y1 - y0) + mt = mb = (y1 - y0) / 2; + if (x < x0 + ml || x >= x1 - mr || y < y0 + mt || y >= y1 - mb) + return true; + } + return false; + } + void Theme::draw(Overlay& o, const Skin& skin, float rx0, float ry0, float rx1, float ry1, float alpha) { for (const Layer& l : skin) diff --git a/src/render/Theme.h b/src/render/Theme.h index 626a5657..aa52a42e 100644 --- a/src/render/Theme.h +++ b/src/render/Theme.h @@ -130,6 +130,9 @@ namespace oc4::render // Draws a skin over the rectangle (each layer at its indent). static void draw(Overlay& overlay, const Skin& skin, float x0, float y0, float x1, float y1, float alpha = 1); + // Whether the skin drawn over the rectangle draws anything at (x, y): not in a frame's + // empty middle (GFC_BITMAPSKIN_CENTER_EMPTY), as the city screen's around the map. + static bool covers(const Skin& skin, float x0, float y0, float x1, float y1, float x, float y); // A bitmap stretched over the rectangle. static void draw(Overlay& overlay, const Bitmap& bitmap, float x0, float y0, float x1, float y1, float alpha = 1); diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..98120a22 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -225,7 +225,8 @@ namespace oc4::render case Kind::Panel: if (const Theme::Panel* p = themedPanel(it)) { - if (!p->inner.empty() || !p->border.empty()) + if (Theme::covers(p->inner, it.x0, it.y0, it.x1, it.y1, float(x), float(y)) || + Theme::covers(p->border, it.x0, it.y0, it.x1, it.y1, float(x), float(y))) return true; } else if (!emptyPanel(it.style)) From ca59cbd6ad9ce7f713bc1d9cd983526f92a77fb7 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Thu, 19 Nov 2026 20:07:08 +0100 Subject: [PATCH 03/89] City screen: no unit stays selected under it Selecting a city (its screen) now lets go of the selected units, as the game core's CvGame::selectUnit lets go of the cities: a unit selected before stayed selected under the city screen, showed its way on a right click and could be ordered there. When the screen closes, the game core selects the next unit that waits (CvGame::updateSelectionList). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Interface.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/oc4core/Interface.cpp b/apps/oc4core/Interface.cpp index 97ae45b3..15579318 100644 --- a/apps/oc4core/Interface.cpp +++ b/apps/oc4core/Interface.cpp @@ -696,6 +696,10 @@ namespace oc4::host m_cities.clear(); if (pNewValue) { + // A city's screen and selected units go not together: the units are let go (as + // CvGame::selectUnit lets go of the cities; once the screen closes the game core + // selects the next unit that waits, CvGame::updateSelectionList). + m_selection.clear(); m_cities.insertAtEnd(pNewValue->getIDInfo()); m_cityScreen = true; lookAtX = pNewValue->getX(); From eeba7b753f234620453e1e5d4e874dd82b8be8ed Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Thu, 19 Nov 2026 20:45:09 +0100 Subject: [PATCH 04/89] End turn button as the original's: brass ring, tinted glass, its colours and beat The original draws the button's style (HUD_EndTurn_btn.tga, a brass ring) as it is, and over it the theme's glass dot (SF_CtrlTheme_Civ4_Control_Button_EndTurn_Skin: HUD_EndTurn.tga at its size in the middle) with the state's colour added less half (AddSigned). OpenCiv4 tinted the whole ring instead. The states were the wrong way round: END_TURN_GO, a steady green dot (EndTurnDot_Green), is the original's while units can still move; once the turn is over and the end of turn message is up, the dot is red, sinking from EndTurnDot_Red to EndTurnDot_DarkRed and back. While the other civilizations move the button is hidden (shouldDisplayEndTurnButton). The beat, measured in Wine at 120 frames a second: every 1.5 s the red rises over 0.5 s, holds 0.5 s and sinks over 0.5 s; the end of turn message ("Press to end turn...", "Waiting for other Civilizations...") blinks with it, gone around the darkest red. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 4 +++- apps/oc4core/python/oc4screens.py | 3 ++- src/render/Theme.cpp | 9 ++++++++ src/render/Theme.h | 3 +++ src/render/UiLayer.cpp | 36 ++++++++++++++++++++++++------- 5 files changed, 45 insertions(+), 10 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..5ffb2cb9 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -417,7 +417,9 @@ namespace oc4::host const PlayerTypes me = GC.getGame().getActivePlayer(); return me != NO_PLAYER && CvPlayerAI::getPlayerNonInl(me).isTurnActive() && ui.isEndTurnMessage(); }); - host.def("ui_end_turn_state", [&ui] { return int(ui.isEndTurnMessage() ? END_TURN_GO : END_TURN_OVER_HIGHLIGHT); }); + // (the original's: END_TURN_GO, a green button, while units can still move; the turn over, + // the end of turn message up, END_TURN_OVER_HIGHLIGHT, a red one) + host.def("ui_end_turn_state", [&ui] { return int(ui.isEndTurnMessage() ? END_TURN_OVER_HIGHLIGHT : END_TURN_GO); }); host.def("ui_should_show_research", [&ui] { const PlayerTypes me = GC.getGame().getActivePlayer(); return me != NO_PLAYER && CvPlayerAI::getPlayerNonInl(me).getCurrentResearch() == NO_TECH && !ui.isCityScreenUp(); diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..0574dc30 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -2211,7 +2211,8 @@ def determineWidth(self, szBuffer): return _textWidth(_text(szBuffer)) def getEndTurnState(self): return _cpe.EndTurnButtonStates(oc4host.ui_end_turn_state()) def shouldDisplayEndTurn(self): return oc4host.ui_end_turn_message() - def shouldDisplayEndTurnButton(self): return True + # (the original hides the button while the other civilizations move) + def shouldDisplayEndTurnButton(self): return oc4host.ui_turn_active() def shouldDisplayWaitingOthers(self): return not oc4host.ui_turn_active() def shouldDisplayWaitingYou(self): return False def shouldDisplayReturn(self): return False diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 81d93bda..aa57c8a1 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -938,6 +938,15 @@ namespace oc4::render return out; } + Color Theme::colour(std::string_view name, Color fallback) + { + Color c = fallback; + float alpha = 1; + if (m->loaded && !m->colour(nullptr, m->anywhere(std::string(name)), c, alpha)) + c = fallback; + return c; + } + Theme::Bitmap Theme::addSigned(const Bitmap& b, Color c) { if (!b) diff --git a/src/render/Theme.h b/src/render/Theme.h index 626a5657..902a6a4a 100644 --- a/src/render/Theme.h +++ b/src/render/Theme.h @@ -120,6 +120,9 @@ namespace oc4::render }; const Progress* progress(std::string_view style); + // A colour of the theme's by its full name ("SF_CtrlTheme_Civ4_Control_Color_EndTurnDot_Red"); + // the fallback when it has none. + Color colour(std::string_view name, Color fallback); // The bitmap with the colour added, less half (the AddSigned combine): how the end of turn // button's glass takes its red or green. Bitmap addSigned(const Bitmap& bitmap, Color colour); diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..cd3529b5 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -12,6 +12,15 @@ namespace oc4::render { + // The end of turn message's beat, as the original's (measured in Wine at 120 frames a second): + // every 1.5 s it rises over 0.5 s, holds 0.5 s, sinks over 0.5 s. 0 at its lowest, 1 where + // the hold starts and ends (1.5 in its middle: callers clamp). + static float endTurnBeat(double clock) + { + const double t = std::fmod(std::max(clock, 0.0), 1.5) / 0.5; + return float(std::min(t, 3 - t)); + } + namespace { using Kind = MapWindow::UiItem::Kind; @@ -504,7 +513,9 @@ namespace oc4::render break; case Kind::EndTurnText: if (!it.text.empty()) - o.richText(widen(it.text), sw / 2, y0 + 6, m_sizes[3], false, { 0.85f, 0.85f, 0.8f }, 0.6f + 0.4f * float(std::sin(clock * 3)), Overlay::Align::Center); + // (blinking with the end turn button's beat: gone around its darkest) + o.richText(widen(it.text), sw / 2, y0 + 6, m_sizes[3], false, { 0.85f, 0.85f, 0.8f }, + std::clamp((endTurnBeat(clock) - 0.25f) / 0.75f, 0.0f, 1.0f), Overlay::Align::Center); break; case Kind::Multiline: o.richBlock(widen(it.text), x0, y0, std::max(20.0f, w), fontSize(it.font), fontBold(it.font), kText, alpha); @@ -641,18 +652,27 @@ namespace oc4::render } case Kind::EndTurnButton: { - // The engine's own button where the script puts it: green when the turn is done. + // The engine's own button where the script puts it: the style's brass ring, and over it + // the theme's glass (SF_CtrlTheme_Civ4_Control_Button_EndTurn_Skin, at its size in the + // middle) taking the state's colour, added less half (AddSigned): EndTurnDot_Green while + // units can still move, steady; EndTurnDot_Red once the turn is over, sinking to + // EndTurnDot_DarkRed and back with the end of turn message's beat. const float cx = w > 0 ? (x0 + x1) / 2 : map ? map->x0 - 22 : sw - 240, cy = h > 0 ? (y0 + y1) / 2 : map ? map->y0 + 18 : sh - 140; const float r = w > 0 ? std::min(w, h) / 2 - 1 : 15; const bool green = it.text == "Green"; - const float pulse = green ? 0.75f + 0.25f * float(std::sin(clock * 5)) : 1.0f; - // The theme's glass takes the colour (EndTurnDot_Green / Red: added to it, less half), - // the green one pulsing. - const Color colour = green ? Color{ 0, std::round(0.75f * pulse * 16) / 16, 0 } : Color{ 0.75f, 0, 0 }; + Color colour = m_theme.colour("SF_CtrlTheme_Civ4_Control_Color_EndTurnDot_Green", { 0, 0.75f, 0 }); + if (!green) + { + const Color red = m_theme.colour("SF_CtrlTheme_Civ4_Control_Color_EndTurnDot_Red", { 0.75f, 0, 0 }); + const Color dark = m_theme.colour("SF_CtrlTheme_Civ4_Control_Color_EndTurnDot_DarkRed", { 0.39f, 0, 0 }); + const float k = std::min(endTurnBeat(clock), 1.0f); + colour = { dark.r + (red.r - dark.r) * k, dark.g + (red.g - dark.g) * k, dark.b + (red.b - dark.b) * k }; + } const Theme::Button* frame = m_theme.loaded() && !it.style.empty() ? m_theme.button(it.style) : nullptr; - if (frame && !frame->skin[0].empty()) + Theme::Skin glass = m_theme.loaded() ? m_theme.skin("", "SF_CtrlTheme_Civ4_Control_Button_EndTurn_Skin") : Theme::Skin{}; + if (frame && !frame->skin[0].empty() && !glass.empty()) { - Theme::Skin glass = frame->skin[hot && !frame->skin[1].empty() ? 1 : 0]; + Theme::draw(o, frame->skin[hot && !frame->skin[1].empty() ? 1 : 0], cx - r, cy - r, cx + r, cy + r, it.alpha); for (Theme::Layer& l : glass) l.image = m_theme.addSigned(l.image, colour); Theme::draw(o, glass, cx - r, cy - r, cx + r, cy + r, it.alpha); From 78a15e3388c6fcf2f6658a5170642929670d20d2 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 00:01:25 +0100 Subject: [PATCH 05/89] Game core: wide "+" in wide formats (text with a sign no longer lost off Windows) Points gamecore at the openciv4-dll commit that passes L"+"/L"" for %s in six wide Format calls (backlog: the city bar's defence, building and religion/corporation help lost their whole text on macOS and Linux). Co-Authored-By: Claude Opus 5.5 --- gamecore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gamecore b/gamecore index 7eb1d6be..01d65b26 160000 --- a/gamecore +++ b/gamecore @@ -1 +1 @@ -Subproject commit 7eb1d6be1ba76b795652af2c76e456b6a8183551 +Subproject commit 01d65b267a8507048da780e1326b11d5eef81aa2 From bf8951e355c40ef3200b01785c8c73e83ecb6536 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 00:06:50 +0100 Subject: [PATCH 06/89] Interface: isDebugMenuCreated and IsModem answer false The options screen asks both; they were unimplemented stubs that logged each call. There is no debug menu and no dial-up connection. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Interface.h | 1 + apps/oc4core/Utility.h | 1 + 2 files changed, 2 insertions(+) diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index e14dd520..382bcfec 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -215,6 +215,7 @@ namespace oc4::host bool updateCursorType() override { return false; } bool isFocusedWidget() override { return false; } bool isFocused() override { return false; } + bool isDebugMenuCreated() const override { return false; } // (the options screen asks; there is no debug menu) bool isScoresVisible() override { return false; } // The tech splash (the scripts' CvTechSplashScreen, with the tech's quote): only with the // game's screens up (Screens::start); without them the game core plays the short sound instead. diff --git a/apps/oc4core/Utility.h b/apps/oc4core/Utility.h index 6622eda8..bf41c71b 100644 --- a/apps/oc4core/Utility.h +++ b/apps/oc4core/Utility.h @@ -197,6 +197,7 @@ namespace oc4::host bool isGameActive() override { return m_gameActive; } int GetLocalNetworkID() override { return -1; } bool IsPitbossHost() const override { return false; } + bool IsModem() override { return false; } // (the options screen's network settings: no dial-up) int getChtLvl() override { return 0; } bool GetWorldBuilderMode() override { return m_interface.worldBuilder(); } int getCurrentLanguage() const override { return m_language; } From f322731f03a205de825ee434ebcf2ea1050f8049 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 00:07:22 +0100 Subject: [PATCH 07/89] Command line: --map with a scenario file relative to the current folder The engine works in the Beyond the Sword folder, so a relative scenario path no longer pointed at the file ("cannot read the scenario"). A --map that names an existing file is made absolute with the other command line paths; a map script's name (Fractal, ...) stays as it is. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..609b7562 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -364,6 +364,9 @@ namespace for (fs::path* p : { &o.civ4Root, &o.pythonHome, &o.logDir, &o.probeSave, &o.load, &o.save, &o.exec, &o.execFirst, &o.profileOut, &o.screenshot }) if (!p->empty()) *p = fs::absolute(*p); + // (--map is a map script's name, or a scenario's file: a file here is resolved too) + if (std::error_code ec; !o.game.mapScript.empty() && fs::is_regular_file(o.game.mapScript, ec)) + o.game.mapScript = fs::absolute(o.game.mapScript).string(); return o; } From 30daf68a0007051e8f59a7257a0a66e50270b801 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 11:59:35 +0100 Subject: [PATCH 08/89] Text in the game's own Sylfaen: its font folders and a Wine prefix's, a serif stand-in The theme (Resource/Themes/Civ4/Civ4Theme_Common.thm) asks for Sylfaen at 12, 14, 16 and 22 for all the interface's text. macOS and Linux lack it, so every text fell back to a sans face. The game ships it (Resource/Civ4/sylfaen{,b,i,bi}.ttf, Resource/Fonts, Assets/res/Fonts), and a game in a Wine prefix has the Windows fonts beside it (drive_c/windows/Fonts): Theme::fontFolders names them and Fonts::addFolders (FreeType) looks there too. No font is copied. A missing serif family (Sylfaen, Georgia, Times New Roman...) now gets a serif stand-in (Georgia, Noto Serif, DejaVu Serif, Liberation Serif, Times) before the sans defaults. macOS's symbol and CJK faces join the per-character fallbacks: the capital's star (U+2605) was a box. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 6 +++ src/render/Font.cpp | 3 ++ src/render/Font.h | 9 ++++- src/render/FontFreeType.cpp | 75 ++++++++++++++++++++++++++++--------- src/render/MapWindow.cpp | 7 +++- src/render/Overlay.cpp | 6 +++ src/render/Overlay.h | 2 + src/render/Theme.cpp | 30 +++++++++++++++ src/render/Theme.h | 4 ++ tests/game_fonts_test.cpp | 61 ++++++++++++++++++++++++++++++ 10 files changed, 182 insertions(+), 21 deletions(-) create mode 100644 tests/game_fonts_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index aa66b460..a2215647 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -402,6 +402,12 @@ target_link_libraries(theme_combine_test PRIVATE oc4_options oc4_render) add_test(NAME theme_combine COMMAND theme_combine_test) set_target_properties(theme_combine_test PROPERTIES FOLDER "tests") +add_executable(game_fonts_test tests/game_fonts_test.cpp) +target_include_directories(game_fonts_test PRIVATE src) +target_link_libraries(game_fonts_test PRIVATE oc4_options oc4_render) +add_test(NAME game_fonts COMMAND game_fonts_test) +set_target_properties(game_fonts_test PROPERTIES FOLDER "tests") + if(WIN32 AND TARGET freetype) add_executable(text_layout_freetype_test tests/text_layout_test.cpp src/render/TextLayout.cpp src/render/FontFreeType.cpp) target_include_directories(text_layout_freetype_test PRIVATE src) diff --git a/src/render/Font.cpp b/src/render/Font.cpp index 4ce03f79..c8c6fbd6 100644 --- a/src/render/Font.cpp +++ b/src/render/Font.cpp @@ -102,6 +102,9 @@ namespace oc4::render Fonts::~Fonts() = default; + // (Windows has the game's fonts installed: Sylfaen ships with it) + void Fonts::addFolders(const std::vector&) {} + int Fonts::face(const std::wstring& family, bool bold, bool italic) { return m->make(family, bold, italic, true); } const Fonts::Metrics& Fonts::metrics(int face) const { return m->faces[size_t(face)].metrics; } diff --git a/src/render/Font.h b/src/render/Font.h index 6c546178..6aa74856 100644 --- a/src/render/Font.h +++ b/src/render/Font.h @@ -5,6 +5,7 @@ // FreeType elsewhere (FontFreeType.cpp). #include +#include #include #include #include @@ -20,7 +21,13 @@ namespace oc4::render Fonts(const Fonts&) = delete; Fonts& operator=(const Fonts&) = delete; - // A face of the family (or a default one when it is missing); faces are numbered from 0. + // More folders whose fonts count as installed: the game's own (it ships Sylfaen in + // Resource/Civ4), a Wine prefix's Windows/Fonts. Families asked for before and missing + // are looked for again. + void addFolders(const std::vector& folders); + + // A face of the family (or a stand-in when it is missing: a serif one for a serif family); + // faces are numbered from 0. int face(const std::wstring& family, bool bold, bool italic); // In ems (times the size in pixels). diff --git a/src/render/FontFreeType.cpp b/src/render/FontFreeType.cpp index e218d544..be929f42 100644 --- a/src/render/FontFreeType.cpp +++ b/src/render/FontFreeType.cpp @@ -28,8 +28,15 @@ namespace oc4::render // Asked in turn for a family missing from the system, then for a character the face lacks. constexpr const wchar_t* kDefaults[] = { L"Segoe UI", L"DejaVu Sans", L"Liberation Sans", L"Noto Sans", L"Arial", L"Helvetica" }; + // For a missing serif family (the game's Sylfaen when neither the game's own fonts nor + // Wine's are found): serifs with a large x-height first, as Sylfaen's. + constexpr const wchar_t* kSerifFamilies[] = { L"sylfaen", L"georgia", L"times new roman", L"times", L"cambria", L"constantia", + L"palatino linotype", L"book antiqua", L"garamond" }; + constexpr const wchar_t* kSerifDefaults[] = { L"Sylfaen", L"Georgia", L"Noto Serif", L"DejaVu Serif", L"Liberation Serif", + L"Times New Roman", L"Times" }; constexpr const wchar_t* kFallbacks[] = { L"Segoe UI", L"Segoe UI Symbol", L"DejaVu Sans", L"Noto Sans", L"Noto Sans Symbols", - L"Noto Sans Symbols 2", L"Arial", L"Microsoft YaHei", L"Noto Sans CJK SC", L"Malgun Gothic", L"Meiryo", L"Nirmala UI" }; + L"Noto Sans Symbols 2", L"Arial", L"Microsoft YaHei", L"Noto Sans CJK SC", L"Malgun Gothic", L"Meiryo", L"Nirmala UI", + L"Arial Unicode MS", L"Apple Symbols", L"Hiragino Sans", L"PingFang SC", L"Apple SD Gothic Neo" }; // (the last: macOS's) std::wstring lower(std::wstring s) { @@ -217,31 +224,40 @@ namespace oc4::render std::vector faces; std::map, int> byName; + std::vector extra; // (addFolders') + void scan() { scanned = true; - std::error_code ec; for (const fs::path& folder : fontFolders()) - for (fs::recursive_directory_iterator it(folder, fs::directory_options::skip_permission_denied, ec), end; it != end; it.increment(ec)) + scan(folder); + for (const fs::path& folder : extra) + scan(folder); + } + + void scan(const fs::path& folder) + { + std::error_code ec; + for (fs::recursive_directory_iterator it(folder, fs::directory_options::skip_permission_denied, ec), end; it != end; it.increment(ec)) + { + const std::wstring ext = lower(it->path().extension().wstring()); + if (ec || (ext != L".ttf" && ext != L".otf" && ext != L".ttc")) + continue; + FT_Face f = nullptr; + if (FT_New_Face(library, it->path().string().c_str(), -1, &f) != 0) + continue; + const FT_Long count = f->num_faces; + FT_Done_Face(f); + for (FT_Long i = 0; i < count; ++i) { - const std::wstring ext = lower(it->path().extension().wstring()); - if (ec || (ext != L".ttf" && ext != L".otf" && ext != L".ttc")) + if (FT_New_Face(library, it->path().string().c_str(), i, &f) != 0) continue; - FT_Face f = nullptr; - if (FT_New_Face(library, it->path().string().c_str(), -1, &f) != 0) - continue; - const FT_Long count = f->num_faces; + if (f->family_name) + files.emplace(lower(widenAscii(f->family_name)), + File{ it->path(), i, (f->style_flags & FT_STYLE_FLAG_BOLD) != 0, (f->style_flags & FT_STYLE_FLAG_ITALIC) != 0 }); FT_Done_Face(f); - for (FT_Long i = 0; i < count; ++i) - { - if (FT_New_Face(library, it->path().string().c_str(), i, &f) != 0) - continue; - if (f->family_name) - files.emplace(lower(widenAscii(f->family_name)), - File{ it->path(), i, (f->style_flags & FT_STYLE_FLAG_BOLD) != 0, (f->style_flags & FT_STYLE_FLAG_ITALIC) != 0 }); - FT_Done_Face(f); - } } + } } int make(const std::wstring& family, bool bold, bool italic, bool orDefault) @@ -264,6 +280,12 @@ namespace oc4::render { if (!orDefault) return -1; + const std::wstring name = lower(family); + if (std::ranges::any_of(kSerifFamilies, [&](const wchar_t* f) { return name == f; })) + for (const wchar_t* other : kSerifDefaults) + if (lower(other) != name) + if (const int i = make(other, bold, italic, false); i >= 0) + return byName[key] = i; for (const wchar_t* other : kDefaults) if (other != family) if (const int i = make(other, bold, italic, false); i >= 0) @@ -331,6 +353,23 @@ namespace oc4::render FT_Done_FreeType(m->library); } + void Fonts::addFolders(const std::vector& folders) + { + bool added = false; + for (const fs::path& folder : folders) + { + std::error_code ec; + if (!fs::is_directory(folder, ec) || std::ranges::find(m->extra, folder) != m->extra.end()) + continue; + m->extra.push_back(folder); + if (m->scanned) + m->scan(folder); + added = true; + } + if (added) + m->byName.clear(); // (a family found missing, or a stand-in's, may be there now; the faces made stay) + } + int Fonts::face(const std::wstring& family, bool bold, bool italic) { return m->make(family, bold, italic, true); } const Fonts::Metrics& Fonts::metrics(int face) const { return m->faces[size_t(face)].metrics; } diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..6bac756d 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -91,8 +91,11 @@ namespace oc4::render overlay = std::make_unique(*renderer); updateUiScale(); overlay->setArt(&art); - // The game's interface theme: the screens' and the popups' look, the text's face. - if (theme.load(assets.layerRoots())) + // The game's interface theme: the screens' and the popups' look, the text's face (the + // game's own Sylfaen, from its folders or Wine's, where the system lacks it). + const bool themed = theme.load(assets.layerRoots()); + overlay->addFontFolders(theme.fontFolders()); + if (themed) { std::array sizes{}; for (int i = 0; i < 5; ++i) diff --git a/src/render/Overlay.cpp b/src/render/Overlay.cpp index 97b344f9..04e1a7ef 100644 --- a/src/render/Overlay.cpp +++ b/src/render/Overlay.cpp @@ -342,6 +342,12 @@ namespace oc4::render m_layouts.clear(); } + void Overlay::addFontFolders(const std::vector& folders) + { + m_fonts.addFolders(folders); + m_layouts.clear(); + } + void Overlay::rect(float x0, float y0, float x1, float y1, Color color, float alpha, float radius) { if (m_drawing && x1 > x0 && y1 > y0) diff --git a/src/render/Overlay.h b/src/render/Overlay.h index 41ebda36..95cb05c8 100644 --- a/src/render/Overlay.h +++ b/src/render/Overlay.h @@ -83,6 +83,8 @@ namespace oc4::render void resetShadow() { setShadow({ 0, 0, 0 }, 0.8f); } // The face for all text, and the pixel sizes of the markup's (the theme's). void setFonts(std::wstring family, const std::array& sizes); + // Folders whose fonts count as installed (the game's own, Wine's): Fonts::addFolders. + void addFontFolders(const std::vector& folders); // Drawing only inside the rectangle until unclip. void clip(float x0, float y0, float x1, float y1); diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 81d93bda..2644f269 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -847,6 +847,36 @@ namespace oc4::render std::filesystem::path Theme::file() const { return m->base; } + std::vector Theme::fontFolders() const + { + std::vector out; + std::error_code ec; + const auto add = [&](const fs::path& p) { + if (fs::is_directory(p, ec) && std::ranges::find(out, p) == out.end()) + out.push_back(p); + }; + for (const fs::path& layer : m->roots) // (each layer's Assets folder's parent) + { + add(layer / "Resource" / "Civ4"); + add(layer / "Resource" / "Fonts"); + add(layer / "Assets" / "res" / "Fonts"); + } + // A Wine prefix: .../drive_c/Program Files/... holds the Windows fonts the original had. + for (const fs::path& layer : m->roots) + for (fs::path p = layer; p.has_relative_path() && p != p.parent_path(); p = p.parent_path()) + if (lower(utf8Path(p.filename())) == "drive_c") + { + for (const char* fonts : { "windows/Fonts", "Windows/Fonts", "windows/fonts" }) // (the first there: one folder) + if (fs::is_directory(p / fonts, ec)) + { + add(p / fonts); + break; + } + break; + } + return out; + } + bool Theme::loaded() const { return m->loaded; } const std::vector& Theme::problems() const { return m->problems; } diff --git a/src/render/Theme.h b/src/render/Theme.h index 626a5657..f4dd0cf0 100644 --- a/src/render/Theme.h +++ b/src/render/Theme.h @@ -99,6 +99,10 @@ namespace oc4::render bool loaded() const; // The folder whose Resource it came from. std::filesystem::path file() const; + // The folders the game keeps its fonts in (it ships Sylfaen, which macOS lacks): each + // layer's Resource/Civ4 and Resource/Fonts and Assets/res/Fonts, then the Windows/Fonts of + // the Wine prefix the game is installed in, if it is. (Known once load has been called.) + std::vector fontFolders() const; // Problems met while reading (unknown syntax, missing pictures), once each. const std::vector& problems() const; diff --git a/tests/game_fonts_test.cpp b/tests/game_fonts_test.cpp new file mode 100644 index 00000000..05a7b98b --- /dev/null +++ b/tests/game_fonts_test.cpp @@ -0,0 +1,61 @@ +// Checks where the game's fonts are looked for (Theme::fontFolders): the original ships Sylfaen in +// Resource/Civ4 (and Resource/Fonts, Assets/res/Fonts), and a game installed in a Wine prefix has +// the Windows fonts it ran with in drive_c/windows/Fonts. A fake install is laid out here. + +#include "render/Theme.h" + +#include +#include +#include +#include + +using namespace oc4::render; +namespace fs = std::filesystem; + +namespace +{ + int failures = 0; + + void check(bool ok, const char* what) + { + if (!ok) + { + std::printf("FAILED: %s\n", what); + ++failures; + } + } +} + +int main() +{ + const fs::path tmp = fs::temp_directory_path() / "oc4_game_fonts_test"; + fs::remove_all(tmp); + const fs::path wineFonts = tmp / "drive_c" / "windows" / "Fonts"; + const fs::path civ4 = tmp / "drive_c" / "Program Files" / "Civ4"; + const fs::path bts = civ4 / "Beyond the Sword"; + for (const fs::path& p : { wineFonts, civ4 / "Assets" / "res" / "Fonts", civ4 / "Resource" / "Civ4", civ4 / "Resource" / "Fonts", + bts / "Assets", bts / "Resource" / "Themes" }) + fs::create_directories(p); + + Theme theme; + theme.load({ bts / "Assets", civ4 / "Assets" }); // (no Civ4.thm: the folders are known all the same) + const std::vector folders = theme.fontFolders(); + const auto at = [&](const fs::path& p) { return std::ranges::find(folders, p) - folders.begin(); }; + const long n = long(folders.size()); + check(n == 4, "four folders (the missing ones left out, the prefix's once)"); + check(at(civ4 / "Resource" / "Civ4") < n, "the theme's Resource/Civ4 (sylfaen*.ttf)"); + check(at(civ4 / "Resource" / "Fonts") < n, "Resource/Fonts"); + check(at(civ4 / "Assets" / "res" / "Fonts") < n, "Assets/res/Fonts"); + check(at(wineFonts) == n - 1, "the Wine prefix's windows/Fonts, last"); + + // Not in a Wine prefix: only the game's own. + fs::rename(tmp / "drive_c", tmp / "c"); + Theme plain; + plain.load({ tmp / "c" / "Program Files" / "Civ4" / "Assets" }); + check(plain.fontFolders().size() == 3, "no prefix: the game's three folders"); + + fs::remove_all(tmp); + if (failures == 0) + std::printf("game fonts: ok\n"); + return failures == 0 ? 0 : 1; +} From 16c8d3eaeb2e2e0bb43b1d4a8a9272097f3b43b4 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 12:10:05 +0100 Subject: [PATCH 09/89] Multiline text in the theme's normal font (size 3, 16 px), as the original draws it addMultilineText took a label's rule (the game font: size 2, 14 px); the original draws it in the GFC control's normal font, Civ4Theme_Common.thm's .Normal = Size3_Normal, as it does setText. Measured on Dawn of Man's body against the original: word spacing and line breaks now match. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4screens.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..60cfcb85 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -915,14 +915,17 @@ def attachTextGFC(self, szAttachTo, szName, text, eFont=1, eType=-1, iData1=-1, w = self._s.add(szName, 'text', szAttachTo, 'flow') w.text, w.font, w.wt, w.d1, w.d2 = _text(text), _int(eFont, 1), _int(eType), _int(iData1), _int(iData2) + # A multiline text is in the theme's normal font (Civ4Theme_Common.thm's .Normal: size 3, Sylfaen + # 16), as a setText is; font 3 (the menus') draws and measures it so. Dawn of Man's body, for one, + # is 16 px in the original. def addMultilineText(self, szName, szText, iX, iY, iWidth, iHeight, eType=-1, iData1=-1, iData2=-1, iJustify=_FONT_LEFT): w = self._s.add(szName, 'multiline') w.text, w.x, w.y, w.w, w.h = _text(szText), int(iX), int(iY), int(iWidth), int(iHeight) - w.wt, w.d1, w.d2, w.flags = _int(eType), _int(iData1), _int(iData2), _int(iJustify, _FONT_LEFT) + w.wt, w.d1, w.d2, w.flags, w.font = _int(eType), _int(iData1), _int(iData2), _int(iJustify, _FONT_LEFT), 3 def attachMultilineText(self, szAttachTo, szName, szText, eType=-1, iData1=-1, iData2=-1, iJustify=_FONT_LEFT): w = self._s.add(szName, 'multiline', szAttachTo, 'flow') - w.text, w.wt, w.d1, w.d2, w.flags = _text(szText), _int(eType), _int(iData1), _int(iData2), _int(iJustify, _FONT_LEFT) + w.text, w.wt, w.d1, w.d2, w.flags, w.font = _text(szText), _int(eType), _int(iData1), _int(iData2), _int(iJustify, _FONT_LEFT), 3 # The engine's own: the end of turn message ("EndTurnText") and the end turn button # ("EndTurnButton", its state "Red" or "Green"). From d91dc7a1adad9e18d109282d831c893f67a458cc Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 13:27:36 +0100 Subject: [PATCH 10/89] Next/previous city with no city selected: the city nearest the camera BUG's city cycle arrows by the minimap (MainCityScrollMinus/Plus, WIDGET_CITY_SCROLL) and the Home/End keys run CONTROL_NEXTCITY/PREVCITY. With no city selected the game core asks the interface's selectLookAtCity, which was a stub, so they did nothing on the map. Now it selects the active player's city nearest the plot the camera looks at (as a selection, not the city screen); later presses cycle on from it (CvGame::cycleCities). getLookAtPlot gives that plot, and getSelectionPlot is the selected city's plot while cities are selected, so lookAtSelectionPlot moves the camera there. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Interface.cpp | 25 +++++++++++++++++++++++++ apps/oc4core/Interface.h | 7 ++++++- apps/oc4core/main.cpp | 6 ++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/apps/oc4core/Interface.cpp b/apps/oc4core/Interface.cpp index 97ae45b3..e3c35737 100644 --- a/apps/oc4core/Interface.cpp +++ b/apps/oc4core/Interface.cpp @@ -164,10 +164,35 @@ namespace oc4::host CvPlot* Interface::getSelectionPlot() { + // (cities selected, as next/previous city leaves them: the first city's plot) + if (CvCity* city = getHeadSelectedCity()) + return city->plot(); CvUnit* head = getHeadSelectedUnit(); return head ? head->plot() : nullptr; } + CvPlot* Interface::getLookAtPlot() + { + return cameraX >= 0 ? GC.getMap().plot(cameraX, cameraY) : nullptr; + } + + void Interface::selectLookAtCity(bool bAdd) + { + CvPlot* at = getLookAtPlot(); + if (!at) + return; + CvCity* city = GC.getMap().findCity(at->getX(), at->getY(), GC.getGame().getActivePlayer(), NO_TEAM, false); + if (!city) + return; + if (bAdd) + { + clearSelectedCities(); + addSelectedCity(city, false); + } + else + selectCity(city, false); + } + bool Interface::soundPlace(const NiPoint3& point, std::optional& place) { place.reset(); diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index e14dd520..89d5d73a 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -59,6 +59,9 @@ namespace oc4::host void selectCity(CvCity* pNewValue, bool bTestProduction) override; void addSelectedCity(CvCity* pNewValue, bool bToggle) override; void clearSelectedCities() override; + // Next/previous city (Home, End, BUG's arrows by the minimap) with no city selected: the + // active player's city nearest the plot the camera looks at. + void selectLookAtCity(bool bAdd) override; bool isCitySelected(CvCity* pCity) override; CvCity* getHeadSelectedCity() override; bool isCitySelection() override { return getHeadSelectedCity() != nullptr; } @@ -69,6 +72,8 @@ namespace oc4::host // Where the DLL asked the camera to go (lookAtSelectionPlot, lookAtCityOffset), for the // window; -1 none. int lookAtX = -1, lookAtY = -1; + // The plot the camera looks at now (the window's, each frame); -1 none. + int cameraX = -1, cameraY = -1; bool isSelected(const CvUnit* pUnit) const { return selected(pUnit); } void lookAtCityOffset(int iCity) override; @@ -221,7 +226,7 @@ namespace oc4::host bool techSplash = false; bool noTechSplash() override { return !techSplash; } bool isInAdvancedStart() const override { return false; } - CvPlot* getLookAtPlot() override { return nullptr; } + CvPlot* getLookAtPlot() override; CvPlot* getGotoPlot() override { return m_gotoPlot; } // Where the right button held would send the selection (the game core's plot help then gives the odds of an attack there). void setGotoPlot(CvPlot* plot) { m_gotoPlot = plot; } diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..1b413f76 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1098,6 +1098,12 @@ namespace } changed = true; } + // (the plot the camera looks at, for the game's getLookAtPlot: next/previous city with + // no city selected picks the city nearest it) + { + const auto look = window.look(); + ui.cameraX = int(std::floor(look.x)), ui.cameraY = int(std::floor(look.y)); + } auto clicks = window.takeClicks(); // (a scripted game answers what it does not expect with the popup's first button) if (!script.empty() && script.front() != '#' && script.front() != '\'' && script.front() != '%' && ui.shownPopup() && Clock::now() - typed > std::chrono::milliseconds(1500)) From 4d78cc364f1a2043d9f5a60f46ac1d2ef84c394b Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 13:39:24 +0100 Subject: [PATCH 11/89] Minimap toggles kept in the player's profile, as the original keeps them The original keeps four of the toggles by the minimap in its player profile (Profiles/.pfl, named by CivilizationIV.ini's UserProfile): the plot grid, the bare map, the yields and the scores, as CyUserProfile's getGrid, getMap, getYields and getScores. It writes the file at each click, and every game takes them from there: after a restart, a new game, and a loaded save (a save made with the grid on loads with the profile's grid). The unit and resource icon layers are not kept. (Watched in Wine.) OpenCiv4 now keeps them in its own profile (Documents/My Games/openciv4/ profile.ini) as grid=, map=, yields=, scores=: oc4options gives them to the host when the profile is read, and Screens::frame tells it when one is switched, by its button or its key. The scores toggle works (it did nothing, and the scores showed always), and CyUserProfile / CyInterface read the toggles as they are. New test minimap_toggles (oc4options with a stand-in host): a switched toggle is in profile.ini at once and comes back after a restart and with readFromFile; an older profile gives the defaults. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 7 ++ apps/oc4core/Interface.h | 9 +- apps/oc4core/Screens.cpp | 41 +++++++++ apps/oc4core/Screens.h | 4 + apps/oc4core/python/oc4options.py | 50 +++++++++-- apps/oc4core/python/oc4screens.py | 27 +++--- tests/minimap_toggles_test.py | 134 ++++++++++++++++++++++++++++++ 7 files changed, 252 insertions(+), 20 deletions(-) create mode 100644 tests/minimap_toggles_test.py diff --git a/CMakeLists.txt b/CMakeLists.txt index aa66b460..e0f838a1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -402,6 +402,13 @@ target_link_libraries(theme_combine_test PRIVATE oc4_options oc4_render) add_test(NAME theme_combine COMMAND theme_combine_test) set_target_properties(theme_combine_test PROPERTIES FOLDER "tests") +# The minimap's toggles kept in the player's profile (oc4options.py, with a stand-in host). +find_package(Python3 COMPONENTS Interpreter QUIET) +if(Python3_Interpreter_FOUND) + add_test(NAME minimap_toggles COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/tests/minimap_toggles_test.py + ${CMAKE_CURRENT_SOURCE_DIR}/apps/oc4core/python) +endif() + if(WIN32 AND TARGET freetype) add_executable(text_layout_freetype_test tests/text_layout_test.cpp src/render/TextLayout.cpp src/render/FontFreeType.cpp) target_include_directories(text_layout_freetype_test PRIVATE src) diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index e14dd520..5a312d43 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -215,7 +215,14 @@ namespace oc4::host bool updateCursorType() override { return false; } bool isFocusedWidget() override { return false; } bool isFocused() override { return false; } - bool isScoresVisible() override { return false; } + // The scores by the minimap (CONTROL_SCORES), shown as the player's profile has them. + std::atomic scores = true; + bool isScoresVisible() override { return scores; } + void toggleScoresVisible() override + { + scores = !scores; + setDirty(Score_DIRTY_BIT, true); + } // The tech splash (the scripts' CvTechSplashScreen, with the tech's quote): only with the // game's screens up (Screens::start); without them the game core plays the short sound instead. bool techSplash = false; diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..207e2988 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -126,6 +126,9 @@ namespace oc4::host std::wstring g_help; // the help shown now (CyInterface.getHelpString) std::function g_textWidth; // how wide a text is in the window render::MapWindow::UiDisplay g_display; // the window's, for the scale's choices + // The minimap's toggles as the player's profile has them (mapToggles; none before the + // profile is read): Screens::frame keeps it so when one is switched. + std::optional> g_profileToggles; std::function g_textHeight; // how high it is, wrapped at a width // (before the window is up: its markup left out, a symbol about two letters wide) @@ -194,6 +197,12 @@ namespace oc4::host return places; } + std::array mapToggles(Utility& utility) + { + const Interface& ui = utility.gameInterface(); + return { utility.engine().grid.load(), ui.bareMap.load(), ui.showYields.load(), ui.scores.load() }; + } + void registerScreenFunctions(Utility& utility) { auto host = py::reinterpret_borrow(PyImport_AddModule("oc4host")); @@ -267,6 +276,24 @@ namespace oc4::host // (the graphic options it has: the game core and the window ask the utility) host.def("set_graphic_option", [&utility](int option, bool on) { utility.setGraphicOption(option, on); }); host.def("reset_graphic_options", [&utility] { utility.resetGraphicOptions(); }); + // The map's toggles by the minimap the original keeps in the player's profile (the plot + // grid, the bare map, the yields, the scores: CyUserProfile's getGrid, getMap, getYields, + // getScores): the profile's, as loaded, and what they are now (Screens::frame keeps them). + host.def("map_toggles", [&utility] { return mapToggles(utility); }); + const auto setMapToggles = [&utility, &ui](bool grid, bool bareMap, bool yields, bool scores) { + utility.engine().grid = grid; + ui.bareMap = bareMap; + ui.showYields = yields; + ui.scores = scores; + ui.setDirty(Score_DIRTY_BIT, true); + ui.setDirty(GlobeLayer_DIRTY_BIT, true); // (the buttons' states) + }; + // (the profile's, as read; a script's switch, as the game's controls do it) + host.def("load_map_toggles", [&utility, setMapToggles](bool grid, bool bareMap, bool yields, bool scores) { + setMapToggles(grid, bareMap, yields, scores); + g_profileToggles = mapToggles(utility); + }); + host.def("set_map_toggles", setMapToggles); host.def("set_ui_scale", [&utility](int percent) { utility.setUiScale(percent); }); // W A S D panning: the profile's, as loaded; the player's, from the options' check box. host.def("set_wasd_pan", [&utility](bool on) { utility.setWasdPan(on); }); @@ -918,6 +945,20 @@ if _walls: } } window.setAutoEndTurn(m_utility.autoEndTurn()); + // (a minimap toggle switched, by its button or its key: kept in the profile, as the + // original keeps it at once, for every game after) + if (const auto toggles = mapToggles(m_utility); g_profileToggles && toggles != *g_profileToggles) + { + g_profileToggles = toggles; + try + { + py::module_::import("oc4options").attr("setMapToggles")(toggles[0], toggles[1], toggles[2], toggles[3]); + } + catch (py::error_already_set& e) + { + printPythonError(e); + } + } if (!m_menu) // (the main menu has no map to scroll) window.setEdgeScroll(m_utility.edgeScroll()); g_display = window.uiDisplay(); diff --git a/apps/oc4core/Screens.h b/apps/oc4core/Screens.h index 5f64207c..412007c6 100644 --- a/apps/oc4core/Screens.h +++ b/apps/oc4core/Screens.h @@ -12,6 +12,7 @@ #include "GameSession.h" #include "render/MapWindow.h" +#include #include #include #include @@ -38,6 +39,9 @@ namespace oc4::host // The oc4host functions CyInterface (oc4screens.py) is built on; before the scripts load. void registerScreenFunctions(Utility& utility); + // The minimap's toggles the player's profile keeps: the plot grid, the bare map, the yields, + // the scores (CyUserProfile's getGrid, getMap, getYields, getScores). + std::array mapToggles(Utility& utility); // Which soundscape (an index of the soundscape table; -1: none) each terrain, feature and // improvement type has, and each era's cities by size (small, medium, large): the types diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 4b2d7a83..9495780f 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -9,7 +9,11 @@ ## ## CyUserProfile is the player's profile those callbacks read and set: the volumes (the sounds ## play as loud), the graphic and player options, the clock; kept in the profile file the host -## names (Documents\My Games\openciv4\profile.ini). +## names (Documents\My Games\openciv4\profile.ini). It also keeps the map's toggles by the minimap +## that the original keeps in its profile (Profiles\.pfl, written at each click): the plot +## grid, the bare map, the yields and the scores (grid=, map=, yields=, scores=); every game, new, +## loaded or after a restart, starts with them as the profile has them. The unit and resource +## icon layers are not kept (nor in the original). import CvPythonExtensions as _cpe import oc4host @@ -48,7 +52,9 @@ def _scales(): 'graphicsLevel': 0, 'renderQuality': 0, 'globeView': 0, 'movieQuality': 0, 'mainMenu': 0, 'antiAliasing': 0, 'uiScale': 0, 'speakers': '', 'musicPath': '', 'voice': False, 'wasdPan': False, 'autoEndTurn': False, 'edgeScroll': True, + 'grid': False, 'map': False, 'yields': False, 'scores': True, } +_TOGGLES = ('grid', 'map', 'yields', 'scores') # (CyUserProfile's getGrid, getMap, getYields, getScores) def _path(): @@ -79,7 +85,7 @@ def _load(): _profile['nosound'][parts[1]] = value == '1' elif parts[0] in ('graphic', 'player'): _profile[parts[0]][int(parts[1])] = value == '1' - elif parts[0] in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): + elif parts[0] in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll') + _TOGGLES: _profile[parts[0]] = value == '1' elif parts[0] in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale'): _profile[parts[0]] = int(value) @@ -98,7 +104,7 @@ def _save(): lines = [] for key in ('name', 'speakers', 'musicPath'): lines.append('%s=%s' % (key, _profile[key])) - for key in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): + for key in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll') + _TOGGLES: lines.append('%s=%d' % (key, 1 if _profile[key] else 0)) for key in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale'): lines.append('%s=%d' % (key, _profile[key])) @@ -130,6 +136,31 @@ def _applyGraphics(): pass +def _applyToggles(): + """The minimap's toggles as the profile has them, to the host (a new game, a loaded one and + the next start of the program all take them so).""" + try: + oc4host.load_map_toggles(*[bool(_profile[k]) for k in _TOGGLES]) + except Exception: + pass + + +def setMapToggles(grid, bareMap, yields, scores): + """A toggle by the minimap switched (its button or its key; the host tells): kept at once.""" + now = dict(zip(_TOGGLES, (bool(grid), bool(bareMap), bool(yields), bool(scores)))) + if [_profile[k] for k in _TOGGLES] != [now[k] for k in _TOGGLES]: + _profile.update(now) + _save() + + +def _toggle(i): + """A minimap toggle as it is now (the profile's, without the host).""" + try: + return bool(oc4host.map_toggles()[i]) + except Exception: + return bool(_profile[_TOGGLES[i]]) + + # W A S D panning (openciv4's own option, no game's): its check box on the options' Game tab, # above the language; while it is on, Ctrl+Shift+W in the window turns it off (the host calls setWasdPan). WASD_PAN_CHECKBOX = 'Oc4WasdPanCheckBox' @@ -252,7 +283,7 @@ def setProfileName(self, s): _profile['name'] = str(s) def getNumProfileFiles(self): return 1 def getProfileFileName(self, i): return 'PROFILES\\%s.prf' % _profile['name'] def loadProfileFileNames(self): pass - def readFromFile(self, s): _load(); _applyVolumes(); _applyGraphics(); return True + def readFromFile(self, s): _load(); _applyVolumes(); _applyGraphics(); _applyToggles(); return True def writeToFile(self, s): _save(); return True def deleteProfileFile(self, s): return False def resetOptions(self, eTab): @@ -346,11 +377,11 @@ def set24Hours(self, b): _profile['hours24'] = bool(b) def wasClockJustTurnedOn(self): return False def setClockJustTurnedOn(self, b): pass - # the map's toggles by the minimap, as they start - def getGrid(self): return False - def getMap(self): return False - def getYields(self): return False - def getScores(self): return True + # the map's toggles by the minimap (the profile keeps them as they are switched) + def getGrid(self): return _toggle(0) + def getMap(self): return _toggle(1) + def getYields(self): return _toggle(2) + def getScores(self): return _toggle(3) def _volumeAccessors(): @@ -837,3 +868,4 @@ def _toggleAlarm(bOn, iHour=0, iMin=0): _load() _applyVolumes() _applyGraphics() +_applyToggles() diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..fc4eceb3 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -35,6 +35,13 @@ _editFocus = [None] # the edit box typed into: (file id, name), or None +def _setToggle(i): + """A minimap toggle switched from a script (CyInterface's toggle...): as its control does.""" + t = list(oc4host.map_toggles()) + t[i] = not t[i] + oc4host.set_map_toggles(*t) + + def _changed(): _version[0] += 1 @@ -2227,15 +2234,15 @@ def isFlashing(self): return False def checkFlashUpdate(self): return False def checkFlashReset(self, ePlayer): pass - def isScoresVisible(self): return True + def isScoresVisible(self): return bool(oc4host.map_toggles()[3]) def isScoresMinimized(self): return False def toggleScoresMinimized(self): pass - def toggleScoresVisible(self): pass + def toggleScoresVisible(self): _setToggle(3) def isOOSVisible(self): return False def isNetStatsVisible(self): return False - def isYieldVisibleMode(self): return False - def toggleYieldVisibleMode(self): pass - def toggleBareMapMode(self): pass + def isYieldVisibleMode(self): return bool(oc4host.map_toggles()[2]) + def toggleYieldVisibleMode(self): _setToggle(2) + def toggleBareMapMode(self): _setToggle(1) def isFocused(self): return False def isFocusedWidget(self): return False def isInAdvancedStart(self): return False @@ -2478,11 +2485,11 @@ def SetBasePitch(self, f): pass _cpe.CyUserProfile.wasClockJustTurnedOn = lambda self: False _cpe.CyUserProfile.setClockJustTurnedOn = lambda self, b: None _cpe.CyUserProfile.getGraphicOption = lambda self, i: False -# (the map's toggles by the minimap, as they start: no grid, no bare map, no yields, the scores shown) -_cpe.CyUserProfile.getGrid = lambda self: False -_cpe.CyUserProfile.getMap = lambda self: False -_cpe.CyUserProfile.getYields = lambda self: False -_cpe.CyUserProfile.getScores = lambda self: True +# (the map's toggles by the minimap, as they are: oc4options keeps them in the profile) +_cpe.CyUserProfile.getGrid = lambda self: bool(oc4host.map_toggles()[0]) +_cpe.CyUserProfile.getMap = lambda self: bool(oc4host.map_toggles()[1]) +_cpe.CyUserProfile.getYields = lambda self: bool(oc4host.map_toggles()[2]) +_cpe.CyUserProfile.getScores = lambda self: bool(oc4host.map_toggles()[3]) def getClockText(): diff --git a/tests/minimap_toggles_test.py b/tests/minimap_toggles_test.py new file mode 100644 index 00000000..d1c09a55 --- /dev/null +++ b/tests/minimap_toggles_test.py @@ -0,0 +1,134 @@ +# Checks that the minimap's toggles the original keeps in its player profile (the plot grid, the +# bare map, the yields, the scores) are kept in OpenCiv4's profile (apps/oc4core/python/oc4options.py): +# switched in one run, they come back after a restart and with a loaded game. +# +# oc4options runs here with a stand-in for the host (oc4host: the toggles as the C++ side holds +# them, Screens::frame telling the profile when one switched) and for the modules it imports. +# python3 minimap_toggles_test.py + +import importlib +import os +import shutil +import sys +import tempfile +import types + +failures = [] + + +def check(ok, what): + if not ok: + print("FAILED: %s" % what) + failures.append(what) + + +class Anything(types.ModuleType): + """A module whose missing names are do-nothing functions (the host calls oc4options makes + that this test does not look at).""" + + def __getattr__(self, name): + if name.startswith('__'): + raise AttributeError(name) + return lambda *args, **kwargs: None + + +class Host(Anything): + """oc4host: where the profile is, and the toggles as the game's controls leave them.""" + + def __init__(self, path): + Anything.__init__(self, 'oc4host') + self.path = path + self.toggles = [False, False, False, True] # (the C++ side's own start: Interface.h, Utility.h) + self.profileToggles = None # (Screens.cpp's g_profileToggles: none before the profile is read) + + def profile_path(self): + return self.path + + def map_toggles(self): + return list(self.toggles) + + def set_map_toggles(self, grid, bareMap, yields, scores): + self.toggles = [grid, bareMap, yields, scores] + + def load_map_toggles(self, grid, bareMap, yields, scores): + self.toggles = [grid, bareMap, yields, scores] + self.profileToggles = list(self.toggles) + + def control(self, i): + """A toggle's button or key (CvGame::doControl), then the next frame (Screens::frame).""" + self.toggles[i] = not self.toggles[i] + if self.toggles != self.profileToggles: + self.profileToggles = list(self.toggles) + sys.modules['oc4options'].setMapToggles(*self.toggles) + + +def start(folder): + """The program starting: a new host, oc4options loaded afresh (it reads the profile).""" + host = Host(os.path.join(folder, 'profile.ini')) + sys.modules['oc4host'] = host + sys.modules['CvPythonExtensions'] = Anything('CvPythonExtensions') + screens = Anything('oc4screens') + screens.beforeDisplay = [] + sys.modules['oc4screens'] = screens + sys.modules.pop('oc4options', None) + return host, importlib.import_module('oc4options') + + +def profileLines(folder): + with open(os.path.join(folder, 'profile.ini')) as f: + return set(f.read().split()) + + +def main(): + sys.path.insert(0, sys.argv[1]) + folder = tempfile.mkdtemp() + try: + # A first start, no profile yet: the original's defaults (the scores shown, nothing else). + host, options = start(folder) + check(host.toggles == [False, False, False, True], "no profile: grid, bare map, yields off, scores on") + check(not os.path.exists(os.path.join(folder, 'profile.ini')), "nothing written before a toggle") + profile = options._UserProfile() + check((profile.getGrid(), profile.getMap(), profile.getYields(), profile.getScores()) == (False, False, False, True), + "CyUserProfile reads the toggles as they are") + + # The grid and the yields on, the scores off: kept at once (the original writes its .pfl at each click). + host.control(0) + host.control(2) + host.control(3) + lines = profileLines(folder) + check({'grid=1', 'map=0', 'yields=1', 'scores=0'} <= lines, "the toggles are in profile.ini at once: %s" % sorted(lines)) + check(profile.getGrid() and profile.getYields() and not profile.getScores() and not profile.getMap(), "CyUserProfile follows the controls") + + # A restart (and a loaded game: OpenCiv4 starts afresh to load one): the profile's toggles again. + host, options = start(folder) + check(host.toggles == [True, False, True, False], "after a restart: grid and yields on, scores off (%s)" % host.toggles) + + # The game's toggles switched in the loaded game (the bare map on, the grid off), and the + # profile read again (CyUserProfile.readFromFile, as the options screen's profile does): + # the toggles as the player left them, not as the game started. + host.control(1) + host.control(0) + host.toggles = [False, False, False, True] # (the host's own start, say a new game) + options._UserProfile().readFromFile('') + check(host.toggles == [False, True, True, False], "readFromFile gives the host the profile's toggles (%s)" % host.toggles) + + # The other options are kept beside them. + check({'scores=0', 'edgeScroll=1'} <= profileLines(folder), "the rest of the profile is kept") + + # A profile written before this change (no toggle keys): the defaults. + with open(os.path.join(folder, 'profile.ini'), 'w') as f: + f.write('name=openciv4\nclock=1\n') + host, options = start(folder) + check(host.toggles == [False, False, False, True], "an older profile: the defaults (%s)" % host.toggles) + finally: + shutil.rmtree(folder, ignore_errors=True) + + if failures: + print("minimap_toggles_test: %d failed" % len(failures)) + return 1 + print("minimap_toggles_test: all passed") + return 0 + + +if __name__ == '__main__': + sys.exit(main()) From 4c04a5280bb83e64b462406195f88dce5c9bc8e2 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 13:50:06 +0100 Subject: [PATCH 12/89] Options: player options kept in the profile, the theme's check boxes, OpenCiv4's own options on their own tab The original keeps the player options in its player profile and sends them to the active player at the start of every game, new or loaded (CvGame::sendPlayerOptions); OpenCiv4 used the XML's defaults for a new game and the save's own after a load, and never wrote them to profile.ini. Now Utility holds the profile's (profile.ini player.N), a choice sent from the options screen goes into it and is written at once. The options screen's check boxes get the theme's GFC_Control_StandardCheckBox_Style, as the custom game screen's; W A S D, idle turns and edge scrolling move to an OpenCiv4 tab. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 8 ++ README.md | 13 +- apps/oc4core/GameSession.cpp | 14 +-- apps/oc4core/Screens.cpp | 5 + apps/oc4core/Utility.cpp | 16 +-- apps/oc4core/Utility.h | 18 ++- apps/oc4core/python/oc4options.py | 123 ++++++++++++++----- tests/player_options_test.py | 192 ++++++++++++++++++++++++++++++ 8 files changed, 332 insertions(+), 57 deletions(-) create mode 100644 tests/player_options_test.py diff --git a/CMakeLists.txt b/CMakeLists.txt index aa66b460..3c95b230 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -379,6 +379,14 @@ target_link_libraries(auto_end_turn_test PRIVATE oc4_options) add_test(NAME auto_end_turn COMMAND auto_end_turn_test) set_target_properties(auto_end_turn_test PROPERTIES FOLDER "tests") +# The player options kept in the player's profile, and the options screen's OpenCiv4 tab +# (oc4options.py, with a stand-in host). +find_package(Python3 COMPONENTS Interpreter QUIET) +if(Python3_Interpreter_FOUND) + add_test(NAME player_options COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/tests/player_options_test.py + ${CMAKE_CURRENT_SOURCE_DIR}/apps/oc4core/python) +endif() + add_executable(xml_decode_test tests/xml_decode_test.cpp) target_include_directories(xml_decode_test PRIVATE apps/oc4core) target_link_libraries(xml_decode_test PRIVATE oc4_options) diff --git a/README.md b/README.md index e0fedcb3..780316e2 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ Ctrl+Shift+F shows the frame rate and the longest frame of the last half second from the start). W A S D can pan the map as the arrows do, an option that is off by default: "Pan the map with -W A S D" on the options' Game tab turns it on and off, and while it is on Ctrl+Shift+W turns it off +W A S D" on the options' OpenCiv4 tab turns it on and off, and while it is on Ctrl+Shift+W turns it off too (a note at the top says so; with the option off, Ctrl+Shift+W is the game's own); it is kept in profile.ini as `wasdPan`, and `--wasd-pan` turns it on for one run. Only the letters pressed alone pan, so while it is on their own hotkeys (S Sentry, A Automate, W the next unit, D destroy) need the unit's buttons; with Shift, Ctrl or Alt they are still the game's @@ -197,17 +197,24 @@ only when a unit moved in it (and "Wait at End of Turn" is off); with this on, a going until something needs you. A popup, a talk, a screen or the city screen pauses it, and a key or click while it waits keeps that turn; hot seat and by-email games never use it. Ctrl+Shift+E turns it on and off (with a note at the top), and so does "End idle turns automatically" on the -options' Game tab; it is kept in profile.ini as `autoEndTurn`, and `--auto-end-turn` turns it on +options' OpenCiv4 tab; it is kept in profile.ini as `autoEndTurn`, and `--auto-end-turn` turns it on for one run. `OC4_PLAY_LOG=1` prints "idle, ended by itself" for each such turn. Decisions: it is in the engine (`apps/oc4core/AutoEndTurn.h`, called from the play loop), not the game core, so the game's rules, AI and saves are untouched; it sends the same end-turn control as Enter. Tested by `tests/auto_end_turn_test.cpp`. The mouse at the window's edge scrolls the map, as in the original; "Scroll the map at the screen -edge" on the options' Game tab turns it off (on by default). It is kept in profile.ini as +edge" on the options' OpenCiv4 tab turns it off (on by default). It is kept in profile.ini as `edgeScroll`, and `--no-edge-scroll` turns it off for one run (scripted runs with `--view-seconds` never edge scroll). The rule is `src/render/EdgeScroll.h`, tested by `tests/edge_scroll_test.cpp`. +The player options (Options → Game: Wait at End of Turn, Quick Combat, …) are kept in the player's +profile, as the original keeps them in its own (`Profiles\.pfl`): a choice is written to +profile.ini at once (`player.N=`), and every game, new or loaded, starts with the profile's, which +the game core sends to the active player (a save's own options are overwritten, as in the original). +OpenCiv4's own options (W A S D, idle turns, edge scrolling) are on a tab of their own, OpenCiv4, +after the original's four. Tested by `tests/player_options_test.py`. + The globe view's colour layers (Culture, Trade, Religion) are drawn on the globe itself. Tools for the game's files, in `build\Release\bin`: diff --git a/apps/oc4core/GameSession.cpp b/apps/oc4core/GameSession.cpp index 5d9b5461..22b2d7fd 100644 --- a/apps/oc4core/GameSession.cpp +++ b/apps/oc4core/GameSession.cpp @@ -421,7 +421,6 @@ namespace oc4::host void GameSession::startScenario(const NewGameSettings& settings) { m_utility.setGameInitializing(true); - m_utility.setProfileOptionsFromPlayer(NO_PLAYER); m_python.run(std::format("import random\nrandom.seed({})\n", settings.seed)); setupScenarioInitCore(settings); CvInitCore& ic = GC.getInitCore(); @@ -465,7 +464,6 @@ namespace oc4::host return; } m_utility.setGameInitializing(true); - m_utility.setProfileOptionsFromPlayer(NO_PLAYER); setupInitCore(settings); CvInitCore& ic = GC.getInitCore(); CvGame& game = GC.getGame(); @@ -612,7 +610,6 @@ namespace oc4::host player(p).updateHuman(); } GC.getGame().setActivePlayer(static_cast(seat)); - m_utility.setProfileOptionsFromPlayer(static_cast(seat)); // (the mods' scripts draw from Python's random module too: the same numbers in every game) m_python.run(std::format("import random\nrandom.seed({})\n", ic.getSyncRandSeed() ^ unsigned(GC.getGame().getGameTurn()))); setInterfaceTime(true); // (from now on, between frames) @@ -793,9 +790,9 @@ namespace oc4::host throw std::runtime_error(path.filename().string() + ": game data does not match this game core (wrong mod or DLL?)"); // CvGame::read picks the active player of single player games; for hotseat and - // other multiplayer types the engine does: the human whose turn it is. The saved - // options of the human at the seat stand in for the user profile (the DLL sends - // the profile's options to the new active player). + // other multiplayer types the engine does: the human whose turn it is. The DLL then + // sends the user profile's options to the active player, as in the original (the + // saved ones are overwritten: the profile's are the player's, in every game). if (GC.getGame().getActivePlayer() == NO_PLAYER) { int chosen = NO_PLAYER; @@ -806,13 +803,8 @@ namespace oc4::host if (player(p).isHuman()) chosen = p; if (chosen != NO_PLAYER) - { - m_utility.setProfileOptionsFromPlayer(static_cast(chosen)); GC.getGame().setActivePlayer(static_cast(chosen)); - } } - else - m_utility.setProfileOptionsFromPlayer(GC.getGame().getActivePlayer()); // Script data back to Python: CvAppInterface.onLoad((pickle,)). void* args[] = { PyString_FromStringAndSize(save.pythonData.data(), Py_ssize_t(save.pythonData.size())) }; diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..a1a9cf19 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -267,6 +267,11 @@ namespace oc4::host // (the graphic options it has: the game core and the window ask the utility) host.def("set_graphic_option", [&utility](int option, bool on) { utility.setGraphicOption(option, on); }); host.def("reset_graphic_options", [&utility] { utility.resetGraphicOptions(); }); + // (its player options: the game core sends them to the active player; 0 the XML's default, + // 1 off, 2 on) + host.def("set_player_option", [&utility](int option, bool on) { utility.setProfilePlayerOption(option, on); }); + host.def("reset_player_options", [&utility] { utility.resetProfilePlayerOptions(); }); + host.def("player_option_state", [&utility](int option) { return utility.profilePlayerOptionState(option); }); host.def("set_ui_scale", [&utility](int percent) { utility.setUiScale(percent); }); // W A S D panning: the profile's, as loaded; the player's, from the options' check box. host.def("set_wasd_pan", [&utility](bool on) { utility.setWasdPan(on); }); diff --git a/apps/oc4core/Utility.cpp b/apps/oc4core/Utility.cpp index bdb9f491..b239b40c 100644 --- a/apps/oc4core/Utility.cpp +++ b/apps/oc4core/Utility.cpp @@ -336,6 +336,7 @@ namespace oc4::host void Utility::sendPlayerOption(PlayerOptionTypes eOption, bool bValue) { + setProfilePlayerOption(eOption, bValue); // (the player's choice, kept in the profile: oc4options saves it) const PlayerTypes active = GC.getInitCore().getActivePlayer(); if (active == NO_PLAYER) return; @@ -354,9 +355,9 @@ namespace oc4::host bool Utility::getPlayerOption(PlayerOptionTypes ePlayerOption) { - if (size_t(ePlayerOption) < m_profileOptions.size()) - return m_profileOptions[size_t(ePlayerOption)] != 0; - return GC.getPlayerOptionInfo(ePlayerOption).getDefault(); + if (const int state = profilePlayerOptionState(ePlayerOption)) + return state == 2; + return ePlayerOption >= 0 && ePlayerOption < GC.getNumPlayerOptionInfos() && GC.getPlayerOptionInfo(ePlayerOption).getDefault(); } bool Utility::getGraphicOption(GraphicOptionTypes eGraphicOption) @@ -367,15 +368,6 @@ namespace oc4::host return eGraphicOption >= 0 && eGraphicOption < GC.getNumGraphicOptions() && GC.getGraphicOptionInfo(eGraphicOption).getDefault(); } - void Utility::setProfileOptionsFromPlayer(PlayerTypes ePlayer) - { - m_profileOptions.clear(); - if (ePlayer == NO_PLAYER) - return; - const CvPlayerAI& player = CvPlayerAI::getPlayerNonInl(ePlayer); - for (int i = 0; i < GC.getNumPlayerOptionInfos(); ++i) // (mods may have more than the SDK's enum) - m_profileOptions.push_back(player.isOption(static_cast(i)) ? 1 : 0); - } CvWString Utility::getText(CvWString szIDTag, ...) { diff --git a/apps/oc4core/Utility.h b/apps/oc4core/Utility.h index 6622eda8..b01d32be 100644 --- a/apps/oc4core/Utility.h +++ b/apps/oc4core/Utility.h @@ -258,9 +258,19 @@ namespace oc4::host o = 0; } bool ChangeINIKeyValue(const char*, const char*, const char*) override { return false; } // the engine writes no INI - // The user profile's player options (wait at end of turn, ...): XML defaults for a - // new game, the active player's own after loading a save. - void setProfileOptionsFromPlayer(PlayerTypes ePlayer); + // The user profile's player options (wait at end of turn, quick combat, ...): the profile's + // (oc4options, profile.ini), the XML's default for one it does not have. As in the original, + // the game core sends them to the active player at the start of every game, new or loaded + // (CvGame::sendPlayerOptions; a save's own are overwritten), and a choice on the options + // screen (sendPlayerOption) goes into the profile too. + void setProfilePlayerOption(int option, bool on) + { + if (option >= 0 && size_t(option) < m_playerOptions.size()) + m_playerOptions[size_t(option)] = on ? 2 : 1; + } + // 0 the XML's default (none chosen), 1 off, 2 on. + int profilePlayerOptionState(int option) const { return option >= 0 && size_t(option) < m_playerOptions.size() ? m_playerOptions[size_t(option)] : 0; } + void resetProfilePlayerOptions() { m_playerOptions.fill(0); } void pumpMessages(); // Multiplayer (Net): a frame's command run, and a player who left made an AI player. void runCommand(const std::vector& command); @@ -420,7 +430,7 @@ namespace oc4::host Xml& m_xml; TextManager m_text; std::vector m_messages; - std::vector m_profileOptions; // empty: XML defaults + std::array m_playerOptions{}; // the profile's: 0 the XML's default, 1 off, 2 on int m_uiScale = 0, m_forcedUiScale = -1; bool m_wasdPan = false, m_forcedWasdPan = false; bool m_autoEndTurn = false, m_forcedAutoEndTurn = false; diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 4b2d7a83..0fede74f 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -123,6 +123,7 @@ def _applyGraphics(): for i, on in _profile['graphic'].items(): oc4host.set_graphic_option(int(i), bool(on)) oc4host.set_ui_scale(_profile['uiScale']) + _applyPlayerOptions() oc4host.set_wasd_pan(_profile['wasdPan']) oc4host.set_auto_end_turn(_profile['autoEndTurn']) oc4host.set_edge_scroll(_profile['edgeScroll']) @@ -130,9 +131,40 @@ def _applyGraphics(): pass -# W A S D panning (openciv4's own option, no game's): its check box on the options' Game tab, -# above the language; while it is on, Ctrl+Shift+W in the window turns it off (the host calls setWasdPan). +def _applyPlayerOptions(): + """The player options the profile has, to the host: the game core sends them to the active + player at the start of every game, new or loaded, as the original's profile (a save's own are + overwritten).""" + try: + oc4host.reset_player_options() + for i, on in _profile['player'].items(): + oc4host.set_player_option(int(i), bool(on)) + except Exception: + pass + + +def _syncPlayerOptions(): + """The player options as the host has them now (a choice on the options screen goes to the + game core, CyMessageControl().sendPlayerOption, and into the profile there), for the file.""" + try: + for i in range(64): + state = oc4host.player_option_state(i) + if state: + _profile['player'][i] = state == 2 + except Exception: + pass + + +def _playerDefault(i): + try: + return bool(_cpe.CyGlobalContext().getPlayerOptionsInfoByIndex(int(i)).getDefault()) + except Exception: + return False + + +# W A S D panning (openciv4's own option, no game's): its check box on the options' OpenCiv4 tab; while it is on, Ctrl+Shift+W in the window turns it off (the host calls setWasdPan). WASD_PAN_CHECKBOX = 'Oc4WasdPanCheckBox' +OC4_FORM = 'Oc4Form' # (the options' OpenCiv4 tab) def setWasdPan(on): @@ -195,7 +227,7 @@ def _autoEndTurnOn(): # Edge scrolling (openciv4's own option, on by default as in the original): its check box under -# the others on the Game tab. +# the others on the OpenCiv4 tab. EDGE_SCROLL_CHECKBOX = 'Oc4EdgeScrollCheckBox' @@ -264,7 +296,15 @@ def resetOptions(self, eTab): _profile['volume'][v], _profile['nosound'][v] = _VOLUME_STOPS, False _applyVolumes() elif eTab == _cpe.TabGroupTypes.TABGROUP_GAME: + # (the XML's defaults, to the profile and to the player in a game) _profile['player'].clear() + _applyPlayerOptions() + try: + gc = _cpe.CyGlobalContext() + for i in range(gc.getNumPlayerOptionInfos()): + _cpe.CyMessageControl().sendPlayerOption(i, _playerDefault(i)) + except Exception: + pass elif eTab == _cpe.TabGroupTypes.TABGROUP_CLOCK: _profile['clock'] = _profile['hours24'] = False @@ -304,17 +344,22 @@ def getResolutionString(self, i): w, h = oc4host.ui_size_at(scale) return '%dx%d (%s)' % (w, h, '%d%%' % scale if scale else 'Auto') - # the player's options (the game's own when one is on: the active player's) + # the player's options (the profile's, the same in every game: the game core sends them to the + # active player when a game starts or is loaded, and a choice sent from the screen comes back here) def getPlayerOption(self, i): try: - game = _cpe.CyGame() - player = _cpe.CyGlobalContext().getPlayer(game.getActivePlayer()) - if player is not None and not player.isNone(): - return player.isOption(int(i)) + state = oc4host.player_option_state(int(i)) + if state: + return state == 2 + except Exception: + pass + return _profile['player'].get(int(i), _playerDefault(i)) + def setPlayerOption(self, i, b): + _profile['player'][int(i)] = bool(b) + try: + oc4host.set_player_option(int(i), bool(b)) except Exception: pass - return _profile['player'].get(int(i), False) - def setPlayerOption(self, i, b): _profile['player'][int(i)] = bool(b) # sounds def getVolumeStops(self): return _VOLUME_STOPS @@ -449,25 +494,37 @@ def attachTabItem(self, szName, szLabel): self._byName[n.name] = n self._tabs.append((n, _text(szLabel))) _schedule() + # (the game's own options screen: openciv4's own options on a tab of their own, after Other) + if str(szName) == 'OtherForm': + self._attachOpenCiv4Tab() + + def _attachOpenCiv4Tab(self): + """OpenCiv4's options, none of the original's: W A S D panning, ending idle turns, edge + scrolling (kept in the profile as wasdPan, autoEndTurn, edgeScroll).""" + self.attachTabItem(OC4_FORM, u'OpenCiv4') + self.attachVBox(OC4_FORM, 'Oc4VBox') + parent = 'Oc4Panel' + self.attachPanel('Oc4VBox', parent) + self.setStyle(parent, 'Panel_Tan15_Style') + self.setLayoutFlag(parent, 'LAYOUT_SIZE_HEXPANDING') + self.setLayoutFlag(parent, 'LAYOUT_SIZE_VEXPANDING') + self.attachCheckBox(parent, WASD_PAN_CHECKBOX, u'Pan the map with W A S D (Ctrl+Shift+W turns it off)', 'oc4options', 'handleWasdPanClicked', + WASD_PAN_CHECKBOX, _wasdPanOn()) + self.setToolTip(WASD_PAN_CHECKBOX, u'Holding W, A, S or D on its own moves the map, as the arrows do. Their own hotkeys ' + u'(S Sentry, A Automate, W next unit, D destroy) then need the unit\'s buttons; with Shift, Ctrl or Alt they are the ' + u'game\'s as ever, and in menus and screens they are letters.') + self.attachCheckBox(parent, AUTO_END_TURN_CHECKBOX, u'End idle turns automatically (Ctrl+Shift+E)', 'oc4options', 'handleAutoEndTurnClicked', + AUTO_END_TURN_CHECKBOX, _autoEndTurnOn()) + self.setToolTip(AUTO_END_TURN_CHECKBOX, u'When no unit needs orders and nothing is open, the turn ends after 2 seconds ' + u'even if you did nothing in it. Press a key or click while it waits to stay on that turn. Popups, the city ' + u'screen and other screens pause it. Pair with Automate Production and automated workers to let the game run.') + self.attachCheckBox(parent, EDGE_SCROLL_CHECKBOX, u'Scroll the map at the screen edge', 'oc4options', 'handleEdgeScrollClicked', + EDGE_SCROLL_CHECKBOX, _edgeScrollOn()) + self.setToolTip(EDGE_SCROLL_CHECKBOX, u'Moving the mouse to the edge of the screen or window moves the map that way. ' + u'Turn it off to pan only with the arrow keys (or W A S D) and the mouse.') def attachVBox(self, parent, name): self._node('vbox', parent, name) def attachHBox(self, parent, name): - # (openciv4's own option, on the Game tab above the language) - if str(parent) == 'GamePanelCenter' and str(name) == 'LangHBox': - self.attachCheckBox(parent, WASD_PAN_CHECKBOX, u'Pan the map with W A S D (Ctrl+Shift+W turns it off)', 'oc4options', 'handleWasdPanClicked', - WASD_PAN_CHECKBOX, _wasdPanOn()) - self.setToolTip(WASD_PAN_CHECKBOX, u'Holding W, A, S or D on its own moves the map, as the arrows do. Their own hotkeys ' - u'(S Sentry, A Automate, W next unit, D destroy) then need the unit\'s buttons; with Shift, Ctrl or Alt they are the ' - u'game\'s as ever, and in menus and screens they are letters.') - self.attachCheckBox(parent, AUTO_END_TURN_CHECKBOX, u'End idle turns automatically (Ctrl+Shift+E)', 'oc4options', 'handleAutoEndTurnClicked', - AUTO_END_TURN_CHECKBOX, _autoEndTurnOn()) - self.setToolTip(AUTO_END_TURN_CHECKBOX, u'When no unit needs orders and nothing is open, the turn ends after 2 seconds ' - u'even if you did nothing in it. Press a key or click while it waits to stay on that turn. Popups, the city ' - u'screen and other screens pause it. Pair with Automate Production and automated workers to let the game run.') - self.attachCheckBox(parent, EDGE_SCROLL_CHECKBOX, u'Scroll the map at the screen edge', 'oc4options', 'handleEdgeScrollClicked', - EDGE_SCROLL_CHECKBOX, _edgeScrollOn()) - self.setToolTip(EDGE_SCROLL_CHECKBOX, u'Moving the mouse to the edge of the screen or window moves the map that way. ' - u'Turn it off to pan only with the arrow keys (or W A S D) and the mouse.') self._node('hbox', parent, name) def attachPanel(self, parent, name): self._node('panel', parent, name) def attachScrollPanel(self, parent, name): self._node('vbox', parent, name) @@ -569,6 +626,13 @@ def changeDropdownContents(self, name, items): _schedule() def setFocus(self, *args): pass + + def setActiveTab(self, i): + if 0 <= int(i) < len(self._tabs): + self._tab = int(i) + _schedule() + + def getActiveTab(self): return self._tab def setEnabled(self, *args): pass @@ -650,7 +714,9 @@ def _place(screen, n, x, y, w, h): if k == 'label': screen.setLabel(name, 'Background', u'' + n.text + u'', 1 << 0, x, y + 2, 0, font, general, -1, -1) elif k in ('checkbox', 'radio'): - screen.addCheckBoxGFC(name, '', '', x, y, 20, 20, general, -1, -1, '') + # (the theme's check box, as the custom game screen's: GFC_Control_StandardCheckBox_Style) + screen.addCheckBoxGFC(name, '', '', x, y, 20, 20, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) + screen.setStyle(name, 'GFC_Control_StandardCheckBox_Style') w_ = screen._s.get(name) if w_ is not None: w_.state = bool(n.value) @@ -817,6 +883,9 @@ def _call(n, args): except Exception: import traceback traceback.print_exc() + # (every choice kept at once, as the original writes its profile: a player option too) + _syncPlayerOptions() + _save() # ---------------------------------------------------------------- in place diff --git a/tests/player_options_test.py b/tests/player_options_test.py new file mode 100644 index 00000000..e06faa8e --- /dev/null +++ b/tests/player_options_test.py @@ -0,0 +1,192 @@ +# Checks that the player options (Options > Game: Wait at End of Turn, Quick Combat, ...) are kept in +# OpenCiv4's profile (apps/oc4core/python/oc4options.py) as the original keeps them in its player +# profile: a choice on the options screen is written at once, and after a restart the host has the +# profile's options again (the game core sends them to the active player of every game, new or +# loaded). Also that the game's options screen gets OpenCiv4's own options on a tab of their own. +# +# oc4options runs here with a stand-in for the host (oc4host: the profile's player options as +# Utility holds them) and for the modules it imports. +# python3 player_options_test.py + +import importlib +import os +import shutil +import sys +import tempfile +import types + +failures = [] +DEFAULTS = {0: True, 1: True, 2: True} # (CIV4PlayerOptionInfos.xml: advisor pop-ups, Sid's tips, wait at end of turn) +NUM = 22 + + +def check(ok, what): + if not ok: + print("FAILED: %s" % what) + failures.append(what) + + +class Anything(types.ModuleType): + """A module whose missing names are do-nothing functions.""" + + def __getattr__(self, name): + if name.startswith('__'): + raise AttributeError(name) + return lambda *args, **kwargs: None + + +class Host(Anything): + """oc4host: where the profile is, and Utility's profile player options (0 default, 1 off, 2 on).""" + + def __init__(self, path): + Anything.__init__(self, 'oc4host') + self.path = path + self.states = [0] * 64 + self.player = {} # (the active player's options, as sendPlayerOption sets them) + + def profile_path(self): + return self.path + + def set_player_option(self, i, on): + self.states[i] = 2 if on else 1 + + def reset_player_options(self): + self.states = [0] * 64 + + def player_option_state(self, i): + return self.states[i] + + +class Info(object): + def __init__(self, i): + self.i = i + + def getDefault(self): + return DEFAULTS.get(self.i, False) + + +def cpe(host): + m = Anything('CvPythonExtensions') + + class Context(object): + def getPlayerOptionsInfoByIndex(self, i): return Info(i) + def getNumPlayerOptionInfos(self): return NUM + + class MessageControl(object): + def sendPlayerOption(self, i, on): + # (Utility::sendPlayerOption: into the profile, then to the active player) + host.set_player_option(i, on) + host.player[i] = bool(on) + + m.CyGlobalContext = Context + m.CyMessageControl = MessageControl + m.TabGroupTypes = types.SimpleNamespace(TABGROUP_GAME=0, TABGROUP_GRAPHICS=1, TABGROUP_AUDIO=2, TABGROUP_CLOCK=3) + return m + + +def start(folder): + """The program starting: a new host, oc4options loaded afresh (it reads the profile).""" + host = Host(os.path.join(folder, 'profile.ini')) + sys.modules['oc4host'] = host + sys.modules['CvPythonExtensions'] = cpe(host) + screens = Anything('oc4screens') + screens.beforeDisplay = [] + screens._text = lambda s: u"%s" % (s,) + sys.modules['oc4screens'] = screens + # (the game's callbacks module: CvOptionsScreenCallbackInterface.handleGameOptionsClicked) + callbacks = types.ModuleType('optionscallbacks') + + def handleGameOptionsClicked(args): + on, name = args + sys.modules['CvPythonExtensions'].CyMessageControl().sendPlayerOption(int(name[name.find('_') + 1:]), on) + return 1 + callbacks.handleGameOptionsClicked = handleGameOptionsClicked + sys.modules['optionscallbacks'] = callbacks + sys.modules.pop('oc4options', None) + return host, importlib.import_module('oc4options') + + +def profileLines(folder): + with open(os.path.join(folder, 'profile.ini')) as f: + return set(f.read().split()) + + +def optionsScreen(options): + """The game's options screen as CvOptionsScreen.py builds it (its tabs, two player options).""" + ctrl = options.CyGTabCtrl('Options', False, False) + for form, label in (('GameForm', 'Game'), ('GraphicsForm', 'Graphics'), ('AudioForm', 'Audio'), ('OtherForm', 'Other')): + ctrl.attachTabItem(form, label) + ctrl.attachVBox('GameForm', 'GameVBox') + ctrl.attachPanel('GameVBox', 'GamePanelCenter') + profile = options._UserProfile() + for i in (2, 6): + name = 'GameOptionCheckBox_%d' % i + ctrl.attachCheckBox('GamePanelCenter', name, 'option %d' % i, 'optionscallbacks', 'handleGameOptionsClicked', name, profile.getPlayerOption(i)) + ctrl.attachHBox('GamePanelCenter', 'LangHBox') + return ctrl + + +def click(options, ctrl, name): + n = ctrl._byName[name] + n.value = not n.value + options._call(n, (n.value, n.callback[2])) + + +def main(): + sys.path.insert(0, sys.argv[1]) + folder = tempfile.mkdtemp() + try: + # No profile yet: the XML's defaults, nothing for the host. + host, options = start(folder) + profile = options._UserProfile() + check(profile.getPlayerOption(2) and not profile.getPlayerOption(6), "no profile: the XML's defaults") + check(host.states[:NUM] == [0] * NUM, "no profile: the host has none chosen") + + # The screen's tabs: the game's four, then OpenCiv4's with its three options. + ctrl = optionsScreen(options) + check([label for form, label in ctrl._tabs] == ['Game', 'Graphics', 'Audio', 'Other', 'OpenCiv4'], "tabs: %s" % [l for f, l in ctrl._tabs]) + oc4 = [n.name for n in ctrl._nodes.values() if n.kind == 'checkbox' and n.name.startswith('Oc4')] + check(sorted(oc4) == sorted([options.WASD_PAN_CHECKBOX, options.AUTO_END_TURN_CHECKBOX, options.EDGE_SCROLL_CHECKBOX]), "OpenCiv4's options: %s" % oc4) + game = [n.name for n in ctrl._byName['GamePanelCenter'].children] + check(game == ['GameOptionCheckBox_2', 'GameOptionCheckBox_6', 'LangHBox'], "the Game tab has only the game's: %s" % game) + + # Wait at End of Turn off, Quick Moves on: sent to the player and kept at once. + click(options, ctrl, 'GameOptionCheckBox_2') + click(options, ctrl, 'GameOptionCheckBox_6') + check(host.player == {2: False, 6: True}, "sent to the active player: %s" % host.player) + lines = profileLines(folder) + check({'player.2=0', 'player.6=1'} <= lines, "in profile.ini at once: %s" % sorted(lines)) + check(not profile.getPlayerOption(2) and profile.getPlayerOption(6), "CyUserProfile reads them back") + + # A restart (a new game, or a save loaded: the game core sends the host's to the player). + host, options = start(folder) + check(host.states[2] == 1 and host.states[6] == 2, "after a restart the host has the profile's (%s)" % host.states[:8]) + profile = options._UserProfile() + check(not profile.getPlayerOption(2) and profile.getPlayerOption(6) and profile.getPlayerOption(0), "and the screen shows them") + + # Restore Defaults on the Game tab: the XML's, to the profile and the player. + profile.resetOptions(0) + options._save() + check(host.player.get(2) is True and host.player.get(6) is False, "defaults sent to the player: %s" % host.player) + host, options = start(folder) + profile = options._UserProfile() + check(profile.getPlayerOption(2) and not profile.getPlayerOption(6), "defaults kept after a restart") + + # A profile written before this change: the XML's defaults, the rest kept. + with open(os.path.join(folder, 'profile.ini'), 'w') as f: + f.write('name=openciv4\nedgeScroll=0\n') + host, options = start(folder) + check(host.states[:NUM] == [0] * NUM, "an older profile: none chosen") + check(options._profile['edgeScroll'] is False, "the other keys still read") + finally: + shutil.rmtree(folder, ignore_errors=True) + + if failures: + print("player_options_test: %d failed" % len(failures)) + return 1 + print("player_options_test: all passed") + return 0 + + +if __name__ == '__main__': + sys.exit(main()) From 0053b8628b305727097866c74568837987462f49 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 13:52:33 +0100 Subject: [PATCH 13/89] Options: the player options' code apart from the minimap toggles' (merges cleanly with #85) Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 10 ++--- apps/oc4core/python/oc4options.py | 65 ++++++++++++++++--------------- 2 files changed, 38 insertions(+), 37 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index a1a9cf19..efe18e86 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -267,11 +267,6 @@ namespace oc4::host // (the graphic options it has: the game core and the window ask the utility) host.def("set_graphic_option", [&utility](int option, bool on) { utility.setGraphicOption(option, on); }); host.def("reset_graphic_options", [&utility] { utility.resetGraphicOptions(); }); - // (its player options: the game core sends them to the active player; 0 the XML's default, - // 1 off, 2 on) - host.def("set_player_option", [&utility](int option, bool on) { utility.setProfilePlayerOption(option, on); }); - host.def("reset_player_options", [&utility] { utility.resetProfilePlayerOptions(); }); - host.def("player_option_state", [&utility](int option) { return utility.profilePlayerOptionState(option); }); host.def("set_ui_scale", [&utility](int percent) { utility.setUiScale(percent); }); // W A S D panning: the profile's, as loaded; the player's, from the options' check box. host.def("set_wasd_pan", [&utility](bool on) { utility.setWasdPan(on); }); @@ -285,6 +280,11 @@ namespace oc4::host host.def("set_edge_scroll", [&utility](bool on) { utility.setEdgeScroll(on); }); host.def("choose_edge_scroll", [&utility](bool on) { utility.chooseEdgeScroll(on); }); host.def("edge_scroll", [&utility] { return utility.edgeScroll(); }); + // The profile's player options (the game core sends them to the active player): 0 the XML's + // default, 1 off, 2 on. + host.def("set_player_option", [&utility](int option, bool on) { utility.setProfilePlayerOption(option, on); }); + host.def("reset_player_options", [&utility] { utility.resetProfilePlayerOptions(); }); + host.def("player_option_state", [&utility](int option) { return utility.profilePlayerOptionState(option); }); host.def("ui_size_at", [](int percent) { const float scale = render::uiScaleFor(percent, g_display.density, g_display.width, g_display.height); return std::pair{ render::uiUnits(g_display.width, scale), render::uiUnits(g_display.height, scale) }; diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 0fede74f..f9f9c7ad 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -131,38 +131,8 @@ def _applyGraphics(): pass -def _applyPlayerOptions(): - """The player options the profile has, to the host: the game core sends them to the active - player at the start of every game, new or loaded, as the original's profile (a save's own are - overwritten).""" - try: - oc4host.reset_player_options() - for i, on in _profile['player'].items(): - oc4host.set_player_option(int(i), bool(on)) - except Exception: - pass - - -def _syncPlayerOptions(): - """The player options as the host has them now (a choice on the options screen goes to the - game core, CyMessageControl().sendPlayerOption, and into the profile there), for the file.""" - try: - for i in range(64): - state = oc4host.player_option_state(i) - if state: - _profile['player'][i] = state == 2 - except Exception: - pass - - -def _playerDefault(i): - try: - return bool(_cpe.CyGlobalContext().getPlayerOptionsInfoByIndex(int(i)).getDefault()) - except Exception: - return False - - -# W A S D panning (openciv4's own option, no game's): its check box on the options' OpenCiv4 tab; while it is on, Ctrl+Shift+W in the window turns it off (the host calls setWasdPan). +# W A S D panning (openciv4's own option, no game's): its check box on the options' OpenCiv4 tab; +# while it is on, Ctrl+Shift+W in the window turns it off (the host calls setWasdPan). WASD_PAN_CHECKBOX = 'Oc4WasdPanCheckBox' OC4_FORM = 'Oc4Form' # (the options' OpenCiv4 tab) @@ -249,6 +219,37 @@ def _edgeScrollOn(): return _profile['edgeScroll'] +def _applyPlayerOptions(): + """The player options the profile has, to the host: the game core sends them to the active + player at the start of every game, new or loaded, as the original's profile (a save's own are + overwritten).""" + try: + oc4host.reset_player_options() + for i, on in _profile['player'].items(): + oc4host.set_player_option(int(i), bool(on)) + except Exception: + pass + + +def _syncPlayerOptions(): + """The player options as the host has them now (a choice on the options screen goes to the + game core, CyMessageControl().sendPlayerOption, and into the profile there), for the file.""" + try: + for i in range(64): + state = oc4host.player_option_state(i) + if state: + _profile['player'][i] = state == 2 + except Exception: + pass + + +def _playerDefault(i): + try: + return bool(_cpe.CyGlobalContext().getPlayerOptionsInfoByIndex(int(i)).getDefault()) + except Exception: + return False + + def _graphicDefault(i): try: return bool(_cpe.CyGlobalContext().getGraphicOptionInfo(int(i)).getDefault()) From bb31c52f22c4f70842b62dd27fa2965ea137cfec Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 13:52:44 +0100 Subject: [PATCH 14/89] Options: leave the W A S D comment's lines as they were (merges cleanly with #85) Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index f9f9c7ad..04ce43c3 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -131,10 +131,10 @@ def _applyGraphics(): pass -# W A S D panning (openciv4's own option, no game's): its check box on the options' OpenCiv4 tab; -# while it is on, Ctrl+Shift+W in the window turns it off (the host calls setWasdPan). +# W A S D panning (openciv4's own option, no game's): its check box on the options' Game tab, +# above the language; while it is on, Ctrl+Shift+W in the window turns it off (the host calls setWasdPan). WASD_PAN_CHECKBOX = 'Oc4WasdPanCheckBox' -OC4_FORM = 'Oc4Form' # (the options' OpenCiv4 tab) +OC4_FORM = 'Oc4Form' # (the options' OpenCiv4 tab: openciv4's own options are there now, not on the Game tab) def setWasdPan(on): From e12acd4ac4498ae14b33cd82ce9977e8c79487cf Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 14:04:20 +0100 Subject: [PATCH 15/89] Options window as the original's: the theme's title bar, window and tabs, GFC's box layout Measured on the original's options screen (Wine, BUG + BULL): the standard window's title bar with the title at the left, tabs as wide as their words from the left (the theme's tab skins, the chosen one lighter, a baseline under them), 31 px rows (GFC's default control height), 16 px text, a box's children as wide as they need with the rest to those that expand (the two columns of player options) or to the spacers (Language at the panel's foot), Restore Defaults and Exit centred under the panel. Empty panels take no room. CyGTabCtrl's setActiveTab/getActiveTab work, so a script can open a tab. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 205 +++++++++++++++++++++--------- 1 file changed, 143 insertions(+), 62 deletions(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 04ce43c3..f4630b69 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -528,7 +528,7 @@ def attachVBox(self, parent, name): self._node('vbox', parent, name) def attachHBox(self, parent, name): self._node('hbox', parent, name) def attachPanel(self, parent, name): self._node('panel', parent, name) - def attachScrollPanel(self, parent, name): self._node('vbox', parent, name) + def attachScrollPanel(self, parent, name): self._node('scroll', parent, name) def attachSpacer(self, parent): self._node('spacer', parent, '') def attachHSeparator(self, parent, name): self._node('hsep', parent, name) def attachVSeparator(self, parent, name): self._node('vsep', parent, name) @@ -648,10 +648,69 @@ def _screen(): # ---------------------------------------------------------------- laying it out -_ROW = {'label': 20, 'checkbox': 22, 'radio': 22, 'dropdown': 26, 'button': 28, 'edit': 26, 'hslider': 18, 'hsep': 10, +# The boxes laid out as the original's GFC does it, measured on its options screen: a control's +# default height is 31 (the theme's GFC_Control_Size Default, GSize(64, 31)), so a check box's row is +# 28 and the gap 3; a box's children are as wide as they need, and what is left goes to those that +# expand (LAYOUT_SIZE_HEXPANDING) or, in a column, to its spacers (the Language row at the panel's +# foot); a row with LAYOUT_HCENTER is centred (Restore Defaults and Exit). +_ROW = {'label': 28, 'checkbox': 28, 'radio': 28, 'dropdown': 28, 'button': 31, 'edit': 26, 'hslider': 18, 'hsep': 10, 'spacer': 8, 'image': 4, 'vsep': 0} _GAP = 3 _PAD = 8 +_SCROLL_PAD = 4 # (a scroll panel's inside, left and right) +_FONT = u'' # (the controls' text: the theme's SF_CtrlTheme_Civ4_Control_Font_Size3_Normal, 16 px) +_BOX = 20 # (a check box's picture; its mark is 14 across inside it) +_BOX_TEXT = 24 # (from the box's left to its text's) + + +def _width(text): + try: + return oc4screens._textWidth(_FONT + text + u'', _cpe.FontTypes.GAME_FONT) + except Exception: + return 8 * len(text) + + +def _pad(n): + """A box's inside: a panel's 8 all round, a scroll panel's 4 at the sides.""" + if n.kind == 'panel': + return _PAD, _PAD + if n.kind == 'scroll': + return _SCROLL_PAD, 0 + return 0, 0 + + +def _hgrow(n): + return 'LAYOUT_SIZE_HEXPANDING' in n.flags or 'LAYOUT_SIZE_HPREFERREDEXPANDING' in n.flags + + +def _vgrow(n): + return 'LAYOUT_SIZE_VEXPANDING' in n.flags or 'LAYOUT_SIZE_VPREFERREDEXPANDING' in n.flags + + +def _natural(n): + """How wide a control is of itself (None: as wide as it is given).""" + k = n.kind + if k == 'label': + return _width(n.text) + 8 + if k in ('checkbox', 'radio'): + return _BOX_TEXT + _width(n.text) + 8 + if k == 'button': + return max(59, _width(n.text) + 20) + if k == 'dropdown': + return max([_width(i) for i in n.items] or [40]) + 36 + if k in ('spacer', 'vsep'): + return 12 + if k in ('vbox', 'scroll', 'panel'): + widths = [_natural(c) for c in n.children] + if None in widths: + return None + return max(widths or [0]) + 2 * _pad(n)[0] + if k == 'hbox': + widths = [_natural(c) for c in n.children] + if None in widths: + return None + return sum(widths) + _GAP * max(0, len(widths) - 1) + return None def _height(n, w): @@ -661,34 +720,40 @@ def _height(n, w): if k == 'vslider': return 4 * (n.maximum - n.minimum + 1) + 4 if k == 'hbox': - widths = _shares(n, w) + start, widths = _shares(n, w) return max([_height(c, cw) for c, cw in zip(n.children, widths)] or [0]) - pad = _PAD if k == 'panel' else 0 - inner = w - 2 * pad + if k == 'panel' and not n.children: + return 0 # (an empty one: the resolution's screen picture, none here) + px, py = _pad(n) + inner = w - 2 * px h = sum(_height(c, inner) for c in n.children) + _GAP * max(0, len(n.children) - 1) - return h + 2 * pad - - -def _natural(n): - """A label's own width (CF_LABEL_DEFAULTSIZE, as BUG asks for its pull downs' titles).""" - try: - return oc4screens._textWidth(u'' + n.text + u'', _cpe.FontTypes.GAME_FONT) + 8 - except Exception: - return 8 * len(n.text) + 8 + return h + 2 * py def _shares(n, w): - """The widths of an horizontal box's children: separators and spacers narrow, labels of their + """Where an horizontal box's children start (from its left) and their widths: each as wide + as it needs, the rest shared by those that expand, else the row centred (LAYOUT_HCENTER) or + left as it is; when one has no width of its own, separators and spacers narrow, labels of their default size (CF_LABEL_DEFAULTSIZE) as wide as their text (up to half the box), the rest alike.""" + gaps = _GAP * max(0, len(n.children) - 1) + natural = [_natural(c) for c in n.children] + if n.children and None not in natural: + extra = max(0, w - sum(natural) - gaps) + grow = [i for i, c in enumerate(n.children) if _hgrow(c)] + if grow: + for i in grow: + natural[i] += extra / len(grow) + return 0, natural + return (extra / 2 if 'LAYOUT_HCENTER' in n.flags else 0), natural fixed = dict((c.id, 12) for c in n.children if c.kind in ('vsep', 'spacer')) if len(n.children) > 1: for c in n.children: if c.kind == 'label' and 'CF_LABEL_DEFAULTSIZE' in c.flags: - fixed[c.id] = min(_natural(c), w / 2) + fixed[c.id] = min(_width(c.text) + 8, w / 2) others = [c for c in n.children if c.id not in fixed] - rest = max(0, w - sum(fixed.values()) - _GAP * max(0, len(n.children) - 1)) + rest = max(0, w - sum(fixed.values()) - gaps) each = rest / max(1, len(others)) - return [fixed.get(c.id, each) for c in n.children] + return 0, [fixed.get(c.id, each) for c in n.children] def _place(screen, n, x, y, w, h): @@ -697,37 +762,49 @@ def _place(screen, n, x, y, w, h): general = _cpe.WidgetTypes.WIDGET_GENERAL font = _cpe.FontTypes.GAME_FONT if k == 'hbox': - cx = x - for c, cw in zip(n.children, _shares(n, w)): - _place(screen, c, cx, y, cw, _height(c, cw)) + start, widths = _shares(n, w) + cx = x + start + for c, cw in zip(n.children, widths): + _place(screen, c, cx, y, cw, h if _vgrow(c) else _height(c, cw)) cx += cw + _GAP return - if k in ('vbox', 'form', 'panel'): - pad = _PAD if k == 'panel' else 0 - if k == 'panel': + if k in ('vbox', 'form', 'panel', 'scroll'): + px, py = _pad(n) + if k == 'panel' and h > 0: screen.addPanel(name, u'', u'', True, False, x, y, w, h, _cpe.PanelStyles.PANEL_STYLE_IN) - cy = y + pad - for c in n.children: - ch = _height(c, w - 2 * pad) - _place(screen, c, x + pad, cy, w - 2 * pad, ch) + if n.style: + screen.setStyle(name, n.style) + inner = w - 2 * px + heights = [_height(c, inner) for c in n.children] + # (the height left over: to the children that expand downwards, else to the spacers; a + # tab's form fills the window) + left = h - 2 * py - sum(heights) - _GAP * max(0, len(heights) - 1) + if left > 0 and n.children: + grow = [i for i, c in enumerate(n.children) if _vgrow(c)] or \ + [i for i, c in enumerate(n.children) if c.kind == 'spacer'] or ([0] if k == 'form' else []) + for i in grow: + heights[i] += left / len(grow) + cy = y + py + for c, ch in zip(n.children, heights): + _place(screen, c, x + px, cy, inner, ch) cy += ch + _GAP return if k == 'label': - screen.setLabel(name, 'Background', u'' + n.text + u'', 1 << 0, x, y + 2, 0, font, general, -1, -1) + screen.setLabel(name, 'Background', _FONT + n.text + u'', 1 << 0, x, y + 4, 0, font, general, -1, -1) elif k in ('checkbox', 'radio'): # (the theme's check box, as the custom game screen's: GFC_Control_StandardCheckBox_Style) - screen.addCheckBoxGFC(name, '', '', x, y, 20, 20, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) + screen.addCheckBoxGFC(name, '', '', x, y + 4, _BOX, _BOX, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) screen.setStyle(name, 'GFC_Control_StandardCheckBox_Style') w_ = screen._s.get(name) if w_ is not None: w_.state = bool(n.value) - screen.setText(name + 'L', 'Background', u'' + n.text + u'', 1 << 0, x + 26, y + 2, 0, font, general, -1, -1) + screen.setText(name + 'L', 'Background', _FONT + n.text + u'', 1 << 0, x + _BOX_TEXT, y + 4, 0, font, general, -1, -1) if n.tip: w_ = screen._s.get(name) if w_ is not None: w_.help = n.tip elif k == 'button': - screen.setButtonGFC(name, n.text, '', x, y, min(w, 220), 26, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) + screen.setButtonGFC(name, n.text, '', x, y + 4, w, 25, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) elif k == 'edit': screen.addEditBoxGFC(name, x, y, min(w, 260), 24, general, -1, -1, font) screen.setEditBoxString(name, n.text) @@ -735,7 +812,7 @@ def _place(screen, n, x, y, w, h): dw = min(w, 260) if 'LAYOUT_RIGHT' in n.flags: x += w - dw - screen.addDropDownBoxGFC(name, x, y, dw, general, -1, -1, font) + screen.addDropDownBoxGFC(name, x, y + 1, dw, general, -1, -1, font) for i, item in enumerate(n.items): screen.addPullDownString(name, item, i, i, i == int(n.value)) elif k in ('hslider', 'vslider'): @@ -783,36 +860,38 @@ def relayout(): # (the size the script asked for, setSize, kept on the display) w, h = min(ctrl._size[0], RW), min(ctrl._size[1], RH) x0, y0 = (RW - w) / 2, max(0, (RH - h) / 2) - screen.addPanel('OptBack', u'', u'', True, False, x0, y0, w, h, _cpe.PanelStyles.PANEL_STYLE_MAIN) - screen.setLabel('OptTitle', 'Background', u'' + ctrl._title + u'', 1 << 2, x0 + w / 2, y0 + 10, 0, + # (the window as the original's: the theme's standard window under its title bar, the title on + # the bar at the left, the tabs under it as wide as their words, then the tab's form) + for name, top, height, style in (('OptBack', _TITLE_H, h - _TITLE_H, _WINDOW_INNER), ('OptFrame', _TITLE_H, h - _TITLE_H, _WINDOW_FRAME), + ('OptTitleBar', 0, _TITLE_H, _WINDOW_TITLE)): + screen.addPanel(name, u'', u'', True, False, x0, y0 + top, w, height, _cpe.PanelStyles.PANEL_STYLE_MAIN) + screen.setStyle(name, style) + screen.setLabel('OptTitle', 'Background', u'' + _DARK + ctrl._title + u'', 1 << 0, x0 + 12, y0 + 3, 0, _cpe.FontTypes.TITLE_FONT, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1) - # the tabs: each as wide as its label, in as many rows as they need (BUG's 14 do not fit one), - # each row stretched across the window - y = _tabRows(screen, ctrl, x0 + 10, y0 + 38, w - 20) + y = _tabRows(screen, ctrl, x0 + 14, y0 + _TAB_Y, w - 28) form = ctrl._tabs[min(ctrl._tab, len(ctrl._tabs) - 1)][0] - _place(screen, form, x0 + 14, y + 6, w - 28, h - (y + 6 - y0) - 14) - - + _place(screen, form, x0 + 30, y + 17, w - 60, h - (y + 17 - y0) - 30) + + +# The theme's window, title bar and tabs (as oc4wb draws the WorldBuilder's tool window). +_WINDOW_INNER = '@GFC_Control_DefaultWindow_Style|GFC_CtrlTheme_Bitmap_Control_Window_Skin_Inner_Default' +_WINDOW_TITLE = '@|SF_CtrlTheme_Civ4_Control_Window_Skin_Standard_TitleBar_Full_Default' +_WINDOW_FRAME = '@SF_CtrlTheme_Civ4_Control_Window_NoTitleBar_InFrameBorder_Normal_Style|GFC_CtrlTheme_Bitmap_Control_Border_Skin_Full_Default' +_TAB_SKIN = '@GFC_CtrlTheme_Bitmap_Control_Tab_SkinStyle_Top_Begin_BaseLevel_Single|GFC_CtrlTheme_Bitmap_Control_Tab_Skin_Full_' +_TAB_BASELINE = '@GFC_CtrlTheme_Bitmap_Control_Tab_SkinStyle_Top_Begin_BaseLevel_Single|GFC_CtrlTheme_Bitmap_Control_Tab_Skin_Baseline_Default' +_DARK = u'' # (the title's and the tabs' words: the theme's dark brown) +_TITLE_H = 26 +_TAB_Y = 39 _TAB_HEIGHT = 28 def _tabWidth(label): - try: - return oc4screens._textWidth(label, _cpe.FontTypes.GAME_FONT) + 24 - except Exception: - return 9 * len(label) + 24 + return _width(label) + 20 def _tabRows(screen, ctrl, x, y, width): - """Lays the tab buttons out in rows; returns where the row under the last one would start.""" - n = len(ctrl._tabs) - tw = width / max(1, n) - if all(_tabWidth(label) <= tw - 4 for form, label in ctrl._tabs): - # (all fit alike in one row: one row of equal tabs, the game's own options screen) - for i, (form, label) in enumerate(ctrl._tabs): - screen.setButtonGFC('OptTab%d' % i, label, '', x + i * tw, y, tw - 4, _TAB_HEIGHT, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1, - _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) - return y + _TAB_HEIGHT + 4 + """Lays the tabs out in rows, each as wide as its word, from the left (BUG's 14 need more than + one row); returns where the row under the last one would start.""" rows, row, used = [], [], 0 for i, (form, label) in enumerate(ctrl._tabs): tw = _tabWidth(label) @@ -820,19 +899,21 @@ def _tabRows(screen, ctrl, x, y, width): rows.append(row) row, used = [], 0 row.append((i, label, tw)) - used += tw + 4 + used += tw + 2 if row: rows.append(row) for r in rows: - natural = sum(tw for i, label, tw in r) + 4 * (len(r) - 1) - extra = (width - natural) / max(1, len(r)) if len(rows) == 1 or r is not rows[-1] else 0 cx = x for i, label, tw in r: - bw = tw + extra - screen.setButtonGFC('OptTab%d' % i, label, '', cx, y, bw, _TAB_HEIGHT, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1, - _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) - cx += bw + 4 - y += _TAB_HEIGHT + 4 + back = 'OptTabBack%d' % i + screen.addPanel(back, u'', u'', True, False, cx, y, tw, _TAB_HEIGHT, _cpe.PanelStyles.PANEL_STYLE_MAIN) + screen.setStyle(back, _TAB_SKIN + ('Select' if i == ctrl._tab else 'Default')) + screen.setText('OptTab%d' % i, 'Background', _FONT + _DARK + label + u'', 1 << 2, cx + tw / 2, y + 5, 0, + _cpe.FontTypes.GAME_FONT, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1) + cx += tw + 2 + y += _TAB_HEIGHT + screen.addPanel('OptTabBaseline', u'', u'', True, False, x, y - 2, width, 7, _cpe.PanelStyles.PANEL_STYLE_MAIN) + screen.setStyle('OptTabBaseline', _TAB_BASELINE) return y From f16f0d9f6c879bdbdf6d7894662542ca9b85610b Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 18:08:42 +0100 Subject: [PATCH 16/89] Messages at the top as the original's: box, bullets, colours, newest first The original shows the game's messages in a see-through black box under the top bar (606 wide in the middle, a line of 18 for each), newest at the top, at most six; each line has a bullet and is drawn in the message's flash colour (BUG's foreign city founded in magenta, losses in red, white when it has none), colours in its text kept. A line shows at once and goes at once when its time is up; one pushed out by newer ones does not come back. Measured in Wine (BUG + BULL) from a film of the window at 1600 x 900. OpenCiv4 drew centred lines without a box, all white, oldest first, fading over their last second, up to twelve. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Interface.cpp | 26 +++++++++++++++++--------- apps/oc4core/Interface.h | 10 ++++++---- apps/oc4core/main.cpp | 4 ++-- src/render/MapWindow.cpp | 28 ++++++++++++++++++---------- src/render/MapWindow.h | 9 +++++++-- 5 files changed, 50 insertions(+), 27 deletions(-) diff --git a/apps/oc4core/Interface.cpp b/apps/oc4core/Interface.cpp index 97ae45b3..402bd739 100644 --- a/apps/oc4core/Interface.cpp +++ b/apps/oc4core/Interface.cpp @@ -214,7 +214,7 @@ namespace oc4::host pszIcon, eFlashColor, iFlashX, iFlashY, bShowOffScreenArrows, bShowOnScreenArrows)); if (ePlayer != GC.getGame().getActivePlayer()) return; - show(szString.c_str(), iLength); + show(szString.c_str(), iLength, eFlashColor); if (sounds && pszSound && *pszSound) sounds->play(pszSound); } @@ -234,7 +234,7 @@ namespace oc4::host } // (the messages of the last turn again, when a game is loaded: CvPlayer::showMissedMessages) - void Interface::showMessage(CvTalkingHeadMessage& msg) { show(msg.getDescription(), msg.getLength()); } + void Interface::showMessage(CvTalkingHeadMessage& msg) { show(msg.getDescription(), msg.getLength(), msg.getFlashColor()); } void Interface::clearEventMessages() { @@ -242,14 +242,22 @@ namespace oc4::host m_shown.clear(); } - void Interface::show(const std::wstring& text, int seconds) + // As the original: a message's line shows at once, in its flash colour (white if it has + // none; colours in its text stay), for its length in seconds, and goes at once; the newest + // six are shown, newest at the top, and one pushed out by newer ones does not come back. + void Interface::show(const std::wstring& text, int seconds, ColorTypes color) { if (text.empty()) return; if (seconds <= 0) seconds = GC.getEVENT_MESSAGE_TIME(); + NiColorA colour(1, 1, 1, 1); + if (color > NO_COLOR && color < GC.getNumColorInfos()) + colour = GC.getColorInfo(color).getColor(); std::lock_guard lock(m_shownMutex); - const auto until = std::chrono::steady_clock::now() + std::chrono::seconds(std::max(seconds, 1)); + const auto now = std::chrono::steady_clock::now(); + std::erase_if(m_shown, [&](const Shown& s) { return s.until <= now; }); + const auto until = now + std::chrono::seconds(std::max(seconds, 1)); // (the same one again while it is up, as a mod's weather has it plot after plot: one line, // counted, moved to the newest) int count = 1; @@ -258,8 +266,8 @@ namespace oc4::host count = same->count + 1; m_shown.erase(same); } - m_shown.push_back({ text, until, count }); - while (m_shown.size() > 12) // (the oldest go first when many come at once) + m_shown.push_back({ text, colour, until, count }); + while (m_shown.size() > kShownLines) m_shown.pop_front(); } @@ -268,9 +276,9 @@ namespace oc4::host const auto now = std::chrono::steady_clock::now(); std::lock_guard lock(m_shownMutex); std::vector out; - for (const Shown& s : m_shown) - if (const float left = std::chrono::duration(s.until - now).count(); left > 0) - out.push_back({ s.count > 1 ? s.text + L" (x" + std::to_wstring(s.count) + L")" : s.text, std::min(1.0f, left) }); // (the last second fades it) + for (auto s = m_shown.rbegin(); s != m_shown.rend(); ++s) + if (s->until > now) + out.push_back({ s->count > 1 ? s->text + L" (x" + std::to_wstring(s->count) + L")" : s->text, s->color }); return out; } diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index e14dd520..55d4cf2a 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -308,27 +308,29 @@ namespace oc4::host void showMessage(CvTalkingHeadMessage& msg) override; void clearEventMessages() override; // The messages on the screen now (the active player's, as the original shows them at the - // top for their length in seconds), oldest first, each with how much of it is left to - // fade (1 shown, towards 0 going). Any thread. + // top for their length in seconds, the newest six), newest first, each in its colour (the + // message's flash colour; white if it has none). Any thread. struct ShownMessage { std::wstring text; - float alpha = 1; + NiColorA color{ 1, 1, 1, 1 }; }; std::vector shownMessages() const; std::vector minimapTerrainColors; private: - void show(const std::wstring& text, int seconds); + void show(const std::wstring& text, int seconds, ColorTypes color = NO_COLOR); bool m_exiting = false; struct Shown { std::wstring text; + NiColorA color{ 1, 1, 1, 1 }; std::chrono::steady_clock::time_point until; int count = 1; // (the same message again while it is up: one line, "(x3)") }; mutable std::mutex m_shownMutex; std::deque m_shown; + static constexpr size_t kShownLines = 6; // (the original's box holds six) mutable std::vector m_minimapBase; bool selected(const CvUnit* pUnit) const; diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..cf0ced61 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -541,11 +541,11 @@ namespace const auto look = window.look(); const float closeness = std::clamp((cameraTop - look.distance) / (cameraTop - cameraNearest), 0.0f, 1.0f); sounds.update({ look.x, look.y, look.distance, closeness }, era); - std::vector> lines; + std::vector lines; // (none over a talk: the leader's face is where they are; the turn log keeps them) if (!utility.diplomacy().active()) for (const auto& m : ui.shownMessages()) - lines.push_back({ host::gameMarkup(m.text.c_str()), m.alpha }); + lines.push_back({ host::gameMarkup(m.text.c_str()), { m.color.r, m.color.g, m.color.b } }); window.setMessages(std::move(lines)); // (and what the game's controls show of the map) window.setLayers({ ui.showYields, utility.engine().resourceLayer, utility.engine().unitLayer, ui.bareMap, utility.engine().grid }); diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..d7bc171f 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -191,7 +191,7 @@ namespace oc4::render std::wstring actionHelpText; bool downOnActions = false; std::wstring info; - std::vector> messages; + std::vector> messages; // (newest first) MapWindow::ScreenMinimap screenMinimap; MapWindow::Layers layers, layersApplied; MapWindow::PlotMarks plotMarks; @@ -1913,17 +1913,25 @@ namespace oc4::render } } - // The messages: centred lines under the top of the interface, the newest lowest. + // The messages as the original's: a see-through black box under the top bar, 606 wide in + // the middle, a line of 18 for each, newest at the top, each line a bullet and its text in + // its colour with a shadow (measured in Wine at 1600 x 900: box 500-1106 x 50-159 for six + // lines, black at a quarter, bullets at 507, text at 514). void drawMessages() { if (messages.empty()) return; - const float size = ui.textSize(2), line = std::round(size * 1.4f), cx = overlay->screenWidth() / 2; - float y = ui.active() ? 74 : 70; - for (const auto& [text, alpha] : messages) + constexpr float kWidth = 606, kTop = 50, kLine = 18, kBullet = 7, kText = 14; + const float size = ui.textSize(2), x0 = std::round(overlay->screenWidth() / 2 - kWidth / 2); + const float y1 = kTop + kLine * float(messages.size()) + 1; + overlay->rect(x0, kTop, x0 + kWidth, y1, { 0, 0, 0 }, 0.25f, 0); + float y = kTop; + for (const auto& [text, colour] : messages) { - overlay->richText(text, cx, y, size, false, { 0.93f, 0.93f, 0.9f }, alpha, Overlay::Align::Center); - y += line; + const float h = overlay->richHeight(text, 4096, size, false), ty = std::round(y + 1 + (kLine - h) / 2); + overlay->rect(x0 + kBullet, y + kLine / 2, x0 + kBullet + 2, y + kLine / 2 + 2, { 0.85f, 0.85f, 0.85f }, 1, 0); + overlay->richText(text, x0 + kText, ty, size, false, colour, 1, Overlay::Align::Left); + y += kLine; } } @@ -2546,11 +2554,11 @@ namespace oc4::render c.x = p.first, c.y = p.second, c.right = right, c.onFigure = figure.has_value(); return c; } - void MapWindow::setMessages(std::vector> messages) + void MapWindow::setMessages(const std::vector& messages) { m->messages.clear(); - for (auto& [text, alpha] : messages) - m->messages.push_back({ widen(text), alpha }); + for (const Message& message : messages) + m->messages.push_back({ widen(message.text), message.color }); } void MapWindow::setPopup(const PopupView* popup) { m->popup.set(popup); } std::optional MapWindow::takePopupAnswer() { return m->popup.takeAnswer(); } diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..e0927550 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -133,8 +133,13 @@ namespace oc4::render // Shown in the lower left corner (the selected unit), lines. void setInfo(const std::string& text); // The game's messages to the player, at the top in the middle as the original shows them: - // lines with the screens' markup (UTF-8), oldest first, each with its opacity. - void setMessages(std::vector> messages); + // lines with the screens' markup (UTF-8), newest first, each in its colour. + struct Message + { + std::string text; + Color color{ 1, 1, 1 }; + }; + void setMessages(const std::vector& messages); // A popup to answer (the game's own: what to build, what to research, ...), over the // map; while it is up, clicks and keys go to it. From 8a0fdf3da5540f2f4ff4efd84429e1c6963f9766 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 18:12:45 +0100 Subject: [PATCH 17/89] Tech advisor as the original's: tech colours, choosing and queueing shown Three pieces, found with BUG's tech advisor in Wine (BUG + BULL): - A panel's colour from setPanelColor tints the layers its theme style tints by the panel's own inner colour (FactorColor GFC_Control_Panel_Color_Inner, Modulate): Panel_Tech_Style's tech_panel01. Known techs are green, the one researched and the queued cyan, the others blue, as in the original; they were all blue. - The tech advisor is told when the active player's research changes (a tech clicked, Shift-clicked into the queue, learnt, a new turn), as the original engine calls CvScreensInterface.forceScreenUpdate for it, and redrawn when it comes up (the turns left show at once). A click did choose the tech, but the screen never showed it. - addScrollPanel draws no panel: the engine's GScrollPanel is transparent (Civ4Theme_ScrollPanel.thm, GFC_CF_TRANSPARENT). The techs lie on the advisor's parchment, not the external style's blue; the city screen's right column loses a blue block Wine does not have. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 26 ++++++++++++++++++++++++++ apps/oc4core/Screens.h | 2 ++ apps/oc4core/python/oc4screens.py | 5 ++++- src/render/Theme.cpp | 16 ++++++++++++++++ src/render/Theme.h | 7 +++++++ src/render/UiLayer.cpp | 5 +++-- 6 files changed, 58 insertions(+), 3 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..5a8bd3e3 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -19,6 +19,7 @@ #include "CvGameTextMgr.h" #include "CvMap.h" #include "CvPlayerAI.h" +#include "CvTeamAI.h" #include "CvPlot.h" #include "CvPopupInfo.h" #include "CvSelectionGroup.h" @@ -714,6 +715,7 @@ if _walls: py::module_ screens = py::module_::import("oc4screens"); screens.attr("setResolution")(width, height); m_mainId = py::module_::import("CvScreenEnums").attr("MAIN_INTERFACE").cast(); + m_techChooserId = py::module_::import("CvScreenEnums").attr("TECH_CHOOSER").cast(); py::module_::import("CvScreensInterface").attr("showMainInterface")(); m_utility.gameInterface().makeInterfaceDirty(); m_utility.gameInterface().techSplash = true; @@ -1008,9 +1010,33 @@ if _walls: // plays its turns so, the military advisor's flashing plots end so). const float dt = m_lastUpdate.time_since_epoch().count() ? std::min(std::chrono::duration(now - m_lastUpdate).count(), 0.25f) : 0.0f; m_lastUpdate = now; + bool techChooser = false; for (py::handle id : screens.attr("shownScreens")().cast()) if (const int screen = id.cast(); screen != kDiplomacyScreen) + { entry.attr("update")(py::make_tuple(screen, dt)); + techChooser = techChooser || screen == m_techChooserId; + } + // The tech advisor told when the research changes, as the original engine does + // (CvScreensInterface.forceScreenUpdate: "forced from net message"): a tech clicked, + // queued with Shift, learnt, the turns left. Its techs then take their colours and + // numbers again (CvTechChooser.updateTechRecords). + if (techChooser && GC.getGame().getActivePlayer() != NO_PLAYER) + { + const CvPlayerAI& player = CvPlayerAI::getPlayerNonInl(GC.getGame().getActivePlayer()); + const CvTeamAI& team = CvTeamAI::getTeamNonInl(player.getTeam()); + std::vector research{ GC.getGame().getGameTurn(), player.getCurrentResearch(), team.getResearchProgress(player.getCurrentResearch() < 0 ? TechTypes(0) : player.getCurrentResearch()), player.calculateResearchRate() }; + for (int i = 0; i < GC.getNumTechInfos(); ++i) + research.push_back(team.isHasTech(TechTypes(i)) ? -1 : player.getQueuePosition(TechTypes(i))); + if (research != m_research) + { + // (redrawn when it comes up: the original's shows the turns left at once) + entry.attr(m_research.empty() ? "forceScreenRedraw" : "forceScreenUpdate")(py::make_tuple(m_techChooserId)); + m_research = std::move(research); + } + } + else + m_research.clear(); if (ui.anyDirty()) entry.attr("forceScreenRedraw")(py::make_tuple(m_mainId)); // Diplomacy: the next talk waiting, when nothing is up (the game's script says what the diff --git a/apps/oc4core/Screens.h b/apps/oc4core/Screens.h index 5f64207c..a671f368 100644 --- a/apps/oc4core/Screens.h +++ b/apps/oc4core/Screens.h @@ -131,6 +131,8 @@ namespace oc4::host bool m_active = false; bool m_menu = false; // the main menu, not the game's screens int m_mainId = -1, m_failures = 0; + int m_techChooserId = -1; + std::vector m_research; // the active player's research when the tech advisor was last told (empty: not up) long long m_version = -1; std::pair m_laidOut{ -1, -1 }, m_seenSize{ -1, -1 }; // the size the screens were made for; the window's std::chrono::steady_clock::time_point m_sizeChanged; diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..517bcedb 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -608,7 +608,10 @@ def addPanel(self, szName, title, helpText, bVerticalLayout, bScrollable, iX, iY def addScrollPanel(self, szName, title, iX, iY, iWidth, iHeight, eStyle): w = self._s.add(szName, 'panel') w.text, w.scroll = _text(title), True - w.x, w.y, w.w, w.h, w.pstyle = int(iX), int(iY), int(iWidth), int(iHeight), _style(_cpe.PanelStyles, eStyle) + # (drawn as nothing whatever its style: the engine's GScrollPanel is transparent, + # GFC_CF_TRANSPARENT in Civ4Theme_ScrollPanel.thm; the tech advisor's techs lie on its + # parchment, SCREEN_BG_OPAQUE under the panel, not on the external style's blue) + w.x, w.y, w.w, w.h, w.pstyle = int(iX), int(iY), int(iWidth), int(iHeight), 'PANEL_STYLE_EMPTY' # (inside the theme's layout margin, GFC_Control_Layout's Size_OuterMargin of 8: the # WorldBuilder's load/save buttons, at 0 in their panel at 70, line up with its landmark and # erase buttons at 8 and 43; the city screen's resource names fit their columns) diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 81d93bda..f7b80866 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -725,7 +725,11 @@ namespace oc4::render if (const Value* f = has("FactorColor")) if (const Value* combine = resolve(s, has("FactorCombine")); combine && combine->kind == Value::Kind::Call && !combine->args.empty() && combine->args[0].text == "Modulate") + { tinted = colour(s, f, tint, tintAlpha); + l.panelColour = tinted && f->kind == Value::Kind::Name && f->text == "GFC_Control_Panel_Color_Inner"; + l.tintAlpha = tintAlpha; + } if (const Value* v = has("Image")) l.image = bitmap(s, v, tinted ? &tint : nullptr, tintAlpha); if (const Value* v = has("Center")) @@ -938,6 +942,18 @@ namespace oc4::render return out; } + Theme::Skin Theme::recoloured(const Skin& skin, Color colour) + { + Skin out = skin; + for (Layer& l : out) + if (l.panelColour) + { + l.image = modulate(l.image, colour, l.tintAlpha); + l.center = modulate(l.center, colour, l.tintAlpha); + } + return out; + } + Theme::Bitmap Theme::addSigned(const Bitmap& b, Color c) { if (!b) diff --git a/src/render/Theme.h b/src/render/Theme.h index 626a5657..910d0a45 100644 --- a/src/render/Theme.h +++ b/src/render/Theme.h @@ -63,6 +63,11 @@ namespace oc4::render bool section[4]{ true, true, true, true }; // its left, top, right, bottom columns / rows drawn Color fill{}; // Middle::Fill float fillAlpha = 0; + // Tinted by the panel's own inner colour (FactorColor GFC_Control_Panel_Color_Inner), + // which a script's setPanelColor changes (the tech advisor's known, researched and + // open techs); its alpha the theme's. + bool panelColour = false; + float tintAlpha = 1; }; using Skin = std::vector; struct Panel @@ -125,6 +130,8 @@ namespace oc4::render Bitmap addSigned(const Bitmap& bitmap, Color colour); // The bitmap multiplied by the colour (the Modulate combine): a bar's fill in its colour. Bitmap modulate(const Bitmap& bitmap, Color colour, float alpha = 1); + // The skin with its panel colour layers tinted by another colour (setPanelColor). + Skin recoloured(const Skin& skin, Color colour); // Font size 1..4 (the markup's ); the theme's, else the nearest it has. Font font(int size, bool bold = false, bool italic = false) const; diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..ff2e15ef 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -402,8 +402,9 @@ namespace oc4::render } else if (const Theme::Panel* p = themedPanel(it)) { - Theme::draw(o, p->inner, x0, y0, x1, y1, it.alpha); - Theme::draw(o, p->border, x0, y0, x1, y1, it.alpha); + // (in the script's colour, setPanelColor, where the theme tints it by its own) + Theme::draw(o, it.hasColor ? m_theme.recoloured(p->inner, it.color) : p->inner, x0, y0, x1, y1, it.alpha); + Theme::draw(o, it.hasColor ? m_theme.recoloured(p->border, it.color) : p->border, x0, y0, x1, y1, it.alpha); } else if (!emptyPanel(it.style)) { From 61766d08365c53f5e7d5f9cd056c5fd3c3356dfa Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 18:18:28 +0100 Subject: [PATCH 18/89] Popups as the original's: choices on stone buttons, the glass inside the border Measured against the original (BUG + BULL, the new civic popup, 1600 x 900): - Each choice (popupAddGenericButton) is the theme's standard stone button across the window, its text dark with the button's light shadow, 9 in; a line's button is 25 high, 6 apart; the first has the focus rim until the keys choose another. They were plain white text lines. - The theme's GFC_BITMAPSKIN_SIDES_FILL is read: a window border's sides are filled with its colour round the glass, which is drawn inside the border's margin (12, 13, 12, 15). The glass's light top now follows on from the border's, as in the original; it was a hard light band with a darker step. (A pull down's open list keeps its look: its inner skin is drawn under the whole border.) - The window sits where the original's does (rim at 1182, 79). Co-Authored-By: Claude Opus 5.5 --- src/render/PopupPanel.cpp | 52 +++++++++++++++++++++++++++++++++++---- src/render/Theme.cpp | 19 +++++++++++++- src/render/Theme.h | 3 ++- src/render/UiLayer.cpp | 2 ++ 4 files changed, 69 insertions(+), 7 deletions(-) diff --git a/src/render/PopupPanel.cpp b/src/render/PopupPanel.cpp index e97dfac5..4f58ba5b 100644 --- a/src/render/PopupPanel.cpp +++ b/src/render/PopupPanel.cpp @@ -26,6 +26,8 @@ namespace oc4::render // (as the game's popups: their width, margins, the choices' pictures, the OK button's height) constexpr float kWidth = 396, kPadX = 21, kPadTop = 18, kPadBottom = 20, kIcon = 28, kOk = 24; + constexpr float kStoneLine = 25, kStoneGap = 6, kStoneInset = 9; // (a choice's stone button) + constexpr Color kFocus{ 0.45f, 0.62f, 0.95f }; // (the focus rim on the first) constexpr Color kPanel{ 0.05f, 0.06f, 0.09f }, kEdge{ 0.78f, 0.64f, 0.36f }, kText{ 0.97f, 0.97f, 0.97f }, kHot{ 1, 0.83f, 0.49f }; constexpr Color kButton{ 0.13f, 0.16f, 0.22f }, kButtonHover{ 0.24f, 0.31f, 0.44f }, kEditFill{ 0.09f, 0.11f, 0.2f }, kEditRim{ 0.62f, 0.72f, 0.9f }; @@ -239,10 +241,11 @@ namespace oc4::render // As the game's: its width, at the right under the top bar (in the middle when narrow). const float w = std::min(kWidth, sw - 40), inner = w - 2 * kPadX; const bool right = sw >= 2.5f * w && !m_view->centered; - const float x0 = right ? sw - 20 - w : (sw - w) / 2; + const float x0 = right ? sw - 22 - w : (sw - w) / 2; // (Wine at 1600 x 900: its rim at 1182, 79) const std::wstring header = widen(m_view->header); std::vector texts(items.size()); std::vector heights(items.size()); + const bool stone = m_button && !m_button->skin[0].empty(); float content = 0; for (size_t i = 0; i < items.size(); ++i) { @@ -251,7 +254,12 @@ namespace oc4::render switch (items[i].kind) { case Kind::Text: heights[i] = o.richHeight(texts[i], inner, m_textSize, false) + 10; break; - case Kind::Button: heights[i] = std::max(kIcon, o.richHeight(texts[i], inner - (icon ? kIcon + 5 : 0), m_textSize, false)) + 8; break; + case Kind::Button: + // (on the theme's stone button, as the original's: 25 high for a line, 6 apart, the + // text 9 in; measured in Wine at 1600 x 900) + heights[i] = stone ? std::max(kIcon * (icon ? 1.0f : 0.0f), std::max(kStoneLine, o.richHeight(texts[i], inner - 2 * kStoneInset - (icon ? kIcon + 5 : 0), m_textSize, false) + 5)) + kStoneGap + : std::max(kIcon, o.richHeight(texts[i], inner - (icon ? kIcon + 5 : 0), m_textSize, false)) + 8; + break; case Kind::Radio: case Kind::Check: heights[i] = std::max(26.0f, o.richHeight(texts[i], inner - 30, m_textSize, false) + 8); break; case Kind::Separator: heights[i] = 12; break; @@ -262,7 +270,7 @@ namespace oc4::render } const float headerHeight = header.empty() ? 0.0f : o.richHeight(header, inner, m_headerSize, false) + 10; const float okHeight = m_view->okButton ? kOk + 10 : 0.0f; - float y0 = right ? 80.0f : 30.0f; + float y0 = right ? 77.0f : 30.0f; const float listHeight = std::max(0.0f, std::min(content, sh - y0 - 20 - headerHeight - okHeight - kPadTop - kPadBottom)); const float h = kPadTop + headerHeight + listHeight + okHeight + kPadBottom; if (!right) @@ -270,7 +278,10 @@ namespace oc4::render m_panel = { x0, y0, x0 + w, y0 + h }; if (!m_glass.empty() || !m_frame.empty()) { - Theme::draw(o, m_glass, x0, y0, x0 + w, y0 + h); + // (the glass inside the border's margin, GFC_Control_Border_Size_Margin of the window + // without a title bar: the border's own sides, filled with the window's colour, round it; + // the glass's light top then follows on from the border's, as the original's) + Theme::draw(o, m_glass, x0 + 12, y0 + 13, x0 + w - 12, y0 + h - 15); Theme::draw(o, m_frame, x0, y0, x0 + w, y0 + h); } else @@ -301,6 +312,10 @@ namespace oc4::render m_scroll = std::clamp(m_scroll, 0.0f, m_scrollMax); o.clip(m_list.x0, m_list.y0, m_list.x1, m_list.y1); m_items.assign(items.size(), Rect{}); + int firstChoice = -1; + for (size_t i = 0; i < items.size() && firstChoice < 0; ++i) + if (items[i].kind == Kind::Button) + firstChoice = int(i); float iy = y - m_scroll; const float rightEdge = x0 + w - kPadX - (m_scrollMax > 0 ? 10 : 0); for (size_t i = 0; i < items.size(); ++i) @@ -318,7 +333,34 @@ namespace oc4::render case Kind::Text: o.richBlock(texts[i], r.x0, r.y0 + 4, r.x1 - r.x0, m_textSize, false, kText); break; case Kind::Button: { - // A choice: its picture and its text, gold under the mouse (its own colours stay). + if (stone) + { + // A choice: the theme's stone button across the window (lit under the mouse), its + // picture and its text dark on it; the first has the focus rim until the keys choose. + // (the skin is drawn over the whole place: its own indent leaves the gap, 3 above + // and below; the stone then shows 1.5 inside the window's text margin) + const float by0 = r.y0, by1 = r.y1; + const size_t st = hot && !m_button->skin[1].empty() ? 1 : 0; + Theme::draw(o, m_button->skin[st], r.x0 - 2.5f, by0, x0 + w - kPadX + 3.5f, by1); + if (!m_keyboard && int(i) == firstChoice) + o.frame(r.x0 - 1.5f, by0 + 3, x0 + w - kPadX + 1.5f, by1 - 3, kFocus, 0.9f, 4, 1.5f); + float tx = r.x0 + kStoneInset; + if (const ButtonArt::Icon* ic = m_art.icon(item.icon)) + { + const float iy0 = std::round(by0 + (by1 - by0 - kIcon) / 2); + o.image(ic->key, ic->bgra, ic->width, ic->height, 1, tx, iy0, tx + kIcon, iy0 + kIcon); + tx += kIcon + 5; + } + const float tw = x0 + w - kPadX - kStoneInset - tx, th = o.richHeight(texts[i], tw, m_textSize, false); + const bool coloured = m_button->coloured; + if (coloured) + o.setShadow(m_button->shadow[st], m_button->shadowAlpha[st]); + o.richBlock(texts[i], tx, std::round(by0 + (by1 - by0 - th) / 2), tw, m_textSize, false, coloured ? m_button->text[st] : kText, + coloured ? m_button->textAlpha[st] : 1); + o.resetShadow(); + break; + } + // Without the theme: its picture and its text, gold under the mouse (its own colours stay). float tx = r.x0; if (const ButtonArt::Icon* ic = m_art.icon(item.icon)) { diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 81d93bda..bb4084c1 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -759,6 +759,12 @@ namespace oc4::render l.middle = Layer::Middle::Fill; else if (f.text == "GFC_BITMAPSKIN_SIDES_NOTVISIBLE") l.sides = false; + else if (f.text == "GFC_BITMAPSKIN_SIDES_FILL") + { + l.sidesFill = true; + if (const Value* c = has("FactorColor"); c && l.fillAlpha == 0) + colour(s, c, l.fill, l.fillAlpha); + } else if (f.text == "GFC_BITMAPSKIN_NOTVISIBLE") l.image = l.center = {}; } @@ -791,7 +797,7 @@ namespace oc4::render next = end = 0; } } - std::erase_if(out, [](const Layer& l) { return !l.image && !l.center && l.middle != Layer::Middle::Fill; }); + std::erase_if(out, [](const Layer& l) { return !l.image && !l.center && l.middle != Layer::Middle::Fill && !(l.sidesFill && l.fillAlpha > 0); }); return out; } @@ -1001,6 +1007,17 @@ namespace oc4::render continue; if (l.middle == Layer::Middle::Fill && l.fillAlpha > 0) o.rect(x0, y0, x1, y1, l.fill, l.fillAlpha * alpha); + else if (l.sidesFill && l.fillAlpha > 0 && !l.image) + { + // The ring inside its margin (its middle the glass's, drawn by the window inside it). + const float ml = std::min(l.margin[0], (x1 - x0) / 2), mr = std::min(l.margin[2], (x1 - x0) / 2); + const float mt = std::min(l.margin[1], (y1 - y0) / 2), mb = std::min(l.margin[3], (y1 - y0) / 2); + const float a = l.fillAlpha * alpha; + o.rect(x0, y0, x1, y0 + mt, l.fill, a); + o.rect(x0, y1 - mb, x1, y1, l.fill, a); + o.rect(x0, y0 + mt, x0 + ml, y1 - mb, l.fill, a); + o.rect(x1 - mr, y0 + mt, x1, y1 - mb, l.fill, a); + } if (const Bitmap& b = l.image) { if (l.middle == Layer::Middle::Fixed && l.margin[0] + l.margin[1] + l.margin[2] + l.margin[3] == 0) diff --git a/src/render/Theme.h b/src/render/Theme.h index 626a5657..d13556bb 100644 --- a/src/render/Theme.h +++ b/src/render/Theme.h @@ -61,8 +61,9 @@ namespace oc4::render Middle middle = Middle::Stretch; bool sides = true; // the edges are drawn bool section[4]{ true, true, true, true }; // its left, top, right, bottom columns / rows drawn - Color fill{}; // Middle::Fill + Color fill{}; // Middle::Fill, or the sides with sidesFill float fillAlpha = 0; + bool sidesFill = false; // the ring inside its margin filled with its FactorColor (GFC_BITMAPSKIN_SIDES_FILL: a window's border round its glass) }; using Skin = std::vector; struct Panel diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..16fa7d9c 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -70,6 +70,8 @@ namespace oc4::render m_dropInner = m_theme.skin("SF_CtrlTheme_Civ4_Control_ComboBox_Standard_PopupBoxTable_Style", "GFC_CtrlTheme_Bitmap_Control_Table_Skin_Inner_Default"); m_dropBorder = m_theme.skin("SF_CtrlTheme_Civ4_Control_ComboBox_Standard_PopupBoxTableBorder_Style", "GFC_CtrlTheme_Bitmap_Control_Border_Skin_Full_Default"); + // (its sides' fill left out: the list's inner skin is drawn under the whole border here) + std::erase_if(m_dropBorder, [](const Theme::Layer& l) { return l.sidesFill && !l.image; }); m_dropSelect = m_theme.skin(combo, "GFC_CtrlTheme_Bitmap_Control_ComboBox_Skin_PopupItem_Select"); constexpr std::string_view scroll = "GFC_Control_StandardScroll_Style"; m_shaft = { m_theme.skin(scroll, "GFC_CtrlTheme_Bitmap_Control_Scroll_Skin_VShaft_Default"), From a4ea00beca28ae535be72cb14d229c0db0da909d Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 18:41:49 +0100 Subject: [PATCH 19/89] Options: a profile the old screen wrote gets the defaults it never showed Before the player options were kept as choices, the options screen wrote every player option it had shown, and it showed those the profile did not have as off. Such a profile has Wait at End of Turn off (and advisor pop-ups, Sid's tips) though the player never chose it; with Wait at End of Turn off the game core ends each turn by itself once a unit has moved, so turns seemed to end on their own. The profile now has a version (2). One without it gets, once, the XML's default for the options that are on by default and off there; every other choice stays, and from then on off is the player's. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 19 ++++++++++++++++++- tests/player_options_test.py | 17 +++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index f4630b69..dd7e1664 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -58,6 +58,13 @@ def _path(): return '' +# The profile's form: 2 since the player options are the player's choices (before, the options +# screen wrote every player option it had shown, those it had never read as off). +_VERSION = 2 +# (the options CIV4PlayerOptionInfos.xml has on: advisor pop-ups, Sid's tips, Wait at End of Turn) +_DEFAULTS_ON = (0, 1, 2) + + def _load(): path = _path() if not path: @@ -66,6 +73,7 @@ def _load(): f = open(path, 'r') except IOError: return + version = 1 try: for line in f: if '=' not in line: @@ -85,17 +93,26 @@ def _load(): _profile[parts[0]] = int(value) elif parts[0] in ('name', 'speakers', 'musicPath'): _profile[parts[0]] = value + elif parts[0] == 'version': + version = int(value) except (ValueError, IndexError): pass finally: f.close() + # A profile the old options screen wrote: an option that is on by default and off there was + # most likely never chosen (the screen showed it off), so it is the default again, once. (With + # Wait at End of Turn off the game core ends a turn by itself after a unit moved.) + if version < _VERSION: + for i in _DEFAULTS_ON: + if _profile['player'].get(i) is False: + del _profile['player'][i] def _save(): path = _path() if not path: return - lines = [] + lines = ['version=%d' % _VERSION] for key in ('name', 'speakers', 'musicPath'): lines.append('%s=%s' % (key, _profile[key])) for key in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): diff --git a/tests/player_options_test.py b/tests/player_options_test.py index e06faa8e..c13debbc 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -178,6 +178,23 @@ def main(): host, options = start(folder) check(host.states[:NUM] == [0] * NUM, "an older profile: none chosen") check(options._profile['edgeScroll'] is False, "the other keys still read") + + # A profile the old options screen wrote (no version): its "off" for the options on by + # default (it showed them off) gives way to the default once; the other choices stay. + with open(os.path.join(folder, 'profile.ini'), 'w') as f: + f.write('name=openciv4\nplayer.0=0\nplayer.1=0\nplayer.2=0\nplayer.6=1\nplayer.13=0\n') + host, options = start(folder) + profile = options._UserProfile() + check(profile.getPlayerOption(2) and profile.getPlayerOption(0) and profile.getPlayerOption(6) and not profile.getPlayerOption(13), + "an old screen's profile: Wait at End of Turn on again, Quick Moves kept") + check(host.states[2] == 0 and host.states[6] == 2, "... and the host has those (%s)" % host.states[:8]) + options._save() + lines = profileLines(folder) + check('version=2' in lines and 'player.6=1' in lines and 'player.2=0' not in lines, "saved with its version: %s" % sorted(lines)) + # Once: then Wait at End of Turn off is the player's choice and stays. + click(options, optionsScreen(options), 'GameOptionCheckBox_2') + host, options = start(folder) + check(not options._UserProfile().getPlayerOption(2), "after that, off is kept") finally: shutil.rmtree(folder, ignore_errors=True) From c1c1f9b0293578ab6811fe3a6e2406d9deef31c6 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 18:43:50 +0100 Subject: [PATCH 20/89] City screen: the units selected before are selected again when it closes The city screen lets go of the selected units (so a right click on it orders nothing), and when it closed the game core picked the next unit that waited, or none: the unit the player had before was gone. The units selected when the screen opened are now kept and selected again when it closes (those still there and the player's), as the original keeps them. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Interface.cpp | 20 ++++++++++++++++++-- apps/oc4core/Interface.h | 1 + 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/apps/oc4core/Interface.cpp b/apps/oc4core/Interface.cpp index 15579318..a05de491 100644 --- a/apps/oc4core/Interface.cpp +++ b/apps/oc4core/Interface.cpp @@ -682,6 +682,17 @@ namespace oc4::host if (CvCity* c = cityOf(id); c && c->getOwner() == id.eOwner) c->updateSelectedCity(true); m_citiesShown.clear(); + // The units selected before the screen opened are selected again (those still there and + // the player's), as the original keeps them; the game core picks the next one only if + // none is left. + if (m_selection.getLength() == 0) + for (const IDInfo& id : m_selectionUnderCity) + if (CvUnit* u = unitOf(id); u && u->getOwner() == GC.getGame().getActivePlayer() && !selected(u)) + { + m_selection.insertAtEnd(id); + m_lastSelected = u; + } + m_selectionUnderCity.clear(); } if (isCityScreenUp() != wasUp) for (const InterfaceDirtyBits bit : { PercentButtons_DIRTY_BIT, ResearchButtons_DIRTY_BIT, GameData_DIRTY_BIT, Score_DIRTY_BIT }) @@ -697,8 +708,13 @@ namespace oc4::host if (pNewValue) { // A city's screen and selected units go not together: the units are let go (as - // CvGame::selectUnit lets go of the cities; once the screen closes the game core - // selects the next unit that waits, CvGame::updateSelectionList). + // CvGame::selectUnit lets go of the cities), and selected again when the screen closes. + if (!wasUp) + { + m_selectionUnderCity.clear(); + for (CLLNode* n = m_selection.head(); n; n = m_selection.next(n)) + m_selectionUnderCity.push_back(n->m_data); + } m_selection.clear(); m_cities.insertAtEnd(pNewValue->getIDInfo()); m_cityScreen = true; diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index e14dd520..e4b9a521 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -358,6 +358,7 @@ namespace oc4::host InterfaceVisibility m_showBeforeWorldBuilder = INTERFACE_SHOW; CLinkList m_cities; std::vector m_citiesShown; // (asked for production when the city screen closes, if idle) + std::vector m_selectionUnderCity; // the units selected when the city screen opened: selected again when it closes bool m_cityScreen = false; void selectionChanged(); // (the dirty bits a new selection sets) void cityScreenChanged(bool wasUp); // (what the main interface hides in the city screen is redrawn) From 3ddcdb81cb95cb598cff8ad63f6c294845a3d7c6 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 18:43:49 +0100 Subject: [PATCH 21/89] Right button held: the buttons for that plot, recommended ones glow; Esc cancels With a unit selected and the right button held on another plot, the original shows the way there and the unit's action buttons for that plot, those recommended there glowing (a worker: the farm, road, cottage it should build there; CvUnit::isActionRecommended and CvGame::canHandleAction read the interface's goto plot). Esc lets go of the way, and the button's release then orders nothing. - The goto plot changing marks the action buttons for redrawing, so the main interface asks again for that plot. - enableMultiListPulse works: a pulsing button has the original's blue rim and tint, a little brighter and dimmer a second a beat (measured in Wine). It shows for the unit's own plot too, as the original's. - Esc with the right button held cancels the way and the order. - --keys can move the mouse ("?") and hold the right button ("/", "\"), to test drags through the window's own input. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Interface.h | 7 ++++++- apps/oc4core/Screens.cpp | 2 ++ apps/oc4core/main.cpp | 15 +++++++++++++++ apps/oc4core/python/oc4screens.py | 24 ++++++++++++++++++------ src/render/MapWindow.cpp | 24 ++++++++++++++++++++++++ src/render/MapWindow.h | 4 ++++ src/render/UiLayer.cpp | 10 ++++++++++ 7 files changed, 79 insertions(+), 7 deletions(-) diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index e14dd520..e66c6b3c 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -224,7 +224,12 @@ namespace oc4::host CvPlot* getLookAtPlot() override { return nullptr; } CvPlot* getGotoPlot() override { return m_gotoPlot; } // Where the right button held would send the selection (the game core's plot help then gives the odds of an attack there). - void setGotoPlot(CvPlot* plot) { m_gotoPlot = plot; } + // (the action buttons again: the main interface's recommend what to do there, CvUnit::isActionRecommended) + void setGotoPlot(CvPlot* plot) + { + if (std::exchange(m_gotoPlot, plot) != plot) + m_dirty[SelectionButtons_DIRTY_BIT] = true; + } // The end of the player's turn as CvGame::updateTestEndTurn works it out with the // interface: when no unit waits for orders, it raises the "press Enter" message or, after diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..c2abf965 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -1211,6 +1211,8 @@ if _walls: info.checkbox = item.kind == Kind::CheckBox; if (item.kind == Kind::Movie) info.movie = item.texture; + if (item.kind == Kind::ImageButton && t.size() >= 24) + item.pulse = t[23].cast(); if ((item.kind == Kind::Bar || item.kind == Kind::Scrollbar) && t.size() >= 25) { item.barStart = t[23].cast(); diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..33c5064d 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -38,6 +38,9 @@ // --screenshot and --view-seconds that game is played offscreen. OC4_PLAY_LOG=1 prints the // popups as they come, the actions the keys run and the widgets clicked; OC4_UI_DUMP= // writes the interface's widgets there when they change. +// In --keys, "?" also moves the mouse to that pixel of the window, "/" presses the +// right button there and holds it, "\" lets it go there (a drag, as the mouse's), and "%x" +// types Esc into the window (where '~' is the game's Esc). // // --menu (and no options at all) opens the window on a temporary main menu: a new game, with // the leader, map script, world and difficulty to choose, or a saved one, played as with @@ -388,6 +391,7 @@ namespace case 'e': return render::key::Return; case 't': return render::key::Tab; case 'b': return render::key::Back; + case 'x': return render::key::Escape; // (into the window: what holds the right button sees it first) default: return 0; } } @@ -1169,6 +1173,17 @@ namespace clicks.push_back(click); script.erase(0, close + 1); } + else if (int px = 0, py = 0; (script.front() == '?' || script.front() == '/' || script.front() == '\\') && script.size() > 1 && script[1] == '<' && + script.find('>') != std::string::npos && std::sscanf(script.c_str() + 2, "%d,%d", &px, &py) == 2) + { + // "?": the mouse moved to that pixel; "/" the right button pressed there and + // held, "\" let go there (a drag, as the mouse's). + if (script.front() == '?') + window.mouseMove(px, py); + else + window.mouseButton(px, py, false, script.front() == '/'); + script.erase(0, script.find('>') + 1); + } else if (int px = 0, py = 0; script.front() == '<' && script.find('>') != std::string::npos && std::sscanf(script.c_str() + 1, "%d,%d", &px, &py) == 2) { // "": a left click at that pixel of the window, on what is there (a popup, the diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..d3cff15e 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -1025,7 +1025,7 @@ def appendMultiListButton(self, szAttachTo, szTexture, listId, eWidgetType=-1, i return while len(w.lists) <= int(listId): w.lists.append([]) - w.lists[int(listId)].append([_str(szTexture), _int(eWidgetType), _int(iData1), _int(iData2), bool(bOption), None]) + w.lists[int(listId)].append([_str(szTexture), _int(eWidgetType), _int(iData1), _int(iData2), bool(bOption), None, False]) _changed() def clearMultiList(self, szName): @@ -1043,7 +1043,18 @@ def disableMultiListButton(self, szName, iListId, iIndexId, szTexture): pass def selectMultiList(self, szName, iListID): pass - def enableMultiListPulse(self, szName, bEnable, listId, iIndexId): pass + + def enableMultiListPulse(self, szName, bEnable, listId, iIndexId): + """The button glows on and off (the main interface's: the action recommended for the unit + where it is, or where the held right button points).""" + w = self._s.get(szName) + try: + b = w.lists[int(listId)][int(iIndexId)] + if b[6] != bool(bEnable): + b[6] = bool(bEnable) + _changed() + except (AttributeError, IndexError, TypeError): + pass # ---------------------------------------------------------------- tables @@ -1585,7 +1596,7 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): if height and (by + bh <= y or by >= y + height): continue out.append((base + ((listId << 16) | index,), 'imagebutton', bx, by, bx + bw, by + bh, box, w.style, u'', b[5] if b[5] and b[5] != '-' else b[0], - '', 1, 0, False, b[5] is None and w.enabled, 0, None, b[1], b[2], b[3], b[4], w.z, w.seq)) + '', 1, 0, False, b[5] is None and w.enabled, 0, None, b[1], b[2], b[3], b[4], w.z, w.seq, b[6])) return if kind == 'table': # (the theme's cell height, GFC_Control_Size_ListItem; taller for a table whose cells have pictures) @@ -1703,8 +1714,9 @@ def dump(path): """Writes every widget of the shown screens (name, kind, place, style, art) to a file.""" f = open(path, 'w') for item in display(): - f.write('%s\t%s\t%s\t(%d,%d)-(%d,%d)\tstyle=%s\ttex=%s\ttext=%s\twidget=%d,%d,%d\n' % (item[0][0], item[0][1], item[1], item[2], item[3], item[4], - item[5], item[7], item[9], _text(item[8]).encode('utf-8')[:60], item[17], item[18], item[19])) + f.write('%s\t%s\t%s\t(%d,%d)-(%d,%d)\tstyle=%s\ttex=%s\ttext=%s\twidget=%d,%d,%d%s\n' % (item[0][0], item[0][1], item[1], item[2], item[3], item[4], + item[5], item[7], item[9], _text(item[8]).encode('utf-8')[:60], item[17], item[18], item[19], + '\tpulse' if item[1] == 'imagebutton' and len(item) > 23 and item[23] else '')) f.close() @@ -1713,7 +1725,7 @@ def display(): Each item: ((file id, widget name, part), kind, x0, y0, x1, y1, clip, style, text, texture, texture2, font, flags, state, enabled, hit test, colour, widget type, data1, data2, option, - z, order[, bar start, bar percent]). + z, order[, bar start, bar percent][, a multi list's button: pulse]). """ for f in beforeDisplay: try: diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..17bc808f 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -197,6 +197,7 @@ namespace oc4::render MapWindow::PlotMarks plotMarks; std::array yieldSymbols; bool pathing = false; // the right button held while playing: the way to the plot under the mouse + bool pathCancelled = false; // ... let go of with Esc: the button's release is no order bool goingTo = false; // the go-to mode (G) while playing: the same, without the button MapWindow::PathView path; // that way, as the host found it std::vector screenPixels; @@ -1078,6 +1079,14 @@ namespace oc4::render } if (k != key::Shift && k != key::Control && k != key::Menu) ++inputs; + // Esc with the right button held: the way shown is let go, and the button's release orders nothing (as the original's). + if (k == key::Escape && pathing) + { + pathing = false; + pathCancelled = true; + path = {}; + return; + } if (uiTakesKeys && !ctrl && !alt && uiKey(k, shift)) return; // (W A S D panning: the press is the map's, not the game's hotkey) @@ -1159,6 +1168,7 @@ namespace oc4::render downX = x; downY = y; downLeft = left; + pathCancelled = false; } // On a popup: its buttons (the map around it still pans). if (down && popup.contains(x, y)) @@ -1209,6 +1219,12 @@ namespace oc4::render return; } // The right button held while playing shows the way there; let go, the units go there. + if (!down && std::exchange(pathCancelled, false)) + { + SDL_CaptureMouse(false); + panning = orbiting = minimapDrag = false; + return; + } if (!down && std::exchange(pathing, false)) { SDL_CaptureMouse(false); @@ -2536,6 +2552,14 @@ namespace oc4::render m->onButton(false, false, x, y); } + void MapWindow::mouseMove(int x, int y) { m->onMouseMove(x, y); } + + void MapWindow::mouseButton(int x, int y, bool left, bool down) + { + m->onMouseMove(x, y); + m->onButton(left && down, down, x, y); // (as SDL's: a button let go says not which) + } + std::optional MapWindow::clickAt(int x, int y, bool right) const { const auto figure = m->figureUnder(x, y); diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..9835d0cf 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -216,6 +216,7 @@ namespace oc4::render int font = 1; // FontTypes int flags = 1; // 1 left, 2 right, 4 centred (x0 is the anchor) bool state = false, enabled = true; + bool pulse = false; // (a button that glows on and off: the action recommended, GFC's multi list pulse) bool interactive = false; // takes clicks and has help bool mainInterface = false; // the main interface's: under a menu the keys do not reach it bool blocks = false; // a screen's own panel or picture over the main interface: what is under it takes no clicks @@ -362,6 +363,9 @@ namespace oc4::render // A left click at that pixel as the mouse makes it (scripted tests): on a popup, the // screens, the action bar or the map, whichever takes it there. void mouseClick(int x, int y); + // The mouse moved to that pixel; a button pressed or let go there (a scripted game's drags). + void mouseMove(int x, int y); + void mouseButton(int x, int y, bool left, bool down); // The mouse's cursor over the window: a cursor file (.cur, .ani: the game's res/Cursors); // none, the system's arrow. void setCursorFile(const std::filesystem::path& file); diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..66e4cc01 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -420,6 +420,16 @@ namespace oc4::render case Kind::ImageButton: if (icon(it.texture, x0, y0, x1, y1, alpha)) { + // (a pulsing button: what the unit is recommended to do; the original's has a blue rim + // that glows round it, a little brighter and dimmer a second a beat, the picture tinted blue) + if (it.pulse) + { + const float beat = 0.5f - 0.5f * std::cos(float(clock) * 2 * std::numbers::pi_v); + constexpr Color kGlow{ 0.2f, 0.55f, 1.0f }; + o.rect(x0, y0, x1, y1, kGlow, 0.18f * alpha, 3); + o.frame(x0 - 2, y0 - 2, x1 + 2, y1 + 2, kGlow, (0.25f + 0.15f * beat) * alpha, 5, 3); + o.frame(x0, y0, x1, y1, { 0.45f, 0.75f, 1.0f }, (0.75f + 0.25f * beat) * alpha, 3, 2); + } if (hot) o.frame(x0, y0, x1, y1, kHot, 1, 3, 2); } From d562307aade61cd9ef14c7d5ff3712a6bf51efb1 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 19:50:15 +0100 Subject: [PATCH 22/89] Tech advisor: read the research through CyPlayer and CyTeam (Windows link) oc4core links the game core through its import library on Windows, where only its exported functions can be called; CvTeam::isHasTech, getResearchProgress, CvPlayer::getQueuePosition, calculateResearchRate and CvGlobals::getNumTechInfos are not (LNK1120 on windows-x64). The research state the tech advisor is told about is now read by oc4screens.researchState through the scripts' CyPlayer and CyTeam, as a string compared each frame. The same values, the same behaviour. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 24 +++++++++--------------- apps/oc4core/Screens.h | 2 +- apps/oc4core/python/oc4screens.py | 17 +++++++++++++++++ 3 files changed, 27 insertions(+), 16 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5a8bd3e3..354fa961 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -19,7 +19,6 @@ #include "CvGameTextMgr.h" #include "CvMap.h" #include "CvPlayerAI.h" -#include "CvTeamAI.h" #include "CvPlot.h" #include "CvPopupInfo.h" #include "CvSelectionGroup.h" @@ -1021,22 +1020,17 @@ if _walls: // (CvScreensInterface.forceScreenUpdate: "forced from net message"): a tech clicked, // queued with Shift, learnt, the turns left. Its techs then take their colours and // numbers again (CvTechChooser.updateTechRecords). - if (techChooser && GC.getGame().getActivePlayer() != NO_PLAYER) + // (read through the scripts' CyPlayer and CyTeam, oc4screens.researchState: the core's + // own functions are not all exported to the engine on Windows) + const std::string research = techChooser ? screens.attr("researchState")().cast() : std::string(); + if (research.empty()) + m_research.clear(); + else if (research != m_research) { - const CvPlayerAI& player = CvPlayerAI::getPlayerNonInl(GC.getGame().getActivePlayer()); - const CvTeamAI& team = CvTeamAI::getTeamNonInl(player.getTeam()); - std::vector research{ GC.getGame().getGameTurn(), player.getCurrentResearch(), team.getResearchProgress(player.getCurrentResearch() < 0 ? TechTypes(0) : player.getCurrentResearch()), player.calculateResearchRate() }; - for (int i = 0; i < GC.getNumTechInfos(); ++i) - research.push_back(team.isHasTech(TechTypes(i)) ? -1 : player.getQueuePosition(TechTypes(i))); - if (research != m_research) - { - // (redrawn when it comes up: the original's shows the turns left at once) - entry.attr(m_research.empty() ? "forceScreenRedraw" : "forceScreenUpdate")(py::make_tuple(m_techChooserId)); - m_research = std::move(research); - } + // (redrawn when it comes up: the original's shows the turns left at once) + entry.attr(m_research.empty() ? "forceScreenRedraw" : "forceScreenUpdate")(py::make_tuple(m_techChooserId)); + m_research = research; } - else - m_research.clear(); if (ui.anyDirty()) entry.attr("forceScreenRedraw")(py::make_tuple(m_mainId)); // Diplomacy: the next talk waiting, when nothing is up (the game's script says what the diff --git a/apps/oc4core/Screens.h b/apps/oc4core/Screens.h index a671f368..58383099 100644 --- a/apps/oc4core/Screens.h +++ b/apps/oc4core/Screens.h @@ -132,7 +132,7 @@ namespace oc4::host bool m_menu = false; // the main menu, not the game's screens int m_mainId = -1, m_failures = 0; int m_techChooserId = -1; - std::vector m_research; // the active player's research when the tech advisor was last told (empty: not up) + std::string m_research; // the active player's research when the tech advisor was last told (empty: not up) long long m_version = -1; std::pair m_laidOut{ -1, -1 }, m_seenSize{ -1, -1 }; // the size the screens were made for; the window's std::chrono::steady_clock::time_point m_sizeChanged; diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 517bcedb..bfc654d0 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -39,6 +39,23 @@ def _changed(): _version[0] += 1 +def researchState(): + """The active player's research as a string that changes when the tech advisor should be told + (the tech researched, its progress, the rate, the queue's places, the techs known, the turn); '' + with no active player.""" + gc = _cpe.CyGlobalContext() + game = _cpe.CyGame() + iPlayer = game.getActivePlayer() + if iPlayer < 0: + return '' + player = gc.getPlayer(iPlayer) + team = gc.getTeam(player.getTeam()) + current = player.getCurrentResearch() + places = [team.isHasTech(i) and -1 or player.getQueuePosition(i) for i in range(gc.getNumTechInfos())] + return repr((game.getGameTurn(), current, current >= 0 and team.getResearchProgress(current) or 0, + player.calculateResearchRate(-1), places)) + + beforeDisplay = [] # (called before the display list is made: oc4options lays its window out) From 21986ab92e1e7dcafbb465e786a5d5da890aed56 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 20:46:30 +0100 Subject: [PATCH 23/89] Game font icons mods add: every cell of a group's rows, and GameFont_75's where GameFont has none BUG draws its attitude faces, war and peace icons as font cells by their offset from a symbol the DLL names (init.xml, FontUtil.addOffsetSymbol), and only BUG's GameFont_75.tga holds them. The original shows them (BUG's foreign advisor GLANCE tab, its INFO attitudes, the espionage screen, the scoreboard); OpenCiv4 mapped only the DLL's own codes and read GameFont.tga only, so they were blank. Co-Authored-By: Claude Opus 5.5 --- src/render/ButtonArt.cpp | 70 ++++++++++++++++++++++++++-------------- src/render/ButtonArt.h | 13 +++++--- 2 files changed, 54 insertions(+), 29 deletions(-) diff --git a/src/render/ButtonArt.cpp b/src/render/ButtonArt.cpp index f86dae8c..a128d493 100644 --- a/src/render/ButtonArt.cpp +++ b/src/render/ButtonArt.cpp @@ -53,18 +53,20 @@ namespace oc4::render void ButtonArt::setFontLayout(std::vector groups) { m_fontLayout = std::move(groups); - m_glyphsRead = false; - m_glyphs.clear(); + for (FontSheet& sheet : m_sheets) + sheet = {}; } // The game font: rows of cells split by magenta lines and columns (the letters' rows // first, then the icons' rows, as tall as the last one). The icon cells are counted on // across the rows (mods' rows are longer than 25); each of the DLL's groups takes its // rows of 25 of them, its characters by their distance from the group's first code. - const ButtonArt::Picture* ButtonArt::readFont() + const ButtonArt::Picture* ButtonArt::readFont(int sheet) { constexpr int kFirstCode = 8483, kRow = 25; - const Picture* font = picture("res/fonts/gamefont.tga"); + const Picture* font = picture(sheet ? "res/fonts/gamefont_75.tga" : "res/fonts/gamefont.tga"); + auto& glyphs = m_sheets[sheet].glyphs; + bool& read = m_sheets[sheet].read; if (!font) return nullptr; const uint32_t w = font->width, h = font->height; @@ -72,9 +74,9 @@ namespace oc4::render const uint8_t* p = font->bgra.data() + (size_t(y) * w + x) * 4; return p[0] == 255 && p[1] == 0 && p[2] == 255; }; - if (!m_glyphsRead) + if (!read) { - m_glyphsRead = true; + read = true; std::vector> bands; // rows of cells: y0, y1 for (uint32_t y = 0, start = 0; y <= h; ++y) { @@ -120,9 +122,18 @@ namespace oc4::render // (the DLL starts every group but the first at a multiple of 25; a mod's bonuses // are numbered by their FontButtonIndex, the first one need not be 0) const int base = std::max(kFirstCode, *std::ranges::min_element(group.codes) / kRow * kRow); + // (every cell of the group's rows, not only the DLL's codes: mods draw more icons + // there, by their offset from one it names: BUG's attitude faces, war and peace + // after the symbols, FontUtil's addOffsetSymbol; the last group, the symbols, to + // the font's end) + const bool last = &group == &m_fontLayout.back(); + const int count = last ? int(cells.size() - std::min(groupStart, cells.size())) : group.rows * kRow; + for (int k = 0; k < count; ++k) + if (const size_t cell = groupStart + size_t(k); cell < cells.size()) + glyphs.try_emplace(base + k, cells[cell]); for (const int code : group.codes) if (const size_t cell = groupStart + size_t(code - base); cell < cells.size()) - m_glyphs[code] = cells[cell]; + glyphs[code] = cells[cell]; } groupStart += size_t(group.rows) * kRow; } @@ -132,24 +143,33 @@ namespace oc4::render bool ButtonArt::fontGlyph(int code, Icon& icon) { - const Picture* font = readFont(); - if (!font) - return false; - const uint32_t w = font->width; - const auto it = m_glyphs.find(code); - if (it == m_glyphs.end()) - return false; - const auto [x0, y0, x1, y1] = it->second; - icon.width = x1 - x0; - icon.height = y1 - y0; - icon.bgra.resize(size_t(icon.width) * icon.height * 4); - for (uint32_t y = 0; y < icon.height; ++y) - std::copy_n(font->bgra.begin() + ptrdiff_t((size_t(y0 + y) * w + x0) * 4), icon.width * 4, - icon.bgra.begin() + ptrdiff_t(size_t(y) * icon.width * 4)); - bool any = false; - for (size_t i = 3; i < icon.bgra.size(); i += 4) - any |= icon.bgra[i] != 0; - return any; + // (the game font's cell; one it leaves empty from the 75 % font: mods draw some icons only + // there, BUG its attitude faces, war and peace, and the original then shows them, as at + // 1600x900) + for (int sheet = 0; sheet < 2; ++sheet) + { + const Picture* font = readFont(sheet); + if (!font) + continue; + const auto& glyphs = m_sheets[sheet].glyphs; + const auto it = glyphs.find(code); + if (it == glyphs.end()) + continue; + const uint32_t w = font->width; + const auto [x0, y0, x1, y1] = it->second; + icon.width = x1 - x0; + icon.height = y1 - y0; + icon.bgra.resize(size_t(icon.width) * icon.height * 4); + for (uint32_t y = 0; y < icon.height; ++y) + std::copy_n(font->bgra.begin() + ptrdiff_t((size_t(y0 + y) * w + x0) * 4), icon.width * 4, + icon.bgra.begin() + ptrdiff_t(size_t(y) * icon.width * 4)); + bool any = false; + for (size_t i = 3; i < icon.bgra.size(); i += 4) + any |= icon.bgra[i] != 0; + if (any) + return true; + } + return false; } // Button art: a DDS of its own, or ",,,,": the atlas cell (64 diff --git a/src/render/ButtonArt.h b/src/render/ButtonArt.h index 9f429ef3..ebc78ecb 100644 --- a/src/render/ButtonArt.h +++ b/src/render/ButtonArt.h @@ -49,12 +49,17 @@ namespace oc4::render const Picture* picture(const std::string& file); // The game font's cell of the character: false without one. bool fontGlyph(int code, Icon& icon); - const Picture* readFont(); + // (sheet 0: GameFont.tga; 1: GameFont_75.tga) + const Picture* readFont(int sheet); - // The font's icon cells, by character: x0, y0, x1, y1 in its picture. - std::map> m_glyphs; + // The fonts' icon cells, by character: x0, y0, x1, y1 in its picture. + struct FontSheet + { + std::map> glyphs; + bool read = false; + }; + std::array m_sheets; std::vector m_fontLayout; - bool m_glyphsRead = false; const AssetResolver& m_assets; std::map m_icons; From 155f0f8a4064e4c1b40a759d20343cf4ac37a11b Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 20:46:36 +0100 Subject: [PATCH 24/89] Screens laid out as the original's: panel titles, rows sharing a panel's height, lines under buttons Measured against the original (BUG's foreign advisor, Wine at 1600x900): - A panel's title is drawn over its box, 11 px in, the box 28 px down ("Surplus Resources", the ACTIVE tab's leaders' names); it was not drawn at all. - The panels in a vertical panel's flow share its free height (GLANCE, ACTIVE, INFO rows). - In a row, attachTextGFC texts and 46 px buttons sit in cells at least 46 wide, 18 apart, in the row's middle (INFO's columns under their headers); BUTTON_SIZE_CUSTOM is as high as the row (ACTIVE's leaders). - A label of spaces is as wide as they are, and labels never take the rest of a row (ACTIVE's " " pushed the leader and the deals out of the row). - addLineGFC lines are a pixel wide and drawn on their draw control, under the widgets made after it (RELATIONS: the lines run under the leaders' buttons). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4screens.py | 74 +++++++++++++++++++++++++++---- src/render/UiLayer.cpp | 3 +- 2 files changed, 67 insertions(+), 10 deletions(-) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..fb397541 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -88,7 +88,7 @@ class _Widget(object): __slots__ = ('name', 'kind', 'parent', 'mode', 'x', 'y', 'z', 'w', 'h', 'style', 'pstyle', 'text', 'help', 'tex', 'tex2', 'wt', 'd1', 'd2', 'opt', 'flags', 'font', 'shown', 'enabled', 'state', 'hittest', 'seq', 'vertical', 'scroll', 'children', 'bars', 'lists', 'columns', 'rows', 'headers', 'iconw', 'iconh', 'items', 'selected', 'color', 'size', 'defw', 'defh', 'points', - 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed') + 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed', 'grow') def __init__(self, name, kind): self.name = name @@ -135,6 +135,7 @@ def __init__(self, name, kind): self.cells = None # tables: {(row, column): the name of the control attached there} self.sort = None # tables that sort: (column, descending) the rows are shown by, or (-1, False) self.inset = 0 # scroll panels (addScrollPanel): where what is placed in them (attach...At) starts + self.grow = 0 # panels in a vertical panel's flow: higher by this, their share of its free height class _Screen(object): @@ -682,6 +683,9 @@ def attachImageButton(self, szAttachTo, szName, szTexture, eSize, eWidgetType=-1 size = {0: 46, 1: 32, 2: 24, 3: 16}.get(_int(eSize, 1), 32) w = self._image('imagebutton', szName, szAttachTo, szTexture, 0, 0, size, size, eWidgetType, iData1, iData2, 'flow') w.opt = bool(bOption) + # (BUTTON_SIZE_CUSTOM: as high as the row it is in, square; the foreign advisor's ACTIVE tab + # leaders, 58 in a row of 66) + w.size = -1 if _int(eSize, 1) == 4 else 0 def setButtonGFC(self, szName, szText, szTexture, iX, iY, iWidth, iHeight, eWidgetType=-1, iData1=-1, iData2=-1, eStyle=0): w = self._image('button', szName, None, szTexture, iX, iY, iWidth, iHeight, eWidgetType, iData1, iData2, 'abs') @@ -1497,8 +1501,12 @@ def _size(s, w): if w.mode == 'full': return _resolution[0], _resolution[1] if w.kind in ('label', 'text'): - # (a text, setText, is in the theme's size 3 whatever font it names; a label in its own) - return max(w.w, _textWidth(w.text, 3 if w.kind == 'text' else w.font)), _TEXT_HEIGHT.get(w.font, 18) + # (a text, setText, is in the theme's size 3 whatever font it names; a label in its own; + # one of spaces as wide as they are: the foreign advisor's " " before a leader) + width = _textWidth(w.text, 3 if w.kind == 'text' else w.font) + if not width and w.text and not w.text.strip(): + width = len(w.text) * _SPACE + return max(w.w, width), _TEXT_HEIGHT.get(w.font, 18) if w.kind == 'multiline': # (one placed with a height, addMultilineText, is that high: a longer text scrolls in it) if w.mode != 'flow' and w.h > 0: @@ -1517,12 +1525,21 @@ def _size(s, w): for cw in held: if cw.mode == 'rel': height = max(height, cw.y + _size(s, cw)[1] + 4) - return w.w, height + return w.w, height + _title(w) + w.grow if w.kind == 'button' and not w.w: return len(w.text) * 8 + 16, w.h or 24 return w.w, w.h +_SPACE = 4 # a space's width in the theme's normal font +_TITLE = 28 # a panel's title: over its box, in a strip this high (the original's panels with a title) + + +def _title(w): + """How much higher than its box a panel is for its title.""" + return _TITLE if w.kind == 'panel' and w.text else 0 + + def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): """Adds a widget (and what is attached to it) to the display list; one attached to a table's cell only there (cell: that cell's corner).""" @@ -1542,13 +1559,27 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): x, y = flow[0], flow[1] width, height = _size(s, w) if w.mode == 'flow': - # (one of no width of its own takes the rest of its parent's; a text then wraps there) - if not width: + # (one of no width of its own takes the rest of its parent's; a text then wraps there; a + # label or text is as wide as it is) + if w.kind == 'imagebutton' and w.size == -1 and len(flow) > 5 and flow[5] > 0: + width = height = flow[5] + if not width and w.kind not in ('label', 'text'): width = max(0, flow[3] - (x - flow[4])) if w.kind == 'multiline' and width: height = max(w.h, _textHeight(w.text, width, w.font)) + if not flow[2] and len(flow) > 5 and flow[5] > height and w.kind != 'panel': + # (in a row as high as its panel, in the middle of its height, as the original's: the + # foreign advisor's INFO rows, their leaders, civics and numbers) + y += (flow[5] - height) / 2 if flow[2]: flow[1] += height + 2 + elif w.kind == 'text' or (w.kind == 'imagebutton' and w.size != -1 and width == 46): + # (in a row, attachTextGFC's texts and the 46 pixel buttons each in a cell at least 46 + # wide, a text in its middle, 18 apart: the foreign advisor's INFO tab, its columns under + # their headers, measured in the original) + cell = max(width, 46) + x += (cell - width) / 2 + flow[0] += cell + 18 else: flow[0] += width + 4 # (a text attached at a place in its parent, setTextAt, starts there whatever its justification: @@ -1656,9 +1687,13 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): w.hittest, None, w.wt, w.d1, w.d2, w.opt, w.z, w.seq)) return if kind == 'line': + # (drawn on its draw control, addLineGFC's: in its place among the others, under what came + # after it; the foreign advisor's relations run under the leaders' buttons, as the original) x0, y0, x1, y1 = w.points + owner = s.widgets.get(w.parent) if w.parent else None + z, seq = (owner.z, owner.seq + w.seq * 1e-7) if owner is not None else (w.z, w.seq) out.append((base + (-1,), 'line', ox + x0, oy + y0, ox + x1, oy + y1, clip, '', u'', '', '', 0, 0, False, True, 4, w.color, -1, -1, -1, False, - w.z, w.seq)) + z, seq)) return if kind == 'bar': start = 0.0 @@ -1675,7 +1710,15 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): text = w.text if kind == 'edit' and _editFocus[0] == (s.id, w.name): text = text + u'|' # (the caret: typed into) - out.append((base + (-1,), kind, x, y, x + width, y + height, clip, w.style if w.style else w.pstyle, text, w.tex, w.tex2, w.font, flags, + title = _title(w) + if title: + # (a panel's title over its box, at its left, in the theme's normal font: the foreign + # advisor's "Surplus Resources", its ACTIVE tab's leaders' names; measured in the original + # at 11 right of the box's edge, the box 28 down) + out.append((base + (-2,), 'text', x + 11, y + 3, x + 11 + _textWidth(text, 3), y + 3 + 18, clip, '', text, '', '', 1, _FONT_LEFT, + False, True, 0, None, -1, -1, -1, False, w.z, w.seq)) + text = u'' + out.append((base + (-1,), kind, x, y + title, x + width, y + height, clip, w.style if w.style else w.pstyle, text, w.tex, w.tex2, w.font, flags, w.state, w.enabled, w.hittest, color, w.wt, w.d1, w.d2, w.opt, w.z, w.seq)) if w.children: inner, left, top = clip, x, y @@ -1683,7 +1726,20 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): if scrolls: inner, left, top = _clipTo(clip, (x, y, x + width, y + height)), x - w.hoffset, y - w.offset first = len(out) - childFlow = [left + 4, top + 4 + (18 if w.text else 0), w.vertical, max(0, width - 8), left + 4] + held = [cw for cw in [s.widgets.get(c) for c in w.children] if cw is not None and cw.shown and cw.mode == 'flow'] + if kind == 'panel' and w.vertical: + # (the panels in a vertical panel's flow share what is left of its height, as the + # original lays them out: the foreign advisor's GLANCE, ACTIVE and INFO rows fill it) + for cw in held: + cw.grow = 0 + grow = [cw for cw in held if cw.kind == 'panel' and not cw.h] + if grow and height > 0: + free = height - title - 8 - sum([_size(s, cw)[1] + 2 for cw in held]) + for cw in grow: + cw.grow = max(0, free / len(grow)) + # (and the rows of a horizontal one: as high as it is, inside its margins; a custom sized + # button is that high) + childFlow = [left + 4, top + 4 + title, w.vertical, max(0, width - 8), left + 4, 0 if w.vertical else max(0, height - title - 8)] for c in w.children: cw = s.widgets.get(c) if cw is not None: diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..4b07ffa8 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -574,7 +574,8 @@ namespace oc4::render break; } case Kind::Line: - o.line(x0, y0, x1, y1, it.hasColor ? it.color : kEdge, it.alpha, 2); + // (a pixel wide, as the original's addLineGFC: the foreign advisor's relations) + o.line(x0, y0, x1, y1, it.hasColor ? it.color : kEdge, it.alpha, 1); break; case Kind::Separator: o.line(x0, y0 + h / 2, x1, y0 + h / 2, kEdge, 0.5f); From cc6b07a63ee48e09fe68ee8fb5bfeeb94a589518 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 21:00:15 +0100 Subject: [PATCH 25/89] City on the map: a double click opens it, one click on its bar selects it As the original (Wine, BUG + BULL): a double click on one's city or its name bar opens the city screen, a single click on the bar selects the city (what it builds in the bottom panel), and a single click on the city's plot is any plot's (its units, else nothing). OpenCiv4 opened the screen on any single click. The single click stays as an OpenCiv4 option, "Open a city with a single click" on the options' OpenCiv4 tab (off; cityOneClick in profile.ini). Clicks carry whether they hit a city's bar, and --keys has "*" for a double click. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +++++- apps/oc4core/Screens.cpp | 2 ++ apps/oc4core/Utility.h | 5 ++++ apps/oc4core/main.cpp | 31 ++++++++++++++++++------- apps/oc4core/python/oc4options.py | 38 +++++++++++++++++++++++++++---- src/render/MapWindow.cpp | 19 +++++++++++----- src/render/MapWindow.h | 6 +++-- tests/player_options_test.py | 22 ++++++++++++++++-- 8 files changed, 107 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 780316e2..310cbeb5 100644 --- a/README.md +++ b/README.md @@ -208,11 +208,16 @@ edge" on the options' OpenCiv4 tab turns it off (on by default). It is kept in p `edgeScroll`, and `--no-edge-scroll` turns it off for one run (scripted runs with `--view-seconds` never edge scroll). The rule is `src/render/EdgeScroll.h`, tested by `tests/edge_scroll_test.cpp`. +Your cities on the map open as in the original: a double click on the city or its name bar opens +its screen, one click on the bar selects the city (what it builds in the bottom panel), and one click +on its plot is any plot's (the units there). "Open a city with a single click" on the options' +OpenCiv4 tab opens the screen with one click instead (off by default; `cityOneClick` in profile.ini). + The player options (Options → Game: Wait at End of Turn, Quick Combat, …) are kept in the player's profile, as the original keeps them in its own (`Profiles\.pfl`): a choice is written to profile.ini at once (`player.N=`), and every game, new or loaded, starts with the profile's, which the game core sends to the active player (a save's own options are overwritten, as in the original). -OpenCiv4's own options (W A S D, idle turns, edge scrolling) are on a tab of their own, OpenCiv4, +OpenCiv4's own options (W A S D, idle turns, edge scrolling, one click on a city) are on a tab of their own, OpenCiv4, after the original's four. Tested by `tests/player_options_test.py`. The globe view's colour layers (Culture, Trade, Religion) are drawn on the globe itself. diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index efe18e86..1b0f9bee 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -272,6 +272,8 @@ namespace oc4::host host.def("set_wasd_pan", [&utility](bool on) { utility.setWasdPan(on); }); host.def("choose_wasd_pan", [&utility](bool on) { utility.chooseWasdPan(on); }); host.def("wasd_pan", [&utility] { return utility.wasdPan(); }); + host.def("set_city_one_click", [&utility](bool on) { utility.setCityOneClick(on); }); + host.def("city_one_click", [&utility] { return utility.cityOneClick(); }); // Ending idle turns: the same. host.def("set_auto_end_turn", [&utility](bool on) { utility.setAutoEndTurn(on); }); host.def("choose_auto_end_turn", [&utility](bool on) { utility.chooseAutoEndTurn(on); }); diff --git a/apps/oc4core/Utility.h b/apps/oc4core/Utility.h index b01d32be..af390f15 100644 --- a/apps/oc4core/Utility.h +++ b/apps/oc4core/Utility.h @@ -240,6 +240,10 @@ namespace oc4::host void setWasdPan(bool on) { m_wasdPan = on; } void forceWasdPan() { m_forcedWasdPan = true; } void chooseWasdPan(bool on) { m_forcedWasdPan = false; m_wasdPan = on; } + // One click on one's city (or its name bar) opens its screen (the profile's; off, as the + // original's: a double click opens it, one on the bar selects the city). + bool cityOneClick() const { return m_cityOneClick; } + void setCityOneClick(bool on) { m_cityOneClick = on; } // End idle turns by themselves (AutoEndTurn.h; the profile's, or --auto-end-turn's for the // session until the player chooses: Ctrl+Shift+E or the options' check box). bool autoEndTurn() const { return m_forcedAutoEndTurn || m_autoEndTurn; } @@ -433,6 +437,7 @@ namespace oc4::host std::array m_playerOptions{}; // the profile's: 0 the XML's default, 1 off, 2 on int m_uiScale = 0, m_forcedUiScale = -1; bool m_wasdPan = false, m_forcedWasdPan = false; + bool m_cityOneClick = false; bool m_autoEndTurn = false, m_forcedAutoEndTurn = false; render::EdgeScrollOption m_edgeScroll; std::array, 64> m_graphicOptions{}; // 0 the XML's default, 1 off, 2 on (set by the window's thread, read by the game's) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index a2b161a5..0ef3a15b 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1169,14 +1169,16 @@ namespace clicks.push_back(click); script.erase(0, close + 1); } - else if (int px = 0, py = 0; script.front() == '<' && script.find('>') != std::string::npos && std::sscanf(script.c_str() + 1, "%d,%d", &px, &py) == 2) + else if (int px = 0, py = 0, twice = script.starts_with("*<"); (script.front() == '<' || twice) && script.find('>') != std::string::npos && + std::sscanf(script.c_str() + 1 + twice, "%d,%d", &px, &py) == 2) { // "": a left click at that pixel of the window, on what is there (a popup, the - // screens, a unit's figure, a plot), as the mouse's. + // screens, a unit's figure, a city's bar, a plot), as the mouse's; "*" a double click. if (log) if (const auto c = window.clickAt(px, py, false)) - std::printf(" click at %d,%d: plot %d,%d%s\n", px, py, c->x, c->y, c->onFigure ? " (a unit's figure)" : ""); - window.mouseClick(px, py); + std::printf(" %s at %d,%d: plot %d,%d%s\n", twice ? "double click" : "click", px, py, c->x, c->y, + c->onFigure ? " (a unit's figure)" : c->onCityBar ? " (a city's bar)" : ""); + window.mouseClick(px, py, twice); script.erase(0, script.find('>') + 1); } else if (const size_t mods = script.find_first_not_of("^@+"), end = script.find('}'); @@ -1329,13 +1331,26 @@ namespace ui.setInterfaceMode(INTERFACEMODE_SELECTION); continue; } - // A click on one's city: its screen (the units there are in the plot list then); on - // one of the figures in it, as anywhere, its unit. + // One's city, as the original's: a double click on it or its name bar opens its screen + // (the units there are in the plot list then), one click on the bar selects the city + // (what it builds in the bottom panel); one click on its plot is any plot's (its + // units). On one of the figures in it, as anywhere, its unit. OpenCiv4's option opens + // the screen with one click on either. if (!click.right && !click.onFigure && !opt.ownInterface && screens.active()) if (CvCity* city = plot->getPlotCity(); city && city->getOwner() == me) { - ui.selectCity(city, true); - continue; + if (click.twice || utility.cityOneClick()) + { + ui.selectCity(city, true); + continue; + } + if (click.onCityBar) + { + ui.clearSelectionList(); + ui.clearSelectedCities(); + ui.addSelectedCity(city, false); + continue; + } } if (!click.right) { diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index dd7e1664..fd2a1f02 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -47,7 +47,7 @@ def _scales(): 'clock': False, 'hours24': False, 'graphicsLevel': 0, 'renderQuality': 0, 'globeView': 0, 'movieQuality': 0, 'mainMenu': 0, 'antiAliasing': 0, 'uiScale': 0, 'speakers': '', 'musicPath': '', 'voice': False, - 'wasdPan': False, 'autoEndTurn': False, 'edgeScroll': True, + 'wasdPan': False, 'autoEndTurn': False, 'edgeScroll': True, 'cityOneClick': False, } @@ -87,7 +87,7 @@ def _load(): _profile['nosound'][parts[1]] = value == '1' elif parts[0] in ('graphic', 'player'): _profile[parts[0]][int(parts[1])] = value == '1' - elif parts[0] in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): + elif parts[0] in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll', 'cityOneClick'): _profile[parts[0]] = value == '1' elif parts[0] in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale'): _profile[parts[0]] = int(value) @@ -115,7 +115,7 @@ def _save(): lines = ['version=%d' % _VERSION] for key in ('name', 'speakers', 'musicPath'): lines.append('%s=%s' % (key, _profile[key])) - for key in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): + for key in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll', 'cityOneClick'): lines.append('%s=%d' % (key, 1 if _profile[key] else 0)) for key in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale'): lines.append('%s=%d' % (key, _profile[key])) @@ -144,6 +144,7 @@ def _applyGraphics(): oc4host.set_wasd_pan(_profile['wasdPan']) oc4host.set_auto_end_turn(_profile['autoEndTurn']) oc4host.set_edge_scroll(_profile['edgeScroll']) + oc4host.set_city_one_click(_profile['cityOneClick']) except Exception: pass @@ -236,6 +237,29 @@ def _edgeScrollOn(): return _profile['edgeScroll'] +# Opening a city with one click (openciv4's own option, off: the original opens a city with a double +# click on it or its name bar, and one click on the bar selects it). +CITY_ONE_CLICK_CHECKBOX = 'Oc4CityOneClickCheckBox' + + +def handleCityOneClickClicked(args): + on = bool(args[0]) + _profile['cityOneClick'] = on + _save() + try: + oc4host.set_city_one_click(on) + except Exception: + pass + return 1 + + +def _cityOneClickOn(): + try: + return bool(oc4host.city_one_click()) + except Exception: + return _profile['cityOneClick'] + + def _applyPlayerOptions(): """The player options the profile has, to the host: the game core sends them to the active player at the start of every game, new or loaded, as the original's profile (a save's own are @@ -518,7 +542,8 @@ def attachTabItem(self, szName, szLabel): def _attachOpenCiv4Tab(self): """OpenCiv4's options, none of the original's: W A S D panning, ending idle turns, edge - scrolling (kept in the profile as wasdPan, autoEndTurn, edgeScroll).""" + scrolling, opening a city with one click (kept in the profile as wasdPan, autoEndTurn, edgeScroll, + cityOneClick).""" self.attachTabItem(OC4_FORM, u'OpenCiv4') self.attachVBox(OC4_FORM, 'Oc4VBox') parent = 'Oc4Panel' @@ -541,6 +566,11 @@ def _attachOpenCiv4Tab(self): self.setToolTip(EDGE_SCROLL_CHECKBOX, u'Moving the mouse to the edge of the screen or window moves the map that way. ' u'Turn it off to pan only with the arrow keys (or W A S D) and the mouse.') + self.attachCheckBox(parent, CITY_ONE_CLICK_CHECKBOX, u'Open a city with a single click', 'oc4options', 'handleCityOneClickClicked', + CITY_ONE_CLICK_CHECKBOX, _cityOneClickOn()) + self.setToolTip(CITY_ONE_CLICK_CHECKBOX, u'One click on your city or its name bar opens the city screen. Off, as in the ' + u'original: a click on the name bar selects the city, a double click on the city or its bar opens it.') + def attachVBox(self, parent, name): self._node('vbox', parent, name) def attachHBox(self, parent, name): self._node('hbox', parent, name) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index 1ab30565..b4c1a2c4 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -1233,11 +1233,13 @@ namespace oc4::render mouseX = x; mouseY = y; // (a city's bar is over the figures: a click on it is on its city) - const auto figure = view->cityBarAt(float(x), float(y)) ? std::nullopt : figureUnder(x, y); + const bool onBar = view->cityBarAt(float(x), float(y)).has_value(); + const auto figure = onBar ? std::nullopt : figureUnder(x, y); if (const auto p = figure ? *figure : hoveredPlot(); p.first >= 0) { clicks.push_back({ p.first, p.second, !downLeft, mods.shift, mods.ctrl, mods.alt, figure.has_value() }); clicks.back().twice = buttonClicks >= 2; + clicks.back().onCityBar = onBar; } } if (down) @@ -2542,23 +2544,28 @@ namespace oc4::render SDL_SetCursor(it->second ? it->second : SDL_GetDefaultCursor()); } - void MapWindow::mouseClick(int x, int y) + void MapWindow::mouseClick(int x, int y, bool twice) { m->onMouseMove(x, y); - m->onButton(true, true, x, y); - m->onButton(false, false, x, y); + for (int n = 1; n <= (twice ? 2 : 1); ++n) + { + m->buttonClicks = n; + m->onButton(true, true, x, y); + m->onButton(false, false, x, y); + } + m->buttonClicks = 1; } std::optional MapWindow::clickAt(int x, int y, bool right) const { - // (a city's bar stands for the city, as the original's: its screen opens) + // (a city's bar stands for the city, as the original's) const auto bar = m->view->cityBarAt(float(x), float(y)); const auto figure = bar ? std::nullopt : m->figureUnder(x, y); const auto p = bar ? *bar : figure ? *figure : m->plotUnder(x, y); if (p.first < 0) return std::nullopt; PlotClick c; - c.x = p.first, c.y = p.second, c.right = right, c.onFigure = figure.has_value(); + c.x = p.first, c.y = p.second, c.right = right, c.onFigure = figure.has_value(), c.onCityBar = bar.has_value(); return c; } void MapWindow::setMessages(std::vector> messages) diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index ac954b2b..9086f825 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -109,6 +109,7 @@ namespace oc4::render bool either = false; // (the gamepad's plot cursor: `right` is the host's to say, see PadAction::Kind::PlotAct) bool clear = false; // (the gamepad's B: no plot's click, the selection let go) bool twice = false; // the second click of a double click + bool onCityBar = false; // on a city's name bar (the plot is the city's) }; void setPlaying(bool playing); std::vector takeClicks(); @@ -361,8 +362,9 @@ namespace oc4::render // The click a press at that pixel of the window would make on the map (a scripted game). std::optional clickAt(int x, int y, bool right) const; // A left click at that pixel as the mouse makes it (scripted tests): on a popup, the - // screens, the action bar or the map, whichever takes it there. - void mouseClick(int x, int y); + // screens, the action bar or the map, whichever takes it there; with twice, a double click + // (its first click, then the second, as the mouse's). + void mouseClick(int x, int y, bool twice = false); // The mouse's cursor over the window: a cursor file (.cur, .ani: the game's res/Cursors); // none, the system's arrow. void setCursorFile(const std::filesystem::path& file); diff --git a/tests/player_options_test.py b/tests/player_options_test.py index c13debbc..45e98895 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -43,6 +43,13 @@ def __init__(self, path): self.path = path self.states = [0] * 64 self.player = {} # (the active player's options, as sendPlayerOption sets them) + self.cityOneClick = False + + def set_city_one_click(self, on): + self.cityOneClick = bool(on) + + def city_one_click(self): + return self.cityOneClick def profile_path(self): return self.path @@ -142,14 +149,25 @@ def main(): check(profile.getPlayerOption(2) and not profile.getPlayerOption(6), "no profile: the XML's defaults") check(host.states[:NUM] == [0] * NUM, "no profile: the host has none chosen") - # The screen's tabs: the game's four, then OpenCiv4's with its three options. + # The screen's tabs: the game's four, then OpenCiv4's with its four options. ctrl = optionsScreen(options) check([label for form, label in ctrl._tabs] == ['Game', 'Graphics', 'Audio', 'Other', 'OpenCiv4'], "tabs: %s" % [l for f, l in ctrl._tabs]) oc4 = [n.name for n in ctrl._nodes.values() if n.kind == 'checkbox' and n.name.startswith('Oc4')] - check(sorted(oc4) == sorted([options.WASD_PAN_CHECKBOX, options.AUTO_END_TURN_CHECKBOX, options.EDGE_SCROLL_CHECKBOX]), "OpenCiv4's options: %s" % oc4) + check(sorted(oc4) == sorted([options.WASD_PAN_CHECKBOX, options.AUTO_END_TURN_CHECKBOX, options.EDGE_SCROLL_CHECKBOX, options.CITY_ONE_CLICK_CHECKBOX]), "OpenCiv4's options: %s" % oc4) game = [n.name for n in ctrl._byName['GamePanelCenter'].children] check(game == ['GameOptionCheckBox_2', 'GameOptionCheckBox_6', 'LangHBox'], "the Game tab has only the game's: %s" % game) + # Opening a city with one click: off (the original's double click), kept when chosen. + check(ctrl._byName[options.CITY_ONE_CLICK_CHECKBOX].value is False and not host.cityOneClick, "one click on a city: off by default") + click(options, ctrl, options.CITY_ONE_CLICK_CHECKBOX) + check(host.cityOneClick and 'cityOneClick=1' in profileLines(folder), "one click on a city: on, in profile.ini") + host, options = start(folder) + check(host.cityOneClick, "one click on a city: the profile's after a restart") + click(options, optionsScreen(options), options.CITY_ONE_CLICK_CHECKBOX) + check(not host.cityOneClick and 'cityOneClick=0' in profileLines(folder), "one click on a city: off again") + ctrl = optionsScreen(options) + profile = options._UserProfile() + # Wait at End of Turn off, Quick Moves on: sent to the player and kept at once. click(options, ctrl, 'GameOptionCheckBox_2') click(options, ctrl, 'GameOptionCheckBox_6') From 15456ef82336d3191046dd6c36f94929daaf555d Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 21:28:28 +0100 Subject: [PATCH 26/89] Multi list buttons in the theme's look: ring, hover glow, pressed, disabled, pulse The unit's actions and the city's builds (GFC multi lists) were bare pictures with a gold square under the mouse. The original lays the theme's MultiList_Item skins (Civ4/Custom/MultiListItem.tga) over each: a rounded ring in the HUDBorder colour; under the mouse the fill glow added (+57 of 255, with a soft edge just outside the ring); pressed, a blue fill half over it; disabled, everything inside the ring half way to black (not the theme's ItemDisable, a white wash); the recommended action's pulse a ring going from a deep to a light blue every 0.6 s, a blue halo outside and a little blue inside. The buttons are 48 wide, one every 50 (2 apart, across and down). All measured in Wine (BUG + BULL, 1600x900). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 2 + apps/oc4core/python/oc4screens.py | 13 ++++--- src/render/MapWindow.h | 1 + src/render/Theme.cpp | 28 ++++++++++++++ src/render/Theme.h | 3 ++ src/render/UiLayer.cpp | 61 ++++++++++++++++++++++++++++++- src/render/UiLayer.h | 6 +++ 7 files changed, 108 insertions(+), 6 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index c2abf965..334d4209 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -1213,6 +1213,8 @@ if _walls: info.movie = item.texture; if (item.kind == Kind::ImageButton && t.size() >= 24) item.pulse = t[23].cast(); + if (item.kind == Kind::ImageButton && t.size() >= 25) + item.listItem = t[24].cast(); if ((item.kind == Kind::Bar || item.kind == Kind::Scrollbar) && t.size() >= 25) { item.barStart = t[23].cast(); diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index d3cff15e..e4296957 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -1440,6 +1440,7 @@ def version(): _LIST_ROW = 20 # a list box's row, and a step of the wheel in what scrolls by pixels +_LIST_GAP = 2 # between a multi list's buttons, across and down (the original's) _DROP_ROW = 22 # a row of a pull down's open list _heights = {} # (text, width, font) -> how high it is @@ -1573,30 +1574,32 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): kind = w.kind if kind == 'multilist': bw, bh = max(1, w.defw), max(1, w.defh) + # (the original's buttons are 2 apart, across and down: 48 wide, one every 50, measured in Wine) + pw, ph = bw + _LIST_GAP, bh + _LIST_GAP row = 0 placed = [] for listId, buttons in enumerate(w.lists or []): col = 0 for index, b in enumerate(buttons): - if width and col and (col + 1) * bw > width: + if width and col and col * pw + bw > width: col, row = 0, row + 1 - placed.append((listId, index, b, col * bw, row * bh)) + placed.append((listId, index, b, col * pw, row * ph)) col += 1 if buttons: row += 1 box, top = clip, y if height: box = _clipTo(clip, (x, y, x + width, y + height)) - w.extent = row * bh + w.extent = row * ph # (a row a notch of the wheel) - _scrolls(w, x, y, x + width, y + height, s.id, max(1, bh / 3), out) + _scrolls(w, x, y, x + width, y + height, s.id, max(1, ph / 3), out) top = y - w.offset for listId, index, b, dx, dy in placed: bx, by = x + dx, top + dy if height and (by + bh <= y or by >= y + height): continue out.append((base + ((listId << 16) | index,), 'imagebutton', bx, by, bx + bw, by + bh, box, w.style, u'', b[5] if b[5] and b[5] != '-' else b[0], - '', 1, 0, False, b[5] is None and w.enabled, 0, None, b[1], b[2], b[3], b[4], w.z, w.seq, b[6])) + '', 1, 0, False, b[5] is None and w.enabled, 0, None, b[1], b[2], b[3], b[4], w.z, w.seq, b[6], True)) return if kind == 'table': # (the theme's cell height, GFC_Control_Size_ListItem; taller for a table whose cells have pictures) diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 9835d0cf..e38d5450 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -217,6 +217,7 @@ namespace oc4::render int flags = 1; // 1 left, 2 right, 4 centred (x0 is the anchor) bool state = false, enabled = true; bool pulse = false; // (a button that glows on and off: the action recommended, GFC's multi list pulse) + bool listItem = false; // (a multi list's button: in the theme's MultiList_Item skins) bool interactive = false; // takes clicks and has help bool mainInterface = false; // the main interface's: under a menu the keys do not reach it bool blocks = false; // a screen's own panel or picture over the main interface: what is under it takes no clicks diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 81d93bda..620cb8ad 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -965,6 +965,34 @@ namespace oc4::render return out; } + Theme::Bitmap Theme::glow(const Bitmap& b, Color c) + { + if (!b) + return b; + const int r = std::clamp(int(c.r * 255), 0, 255), g = std::clamp(int(c.g * 255), 0, 255), bl = std::clamp(int(c.b * 255), 0, 255); + const std::string key = lower(b.picture->path) + "|glow" + std::to_string(r) + "," + std::to_string(g) + "," + std::to_string(bl); + auto& slot = m->pictures[key]; + if (!slot) + if (const Picture* plain = m->picture(b.picture->path, nullptr, 1)) + { + slot = std::make_unique(*plain); + const int colour[3] = { bl, g, r }; // (BGRA) + for (size_t i = 0; i + 3 < slot->bgra.size(); i += 4) + { + // (its brightness the alpha: white is the colour, black nothing; premultiplied) + const int lum = std::max({ slot->bgra[i], slot->bgra[i + 1], slot->bgra[i + 2] }) * slot->bgra[i + 3] / 255; + for (int k = 0; k < 3; ++k) + slot->bgra[i + size_t(k)] = uint8_t(colour[k] * lum / 255); + slot->bgra[i + 3] = uint8_t(lum); + } + slot->key = (uint64_t(0x7E) << 56) | ++m->nextKey; + } + Bitmap out = b; + if (slot) + out.picture = slot.get(); + return out; + } + Theme::Font Theme::font(int size, bool bold, bool italic) const { static const float kSizes[] = { 10, 12, 14, 16, 22 }; // (the theme's, when it says nothing) diff --git a/src/render/Theme.h b/src/render/Theme.h index 626a5657..2815aafb 100644 --- a/src/render/Theme.h +++ b/src/render/Theme.h @@ -125,6 +125,9 @@ namespace oc4::render Bitmap addSigned(const Bitmap& bitmap, Color colour); // The bitmap multiplied by the colour (the Modulate combine): a bar's fill in its colour. Bitmap modulate(const Bitmap& bitmap, Color colour, float alpha = 1); + // The bitmap's brightness as the alpha of the colour (a glow drawn in black and white, + // laid over what is under it in a colour: the multi list's pulse). + Bitmap glow(const Bitmap& bitmap, Color colour); // Font size 1..4 (the markup's ); the theme's, else the nearest it has. Font font(int size, bool bold = false, bool italic = false) const; diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 66e4cc01..613c960b 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -62,6 +62,28 @@ namespace oc4::render for (int i = 0; i < 5; ++i) m_sizes[size_t(i)] = m_theme.font(i).size; m_tooltip = m_theme.skin("GFC_Control_StandardToolTip_Style", "GFC_CtrlTheme_Bitmap_Control_ToolTip_Skin_Inner_Default"); + m_listBorder = m_theme.skin("", "SF_CtrlTheme_Civ4_Control_MultiList_ItemBorder_Skin"); + m_listBorderGlow = m_theme.skin("", "SF_CtrlTheme_Civ4_Control_MultiList_ItemBorderGlow_Skin"); + m_listFill = m_theme.skin("", "SF_CtrlTheme_Civ4_Control_MultiList_ItemFill_Skin"); + m_listFillGlow = m_theme.skin("", "SF_CtrlTheme_Civ4_Control_MultiList_ItemFillGlow_Skin"); + const auto tinted = [&](const Theme::Skin& skin, Color c) { + Theme::Skin out = skin; + for (Theme::Layer& l : out) + l.image = m_theme.modulate(l.image, c); + return out; + }; + // (pressed: the fill in a blue half over it; pulsing: a little blue inside, the ring from a + // deep to a light blue, a blue halo round it; Wine's colours) + m_listPress = tinted(m_listFill, { 0.27f, 0.26f, 0.77f }); + // (disabled: everything inside the ring and the ring itself half way to black, as Wine draws + // a worker's farm and railroad it cannot build; not the theme's ItemDisable, a white wash) + m_listDisable = tinted(m_listFill, { 0, 0, 0 }); + m_pulseInside = tinted(m_listFill, { 0, 0.35f, 1 }); + m_pulseDeep = tinted(m_listBorder, { 0.13f, 0.45f, 1 }); + m_pulseLight = tinted(m_listBorder, { 0.01f, 0.59f, 1 }); + m_pulseHalo = m_listBorderGlow; + for (Theme::Layer& l : m_pulseHalo) + l.image = m_theme.glow(l.image, { 0, 0.31f, 1 }); constexpr std::string_view combo = "GFC_Control_StandardComboBox_Style", button = "SF_CtrlTheme_Civ4_Control_ComboBox_Standard_PopupButton_Style"; m_comboBox = { m_theme.skin(combo, "GFC_CtrlTheme_Bitmap_Control_ComboBox_Skin_ViewItem_Default"), m_theme.skin(combo, "GFC_CtrlTheme_Bitmap_Control_ComboBox_Skin_ViewItem_Rollover") }; @@ -332,6 +354,41 @@ namespace oc4::render m_helpDown = expandDown; } + void UiLayer::drawListButton(Overlay& o, const Item& it, bool hot, bool pressed, double clock) + { + // As the original draws a multi list's button (measured in Wine, BUG + BULL, 2026-11-20): its + // picture whole, the ring over its edge in the HUDBorder colour; under the mouse the fill + // glow added (+57 of 255: its inside, the ring, and a soft edge just outside); pressed, a + // blue fill half over that; disabled, half way to black (its own picture, the one + // disableMultiListButton gives). + const float x0 = it.x0, y0 = it.y0, x1 = it.x1, y1 = it.y1, a = it.alpha; + if (it.pulse) + { + // The action recommended: a blue glow that beats every 0.6 s, the ring going from a deep to + // a light blue, a blue halo just outside it and a little blue inside (Wine, 120 fps film). + const float beat = 0.5f - 0.5f * std::cos(float(clock) * 2 * std::numbers::pi_v / 0.6f); + Theme::draw(o, m_pulseInside, x0, y0, x1, y1, 0.25f * beat * a); + if (const Theme::Skin& h = m_pulseHalo; !h.empty()) + { + // (strong: at its peak the halo covers what is under it where the glow is two thirds white) + const float k = 0.75f + 0.75f * beat; + Theme::draw(o, h, x0, y0, x1, y1, std::min(k, 1.0f) * a); + if (k > 1) + Theme::draw(o, h, x0, y0, x1, y1, (k - 1) * a); + } + Theme::draw(o, m_pulseDeep, x0, y0, x1, y1, a); + Theme::draw(o, m_pulseLight, x0, y0, x1, y1, beat * a); + } + else + Theme::draw(o, m_listBorder, x0, y0, x1, y1, a); + if (!it.enabled) + Theme::draw(o, m_listDisable, x0, y0, x1, y1, 0.5f * a); + if (hot) + Theme::draw(o, m_listFillGlow, x0, y0, x1, y1, 0.224f * a); + if (pressed) + Theme::draw(o, m_listPress, x0, y0, x1, y1, 0.5f * a); + } + void UiLayer::draw(Overlay& o, const std::function& minimap, double clock, const std::function& leaderhead) { @@ -418,7 +475,9 @@ namespace oc4::render icon(it.texture, x0, y0, x1, y1, alpha); break; case Kind::ImageButton: - if (icon(it.texture, x0, y0, x1, y1, alpha)) + if (it.listItem && !m_listBorder.empty() && icon(it.texture, x0, y0, x1, y1, it.alpha)) + drawListButton(o, it, hot, hot && int(i) == m_pressed, clock); + else if (icon(it.texture, x0, y0, x1, y1, alpha)) { // (a pulsing button: what the unit is recommended to do; the original's has a blue rim // that glows round it, a little brighter and dimmer a second a beat, the picture tinted blue) diff --git a/src/render/UiLayer.h b/src/render/UiLayer.h index f9292882..65f66223 100644 --- a/src/render/UiLayer.h +++ b/src/render/UiLayer.h @@ -88,6 +88,12 @@ namespace oc4::render std::map> m_namedSkins; // panels styled "@style|property": that skin of the theme bool m_fontsRead = false; Theme::Skin m_tooltip; // the theme's (the help's box) + // A multi list's button (the unit's actions, the city's builds): the theme's MultiList_Item + // skins over its picture: its ring (HUDBorder), the glow under the mouse (added), its fill + // when pressed, darker when disabled, and the glow round a pulsing one. + Theme::Skin m_listBorder, m_listBorderGlow, m_listFill, m_listFillGlow, m_listDisable; + Theme::Skin m_listPress, m_pulseInside, m_pulseDeep, m_pulseLight, m_pulseHalo; + void drawListButton(Overlay& o, const Item& it, bool hot, bool pressed, double clock); // The theme's pull down (GFC_Control_StandardComboBox_Style): its box and its button, plain // and under the mouse; its open list's box, frame and chosen item. std::array m_comboBox, m_comboButton; From 50a48aaa3b548152e63db7e5748c8090110e3299 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 21:30:21 +0100 Subject: [PATCH 27/89] Screens: a screen's own minimap in its widgets' order; theme alpha by FactorCombine The military advisor (BUG) keeps the DEPLOYMENT tab's map and its panel when it switches to SIT-REP or STRATEGIC ADVANTAGES; in the original the tab's panel, made after them, covers both. OpenCiv4 drew a screen's own minimap over all its widgets: it is now drawn where initMinimap / bringMinimapToFront placed it among them, and left out (with its clicks) when a later panel covers it whole. The covering panel is PANEL_STYLE_MAIN, whose theme layers say FactorCombine = GColorCombine(Modulate, Source): the colour tints, the alpha is the image's own. The theme took the tint's alpha too, so the panel let the map's box and the background show through; it is opaque now, as in Wine. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4screens.py | 31 ++++++++++++++++++++++++------- src/render/Theme.cpp | 6 ++++++ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..185c0882 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -151,6 +151,7 @@ def __init__(self, name, fileId): self.helpText = u'' self.minimap = None self.mm = None # its own minimap's layers (not the main interface's): see _Minimap + self.mmSeq = 0 # its own minimap's place among its widgets (initMinimap, bringMinimapToFront) self.hideLists = {} self.endTurn = None # (text, shown) self.closeOnEscape = True @@ -1287,6 +1288,17 @@ def initMinimap(self, iLeft, iRight, iTop, iBottom, fZ): if self._s.minimap != r: self._s.minimap = r _changed() + self._placeMinimap() + + def _placeMinimap(self): + # (a screen's own minimap is drawn in its widgets' order, where it was made or brought to + # the front: a widget made after it covers it, as the military advisor's SIT-REP panel does + # in the original, which BUG never hides the DEPLOYMENT tab's map under) + s = self._s + if not s.main: + s.seq += 1 + s.mmSeq = s.seq + _changed() def _mm(self): if self._s.mm is None: @@ -1338,7 +1350,7 @@ def setMinimapMap(self, replayInfo, iLeft, iRight, iTop, iBottom, fZ): def setMinimapNoRender(self, *args): pass def setMinimapSectionOverride(self, *args): pass - def bringMinimapToFront(self): pass + def bringMinimapToFront(self): self._placeMinimap() def minimapClearAllFlashingTiles(self): mm = self._s.mm @@ -1736,6 +1748,17 @@ def display(): w = s.widgets.get(name) if w is not None: _display_widget(s, w, ox, oy, None, [ox, oy, True, 0, 0], items) + # (a screen's own minimap, the military advisor's, the replay's: among its widgets, in the + # order it was placed (_placeMinimap), from the screen's corner as they are; a panel made + # after it that covers it whole hides it and takes its clicks: BUG's SIT-REP and STRATEGIC + # ADVANTAGES tabs lay their panel over the DEPLOYMENT tab's map, which they leave) + if s.minimap is not None and not s.main and s.mm is not None: + l, t, r, b = s.minimap + l, t, r, b = l + ox, t + oy, r + ox, b + oy + if not any(i[1] == 'panel' and i[22] > s.mmSeq and i[21] <= 0.0 and i[7] not in ('', 'PANEL_STYLE_EMPTY') and + i[2] <= l and i[3] <= t and i[4] >= r and i[5] >= b for i in items): + items.append(((s.id, '__minimap', -1), 'minimap', l, t, r, b, None, '__screenmap', u'', '', '', 0, 0, False, True, 0, None, + -1, -1, -1, False, 0.0, s.mmSeq)) # farther first (GFC's z: smaller is nearer), then in the order they came items.sort(key=lambda i: (-i[21], i[22])) out.extend(items) @@ -1743,12 +1766,6 @@ def display(): if s.minimap is not None and s.main: l, t, r, b = s.minimap out.append(((s.id, '__minimap', -1), 'minimap', l, t, r, b, None, '', u'', '', '', 0, 0, False, True, 0, None, -1, -1, -1, False, 0, 0)) - # (a screen's own, over what it shows: the military advisor's, the replay's; placed from - # the screen's corner as its widgets) - elif s.minimap is not None and s.mm is not None: - l, t, r, b = s.minimap - out.append(((s.id, '__minimap', -1), 'minimap', l + ox, t + oy, r + ox, b + oy, None, '__screenmap', u'', '', '', 0, 0, False, True, 0, None, - -1, -1, -1, False, 0, 0)) _dropList(out) return out diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 81d93bda..e4b68d15 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -726,6 +726,12 @@ namespace oc4::render if (const Value* combine = resolve(s, has("FactorCombine")); combine && combine->kind == Value::Kind::Call && !combine->args.empty() && combine->args[0].text == "Modulate") tinted = colour(s, f, tint, tintAlpha); + // (FactorCombine's second part is the alpha's: "Source" keeps the image's own, the colour + // tints only; PANEL_STYLE_MAIN's, opaque as in the original, so the military advisor's + // SIT-REP panel hides what is under it) + if (const Value* combine = resolve(s, has("FactorCombine")); + tinted && combine && combine->args.size() > 1 && combine->args[1].text == "Source") + tintAlpha = 1; if (const Value* v = has("Image")) l.image = bitmap(s, v, tinted ? &tint : nullptr, tintAlpha); if (const Value* v = has("Center")) From ccf09609da643ae4e8239352166819d0ed239ce8 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 21:54:47 +0100 Subject: [PATCH 28/89] The main interface's help in the theme's see-through HUD help panel The original draws a help area with no art of its own (CvMainInterface's setHelpTextArea(350, ..., "", ..., 300)) in PANEL_STYLE_HUD_HELP: help_panel.tga tinted HelpBG (69,93,156) at 35 %, the map seen through it, a dark line and a faint blue one at its top and bottom, the text 4 in from its sides, wrapped at the area's minimum width (300). The city screen's area has art (POPUPS_BACKGROUND_TRANSPARENT) and keeps the framed tooltip. The plot's help sits in the same box. Measured in Wine (BUG + BULL, 1600x900): out = 0.65 map + (8,13,19), as the panel gives. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 12 ++++-- apps/oc4core/python/oc4screens.py | 7 ++-- src/render/MapWindow.cpp | 4 +- src/render/MapWindow.h | 2 +- src/render/UiLayer.cpp | 64 ++++++++++++++++++------------- src/render/UiLayer.h | 13 +++++-- 6 files changed, 61 insertions(+), 41 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..a46ef750 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -1103,8 +1103,8 @@ if _walls: { m_hovered = hovered; const std::string text = hovered >= 0 && size_t(hovered) < m_items.size() ? help(m_items[size_t(hovered)]) : std::string(); - float x = 7, y = float(height) - 172, w = 350; - bool right = true, down = false; + float x = 7, y = float(height) - 172, w = 300; + bool right = true, down = false, framed = false; try { if (py::object area = py::module_::import("oc4screens").attr("helpArea")(); !area.is_none()) @@ -1112,16 +1112,20 @@ if _walls: auto t = area.cast(); x = t[0].cast(); y = t[1].cast(); - w = t[2].cast(); + // (the original wraps at the minimum width when there is one: the main + // interface's 300 of 350) + const float minWidth = t[3].cast(); + w = minWidth > 0 ? minWidth : t[2].cast(); right = t[4].cast(); down = t[5].cast(); + framed = t.size() > 6 && t[6].cast(); } } catch (py::error_already_set& e) { printPythonError(e); } - window.setUiHelp(text, x, y, w, right, down); + window.setUiHelp(text, x, y, w, right, down, framed); } } diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..fcce18b6 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -147,7 +147,7 @@ def __init__(self, name, fileId): self.shown = False self.main = False self.dims = None - self.helpArea = None # (x, y, width, minWidth, expandRight, expandDown) + self.helpArea = None # (x, y, width, minWidth, expandRight, expandDown, framed) self.helpText = u'' self.minimap = None self.mm = None # its own minimap's layers (not the main interface's): see _Minimap @@ -946,7 +946,8 @@ def hideEndTurn(self, szName): _set(w, 'shown', False) def setHelpTextArea(self, fWidth, eFont, fX, fY, fZ, bFloating, szArtFile, bExpandRight, bExpandDown, uiFlags, iMinWidth): - self._s.helpArea = (int(fX), int(fY), int(fWidth), int(iMinWidth), bool(bExpandRight), bool(bExpandDown)) + # (with art, the city screen's, it is framed; without, the main interface's, see-through) + self._s.helpArea = (int(fX), int(fY), int(fWidth), int(iMinWidth), bool(bExpandRight), bool(bExpandDown), bool(szArtFile)) def setHelpTextString(self, szString): self._s.helpText = _text(szString) @@ -1972,7 +1973,7 @@ def rowClicked(fileId, name, part, shift, ctrl): def helpArea(): - """(x, y, width, min width, expand right, expand down) of the main interface's help, or None.""" + """(x, y, width, min width, expand right, expand down, framed) of the main interface's help, or None.""" for s in _screens.values(): if s.main and s.helpArea is not None: return s.helpArea diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..cd0eb9e0 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -2640,9 +2640,9 @@ namespace oc4::render return std::format("camera at {:.1f},{:.1f} (height {:.0f}), {:.1f} plots away, pitch {:.2f}", m->camera.target.x / p, m->camera.target.y / p, m->camera.target.z, m->camera.distance / p, m->camera.pitch); } - void MapWindow::setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown) + void MapWindow::setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed) { - m->ui.setHelp(text, x, y, width, expandRight, expandDown); + m->ui.setHelp(text, x, y, width, expandRight, expandDown, framed); } void MapWindow::pressKeys(const std::string& keys) { diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..9c48f056 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -351,7 +351,7 @@ namespace oc4::render // Where the mouse is, in window pixels ((-1, -1) before it came in). std::pair mousePosition() const; // The help for what is under the mouse, in the screens' help area. - void setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown); + void setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false); // The text shown when the mouse rests on a plot (lines; the game's plot help). void setPlotHelp(std::function help); diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..c7ec4b5a 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -62,6 +62,8 @@ namespace oc4::render for (int i = 0; i < 5; ++i) m_sizes[size_t(i)] = m_theme.font(i).size; m_tooltip = m_theme.skin("GFC_Control_StandardToolTip_Style", "GFC_CtrlTheme_Bitmap_Control_ToolTip_Skin_Inner_Default"); + if (const Theme::Panel* p = m_theme.panel("PANEL_STYLE_HUD_HELP")) + m_hudHelp = p->inner; constexpr std::string_view combo = "GFC_Control_StandardComboBox_Style", button = "SF_CtrlTheme_Civ4_Control_ComboBox_Standard_PopupButton_Style"; m_comboBox = { m_theme.skin(combo, "GFC_CtrlTheme_Bitmap_Control_ComboBox_Skin_ViewItem_Default"), m_theme.skin(combo, "GFC_CtrlTheme_Bitmap_Control_ComboBox_Skin_ViewItem_Rollover") }; @@ -263,10 +265,38 @@ namespace oc4::render void UiLayer::drawPlotHelp(Overlay& o, const std::wstring& text) { - const float w = m_helpWidth, h = o.richHeight(text, w - 10, m_sizes[2], false); - const float x = (m_helpRight ? m_helpX : m_helpX - w) + 5; - const float y = std::clamp(m_helpDown ? m_helpY : m_helpY - h - 4, 0.0f, std::max(o.screenHeight() - h, 0.0f)); - o.richBlock(text, x, y, w - 10, m_sizes[2], false, kText); + drawHelp(o, text); + } + + void UiLayer::drawHelp(Overlay& o, const std::wstring& text) + { + // The main interface's: the theme's HUD help panel (help_panel.tga in HelpBG, 35 %), the + // map seen through it, the text 4 in from its sides (as in the original: BUG + BULL in + // Wine); the city screen's, framed: the theme's tooltip. + const bool see = !m_helpFramed && !m_hudHelp.empty(); + const float inX = see ? 4.0f : 10.0f, inY = 5; + const float sw = o.screenWidth(), sh = o.screenHeight(); + // A help taller than the room it grows into gets wider, then is kept on the screen. + const float room = std::max(m_helpDown ? sh - m_helpY : m_helpY, 100.0f); + const float widest = std::max(m_helpRight ? sw - m_helpX : m_helpX, m_helpWidth); + float w = m_helpWidth, h = o.richHeight(text, w - 2 * inX, m_sizes[2], false) + 2 * inY; + while (h > room && w < widest) + { + w = std::min(w * 1.5f, widest); + h = o.richHeight(text, w - 2 * inX, m_sizes[2], false) + 2 * inY; + } + const float x = m_helpRight ? m_helpX : m_helpX - w; + const float y = std::clamp(m_helpDown ? m_helpY : m_helpY - h, 0.0f, std::max(sh - h, 0.0f)); + if (see) + Theme::draw(o, m_hudHelp, x, y, x + w, y + h); + else if (!m_tooltip.empty()) + Theme::draw(o, m_tooltip, x, y, x + w, y + h); + else + { + o.rect(x, y, x + w, y + h, kPanel, 0.93f, 5); + o.frame(x, y, x + w, y + h, kEdge, 0.6f, 5, 1); + } + o.richBlock(text, x + inX, y + inY, w - 2 * inX, m_sizes[2], false, kText); } const Theme::Panel* UiLayer::themedPanel(const Item& it) const @@ -322,8 +352,9 @@ namespace oc4::render return MapWindow::UiClick{ pressed, m_pressedRight, shift, ctrl, alt }; } - void UiLayer::setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown) + void UiLayer::setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed) { + m_helpFramed = framed; m_help = widen(text); m_helpX = x; m_helpY = y; @@ -679,27 +710,6 @@ namespace oc4::render o.frame(x0 - 2, it.y0 - 2, x1 + 2, it.y1 + 2, kHot, 1, 3, 2); } if (!m_help.empty()) - { - // A help taller than the room it grows into gets wider, then is kept on the screen. - const float room = std::max(m_helpDown ? sh - m_helpY : m_helpY, 100.0f); - const float widest = std::max(m_helpRight ? sw - m_helpX : m_helpX, m_helpWidth); - float w = m_helpWidth, h = o.richHeight(m_help, w - 20, m_sizes[2], false) + 10; - while (h > room && w < widest) - { - w = std::min(w * 1.5f, widest); - h = o.richHeight(m_help, w - 20, m_sizes[2], false) + 10; - } - const float x = m_helpRight ? m_helpX : m_helpX - w; - const float y = std::clamp(m_helpDown ? m_helpY : m_helpY - h, 0.0f, std::max(sh - h, 0.0f)); - // (in the theme's tooltip) - if (!m_tooltip.empty()) - Theme::draw(o, m_tooltip, x, y, x + w, y + h); - else - { - o.rect(x, y, x + w, y + h, kPanel, 0.93f, 5); - o.frame(x, y, x + w, y + h, kEdge, 0.6f, 5, 1); - } - o.richBlock(m_help, x + 10, y + 5, w - 20, m_sizes[2], false, kText); - } + drawHelp(o, m_help); } } diff --git a/src/render/UiLayer.h b/src/render/UiLayer.h index f9292882..f00bca73 100644 --- a/src/render/UiLayer.h +++ b/src/render/UiLayer.h @@ -58,10 +58,12 @@ namespace oc4::render void press(int x, int y, bool right); std::optional release(int x, int y, bool shift, bool ctrl, bool alt); - void setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown); + // framed: the help area has art of its own (the city screen's), in the theme's tooltip; + // else the main interface's see-through box (PANEL_STYLE_HUD_HELP). + void setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false); // The size of a widget's font (FontTypes) as the screens draw it. float textSize(int font) const { return fontSize(font); } - // The plot's help where the screens show theirs, over the map without a box (the game's look). + // The plot's help where the screens show theirs, in the same box (the game's look). void drawPlotHelp(Overlay& overlay, const std::wstring& text); // minimap(x0, y0, x1, y1, screen) draws the map's minimap there (screen: a screen's own, the // military advisor's); leaderhead(item) a leader's head @@ -87,7 +89,8 @@ namespace oc4::render Theme& m_theme; std::map> m_namedSkins; // panels styled "@style|property": that skin of the theme bool m_fontsRead = false; - Theme::Skin m_tooltip; // the theme's (the help's box) + Theme::Skin m_tooltip; // the theme's (the framed help's box) + Theme::Skin m_hudHelp; // the main interface's help box (PANEL_STYLE_HUD_HELP: see-through) // The theme's pull down (GFC_Control_StandardComboBox_Style): its box and its button, plain // and under the mouse; its open list's box, frame and chosen item. std::array m_comboBox, m_comboButton; @@ -107,6 +110,8 @@ namespace oc4::render bool m_pressedRight = false; std::wstring m_help; float m_helpX = 0, m_helpY = 0, m_helpWidth = 350; - bool m_helpRight = true, m_helpDown = false; + bool m_helpRight = true, m_helpDown = false, m_helpFramed = false; + // A help in the help area: its box, then its text. + void drawHelp(Overlay& o, const std::wstring& text); }; } From b6da36daf463672c4a6dd2af3b2ecf242a5d8109 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 22:44:53 +0100 Subject: [PATCH 29/89] Tables and list boxes: the theme's row skins, row heights and background Rows of addTableControlGFC / addListBoxGFC are drawn as the original's GTable: the theme's .Row skins (Civ4Theme_Table.thm, Civ4Theme_Custom.thm) under each row's cells - every other row Alt_ (selection.tga in AltCell), the row under the mouse Rollover where the style has one (BUG's Table_StandardCiv_Style: gold), a selected one Select - as wide as the table's columns, and the table's Inner skin (table_innerTB.tga in BG; none with Flag_NoInnerFill) under them. A row is the style's Size_CellHeight (GFC_Control_Size_ListItem, 24) or taller for a line of its text and the style's Size_CellContentMargin: a list box's text is in the normal font (size 3), so BUG's military advisor's unit list has 25 px rows as in the original; a table's text stays size 2 (24 px, the domestic advisor's). TableStyles map to the theme's table styles, and a list box keeps the style it is given. Theme::table() reads it; themedump prints it; theme_table_test checks it. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 6 + apps/oc4core/Screens.cpp | 10 +- apps/oc4core/Screens.h | 1 + apps/oc4core/main.cpp | 2 + apps/oc4core/python/oc4screens.py | 57 ++++++-- src/render/MapWindow.cpp | 6 + src/render/MapWindow.h | 6 +- src/render/Theme.cpp | 34 +++++ src/render/Theme.h | 16 +++ src/render/UiLayer.cpp | 43 +++++- tests/theme_table_test.cpp | 214 ++++++++++++++++++++++++++++++ tools/themedump/main.cpp | 12 ++ 12 files changed, 392 insertions(+), 15 deletions(-) create mode 100644 tests/theme_table_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index aa66b460..7eb9ae92 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -402,6 +402,12 @@ target_link_libraries(theme_combine_test PRIVATE oc4_options oc4_render) add_test(NAME theme_combine COMMAND theme_combine_test) set_target_properties(theme_combine_test PROPERTIES FOLDER "tests") +add_executable(theme_table_test tests/theme_table_test.cpp) +target_include_directories(theme_table_test PRIVATE src) +target_link_libraries(theme_table_test PRIVATE oc4_options oc4_render) +add_test(NAME theme_table COMMAND theme_table_test) +set_target_properties(theme_table_test PROPERTIES FOLDER "tests") + if(WIN32 AND TARGET freetype) add_executable(text_layout_freetype_test tests/text_layout_test.cpp src/render/TextLayout.cpp src/render/FontFreeType.cpp) target_include_directories(text_layout_freetype_test PRIVATE src) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..49215710 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -127,6 +127,7 @@ namespace oc4::host std::function g_textWidth; // how wide a text is in the window render::MapWindow::UiDisplay g_display; // the window's, for the scale's choices std::function g_textHeight; // how high it is, wrapped at a width + std::function(const std::string&)> g_tableRow; // a table style's row: least height, room above and below // (before the window is up: its markup left out, a symbol about two letters wide) int estimatedWidth(const std::wstring& text) @@ -531,6 +532,12 @@ namespace oc4::host return g_textHeight ? g_textHeight(gameMarkup(toWide(text).c_str()), width, font) : (int(toWide(text).size()) * 7 / std::max(1, width) + 1) * 16; }); + // a table style's row, as the theme has it: (least height, room above, room below its content) + host.def("ui_table_row", [](const std::string& style) { + const std::array r = g_tableRow ? g_tableRow(style) : std::array{ 24, 2, 2 }; + return py::make_tuple(r[0], r[1], r[2]); + }); + // the plot list (the main interface's row size for the DLL's clicks on it) host.def("ui_plot_list_offset", [&ui] { return ui.getPlotListOffset(); }); host.def("ui_plot_list_column", [&ui] { return ui.getPlotListColumn(); }); @@ -706,6 +713,7 @@ if _walls: void Screens::setTextWidth(std::function width) { g_textWidth = std::move(width); } void Screens::setTextHeight(std::function height) { g_textHeight = std::move(height); } + void Screens::setTableRow(std::function(const std::string&)> row) { g_tableRow = std::move(row); } bool Screens::start(int width, int height) { @@ -1156,7 +1164,7 @@ if _walls: { "bar", Kind::Bar }, { "line", Kind::Line }, { "header", Kind::Header }, { "cell", Kind::Cell }, { "dropdown", Kind::Dropdown }, { "endturn", Kind::EndTurnText }, { "endbutton", Kind::EndTurnButton }, { "minimap", Kind::Minimap }, { "graphic", Kind::Graphic }, { "separator", Kind::Separator }, { "edit", Kind::Edit }, { "slider", Kind::Slider }, { "option", Kind::Cell }, { "flag", Kind::Flag }, { "scrollbar", Kind::Scrollbar }, - { "leaderhead", Kind::Leaderhead }, { "model", Kind::Model }, { "movie", Kind::Movie } }; + { "leaderhead", Kind::Leaderhead }, { "model", Kind::Model }, { "movie", Kind::Movie }, { "row", Kind::Row } }; std::vector items; m_items.clear(); if (const char* dump = std::getenv("OC4_UI_DUMP")) diff --git a/apps/oc4core/Screens.h b/apps/oc4core/Screens.h index 5f64207c..a040f608 100644 --- a/apps/oc4core/Screens.h +++ b/apps/oc4core/Screens.h @@ -75,6 +75,7 @@ namespace oc4::host static void setTextWidth(std::function width); // How high a text is when it wraps at a width, in a widget's font (FontTypes). static void setTextHeight(std::function height); + static void setTableRow(std::function(const std::string& style)> row); // The main interface up; false if the scripts failed (the host keeps its own then). bool start(int width, int height); bool active() const { return m_active; } diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..c39625d3 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -660,6 +660,7 @@ namespace }; host::Screens::setTextWidth([&window](const std::string& markup, int font) { return window.textWidth(markup, font); }); host::Screens::setTextHeight([&window](const std::string& markup, int width, int font) { return window.textHeight(markup, width, font); }); + host::Screens::setTableRow([&window](const std::string& style) { return window.tableRow(style); }); window.setUiWheel([&screens](int x, int y, int delta) { return screens.wheel(x, y, delta); }); struct ForgetWheel { @@ -1740,6 +1741,7 @@ namespace host::Screens screens(utility); host::Screens::setTextWidth([&window](const std::string& markup, int font) { return window.textWidth(markup, font); }); host::Screens::setTextHeight([&window](const std::string& markup, int width, int font) { return window.textHeight(markup, width, font); }); + host::Screens::setTableRow([&window](const std::string& style) { return window.tableRow(style); }); window.setUiWheel([&screens](int x, int y, int delta) { return screens.wheel(x, y, delta); }); std::vector> saveFolders; if (const fs::path documents = documentsFolder(); !documents.empty()) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..25bf8169 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -1167,10 +1167,12 @@ def isRowSelected(self, szName, iRow): def addListBoxGFC(self, szName, helpText, iX, iY, iWidth, iHeight, eStyle=0): w = self._s.add(szName, 'listbox') w.help, w.x, w.y, w.w, w.h, w.items = _text(helpText), int(iX), int(iY), int(iWidth), int(iHeight), [] + w.pstyle = _style(_cpe.TableStyles, eStyle) def attachListBoxGFC(self, szAttachTo, szName, helpText, eStyle=0): w = self._s.add(szName, 'listbox', szAttachTo, 'flow') w.help, w.items = _text(helpText), [] + w.pstyle = _style(_cpe.TableStyles, eStyle) def appendListBoxString(self, szAttachTo, item, eType=-1, iData1=-1, iData2=-1, iJustify=_FONT_LEFT): w = self._s.get(szAttachTo) @@ -1428,9 +1430,33 @@ def version(): return _version[0] -_LIST_ROW = 20 # a list box's row, and a step of the wheel in what scrolls by pixels +_LIST_ROW = 20 # a step of the wheel in what scrolls by pixels _DROP_ROW = 22 # a row of a pull down's open list _heights = {} # (text, width, font) -> how high it is +_tableRows = {} # a table style -> (least row height, room above, room below a cell's content), the theme's + + +def _rowHeight(style, size, least=0): + """A table's or list box's row: the style's cell height (GFC_Control_Size_ListItem, 24), or + taller for a line of its text (font size: a table's 2, a list box's 3) and the room the style + leaves above and below it (Size_CellContentMargin: BUG's Table_StandardCiv_Style 1 and 2, its + military advisor's list 25 high), or for its pictures.""" + row = _tableRows.get(style) + if row is None: + try: + row = tuple(oc4host.ui_table_row(style)) + except Exception: + row = (24, 2, 2) + _tableRows[style] = row + line = _textHeight(u'Ag' % size, 4096) + return int(max(row[0], least, line + row[1] + row[2])) + + +def _tableInner(base, x, y, width, height, clip, style, w, out): + """A table's or list box's own background under its rows (the theme's Inner skin: the standard + table's blue gradient; none for the Empty styles).""" + out.append((base + (-199,), 'row', x, y, x + width, y + height, clip, style, u'', '', '', 0, 2, False, True, 0, None, -1, -1, -1, False, + w.z, w.seq)) def _origin(s): @@ -1590,9 +1616,11 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): if kind == 'table': # (the theme's cell height, GFC_Control_Size_ListItem; taller for a table whose cells have pictures) pictures = [1 for row in w.rows for cell in row.values() if cell and cell[1]] - rowHeight = max(24, w.iconh) if pictures else 24 + style = w.style or w.pstyle + rowHeight = _rowHeight(style, 2, w.iconh if pictures else 0) # (its rows scroll under its headers, in its box) box = _clipTo(clip, (x, y, x + width, y + height)) if height else clip + _tableInner(base, x, y, width, height or (len(w.rows) + (1 if w.headers else 0)) * rowHeight, box, style, w, out) top = y if w.headers: cx = x @@ -1610,17 +1638,21 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): if w.sort is not None and w.sort[0] >= 0: column = w.sort[0] order.sort(key=lambda ri: _sortKey(w.rows[ri].get(column)), reverse=w.sort[1]) - for ri in order: + for at, ri in enumerate(order): r = w.rows[ri] if height and (cy + rowHeight <= top or cy >= y + height): cy += rowHeight continue + # (the row's look under its cells: every other one the theme's Alt_, selected; as wide + # as its columns, as in the original: BUG's domestic advisor's rows end with its last) + out.append((base + (-200 - ri,), 'row', x, cy, x + (sum(c[1] for c in w.columns) or width), cy + rowHeight, body, style, u'', '', '', 0, at & 1, ri in w.picked, True, 0, None, + -1, -1, -1, False, w.z, w.seq)) cx = x for ci, c in enumerate(w.columns): cell = r.get(ci) if cell is not None: flags = _FONT_RIGHT if c[2] else cell[5] - out.append((base + ((ri << 8) | ci,), 'cell', cx, cy, cx + c[1], cy + rowHeight, body, w.style, cell[0], cell[1], '', 2, flags, + out.append((base + ((ri << 8) | ci,), 'cell', cx, cy, cx + c[1], cy + rowHeight, body, style, cell[0], cell[1], '', 2, flags, ri in w.picked, True, 0, None, cell[2], cell[3], cell[4], len(cell) > 6 and cell[6], w.z, w.seq)) # (a control attached to the cell: there, scrolling with its row) control = s.widgets.get(w.cells.get((ri, ci))) if w.cells else None @@ -1632,14 +1664,21 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): if kind == 'listbox': box = _clipTo(clip, (x, y, x + width, y + height)) if height else clip items = w.items or [] - w.extent = len(items) * _LIST_ROW - _scrolls(w, x, y, x + width, y + height if height else y + w.extent, s.id, _LIST_ROW, out) + # (a list box's text is in the theme's normal font, size 3: a row of BUG's military + # advisor's list is 25 high, a table's text size 2) + style = w.style or w.pstyle + rowHeight = _rowHeight(style, 3) + w.extent = len(items) * rowHeight + _tableInner(base, x, y, width, height or w.extent, box, style, w, out) + _scrolls(w, x, y, x + width, y + height if height else y + w.extent, s.id, rowHeight, out) cy = y - w.offset for i, item in enumerate(items): - if not height or (cy + _LIST_ROW > y and cy < y + height): - out.append((base + (i,), 'cell', x, cy, x + width, cy + _LIST_ROW, box, w.style, item[0], '', '', 2, item[4], w.selected == i, True, 0, None, + if not height or (cy + rowHeight > y and cy < y + height): + out.append((base + (-200 - i,), 'row', x, cy, x + width, cy + rowHeight, box, style, u'', '', '', 0, i & 1, w.selected == i, True, 0, None, + -1, -1, -1, False, w.z, w.seq)) + out.append((base + (i,), 'cell', x, cy, x + width, cy + rowHeight, box, style, item[0], '', '', 3, item[4], w.selected == i, True, 0, None, item[1], item[2], item[3], False, w.z, w.seq)) - cy += _LIST_ROW + cy += rowHeight return if kind == 'multiline' and w.mode != 'flow' and width > 0 and height > 0: # (in a box of its own: clipped there, and it scrolls when it is longer) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..8cd32371 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -2633,6 +2633,12 @@ namespace oc4::render { return int(std::ceil(m->overlay->richHeight(widen(markup), float(std::max(20, width)), m->ui.textSize(font), font == 0 || font == 4))); } + std::array MapWindow::tableRow(const std::string& style) const + { + if (const Theme::Table* t = m->theme.loaded() ? m->theme.table(style) : nullptr) + return { t->cellHeight, t->content[1], t->content[3] }; + return { 24, 2, 2 }; + } std::pair MapWindow::mousePosition() const { return { m->mouseX, m->mouseY }; } std::string MapWindow::cameraText() const { diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..db59881c 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -204,7 +204,8 @@ namespace oc4::render enum class Kind : uint8_t { Panel, Image, ImageButton, Button, CheckBox, Label, Text, Multiline, Bar, Line, Header, Cell, Dropdown, EndTurnText, - EndTurnButton, Minimap, Graphic, Separator, Edit, Slider, Flag, Scrollbar, Leaderhead, Model, Movie + EndTurnButton, Minimap, Graphic, Separator, Edit, Slider, Flag, Scrollbar, Leaderhead, Model, Movie, + Row // a table's or list box's row, under its cells (flags 1: an Alt_ one; state: selected; flags 2: the table's background) }; Kind kind = Kind::Panel; float x0 = 0, y0 = 0, x1 = 0, y1 = 0; @@ -342,6 +343,9 @@ namespace oc4::render // How high a text with the screens' markup is when it wraps at a width, in a widget's // font (FontTypes), as the screens draw their multi-line texts. int textHeight(const std::string& markup, int width, int font) const; + // A table style's row (the theme's): its least height, and the room above and below a + // cell's content. + std::array tableRow(const std::string& style) const; // The interactive item under the mouse, -1 none. int uiHovered() const; // As if the mouse rested on that item (a scripted game's look at its help). diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 81d93bda..4620dee8 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -262,6 +262,10 @@ namespace oc4::render { "BUTTON_STYLE_CITY_B03BC", "Button_CityBtn10_Style" }, { "BUTTON_STYLE_CITY_B03BR", "Button_CityBtn11_Style" }, { "BUTTON_STYLE_CITY_PLUS", "Button_Plus_Style" }, { "BUTTON_STYLE_CITY_MINUS", "Button_Minus_Style" }, { "BUTTON_STYLE_ARROW_LEFT", "Button_CityArrowL_Style" }, { "BUTTON_STYLE_ARROW_RIGHT", "Button_CityArrowR_Style" }, + // (TableStyles, by their names: Civ4Theme_Custom.thm's custom tables) + { "TABLE_STYLE_STANDARD", "GFC_Control_StandardTable_Style" }, { "TABLE_STYLE_EMPTY", "Table_Empty_Style" }, + { "TABLE_STYLE_ALTEMPTY", "Table_AltEmpty_Style" }, { "TABLE_STYLE_CITY", "Table_City_Style" }, + { "TABLE_STYLE_EMPTYSELECTINACTIVE", "Table_EmptySelectInactive_Style" }, { "TABLE_STYLE_ALTDEFAULT", "Table_AltStandard_Style" }, }; return m; } @@ -287,6 +291,7 @@ namespace oc4::render std::map, std::less<>> panels; // (null: the theme has none) std::map, std::less<>> buttons; std::map, std::less<>> progresses; + std::map, std::less<>> tables; std::vector problems; std::set told; bool loaded = false; @@ -925,6 +930,35 @@ namespace oc4::render return (m->progresses[key] = std::move(p)).get(); } + const Theme::Table* Theme::table(std::string_view style) + { + if (const auto it = m->tables.find(style); it != m->tables.end()) + return it->second.get(); + std::unique_ptr t; + const Style* s = m->loaded ? m->styleFor(style) : nullptr; + if (!s && m->loaded) + s = m->findStyle("GFC_Control_StandardTable_Style"); + if (s) + { + // (Civ4Theme_Table.thm: the standard table's rows are blank, every other one + // selection.tga in AltCell, a selected one in Select; Table_StandardCiv_Style adds the + // Rollover gold; GFC_Control_Size_ListItem, 24, is the cell's height) + t = std::make_unique
(); + static const char* const kRow[] = { "Default", "Rollover", "Select", "SelectRollover" }; + for (size_t alt = 0; alt < 2; ++alt) + for (size_t i = 0; i < Table::RowCount; ++i) + t->row[alt][i] = m->skin(s, m->property(s, std::string("GFC_CtrlTheme_Bitmap_Control_Table_Skin_Row_") + (alt ? "Alt_" : "") + kRow[i])); + if (const Value* v = m->resolve(s, m->property(s, "GFC_Control_Table_Size_CellHeight")); v && v->kind == Value::Kind::Number && v->number > 0) + t->cellHeight = float(v->number); + m->margins(s, m->property(s, "GFC_Control_Table_Size_CellContentMargin"), t->content); + // (the standard table's: table_innerTB.tga in the theme's BG; a GFlags(...) NoInnerFill none) + const Value* noFill = m->resolve(s, m->property(s, "GFC_Control_Table_Flag_NoInnerFill")); + if (!noFill || noFill->kind != Value::Kind::Call) + t->inner = m->skin(s, m->property(s, "GFC_CtrlTheme_Bitmap_Control_Table_Skin_Inner_Default")); + } + return (m->tables[std::string(style)] = std::move(t)).get(); + } + Theme::Bitmap Theme::modulate(const Bitmap& b, Color c, float alpha) { if (!b) diff --git a/src/render/Theme.h b/src/render/Theme.h index 626a5657..1fb181f9 100644 --- a/src/render/Theme.h +++ b/src/render/Theme.h @@ -119,6 +119,22 @@ namespace oc4::render Skin rim; // over it all (HBorder) }; const Progress* progress(std::string_view style); + // A table's or list box's look (GFC_Control_Table): its rows' skins, every other row the + // Alt_ one, under the mouse and selected; how high a row is at least, and the room + // round a cell's content (style: a table style; the standard table when the theme has + // none such). + struct Table + { + enum Row : uint8_t + { + Default, Rollover, Select, SelectRollover, RowCount + }; + std::array, 2> row; // [alt][state] + Skin inner; // its background (none with Flag_NoInnerFill: the Empty styles) + float cellHeight = 24; + float content[4]{ 4, 2, 4, 2 }; // left, top, right, bottom + }; + const Table* table(std::string_view style); // The bitmap with the colour added, less half (the AddSigned combine): how the end of turn // button's glass takes its red or green. diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..1c7611a9 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -562,15 +562,50 @@ namespace oc4::render o.richText(text, x0 + 8, y0 + (h - o.richHeight(text, 4096, m_sizes[2], false)) / 2, m_sizes[2], false, it.state ? kHot : kText, alpha); break; } - if (it.state || hot) - o.rect(x0, y0, x1, y1, { 0.25f, 0.3f, 0.42f }, it.state ? 0.7f : 0.4f, 0); + // (its row under it has the look: alternate, under the mouse, selected) float tx = x0 + 4; if (!it.texture.empty() && icon(it.texture, x0 + 2, y0 + 1, x0 + h - 1, y1 - 1, alpha)) tx = x0 + h + 2; const bool right = (it.flags & 2) != 0, centre = (it.flags & 4) != 0; const std::wstring text = widen(it.text); - o.richText(text, right ? x1 - 4 : centre ? (x0 + x1) / 2 : tx, y0 + (h - o.richHeight(text, 4096, m_sizes[2], false)) / 2, m_sizes[2], false, - kText, alpha, right ? Overlay::Align::Right : centre ? Overlay::Align::Center : Overlay::Align::Left); + // (in its font, size 2 a table's, 3 a list box's; in the middle of the room the style + // leaves round a cell's content) + const float size = m_sizes[size_t(std::clamp(it.font, 0, 4))]; + float above = 0, below = 0; + if (const Theme::Table* t = m_theme.loaded() ? m_theme.table(it.style) : nullptr) + above = t->content[1], below = t->content[3]; + const float ty = y0 + above + (h - above - below - o.richHeight(text, 4096, size, false)) / 2; + o.richText(text, right ? x1 - 4 : centre ? (x0 + x1) / 2 : tx, ty, size, false, kText, alpha, + right ? Overlay::Align::Right : centre ? Overlay::Align::Center : Overlay::Align::Left); + break; + } + case Kind::Row: + { + // A table's or list box's row: the theme's skin for it (Civ4Theme_Table.thm's .Row): + // every other one Alt_, under the mouse Rollover (the whole row, whichever of its + // cells is), selected Select. + if (it.flags & 2) + { + // (the table's own background, under its rows: the theme's inner skin) + if (const Theme::Table* t = m_theme.loaded() ? m_theme.table(it.style) : nullptr) + Theme::draw(o, t->inner, x0, y0, x1, y1, alpha); + break; + } + bool over = inside(it, m_mouseX, m_mouseY); + for (size_t j = i + 1; over && j < m_items.size(); ++j) + if (const Item& above = m_items[j]; (above.interactive || above.blocks) && inside(above, m_mouseX, m_mouseY)) + { + over = above.kind == Kind::Cell && above.y0 == y0 && above.y1 == y1 && above.x0 >= x0 && above.x1 <= x1; + break; + } + const bool alt = (it.flags & 1) != 0; + if (const Theme::Table* t = m_theme.loaded() ? m_theme.table(it.style) : nullptr) + { + using R = Theme::Table::Row; + Theme::draw(o, t->row[alt][it.state ? (over ? R::SelectRollover : R::Select) : over ? R::Rollover : R::Default], x0, y0, x1, y1, alpha); + } + else if (it.state || over) + o.rect(x0, y0, x1, y1, { 0.25f, 0.3f, 0.42f }, it.state ? 0.7f : 0.4f, 0); break; } case Kind::Line: diff --git a/tests/theme_table_test.cpp b/tests/theme_table_test.cpp new file mode 100644 index 00000000..68ec5dda --- /dev/null +++ b/tests/theme_table_test.cpp @@ -0,0 +1,214 @@ +// Checks a table's look as the theme gives it (Theme::table): the rows' skins as +// Civ4Theme_Table.thm and Civ4Theme_Custom.thm lay them out (the standard table's rows blank, +// every other one selection.tga tinted AltCell, a selected one tinted Select; a custom style +// mapped to it adding a rollover and its own room round a cell's content), the cell height +// through GFC_Control_Size_ListItem, and the standard table for a style the theme has not. + +#include "render/Theme.h" + +#include +#include +#include +#include + +using namespace oc4::render; +namespace fs = std::filesystem; + +namespace +{ + int failures = 0; + + void check(bool ok, const char* what) + { + if (!ok) + { + std::printf("FAILED: %s\n", what); + ++failures; + } + } + + // A 2 x 2 opaque white 32-bit TGA (selection.tga is white: the tint is the colour). + void writeTga(const fs::path& file) + { + std::vector d(18, 0); + d[2] = 2, d[12] = 2, d[14] = 2, d[16] = 32, d[17] = 0x28; + for (int i = 0; i < 4; ++i) + d.insert(d.end(), { 255, 255, 255, 255 }); + std::ofstream(file, std::ios::binary).write(reinterpret_cast(d.data()), std::streamsize(d.size())); + } + + // The first pixel of a skin's single layer (BGRA, premultiplied), or null. + const unsigned char* pixel(const Theme::Skin& skin) + { + return skin.size() == 1 && skin[0].image ? &skin[0].image.picture->bgra[0] : nullptr; + } +} + +int main() +{ + const fs::path dir = fs::current_path() / "theme_table_test"; + fs::remove_all(dir); + fs::create_directories(dir / "Assets"); + fs::create_directories(dir / "Resource"); + writeTga(dir / "Resource/selection.tga"); + std::ofstream(dir / "Resource/Civ4.thm") << R"( +with GFC_Control +{ + with .Size + { + .ListItem = 24; + } +} +skin SF_CtrlTheme_Civ4_Control_Skin_Blank +{ + layer + { + } +} +with GFC_Control_Table +{ + GFC_Control_StandardTable_Style + { + with .Size + { + .CellContentMargin = GRectMargin(4,2,4,2); + .CellHeight = GFC_Control_Size_ListItem; + } + with .Flag + { + .NoInnerFill = 0; + } + with GFC_CtrlTheme_Bitmap_Control_Table_Skin + { + with .Inner + { + .Default + { + layer { + LayerFlags = GFlags(GCtrlBitmapSkin, GFC_BITMAPSKIN_CENTER_SCALE); + DestCombine = GColorCombine(BlendSource,Disable); + Image = GBitmap("selection.tga", HVGrid, 1, 1, 0, 0); + Margin = GRectMargin(0,0,0,0); + } + } + } + with .Row + { + .Default = SF_CtrlTheme_Civ4_Control_Skin_Blank; + .Rollover = .Default; + .Select + { + layer { + LayerFlags = GFlags(GCtrlBitmapSkin, GFC_BITMAPSKIN_CENTER_BILINEAR); + DestCombine = GColorCombine(BlendSource,Disable); + FactorCombine = GColorCombine(Modulate,Modulate); + FactorColor = GColor(128,168,255,89); + Image = GBitmap("selection.tga", HVGrid, 1, 1, 0, 0); + Margin = GRectMargin(0,0,0,0); + } + } + .Alt_Default + { + layer { + LayerFlags = GFlags(GCtrlBitmapSkin, GFC_BITMAPSKIN_CENTER_BILINEAR); + DestCombine = GColorCombine(BlendSource,Disable); + FactorCombine = GColorCombine(Modulate,Modulate); + FactorColor = GColor(199,178,153,32); + Image = GBitmap("selection.tga", HVGrid, 1, 1, 0, 0); + Margin = GRectMargin(0,0,0,0); + } + } + .Alt_Rollover = .Alt_Default; + } + } + } + + style SF_CtrlTheme_Civ4_Control_Table_StandardCiv_Style + { + .Size_CellContentMargin = GRectMargin(4,1,4,2); + with GFC_CtrlTheme_Bitmap_Control_Table_Skin + { + with .Row + { + .Rollover + { + layer { + LayerFlags = GFlags(GCtrlBitmapSkin, GFC_BITMAPSKIN_CENTER_BILINEAR); + DestCombine = GColorCombine(BlendSource,Disable); + FactorCombine = GColorCombine(Modulate,Modulate); + FactorColor = GColor(255,229,121,64); + Image = GBitmap("selection.tga", HVGrid, 1, 1, 0, 0); + Margin = GRectMargin(0,0,0,0); + } + } + .Alt_Rollover = .Rollover; + } + } + map GFC_CtrlTheme_Bitmap_Control_Table = GFC_Control_StandardTable_Style; + map GFC_Control = GFC_Control_StandardTable_Style; + } + + style SF_CtrlTheme_Civ4_Control_Table_Empty_Style + { + .Flag_NoInnerFill = GFlags(GTableCtrl, GFC_CF_TABLE_NOINNERFILL); + map GFC_CtrlTheme_Bitmap_Control_Table = GFC_Control_StandardTable_Style; + map GFC_Control = GFC_Control_StandardTable_Style; + } + + style SF_CtrlTheme_Civ4_Control_Table_MainMenu_Style + { + .Size_CellHeight = 32; + map GFC_CtrlTheme_Bitmap_Control_Table = GFC_Control_StandardTable_Style; + map GFC_Control = GFC_Control_StandardTable_Style; + } +} +)"; + + using R = Theme::Table::Row; + Theme theme; + check(theme.load({ dir / "Assets" }), "theme loads"); + for (const std::string& p : theme.problems()) + std::printf(" theme problem: %s\n", p.c_str()); + + const Theme::Table* standard = theme.table("TABLE_STYLE_STANDARD"); + check(standard != nullptr, "the standard table (TABLE_STYLE_STANDARD)"); + if (standard) + { + check(standard->cellHeight == 24, "cell height GFC_Control_Size_ListItem"); + check(standard->content[1] == 2 && standard->content[3] == 2, "content margin 2 above and below"); + check(standard->row[0][R::Default].empty(), "a row is blank"); + check(standard->row[0][R::Rollover].empty(), "no rollover in the standard table"); + const unsigned char* alt = pixel(standard->row[1][R::Default]); + check(alt && alt[3] == 32 && alt[2] == 199 * 32 / 255, "every other row selection.tga in AltCell (premultiplied)"); + check(pixel(standard->row[1][R::Rollover]) != nullptr, "an alt row under the mouse keeps its look"); + const unsigned char* select = pixel(standard->row[0][R::Select]); + check(select && select[3] == 89 && select[0] == 255 * 89 / 255, "a selected row selection.tga in Select"); + check(standard->inner.size() == 1, "the standard table's background"); + } + const Theme::Table* empty = theme.table("TABLE_STYLE_EMPTY"); + check(empty && empty->inner.empty(), "no background with Flag_NoInnerFill (TABLE_STYLE_EMPTY)"); + + const Theme::Table* civ = theme.table("Table_StandardCiv_Style"); + check(civ != nullptr && civ != standard, "BUG's Table_StandardCiv_Style"); + if (civ) + { + check(civ->cellHeight == 24, "its cell height the standard table's"); + check(civ->content[1] == 1 && civ->content[3] == 2, "its own content margin (1 above, 2 below)"); + const unsigned char* over = pixel(civ->row[0][R::Rollover]); + check(over && over[3] == 64, "a row under the mouse selection.tga in Rollover"); + const unsigned char* altOver = pixel(civ->row[1][R::Rollover]); + check(altOver && altOver[3] == 64, "an alt row under the mouse too (Alt_Rollover = .Rollover)"); + check(pixel(civ->row[1][R::Default]) != nullptr, "its alt rows the standard table's"); + } + + const Theme::Table* menu = theme.table("Table_MainMenu_Style"); + check(menu && menu->cellHeight == 32, "a style's own cell height"); + + const Theme::Table* unknown = theme.table("NoSuchTable_Style"); + check(unknown && unknown->cellHeight == 24 && pixel(unknown->row[1][R::Default]) != nullptr, "an unknown style: the standard table"); + + fs::remove_all(dir); + if (failures == 0) + std::printf("theme_table: all checks passed\n"); + return failures == 0 ? 0 : 1; +} diff --git a/tools/themedump/main.cpp b/tools/themedump/main.cpp index afca3777..b383181f 100644 --- a/tools/themedump/main.cpp +++ b/tools/themedump/main.cpp @@ -83,6 +83,18 @@ int main(int argc, char** argv) int(b->image[i].x1), int(b->image[i].y1)); } } + if (n.find("able") != std::string::npos && n.find('/') == std::string::npos) + if (const Theme::Table* t = theme.table(n)) + { + // (a table style: its row's least height, the room round a cell's content, its rows) + std::printf("%s: table, cell height %g, content margin %g,%g,%g,%g\n", n.c_str(), t->cellHeight, t->content[0], t->content[1], t->content[2], + t->content[3]); + printSkin("inner", t->inner); + static const char* kRows[] = { "row", "row rollover", "row select", "row select rollover" }; + for (size_t alt = 0; alt < 2; ++alt) + for (size_t i = 0; i < Theme::Table::RowCount; ++i) + printSkin((std::string(alt ? "alt " : "") + kRows[i]).c_str(), t->row[alt][i]); + } if (const size_t at = n.find('/'); at != std::string::npos) { // "style/property": that skin (an empty style: the theme's own skin of that name) From 8fa44a345ebc450908569964dc6e3809a9e6e081 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 23:04:50 +0100 Subject: [PATCH 30/89] Screens: tell the scripts when the mouse goes onto a widget and off it NOTIFY_CURSOR_MOVE_ON/_OFF, as the original's widgets send them: the civics screen shows the civic under the mouse in its column's help (the religion screen and BUG's unit list use them too). Known by screen, name and part, so a script that redraws on it hears it once. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 30 ++++++++++++++++++++++++++++++ apps/oc4core/Screens.h | 2 ++ 2 files changed, 32 insertions(+) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..79ab6dbd 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -1275,6 +1275,7 @@ if _walls: if (!m_active) return; m_mouse = window.mousePosition(); + moveOnOff(window); // A movie at its end: its screen hears NOTIFY_MOVIE_DONE. constexpr int kMovieDone = 17; // Keys typed into an edit box, and whether one takes them. @@ -1314,6 +1315,35 @@ if _walls: } } + void Screens::moveOnOff(render::MapWindow& window) + { + // The mouse onto a widget and off it: its script hears NOTIFY_CURSOR_MOVE_ON and _OFF, as + // the original's widgets tell it (the civics screen shows the civic under the mouse in its + // column's help, the religion screen and BUG's unit list theirs). The widget is known by + // its screen, name and part: a script that redraws on it (new widgets, the same name) hears + // it once. Only the game's screens (not the host's menu, options, turn log or talks). + constexpr int kMoveOn = 4, kMoveOff = 5; + const int hovered = m_menu ? -1 : window.uiHovered(); + std::optional now; + if (hovered >= 0 && size_t(hovered) < m_items.size()) + { + const Item& it = m_items[size_t(hovered)]; + if (it.screen != kDiplomacyScreen && it.screen != kOptionsScreen && it.screen != kTurnLogScreen && !it.name.empty() && + !it.name.starts_with("OC4") && it.kind != "option" && it.kind != "header" && it.kind != "scrollbar") + now = it; + } + const auto same = [](const Item& a, const Item& b) { return a.screen == b.screen && a.name == b.name && a.part == b.part; }; + if (now ? m_movedOn && same(*m_movedOn, *now) : !m_movedOn) + return; + const std::optional before = std::exchange(m_movedOn, now); + if (before) + // (to the widget as it is now, if it is still there) + if (const auto it = std::ranges::find_if(m_items, [&](const Item& i) { return same(i, *before); }); it != m_items.end()) + scriptInput(Item(*it), kMoveOff, it->part < 0 ? 0 : (it->part & 0xFFFF), 0, false, false, false, false); + if (now) + scriptInput(*now, kMoveOn, now->part < 0 ? 0 : (now->part & 0xFFFF), 0, false, false, false, false); + } + bool Screens::click(const std::string& name, int part, bool shift, bool ctrl, bool alt) { for (const Item& it : m_items) diff --git a/apps/oc4core/Screens.h b/apps/oc4core/Screens.h index 5f64207c..16b00740 100644 --- a/apps/oc4core/Screens.h +++ b/apps/oc4core/Screens.h @@ -123,6 +123,7 @@ namespace oc4::host }; void rebuild(render::MapWindow& window); void click(const Item& item, bool right, bool shift, bool ctrl, bool alt); + void moveOnOff(render::MapWindow& window); // NOTIFY_CURSOR_MOVE_ON/_OFF as the mouse goes onto a widget and off it // The script's handleInput for the item (a NotifyCode, its data). void scriptInput(const Item& item, int notify, int data, int column, bool right, bool shift, bool ctrl, bool alt); std::string help(const Item& item) const; @@ -136,6 +137,7 @@ namespace oc4::host std::chrono::steady_clock::time_point m_sizeChanged; std::vector m_items; int m_hovered = -1; + std::optional m_movedOn; // the widget the scripts were told the mouse is on std::pair m_mouse{ -1, -1 }; // where the mouse was at the clicks taken unsigned m_diploVersion = 0; // the talk the diplomacy screen shows std::vector> m_talkAnswers; // the player's answers in it, last frame From b44baa0f5414ad337f85204ec7bd09b30d21a73f Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 23:11:45 +0100 Subject: [PATCH 31/89] Domestic Advisor: BUG's saved pages load; table headers in the theme's look BUG's customizable Domestic Advisor keeps its pages in UserSettings/CustomDomAdv/CustomDomAdv.txt, a pickle with CRLF line ends, read with open(name, 'r'). Windows' text mode drops the CRs; macOS's doesn't, pickle.load failed ("insecure string pickle") and BUG fell back to its built-in pages (Executive Summary, ...) instead of City Overview and the other 18. Off Windows, the host's Python now reads 'r'/'rt' with universal newlines ('rU'), as Windows reads them. A table's column headers are drawn as the original's: the theme's header button (the table style's StyleId_HHeader -> the header's StyleId_HButton, Civ4Theme_Table.thm's Header_Table_HButtonStyle: bg_header.tga parchment with header_h.tga's edges between the columns), Size_Header high (22; it was a row's 24), the text dark brown in the middle (Wine's 65,40,38) and lighter under the mouse. ui_table_row gives the header height as a fourth value. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/PythonHost.cpp | 20 +++++++++++++++++++ apps/oc4core/Screens.cpp | 10 +++++----- apps/oc4core/Screens.h | 2 +- apps/oc4core/python/oc4screens.py | 32 +++++++++++++++++++++---------- src/render/MapWindow.cpp | 6 +++--- src/render/MapWindow.h | 2 +- src/render/Theme.cpp | 9 +++++++++ src/render/Theme.h | 5 +++++ src/render/UiLayer.cpp | 20 +++++++++++++++++-- 9 files changed, 84 insertions(+), 22 deletions(-) diff --git a/apps/oc4core/PythonHost.cpp b/apps/oc4core/PythonHost.cpp index 91a1bff3..ecb823b5 100644 --- a/apps/oc4core/PythonHost.cpp +++ b/apps/oc4core/PythonHost.cpp @@ -95,6 +95,22 @@ if not hasattr(sys, 'argv'): sys.argv = [''] )py"; +#ifndef _WIN32 + // Windows reads a file opened in text mode ('r') with its CRLF line ends as LF. + // Mods ship such files and rely on it: BUG's Domestic Advisor pickles its pages + // into UserSettings/CustomDomAdv/CustomDomAdv.txt with CRLF ends, and pickle.load + // fails on the '\r' elsewhere, so BUG fell back to its built-in pages. + constexpr const char* kTextModeOpen = R"py( +import __builtin__ +def _oc4_text_open(name, mode='r', buffering=-1, _open=__builtin__.open): + if mode in ('r', 'rt'): + mode = 'rU' + return _open(name, mode, buffering) +__builtin__.open = _oc4_text_open +del _oc4_text_open +)py"; +#endif + template bool toList(PyObject* o, std::vector& out, Convert convert) { @@ -209,6 +225,10 @@ if not hasattr(sys, 'argv'): PyRun_SimpleString("import sys, os\nsys.stdout = sys.__stdout__ = os.fdopen(1, 'w', 0)\nsys.stderr = sys.__stderr__ = os.fdopen(2, 'w', 0)\n"); if (PyRun_SimpleString(kImporter) != 0) throw std::runtime_error("failed to install the asset importer"); +#ifndef _WIN32 + if (PyRun_SimpleString(kTextModeOpen) != 0) + throw std::runtime_error("failed to install the text-mode open"); +#endif // The DLL publishes its classes into CvPythonExtensions. PyImport_AddModule("CvPythonExtensions"); diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 49215710..dc990982 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -127,7 +127,7 @@ namespace oc4::host std::function g_textWidth; // how wide a text is in the window render::MapWindow::UiDisplay g_display; // the window's, for the scale's choices std::function g_textHeight; // how high it is, wrapped at a width - std::function(const std::string&)> g_tableRow; // a table style's row: least height, room above and below + std::function(const std::string&)> g_tableRow; // a table style's row: least height, room above and below; its headers' height // (before the window is up: its markup left out, a symbol about two letters wide) int estimatedWidth(const std::wstring& text) @@ -532,10 +532,10 @@ namespace oc4::host return g_textHeight ? g_textHeight(gameMarkup(toWide(text).c_str()), width, font) : (int(toWide(text).size()) * 7 / std::max(1, width) + 1) * 16; }); - // a table style's row, as the theme has it: (least height, room above, room below its content) + // a table style's row, as the theme has it: (least height, room above, room below its content, its headers' height) host.def("ui_table_row", [](const std::string& style) { - const std::array r = g_tableRow ? g_tableRow(style) : std::array{ 24, 2, 2 }; - return py::make_tuple(r[0], r[1], r[2]); + const std::array r = g_tableRow ? g_tableRow(style) : std::array{ 24, 2, 2, 22 }; + return py::make_tuple(r[0], r[1], r[2], r[3]); }); // the plot list (the main interface's row size for the DLL's clicks on it) @@ -713,7 +713,7 @@ if _walls: void Screens::setTextWidth(std::function width) { g_textWidth = std::move(width); } void Screens::setTextHeight(std::function height) { g_textHeight = std::move(height); } - void Screens::setTableRow(std::function(const std::string&)> row) { g_tableRow = std::move(row); } + void Screens::setTableRow(std::function(const std::string&)> row) { g_tableRow = std::move(row); } bool Screens::start(int width, int height) { diff --git a/apps/oc4core/Screens.h b/apps/oc4core/Screens.h index a040f608..d15f7532 100644 --- a/apps/oc4core/Screens.h +++ b/apps/oc4core/Screens.h @@ -75,7 +75,7 @@ namespace oc4::host static void setTextWidth(std::function width); // How high a text is when it wraps at a width, in a widget's font (FontTypes). static void setTextHeight(std::function height); - static void setTableRow(std::function(const std::string& style)> row); + static void setTableRow(std::function(const std::string& style)> row); // The main interface up; false if the scripts failed (the host keeps its own then). bool start(int width, int height); bool active() const { return m_active; } diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 25bf8169..9c3edfc8 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -1433,21 +1433,32 @@ def version(): _LIST_ROW = 20 # a step of the wheel in what scrolls by pixels _DROP_ROW = 22 # a row of a pull down's open list _heights = {} # (text, width, font) -> how high it is -_tableRows = {} # a table style -> (least row height, room above, room below a cell's content), the theme's +_tableRows = {} # a table style -> (least row height, room above, room below a cell's content, header height), the theme's -def _rowHeight(style, size, least=0): - """A table's or list box's row: the style's cell height (GFC_Control_Size_ListItem, 24), or - taller for a line of its text (font size: a table's 2, a list box's 3) and the room the style - leaves above and below it (Size_CellContentMargin: BUG's Table_StandardCiv_Style 1 and 2, its - military advisor's list 25 high), or for its pictures.""" +def _tableRow(style): row = _tableRows.get(style) if row is None: try: row = tuple(oc4host.ui_table_row(style)) except Exception: - row = (24, 2, 2) + row = (24, 2, 2, 22) _tableRows[style] = row + return row + + +def _headerHeight(style, rowHeight): + """A table's header row: the theme's Size_Header (22), a row's height if the theme has none.""" + row = _tableRow(style) + return int(row[3]) if len(row) > 3 and row[3] > 0 else rowHeight + + +def _rowHeight(style, size, least=0): + """A table's or list box's row: the style's cell height (GFC_Control_Size_ListItem, 24), or + taller for a line of its text (font size: a table's 2, a list box's 3) and the room the style + leaves above and below it (Size_CellContentMargin: BUG's Table_StandardCiv_Style 1 and 2, its + military advisor's list 25 high), or for its pictures.""" + row = _tableRow(style) line = _textHeight(u'Ag' % size, 4096) return int(max(row[0], least, line + row[1] + row[2])) @@ -1620,16 +1631,17 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): rowHeight = _rowHeight(style, 2, w.iconh if pictures else 0) # (its rows scroll under its headers, in its box) box = _clipTo(clip, (x, y, x + width, y + height)) if height else clip - _tableInner(base, x, y, width, height or (len(w.rows) + (1 if w.headers else 0)) * rowHeight, box, style, w, out) + headerHeight = _headerHeight(style, rowHeight) if w.headers else 0 + _tableInner(base, x, y, width, height or len(w.rows) * rowHeight + headerHeight, box, style, w, out) top = y if w.headers: cx = x for ci, c in enumerate(w.columns): # (a table that sorts: each header a part of its own, -100 - column, that a click sorts by) - out.append((base + (-100 - ci if w.sort is not None else -1,), 'header', cx, top, cx + c[1], top + rowHeight, box, w.style, c[0], '', '', 2, _FONT_RIGHT if c[2] else _FONT_LEFT, + out.append((base + (-100 - ci if w.sort is not None else -1,), 'header', cx, top, cx + c[1], top + headerHeight, box, style, c[0], '', '', 2, _FONT_RIGHT if c[2] else _FONT_LEFT, False, True, 0, None, -1, -1, -1, False, w.z, w.seq)) cx += c[1] - top += rowHeight + top += headerHeight body = _clipTo(box, (x, top, x + width, y + height)) if height else box w.extent = len(w.rows) * rowHeight _scrolls(w, x, top, x + width, y + height if height else top + w.extent, s.id, rowHeight, out) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index 8cd32371..514858e8 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -2633,11 +2633,11 @@ namespace oc4::render { return int(std::ceil(m->overlay->richHeight(widen(markup), float(std::max(20, width)), m->ui.textSize(font), font == 0 || font == 4))); } - std::array MapWindow::tableRow(const std::string& style) const + std::array MapWindow::tableRow(const std::string& style) const { if (const Theme::Table* t = m->theme.loaded() ? m->theme.table(style) : nullptr) - return { t->cellHeight, t->content[1], t->content[3] }; - return { 24, 2, 2 }; + return { t->cellHeight, t->content[1], t->content[3], t->headerHeight }; + return { 24, 2, 2, 22 }; } std::pair MapWindow::mousePosition() const { return { m->mouseX, m->mouseY }; } std::string MapWindow::cameraText() const diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index db59881c..29359ac5 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -345,7 +345,7 @@ namespace oc4::render int textHeight(const std::string& markup, int width, int font) const; // A table style's row (the theme's): its least height, and the room above and below a // cell's content. - std::array tableRow(const std::string& style) const; + std::array tableRow(const std::string& style) const; // The interactive item under the mouse, -1 none. int uiHovered() const; // As if the mouse rested on that item (a scripted game's look at its help). diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 4620dee8..47f91b1a 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -950,6 +950,15 @@ namespace oc4::render t->row[alt][i] = m->skin(s, m->property(s, std::string("GFC_CtrlTheme_Bitmap_Control_Table_Skin_Row_") + (alt ? "Alt_" : "") + kRow[i])); if (const Value* v = m->resolve(s, m->property(s, "GFC_Control_Table_Size_CellHeight")); v && v->kind == Value::Kind::Number && v->number > 0) t->cellHeight = float(v->number); + if (const Value* v = m->resolve(s, m->property(s, "GFC_Control_Table_Size_Header")); + v && v->kind == Value::Kind::Call && v->args.size() >= 2 && v->args[1].kind == Value::Kind::Number && v->args[1].number > 0) + t->headerHeight = float(v->args[1].number); + if (const Value* h = m->resolve(s, m->property(s, "GFC_Control_Table_StyleId_HHeader")); + h && h->kind == Value::Kind::Call && h->text == "GPropertyId" && !h->args.empty()) + if (const Style* hs = m->findStyle(h->args[0].text)) + if (const Value* b = m->resolve(hs, m->property(hs, "GFC_Control_Header_StyleId_HButton")); + b && b->kind == Value::Kind::Call && b->text == "GPropertyId" && !b->args.empty()) + t->header = button(b->args[0].text); m->margins(s, m->property(s, "GFC_Control_Table_Size_CellContentMargin"), t->content); // (the standard table's: table_innerTB.tga in the theme's BG; a GFlags(...) NoInnerFill none) const Value* noFill = m->resolve(s, m->property(s, "GFC_Control_Table_Flag_NoInnerFill")); diff --git a/src/render/Theme.h b/src/render/Theme.h index 1fb181f9..f5086290 100644 --- a/src/render/Theme.h +++ b/src/render/Theme.h @@ -131,6 +131,11 @@ namespace oc4::render }; std::array, 2> row; // [alt][state] Skin inner; // its background (none with Flag_NoInnerFill: the Empty styles) + // Its headers: the header table's (StyleId_HHeader) button (StyleId_HButton): the + // standard one's bg_header.tga and header_h.tga, a light band with dark text; and + // how high they are (Size_Header, 22). + const Button* header = nullptr; + float headerHeight = 22; float cellHeight = 24; float content[4]{ 4, 2, 4, 2 }; // left, top, right, bottom }; diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 1c7611a9..46f4bffb 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -27,6 +27,8 @@ namespace oc4::render } constexpr Color kPanel{ 0.05f, 0.06f, 0.09f }, kEdge{ 0.78f, 0.64f, 0.36f }, kText{ 0.93f, 0.93f, 0.9f }, kHot{ 1, 0.9f, 0.6f }; + // (a table header's text: the original's, dark brown on the parchment) + constexpr Color kHeaderText{ 65 / 255.f, 40 / 255.f, 38 / 255.f }; // The built-in panel styles that draw nothing (PANEL_STYLE_EMPTY, PANEL_STYLE_EXTERNAL). bool emptyPanel(const std::string& style) @@ -541,10 +543,24 @@ namespace oc4::render break; } case Kind::Header: - o.rect(x0, y0, x1, y1, { 0.1f, 0.11f, 0.15f }, 0.9f, 0); - o.richText(widen(it.text), (it.flags & 2) ? x1 - 4 : x0 + 4, y0 + 2, m_sizes[1], true, { 1, 0.9f, 0.65f }, 1, + { + // A table's column header: the theme's header button (Civ4Theme_Table.thm's + // Header_Table_HButtonStyle: the parchment of bg_header.tga, header_h.tga's edges + // between the columns), its text in the button's colours, in the middle of its height. + const Theme::Table* t = m_theme.loaded() ? m_theme.table(it.style) : nullptr; + const Theme::Button* b = t ? t->header : nullptr; + const std::wstring text = widen(it.text); + const size_t state = hot ? size_t(Theme::State::Rollover) : size_t(Theme::State::Default); + if (b && !b->skin[state].empty()) + Theme::draw(o, b->skin[state], x0, y0, x1, y1, alpha); + else + o.rect(x0, y0, x1, y1, { 0.1f, 0.11f, 0.15f }, 0.9f, 0); + const Color colour = b && b->coloured ? b->text[state] : b ? kHeaderText : Color{ 1, 0.9f, 0.65f }; + const float ty = y0 + (h - o.richHeight(text, 4096, m_sizes[2], false)) / 2; + o.richText(text, (it.flags & 2) ? x1 - 4 : x0 + 4, ty, m_sizes[2], false, colour, alpha, (it.flags & 2) ? Overlay::Align::Right : Overlay::Align::Left); break; + } case Kind::Cell: { if (it.style == "__option") From 06f19abff8bff08204aaa7517880d18276e5cb7e Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 23:38:27 +0100 Subject: [PATCH 32/89] Screens: a screen's help beside its widget; labels don't light up under the mouse A screen widget's help (not the main interface's, which has its help area) is drawn in the theme's tooltip beside the widget, as the original does: its top at the widget's, its right edge at the widget's left (on its right when there is no room), wrapped at 220 and as wide as its widest line. Measured in Wine on BUG's Finance Advisor at 1600x900. Before, it went to the main interface's help area in the bottom left corner. A label (CyGInterfaceScreen.setLabel) keeps its colour under the mouse, as in the original; only a text (setText) lights up. Co-Authored-By: Claude Opus 5.5 --- src/render/UiLayer.cpp | 40 ++++++++++++++++++++++++++++++++++++++-- src/render/UiLayer.h | 2 ++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..ad8fb22c 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -500,7 +500,9 @@ namespace oc4::render case Kind::Text: // (a text, CyGInterfaceScreen.setText, is in the theme's normal font, size 3, whatever // font it names; a label in the one it names) - label(y0, it.kind == Kind::Text ? m_sizes[3] : fontSize(it.font), fontBold(it.font), it.interactive && hot ? kHot : kText); + // (only a text lights up under the mouse; a label keeps its colour, its help aside) + label(y0, it.kind == Kind::Text ? m_sizes[3] : fontSize(it.font), fontBold(it.font), + it.kind == Kind::Text && it.interactive && hot ? kHot : kText); break; case Kind::EndTurnText: if (!it.text.empty()) @@ -678,7 +680,41 @@ namespace oc4::render const float x0 = std::min(it.x0, it.x1), x1 = std::max(it.x0, it.x1); o.frame(x0 - 2, it.y0 - 2, x1 + 2, it.y1 + 2, kHot, 1, 3, 2); } - if (!m_help.empty()) + if (!m_help.empty() && m_hover >= 0 && size_t(m_hover) < m_items.size() && !m_items[size_t(m_hover)].mainInterface) + { + // A screen's widget (not the main interface's, which has its help area): the help in the + // theme's tooltip beside it, as the original: its top at the widget's, its right edge at + // the widget's left (on its right when there is no room), wrapped at 220 and as wide as + // its widest line (measured in Wine, BUG's Finance Advisor at 1600x900). + const Item& it = m_items[size_t(m_hover)]; + constexpr float kWrap = 220, kPad = 10; + const float size = m_sizes[2]; + if (m_besideFor != m_help) + { + m_besideFor = m_help; + const float lines = o.richHeight(m_help, kWrap, size, false); + float lo = 20, hi = kWrap; // (the narrowest width that wraps no more than kWrap does) + while (hi - lo > 1) + { + const float mid = (lo + hi) / 2; + (o.richHeight(m_help, mid, size, false) > lines ? lo : hi) = mid; + } + m_besideWidth = hi; + } + const float w = m_besideWidth + 2 * kPad, h = o.richHeight(m_help, m_besideWidth, size, false) + 10; + const float left = std::min(it.x0, it.x1), right = std::max(it.x0, it.x1); + const float x = left - w >= 0 ? left - w : std::min(right, std::max(sw - w, 0.0f)); + const float y = std::clamp(it.y0, 0.0f, std::max(sh - h, 0.0f)); + if (!m_tooltip.empty()) + Theme::draw(o, m_tooltip, x, y, x + w, y + h); + else + { + o.rect(x, y, x + w, y + h, kPanel, 0.93f, 5); + o.frame(x, y, x + w, y + h, kEdge, 0.6f, 5, 1); + } + o.richBlock(m_help, x + kPad, y + 5, m_besideWidth, size, false, kText); + } + else if (!m_help.empty()) { // A help taller than the room it grows into gets wider, then is kept on the screen. const float room = std::max(m_helpDown ? sh - m_helpY : m_helpY, 100.0f); diff --git a/src/render/UiLayer.h b/src/render/UiLayer.h index f9292882..ab57c499 100644 --- a/src/render/UiLayer.h +++ b/src/render/UiLayer.h @@ -108,5 +108,7 @@ namespace oc4::render std::wstring m_help; float m_helpX = 0, m_helpY = 0, m_helpWidth = 350; bool m_helpRight = true, m_helpDown = false; + std::wstring m_besideFor; // (the help m_besideWidth was measured for) + float m_besideWidth = 0; }; } From 98e2053f5e1c4a4b194bfaa9a8ab78d9525718dc Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 23:40:23 +0100 Subject: [PATCH 33/89] Screens: a screen widget's help as wide as its widest line, wrapped greedily The box's width is the widest of the lines wrapped word by word at 220, as Wine's (the narrowest width with as many lines made them too even). Co-Authored-By: Claude Opus 5.5 --- src/render/UiLayer.cpp | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index ad8fb22c..9737d3b7 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -692,14 +692,31 @@ namespace oc4::render if (m_besideFor != m_help) { m_besideFor = m_help; - const float lines = o.richHeight(m_help, kWrap, size, false); - float lo = 20, hi = kWrap; // (the narrowest width that wraps no more than kWrap does) - while (hi - lo > 1) + // (its lines wrapped word by word at kWrap; the widest of them) + float widest = 0; + size_t start = 0; + while (start <= m_help.size()) { - const float mid = (lo + hi) / 2; - (o.richHeight(m_help, mid, size, false) > lines ? lo : hi) = mid; + const size_t end = std::min(m_help.find(L'\n', start), m_help.size()); + std::wstring line; + size_t word = start; + while (word < end) + { + const size_t space = std::min(m_help.find(L' ', word), end); + const std::wstring next = (line.empty() ? L"" : line + L" ") + m_help.substr(word, space - word); + if (!line.empty() && o.richWidth(next, size, false) > kWrap) + { + widest = std::max(widest, o.richWidth(line, size, false)); + line = m_help.substr(word, space - word); + } + else + line = next; + word = space + 1; + } + widest = std::max(widest, o.richWidth(line, size, false)); + start = end + 1; } - m_besideWidth = hi; + m_besideWidth = std::clamp(std::ceil(widest) + 1, 20.0f, kWrap); } const float w = m_besideWidth + 2 * kPad, h = o.richHeight(m_help, m_besideWidth, size, false) + 10; const float left = std::min(it.x0, it.x1), right = std::max(it.x0, it.x1); From 3f34951b4b27cab790b7ec3b3c875f9b21ae73a5 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 23:42:04 +0100 Subject: [PATCH 34/89] Screens: the top messages over the main interface, under the game's screens The original draws an open screen (an advisor, the Civilopedia) over the messages under the top bar; OpenCiv4 drew them over everything, across the screen's title. They are now drawn by UiLayer::draw just before the first widget that is not the main interface's (after all of them when no screen is open, under the main interface's help as before). Co-Authored-By: Claude Opus 5.5 --- src/render/MapWindow.cpp | 6 ++++-- src/render/UiLayer.cpp | 11 ++++++++++- src/render/UiLayer.h | 3 ++- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..7284f0e9 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -1505,7 +1505,9 @@ namespace oc4::render else drawMinimap(x0, y0, x1, y1, false); }, clock, - [&](const UiItem& it) { return drawHead(it); }); + [&](const UiItem& it) { return drawHead(it); }, + // (the top messages: over the main interface, under the game's screens, as the original) + [&] { drawMessages(); }); } else { @@ -1522,8 +1524,8 @@ namespace oc4::render drawMinimap(sw - 12 - mw, sh - 12 - mw, sw - 12, sh - 12, true); drawInfo(); drawActions(); + drawMessages(); } - drawMessages(); if (!popup.active()) drawPlotHelp(); popup.draw(*overlay, busy ? std::function{} : popupHelp); diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 9737d3b7..8a9e4be6 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -333,9 +333,10 @@ namespace oc4::render } void UiLayer::draw(Overlay& o, const std::function& minimap, double clock, - const std::function& leaderhead) + const std::function& leaderhead, const std::function& underScreens) { const float sw = o.screenWidth(), sh = o.screenHeight(); + bool screensReached = false; const Item* map = nullptr; for (const Item& it : m_items) if (it.kind == Kind::Minimap) @@ -343,6 +344,12 @@ namespace oc4::render for (size_t i = 0; i < m_items.size(); ++i) { Item& it = m_items[i]; + if (!screensReached && !it.mainInterface) + { + screensReached = true; + if (underScreens) + underScreens(); + } const bool hot = int(i) == m_hover && it.enabled; const float x0 = it.x0, y0 = it.y0, x1 = it.x1, y1 = it.y1, w = x1 - x0, h = y1 - y0; const float alpha = it.alpha * (it.enabled ? 1.0f : 0.45f); @@ -671,6 +678,8 @@ namespace oc4::render if (it.clipped) o.unclip(); } + if (!screensReached && underScreens) + underScreens(); // (no screen: over the main interface, under its help) // The help for what is under the mouse, in the help area (growing up from it unless it // expands down). // (what the keyboard chose: the mouse's highlight alone is too faint to follow) diff --git a/src/render/UiLayer.h b/src/render/UiLayer.h index ab57c499..b7e0e0be 100644 --- a/src/render/UiLayer.h +++ b/src/render/UiLayer.h @@ -67,7 +67,8 @@ namespace oc4::render // military advisor's); leaderhead(item) a leader's head // (false: it has none, its button shows). void draw(Overlay& overlay, const std::function& minimap, double clock, - const std::function& leaderhead = {}); + const std::function& leaderhead = {}, + const std::function& underScreens = {}); // (drawn over the main interface, under the screens) private: using Item = MapWindow::UiItem; From a5f072a1a870b2d0499df03f4de37def733769cd Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 23:43:26 +0100 Subject: [PATCH 35/89] UiLayer: civic buttons as the original: the highlight alone, no frames A checkbox picture with its own highlight (the civics screen's BUTTON_HILITE_SQUARE) shows that highlight when on and nothing else, not under the mouse either; a screen's picture button (the civics screen's big civic buttons) gets no gold frame under the mouse. Measured in Wine (BUG + BULL): no hovered look on either. Co-Authored-By: Claude Opus 5.5 --- src/render/UiLayer.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..7d35a00f 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -420,7 +420,9 @@ namespace oc4::render case Kind::ImageButton: if (icon(it.texture, x0, y0, x1, y1, alpha)) { - if (hot) + // (a screen's picture button has no look of its own under the mouse in the + // original: the civics screen's big civic buttons; the main interface's keep theirs) + if (hot && it.mainInterface) o.frame(x0, y0, x1, y1, kHot, 1, 3, 2); } else if (!themedButton(o, it, int(i), hot, it.state) && w > 0) @@ -480,8 +482,14 @@ namespace oc4::render case Kind::CheckBox: if (icon(it.texture, x0, y0, x1, y1, alpha)) { - if (it.state && !it.texture2.empty()) - icon(it.texture2, x0, y0, x1, y1, alpha); + // (a picture with its own highlight, as the civics screen's: that highlight says + // it is on, and nothing more is drawn, under the mouse either, as the original) + if (!it.texture2.empty()) + { + if (it.state) + icon(it.texture2, x0, y0, x1, y1, alpha); + break; + } } else if (themedButton(o, it, int(i), hot, it.state)) break; // (its toggled look says it is on) From 12864defaef101ee5be48385b165b2bd1f474e4b Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 00:07:36 +0100 Subject: [PATCH 36/89] Tables as the original's GTable: sort arrows, the lit first row, cells cut with dots Measured in Wine with BUG's Domestic Advisor and its page editor: - The column a table is sorted by shows the theme's arrow (the header's HSortAscend/DescendButton image, table_sort_arrows.tga) at its right, its text left of it and cut with dots ("P.. ^" over POP). The first click sorts up, the next down. - A table one selects rows of (enableSelect) shows its first row with the selected look while no row is selected: the advisor opens with its first city lit, though isRowSelected says none is; so do the page editor's two tables. - A cell's text is cut with "..." where its column ends (GREATPEOPLE_TUR..., COULD_CONSCRIPT...); it ran into the next column. - getTableText gives the cell's text without its markup (BUG's red "-1" is "-1"). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4screens.py | 25 +++++++++++++---- src/render/Theme.cpp | 8 ++++++ src/render/Theme.h | 3 +++ src/render/UiLayer.cpp | 45 +++++++++++++++++++++++++++++-- 4 files changed, 74 insertions(+), 7 deletions(-) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 9c3edfc8..afb74205 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -17,11 +17,14 @@ ## screens; a click on a row of a table or a list box selects it (Ctrl adds or takes one, ## Shift a range) and the script hears NOTIFY_LISTBOX_ITEM_SELECTED. +import re import time import oc4host import CvPythonExtensions as _cpe _FONT_LEFT, _FONT_RIGHT, _FONT_CENTER = 1 << 0, 1 << 1, 1 << 2 +_SORT_UP, _SORT_DOWN = 1 << 8, 1 << 9 # (a header's flags: its table is sorted by it, up or down) +_markup = re.compile(u'<[^<>]*>') _version = [1] # bumped on every change the display list shows _screens = {} # python file id -> _Screen @@ -88,7 +91,7 @@ class _Widget(object): __slots__ = ('name', 'kind', 'parent', 'mode', 'x', 'y', 'z', 'w', 'h', 'style', 'pstyle', 'text', 'help', 'tex', 'tex2', 'wt', 'd1', 'd2', 'opt', 'flags', 'font', 'shown', 'enabled', 'state', 'hittest', 'seq', 'vertical', 'scroll', 'children', 'bars', 'lists', 'columns', 'rows', 'headers', 'iconw', 'iconh', 'items', 'selected', 'color', 'size', 'defw', 'defh', 'points', - 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed') + 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed', 'selectable') def __init__(self, name, kind): self.name = name @@ -134,6 +137,7 @@ def __init__(self, name, kind): self.points = None # lines self.cells = None # tables: {(row, column): the name of the control attached there} self.sort = None # tables that sort: (column, descending) the rows are shown by, or (-1, False) + self.selectable = False # tables: enableSelect(True): with no row selected, the first shown has the selected look self.inset = 0 # scroll panels (addScrollPanel): where what is placed in them (attach...At) starts @@ -1118,9 +1122,10 @@ def setTableDate(self, szName, iColumn, iRow, text, szIcon='', eWidgetType=-1, i self.setTableText(szName, iColumn, iRow, text, szIcon, eWidgetType, iData1, iData2, iJustify) def getTableText(self, szName, iColumn, iRow): + # (the cell's text without its markup, as the original gives it back: BUG's red "-1" is "-1") w = self._s.get(szName) try: - return w.rows[int(iRow)][int(iColumn)][0] + return _markup.sub(u'', w.rows[int(iRow)][int(iColumn)][0]) except (AttributeError, IndexError, KeyError, TypeError): return u'' @@ -1139,7 +1144,11 @@ def enableSort(self, szName): if w is not None and w.rows is not None and w.sort is None: w.sort = (-1, False) _changed() - def enableSelect(self, szName, bSelect): pass + def enableSelect(self, szName, bSelect): + w = self._s.get(szName) + if w is not None and w.rows is not None and w.selectable != bool(bSelect): + w.selectable = bool(bSelect) + _changed() def enableGridlines(self, *args): pass def selectRow(self, szName, iRow, bSelected): @@ -1638,7 +1647,10 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): cx = x for ci, c in enumerate(w.columns): # (a table that sorts: each header a part of its own, -100 - column, that a click sorts by) - out.append((base + (-100 - ci if w.sort is not None else -1,), 'header', cx, top, cx + c[1], top + headerHeight, box, style, c[0], '', '', 2, _FONT_RIGHT if c[2] else _FONT_LEFT, + sortFlags = 0 + if w.sort is not None and w.sort[0] == ci: + sortFlags = _SORT_DOWN if w.sort[1] else _SORT_UP + out.append((base + (-100 - ci if w.sort is not None else -1,), 'header', cx, top, cx + c[1], top + headerHeight, box, style, c[0], '', '', 2, (_FONT_RIGHT if c[2] else _FONT_LEFT) | sortFlags, False, True, 0, None, -1, -1, -1, False, w.z, w.seq)) cx += c[1] top += headerHeight @@ -1657,7 +1669,10 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): continue # (the row's look under its cells: every other one the theme's Alt_, selected; as wide # as its columns, as in the original: BUG's domestic advisor's rows end with its last) - out.append((base + (-200 - ri,), 'row', x, cy, x + (sum(c[1] for c in w.columns) or width), cy + rowHeight, body, style, u'', '', '', 0, at & 1, ri in w.picked, True, 0, None, + # (a table one selects rows of shows its first row selected while none is, as the original's + # GTable its current row: BUG's Domestic Advisor opens with its first city lit) + lit = ri in w.picked or (w.selectable and not w.picked and at == 0) + out.append((base + (-200 - ri,), 'row', x, cy, x + (sum(c[1] for c in w.columns) or width), cy + rowHeight, body, style, u'', '', '', 0, at & 1, lit, True, 0, None, -1, -1, -1, False, w.z, w.seq)) cx = x for ci, c in enumerate(w.columns): diff --git a/src/render/Theme.cpp b/src/render/Theme.cpp index 47f91b1a..4a348b0e 100644 --- a/src/render/Theme.cpp +++ b/src/render/Theme.cpp @@ -956,9 +956,17 @@ namespace oc4::render if (const Value* h = m->resolve(s, m->property(s, "GFC_Control_Table_StyleId_HHeader")); h && h->kind == Value::Kind::Call && h->text == "GPropertyId" && !h->args.empty()) if (const Style* hs = m->findStyle(h->args[0].text)) + { if (const Value* b = m->resolve(hs, m->property(hs, "GFC_Control_Header_StyleId_HButton")); b && b->kind == Value::Kind::Call && b->text == "GPropertyId" && !b->args.empty()) t->header = button(b->args[0].text); + static const char* const kSort[] = { "GFC_Control_Header_StyleId_HSortAscendButton", "GFC_Control_Header_StyleId_HSortDescendButton" }; + for (size_t d = 0; d < 2; ++d) + if (const Value* b = m->resolve(hs, m->property(hs, kSort[d])); + b && b->kind == Value::Kind::Call && b->text == "GPropertyId" && !b->args.empty()) + if (const Button* arrow = button(b->args[0].text)) + t->sortArrow[d] = arrow->image[size_t(State::Default)]; + } m->margins(s, m->property(s, "GFC_Control_Table_Size_CellContentMargin"), t->content); // (the standard table's: table_innerTB.tga in the theme's BG; a GFlags(...) NoInnerFill none) const Value* noFill = m->resolve(s, m->property(s, "GFC_Control_Table_Flag_NoInnerFill")); diff --git a/src/render/Theme.h b/src/render/Theme.h index f5086290..dedbc3f1 100644 --- a/src/render/Theme.h +++ b/src/render/Theme.h @@ -135,6 +135,9 @@ namespace oc4::render // standard one's bg_header.tga and header_h.tga, a light band with dark text; and // how high they are (Size_Header, 22). const Button* header = nullptr; + // The column it is sorted by: its arrow (HSortAscendButton / HSortDescendButton's + // image, table_sort_arrows.tga), up and down. + Bitmap sortArrow[2]; float headerHeight = 22; float cellHeight = 24; float content[4]{ 4, 2, 4, 2 }; // left, top, right, bottom diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 46f4bffb..1114d131 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -30,6 +30,34 @@ namespace oc4::render // (a table header's text: the original's, dark brown on the parchment) constexpr Color kHeaderText{ 65 / 255.f, 40 / 255.f, 38 / 255.f }; + // The markup cut to the width with ".." after what is left of its text, as the theme's + // buttons crop (GFC_CF_BUTTON_CROP_DOTTED); its tags stay whole. + std::wstring fitWithDots(Overlay& o, const std::wstring& markup, float width, float size, std::wstring_view dots = L"..") + { + if (width <= 0) + return {}; + if (o.richWidth(markup, size, false) <= width) + return markup; + std::vector ends; // after each character of text + for (size_t i = 0; i < markup.size(); ++i) + { + if (markup[i] == L'<') + if (const size_t close = markup.find(L'>', i); close != std::wstring::npos) + { + i = close; + continue; + } + ends.push_back(i + 1); + } + for (size_t k = ends.size(); k-- > 1;) + { + const std::wstring cut = markup.substr(0, ends[k - 1]) + std::wstring(dots); + if (o.richWidth(cut, size, false) <= width) + return cut; + } + return ends.empty() ? std::wstring() : markup.substr(0, ends[0]) + std::wstring(dots); + } + // The built-in panel styles that draw nothing (PANEL_STYLE_EMPTY, PANEL_STYLE_EXTERNAL). bool emptyPanel(const std::string& style) { @@ -557,6 +585,18 @@ namespace oc4::render o.rect(x0, y0, x1, y1, { 0.1f, 0.11f, 0.15f }, 0.9f, 0); const Color colour = b && b->coloured ? b->text[state] : b ? kHeaderText : Color{ 1, 0.9f, 0.65f }; const float ty = y0 + (h - o.richHeight(text, 4096, m_sizes[2], false)) / 2; + // (the column the table is sorted by: its arrow at the right, the text left of it, cut + // with dots where it does not fit: Wine's "P.. ^" over BUG's POP) + const int sorted = (it.flags & 0x100) ? 0 : (it.flags & 0x200) ? 1 : -1; + if (sorted >= 0 && t && t->sortArrow[sorted]) + { + const Theme::Bitmap& arrow = t->sortArrow[sorted]; + const float aw = arrow.width(), ah = arrow.height(); + const float ax = std::round(x1 - 4 - aw), ay = std::round(y0 + (h - ah) / 2); + Theme::draw(o, arrow, ax, ay, ax + aw, ay + ah, alpha); + o.richText(fitWithDots(o, text, ax - 2 - (x0 + 4), m_sizes[2]), x0 + 4, ty, m_sizes[2], false, colour, alpha, Overlay::Align::Left); + break; + } o.richText(text, (it.flags & 2) ? x1 - 4 : x0 + 4, ty, m_sizes[2], false, colour, alpha, (it.flags & 2) ? Overlay::Align::Right : Overlay::Align::Left); break; @@ -583,10 +623,11 @@ namespace oc4::render if (!it.texture.empty() && icon(it.texture, x0 + 2, y0 + 1, x0 + h - 1, y1 - 1, alpha)) tx = x0 + h + 2; const bool right = (it.flags & 2) != 0, centre = (it.flags & 4) != 0; - const std::wstring text = widen(it.text); // (in its font, size 2 a table's, 3 a list box's; in the middle of the room the style - // leaves round a cell's content) + // leaves round a cell's content; cut with "..." where its column ends, as the original's: + // BUG's page editor's "GREATPEOPLE_TUR...") const float size = m_sizes[size_t(std::clamp(it.font, 0, 4))]; + const std::wstring text = fitWithDots(o, widen(it.text), (right || centre ? x1 - x0 - 8 : x1 - 4 - tx), size, L"..."); float above = 0, below = 0; if (const Theme::Table* t = m_theme.loaded() ? m_theme.table(it.style) : nullptr) above = t->content[1], below = t->content[3]; From d258d3114e43fa8e55b37b463e8096bd9f1258ef Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 00:17:04 +0100 Subject: [PATCH 37/89] Table cells: a cell of one character or icon is never cut BUG's Religion Advisor puts a religion's mark, %c, in 25 px columns: cut, it became nothing (an icon is markup, no character was left). Wine draws the whole icon. Found by the Religion Advisor session. Co-Authored-By: Claude Opus 5.5 --- src/render/UiLayer.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 1114d131..f19a0d76 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -49,6 +49,9 @@ namespace oc4::render } ends.push_back(i + 1); } + // (one character, an icon, is drawn whole: BUG's religion marks in 25 px columns) + if (ends.size() <= 1) + return markup; for (size_t k = ends.size(); k-- > 1;) { const std::wstring cut = markup.substr(0, ends[k - 1]) + std::wstring(dots); From 6ccf0c8e2c9c519732de4877ed8a0cd8d47af0f0 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 00:18:53 +0100 Subject: [PATCH 38/89] Screens: a cursor move's getMouseX is the mouse's x, not a column BUG's religion and domestic advisors open a row's city when a table input's getMouseX is 0, whatever the notify: resting the mouse on a cell zoomed to its city. The original gives the mouse's x in pixels then. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 79ab6dbd..4923a8c1 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -1336,12 +1336,15 @@ if _walls: if (now ? m_movedOn && same(*m_movedOn, *now) : !m_movedOn) return; const std::optional before = std::exchange(m_movedOn, now); + // (getMouseX is the mouse's x in pixels then, as in the original, not a table's column: BUG's + // religion and domestic advisors zoom to a row's city when it is 0, whatever the notify) + const int mouseX = window.mousePosition().first; if (before) // (to the widget as it is now, if it is still there) if (const auto it = std::ranges::find_if(m_items, [&](const Item& i) { return same(i, *before); }); it != m_items.end()) - scriptInput(Item(*it), kMoveOff, it->part < 0 ? 0 : (it->part & 0xFFFF), 0, false, false, false, false); + scriptInput(Item(*it), kMoveOff, it->part < 0 ? 0 : (it->part & 0xFFFF), mouseX, false, false, false, false); if (now) - scriptInput(*now, kMoveOn, now->part < 0 ? 0 : (now->part & 0xFFFF), 0, false, false, false, false); + scriptInput(*now, kMoveOn, now->part < 0 ? 0 : (now->part & 0xFFFF), mouseX, false, false, false, false); } bool Screens::click(const std::string& name, int part, bool shift, bool ctrl, bool alt) From cbfc1203e3e5149b4425dc1e5869dbb00f9dd49f Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 00:21:06 +0100 Subject: [PATCH 39/89] Tables drawn with a grid show the theme's grid lines A table made with bDrawGrid (addTableControlGFC's 8th argument) draws the theme's grid in the original: SF_CtrlTheme_Civ4_Control_Color's Grid, GColor(105, 97, 86, 128), one pixel at each column's right edge and each row's bottom. OpenCiv4 ignored the flag, so BUG's Religion Advisor's city table (and the Info screen's charts, the Hall of Fame) had no lines between their religion marks and buildings. Measured in Wine (BUG + BULL, 1600x900): rows of (57, 80, 134) show (82, 89, 110) lines, the grid colour at half alpha. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4screens.py | 23 ++++++++++++++++++++++- src/render/UiLayer.cpp | 3 ++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..f978e601 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -88,7 +88,7 @@ class _Widget(object): __slots__ = ('name', 'kind', 'parent', 'mode', 'x', 'y', 'z', 'w', 'h', 'style', 'pstyle', 'text', 'help', 'tex', 'tex2', 'wt', 'd1', 'd2', 'opt', 'flags', 'font', 'shown', 'enabled', 'state', 'hittest', 'seq', 'vertical', 'scroll', 'children', 'bars', 'lists', 'columns', 'rows', 'headers', 'iconw', 'iconh', 'items', 'selected', 'color', 'size', 'defw', 'defh', 'points', - 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed') + 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed', 'grid') def __init__(self, name, kind): self.name = name @@ -118,6 +118,7 @@ def __init__(self, name, kind): self.bars = None # stacked bars: [[percent, (r, g, b, a)], ...] self.lists = None # multi lists: [[(texture, wt, d1, d2, option, disabledTexture), ...], ...] self.columns = None # tables: [[header, width, right], ...] + self.grid = False # ... drawn with the theme's grid (bDrawGrid) self.rows = None # tables: [{column: (text, icon, wt, d1, d2, justify)}, ...] self.headers = True self.iconw = self.iconh = 0 @@ -1053,6 +1054,7 @@ def addTableControlGFC(self, szName, numColumns, iX, iY, iWidth, iHeight, bInclu w.columns = [[u'', 0, False] for _ in range(max(1, int(numColumns)))] w.rows = [] w.headers, w.iconw, w.iconh, w.pstyle = bool(bIncludeHeaders), int(iconWidth), int(iconHeight), _style(_cpe.TableStyles, style) + w.grid = bool(bDrawGrid) def addTableControlGFCWithHelp(self, szName, numColumns, iX, iY, iWidth, iHeight, bIncludeHeaders, bDrawGrid, iconWidth, iconHeight, style, szHelpText): @@ -1523,6 +1525,23 @@ def _size(s, w): return w.w, w.h +# The theme's grid of a table drawn with one (bDrawGrid): SF_CtrlTheme_Civ4_Control_Color's Grid, +# GColor(105, 97, 86, 128), one pixel at each column's right and each row's bottom, as the +# original's (BUG's Religion Advisor: Wine's rows (57, 80, 134) show (82, 89, 110) lines). +_GRID_COLOR = (105 / 255.0, 97 / 255.0, 86 / 255.0, 128 / 255.0) + +def _gridLines(base, ri, x, cy, columns, rowHeight, clip, w, out): + cx = x + for ci, c in enumerate(columns): + cx += c[1] + if c[1] > 0: + out.append((base + (-(0x1000000 | (ri << 8) | ci),), 'line', cx - 0.5, cy, cx - 0.5, cy + rowHeight, clip, '__grid', u'', '', '', 0, 0, False, True, 4, + _GRID_COLOR, -1, -1, -1, False, w.z, w.seq)) + if cx > x: + out.append((base + (-(0x2000000 | ri),), 'line', x, cy + rowHeight - 0.5, cx, cy + rowHeight - 0.5, clip, '__grid', u'', '', '', 0, 0, False, True, 4, + _GRID_COLOR, -1, -1, -1, False, w.z, w.seq)) + + def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): """Adds a widget (and what is attached to it) to the display list; one attached to a table's cell only there (cell: that cell's corner).""" @@ -1627,6 +1646,8 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): if control is not None: _display_widget(s, control, cx, cy, body, [cx, cy, True, c[1], cx], out, (cx, cy)) cx += c[1] + if w.grid: + _gridLines(base, ri, x, cy, w.columns, rowHeight, body, w, out) cy += rowHeight return if kind == 'listbox': diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..e94cf21a 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -574,7 +574,8 @@ namespace oc4::render break; } case Kind::Line: - o.line(x0, y0, x1, y1, it.hasColor ? it.color : kEdge, it.alpha, 2); + // (a table's grid, "__grid": one pixel, as the theme's) + o.line(x0, y0, x1, y1, it.hasColor ? it.color : kEdge, it.alpha, it.style == "__grid" ? 1.0f : 2.0f); break; case Kind::Separator: o.line(x0, y0 + h / 2, x1, y0 + h / 2, kEdge, 0.5f); From ac0d8a3dd715e9e18d7c482508739c4818b037bd Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 00:34:16 +0100 Subject: [PATCH 40/89] Screens: setText plain at size 3, determineWidth measures it so The original draws a CyGInterfaceScreen.setText in the theme's normal font, size 3 and not bold, whatever FontTypes it names, and CyInterface ().determineWidth measures untagged text at that size (Wine: "The Apostolic Palace" 139, as ; 121). OpenCiv4 measured at size 2 and drew a TITLE_FONT text bold, so labels laid out with determineWidth ran into each other: BUG's Victory Advisor members tab (The Apostolic Palace / The United Nations, Diplomatic Victory / U.N. Secretary General). Now they keep BUG's 10 px gaps as in the original. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4screens.py | 4 +++- src/render/UiLayer.cpp | 8 +++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..4f79b5be 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -2207,7 +2207,9 @@ def getCityTabSelectionRow(self): return getattr(self.__class__, '_cityTab', 0) def setCityTabSelectionRow(self, eIndex): self.__class__._cityTab = int(eIndex) def getHelpString(self): return oc4host.ui_help_string() - def determineWidth(self, szBuffer): return _textWidth(_text(szBuffer)) + # (the original measures untagged text at the size setText draws it, whatever its FontTypes: + # the theme's size 3, as ; Wine's "The Apostolic Palace" is 139, its 121) + def determineWidth(self, szBuffer): return _textWidth(_text(szBuffer), 3) def getEndTurnState(self): return _cpe.EndTurnButtonStates(oc4host.ui_end_turn_state()) def shouldDisplayEndTurn(self): return oc4host.ui_end_turn_message() diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..34a843f0 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -498,9 +498,11 @@ namespace oc4::render break; case Kind::Label: case Kind::Text: - // (a text, CyGInterfaceScreen.setText, is in the theme's normal font, size 3, whatever - // font it names; a label in the one it names) - label(y0, it.kind == Kind::Text ? m_sizes[3] : fontSize(it.font), fontBold(it.font), it.interactive && hot ? kHot : kText); + // (a text, CyGInterfaceScreen.setText, is in the theme's normal font, size 3 and not bold, + // whatever font it names, as the original draws it and as determineWidth measures it; a + // label in the one it names) + label(y0, it.kind == Kind::Text ? m_sizes[3] : fontSize(it.font), it.kind != Kind::Text && fontBold(it.font), + it.interactive && hot ? kHot : kText); break; case Kind::EndTurnText: if (!it.text.empty()) From d082f6b0c7907b372607cd204690484fd93bec9a Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 00:34:20 +0100 Subject: [PATCH 41/89] Screens: list rows as the original's espionage advisor lays them out BtS's and BUG's Espionage Advisor build each leader's row as a panel in a scrolling list (attachPanel) holding a separator 30 long, the leader's button (addCheckBoxGFCAt), a name panel placed over it (attachPanelAt) and texts. Measured in the original (Wine, BUG + BULL, 1600x900): - the name panel shows nothing and the leader buttons are seen and clicked: a panel placed in a list's row is no longer drawn (it hid the buttons and took their clicks, so no other leader could be chosen); - the rows are 32 high, 34 apart: a separator sets its row's height (what is placed in the row doesn't grow it), the flow 1 in; - separators draw nothing (GSeparator: transparent, no inner fill); - the 17 rows end at the list's bottom with no scroll bar: the gap after the last of a flow isn't part of what scrolls, and a panel laid out top to bottom (addPanel/attachPanel) scrolls only down, so the passive missions' icons past the rows' right edge give no sideways bar. Every other advisor and the Civilopedia draw as before. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4screens.py | 30 ++++++++++++++++++++++++------ src/render/UiLayer.cpp | 3 ++- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..286f830e 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -86,7 +86,7 @@ def _int(value, default=-1): class _Widget(object): __slots__ = ('name', 'kind', 'parent', 'mode', 'x', 'y', 'z', 'w', 'h', 'style', 'pstyle', 'text', 'help', 'tex', 'tex2', - 'wt', 'd1', 'd2', 'opt', 'flags', 'font', 'shown', 'enabled', 'state', 'hittest', 'seq', 'vertical', 'scroll', 'children', + 'wt', 'd1', 'd2', 'opt', 'flags', 'font', 'shown', 'enabled', 'state', 'hittest', 'seq', 'vertical', 'sideways', 'scroll', 'children', 'bars', 'lists', 'columns', 'rows', 'headers', 'iconw', 'iconh', 'items', 'selected', 'color', 'size', 'defw', 'defh', 'points', 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed') @@ -111,6 +111,7 @@ def __init__(self, name, kind): self.hittest = 0 self.seq = 0 self.vertical = True + self.sideways = True # (a scrolling panel: also scrolls sideways (addScrollPanel); not one laid out top to bottom) self.scroll = False self.children = [] self.maxChars = 0 # an edit box's: at most this many characters (0: any) @@ -604,6 +605,9 @@ def addPanel(self, szName, title, helpText, bVerticalLayout, bScrollable, iX, iY w = self._s.add(szName, 'panel') w.text, w.help, w.vertical, w.scroll = _text(title), _text(helpText), bool(bVerticalLayout), bool(bScrollable) w.x, w.y, w.w, w.h, w.pstyle = int(iX), int(iY), int(iWidth), int(iHeight), _style(_cpe.PanelStyles, eStyle) + # (one laid out top to bottom scrolls only down: in the original the espionage advisor's + # leader list shows no sideways scroll bar though its icons reach past the rows' right edge) + w.sideways = not w.vertical def addScrollPanel(self, szName, title, iX, iY, iWidth, iHeight, eStyle): w = self._s.add(szName, 'panel') @@ -1513,6 +1517,11 @@ def _size(s, w): # placed in it, attachXAt, down to its lowest) held = [cw for cw in [s.widgets.get(c) for c in w.children] if cw is not None and cw.shown] heights = [_size(s, cw)[1] for cw in held if cw.mode == 'flow'] + if [cw for cw in held if cw.kind == 'separator' and cw.mode == 'flow']: + # (a separator sets the height of the panel it is in: the espionage advisor's leader + # rows, a separator 30 long and the leader's texts placed in it, are 32 high in the + # original, 34 apart; what is placed in it doesn't make it higher) + return w.w, 2 + (sum(heights) + 2 * (len(heights) - 1) if w.vertical else max(heights)) height = 8 + (sum([h + 2 for h in heights]) if w.vertical else max(heights + [0])) for cw in held: if cw.mode == 'rel': @@ -1675,15 +1684,22 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): text = w.text if kind == 'edit' and _editFocus[0] == (s.id, w.name): text = text + u'|' # (the caret: typed into) - out.append((base + (-1,), kind, x, y, x + width, y + height, clip, w.style if w.style else w.pstyle, text, w.tex, w.tex2, w.font, flags, - w.state, w.enabled, w.hittest, color, w.wt, w.d1, w.d2, w.opt, w.z, w.seq)) + owner = s.widgets.get(w.parent) if w.parent else None + if not (kind == 'panel' and w.mode == 'rel' and owner is not None and owner.mode == 'flow'): + # (a panel placed in a row of a list (attachPanelAt in an attachPanel's) isn't seen and + # takes no clicks: the espionage advisor's leader names' panels, made after the leaders' + # buttons, show nothing in the original, and the buttons are clicked) + out.append((base + (-1,), kind, x, y, x + width, y + height, clip, w.style if w.style else w.pstyle, text, w.tex, w.tex2, w.font, flags, + w.state, w.enabled, w.hittest, color, w.wt, w.d1, w.d2, w.opt, w.z, w.seq)) if w.children: inner, left, top = clip, x, y scrolls = kind == 'panel' and w.scroll and width > 0 and height > 0 if scrolls: inner, left, top = _clipTo(clip, (x, y, x + width, y + height)), x - w.hoffset, y - w.offset first = len(out) - childFlow = [left + 4, top + 4 + (18 if w.text else 0), w.vertical, max(0, width - 8), left + 4] + # (in a row a separator sets, 1 in: the espionage advisor's rows, 32 high) + edge = 1 if [cw for cw in [s.widgets.get(c) for c in w.children] if cw is not None and cw.kind == 'separator' and cw.mode == 'flow'] else 4 + childFlow = [left + edge, top + edge + (18 if w.text else 0), w.vertical, max(0, width - 2 * edge), left + edge] for c in w.children: cw = s.widgets.get(c) if cw is not None: @@ -1692,11 +1708,13 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): held = [i for i in out[first:] if i[1] != 'scrollbar'] # (the margin below and right of what it holds only once that overflows: a strip of # buttons as big as its panel, the WorldBuilder's load/save one, has no scroll bars) - extent = max([i[5] for i in held] + [childFlow[1]]) - top + # (the gap after the last of a top to bottom flow isn't held: the espionage advisor's + # 17 rows end at its list's bottom edge, with no scroll bar in the original) + extent = max([i[5] for i in held] + [childFlow[1] - (2 if w.vertical and childFlow[1] > top + 4 else 0)]) - top hextent = max([i[4] for i in held] + [left]) - left w.extent = extent + 4 if extent > height else extent w.hextent = hextent + 4 if hextent > width else hextent - _scrolls(w, x, y, x + width, y + height, s.id, _LIST_ROW, out, True) + _scrolls(w, x, y, x + width, y + height, s.id, _LIST_ROW, out, w.sideways) def dump(path): diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..809347d1 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -577,7 +577,8 @@ namespace oc4::render o.line(x0, y0, x1, y1, it.hasColor ? it.color : kEdge, it.alpha, 2); break; case Kind::Separator: - o.line(x0, y0 + h / 2, x1, y0 + h / 2, kEdge, 0.5f); + // (nothing: the theme's GSeparator is transparent with no inner fill, + // Civ4Theme_Separator.thm; it only takes its room in the flow) break; case Kind::Slider: o.rect(x0, y0 + h / 2 - 2, x1, y0 + h / 2 + 2, kEdge, 0.6f, 2); From 8ff2f5fa8b9dd9dfd1b42630f871909ea3d0228b Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 06:15:56 +0100 Subject: [PATCH 42/89] BUG's dot map: the mouse over the map for the scripts, as the original's BUG's Strategy Overlay (Alt+X edits the dot map, Ctrl+X shows or hides it) reads CyInterface's getMouseOverPlot, isLeftMouseDown and isRightMouseDown every frame and is told by CvScreensInterface.mouseOverPlot when the mouse moves to another plot. Those were kept only in the World Builder, so a click placed no city and the cross under the mouse never followed it. - Out of the World Builder the host now keeps the plot under the mouse and the buttons held over the map, and tells the shown screens when the mouse moves to another plot. A click no frame saw held (a scripted one, or one quicker than a frame) counts as held for one frame. - A plot marked again in its layer takes the new colour instead of a second mark (BUG erases a dot so, with alpha 0). - CyEngine.addColoredPlot takes the Mac engine's form without a style, (x, y, color, layer): BUG calls it so where sys.platform is darwin. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 17 ++++++++++++++++ apps/oc4core/Screens.h | 4 ++++ apps/oc4core/Utility.h | 10 ++++++++- apps/oc4core/main.cpp | 34 +++++++++++++++++++++++++++++++ apps/oc4core/python/oc4screens.py | 6 +++++- 5 files changed, 69 insertions(+), 2 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..9d7bf481 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -1508,6 +1508,23 @@ if _walls: return taken; } + void Screens::mouseOverPlot() + { + if (!m_active || m_menu) + return; + try + { + py::module_ entry = py::module_::import("CvScreensInterface"); + for (py::handle id : py::module_::import("oc4screens").attr("shownScreens")().cast()) + if (const int screen = id.cast(); screen != kDiplomacyScreen) + entry.attr("mouseOverPlot")(py::make_tuple(screen)); + } + catch (py::error_already_set& e) + { + printPythonError(e); + } + } + bool Screens::diploKey(unsigned key) { if (!m_active || !m_utility.diplomacy().active()) diff --git a/apps/oc4core/Screens.h b/apps/oc4core/Screens.h index 5f64207c..2cc61349 100644 --- a/apps/oc4core/Screens.h +++ b/apps/oc4core/Screens.h @@ -106,6 +106,10 @@ namespace oc4::host // manager's kbdEvent, down and up, with the mouse and the plot under it (BUG's shortcuts // are there). True if they took it (it goes no further then). bool keyEvent(int key, bool shift, bool ctrl, bool alt, int mouseX, int mouseY, int plotX, int plotY); + // The mouse onto another plot of the map: CvScreensInterface's mouseOverPlot for each screen + // shown over the main interface, as the original engine tells them (BUG's dot map editor + // draws the city it would place there). + void mouseOverPlot(); bool menuUp(); // the main menu, a talk or a screen over the map: the arrows are its diff --git a/apps/oc4core/Utility.h b/apps/oc4core/Utility.h index 6622eda8..8238729c 100644 --- a/apps/oc4core/Utility.h +++ b/apps/oc4core/Utility.h @@ -119,8 +119,16 @@ namespace oc4::host } void mark(const PlotMark& m) { + // (a plot marked again in its layer takes the new colour, as the original's: BUG's dot + // map erases a dot so, with a colour of alpha 0) std::lock_guard lock(marksMutex); - marks.push_back(m); + const auto same = std::find_if(marks.begin(), marks.end(), [&m](const PlotMark& o) { + return o.x == m.x && o.y == m.y && o.layer == m.layer && o.border == m.border && o.core == m.core; + }); + if (same != marks.end()) + *same = m; + else + marks.push_back(m); ++marksVersion; } void clear(int layer, bool border) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..4a282234 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1223,6 +1223,40 @@ namespace // The WorldBuilder: the mouse over the map is its screen's (where it is, its buttons held, // its clicks: CvScreensInterface's mouseOverPlot, leftMouseDown, rightMouseDown), and the // plot its brush is on outlined (WorldBuilderGetHighlightPlot); the game's clicks wait. + // Out of it, the mouse over the map as the original engine keeps it for the scripts + // (CyInterface's getMouseOverPlot, isLeftMouseDown, isRightMouseDown; BUG's dot map editor + // reads them every frame and draws its city where the mouse is): the plot under it, the + // screens over the map told when it moves to another, and its buttons held. A click + // whose press no frame saw (a scripted one, or one quicker than a frame) is held for this + // frame, so that it is seen once. + if (!ui.worldBuilder() && !opt.ownInterface) + { + static bool heldSeen[2] = {}; + const auto [hx, hy] = window.hoveredPlot(); + ui.mouseOverMap = hx >= 0 && window.uiHovered() < 0; + int px = ui.mouseOverMap ? hx : ui.mouseX, py = ui.mouseOverMap ? hy : ui.mouseY; + bool clicked[2] = {}; + for (const auto& click : clicks) + if (!click.clear && !click.either) + { + clicked[click.right ? 1 : 0] = true; + px = click.x, py = click.y; + } + if (px != ui.mouseX || py != ui.mouseY) + { + ui.mouseX = px, ui.mouseY = py; + if (px >= 0) + screens.mouseOverPlot(); + } + bool down[2]; + for (int b = 0; b < 2; ++b) + { + const bool held = render::mouseHeld(b == 0); + down[b] = (ui.mouseOverMap && held) || (clicked[b] && !heldSeen[b]); + heldSeen[b] = held || (heldSeen[b] && !clicked[b]); + } + ui.mouseLeft = down[0], ui.mouseRight = down[1]; + } window.setWorldBuilder(ui.worldBuilder()); if (ui.worldBuilder()) { diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..06d84ab7 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -2387,7 +2387,11 @@ def setUnitFlagVisibility(self, b): _engineFlags['flags'] = bool(b) def getSelectionCursorVisibility(self): return _engineFlags['cursor'] def setSelectionCursorVisibility(self, b): _engineFlags['cursor'] = bool(b) # the plots it marks (oc4host keeps them, the window draws them): coloured, outlined - def addColoredPlot(self, iX, iY, color, ePlotStyle, eLayer): + # (the Mac engine's has no style, addColoredPlot(iX, iY, color, eLayer): BUG calls it so when + # sys.platform is darwin, for its dot map) + def addColoredPlot(self, iX, iY, color, ePlotStyle, eLayer=None): + if eLayer is None: + ePlotStyle, eLayer = None, ePlotStyle oc4host.engine_mark(_int(iX), _int(iY), float(color.r), float(color.g), float(color.b), float(color.a), _int(eLayer, 0), False) def addColoredPlotAlt(self, iX, iY, ePlotStyle, eLayer, szColor, fAlpha): From 8d8ad9b515e3ad23246201e80f4f465369ab9e22 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 06:22:56 +0100 Subject: [PATCH 43/89] BUG's dot map: crosses and dots drawn as the original's As the Wine game shows them (BUG's Strategy Overlay, Alt+X / Ctrl+X): - Area border layers past the game's own (scripts' layers; BUG's dot map uses 8 and up) are drawn in the original's AreaBorder style, rounded, hatched and with a glow, as the World Builder's highlight already is. - A coloured plot keeps its PlotStyles. TARGET and DOT_TARGET are drawn as their picture in plottexture.dds: four rounded corners and, for DOT_TARGET, a dot in the middle (BUG's dot). The Mac engine's form without a style draws DOT_TARGET, the icon BUG uses on Windows. - Overlay::polygon and Overlay::polyline draw a shape or an open line in one piece (no darker seams where parts meet). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 6 ++-- apps/oc4core/Utility.h | 5 +-- apps/oc4core/main.cpp | 8 +++-- apps/oc4core/python/oc4screens.py | 12 ++++--- src/render/MapWindow.cpp | 56 +++++++++++++++++++++++++++++++ src/render/MapWindow.h | 1 + src/render/Overlay.cpp | 27 +++++++++++---- src/render/Overlay.h | 6 +++- 8 files changed, 100 insertions(+), 21 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 9d7bf481..f01f4096 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -246,9 +246,9 @@ namespace oc4::host // CyEngine's marks on the map (the game core's coordinates): coloured plots, outlines, // signs and landmarks Engine& engine = utility.engine(); - host.def("engine_mark", [&engine](int x, int y, float r, float g, float b, float a, int layer, bool border) { - engine.mark({ x, y, r, g, b, a, layer, border, true }); - }); + host.def("engine_mark", [&engine](int x, int y, float r, float g, float b, float a, int layer, bool border, int style) { + engine.mark({ x, y, r, g, b, a, layer, border, true, style }); + }, py::arg("x"), py::arg("y"), py::arg("r"), py::arg("g"), py::arg("b"), py::arg("a"), py::arg("layer"), py::arg("border"), py::arg("style") = -1); host.def("engine_effect", [&engine](int effect, float x, float y, float z, float rotation) { engine.TriggerEffect(effect, NiPoint3(x, y, z), rotation); }); // The player's profile (oc4options): where it is kept, how loud the sounds play. host.def("profile_path", [] { diff --git a/apps/oc4core/Utility.h b/apps/oc4core/Utility.h index 8238729c..3f347ded 100644 --- a/apps/oc4core/Utility.h +++ b/apps/oc4core/Utility.h @@ -91,6 +91,7 @@ namespace oc4::host float r = 1, g = 1, b = 1, a = 1; int layer = 0; bool border = false, core = true; + int style = -1; // (coloured plots: PlotStyles, the picture of plottexture.dds drawn) }; struct Sign { @@ -98,9 +99,9 @@ namespace oc4::host std::wstring caption; bool core = true; }; - void addColoredPlot(int plotX, int plotY, const NiColorA& color, PlotStyles, PlotLandscapeLayers layer) override + void addColoredPlot(int plotX, int plotY, const NiColorA& color, PlotStyles style, PlotLandscapeLayers layer) override { - mark({ plotX, plotY, color.r, color.g, color.b, color.a, int(layer), false }); + mark({ plotX, plotY, color.r, color.g, color.b, color.a, int(layer), false, true, int(style) }); } void clearColoredPlots(PlotLandscapeLayers layer) override { clear(int(layer), false); } void fillAreaBorderPlot(int plotX, int plotY, const NiColorA& color, AreaBorderLayers layer) override diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 4a282234..eefad43f 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1487,9 +1487,11 @@ namespace for (const auto& m : marks) { const auto [x, y] = m.core ? host::windowPlot({ m.x, m.y }) : std::pair{ m.x, m.y }; - // (the WorldBuilder's plot and brush in the original's area border style) - const bool hatched = m.border && (m.layer == AREA_BORDER_LAYER_HIGHLIGHT_PLOT || m.layer == AREA_BORDER_LAYER_WORLD_BUILDER); - shownMarks.marks.push_back({ x, y, m.layer, { m.r, m.g, m.b }, m.a, m.border, false, hatched }); + // (the WorldBuilder's plot and brush in the original's area border style, and the layers + // past the game's own that scripts draw: BUG's dot map's cities, as in the Wine game) + const bool hatched = m.border && (m.layer == AREA_BORDER_LAYER_HIGHLIGHT_PLOT || m.layer == AREA_BORDER_LAYER_WORLD_BUILDER || + m.layer >= NUM_AREA_BORDER_LAYERS); + shownMarks.marks.push_back({ x, y, m.layer, { m.r, m.g, m.b }, m.a, m.border, false, hatched, m.style }); } for (const auto& s : signs) { diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 06d84ab7..0120b472 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -2387,17 +2387,19 @@ def setUnitFlagVisibility(self, b): _engineFlags['flags'] = bool(b) def getSelectionCursorVisibility(self): return _engineFlags['cursor'] def setSelectionCursorVisibility(self, b): _engineFlags['cursor'] = bool(b) # the plots it marks (oc4host keeps them, the window draws them): coloured, outlined - # (the Mac engine's has no style, addColoredPlot(iX, iY, color, eLayer): BUG calls it so when - # sys.platform is darwin, for its dot map) + # (the Mac engine's has no style, addColoredPlot(iX, iY, color, eLayer): BUG calls it so where + # sys.platform is darwin, for its dot map's dots, which on Windows it draws as + # PLOT_STYLE_DOT_TARGET, its default icon: so drawn here too, as the Wine game shows them) def addColoredPlot(self, iX, iY, color, ePlotStyle, eLayer=None): if eLayer is None: - ePlotStyle, eLayer = None, ePlotStyle - oc4host.engine_mark(_int(iX), _int(iY), float(color.r), float(color.g), float(color.b), float(color.a), _int(eLayer, 0), False) + ePlotStyle, eLayer = _cpe.PlotStyles.PLOT_STYLE_DOT_TARGET, ePlotStyle + oc4host.engine_mark(_int(iX), _int(iY), float(color.r), float(color.g), float(color.b), float(color.a), _int(eLayer, 0), False, + _int(ePlotStyle, -1)) def addColoredPlotAlt(self, iX, iY, ePlotStyle, eLayer, szColor, fAlpha): c = _namedColor(szColor) if c is not None: - oc4host.engine_mark(_int(iX), _int(iY), c[0], c[1], c[2], c[3] * float(fAlpha), _int(eLayer, 0), False) + oc4host.engine_mark(_int(iX), _int(iY), c[0], c[1], c[2], c[3] * float(fAlpha), _int(eLayer, 0), False, _int(ePlotStyle, -1)) def clearColoredPlots(self, eLayer): oc4host.engine_clear(_int(eLayer, -1), False) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..7749013c 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -1708,6 +1708,60 @@ namespace oc4::render edges(0, m.color, std::min(1.0f, m.alpha + 0.1f), 3); } + // A coloured plot of the original's PlotStyles TARGET (22) or DOT_TARGET (23): its picture in + // plottexture.dds (a 128-texel cell of the plot), laid on the ground in the plot's colour: + // four rounded corners 4 texels wide, 8 in from the plot's edges, reaching 30 texels along + // them; DOT_TARGET with a dot of radius 23 in the middle (BUG's dot map draws its cities' + // dots so). + static constexpr int kPlotStyleTarget = 22, kPlotStyleDotTarget = 23; + void drawTarget(const MapWindow::PlotMarks::Mark& m, float S) + { + const auto project = [&](float u, float v, float& sx, float& sy) { + return groundToScreen((float(m.x) + u) * S, (float(m.y) + v) * S, 3, sx, sy); + }; + float cx = 0, cy = 0, ex = 0, ey = 0; + if (!project(0.5f, 0.5f, cx, cy) || !project(0.6f, 0.5f, ex, ey)) + return; + const float perPlot = 10 * std::hypot(ex - cx, ey - cy); // (pixels a plot across, near its middle) + constexpr float kTexel = 1.0f / 128, kEdge = 10 * kTexel, kReach = 38 * kTexel, kRound = 8 * kTexel, kDot = 23 * kTexel; + const float width = std::max(1.0f, 4 * kTexel * perPlot); + const float alpha = std::min(1.0f, m.alpha); + constexpr float pi = 3.14159265f; + // a corner: along one edge, round, along the other (u, v from the corner, mirrored) + for (const auto& [su, sv] : { std::pair{ 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }) + { + const auto at = [&](float a, float b, float& sx, float& sy) { + return project(su ? 1 - a : a, sv ? 1 - b : b, sx, sy); + }; + std::vector> path{ { kEdge, kReach } }; + for (int i = 0; i <= 6; ++i) + { + const float t = pi * (1.0f + 0.5f * float(i) / 6); // (from west round to south of the arc's centre) + path.push_back({ kEdge + kRound + kRound * std::cos(t), kEdge + kRound + kRound * std::sin(t) }); + } + path.push_back({ kReach, kEdge }); + std::vector> line; + for (const auto& [a, b] : path) + if (float sx = 0, sy = 0; at(a, b, sx, sy)) + line.push_back({ sx, sy }); + if (line.size() == path.size()) + overlay->polyline(line, m.color, alpha, width); + } + if (m.style != kPlotStyleDotTarget) + return; + // the dot + constexpr int kSteps = 24; + std::vector> dot; + for (int i = 0; i < kSteps; ++i) + { + const float t = 2 * pi * float(i) / kSteps; + if (float sx = 0, sy = 0; project(0.5f + kDot * std::cos(t), 0.5f + kDot * std::sin(t), sx, sy)) + dot.push_back({ sx, sy }); + } + if (dot.size() == kSteps) + overlay->polygon(dot, m.color, alpha); + } + // The marked plots: circles; the outline of each layer's and colour's set of plots, its // edges where the next plot is not of it; the signs' captions. void drawMarks() @@ -1763,6 +1817,8 @@ namespace oc4::render } } } + else if (m.style == kPlotStyleTarget || m.style == kPlotStyleDotTarget) + drawTarget(m, S); else { float cx = 0, cy = 0, ex = 0, ey = 0; diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..f6ad6286 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -295,6 +295,7 @@ namespace oc4::render bool border = false; bool fill = false; // the whole plot coloured (a globe layer's) bool hatched = false; // (borders) as the original's AreaBorder texture: rounded, a glow inside, hatched + int style = -1; // (coloured plots) the original's PlotStyles: 23 a dot in four corners (BUG's dot map); else a circle }; struct Sign { diff --git a/src/render/Overlay.cpp b/src/render/Overlay.cpp index 97b344f9..c7159bf9 100644 --- a/src/render/Overlay.cpp +++ b/src/render/Overlay.cpp @@ -248,8 +248,9 @@ namespace oc4::render return out; } - // Each point's way out of the shape (by a unit across its edges): the edges' normals mitred. - std::vector> outward(const std::vector>& p) + // Each point's way out of the shape (by a unit across its edges): the edges' normals mitred + // (an open line's ends: their one edge's). + std::vector> outward(const std::vector>& p, bool closed = true) { const size_t n = p.size(); float area = 0; @@ -264,8 +265,8 @@ namespace oc4::render } for (size_t i = 0; i < n; ++i) { - const auto& a = edge[(i + n - 1) % n]; - const auto& b = edge[i]; + const auto& a = edge[!closed && i == 0 ? 0 : (i + n - 1) % n]; + const auto& b = edge[!closed && i + 1 == n ? n - 2 : i]; float mx = a[0] + b[0], my = a[1] + b[1]; const float len = std::hypot(mx, my); if (len < 1e-4f) @@ -307,18 +308,18 @@ namespace oc4::render } } - void Overlay::strokeClosed(const std::vector>& p, float width, uint32_t color) + void Overlay::strokeClosed(const std::vector>& p, float width, uint32_t color, bool closed) { const size_t n = p.size(); if (n < 2 || width <= 0) return; use(nullptr); - const auto o = outward(p); + const auto o = outward(p, closed); const float pixels = width * m_scale, soft = 0.5f / m_scale; const uint32_t peak = pixels < 1 ? scaled(color, pixels) : color; const float edge = width / 2 + soft, solid = std::max(width / 2 - soft, 0.0f); const auto strip = [&](float t0, uint32_t c0, float t1, uint32_t c1) { - for (size_t i = 0; i < n; ++i) + for (size_t i = 0; i + (closed ? 0 : 1) < n; ++i) { const size_t j = (i + 1) % n; const float ax = p[i][0] + o[i][0] * t0, ay = p[i][1] + o[i][1] * t0, bx = p[j][0] + o[j][0] * t0, by = p[j][1] + o[j][1] * t0; @@ -392,6 +393,18 @@ namespace oc4::render fillConvex({ { x[0], y[0] }, { x[1], y[1] }, { x[2], y[2] }, { x[3], y[3] } }, premultiplied(color, alpha)); } + void Overlay::polygon(const std::vector>& points, Color color, float alpha) + { + if (m_drawing) + fillConvex(points, premultiplied(color, alpha)); + } + + void Overlay::polyline(const std::vector>& points, Color color, float alpha, float width) + { + if (m_drawing) + strokeClosed(points, width, premultiplied(color, alpha), false); + } + void Overlay::image(uint64_t key, const std::vector& bgra, uint32_t w, uint32_t h, uint64_t version, float x0, float y0, float x1, float y1, float alpha) { diff --git a/src/render/Overlay.h b/src/render/Overlay.h index 41ebda36..ee008901 100644 --- a/src/render/Overlay.h +++ b/src/render/Overlay.h @@ -42,6 +42,10 @@ namespace oc4::render void line(float x0, float y0, float x1, float y1, Color color, float alpha, float width = 1); // A filled four-cornered shape (its corners in order). void quad(const float x[4], const float y[4], Color color, float alpha); + // A filled convex shape (its corners in order), and a line through points (not closed), + // each drawn in one piece (no darker seams where parts meet). + void polygon(const std::vector>& points, Color color, float alpha); + void polyline(const std::vector>& points, Color color, float alpha, float width = 1); // BGRA8 pixels (premultiplied alpha), stretched over the rectangle; `version` tells // when they changed (the bitmap is kept until then). Each picture has its own `key`. void image(uint64_t key, const std::vector& bgra, uint32_t width, uint32_t height, uint64_t version, float x0, float y0, float x1, @@ -112,7 +116,7 @@ namespace oc4::render void vertex(float x, float y, uint32_t color, float u = 0, float v = 0); void pixelVertex(float x, float y, uint32_t color, float u, float v); // (x, y in pixels) void fillConvex(const std::vector>& points, uint32_t color); - void strokeClosed(const std::vector>& points, float width, uint32_t color); + void strokeClosed(const std::vector>& points, float width, uint32_t color, bool closed = true); void flush(); uint32_t premultiplied(Color c, float alpha) const; From 66d7273cec61a6a5b31c552513eebbf4461b10a5 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 07:02:09 +0100 Subject: [PATCH 44/89] Options Audio tab as the original's: theme sliders, speakers, own music folder - Sliders are the theme's (GFC_Control_StandardSlider_Style): track, the light blue fill on the side the control flag names (CF_SLIDER_FILL_DOWN / _UP), and the grip, which follows the mouse while held (NOTIFY_SLIDER_NEWSTOP to the script at each new stop). They were a stack of little check boxes. No click sound, as the original's. - Audio Speakers lists the original's 15 setups; the choice is kept, Mono plays both sides the same. - Custom Music Folder: Browse opens the system's folder dialog; ticked, the folder's MP3 and WAV files play instead of the era's soundtrack, at once. - Voice chat (the original's GameSpy voice) is shown with the system's devices but disabled, with a tool tip saying OpenCiv4 does not implement it. - The path box gets the row's width as the original's; an edit box's text is kept inside it. - --keys "" drags with the left button (for scripted checks). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 40 +++++++- apps/oc4core/Sounds.cpp | 93 ++++++++++++++++- apps/oc4core/Sounds.h | 5 + apps/oc4core/main.cpp | 11 +- apps/oc4core/python/oc4options.py | 161 ++++++++++++++++++++++-------- apps/oc4core/python/oc4screens.py | 40 +++++++- src/audio/Audio.h | 5 + src/audio/Device.cpp | 25 +++++ src/render/MapWindow.cpp | 51 +++++++++- src/render/MapWindow.h | 10 ++ src/render/UiLayer.cpp | 56 ++++++++++- src/render/UiLayer.h | 7 ++ 12 files changed, 450 insertions(+), 54 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index efe18e86..5ee80e3d 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -46,6 +46,10 @@ namespace oc4::host { namespace { + // A folder the options screen asked the player for (its Browse...: the system's folder + // dialog, from there), until the window opens it. + std::optional g_folderRequest; + std::wstring toWide(py::handle o) { PyObject* p = o.ptr(); @@ -324,6 +328,12 @@ namespace oc4::host if (const PlayerTypes active = GC.getGame().getActivePlayer(); active != NO_PLAYER && victory >= 0) CvMessageControl::getInstance().sendLaunch(active, static_cast(victory)); }); + // (the options' Audio tab: the speakers, the player's own music, the system's sound devices, + // a folder chosen in the system's dialog: oc4options.folderChosen hears it) + host.def("set_mono", [](bool mono) { Sounds::setMono(mono); }); + host.def("set_music_folder", [](const std::string& folder) { Sounds::setMusicFolder(folder); }); + host.def("audio_devices", [](bool recording) { return audio::deviceNames(recording); }); + host.def("choose_folder", [](const std::string& start) { g_folderRequest = start; }); host.def("set_volumes", [](std::vector volumes) { float v[6] = { 1, 1, 1, 1, 1, 1 }; for (size_t i = 0; i < 6 && i < volumes.size(); ++i) @@ -1216,7 +1226,7 @@ if _walls: info.checkbox = item.kind == Kind::CheckBox; if (item.kind == Kind::Movie) info.movie = item.texture; - if ((item.kind == Kind::Bar || item.kind == Kind::Scrollbar) && t.size() >= 25) + if ((item.kind == Kind::Bar || item.kind == Kind::Scrollbar || item.kind == Kind::Slider) && t.size() >= 25) { item.barStart = t[23].cast(); item.barPercent = t[24].cast(); @@ -1260,7 +1270,7 @@ if _walls: } const bool buttonLike = item.kind == Kind::ImageButton || item.kind == Kind::Button || item.kind == Kind::CheckBox || item.kind == Kind::Dropdown || item.kind == Kind::EndTurnButton || item.kind == Kind::Cell || item.kind == Kind::Scrollbar || - item.kind == Kind::Edit; + item.kind == Kind::Edit || item.kind == Kind::Slider; // (a text, setText, is clicked as a button is: the scripts' "EXIT"s are texts) item.mainInterface = !m_menu && info.screen == m_mainId; item.interactive = hitTest != HITTEST_NOHIT && (buttonLike || item.kind == Kind::Text || item.kind == Kind::Movie || (info.widget >= 0 && info.widget != WIDGET_GENERAL) || @@ -1294,6 +1304,17 @@ if _walls: { printPythonError(e); } + if (g_folderRequest) + window.chooseFolder(*std::exchange(g_folderRequest, std::nullopt)); + if (const auto folder = window.takeChosenFolder()) + try + { + py::module_::import("oc4options").attr("folderChosen")(*folder); + } + catch (py::error_already_set& e) + { + printPythonError(e); + } for (const std::string& file : window.takeMoviesDone()) if (const auto it = std::ranges::find(m_items, file, &Item::movie); it != m_items.end()) scriptInput(*it, kMovieDone, 0, 0, false, false, false, false); @@ -1313,6 +1334,8 @@ if _walls: } else if (size_t(click.item) < m_items.size()) { + if (click.x >= 0) + m_mouse = { click.x, click.y }; // (a slider's: where the mouse was then) if (std::getenv("OC4_PLAY_LOG")) std::printf(" mouse on %d/%s/%d\n", m_items[size_t(click.item)].screen, m_items[size_t(click.item)].name.c_str(), m_items[size_t(click.item)].part); this->click(m_items[size_t(click.item)], click.right, click.shift, click.ctrl, click.alt); @@ -1365,6 +1388,19 @@ if _walls: screens.attr("sortBy")(it.screen, it.name, it.part); return; } + if (it.kind == "slider") + { + // A slider: set to the stop nearest the mouse (pressed or dragged there); its script hears + // NOTIFY_SLIDER_NEWSTOP with the stop when it changes. No sound: the original's sliders + // make none. + constexpr int kSliderNewStop = 18; + screens.attr("closeDropdown")(); + if (right) + return; + if (const py::object stop = screens.attr("sliderTo")(it.screen, it.name, m_mouse.first, m_mouse.second); !stop.is_none()) + scriptInput(it, kSliderNewStop, stop.cast(), 0, false, shift, ctrl, alt); + return; + } if (it.kind == "scrollbar") { // A scroll bar: what it scrolls moves so that its grip is under the mouse. diff --git a/apps/oc4core/Sounds.cpp b/apps/oc4core/Sounds.cpp index 5407165d..9bdd9c74 100644 --- a/apps/oc4core/Sounds.cpp +++ b/apps/oc4core/Sounds.cpp @@ -10,6 +10,8 @@ #include #include #include +#include +#include #include #include #include @@ -32,6 +34,28 @@ namespace oc4::host // The player's volumes (the options' sliders, 0..1): master, music, effects, speech, // ambience, interface. std::atomic g_volumes[6] = { 1, 1, 1, 1, 1, 1 }; + std::atomic g_mono = false; + std::mutex g_folderMutex; + std::string g_musicFolder; // (the player's own music; empty: the era's) + std::atomic g_folderChanges = 0; + + // The music files of a folder (MP3, WAV), by name. + std::vector musicFiles(const std::string& folder) + { + std::vector out; + std::error_code ec; + if (folder.empty() || !std::filesystem::is_directory(folder, ec)) + return out; + for (const auto& e : std::filesystem::directory_iterator(folder, ec)) + { + std::string ext = e.path().extension().string(); + std::ranges::transform(ext, ext.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + if ((ext == ".mp3" || ext == ".wav") && e.is_regular_file(ec)) + out.push_back(e.path().string()); + } + std::ranges::sort(out); + return out; + } float userGain(Kind k) { switch (k) @@ -110,6 +134,9 @@ namespace oc4::host bool loop = false, era = false, intro = false; }; std::optional pending; + // The player's own music (the options' Custom Music Folder): its files, as last read. + std::vector ownTracks; + int folderChanges = 0; std::optional> talk; // (intro, loop) while talking bool introDone = false; Clock::time_point nextTrack{}, lastUpdate{}; @@ -283,10 +310,26 @@ namespace oc4::host auto it = loading.find(file); if (it == loading.end()) { - const auto loc = assets.locate(file); - if (!loc) - return cache[file] = nullptr; - auto bytes = std::make_shared>(assets.read(*loc)); + std::shared_ptr> bytes; + if (std::filesystem::path(file).is_absolute()) + { + // (the player's own music, from their folder) + std::ifstream in(std::filesystem::path(file), std::ios::binary); + if (!in) + return cache[file] = nullptr; + bytes = std::make_shared>(); + in.seekg(0, std::ios::end); + bytes->resize(size_t(in.tellg())); + in.seekg(0); + in.read(reinterpret_cast(bytes->data()), std::streamsize(bytes->size())); + } + else + { + const auto loc = assets.locate(file); + if (!loc) + return cache[file] = nullptr; + bytes = std::make_shared>(assets.read(*loc)); + } it = loading.emplace(file, std::async(std::launch::async, [bytes, file]() -> PcmPtr { std::string error; auto pcm = audio::decode(*bytes, &error); @@ -449,6 +492,16 @@ namespace oc4::host } if (now < nextTrack) return; + if (!ownTracks.empty()) + { + // (the player's own music instead of the era's, one after another in no order) + std::vector choices = ownTracks; + if (choices.size() > 1) + std::erase(choices, lastTrack); + lastTrack = choices[std::uniform_int_distribution(0, choices.size() - 1)(rng)]; + pending = Pending{ lastTrack, lastTrack, kindGain(Kind::Music), false, true, false }; + return; + } const AudioScripts::Soundtracks* tracks = scripts.soundtracks(eraType); if (!tracks || tracks->scripts.empty()) return; @@ -600,10 +653,42 @@ namespace oc4::host g_volumes[i] = std::clamp(volumes[i], 0.0f, 1.0f); } + void Sounds::setMono(bool mono) { g_mono = mono; } + + void Sounds::setMusicFolder(const std::string& folder) + { + { + const std::lock_guard lock(g_folderMutex); + if (folder == g_musicFolder) + return; + g_musicFolder = folder; + } + ++g_folderChanges; + } + void Sounds::update(const Listener& listener, const std::string& eraType) { if (!m->started || !m->device->ok()) return; + m->device->setMono(g_mono); + if (const int changes = g_folderChanges; changes != m->folderChanges) + { + // Another folder of the player's own music (or none): the era's track playing makes way + // at once, faded out, for the next from the new choice. + m->folderChanges = changes; + std::string folder; + { + const std::lock_guard lock(g_folderMutex); + folder = g_musicFolder; + } + m->ownTracks = musicFiles(folder); + m->lastTrack.clear(); + if (m->pending && m->pending->era) + m->pending.reset(); + if (m->music && m->musicIsEra) + m->fadingOut = true; + m->nextTrack = Clock::now(); + } if (const float master = m->muted ? 0.0f : float(g_volumes[0]); master != m->master) { m->master = master; diff --git a/apps/oc4core/Sounds.h b/apps/oc4core/Sounds.h index 03b9352d..477b5646 100644 --- a/apps/oc4core/Sounds.h +++ b/apps/oc4core/Sounds.h @@ -60,6 +60,11 @@ namespace oc4::host // Any thread: the player's volumes, 0..1 (the options screen's: master, music, effects, // speech, ambience, interface; a kind "no sound": 0). static void setVolumes(const float volumes[6]); + // Any thread: the player's speakers (Mono: both sides the same), and their own music + // (the options' Custom Music Folder: its MP3 and WAV files instead of the era's + // soundtrack; empty: the soundtrack). A new folder ends the track playing. + static void setMono(bool mono); + static void setMusicFolder(const std::string& folder); // The window's thread, each frame: where the camera looks (plot units) and from how far // (plots), the active player's era (its type, "ERA_ANCIENT") for the soundtrack. diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..4269e1ea 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -31,7 +31,7 @@ // opens it, Esc closes it), or with --own-interface the window's simple one. // --keys are typed in on your turns then (letters and Space as keys, '^', '@' and '+' before // one hold Ctrl, Alt and Shift, '>' ends the turn, '~' is Esc, "(x,y)" right clicks that plot, -// "[x,y]" left clicks it, "%u", "%d", "%l", "%r", "%e", "%t" and "%b" type an arrow, Return, Tab or Backspace into the window, "" clicks that pixel of the window (a figure there: its unit), "#n" picks the n-th button of the popup up (OK if it has none), a +// "[x,y]" left clicks it, "%u", "%d", "%l", "%r", "%e", "%t" and "%b" type an arrow, Return, Tab or Backspace into the window, "" clicks that pixel of the window (a figure there: its unit), "" drags from one to the other with the left button, "#n" picks the n-th button of the popup up (OK if it has none), a // popup nothing answers gets its first, 'text' goes into its next edit box, "{Name}" or // "{Name/part}" clicks the interface's widget so named, "^{Name}" with Ctrl held, "?{Name}" rests // the mouse on it); with @@ -1169,6 +1169,15 @@ namespace clicks.push_back(click); script.erase(0, close + 1); } + else if (int px = 0, py = 0, qx = 0, qy = 0; script.front() == '<' && script.find('>') != std::string::npos && + std::sscanf(script.c_str() + 1, "%d,%d:%d,%d", &px, &py, &qx, &qy) == 4) + { + // "": the left button pressed at x,y, the mouse moved to x2,y2 and let go (a drag). + if (log) + std::printf(" drag %d,%d to %d,%d\n", px, py, qx, qy); + window.mouseDrag(px, py, qx, qy); + script.erase(0, script.find('>') + 1); + } else if (int px = 0, py = 0; script.front() == '<' && script.find('>') != std::string::npos && std::sscanf(script.c_str() + 1, "%d,%d", &px, &py) == 2) { // "": a left click at that pixel of the window, on what is there (a popup, the diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index dd7e1664..8371c0b9 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -21,6 +21,17 @@ # ---------------------------------------------------------------- the profile _VOLUME_STOPS = 20 +# The speaker setups the original offers (Miles': its names, the first four by text key, as the +# original's getSpeakerConfigFromList gives them). On macOS the sound goes out as the system has +# it set; Mono makes both sides the same. +_SPEAKERS = ('TXT_KEY_OPTION_SOUND_MONO', 'TXT_KEY_OPTION_SOUND_STEREO', 'TXT_KEY_OPTION_SOUND_SYSTEM_CONFIG', 'TXT_KEY_OPTION_SOUND_HEADPHONES', + 'Dolby Surround', 'SRS Circle Surround', '4.0 Discrete', '5.1 Discrete', '6.1 Discrete', '7.1 Discrete', '8.1 Discrete', 'DirectSound 3D', + 'EAX 2.0', 'EAX Advanced HD 3.0', 'EAX Advanced HD 4.0') +_SPEAKERS_DEFAULT = 'TXT_KEY_OPTION_SOUND_SYSTEM_CONFIG' +# The voice chat's controls: the original's is GameSpy's multiplayer voice, which OpenCiv4 has not; +# they show as the original's, the system's own devices in them, but cannot be used. +_VOICE_CONTROLS = ('VoiceChatCheckbox', 'CaptureDeviceDropdownBox', 'PlaybackDeviceDropdownBox', 'CaptureVolumeSlider', 'PlaybackVolumeSlider') +_VOICE_TIP = u'OpenCiv4 does not implement voice chat.' _VOLUMES = ('Master', 'Music', 'SoundEffects', 'Speech', 'Ambience', 'Interface') _UI_SCALES = (0, 100, 125, 150, 200) # the resolution's choices: the interface's scale, 0 the window's own @@ -46,7 +57,7 @@ def _scales(): 'player': {}, 'clock': False, 'hours24': False, 'graphicsLevel': 0, 'renderQuality': 0, 'globeView': 0, 'movieQuality': 0, 'mainMenu': 0, 'antiAliasing': 0, 'uiScale': 0, - 'speakers': '', 'musicPath': '', 'voice': False, + 'speakers': '', 'musicPath': '', 'voice': False, 'captureVolume': 67, 'playbackVolume': 67, 'wasdPan': False, 'autoEndTurn': False, 'edgeScroll': True, } @@ -89,7 +100,7 @@ def _load(): _profile[parts[0]][int(parts[1])] = value == '1' elif parts[0] in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): _profile[parts[0]] = value == '1' - elif parts[0] in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale'): + elif parts[0] in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale', 'captureVolume', 'playbackVolume'): _profile[parts[0]] = int(value) elif parts[0] in ('name', 'speakers', 'musicPath'): _profile[parts[0]] = value @@ -117,7 +128,7 @@ def _save(): lines.append('%s=%s' % (key, _profile[key])) for key in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): lines.append('%s=%d' % (key, 1 if _profile[key] else 0)) - for key in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale'): + for key in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale', 'captureVolume', 'playbackVolume'): lines.append('%s=%d' % (key, _profile[key])) for v in _VOLUMES: lines.append('volume.%s=%d' % (v, _profile['volume'][v])) @@ -284,10 +295,46 @@ def _applyVolumes(): gains.append(g) try: oc4host.set_volumes(gains) + oc4host.set_mono(_profile['speakers'] == _SPEAKERS[0]) + oc4host.set_music_folder(_profile['musicPath']) except Exception: pass +_deviceCache = {} + + +def _devices(recording): + """The system's microphones or outputs, by name (asked once a showing of the screen).""" + if recording not in _deviceCache: + try: + _deviceCache[recording] = [n.decode('utf-8', 'replace') if isinstance(n, str) else n for n in oc4host.audio_devices(recording)] + except Exception: + _deviceCache[recording] = [] + return _deviceCache[recording] + + +def _deviceName(recording, i): + names = _devices(recording) + return names[int(i)] if 0 <= int(i) < len(names) else u'' + + +def folderChosen(path): + """The folder the player chose in the system's dialog (Browse...): in the path box with Custom + Music Folder ticked (the game's own updateMusicPath), and kept: their music plays from there.""" + if not path: + return + try: + import CvScreensInterface + CvScreensInterface.updateMusicPath((path.decode('utf-8', 'replace') if isinstance(path, str) else path,)) + except Exception: + import traceback + traceback.print_exc() + _profile['musicPath'] = path + _save() + _applyVolumes() + + class _UserProfile(object): """CyUserProfile: the player's options (one profile, the host's file).""" @@ -383,23 +430,37 @@ def setPlayerOption(self, i, b): def getVolumeStops(self): return _VOLUME_STOPS def recalculateAudioSettings(self): _applyVolumes() def getMusicPath(self): return _profile['musicPath'] - def setMusicPath(self, s): _profile['musicPath'] = str(s) - def musicPathDialogBox(self): pass - def getSpeakerConfig(self): return _profile['speakers'] - def setSpeakerConfig(self, s): _profile['speakers'] = str(s) - def getSpeakerConfigFromList(self, i): return '' - def useVoice(self): return _profile['voice'] - def setUseVoice(self, b): _profile['voice'] = bool(b) - def getNumCaptureDevices(self): return 0 - def getNumPlaybackDevices(self): return 0 + def setMusicPath(self, s): _profile['musicPath'] = str(s); _save(); _applyVolumes() + def musicPathDialogBox(self): + # (the system's folder dialog; the folder chosen comes back to folderChosen) + try: + import os + oc4host.choose_folder(_profile['musicPath'] or os.path.expanduser('~/Music')) + except Exception: + pass + def getSpeakerConfig(self): return _profile['speakers'] or _SPEAKERS_DEFAULT + def setSpeakerConfig(self, s): + if str(s) in _SPEAKERS: + _profile['speakers'] = str(s) + _save() + _applyVolumes() + def getSpeakerConfigFromList(self, i): return _SPEAKERS[int(i)] if 0 <= int(i) < len(_SPEAKERS) else '' + def useVoice(self): return False + def setUseVoice(self, b): pass + def getNumCaptureDevices(self): return len(_devices(True)) + def getNumPlaybackDevices(self): return len(_devices(False)) def getCaptureDeviceIndex(self): return 0 def getPlaybackDeviceIndex(self): return 0 - def getCaptureDeviceDesc(self, i): return '' - def getPlaybackDeviceDesc(self, i): return '' - def getCaptureVolume(self): return 0 - def getPlaybackVolume(self): return 0 - def getMaxCaptureVolume(self): return 0 - def getMaxPlaybackVolume(self): return 0 + def getCaptureDeviceDesc(self, i): return _deviceName(True, i) + def getPlaybackDeviceDesc(self, i): return _deviceName(False, i) + def setCaptureDevice(self, i): pass + def setPlaybackDevice(self, i): pass + def getCaptureVolume(self): return _profile['captureVolume'] + def getPlaybackVolume(self): return _profile['playbackVolume'] + def setCaptureVolume(self, i): _profile['captureVolume'] = max(0, min(100, int(i))) + def setPlaybackVolume(self, i): _profile['playbackVolume'] = max(0, min(100, int(i))) + def getMaxCaptureVolume(self): return 100 + def getMaxPlaybackVolume(self): return 100 # the clock def isClockOn(self): return _profile['clock'] @@ -461,6 +522,7 @@ class CyGTabCtrl(object): def __init__(self, szName='', bStatic=False, bCloseButton=False): self._title = _text(szName) + _deviceCache.clear() # (the system's sound devices asked again, as the screen is made) self._nodes = {} # id: node self._byName = {} # name: the last node so named (some names are used again in other forms) self._tabs = [] # (form node, label) @@ -670,7 +732,7 @@ def _screen(): # 28 and the gap 3; a box's children are as wide as they need, and what is left goes to those that # expand (LAYOUT_SIZE_HEXPANDING) or, in a column, to its spacers (the Language row at the panel's # foot); a row with LAYOUT_HCENTER is centred (Restore Defaults and Exit). -_ROW = {'label': 28, 'checkbox': 28, 'radio': 28, 'dropdown': 28, 'button': 31, 'edit': 26, 'hslider': 18, 'hsep': 10, +_ROW = {'label': 28, 'checkbox': 28, 'radio': 28, 'dropdown': 28, 'button': 31, 'edit': 26, 'hslider': 28, 'hsep': 10, 'spacer': 8, 'image': 4, 'vsep': 0} _GAP = 3 _PAD = 8 @@ -697,7 +759,7 @@ def _pad(n): def _hgrow(n): - return 'LAYOUT_SIZE_HEXPANDING' in n.flags or 'LAYOUT_SIZE_HPREFERREDEXPANDING' in n.flags + return 'LAYOUT_SIZE_HEXPANDING' in n.flags or 'LAYOUT_SIZE_HPREFERREDEXPANDING' in n.flags or 'LAYOUT_SIZE_HFIXEDEXPANDING' in n.flags def _vgrow(n): @@ -717,6 +779,8 @@ def _natural(n): return max([_width(i) for i in n.items] or [40]) + 36 if k in ('spacer', 'vsep'): return 12 + if k == 'hslider': + return 210 # (the original's voice volume sliders) if k in ('vbox', 'scroll', 'panel'): widths = [_natural(c) for c in n.children] if None in widths: @@ -735,7 +799,7 @@ def _height(n, w): if k in _ROW: return _ROW[k] if k == 'vslider': - return 4 * (n.maximum - n.minimum + 1) + 4 + return 92 # (the original's volume sliders' height) if k == 'hbox': start, widths = _shares(n, w) return max([_height(c, cw) for c, cw in zip(n.children, widths)] or [0]) @@ -763,6 +827,18 @@ def _shares(n, w): return 0, natural return (extra / 2 if 'LAYOUT_HCENTER' in n.flags else 0), natural fixed = dict((c.id, 12) for c in n.children if c.kind in ('vsep', 'spacer')) + if 'LAYOUT_SIZE_HPREFERREDEXPANDING' in n.flags: + # (a row at its preferred size: who knows their width keep it, the rest share what is left; + # the Audio tab's voice column, the speakers and music the rest) + for c, nat in zip(n.children, natural): + if nat is not None and c.kind not in ('vsep', 'spacer'): + fixed[c.id] = nat + if any(_hgrow(c) for c in n.children) or 'LAYOUT_SIZE_HFIXEDEXPANDING' in n.flags: + # (beside one that expands, a check box or a button is as wide as it needs: the Custom Music + # Folder row, its path box the rest) + for c, nat in zip(n.children, natural): + if c.kind in ('checkbox', 'button') and nat is not None: + fixed[c.id] = nat if len(n.children) > 1: for c in n.children: if c.kind == 'label' and 'CF_LABEL_DEFAULTSIZE' in c.flags: @@ -833,24 +909,17 @@ def _place(screen, n, x, y, w, h): for i, item in enumerate(n.items): screen.addPullDownString(name, item, i, i, i == int(n.value)) elif k in ('hslider', 'vslider'): - # (its stops, each a little button: the slider set to the one clicked) - stops = n.maximum - n.minimum + 1 - for s in range(stops): - value = n.minimum + s - if k == 'hslider': - size = max(3, min(10, (w - 4) / max(1, stops) - 1)) - bx, by, bw, bh = x + s * (size + 1), y + 2, size, 14 - on = value <= int(n.value) - else: - bx, by, bw, bh = x + 8, y + 2 + s * 4, 40, 3 - on = value >= int(n.value) - bname = 'OptSlider%d' % (n.id * 1000 + s) - screen.addCheckBoxGFC(bname, '', '', bx, by, bw, bh, general, -1, -1, '') - b = screen._s.get(bname) - if b is not None: - b.state = on + # (the theme's slider: its fill on the side its control flag names, CF_SLIDER_FILL_UP / _DOWN) + screen.addSlider(name, x, y, w, h, int(n.value), n.minimum, n.maximum, general, -1, -1, k == 'vslider') + screen.setSliderFill(name, 'down' if 'CF_SLIDER_FILL_DOWN' in n.flags else 'up' if 'CF_SLIDER_FILL_UP' in n.flags else '') elif k == 'hsep': screen.addPanel(name, u'', u'', True, False, x, y + 4, w, 2, _cpe.PanelStyles.PANEL_STYLE_MAIN) + if n.name in _VOICE_CONTROLS: + # (voice chat: shown as the original's, not to be used) + for part in (name, name + 'L'): + w_ = screen._s.get(part) + if w_ is not None: + w_.enabled, w_.help = False, _VOICE_TIP def resized(): @@ -865,6 +934,13 @@ def relayout(): return _state['dirty'] = False ctrl = _state['ctrl'] + if ctrl is not None: + # (what was typed into the edit boxes stays: they are made again) + for n in ctrl._nodes.values(): + if n.kind == 'edit': + w_ = _screen()._s.get('OptW%d' % n.id) + if w_ is not None: + n.text = w_.text oc4screens.reset(OPTIONS) if ctrl is None or not ctrl._shown or not ctrl._tabs: oc4screens.hide(OPTIONS) @@ -943,13 +1019,6 @@ def handleInput(args): ctrl._tab = ident _schedule() return 1 - if function == 'OptSlider' and notify == 0: - n = ctrl._nodes.get(ident / 1000) - if n is not None: - n.value = n.minimum + ident % 1000 - _call(n, (int(n.value), n.callback[2] if n.callback else n.name)) - _schedule() - return 1 if function != 'OptW': return 0 n = ctrl._nodes.get(ident) @@ -965,6 +1034,10 @@ def handleInput(args): elif n.kind == 'button' and notify == 0: _call(n, n.callback[2] if n.callback else n.name) _schedule() + elif n.kind in ('hslider', 'vslider') and notify == 18: + # (NOTIFY_SLIDER_NEWSTOP: the slider pressed or dragged to another stop; it shows it already) + n.value = int(data) + _call(n, (int(data), n.callback[2] if n.callback else n.name)) elif n.kind == 'dropdown' and notify == 11: n.value = int(data) _call(n, (int(data), n.callback[2] if n.callback else n.name)) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..201d35b7 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -31,6 +31,7 @@ _drop = [None, 0] # the pull down whose list is open (file id, name), and how far that list is scrolled _areas = [] # what scrolls under the mouse, back to front: (x0, y0, x1, y1, file id, name, step, down, sideways) _bars = {} # the scroll bars: (file id, name, part) -> (x0, y0, x1, y1) +_sliders = {} # the sliders: (file id, name) -> (x0, y0, x1, y1) _dropRects = {} # where each pull down is: (file id, name) -> (x0, y0, x1, y1) _editFocus = [None] # the edit box typed into: (file id, name), or None @@ -88,7 +89,8 @@ class _Widget(object): __slots__ = ('name', 'kind', 'parent', 'mode', 'x', 'y', 'z', 'w', 'h', 'style', 'pstyle', 'text', 'help', 'tex', 'tex2', 'wt', 'd1', 'd2', 'opt', 'flags', 'font', 'shown', 'enabled', 'state', 'hittest', 'seq', 'vertical', 'scroll', 'children', 'bars', 'lists', 'columns', 'rows', 'headers', 'iconw', 'iconh', 'items', 'selected', 'color', 'size', 'defw', 'defh', 'points', - 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed') + 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed', + 'minimum', 'maximum', 'value', 'upright', 'fill') def __init__(self, name, kind): self.name = name @@ -115,6 +117,7 @@ def __init__(self, name, kind): self.children = [] self.maxChars = 0 # an edit box's: at most this many characters (0: any) self.allowed = None # ... and only these (None: any) + self.minimum, self.maximum, self.value, self.upright, self.fill = 0, 0, 0, False, '' # a slider's stops, where it is, its fill's side self.bars = None # stacked bars: [[percent, (r, g, b, a)], ...] self.lists = None # multi lists: [[(texture, wt, d1, d2, option, disabledTexture), ...], ...] self.columns = None # tables: [[header, width, right], ...] @@ -1269,6 +1272,15 @@ def setEditBoxTextColor(self, *args): pass def addSlider(self, szName, iX, iY, iWidth, iHeight, iDefault, iMin, iMax, eWidgetType=-1, iData1=-1, iData2=-1, bIsVertical=False): w = self._s.add(szName, 'slider') w.x, w.y, w.w, w.h, w.size = int(iX), int(iY), int(iWidth), int(iHeight), int(iDefault) + w.minimum, w.maximum, w.value, w.upright, w.fill = int(iMin), int(iMax), int(iDefault), bool(bIsVertical), '' + w.wt, w.d1, w.d2 = int(eWidgetType), int(iData1), int(iData2) + + def setSliderFill(self, szName, szFill): + """(openciv4's: the side of its grip the slider's fill is on, as the CF_SLIDER_FILL_UP / + _DOWN control flags: 'up' the top or left, 'down' the bottom or right, '' none)""" + w = self._s.get(szName) + if w is not None: + _set(w, 'fill', _str(szFill)) # ---------------------------------------------------------------- lines @@ -1660,6 +1672,14 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): out.append((base + (-1,), 'line', ox + x0, oy + y0, ox + x1, oy + y1, clip, '', u'', '', '', 0, 0, False, True, 4, w.color, -1, -1, -1, False, w.z, w.seq)) return + if kind == 'slider': + # (the theme's slider: its grip as far along it as its stop; it follows the mouse, sliderTo) + _sliders[(s.id, w.name)] = (x, y, x + width, y + height) + span = max(1, w.maximum - w.minimum) + at = float(max(w.minimum, min(w.maximum, w.value)) - w.minimum) / span + out.append((base + (-1,), 'slider', x, y, x + width, y + height, clip, ('v ' if w.upright else 'h ') + w.fill, u'', '', '', 0, 0, False, + w.enabled, w.hittest, None, w.wt, w.d1, w.d2, w.opt, w.z, w.seq, at, 0.0)) + return if kind == 'bar': start = 0.0 for i, (pct, color) in enumerate(w.bars): @@ -1725,6 +1745,7 @@ def display(): del _areas[:] _dropRects.clear() _bars.clear() + _sliders.clear() for s in sorted(_screens.values(), key=lambda s: (not s.main, s.id)): if not (s.main or s.shown): continue @@ -1843,6 +1864,23 @@ def scrollTo(fileId, name, part, x, y): _set(w, 'hoffset', int(max(0, min(w.hextent - wide, at * w.hextent - wide / 2)))) +def sliderTo(fileId, name, x, y): + """A slider pressed or dragged: set to the stop nearest the mouse (its grip, 14 long, kept + within it, as drawn); the stop when that is another one, else None.""" + r = _sliders.get((int(fileId), _str(name))) + s = _screens.get(int(fileId)) + w = s.get(name) if s is not None else None + if r is None or w is None or not w.enabled: + return None + start, length, at = (r[1], r[3] - r[1], y) if w.upright else (r[0], r[2] - r[0], x) + f = float(at - start - 7) / max(1, length - 14) + stop = w.minimum + int(round(max(0.0, min(1.0, f)) * (w.maximum - w.minimum))) + if stop == w.value: + return None + _set(w, 'value', stop) + return stop + + def openDropdown(fileId, name): """A click on a pull down opens its list, or closes it when it is open.""" key = (int(fileId), _str(name)) diff --git a/src/audio/Audio.h b/src/audio/Audio.h index 25aa7d87..fa87a6fb 100644 --- a/src/audio/Audio.h +++ b/src/audio/Audio.h @@ -30,6 +30,9 @@ namespace oc4::audio // By its first bytes: a WAVE file or else an MP3. std::optional decode(std::span file, std::string* error = nullptr); + // The names of the system's sound devices: its microphones (recording) or its outputs. + std::vector deviceNames(bool recording); + // The output device. Its calls are the thread's that made it. class Device { @@ -42,6 +45,8 @@ namespace oc4::audio // False without an output device (then nothing plays). bool ok() const; void setMasterVolume(float volume); + // Both sides the same (the player's speakers set to Mono). + void setMono(bool mono); using Voice = uint64_t; // 0: none // Plays the sound from its start: volume as a gain (0..1), pan from -1 (left) to 1, pitch as diff --git a/src/audio/Device.cpp b/src/audio/Device.cpp index 0fb95cf7..a8f2e3b8 100644 --- a/src/audio/Device.cpp +++ b/src/audio/Device.cpp @@ -2,9 +2,11 @@ #include #include +#include #include #include +#include #include #include #include @@ -32,6 +34,7 @@ namespace oc4::audio std::unordered_map voices; Voice next = 1; std::vector mix; + std::atomic mono{ false }; // (the player's speakers: one, both sides the same) static void route(Playing& p, float volume, float pan) { @@ -85,10 +88,30 @@ namespace oc4::audio return; d.mix.resize(size_t(frames) * 2); d.render(d.mix.data(), frames); + if (d.mono) + for (int f = 0; f < frames; ++f) + d.mix[size_t(f) * 2] = d.mix[size_t(f) * 2 + 1] = (d.mix[size_t(f) * 2] + d.mix[size_t(f) * 2 + 1]) * 0.5f; SDL_PutAudioStreamData(stream, d.mix.data(), frames * int(sizeof(float) * 2)); } }; + std::vector deviceNames(bool recording) + { + std::vector out; + if (!SDL_InitSubSystem(SDL_INIT_AUDIO)) + return out; + int count = 0; + if (SDL_AudioDeviceID* ids = recording ? SDL_GetAudioRecordingDevices(&count) : SDL_GetAudioPlaybackDevices(&count)) + { + for (int i = 0; i < count; ++i) + if (const char* name = SDL_GetAudioDeviceName(ids[i])) + out.emplace_back(name); + SDL_free(ids); + } + SDL_QuitSubSystem(SDL_INIT_AUDIO); + return out; + } + Device::Device() : m(std::make_unique()) { if (!SDL_InitSubSystem(SDL_INIT_AUDIO)) @@ -123,6 +146,8 @@ namespace oc4::audio SDL_SetAudioStreamGain(m->stream, std::max(0.0f, volume)); } + void Device::setMono(bool mono) { m->mono = mono; } + Device::Voice Device::play(std::shared_ptr sound, float volume, float pan, float pitch, bool loop) { if (!m->stream || !sound || sound->samples.empty() || !sound->channels || sound->channels > 2 || !sound->rate) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..75b77b7d 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -19,6 +19,7 @@ #include "render/Input.h" #include "media/Movie.h" +#include #include #include #include @@ -32,6 +33,7 @@ #include #include +#include #include #include #include @@ -250,6 +252,9 @@ namespace oc4::render } std::vector uiClicks; bool downOnUi = false; + bool sliderDrag = false; // (the left button held on a slider: it follows the mouse) + std::mutex folderMutex; // (the folder dialog answers on a thread of its own) + std::optional chosenFolder; std::pair helpPlot{ -1, -1 }; bool helpCombat = false; // (plotHelpText was asked with the right button held: the odds of an attack there) std::wstring plotHelpText; @@ -1128,7 +1133,12 @@ namespace oc4::render mouseY = y; popup.hover(x, y); ui.hover(x, y); - if (minimapDrag) + if (sliderDrag) + { + if (const int item = ui.pressed(); item >= 0) + uiClicks.push_back({ item, false, false, false, false, x, y }); + } + else if (minimapDrag) jumpFromMinimap(std::clamp(x, int(minimapRect[0]), int(minimapRect[2])), std::clamp(y, int(minimapRect[1]), int(minimapRect[3]))); else if (panning) { @@ -1181,6 +1191,21 @@ namespace oc4::render { downOnUi = true; ui.press(x, y, !left); + // (a slider is set where it is pressed, and follows the mouse while held) + if (const int item = ui.pressed(); left && item >= 0 && ui.items()[size_t(item)].kind == UiItem::Kind::Slider && + ui.items()[size_t(item)].enabled) + { + sliderDrag = true; + SDL_CaptureMouse(true); + uiClicks.push_back({ item, false, mods.shift, mods.ctrl, mods.alt, x, y }); + } + return; + } + if (!down && std::exchange(sliderDrag, false)) + { + SDL_CaptureMouse(false); + downOnUi = false; + ui.release(x, y, mods.shift, mods.ctrl, mods.alt); return; } if (!down && std::exchange(downOnUi, false)) @@ -2536,6 +2561,15 @@ namespace oc4::render m->onButton(false, false, x, y); } + void MapWindow::mouseDrag(int x0, int y0, int x1, int y1, int steps) + { + m->onMouseMove(x0, y0); + m->onButton(true, true, x0, y0); + for (int i = 1; i <= steps; ++i) + m->onMouseMove(x0 + (x1 - x0) * i / steps, y0 + (y1 - y0) * i / steps); + m->onButton(true, false, x1, y1); + } + std::optional MapWindow::clickAt(int x, int y, bool right) const { const auto figure = m->figureUnder(x, y); @@ -2612,6 +2646,21 @@ namespace oc4::render MapWindow::UiDisplay MapWindow::uiDisplay() const { return { m->renderer->width(), m->renderer->height(), m->windowDensity() }; } bool MapWindow::uiActive() const { return m->ui.active(); } std::vector MapWindow::takeUiClicks() { return std::exchange(m->uiClicks, {}); } + void MapWindow::chooseFolder(const std::string& start) + { + SDL_ShowOpenFolderDialog( + [](void* self, const char* const* files, int) { + auto& impl = *static_cast(self); + const std::lock_guard lock(impl.folderMutex); + impl.chosenFolder = files && files[0] ? std::string(files[0]) : std::string(); + }, + m.get(), m->window, start.empty() ? nullptr : start.c_str(), false); + } + std::optional MapWindow::takeChosenFolder() + { + const std::lock_guard lock(m->folderMutex); + return std::exchange(m->chosenFolder, std::nullopt); + } void MapWindow::setUiTextFocus(bool focus) { m->uiTextFocus = focus; } std::wstring MapWindow::takeUiTyped() { return std::exchange(m->uiTyped, {}); } void MapWindow::typeText(const std::string& utf8) diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..79512750 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -224,6 +224,9 @@ namespace oc4::render float alpha = 1; float barStart = 0, barPercent = 0; // (a scroll bar's: where its grip starts, how long it is, as parts of it) bool barLast = false; // a stacked bar's last part (its rim goes over them all) + // A slider (style "v" or "h", then "down"/"up" for the side the theme's fill is on): + // barStart is where its grip is along it (0 top / left .. 1); it follows the mouse + // while held. // A leader's head: its art (texture the NIF, texture2 the KFM, and the background // KFM), its button where the art cannot be drawn, its attitude (AttitudeTypes), the // gesture last asked of it (LeaderheadAction) and how many have been asked. @@ -333,8 +336,13 @@ namespace oc4::render { int item = -1; // -1: on the screens but on none of their widgets bool right = false, shift = false, ctrl = false, alt = false; + int x = -1, y = -1; // where the mouse was (a slider's: where it is set to) }; std::vector takeUiClicks(); + // A folder chosen by the player in the system's folder dialog (from `start`), once + // chosen: takeChosenFolder has it then (an empty string: cancelled). + void chooseFolder(const std::string& start); + std::optional takeChosenFolder(); // How wide a text with the screens' markup is, in the theme's font (size 2 outside its // tags), as the scripts measure theirs. // In a widget's font (FontTypes; -1 the theme's size 2, as the scripts measure). @@ -362,6 +370,8 @@ namespace oc4::render // A left click at that pixel as the mouse makes it (scripted tests): on a popup, the // screens, the action bar or the map, whichever takes it there. void mouseClick(int x, int y); + // The left button pressed at x0,y0, the mouse moved to x1,y1 in steps, let go there (a drag). + void mouseDrag(int x0, int y0, int x1, int y1, int steps = 8); // The mouse's cursor over the window: a cursor file (.cur, .ani: the game's res/Cursors); // none, the system's arrow. void setCursorFile(const std::filesystem::path& file); diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..36d99b88 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -80,6 +80,17 @@ namespace oc4::render m_grip[d] = { m_theme.skin(grip, "GFC_CtrlTheme_Bitmap_Control_Button_Skin_Default"), m_theme.skin(grip, "GFC_CtrlTheme_Bitmap_Control_Button_Skin_Rollover") }; } + constexpr std::string_view slider = "GFC_Control_StandardSlider_Style"; + for (size_t d = 0; d < 2; ++d) + { + const std::string track = std::string("GFC_CtrlTheme_Bitmap_Control_Slider_Skin_") + (d == 0 ? "VTrack" : "HTrack"); + m_sliderTrack[d] = { m_theme.skin(slider, track + "_Inner_Default"), m_theme.skin(slider, track + "_Inner_Disable") }; + m_sliderFill[d] = { m_theme.skin(slider, track + "_Fill_Default"), m_theme.skin(slider, track + "_Fill_Disable") }; + const std::string_view grip = d == 0 ? "SF_CtrlTheme_Civ4_Control_Slider_VGripButton_Normal_Style" : "SF_CtrlTheme_Civ4_Control_Slider_HGripButton_Normal_Style"; + m_sliderGrip[d] = { m_theme.skin(grip, "GFC_CtrlTheme_Bitmap_Control_Button_Skin_Default"), + m_theme.skin(grip, "GFC_CtrlTheme_Bitmap_Control_Button_Skin_Rollover"), m_theme.skin(grip, "GFC_CtrlTheme_Bitmap_Control_Button_Skin_Press"), + m_theme.skin(grip, "GFC_CtrlTheme_Bitmap_Control_Button_Skin_Disable") }; + } } // (the screens are made again whenever something on them changes, often between a press // and its release: the item pressed is the same one in the new list, and what is under the @@ -468,6 +479,17 @@ namespace oc4::render } if (it.kind == Kind::Button && it.texture.empty()) o.richText(text, (x0 + x1) / 2, ty, size, false, colour, a, Overlay::Align::Center); + else if (it.kind == Kind::Edit) + { + // (an edit box's text kept inside it: a long path is cut at its right edge) + o.clip(it.clipped ? std::max(x0, it.clip[0]) : x0, it.clipped ? std::max(y0, it.clip[1]) : y0, + it.clipped ? std::min(x1 - 3, it.clip[2]) : x1 - 3, it.clipped ? std::min(y1, it.clip[3]) : y1); + o.richText(text, tx, ty, size, false, colour, a); + if (it.clipped) + o.clip(it.clip[0], it.clip[1], it.clip[2], it.clip[3]); + else + o.unclip(); + } else o.richText(text, tx, ty, size, false, colour, a); o.resetShadow(); @@ -580,8 +602,40 @@ namespace oc4::render o.line(x0, y0 + h / 2, x1, y0 + h / 2, kEdge, 0.5f); break; case Kind::Slider: - o.rect(x0, y0 + h / 2 - 2, x1, y0 + h / 2 + 2, kEdge, 0.6f, 2); + { + // The theme's slider (GFC_Control_StandardSlider_Style): a track 12 thick in the middle + // of its box, its fill from the grip to the side the style names ("down": the bottom + // or the right, "up": the top or the left), and the grip, 28 by 14, where it is set. + const bool down = it.style.starts_with('v'), fillEnd = it.style.find("down") != std::string::npos, + fillStart = it.style.find("up") != std::string::npos; + const size_t d = down ? 0 : 1, off = it.enabled ? 0 : 1; + constexpr float thick = 12, gripLong = 28, gripShort = 14; + const float length = down ? h : w, at = std::clamp(it.barStart, 0.0f, 1.0f); + const float centre = (down ? y0 : x0) + gripShort / 2 + at * std::max(0.0f, length - gripShort); + const float tx0 = down ? (x0 + x1 - thick) / 2 : x0, ty0 = down ? y0 : (y0 + y1 - thick) / 2; + const float tx1 = down ? tx0 + thick : x1, ty1 = down ? y1 : ty0 + thick; + if (!m_sliderTrack[d][off].empty()) + { + Theme::draw(o, m_sliderTrack[d][off], tx0, ty0, tx1, ty1, it.alpha); + if (fillEnd || fillStart) + { + const float f0 = fillEnd ? centre : (down ? ty0 : tx0), f1 = fillEnd ? (down ? ty1 : tx1) : centre; + if (f1 > f0) + Theme::draw(o, m_sliderFill[d][off], down ? tx0 : f0, down ? f0 : ty0, down ? tx1 : f1, down ? f1 : ty1, it.alpha); + } + } + else + o.rect(tx0, ty0, tx1, ty1, kEdge, 0.6f * alpha, 2); + // (the theme's disabled grip is an empty cell: a disabled one is the plain grip, dimmed) + const size_t state = !it.enabled ? 0 : int(i) == m_pressed ? 2 : hot ? 1 : 0; + const float gx0 = down ? (x0 + x1 - gripLong) / 2 : centre - gripShort / 2, gy0 = down ? centre - gripShort / 2 : (y0 + y1 - gripLong) / 2; + const float gx1 = gx0 + (down ? gripLong : gripShort), gy1 = gy0 + (down ? gripShort : gripLong); + if (const Theme::Skin& g = !m_sliderGrip[d][state].empty() ? m_sliderGrip[d][state] : m_sliderGrip[d][0]; !g.empty()) + Theme::draw(o, g, gx0, gy0, gx1, gy1, alpha); + else + o.rect(gx0, gy0, gx1, gy1, hot ? kHot : kText, alpha, 2); break; + } case Kind::Minimap: if (minimap) minimap(x0, y0, x1, y1, it.style == "__screenmap"); diff --git a/src/render/UiLayer.h b/src/render/UiLayer.h index f9292882..3caa59d8 100644 --- a/src/render/UiLayer.h +++ b/src/render/UiLayer.h @@ -56,6 +56,8 @@ namespace oc4::render std::pair keyChoicePlace() const; // A press and its release on the same item make a click. void press(int x, int y, bool right); + // The item pressed and not let go yet (found again when the items are made again), -1 none. + int pressed() const { return m_pressed; } std::optional release(int x, int y, bool shift, bool ctrl, bool alt); void setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown); @@ -96,6 +98,11 @@ namespace oc4::render // across, and the grip, plain and under the mouse. std::array m_shaft; std::array, 2> m_grip; + // The theme's sliders (GFC_Control_StandardSlider_Style), up and down [0] and across [1]: + // the track, the track with its fill, plain and disabled, and the grip plain, under the + // mouse, pressed and disabled. + std::array, 2> m_sliderTrack, m_sliderFill; + std::array, 2> m_sliderGrip; std::array m_sizes{ 10, 12, 14, 16, 22 }; // the markup's (the theme's) std::vector m_items; int m_hover = -1, m_pressed = -1; From c4ef27a3af42cc1e897c3e9924cb7e4414747d38 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 07:09:04 +0100 Subject: [PATCH 45/89] Options > Other: profiles, the clock and the alarm as the original's; network greyed Measured in the original (Wine, BUG Mod) and made the same: - Profiles: one file each, Profiles/.ini beside profile.ini (the original's Profiles\.pfl), the loaded one named by profile.ini's UserProfile (CivilizationIV.ini's). The drop-down loads one (its options to the sounds, graphics, player options, minimap toggles and clock), Create New Profile writes the options under the typed name and loads it, Delete Profile deletes a file (the loaded one: the first is loaded; the last is kept). profile.ini keeps OpenCiv4's own options, the same whichever is loaded; an older profile.ini becomes the profile "openciv4". - Clock: setClockOn marks the clock just turned on (BUG's NJAGC starts over); getClockText in the user's own short time format (CoreFoundation, as the original takes Windows'), in 24 hours with 24 Hour Clock, with a * while the alarm is set. - Alarm: toggleAlarm sets it hours and minutes from this minute with the "Alarm will go off at 7:06 AM." popup; the getters as the original's (time left in the boxes, -1 when off); at that minute AS2D_ALARM and the "RIIIIIIIIING!" popup. - Broadband / Modem: greyed, with a tooltip saying why (no multiplayer); clicks do nothing. CyGTabCtrl.setEnabled works. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 6 + apps/oc4core/Screens.cpp | 41 ++++ apps/oc4core/python/oc4options.py | 372 ++++++++++++++++++++++++++---- apps/oc4core/python/oc4screens.py | 5 +- tests/options_other_test.py | 235 +++++++++++++++++++ tests/player_options_test.py | 9 +- 6 files changed, 618 insertions(+), 50 deletions(-) create mode 100644 tests/options_other_test.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3c95b230..38eedeb5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -310,6 +310,10 @@ endif() if(WIN32) target_link_libraries(oc4core PRIVATE dbghelp bcrypt winmm shell32 ole32 advapi32 ws2_32) endif() +if(APPLE) + # (the user's time format for the interface clock: CFDateFormatter) + target_link_libraries(oc4core PRIVATE "-framework CoreFoundation") +endif() # Includes the SDK headers, so it shares the game core's dialect (no UNICODE, lenient conformance). target_compile_definitions(oc4core PRIVATE OC4_GAMECORE_IMPORT _USRDLL _CRT_SECURE_NO_WARNINGS "OC4_DEFAULT_PYTHON_HOME=\"${OC4_PYTHON27_DIR}\"" "OC4_GAME_CORE_DLL=\"${OC4_GAME_CORE_NAME}.dll\"") @@ -385,6 +389,8 @@ find_package(Python3 COMPONENTS Interpreter QUIET) if(Python3_Interpreter_FOUND) add_test(NAME player_options COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/tests/player_options_test.py ${CMAKE_CURRENT_SOURCE_DIR}/apps/oc4core/python) + add_test(NAME options_other COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/tests/options_other_test.py + ${CMAKE_CURRENT_SOURCE_DIR}/apps/oc4core/python) endif() add_executable(xml_decode_test tests/xml_decode_test.cpp) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index efe18e86..7c366eb6 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -32,12 +32,50 @@ #include #include +#if defined(__APPLE__) +#include +#endif + #include #include #include #include #include #include + +namespace +{ + // The user's short time pattern (the clock on the main interface): the system's, else 24 hours. + std::string clockPattern() + { + std::string pattern = "HH:mm"; +#if defined(__APPLE__) + if (CFLocaleRef locale = CFLocaleCopyCurrent()) + { + if (CFDateFormatterRef f = CFDateFormatterCreate(nullptr, locale, kCFDateFormatterNoStyle, kCFDateFormatterShortStyle)) + { + if (CFStringRef format = CFDateFormatterGetFormat(f)) + { + char buffer[64]; + if (CFStringGetCString(format, buffer, sizeof buffer, kCFStringEncodingUTF8)) + pattern = buffer; + } + CFRelease(f); + } + CFRelease(locale); + } +#elif defined(_WIN32) + wchar_t buffer[64]; + if (GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SSHORTTIME, buffer, 64) > 0) + { + pattern.clear(); + for (const wchar_t* c = buffer; *c; ++c) + pattern += *c < 128 ? char(*c) : ' '; + } +#endif + return pattern; + } +} #include namespace py = pybind11; @@ -250,6 +288,9 @@ namespace oc4::host engine.mark({ x, y, r, g, b, a, layer, border, true }); }); host.def("engine_effect", [&engine](int effect, float x, float y, float z, float rotation) { engine.TriggerEffect(effect, NiPoint3(x, y, z), rotation); }); + // The interface clock's form (getClockText): the user's own short time, as the original + // takes Windows' (its "HH.mm" on a Danish Mac in Wine); an ICU/Windows pattern such as "h:mm a". + host.def("clock_pattern", [] { return clockPattern(); }); // The player's profile (oc4options): where it is kept, how loud the sounds play. host.def("profile_path", [] { PWSTR documents = nullptr; diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index dd7e1664..75c966f1 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -11,6 +11,8 @@ ## play as loud), the graphic and player options, the clock; kept in the profile file the host ## names (Documents\My Games\openciv4\profile.ini). +import os +import time import CvPythonExtensions as _cpe import oc4host import oc4screens @@ -38,17 +40,21 @@ def _scales(): out[out.index(seen[size])] = seen[size] = scale return out -_profile = { - 'name': 'openciv4', - 'volume': dict((v, _VOLUME_STOPS) for v in _VOLUMES), - 'nosound': dict((v, False) for v in _VOLUMES), - 'graphic': {}, - 'player': {}, - 'clock': False, 'hours24': False, - 'graphicsLevel': 0, 'renderQuality': 0, 'globeView': 0, 'movieQuality': 0, 'mainMenu': 0, 'antiAliasing': 0, 'uiScale': 0, - 'speakers': '', 'musicPath': '', 'voice': False, - 'wasdPan': False, 'autoEndTurn': False, 'edgeScroll': True, -} +def _fresh(): + """A new profile's options.""" + return { + 'name': 'openciv4', + 'volume': dict((v, _VOLUME_STOPS) for v in _VOLUMES), + 'nosound': dict((v, False) for v in _VOLUMES), + 'graphic': {}, + 'player': {}, + 'clock': False, 'hours24': False, + 'graphicsLevel': 0, 'renderQuality': 0, 'globeView': 0, 'movieQuality': 0, 'mainMenu': 0, 'antiAliasing': 0, 'uiScale': 0, + 'speakers': '', 'musicPath': '', 'voice': False, + 'wasdPan': False, 'autoEndTurn': False, 'edgeScroll': True, + } + +_profile = _fresh() def _path(): @@ -65,23 +71,104 @@ def _path(): _DEFAULTS_ON = (0, 1, 2) +# ---------------------------------------------------------------- the profiles + +# As the original keeps its profiles, one file each (Profiles\.pfl) and the one loaded at +# start named by CivilizationIV.ini's UserProfile: Profiles/.ini beside profile.ini, each +# with the options the original keeps in a profile (the Game, Graphics, Audio and Other tabs' and +# the minimap's toggles). profile.ini keeps the rest, the same whichever profile is loaded: +# UserProfile= and OpenCiv4's own options (the keys in _GLOBAL; the ini's settings too). A +# profile.ini from before (every option in it) is the profile "openciv4"'s first file. +_GLOBAL = ('UserProfile', 'wasdPan', 'autoEndTurn', 'edgeScroll', 'cityOneClick', 'keepAttacker') +_DEFAULT_NAME = 'openciv4' +_BAD = '\\/:*?"<>|' + + +def _isGlobal(key): + return key.split('.')[0] in _GLOBAL + + +def _profilesDir(): + path = _path() + return os.path.join(os.path.dirname(path), 'Profiles') if path else '' + + +def _fileName(name): + """The profile's file (a name the file system cannot have: None).""" + name = str(name).strip() + if not name or name in ('.', '..') or [c for c in name if c in _BAD or ord(c) < 32]: + return None + folder = _profilesDir() + return os.path.join(folder, name + '.ini') if folder else None + + +def _profileNames(): + """The profiles there are (their files'), sorted as the original lists them.""" + folder = _profilesDir() + try: + names = [f[:-4] for f in os.listdir(folder) if f.lower().endswith('.ini') and os.path.isfile(os.path.join(folder, f))] + except OSError: + names = [] + return sorted(names, key=lambda n: n.lower()) + + +def _resetProfile(): + """The profile's options as a new profile has them (the global ones kept).""" + keep = dict((k, _profile[k]) for k in _GLOBAL if k in _profile) + _profile.clear() + _profile.update(_fresh()) + _profile.update(keep) + + def _load(): + """At start: profile.ini, then the profile it names (an older profile.ini's own options over it).""" path = _path() if not path: return + legacy = _read(path, _isGlobal, True) + name = _profile.get('UserProfile') or legacy.get('name') or _DEFAULT_NAME + _profile['name'] = name + own = _fileName(name) + if own and os.path.isfile(own): + _read(own, lambda key: not _isGlobal(key)) + _profile['name'] = name + if legacy: + _read(path, lambda key: not _isGlobal(key)) + _profile['name'] = name + _save() + + +def _read(path, which, others=False): + """Reads the options in the file for which which(key) holds; with others, returns the rest's + (key: value) without taking them.""" + rest = {} try: f = open(path, 'r') except IOError: - return + return rest version = 1 + player = False try: for line in f: if '=' not in line: continue key, value = line.strip().split('=', 1) parts = key.split('.') + if key == 'version': + try: + version = int(value) + except ValueError: + pass + continue + if not which(key): + if others: + rest[key] = value + continue + player = player or parts[0] == 'player' try: - if parts[0] in ('volume',) and parts[1] in _VOLUMES: + if parts[0] == 'UserProfile': + _profile['UserProfile'] = value + elif parts[0] in ('volume',) and parts[1] in _VOLUMES: _profile['volume'][parts[1]] = max(0, min(_VOLUME_STOPS, int(value))) elif parts[0] == 'nosound' and parts[1] in _VOLUMES: _profile['nosound'][parts[1]] = value == '1' @@ -93,8 +180,6 @@ def _load(): _profile[parts[0]] = int(value) elif parts[0] in ('name', 'speakers', 'musicPath'): _profile[parts[0]] = value - elif parts[0] == 'version': - version = int(value) except (ValueError, IndexError): pass finally: @@ -102,17 +187,48 @@ def _load(): # A profile the old options screen wrote: an option that is on by default and off there was # most likely never chosen (the screen showed it off), so it is the default again, once. (With # Wait at End of Turn off the game core ends a turn by itself after a unit moved.) - if version < _VERSION: + if player and version < _VERSION: for i in _DEFAULTS_ON: if _profile['player'].get(i) is False: del _profile['player'][i] + return rest -def _save(): +def _save(name=None): + """The options kept: the profile's in its file (the loaded one's, or under name), the rest in + profile.ini. A profile with no name (while one is deleted) is not written, as the original's.""" path = _path() if not path: - return - lines = ['version=%d' % _VERSION] + return False + if name is None: + name = _profile['name'] + lines = _lines() + own = _fileName(name) + ok = False + if own: + try: + if not os.path.isdir(os.path.dirname(own)): + os.makedirs(os.path.dirname(own)) + f = open(own, 'w') + f.write('\n'.join(['version=%d' % _VERSION] + [l for l in lines if not _isGlobal(l.split('=', 1)[0])]) + '\n') + f.close() + ok = True + except (IOError, OSError): + pass + if name == _profile['name']: + _profile['UserProfile'] = name + try: + f = open(path, 'w') + f.write('\n'.join(['version=%d' % _VERSION, 'UserProfile=%s' % _profile.get('UserProfile', '')] + + [l for l in lines if _isGlobal(l.split('=', 1)[0])]) + '\n') + f.close() + except IOError: + pass + return ok + + +def _lines(): + lines = [] for key in ('name', 'speakers', 'musicPath'): lines.append('%s=%s' % (key, _profile[key])) for key in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): @@ -125,12 +241,7 @@ def _save(): for kind in ('graphic', 'player'): for i, on in sorted(_profile[kind].items()): lines.append('%s.%d=%d' % (kind, i, 1 if on else 0)) - try: - f = open(path, 'w') - f.write('\n'.join(lines) + '\n') - f.close() - except IOError: - pass + return lines def _applyGraphics(): @@ -288,6 +399,10 @@ def _applyVolumes(): pass +_names = [] # (the profiles listed, loadProfileFileNames) +_clock = {'justOn': False} + + class _UserProfile(object): """CyUserProfile: the player's options (one profile, the host's file).""" @@ -297,14 +412,46 @@ def __getattr__(self, name): return lambda *args, **kwargs: 0 # the profile itself + # the profiles (Profiles/.ini): the Other tab's list, Create New Profile, Delete Profile def getProfileName(self): return _profile['name'] def setProfileName(self, s): _profile['name'] = str(s) - def getNumProfileFiles(self): return 1 - def getProfileFileName(self, i): return 'PROFILES\\%s.prf' % _profile['name'] - def loadProfileFileNames(self): pass - def readFromFile(self, s): _load(); _applyVolumes(); _applyGraphics(); return True - def writeToFile(self, s): _save(); return True - def deleteProfileFile(self, s): return False + def loadProfileFileNames(self): _names[:] = _profileNames() or [_profile['name']] + def getNumProfileFiles(self): return len(_names) + def getProfileFileName(self, i): + # (as the original's, a path the screen cuts the name from: after PROFILES\ and before the extension) + i = int(i) + return 'PROFILES\\%s.pfl' % (_names[i] if 0 <= i < len(_names) else _profile['name']) + def isProfileFileExist(self, s): + own = _fileName(s) + return bool(own and os.path.isfile(own)) + def readFromFile(self, s): + """Loads the profile s (its file): its options, to the sounds, the map and the game core.""" + own = _fileName(s) + if not own or not os.path.isfile(own): + return False + _resetProfile() + _read(own, lambda key: not _isGlobal(key)) + _profile['name'] = str(s) + _save() + _clock['justOn'] = True + _applyVolumes() + _applyGraphics() + _applyPlayerOptions() + toggles = globals().get('_applyToggles') # (the minimap's toggles, where they are kept) + if toggles: + toggles() + return True + def writeToFile(self, s): return _save(str(s)) + def deleteProfileFile(self, s): + """Deletes the profile s's file; not the last one (a profile is always loaded).""" + own = _fileName(s) + if not own or not os.path.isfile(own) or len(_profileNames()) < 2: + return False + try: + os.remove(own) + except OSError: + return False + return True def resetOptions(self, eTab): if eTab == _cpe.TabGroupTypes.TABGROUP_GRAPHICS: _profile['graphic'].clear() @@ -402,12 +549,14 @@ def getMaxCaptureVolume(self): return 0 def getMaxPlaybackVolume(self): return 0 # the clock + # (the original marks the clock just turned on at every setClockOn, on or off, and at a profile's + # load; BUG's clock starts its time-and-turn alternation over then and clears the mark) def isClockOn(self): return _profile['clock'] - def setClockOn(self, b): _profile['clock'] = bool(b) + def setClockOn(self, b): _profile['clock'] = bool(b); _clock['justOn'] = True def is24Hours(self): return _profile['hours24'] def set24Hours(self, b): _profile['hours24'] = bool(b) - def wasClockJustTurnedOn(self): return False - def setClockJustTurnedOn(self, b): pass + def wasClockJustTurnedOn(self): return _clock['justOn'] + def setClockJustTurnedOn(self, b): _clock['justOn'] = bool(b) # the map's toggles by the minimap, as they start def getGrid(self): return False @@ -438,12 +587,13 @@ def setNo(self, b, v=v): # ---------------------------------------------------------------- the tab control class _Node(object): - __slots__ = ('id', 'kind', 'name', 'children', 'text', 'value', 'items', 'callback', 'flags', 'style', 'minimum', 'maximum', 'tip') + __slots__ = ('id', 'kind', 'name', 'children', 'text', 'value', 'items', 'callback', 'flags', 'style', 'minimum', 'maximum', 'tip', 'disabled') def __init__(self, id, kind, name): self.id, self.kind, self.name = id, kind, name self.children, self.text, self.value, self.items, self.callback = [], u'', 0, (), None self.flags, self.style, self.minimum, self.maximum, self.tip = set(), '', 0, 0, u'' + self.disabled = False _state = {'ctrl': None, 'dirty': False} @@ -565,6 +715,10 @@ def attachRadioButton(self, parent, name, text, module, function, arg, bValue): n = self._node('radio', parent, name) n.text, n.value = _text(text), bool(bValue) self._callback(n, module, function, arg) + if str(name) in _NETWORK: + # (the connection speed: what the original's multiplayer sends, CivilizationIV.ini's + # Bandwidth; OpenCiv4 has no multiplayer) + n.disabled, n.tip = True, _NETWORK_TIP def attachButton(self, parent, name, text, module, function, arg): n = self._node('button', parent, name) @@ -651,7 +805,18 @@ def setActiveTab(self, i): _schedule() def getActiveTab(self): return self._tab - def setEnabled(self, *args): pass + def setEnabled(self, name, bEnabled=True): + n = self._byName.get(str(name)) + if n is not None: + n.disabled = not bEnabled + _schedule() + + +# The Other tab's connection speed: no sense in OpenCiv4 (shown as the original's, greyed, with why). +_NETWORK = ('BroadbandSelection', 'ModemSelection') +_NETWORK_TIP = (u'OpenCiv4 has no multiplayer games, so there is no connection to set the speed of: ' + u'this choice (the original\'s CivilizationIV.ini Bandwidth) does nothing here.') +_GREY = u'' def _schedule(): @@ -815,11 +980,15 @@ def _place(screen, n, x, y, w, h): w_ = screen._s.get(name) if w_ is not None: w_.state = bool(n.value) - screen.setText(name + 'L', 'Background', _FONT + n.text + u'', 1 << 0, x + _BOX_TEXT, y + 4, 0, font, general, -1, -1) - if n.tip: - w_ = screen._s.get(name) + text = n.text if not n.disabled else _GREY + n.text + u'' + screen.setText(name + 'L', 'Background', _FONT + text + u'', 1 << 0, x + _BOX_TEXT, y + 4, 0, font, general, -1, -1) + for part in (name, name + 'L'): + w_ = screen._s.get(part) if w_ is not None: - w_.help = n.tip + if n.tip: + w_.help = n.tip + if n.disabled and part == name: + w_.enabled = False elif k == 'button': screen.setButtonGFC(name, n.text, '', x, y + 4, w, 25, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) elif k == 'edit': @@ -955,6 +1124,8 @@ def handleInput(args): n = ctrl._nodes.get(ident) if n is None: return 0 + if n.disabled: + return 1 if n.kind in ('checkbox', 'radio') and notify == 0: w = _screen()._s.get('OptW%d' % n.id) n.value = bool(w.state) if w is not None else not n.value @@ -989,16 +1160,121 @@ def _call(n, args): # ---------------------------------------------------------------- in place -# (the engine's alarm clock, as the options screen sets it: off) -_alarm = {'on': False, 'hour': 0, 'min': 0} -_cpe.isAlarmOn = lambda: _alarm['on'] -_cpe.getAlarmHour = lambda: _alarm['hour'] -_cpe.getAlarmMin = lambda: _alarm['min'] -_cpe.getAlarmHourLeft = lambda: _alarm['hour'] -_cpe.getAlarmMinLeft = lambda: _alarm['min'] +# ---------------------------------------------------------------- the clock and the alarm + +# The engine's alarm clock (CvPythonExtensions' toggleAlarm and its getters), as in the original: +# set to go off in so many hours and minutes from this minute (Alarm On on the Other tab, with the +# boxes' hours and minutes), with a popup saying when; the interface clock has a * before it while +# it is set; at that minute it rings (its sound and a popup) and is off again. Not in the profile: +# kept until the program ends. +_alarm = {'at': None} # (the minute it goes off, in seconds since the epoch) + + +def _minuteNow(): + return int(time.time()) // 60 * 60 + + +def _hhmm(t, hours24): + """A time as the alarm's popups write it: 6:53, or 6:53 AM with the 12-hour clock.""" + lt = time.localtime(t) + if hours24: + return u'%d:%02d' % (lt.tm_hour, lt.tm_min) + ampm = _cpe.CyTranslator().getText('TXT_KEY_MISC_PM_AFTERNOON' if lt.tm_hour >= 12 else 'TXT_KEY_MISC_AM_MORNING', ()) + return u'%d:%02d%s' % ((lt.tm_hour + 11) % 12 + 1, lt.tm_min, ampm) + + +def _alarmPopup(key, t): + try: + popup = oc4screens.CyPopup(-1, _cpe.EventContextTypes.NO_EVENTCONTEXT, True) + tr = _cpe.CyTranslator() + popup.setHeaderString(tr.getText('TXT_KEY_POPUP_ALARM_TITLE', ()), 1 << 2) + popup.setBodyString(tr.getText(key, (_hhmm(t, _profile['hours24']),)), 1 << 0) + popup.launch(True, _cpe.PopupStates.POPUPSTATE_IMMEDIATE) + except Exception: + import traceback + traceback.print_exc() + + def _toggleAlarm(bOn, iHour=0, iMin=0): - _alarm['on'], _alarm['hour'], _alarm['min'] = bool(bOn), int(iHour), int(iMin) + if bOn: + _alarm['at'] = _minuteNow() + 60 * (60 * int(iHour) + int(iMin)) + _alarmPopup('TXT_KEY_MISC_ALARM_WILL_GO_OFF', _alarm['at']) + else: + _alarm['at'] = None + + +def _alarmLeft(): + """Minutes till it goes off (0 when off).""" + return max(0, (_alarm['at'] - _minuteNow()) // 60) if _alarm['at'] is not None else 0 + + +def _alarmTime(i): + return time.localtime(_alarm['at'])[i] if _alarm['at'] is not None else -1 + + +def _checkAlarm(): + """(every frame) The alarm's minute come: it rings.""" + if _alarm['at'] is not None and time.time() >= _alarm['at']: + _alarm['at'] = None + try: + oc4host.audio_play('AS2D_ALARM') + except Exception: + pass + _alarmPopup('TXT_KEY_MISC_ALARM_GOES_OFF', time.time()) + + +_PATTERN = [] + + +def clockText(): + """getClockText: the time of day as the user's system writes it (the original takes Windows'), + in 24 hours with the options' 24 Hour Clock; a * before it while the alarm is set.""" + if not _PATTERN: + try: + _PATTERN.append(str(oc4host.clock_pattern())) + except Exception: + _PATTERN.append('HH:mm') + pattern = _PATTERN[0] + if _profile['hours24'] and ('h' in pattern or 'a' in pattern or 't' in pattern): + sep = ([c for c in pattern if c not in 'Hhm \'at'] or [':'])[0] + pattern = 'HH%smm' % sep + lt = time.localtime() + out, i = [], 0 + while i < len(pattern): + c = pattern[i] + n = 1 + while i + n < len(pattern) and pattern[i + n] == c: + n += 1 + if c == 'H': + out.append('%02d' % lt.tm_hour if n > 1 else '%d' % lt.tm_hour) + elif c in 'hK': + h = (lt.tm_hour + 11) % 12 + 1 if c == 'h' else lt.tm_hour % 12 + out.append('%02d' % h if n > 1 else '%d' % h) + elif c == 'm': + out.append('%02d' % lt.tm_min if n > 1 else '%d' % lt.tm_min) + elif c == 's': + out.append('%02d' % lt.tm_sec if n > 1 else '%d' % lt.tm_sec) + elif c in 'at': + out.append('PM' if lt.tm_hour >= 12 else 'AM') + elif c == "'": + n = 1 + else: + out.append(c * n) + i += n + text = u''.join(out).strip() + return (u'*' if _alarm['at'] is not None else u'') + text + + +_cpe.isAlarmOn = lambda: _alarm['at'] is not None +_cpe.getAlarmHour = lambda: _alarmTime(3) +_cpe.getAlarmMin = lambda: _alarmTime(4) +_cpe.getAlarmHourLeft = lambda: _alarmLeft() // 60 +_cpe.getAlarmMinLeft = lambda: _alarmLeft() % 60 _cpe.toggleAlarm = _toggleAlarm +_cpe.getClockText = clockText +if isinstance(getattr(oc4screens, '_clockText', None), list): + oc4screens._clockText[0] = clockText +oc4screens.beforeDisplay.append(_checkAlarm) _cpe.CyGTabCtrl = CyGTabCtrl _cpe.CyUserProfile = _UserProfile oc4screens.beforeDisplay.append(relayout) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..91495060 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -2485,9 +2485,12 @@ def SetBasePitch(self, f): pass _cpe.CyUserProfile.getScores = lambda self: True +_clockText = [lambda: unicode(time.strftime('%H:%M'))] # (oc4options': the user's time format, the alarm's *) + + def getClockText(): """The time of day for the interface's clock (the engine's, in CvPythonExtensions).""" - return unicode(time.strftime('%H:%M')) + return _clockText[0]() _cpe.getClockText = getClockText diff --git a/tests/options_other_test.py b/tests/options_other_test.py new file mode 100644 index 00000000..5f6969bb --- /dev/null +++ b/tests/options_other_test.py @@ -0,0 +1,235 @@ +# Checks the options' Other tab (apps/oc4core/python/oc4options.py) against what the original does +# (measured in the Wine game, 2026-11-21, docs/options-other.md): +# - profiles: one file each (Profiles/.ini beside profile.ini, the original's Profiles\.pfl), +# the loaded one named in profile.ini (the original's CivilizationIV.ini UserProfile); Create New +# Profile writes the options under the new name and loads it, the drop-down loads another (its +# options to the sounds, the map and the game core), Delete Profile deletes a file (the loaded one: +# the first in the list is loaded); OpenCiv4's own options stay whichever is loaded; +# - an older profile.ini (every option in it) becomes the profile "openciv4"; +# - the clock: setClockOn marks it just turned on (BUG's clock starts over), 24 Hour Clock; +# - the alarm: set so many minutes ahead, a * before the clock while set, it rings at that minute; +# - the connection speed: greyed with its reason, a click does nothing. +# python3 options_other_test.py + +import importlib +import os +import shutil +import sys +import tempfile +import time +import types + +failures = [] + + +def check(ok, what): + if not ok: + print("FAILED: %s" % what) + failures.append(what) + + +class Anything(types.ModuleType): + def __getattr__(self, name): + if name.startswith('__'): + raise AttributeError(name) + return lambda *args, **kwargs: None + + +class Host(Anything): + def __init__(self, path, pattern='HH.mm'): + Anything.__init__(self, 'oc4host') + self.path, self.pattern = path, pattern + self.states = [0] * 64 + self.sounds = [] + self.graphics = {} + + def profile_path(self): return self.path + def clock_pattern(self): return self.pattern + def set_player_option(self, i, on): self.states[i] = 2 if on else 1 + def reset_player_options(self): self.states = [0] * 64 + def player_option_state(self, i): return self.states[i] + def audio_play(self, tag): self.sounds.append(tag) + def reset_graphic_options(self): self.graphics = {} + def set_graphic_option(self, i, on): self.graphics[i] = on + + +popups = [] + + +def cpe(host): + m = Anything('CvPythonExtensions') + + class Translator(object): + def getText(self, key, args): + return key + ('(%s)' % args[0] if args else '') + + m.CyTranslator = Translator + m.TabGroupTypes = types.SimpleNamespace(TABGROUP_GAME=0, TABGROUP_GRAPHICS=1, TABGROUP_AUDIO=2, TABGROUP_CLOCK=3) + m.EventContextTypes = types.SimpleNamespace(NO_EVENTCONTEXT=-1) + m.PopupStates = types.SimpleNamespace(POPUPSTATE_IMMEDIATE=1) + return m + + +class Popup(object): + def __init__(self, *args): + self.header, self.body = u'', u'' + def setHeaderString(self, s, *args): self.header = s + def setBodyString(self, s, *args): self.body = s + def launch(self, *args): popups.append((self.header, self.body)) + + +def start(folder, pattern='HH.mm'): + host = Host(os.path.join(folder, 'profile.ini'), pattern) + sys.modules['oc4host'] = host + sys.modules['CvPythonExtensions'] = cpe(host) + screens = Anything('oc4screens') + screens.beforeDisplay = [] + screens._clockText = [None] + screens._text = lambda s: u"%s" % (s,) + screens.CyPopup = Popup + sys.modules['oc4screens'] = screens + sys.modules.pop('oc4options', None) + return host, importlib.import_module('oc4options') + + +def listed(profile): + """The drop-down's names, as CvOptionsScreen cuts them from the file names.""" + profile.loadProfileFileNames() + out = [] + for i in range(profile.getNumProfileFiles()): + f = profile.getProfileFileName(i) + out.append(f[f.find("PROFILES\\") + 9:-4]) + return out + + +def read(path): + with open(path) as f: + return set(f.read().split()) + + +def main(): + sys.path.insert(0, sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), '..', 'apps', 'oc4core', 'python')) + folder = tempfile.mkdtemp() + try: + # An older profile.ini: every option in it; it becomes the profile "openciv4". + with open(os.path.join(folder, 'profile.ini'), 'w') as f: + f.write('version=2\nname=openciv4\nclock=1\nwasdPan=1\nvolume.Music=7\nplayer.6=1\n') + host, options = start(folder) + profile = options._UserProfile() + own = os.path.join(folder, 'Profiles', 'openciv4.ini') + check(os.path.isfile(own), "the old profile.ini's options moved to Profiles/openciv4.ini") + check({'clock=1', 'volume.Music=7', 'player.6=1'} <= read(own), "with its options: %s" % sorted(read(own))) + check('clock=1' not in read(os.path.join(folder, 'profile.ini')) and {'UserProfile=openciv4', 'wasdPan=1'} <= read(os.path.join(folder, 'profile.ini')), + "profile.ini keeps the name and OpenCiv4's own: %s" % sorted(read(os.path.join(folder, 'profile.ini')))) + check(profile.isClockOn() and profile.getMusicVolume() == 7 and host.states[6] == 2, "and they are loaded") + check(listed(profile) == ['openciv4'], "one profile listed: %s" % listed(profile)) + + # Create New Profile (CvOptionsScreenCallbackInterface.handleNewProfileButtonInput). + profile.set24Hours(True) + profile.setProfileName('Second') + check(profile.writeToFile('Second'), "Create New Profile writes it") + profile.loadProfileFileNames() + options._save() + check(listed(profile) == ['openciv4', 'Second'], "two listed: %s" % listed(profile)) + check('UserProfile=Second' in read(os.path.join(folder, 'profile.ini')), "the new one is the loaded one") + check({'hours24=1', 'clock=1', 'player.6=1'} <= read(os.path.join(folder, 'Profiles', 'Second.ini')), "with the options as they were") + + # Its own options; then the drop-down's openciv4 (saveProfile, then loadProfile). + profile.setClockOn(False) + profile.setMusicVolume(3) + profile.setGraphicOption(4, True) + options._UserProfile().setPlayerOption(6, False) + options._save() + host.audio = [] + check(profile.readFromFile('openciv4'), "the drop-down loads openciv4") + check(profile.getProfileName() == 'openciv4' and profile.isClockOn() and not profile.is24Hours() and profile.getMusicVolume() == 7, + "openciv4's options back") + check(host.states[6] == 2 and 4 not in host.graphics, "its player and graphic options to the host (%s, %s)" % (host.states[6], host.graphics)) + check(profile.wasClockJustTurnedOn(), "a load marks the clock just turned on") + check(options._profile['wasdPan'] is True, "OpenCiv4's own option stays") + check('UserProfile=openciv4' in read(os.path.join(folder, 'profile.ini')), "profile.ini names it") + + # A restart: the loaded one again. + host, options = start(folder) + profile = options._UserProfile() + check(profile.getProfileName() == 'openciv4' and profile.isClockOn(), "after a restart, openciv4 is loaded") + host, options = start(folder) + profile = options._UserProfile() + profile.readFromFile('Second') + host, options = start(folder) + profile = options._UserProfile() + check(profile.getProfileName() == 'Second' and not profile.isClockOn() and profile.getMusicVolume() == 3 and host.states[6] == 1, + "after a restart, Second is loaded with its options") + + # Delete Profile: one with no file, the loaded one, the last one. + check(not profile.deleteProfileFile('NoSuch'), "no such profile: nothing deleted") + check(not profile.writeToFile('a/b') and not profile.writeToFile(''), "a name a file cannot have is not written") + check(profile.deleteProfileFile('Second'), "the loaded one deleted") + profile.setProfileName('') + check(listed(profile) == ['openciv4'], "one left: %s" % listed(profile)) + check(profile.readFromFile('openciv4') and profile.getProfileName() == 'openciv4', "the first loaded then") + check(not profile.deleteProfileFile('openciv4'), "the last one is kept") + + # The clock. + profile.setClockJustTurnedOn(False) + profile.setClockOn(False) + check(profile.wasClockJustTurnedOn(), "setClockOn marks it just turned on, as the original (off too)") + lt = time.localtime() + check(options.clockText() == u'%02d.%02d' % (lt.tm_hour, lt.tm_min), "the user's format: %s" % options.clockText()) + host, options = start(folder, 'h:mm a') + profile = options._UserProfile() + profile.set24Hours(False) + lt = time.localtime() + check(options.clockText() == u'%d:%02d %s' % ((lt.tm_hour + 11) % 12 + 1, lt.tm_min, 'PM' if lt.tm_hour >= 12 else 'AM'), + "a 12-hour format: %s" % options.clockText()) + profile.set24Hours(True) + check(options.clockText() == u'%02d:%02d' % (lt.tm_hour, lt.tm_min), "24 Hour Clock: %s" % options.clockText()) + + # The alarm: one minute ahead, from this minute. + cp = sys.modules['CvPythonExtensions'] + del popups[:] + cp.toggleAlarm(True, 0, 1) + at = time.localtime((int(time.time()) // 60 + 1) * 60) + check(cp.isAlarmOn() and (cp.getAlarmHour(), cp.getAlarmMin()) == (at.tm_hour, at.tm_min), "set: goes off at %d:%02d" % (cp.getAlarmHour(), cp.getAlarmMin())) + check((cp.getAlarmHourLeft(), cp.getAlarmMinLeft()) == (0, 1), "1 minute left") + check(popups and popups[-1] == ('TXT_KEY_POPUP_ALARM_TITLE', 'TXT_KEY_MISC_ALARM_WILL_GO_OFF(%d:%02d)' % (at.tm_hour, at.tm_min)), + "its popup: %s" % popups) + check(options.clockText().startswith(u'*'), "a * before the clock") + options._checkAlarm() + check(cp.isAlarmOn() and 'AS2D_ALARM' not in host.sounds, "not yet") + options._alarm['at'] = time.time() - 1 + options._checkAlarm() + check(not cp.isAlarmOn() and host.sounds == ['AS2D_ALARM'] and popups[-1][1].startswith('TXT_KEY_MISC_ALARM_GOES_OFF'), + "it rings: %s %s" % (host.sounds, popups[-1])) + check((cp.getAlarmHour(), cp.getAlarmMin(), cp.getAlarmHourLeft(), cp.getAlarmMinLeft()) == (-1, -1, 0, 0), "and is off") + check(not options.clockText().startswith(u'*'), "no * then") + cp.toggleAlarm(True, 2, 5) + check((cp.getAlarmHourLeft(), cp.getAlarmMinLeft()) == (2, 5), "2 hours 5 left") + cp.toggleAlarm(False, 0, 0) + check(not cp.isAlarmOn(), "turned off") + + # The connection speed: greyed, with why; a click does nothing. + ctrl = options.CyGTabCtrl('Options', False, False) + ctrl.attachTabItem('OtherForm', 'Other') + ctrl.attachVBox('OtherForm', 'NetPanelVBox') + ctrl.attachRadioButton('NetPanelVBox', 'BroadbandSelection', 'Broadband', 'cb', 'handleBroadbandSelected', 'BroadbandSelection', True) + ctrl.attachRadioButton('NetPanelVBox', 'ModemSelection', 'Modem', 'cb', 'handleModemSelected', 'ModemSelection', False) + for name in ('BroadbandSelection', 'ModemSelection'): + n = ctrl._byName[name] + check(n.disabled and 'OpenCiv4' in n.tip, "%s greyed with its reason" % name) + options._state['ctrl'] = ctrl + n = ctrl._byName['ModemSelection'] + options.handleInput((0, 0, 0, n.id, 0, 'OptW')) + check(n.value is False, "a click on Modem does nothing") + finally: + shutil.rmtree(folder, ignore_errors=True) + + if failures: + print("options_other_test: %d failed" % len(failures)) + return 1 + print("options_other_test: all passed") + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/player_options_test.py b/tests/player_options_test.py index c13debbc..2b0bbdb2 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -107,8 +107,15 @@ def handleGameOptionsClicked(args): def profileLines(folder): + """profile.ini's lines and the loaded profile's (Profiles/.ini).""" with open(os.path.join(folder, 'profile.ini')) as f: - return set(f.read().split()) + lines = set(f.read().split()) + name = [l.split('=', 1)[1] for l in lines if l.startswith('UserProfile=')] + own = os.path.join(folder, 'Profiles', (name[0] if name else 'openciv4') + '.ini') + if os.path.isfile(own): + with open(own) as f: + lines |= set(f.read().split()) + return lines def optionsScreen(options): From 8a78754e89211b2749623c03aa7caf2d8a6f1f22 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 07:40:28 +0100 Subject: [PATCH 46/89] Options -> Graphics: every option as the original's, without a restart The original asks for a restart after Single Unit Graphics, Full-screen, Graphics Level, High Detail Terrain and Restore Defaults; here every option takes effect at once, so the restart popup is gone. - Graphics Level is the original's preset (measured in Wine): Low/Medium/ High switch the other options and qualities as the original does. - No Enemy Glow: enemies in the active team's land get the selection ring in the original's red (no dots) unless the option is on. - Show City Radius: the original's hatched area border style. - Globe View Buildings Disabled: no city models in the globe view. - Low Resolution Textures: textures from their half size level (the samplers' lowest level), at once. - Anti-Aliasing: real MSAA 2/4/8 on the main target, resolved per pass. - Movie Quality Low: no map drawn behind a playing movie. - Opening Menu: the temporary menu shows the chosen menu's loading picture and plays its music. - Render Quality, Globe Quality and High Detail Terrain are greyed out with a tool tip (no visible effect in the original either). - The options' defaults are read again (getGraphicOptionsInfoByIndex: the old name did not exist, so every default read as off). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/MapCapture.cpp | 6 ++ apps/oc4core/Screens.cpp | 14 ++++ apps/oc4core/Screens.h | 2 + apps/oc4core/Utility.h | 6 ++ apps/oc4core/main.cpp | 12 ++-- apps/oc4core/python/oc4menu.py | 26 ++++++- apps/oc4core/python/oc4options.py | 114 ++++++++++++++++++++++++++---- src/render/MapSnapshot.h | 1 + src/render/MapView.cpp | 50 +++++++++++-- src/render/MapView.h | 1 + src/render/MapWindow.cpp | 28 ++++++-- src/render/MapWindow.h | 4 ++ src/render/Renderer.cpp | 109 +++++++++++++++++++++++----- src/render/Renderer.h | 20 ++++++ 14 files changed, 346 insertions(+), 47 deletions(-) diff --git a/apps/oc4core/MapCapture.cpp b/apps/oc4core/MapCapture.cpp index 491e2537..52fa6aad 100644 --- a/apps/oc4core/MapCapture.cpp +++ b/apps/oc4core/MapCapture.cpp @@ -17,6 +17,7 @@ #include "CvPlayerAI.h" #include "CvPlot.h" #include "CvSelectionGroup.h" +#include "CvTeamAI.h" #include "CvUnit.h" #include @@ -926,6 +927,11 @@ namespace oc4::host u.y = plot->getY(); u.owner = shown->getOwner(); u.shownOwner = shown->getVisualOwner(GC.getGame().getActiveTeam()); + // (an enemy of the active team in its land, seen there: the red ring under it, unless + // the No Enemy Glow option is on) + if (active != NO_TEAM && v.visible && plot->getOwner() != NO_PLAYER && player(plot->getOwner()).getTeam() == active && + CvTeamAI::getTeamNonInl(active).isAtWar(shown->getTeam()) && !gDLL->getGraphicOption(GRAPHICOPTION_NO_ENEMY_GLOW)) + u.enemy = true; u.air = shown->getDomainType() == DOMAIN_AIR; u.direction = int(shown->getFacingDirection(false)); u.resting = Entities::resting(*shown); diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index efe18e86..579c2c1a 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -268,6 +268,7 @@ namespace oc4::host host.def("set_graphic_option", [&utility](int option, bool on) { utility.setGraphicOption(option, on); }); host.def("reset_graphic_options", [&utility] { utility.resetGraphicOptions(); }); host.def("set_ui_scale", [&utility](int percent) { utility.setUiScale(percent); }); + host.def("set_graphic_levels", [&utility](int movieQuality, int samples) { utility.setGraphicLevels(movieQuality, samples); }); // W A S D panning: the profile's, as loaded; the player's, from the options' check box. host.def("set_wasd_pan", [&utility](bool on) { utility.setWasdPan(on); }); host.def("choose_wasd_pan", [&utility](bool on) { utility.chooseWasdPan(on); }); @@ -733,6 +734,19 @@ if _walls: return m_active; } + std::string Screens::menuSoundtrack() + { + try + { + return py::module_::import("oc4menu").attr("soundtrack")().cast(); + } + catch (py::error_already_set& e) + { + printPythonError(e); + return "AS2D_OPENING_MENU"; + } + } + bool Screens::startMenu(int width, int height, const std::string& title, const std::vector& mapScripts, const std::vector>& saveFolders, const std::vector& mods, const std::string& message, const std::string& page) diff --git a/apps/oc4core/Screens.h b/apps/oc4core/Screens.h index 5f64207c..44b1d585 100644 --- a/apps/oc4core/Screens.h +++ b/apps/oc4core/Screens.h @@ -81,6 +81,8 @@ namespace oc4::host // The temporary main menu instead (the original's is the engine's own, no script's): // a title, the map scripts to choose from and the folders with saved games (each with a // label). Its choice, once made, from takeMenuChoice; closeMenu takes it down. + // The opening menu's music the options chose (its 2D sound script: AS2D_OPENING_MENU...). + std::string menuSoundtrack(); bool startMenu(int width, int height, const std::string& title, const std::vector& mapScripts, const std::vector>& saveFolders, const std::vector& mods, const std::string& message = {}, const std::string& page = {}); diff --git a/apps/oc4core/Utility.h b/apps/oc4core/Utility.h index b01d32be..65a63761 100644 --- a/apps/oc4core/Utility.h +++ b/apps/oc4core/Utility.h @@ -234,6 +234,11 @@ namespace oc4::host int uiScale() const { return m_forcedUiScale >= 0 ? m_forcedUiScale : m_uiScale; } void setUiScale(int percent) { m_uiScale = percent; } void forceUiScale(int percent) { m_forcedUiScale = percent; } + // The options screen's quality choices the window follows: the movies' (0 high .. 2 low) + // and the anti-aliasing's samples (0, 2, 4, 8). + int movieQuality() const { return m_movieQuality; } + int antiAliasing() const { return m_antiAliasing; } + void setGraphicLevels(int movieQuality, int samples) { m_movieQuality = movieQuality, m_antiAliasing = samples; } // W A S D pan the map (the profile's, or --wasd-pan's for the session until the player // chooses: the options' check box, or Ctrl+Shift+W to turn it off). bool wasdPan() const { return m_forcedWasdPan || m_wasdPan; } @@ -432,6 +437,7 @@ namespace oc4::host std::vector m_messages; std::array m_playerOptions{}; // the profile's: 0 the XML's default, 1 off, 2 on int m_uiScale = 0, m_forcedUiScale = -1; + std::atomic m_movieQuality = 0, m_antiAliasing = 0; bool m_wasdPan = false, m_forcedWasdPan = false; bool m_autoEndTurn = false, m_forcedAutoEndTurn = false; render::EdgeScrollOption m_edgeScroll; diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..da5d612c 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -554,7 +554,8 @@ namespace return i >= 0 && utility.getGraphicOption(static_cast(i)); }; window.setGraphics({ option("GRAPHICOPTION_HEALTH_BARS"), option("GRAPHICOPTION_FROZEN_ANIMATIONS"), !option("GRAPHICOPTION_EFFECTS_DISABLED"), - utility.graphicOptionChosen(GC.getInfoTypeForString("GRAPHICOPTION_FULLSCREEN", true)) }); + utility.graphicOptionChosen(GC.getInfoTypeForString("GRAPHICOPTION_FULLSCREEN", true)), !option("GRAPHICOPTION_GLOBE_VIEW_BUILDINGS_DISABLED"), + option("GRAPHICOPTION_LOWRES_TEXTURES"), utility.movieQuality() >= 2, utility.antiAliasing() }); }; { std::array symbols; @@ -1453,8 +1454,10 @@ namespace for (const auto& m : marks) { const auto [x, y] = m.core ? host::windowPlot({ m.x, m.y }) : std::pair{ m.x, m.y }; - // (the WorldBuilder's plot and brush in the original's area border style) - const bool hatched = m.border && (m.layer == AREA_BORDER_LAYER_HIGHLIGHT_PLOT || m.layer == AREA_BORDER_LAYER_WORLD_BUILDER); + // (the WorldBuilder's plot and brush and a settler's view of the cities' plots, Show City + // Radius, in the original's area border style) + const bool hatched = m.border && (m.layer == AREA_BORDER_LAYER_HIGHLIGHT_PLOT || m.layer == AREA_BORDER_LAYER_WORLD_BUILDER || + m.layer == AREA_BORDER_LAYER_CITY_RADIUS); shownMarks.marks.push_back({ x, y, m.layer, { m.r, m.g, m.b }, m.a, m.border, false, hatched }); } for (const auto& s : signs) @@ -1765,7 +1768,8 @@ namespace host::Sounds& sounds = utility.sounds(); if (const char* s = std::getenv("OC4_SOUND"); s ? std::string_view(s) != "0" : opt.viewSeconds <= 0) sounds.start(s && std::string_view(s) == "mute"); - sounds.setTalkMusic(-1, utility.audioScripts().index("AS2D_OPENING_MENU", AUDIOTAG_2DSCRIPT)); + // (the opening menu's the options chose: Options -> Graphics -> Opening Menu) + sounds.setTalkMusic(-1, utility.audioScripts().index(screens.menuSoundtrack().c_str(), AUDIOTAG_2DSCRIPT)); std::optional choice; auto last = Clock::now(), typed = last; const auto start = last; diff --git a/apps/oc4core/python/oc4menu.py b/apps/oc4core/python/oc4menu.py index 367d7550..85febdb4 100644 --- a/apps/oc4core/python/oc4menu.py +++ b/apps/oc4core/python/oc4menu.py @@ -122,9 +122,24 @@ def _draw(): {'main': _mainPage, 'new': _newPage, 'custom': _customPage, 'load': _loadPage, 'multi': _multiPage, 'mods': _modsPage}[_state['page']](screen, W, H) +def _openingMenu(): + """The opening menu the options chose (CyUserProfile.getMainMenu: CIV4MainMenus.xml), or None.""" + try: + gc = _gc() + i = int(_cpe.CyUserProfile().getMainMenu()) + if 0 <= i < gc.getNumMainMenus(): + return gc.getMainMenus(i) + except Exception: + pass + return None + + def _background(): + """The chosen opening menu's loading picture (the original shows its 3D scene), else BtS's.""" afm = _cpe.CyArtFileMgr() - for tag in ('MAINMENU_LOAD_BTS', 'MAINMENU_LOAD'): + menu = _openingMenu() + tags = ((menu.getLoading(),) if menu else ()) + ('MAINMENU_LOAD_BTS', 'MAINMENU_LOAD') + for tag in tags: try: info = afm.getInterfaceArtInfo(tag) if info and info.getPath(): @@ -134,6 +149,15 @@ def _background(): return '' +def soundtrack(): + """The chosen opening menu's music (its 2D sound script), for the host.""" + menu = _openingMenu() + try: + return str(menu.getSoundtrack()) if menu and menu.getSoundtrack() else 'AS2D_OPENING_MENU' + except Exception: + return 'AS2D_OPENING_MENU' + + def _button(screen, name, text, x, y, w, h=40): screen.setButtonGFC(name, u'' + text + u'', '', x, y, w, h, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index dd7e1664..c4c7b30f 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -140,6 +140,7 @@ def _applyGraphics(): for i, on in _profile['graphic'].items(): oc4host.set_graphic_option(int(i), bool(on)) oc4host.set_ui_scale(_profile['uiScale']) + oc4host.set_graphic_levels(_profile['movieQuality'], _AA_SAMPLES[min(max(_profile['antiAliasing'], 0), len(_AA_SAMPLES) - 1)]) _applyPlayerOptions() oc4host.set_wasd_pan(_profile['wasdPan']) oc4host.set_auto_end_turn(_profile['autoEndTurn']) @@ -267,9 +268,44 @@ def _playerDefault(i): return False +# What the original's Graphics Level sets (Civ4BeyondSword.exe, CyUserProfile.setGraphicsLevel, +# measured in Wine 2026-11-21): the graphic options it switches on and off, the render, globe and +# movie quality (0 high, 1 medium, 2 low) and the anti-aliasing (an index into 0, 2, 4, 8 samples; +# None: as it is). +_LEVEL_PRESETS = { + 0: ((), ('SINGLE_UNIT_GRAPHICS', 'FROZEN_ANIMATIONS', 'EFFECTS_DISABLED', 'GLOBE_VIEW_BUILDINGS_DISABLED', 'LOWRES_TEXTURES'), 0, None), + 1: (('SINGLE_UNIT_GRAPHICS', 'GLOBE_VIEW_BUILDINGS_DISABLED'), ('FROZEN_ANIMATIONS', 'EFFECTS_DISABLED', 'LOWRES_TEXTURES'), 1, 1), + 2: (('SINGLE_UNIT_GRAPHICS', 'FROZEN_ANIMATIONS', 'EFFECTS_DISABLED', 'GLOBE_VIEW_BUILDINGS_DISABLED', 'LOWRES_TEXTURES'), ('HIRES_TERRAIN',), 2, 0), +} + + +# The original's options OpenCiv4 does not do, by their controls' names on the options screen +# (CvOptionsScreen.py): Render Quality and Globe Quality, which made no difference in the original +# either, and High Detail Terrain (the terrain's mesh detail; OpenCiv4 has one). +_AA_SAMPLES = (0, 2, 4, 8) # the anti-aliasing drop-down's choices (CvOptionsScreen: 0, 2, 4, 8, 16), as the renderer does them +_NOT_DONE_TIP = u'OpenCiv4 does not implement this option.' + + +def _notDone(): + names = set(('GraphicsQualityLabel', 'RenderQualityDropdownBox', 'GlobeViewLabel', 'GlobeViewDropdownBox')) + try: + names.add('GraphicOptionCheckbox_%d' % _graphicOption('HIRES_TERRAIN')) + except Exception: + pass + return names + + +def _graphicOption(name): + return int(getattr(_cpe.GraphicOptionTypes, 'GRAPHICOPTION_' + name)) + + def _graphicDefault(i): + """The XML's default (CIV4GraphicOptionInfos), but full screen: OpenCiv4 starts in a window + until it is chosen (the host's graphicOptionChosen).""" try: - return bool(_cpe.CyGlobalContext().getGraphicOptionInfo(int(i)).getDefault()) + if int(i) == int(_cpe.GraphicOptionTypes.GRAPHICOPTION_FULLSCREEN): + return False + return bool(_cpe.CyGlobalContext().getGraphicOptionsInfoByIndex(int(i)).getDefault()) except Exception: return False @@ -330,18 +366,33 @@ def resetOptions(self, eTab): def getGraphicOption(self, i): return _profile['graphic'].get(int(i), _graphicDefault(i)) def setGraphicOption(self, i, b): _profile['graphic'][int(i)] = bool(b); _save(); _applyGraphics() def getGraphicsLevel(self): return _profile['graphicsLevel'] - def setGraphicsLevel(self, i): _profile['graphicsLevel'] = int(i) + def setGraphicsLevel(self, i): + # (the original's level is a preset of the others, as measured in it: see _LEVEL_PRESETS) + _profile['graphicsLevel'] = int(i) + preset = _LEVEL_PRESETS.get(int(i)) + if preset: + on, off, level, aa = preset + for name in on: + _profile['graphic'][_graphicOption(name)] = True + for name in off: + _profile['graphic'][_graphicOption(name)] = False + _profile['renderQuality'] = _profile['globeView'] = _profile['movieQuality'] = level + if aa is not None: + _profile['antiAliasing'] = aa + _save() + _applyGraphics() def getRenderQualityLevel(self): return _profile['renderQuality'] def setRenderQualityLevel(self, i): _profile['renderQuality'] = int(i) + # (the movies' and the anti-aliasing's take effect at once) def getGlobeViewRenderLevel(self): return _profile['globeView'] def setGlobeViewRenderLevel(self, i): _profile['globeView'] = int(i) def getMovieQualityLevel(self): return _profile['movieQuality'] - def setMovieQualityLevel(self, i): _profile['movieQuality'] = int(i) + def setMovieQualityLevel(self, i): _profile['movieQuality'] = int(i); _save(); _applyGraphics() def getMainMenu(self): return _profile['mainMenu'] def setMainMenu(self, i): _profile['mainMenu'] = int(i) def getAntiAliasing(self): return _profile['antiAliasing'] - def setAntiAliasing(self, i): _profile['antiAliasing'] = int(i) - def getAntiAliasingMaxMultiSamples(self): return 0 + def setAntiAliasing(self, i): _profile['antiAliasing'] = int(i); _save(); _applyGraphics() + def getAntiAliasingMaxMultiSamples(self): return len(_AA_SAMPLES) - 1 # (the map keeps the window's pixels: the resolution's choices are the interface's, which # takes effect at once) def getResolution(self): @@ -438,12 +489,13 @@ def setNo(self, b, v=v): # ---------------------------------------------------------------- the tab control class _Node(object): - __slots__ = ('id', 'kind', 'name', 'children', 'text', 'value', 'items', 'callback', 'flags', 'style', 'minimum', 'maximum', 'tip') + __slots__ = ('id', 'kind', 'name', 'children', 'text', 'value', 'items', 'callback', 'flags', 'style', 'minimum', 'maximum', 'tip', 'enabled') def __init__(self, id, kind, name): self.id, self.kind, self.name = id, kind, name self.children, self.text, self.value, self.items, self.callback = [], u'', 0, (), None self.flags, self.style, self.minimum, self.maximum, self.tip = set(), '', 0, 0, u'' + self.enabled = True _state = {'ctrl': None, 'dirty': False} @@ -493,6 +545,9 @@ def destroy(self): def _node(self, kind, parent, name): n = _Node(self._next, kind, str(name)) + # (the original's options OpenCiv4 does not do: greyed, with a tool tip saying so) + if n.name in _notDone(): + n.enabled, n.tip = False, _NOT_DONE_TIP self._next += 1 self._nodes[n.id] = n self._byName[n.name] = n @@ -607,7 +662,7 @@ def setStyle(self, name, style): def setToolTip(self, name, text): n = self._byName.get(str(name)) - if n is not None: + if n is not None and n.name not in _notDone(): n.tip = _text(text) def setValue(self, name, value): @@ -651,7 +706,11 @@ def setActiveTab(self, i): _schedule() def getActiveTab(self): return self._tab - def setEnabled(self, *args): pass + def setEnabled(self, name, bEnabled=True): + n = self._byName.get(str(name)) + if n is not None: + n.enabled = bool(bEnabled) + _schedule() def _schedule(): @@ -806,8 +865,12 @@ def _place(screen, n, x, y, w, h): _place(screen, c, x + px, cy, inner, ch) cy += ch + _GAP return + # (a control OpenCiv4 does not do: greyed, takes no clicks, its tool tip says why) + grey, ungrey = (_GREY, u'') if not n.enabled else (u'', u'') if k == 'label': - screen.setLabel(name, 'Background', _FONT + n.text + u'', 1 << 0, x, y + 4, 0, font, general, -1, -1) + screen.setLabel(name, 'Background', _FONT + grey + n.text + ungrey + u'', 1 << 0, x, y + 4, 0, font, general, -1, -1) + if n.tip: + _tip(screen, name, n.tip) elif k in ('checkbox', 'radio'): # (the theme's check box, as the custom game screen's: GFC_Control_StandardCheckBox_Style) screen.addCheckBoxGFC(name, '', '', x, y + 4, _BOX, _BOX, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) @@ -815,11 +878,12 @@ def _place(screen, n, x, y, w, h): w_ = screen._s.get(name) if w_ is not None: w_.state = bool(n.value) - screen.setText(name + 'L', 'Background', _FONT + n.text + u'', 1 << 0, x + _BOX_TEXT, y + 4, 0, font, general, -1, -1) + screen.setText(name + 'L', 'Background', _FONT + grey + n.text + ungrey + u'', 1 << 0, x + _BOX_TEXT, y + 4, 0, font, general, -1, -1) if n.tip: - w_ = screen._s.get(name) - if w_ is not None: - w_.help = n.tip + _tip(screen, name, n.tip) + _tip(screen, name + 'L', n.tip) + if not n.enabled: + screen.enable(name, False) elif k == 'button': screen.setButtonGFC(name, n.text, '', x, y + 4, w, 25, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) elif k == 'edit': @@ -832,6 +896,10 @@ def _place(screen, n, x, y, w, h): screen.addDropDownBoxGFC(name, x, y + 1, dw, general, -1, -1, font) for i, item in enumerate(n.items): screen.addPullDownString(name, item, i, i, i == int(n.value)) + if n.tip: + _tip(screen, name, n.tip) + if not n.enabled: + screen.enable(name, False) elif k in ('hslider', 'vslider'): # (its stops, each a little button: the slider set to the one clicked) stops = n.maximum - n.minimum + 1 @@ -853,6 +921,15 @@ def _place(screen, n, x, y, w, h): screen.addPanel(name, u'', u'', True, False, x, y + 4, w, 2, _cpe.PanelStyles.PANEL_STYLE_MAIN) +_GREY = u'' + + +def _tip(screen, name, text): + w = screen._s.get(name) + if w is not None: + w.help = text + + def resized(): """Another size: the window laid out again for it, as it would not be otherwise.""" if _state['ctrl'] is not None: @@ -955,6 +1032,8 @@ def handleInput(args): n = ctrl._nodes.get(ident) if n is None: return 0 + if not n.enabled: + return 1 if n.kind in ('checkbox', 'radio') and notify == 0: w = _screen()._s.get('OptW%d' % n.id) n.value = bool(w.state) if w is not None else not n.value @@ -972,12 +1051,21 @@ def handleInput(args): return 1 +def _noRestart(bForceShowing=False): + """CvOptionsScreenCallbackInterface.restartPopup: the original's resolution, graphics level, + single unit graphics, full screen, terrain detail and speakers took a restart; here none does.""" + pass + + def _call(n, args): if not n.callback: return module, function = n.callback[0], n.callback[1] try: m = __import__(module) + # (no "Program must be restarted" popup: every option here takes effect at once) + if hasattr(m, 'restartPopup'): + m.restartPopup = _noRestart getattr(m, function)(args) except Exception: import traceback diff --git a/src/render/MapSnapshot.h b/src/render/MapSnapshot.h index 851cb25e..42e05167 100644 --- a/src/render/MapSnapshot.h +++ b/src/render/MapSnapshot.h @@ -160,6 +160,7 @@ namespace oc4::render float health = 1; std::string button; // the shown unit's button art (the unit layer's icons) bool selected = false; // the player has selected units there + bool enemy = false; // an enemy in the active team's land (the red ring under it: the enemy glow) bool promotionReady = false; // enough experience and at least one promotion it can take // ... and how the head of them can move (the selection ring's dots): 2 it has not moved // yet, 1 it has but can go on, 0 it cannot; -1 another player's. diff --git a/src/render/MapView.cpp b/src/render/MapView.cpp index 4085df17..e1c2be11 100644 --- a/src/render/MapView.cpp +++ b/src/render/MapView.cpp @@ -464,7 +464,8 @@ float4 PSTerrain(PSIn i) : SV_Target Impl(Renderer& r, const AssetResolver& a) : renderer(r), assets(a) { createPipeline(); } ~Impl() { - SDL_ReleaseGPUGraphicsPipeline(renderer.device(), terrainPipeline); + for (const auto& [samples, p] : terrainPipelines) + SDL_ReleaseGPUGraphicsPipeline(renderer.device(), p); SDL_ReleaseGPUShader(renderer.device(), terrainVS); SDL_ReleaseGPUShader(renderer.device(), terrainPS); SDL_ReleaseGPUSampler(renderer.device(), sampler); @@ -604,6 +605,7 @@ float4 PSTerrain(PSIn i) : SV_Target // The ring the game puts under the selected units (Art/Units/Selection Effect): its // circle turning (the default clip) and its dots over it as the head unit can move // (no dots, red, yellow, green: UnitView::moves + 1). + static constexpr Vec3 kEnemyGlow{ 0.74f, 0.28f, 0.16f }; // (the ring's colour under an enemy: the original's red) struct SelectionRing { bool tried = false, ok = false; @@ -669,10 +671,12 @@ float4 PSTerrain(PSIn i) : SV_Target return false; for (const UnitView& u : map.units) { - if (!u.selected) + // (and under an enemy in the active team's land, red and without dots: the enemy glow) + if (!u.selected && !u.enemy) continue; + const bool glow = !u.selected; // (its dots: how the head unit can move) - if (const int d = std::clamp(u.moves + 1, 0, 3); d != ring.shown && ring.dots[d]) + if (const int d = glow ? 0 : std::clamp(u.moves + 1, 0, 3); d != ring.shown && ring.dots[d]) { ring.shown = d; ring.player.setLayers({ *ring.dots[d] }); @@ -691,7 +695,12 @@ float4 PSTerrain(PSIn i) : SV_Target world[k] = place * local[k]; std::vector materials; for (const auto& item : ring.model.items) + { materials.push_back(anim::animatedMaterial(item, pose)); + if (glow) + for (nif::Color3* c : { &materials.back().diffuse, &materials.back().emissive, &materials.back().ambient }) + c->r *= kEnemyGlow.x, c->g *= kEnemyGlow.y, c->b *= kEnemyGlow.z; + } renderer.draw(*ring.gpu, world, ring.model.visibility(pose.hidden), materials, kDefaultTeamColor, true); } return true; @@ -716,10 +725,21 @@ float4 PSTerrain(PSIn i) : SV_Target void createPipeline() { - SDL_GPUDevice* dev = renderer.device(); const std::string source = std::string(kFrameConstantsHlsl) + kTerrainHlsl; terrainVS = renderer.compile(source, "terrain.hlsl", "VSTerrain", SDL_GPU_SHADERSTAGE_VERTEX, 0, 0, 2); terrainPS = renderer.compile(source, "terrain.hlsl", "PSTerrain", SDL_GPU_SHADERSTAGE_FRAGMENT, 6, 0, 2); + terrainPipeline = terrainPipelineFor(1); + makeTerrainSamplers(); + } + + // The terrain's pipeline for a pass of so many samples (anti-aliasing), made when first needed. + std::map terrainPipelines; + SDL_GPUGraphicsPipeline* terrainPipelineFor(uint32_t samples) + { + if (const auto it = terrainPipelines.find(samples); it != terrainPipelines.end()) + return it->second; + SDL_GPUDevice* dev = renderer.device(); + SDL_GPUGraphicsPipeline* made = nullptr; SDL_GPUGraphicsPipelineCreateInfo ci{}; ci.vertex_shader = terrainVS; ci.fragment_shader = terrainPS; @@ -740,21 +760,35 @@ float4 PSTerrain(PSIn i) : SV_Target ci.target_info.num_color_targets = 1; ci.target_info.depth_stencil_format = renderer.depthFormat(); ci.target_info.has_depth_stencil_target = true; - if (!(terrainPipeline = SDL_CreateGPUGraphicsPipeline(dev, &ci))) + ci.multisample_state.sample_count = Renderer::sampleCount(samples); + if (!(made = SDL_CreateGPUGraphicsPipeline(dev, &ci))) throw std::runtime_error(std::string("terrain pipeline: ") + SDL_GetError()); + return terrainPipelines[samples] = made; + } + // The terrain's samplers, again when the renderer's lowest level changes (low resolution textures). + uint32_t terrainSamplerGeneration = ~0u; + void makeTerrainSamplers() + { + SDL_GPUDevice* dev = renderer.device(); + if (sampler) + SDL_ReleaseGPUSampler(dev, sampler); + if (detailWrap) + SDL_ReleaseGPUSampler(dev, detailWrap); SDL_GPUSamplerCreateInfo sd{}; sd.min_filter = sd.mag_filter = SDL_GPU_FILTER_LINEAR; sd.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR; sd.address_mode_u = sd.address_mode_v = sd.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; sd.enable_anisotropy = true; sd.max_anisotropy = 8; + sd.min_lod = renderer.minLod(); // (low resolution textures: from the half size level) sd.max_lod = 1000; sampler = SDL_CreateGPUSampler(dev, &sd); sd.address_mode_u = sd.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_REPEAT; detailWrap = SDL_CreateGPUSampler(dev, &sd); if (!sampler || !detailWrap) throw std::runtime_error(std::string("terrain samplers: ") + SDL_GetError()); + terrainSamplerGeneration = renderer.samplerGeneration(); } // ------------------------------------------------------------ art @@ -2859,9 +2893,11 @@ float4 PSTerrain(PSIn i) : SV_Target const Vec3 c{ worldW() / 2 + dx, worldH() / 2, 0 }; return frustum.sphere(c, length(Vec3{ worldW(), worldH(), 0 }) / 2 + map.peakScale * S()); }; + if (terrainSamplerGeneration != renderer.samplerGeneration()) + makeTerrainSamplers(); renderer.reserveSamplers(6); SDL_GPURenderPass* pass = renderer.pass(); - renderer.bindPipeline(terrainPipeline); + renderer.bindPipeline(terrainPipelineFor(renderer.passSamples())); const SDL_GPUTextureSamplerBinding textures[6] = { { plotTex->texture, sampler }, { atlasTex->texture, sampler }, { decalTex->texture, detailWrap }, { detailTex->texture, detailWrap }, { cellTex->texture, sampler }, { borderTex->texture, sampler } }; SDL_BindGPUFragmentSamplers(pass, 0, textures, 6); @@ -3743,7 +3779,7 @@ float4 PSTerrain(PSIn i) : SV_Target m->drawInstances(m->features, frustum); if (options.improvements) m->drawInstances(m->decor, frustum); - if (options.cities) + if (options.cities && (options.globeBuildings || !m->renderer.globe())) m->drawInstances(m->cities, frustum); m->figureHits.clear(); if (options.units) diff --git a/src/render/MapView.h b/src/render/MapView.h index 815fbe6c..ac946f14 100644 --- a/src/render/MapView.h +++ b/src/render/MapView.h @@ -31,6 +31,7 @@ namespace oc4::render bool fog = false; // as the active team sees the map bool flags = true; // the units' flags bool healthBars = true, frozen = false, effects = true; // (the game's graphic options: health under the flags, idle figures still, no particles) + bool globeBuildings = true; // the cities' models in the globe view (Globe View Buildings Disabled: none) }; MapView(Renderer& renderer, const AssetResolver& assets); diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..9abacd32 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -244,6 +244,7 @@ namespace oc4::render std::function)> playMovieSound; std::function stopMovieSound; std::vector moviesDone; + bool lowMovieQuality = false; // (Movie Quality low: the map is not drawn while a movie plays) static std::string modelKey(const UiItem& it) { return std::format("{}|{}|{}|{}|{}|{}|{}", it.texture, it.texture2, it.modelTilt, it.modelTurn, it.modelScale, it.modelAnimated, it.modelLayers); @@ -1484,17 +1485,25 @@ namespace oc4::render renderer->setGlobe(g.x, g.y, g.radius, g.wrapWidth); fitFov(); // (beyond the map: black as the ground not seen, until the team's map is centred) - renderer->beginFrame(camera, view->seenBounds() ? Vec3{ 0, 0, 0 } : Vec3{ 0.05f, 0.07f, 0.10f }); - view->draw(); + // (a movie playing with the Movie Quality low: no map behind it, black, as the original) + const bool mapShown = !(lowMovieQuality && !movies.empty()); + renderer->beginFrame(camera, view->seenBounds() || !mapShown ? Vec3{ 0, 0, 0 } : Vec3{ 0.05f, 0.07f, 0.10f }); + if (mapShown) + view->draw(); + else + renderer->pass(); // (cleared, black, though nothing is drawn) renderer->endFrame(); syncHeads(); renderHeads(); if (!overlay->begin()) return; - view->drawOverlay(*overlay); - drawMarks(); - drawLayers(); - drawPath(); + if (mapShown) + { + view->drawOverlay(*overlay); + drawMarks(); + drawLayers(); + drawPath(); + } if (ui.active()) { // The game's own interface: it has the status, the scores, the unit's buttons. @@ -2480,6 +2489,13 @@ namespace oc4::render o.healthBars = g.healthBars; o.frozen = g.frozen; o.effects = g.effects; + o.globeBuildings = g.globeBuildings; + m->lowMovieQuality = g.lowMovieQuality; + if (m->renderer) + { + m->renderer->setLowResTextures(g.lowResTextures); + m->renderer->setSamples(uint32_t(std::max(1, g.samples))); + } setFullscreen(g.fullscreen); } diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..ad432709 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -273,6 +273,10 @@ namespace oc4::render struct Graphics { bool healthBars = false, frozen = false, effects = true, fullscreen = false; + bool globeBuildings = false; // the cities' models in the globe view + bool lowResTextures = false; // textures from their half size level + bool lowMovieQuality = false; // no map drawn behind a playing movie + int samples = 0; // anti-aliasing: the map's samples a pixel (0, 2, 4, 8) }; void setGraphics(Graphics graphics); // Full screen or windowed (the profile's option; the menu's too, not only a game's). diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp index a85442da..fb03f3b8 100644 --- a/src/render/Renderer.cpp +++ b/src/render/Renderer.cpp @@ -503,6 +503,8 @@ float4 PSOverlay(Out p) : SV_Target m_noPlots.reset(); m_color.reset(); m_depth.reset(); + m_msColor.reset(); + m_msDepth.reset(); m_particleVb.reset(); m_overlayVb.reset(); if (m_window) @@ -533,6 +535,50 @@ float4 PSOverlay(Out p) : SV_Target fail("SDL_CreateGPUTexture(depth)"); m_depth = std::make_shared(m_device, depth); m_target = { m_color->texture, m_depth->texture, m_width, m_height }; + createSampleTargets(); + } + + SDL_GPUSampleCount Renderer::sampleCount(uint32_t samples) + { + return samples >= 8 ? SDL_GPU_SAMPLECOUNT_8 : samples >= 4 ? SDL_GPU_SAMPLECOUNT_4 : samples >= 2 ? SDL_GPU_SAMPLECOUNT_2 : SDL_GPU_SAMPLECOUNT_1; + } + + void Renderer::createSampleTargets() + { + m_msColor.reset(); + m_msDepth.reset(); + // (as many samples as asked for that the device can do with both formats) + while (m_samples > 1 && !(SDL_GPUTextureSupportsSampleCount(m_device, colorFormat(), sampleCount(m_samples)) && + SDL_GPUTextureSupportsSampleCount(m_device, m_depthFormat, sampleCount(m_samples)))) + m_samples /= 2; + if (m_samples <= 1) + { + m_samples = 1; + return; + } + SDL_GPUTextureCreateInfo ci{}; + ci.type = SDL_GPU_TEXTURETYPE_2D; + ci.format = colorFormat(); + ci.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET; + ci.width = m_width; + ci.height = m_height; + ci.layer_count_or_depth = 1; + ci.num_levels = 1; + ci.sample_count = sampleCount(m_samples); + SDL_GPUTexture* color = SDL_CreateGPUTexture(m_device, &ci); + ci.format = m_depthFormat; + ci.usage = SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET; + SDL_GPUTexture* depth = color ? SDL_CreateGPUTexture(m_device, &ci) : nullptr; + if (!color || !depth) + { + if (color) + SDL_ReleaseGPUTexture(m_device, color); + m_samples = 1; // (none: drawn without) + return; + } + m_msColor = std::make_shared(m_device, color); + m_msColor->width = m_width, m_msColor->height = m_height; + m_msDepth = std::make_shared(m_device, depth); } void Renderer::resize(uint32_t width, uint32_t height) @@ -625,21 +671,7 @@ float4 PSOverlay(Out p) : SV_Target m_overlayVs = compile(kOverlayHlsl, "overlay.hlsl", "VSOverlay", SDL_GPU_SHADERSTAGE_VERTEX, 0, 0, 2); m_overlayPs = compile(kOverlayHlsl, "overlay.hlsl", "PSOverlay", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 0, 2); - for (int clamp = 0; clamp < 4; ++clamp) - { - // TexClamp: bit1 = S wraps, bit0 = T wraps. - SDL_GPUSamplerCreateInfo sd{}; - sd.min_filter = sd.mag_filter = SDL_GPU_FILTER_LINEAR; - sd.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR; - sd.address_mode_u = (clamp & 2) ? SDL_GPU_SAMPLERADDRESSMODE_REPEAT : SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; - sd.address_mode_v = (clamp & 1) ? SDL_GPU_SAMPLERADDRESSMODE_REPEAT : SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; - sd.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_REPEAT; - sd.enable_anisotropy = true; - sd.max_anisotropy = 8; - sd.max_lod = 1000; - if (!(m_samplers[clamp] = SDL_CreateGPUSampler(m_device, &sd))) - fail("SDL_CreateGPUSampler"); - } + makeSamplers(); SDL_GPUSamplerCreateInfo gd{}; gd.min_filter = gd.mag_filter = SDL_GPU_FILTER_LINEAR; gd.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR; @@ -658,8 +690,10 @@ float4 PSOverlay(Out p) : SV_Target m_noPlots = createTexture(1, 1, 1, 1, TextureFormat::RGBA16, std::span(&plots, 1)); } - SDL_GPUGraphicsPipeline* Renderer::pipeline(const PipelineKey& key) + SDL_GPUGraphicsPipeline* Renderer::pipeline(const PipelineKey& asked) { + PipelineKey key = asked; + key.samples = passSamples(); // (as many samples as the pass it is drawn in) if (const auto it = m_pipelines.find(key); it != m_pipelines.end()) return it->second; const bool overlay = key.kind == 1; @@ -709,6 +743,7 @@ float4 PSOverlay(Out p) : SV_Target ci.target_info.num_color_targets = 1; ci.target_info.depth_stencil_format = m_depthFormat; ci.target_info.has_depth_stencil_target = true; + ci.multisample_state.sample_count = sampleCount(key.samples); SDL_GPUGraphicsPipeline* p = SDL_CreateGPUGraphicsPipeline(m_device, &ci); if (!p) fail("SDL_CreateGPUGraphicsPipeline"); @@ -782,6 +817,14 @@ float4 PSOverlay(Out p) : SV_Target color.store_op = SDL_GPU_STOREOP_STORE; SDL_GPUDepthStencilTargetInfo depth{}; depth.texture = m_target.depth; + if (passSamples() > 1) + { + // (anti-aliasing: drawn into the samples, kept for the next pass, resolved into the target) + color.texture = m_msColor->texture; + color.resolve_texture = m_target.color; + color.store_op = SDL_GPU_STOREOP_RESOLVE_AND_STORE; + depth.texture = m_msDepth->texture; + } depth.load_op = depth.stencil_load_op = m_clearDepth ? SDL_GPU_LOADOP_CLEAR : SDL_GPU_LOADOP_LOAD; depth.store_op = depth.stencil_store_op = SDL_GPU_STOREOP_STORE; depth.clear_depth = 1; @@ -1073,9 +1116,43 @@ float4 PSOverlay(Out p) : SV_Target SDL_DrawGPUIndexedPrimitives(m_pass, mesh.indexCount, 1, 0, 0, 0); } + void Renderer::makeSamplers() + { + for (int clamp = 0; clamp < 4; ++clamp) + { + if (m_samplers[clamp]) + SDL_ReleaseGPUSampler(m_device, m_samplers[clamp]); + // TexClamp: bit1 = S wraps, bit0 = T wraps. + SDL_GPUSamplerCreateInfo sd{}; + sd.min_filter = sd.mag_filter = SDL_GPU_FILTER_LINEAR; + sd.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR; + sd.address_mode_u = (clamp & 2) ? SDL_GPU_SAMPLERADDRESSMODE_REPEAT : SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + sd.address_mode_v = (clamp & 1) ? SDL_GPU_SAMPLERADDRESSMODE_REPEAT : SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + sd.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_REPEAT; + sd.enable_anisotropy = true; + sd.max_anisotropy = 8; + sd.min_lod = minLod(); // (low resolution textures: from the half size level) + sd.max_lod = 1000; + if (!(m_samplers[clamp] = SDL_CreateGPUSampler(m_device, &sd))) + fail("SDL_CreateGPUSampler"); + } + ++m_samplerGeneration; + } + void Renderer::beginFrame(const Camera& camera, Vec3 clearColor) { endPass(); + if (m_lowResWanted != m_lowRes) + { + m_lowRes = m_lowResWanted; + makeSamplers(); + } + if (m_samplesWanted != m_samplesAsked && !m_inView) + { + // (as many as asked for, or the device's most) + m_samplesAsked = m_samples = m_samplesWanted; + createSampleTargets(); + } m_camera = camera; m_deferred.clear(); m_deferredWorlds.clear(); diff --git a/src/render/Renderer.h b/src/render/Renderer.h index 11c741a2..d871dae0 100644 --- a/src/render/Renderer.h +++ b/src/render/Renderer.h @@ -260,6 +260,19 @@ float3 globeBend(float3 p) // wrapping every wrapWidth (0: not). void setGlobe(float x, float y, float radius, float wrapWidth) { m_globe[0] = x, m_globe[1] = y, m_globe[2] = radius, m_globe[3] = wrapWidth; } bool globe() const { return m_globe[2] > 0; } + // Low resolution textures (the game's graphic option): every texture with mipmaps drawn + // from its half size level (the samplers' lowest level 1); from the next beginFrame. + void setLowResTextures(bool on) { m_lowResWanted = on; } + float minLod() const { return m_lowRes ? 1.0f : 0.0f; } + uint32_t samplerGeneration() const { return m_samplerGeneration; } // (changes with minLod) + // Anti-aliasing (the game's option): the main target drawn with this many samples a pixel + // (1, 2, 4, 8: as many as the device can), resolved into it at the end of each pass; from + // the next beginFrame. The views (setView) are drawn with one. + void setSamples(uint32_t samples) { m_samplesWanted = std::max(1u, samples); } + uint32_t samples() const { return m_samples; } + // The samples of the pass drawn now (a pipeline for it must have as many). + uint32_t passSamples() const { return (!m_target.color || m_target.color == m_color->texture) ? m_samples : 1; } + static SDL_GPUSampleCount sampleCount(uint32_t samples); // Row-major view-projection of the current frame (p_clip = M * p). const float* viewProjection() const { return m_viewProj; } // Cached by asset key; null when missing or unsupported (recorded in stats). @@ -280,10 +293,12 @@ float3 globeBend(float3 p) int src = 0, dst = 0; bool zTest = true, zWrite = true; int cull = 0; + uint32_t samples = 1; auto operator<=>(const PipelineKey&) const = default; }; void createTargets(); + void createSampleTargets(); void createPipelines(); SDL_GPUGraphicsPipeline* pipeline(const PipelineKey& key); SDL_GPUGraphicsPipeline* modelPipeline(const scene::Material& m, bool particles = false); @@ -303,6 +318,8 @@ float3 globeBend(float3 p) uint32_t m_width = 0, m_height = 0; SDL_GPUTextureFormat m_depthFormat = SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT; std::shared_ptr m_color, m_depth; + std::shared_ptr m_msColor, m_msDepth; // (anti-aliasing: the main target's samples, resolved into m_color) + uint32_t m_samples = 1, m_samplesWanted = 1, m_samplesAsked = 1; SDL_GPUCommandBuffer* m_cmd = nullptr; uint32_t m_samplersUsed = 0; // (in m_cmd) @@ -318,6 +335,9 @@ float3 globeBend(float3 p) SDL_GPUShader* m_overlayPs = nullptr; std::map m_pipelines; SDL_GPUSampler* m_samplers[4]{}; // by scene::TexClamp + bool m_lowRes = false, m_lowResWanted = false; + uint32_t m_samplerGeneration = 0; + void makeSamplers(); SDL_GPUSampler* m_linearClamp = nullptr; std::shared_ptr m_white, m_noHeights, m_noPlots; const GpuImage* m_ground = nullptr; From e6ab2886a96f3433f43e0d263a9ac9d4532627eb Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 08:17:45 +0100 Subject: [PATCH 47/89] Scroll bars: drag the grip, arrows and paging as the original's Every scroll bar of the screens (scroll panels, tables, list boxes, multi-line texts, the Civilopedia, the menus' lists) is one control: oc4screens' scroll bar item, drawn and pressed in UiLayer. It only jumped on a click; its grip could not be dragged. Now, as GFC's scroll bar in the original: - the grip follows the mouse from where it was taken, also off the bar and out of the window, until the button is let go (theme's Press look while held); - an arrow at each end (the theme's Up/Down/Left/Right buttons, 16 long) steps a line, the shaft a page; both repeat while held (250 ms, then every 90 ms), the shaft until the grip reaches the mouse (its Press look meanwhile); - the open pull down's list, which only took the wheel, gets the combo box's own bar (SF_CtrlTheme_Civ4_Control_ComboBox_Standard_Scroll_Style: 18 wide, 22 long arrows) inside it on the right. The bar's request is kept in UiLayer and handed over with the clicks, for the item as the screens have it then: the screens are made again while dragging, and a queued index pointed at another widget. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 13 +++ apps/oc4core/python/oc4screens.py | 57 +++++++++-- src/render/MapWindow.cpp | 29 +++++- src/render/MapWindow.h | 5 + src/render/UiLayer.cpp | 165 ++++++++++++++++++++++++++---- src/render/UiLayer.h | 38 ++++++- 6 files changed, 276 insertions(+), 31 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 5c35d37b..439866a1 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -1306,6 +1306,19 @@ if _walls: printPythonError(e); } } + else if (size_t(click.item) < m_items.size() && (click.barTo >= 0 || click.barStep != 0)) + { + // A scroll bar held: what it scrolls follows its grip, or steps a line or a page. + const Item& it = m_items[size_t(click.item)]; + try + { + py::module_::import("oc4screens").attr("scrollBar")(it.screen, it.name, it.part, click.barTo, click.barStep); + } + catch (py::error_already_set& e) + { + printPythonError(e); + } + } else if (size_t(click.item) < m_items.size()) { if (std::getenv("OC4_PLAY_LOG")) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..99cc2660 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -30,7 +30,7 @@ _citySelection = [()] # the cities a table's rows selected last _drop = [None, 0] # the pull down whose list is open (file id, name), and how far that list is scrolled _areas = [] # what scrolls under the mouse, back to front: (x0, y0, x1, y1, file id, name, step, down, sideways) -_bars = {} # the scroll bars: (file id, name, part) -> (x0, y0, x1, y1) +_bars = {} # the scroll bars: (file id, name, part) -> (x0, y0, x1, y1, a line's step) _dropRects = {} # where each pull down is: (file id, name) -> (x0, y0, x1, y1) _editFocus = [None] # the edit box typed into: (file id, name), or None @@ -1430,6 +1430,7 @@ def version(): _LIST_ROW = 20 # a list box's row, and a step of the wheel in what scrolls by pixels _DROP_ROW = 22 # a row of a pull down's open list +_DROP_BAR = 18 # its scroll bar's width (the combo box's: a 7 wide rail in the middle) _heights = {} # (text, width, font) -> how high it is @@ -1482,12 +1483,12 @@ def _scrolls(w, x0, y0, x1, y1, fileId, step, out, sideways=False): _areas.append((x0, y0, x1, y1, fileId, w.name, step, down, across)) # (over what the widget holds: nearer than anything of its screen) if down: - _bars[(fileId, w.name, -2)] = (x1 - _BAR, y0, x1, y1) + _bars[(fileId, w.name, -2)] = (x1 - _BAR, y0, x1, y1, step) out.append(((fileId, w.name, -2), 'scrollbar', x1 - _BAR, y0, x1, y1, None, '', u'', '', '', 0, 0, False, True, 0, None, -1, -1, -1, False, -1000.0, w.seq, float(offset) / w.extent, float(high) / w.extent)) if across: right = x1 - (_BAR if down else 0) - _bars[(fileId, w.name, -3)] = (x0, y1 - _BAR, right, y1) + _bars[(fileId, w.name, -3)] = (x0, y1 - _BAR, right, y1, step) out.append(((fileId, w.name, -3), 'scrollbar', x0, y1 - _BAR, right, y1, None, '', u'', '', '', 0, 0, False, True, 0, None, -1, -1, -1, False, -1000.0, w.seq, float(hoffset) / w.hextent, float(wide) / w.hextent)) @@ -1764,11 +1765,12 @@ def _dropList(out): _drop[0] = None return n = len(w.items) - width = r[2] - r[0] - for item in w.items: - width = max(width, _textWidth(item[0]) + 24) below, above = _resolution[1] - r[3] - 12, r[1] - 12 rows = min(n, max(1, max(below, above) // _DROP_ROW)) + bar = _DROP_BAR if n > rows else 0 + width = r[2] - r[0] + for item in w.items: + width = max(width, _textWidth(item[0]) + 24 + bar) height = rows * _DROP_ROW + 8 y0 = r[3] if below >= height or below >= above else r[1] - height x0 = max(0, min(r[0], _resolution[0] - width)) @@ -1782,9 +1784,14 @@ def _dropList(out): cy = top - _drop[1] for i, item in enumerate(w.items): if cy + _DROP_ROW > top and cy < box[3]: - out.append(((s.id, w.name, i), 'option', x0, cy, x0 + width, cy + _DROP_ROW, box, '__option', item[0], '', '', 2, _FONT_LEFT, i == w.selected, - True, 0, None, -1, -1, -1, False, 0, 0)) + out.append(((s.id, w.name, i), 'option', x0, cy, x0 + width - bar, cy + _DROP_ROW, box, '__option', item[0], '', '', 2, _FONT_LEFT, + i == w.selected, True, 0, None, -1, -1, -1, False, 0, 0)) cy += _DROP_ROW + if bar: + # (its scroll bar, the combo box's own: inside the list on its right, as the original's) + whole = n * _DROP_ROW + out.append(((s.id, w.name, -4), 'scrollbar', x0 + width - bar, top, x0 + width, box[3], None, '__combo', u'', '', '', 0, 0, False, True, 0, + None, -1, -1, -1, False, 0, 0, float(_drop[1]) / whole, float(rows * _DROP_ROW) / whole)) _widths = {} # (text, font) -> how wide it is @@ -1843,6 +1850,40 @@ def scrollTo(fileId, name, part, x, y): _set(w, 'hoffset', int(max(0, min(w.hextent - wide, at * w.hextent - wide / 2)))) +def scrollBar(fileId, name, part, to, step): + """A scroll bar held: what it scrolls is put where its grip was dragged (`to`, how far along, + as a part of all it holds), or moved a line (`step` -1 back, 1 on: its arrows) or a page (-2, + 2: its shaft). Part -4 is the open pull down list's bar; any other closes that list.""" + fileId, name, part, to, step = int(fileId), _str(name), int(part), float(to), int(step) + if part == -4: + s = _screens.get(fileId) + w = s.get(name) if s is not None else None + r = [a for a in _areas if a[4] == -1] + if w is None or _drop[0] != (fileId, name) or not r: + return + shown = r[0][3] - r[0][1] + whole = len(w.items) * _DROP_ROW + at = to * whole if to >= 0 else _drop[1] + (_DROP_ROW if abs(step) == 1 else shown) * (1 if step > 0 else -1) + _drop[1] = int(max(0, min(whole - shown, round(at)))) + _changed() + return + closeDropdown() + r = _bars.get((fileId, name, part)) + s = _screens.get(fileId) + w = s.get(name) if s is not None else None + if r is None or w is None: + return + if part == -2: + key, shown, whole = 'offset', r[3] - r[1], w.extent + else: + key, shown, whole = 'hoffset', r[2] - r[0], w.hextent + if to >= 0: + at = to * whole + else: + at = getattr(w, key) + (r[4] if abs(step) == 1 else shown) * (1 if step > 0 else -1) + _set(w, key, int(max(0, min(whole - shown, round(at))))) + + def openDropdown(fileId, name): """A click on a pull down opens its list, or closes it when it is open.""" key = (int(fileId), _str(name)) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..7bb7cd05 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -1128,7 +1128,9 @@ namespace oc4::render mouseY = y; popup.hover(x, y); ui.hover(x, y); - if (minimapDrag) + if (ui.barHeld()) + ui.holdBar(x, y); + else if (minimapDrag) jumpFromMinimap(std::clamp(x, int(minimapRect[0]), int(minimapRect[2])), std::clamp(y, int(minimapRect[1]), int(minimapRect[3]))); else if (panning) { @@ -1181,6 +1183,21 @@ namespace oc4::render { downOnUi = true; ui.press(x, y, !left); + // (a scroll bar is held: its arrows and shaft step, its grip follows the mouse, until let go) + if (left) + { + ui.pressBar(x, y); + if (ui.barHeld()) + SDL_CaptureMouse(true); + } + return; + } + if (!down && ui.barHeld()) + { + SDL_CaptureMouse(false); + ui.releaseBar(); + downOnUi = false; + ui.release(x, y, mods.shift, mods.ctrl, mods.alt); return; } if (!down && std::exchange(downOnUi, false)) @@ -2218,6 +2235,8 @@ namespace oc4::render frameStats.add(std::chrono::duration(now - lastFrame).count()); lastFrame = now; clock += dt; + if (ui.barHeld()) + ui.holdBar(mouseX, mouseY); handlePad(dt); handleHeldKeys(dt); easeZoom(dt); @@ -2611,7 +2630,13 @@ namespace oc4::render void MapWindow::pressKey(unsigned key) { m->onKey(key); } MapWindow::UiDisplay MapWindow::uiDisplay() const { return { m->renderer->width(), m->renderer->height(), m->windowDensity() }; } bool MapWindow::uiActive() const { return m->ui.active(); } - std::vector MapWindow::takeUiClicks() { return std::exchange(m->uiClicks, {}); } + std::vector MapWindow::takeUiClicks() + { + // (a scroll bar held: its latest, for the item as the screens have it now) + if (const auto bar = m->ui.takeBarClick()) + m->uiClicks.push_back(*bar); + return std::exchange(m->uiClicks, {}); + } void MapWindow::setUiTextFocus(bool focus) { m->uiTextFocus = focus; } std::wstring MapWindow::takeUiTyped() { return std::exchange(m->uiTyped, {}); } void MapWindow::typeText(const std::string& utf8) diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..9e1befd3 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -333,6 +333,11 @@ namespace oc4::render { int item = -1; // -1: on the screens but on none of their widgets bool right = false, shift = false, ctrl = false, alt = false; + // A scroll bar held: its grip dragged to barTo (how far along what it scrolls, as a part + // of all that it holds; -1 not dragged), or a step of a line (barStep +-1, its arrows) or + // a page (+-2, its shaft). + float barTo = -1; + int barStep = 0; }; std::vector takeUiClicks(); // How wide a text with the screens' markup is, in the theme's font (size 2 outside its diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 4c54726a..f66a9079 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -71,14 +71,28 @@ namespace oc4::render m_dropBorder = m_theme.skin("SF_CtrlTheme_Civ4_Control_ComboBox_Standard_PopupBoxTableBorder_Style", "GFC_CtrlTheme_Bitmap_Control_Border_Skin_Full_Default"); m_dropSelect = m_theme.skin(combo, "GFC_CtrlTheme_Bitmap_Control_ComboBox_Skin_PopupItem_Select"); - constexpr std::string_view scroll = "GFC_Control_StandardScroll_Style"; - m_shaft = { m_theme.skin(scroll, "GFC_CtrlTheme_Bitmap_Control_Scroll_Skin_VShaft_Default"), - m_theme.skin(scroll, "GFC_CtrlTheme_Bitmap_Control_Scroll_Skin_HShaft_Default") }; - for (size_t d = 0; d < 2; ++d) + // The scroll bars: the standard one (GFC_Control_StandardScroll_Style) and the pull down + // list's (the combo box's), each with its arrows, shaft and grip. + constexpr std::string_view bs = "GFC_CtrlTheme_Bitmap_Control_Button_Skin_"; + const auto barSkin = [&](std::string_view style, std::string_view state) { return m_theme.skin(style, std::string(bs) + std::string(state)); }; + constexpr std::array states{ "Default", "Rollover", "Press" }; + for (size_t look = 0; look < 2; ++look) { - const std::string_view grip = d == 0 ? "SF_CtrlTheme_Civ4_Control_Scroll_VGripButton_Style" : "SF_CtrlTheme_Civ4_Control_Scroll_HGripButton_Style"; - m_grip[d] = { m_theme.skin(grip, "GFC_CtrlTheme_Bitmap_Control_Button_Skin_Default"), - m_theme.skin(grip, "GFC_CtrlTheme_Bitmap_Control_Button_Skin_Rollover") }; + BarLook& b = m_bar[look]; + const std::string prefix = look == 0 ? "SF_CtrlTheme_Civ4_Control_Scroll_" : "SF_CtrlTheme_Civ4_Control_ComboBox_Standard_Scroll_"; + const std::string_view scroll = look == 0 ? "GFC_Control_StandardScroll_Style" : "SF_CtrlTheme_Civ4_Control_ComboBox_Standard_Scroll_Style"; + for (size_t d = 0; d < 2; ++d) + { + const std::string shaft = std::string("GFC_CtrlTheme_Bitmap_Control_Scroll_Skin_") + (d == 0 ? "VShaft_" : "HShaft_"); + b.shaft[d] = { m_theme.skin(scroll, shaft + "Default"), m_theme.skin(scroll, shaft + "Press") }; + const std::string grip = prefix + (d == 0 ? "VGrip" : "HGrip") + (look == 0 ? "Button_Style" : "_Style"); + for (size_t k = 0; k < 3; ++k) + b.grip[d][k] = barSkin(grip, states[k]); + } + constexpr std::array arrows{ "UpButton", "DownButton", "LeftButton", "RightButton" }; + for (size_t a = 0; a < 4; ++a) + for (size_t k = 0; k < 3; ++k) + b.arrow[a][k] = barSkin(prefix + std::string(arrows[a]) + "_Style", states[k]); } } // (the screens are made again whenever something on them changes, often between a press @@ -97,6 +111,13 @@ namespace oc4::render break; } } + if (m_barClick) + { + if (m_pressed >= 0) + m_barClick->item = m_pressed; + else + m_barClick.reset(); + } m_hover = m_mouseX >= 0 ? hit(m_mouseX, m_mouseY) : m_hover < int(m_items.size()) ? m_hover : -1; // (the keyboard's choice: the same item, or what is now nearest it) if (m_keyHover) @@ -322,6 +343,89 @@ namespace oc4::render return MapWindow::UiClick{ pressed, m_pressedRight, shift, ctrl, alt }; } + UiLayer::BarParts UiLayer::barParts(const Item& it) + { + // (the standard bar's arrows are as long as it is wide, 16, its grip at least 16; the + // pull down list's arrows 22, its grip at least 7: as the original draws them) + BarParts p; + p.down = it.y1 - it.y0 >= it.x1 - it.x0; + p.a0 = p.down ? it.y0 : it.x0; + p.a1 = p.down ? it.y1 : it.x1; + const bool combo = it.style == "__combo"; + const float length = p.a1 - p.a0, minGrip = combo ? 7.0f : 16.0f; + const float arrow = std::clamp((length - minGrip) / 2, 0.0f, combo ? 22.0f : (p.down ? it.x1 - it.x0 : it.y1 - it.y0)); + p.t0 = p.a0 + arrow; + p.t1 = p.a1 - arrow; + const float track = p.t1 - p.t0, shown = std::clamp(it.barPercent, 0.0f, 1.0f); + const float grip = std::min(track, std::max(minGrip, track * shown)); + const float at = shown < 1 ? std::clamp(it.barStart / (1 - shown), 0.0f, 1.0f) : 0.0f; + p.g0 = p.t0 + (track - grip) * at; + p.g1 = p.g0 + grip; + return p; + } + + UiLayer::BarPart UiLayer::barPartAt(const Item& it, int x, int y) const + { + if (!inside(it, x, y)) + return BarPart::None; + const BarParts p = barParts(it); + const float a = float(p.down ? y : x); + return a < p.t0 ? BarPart::Back : a >= p.t1 ? BarPart::Forward : a < p.g0 ? BarPart::PageBack : a >= p.g1 ? BarPart::PageForward : BarPart::Grip; + } + + void UiLayer::pressBar(int x, int y) + { + m_barPart = BarPart::None; + m_barClick.reset(); + if (m_pressed < 0 || m_pressedRight || m_items[size_t(m_pressed)].kind != Kind::Scrollbar || !m_items[size_t(m_pressed)].enabled) + return; + const Item& it = m_items[size_t(m_pressed)]; + m_barPart = barPartAt(it, x, y); + if (m_barPart == BarPart::Grip) + { + const BarParts p = barParts(it); + m_barGrab = float(p.down ? y : x) - p.g0; + return; + } + m_barNext = std::chrono::steady_clock::now() + std::chrono::milliseconds(250); + barStep(x, y); + } + + void UiLayer::barStep(int x, int y) + { + // (an arrow steps while the mouse is on it; the shaft pages until the grip is under the mouse) + if (barPartAt(m_items[size_t(m_pressed)], x, y) != m_barPart) + return; + m_barClick = MapWindow::UiClick{ m_pressed }; + m_barClick->barStep = m_barPart == BarPart::Back ? -1 : m_barPart == BarPart::Forward ? 1 : m_barPart == BarPart::PageBack ? -2 : 2; + } + + void UiLayer::holdBar(int x, int y) + { + if (!barHeld() || m_pressed < 0) + return; + const Item& it = m_items[size_t(m_pressed)]; + if (m_barPart == BarPart::Grip) + { + // (the grip's start where the mouse has it, as a part of the way it can go, as a part of + // all that is scrolled) + const BarParts p = barParts(it); + const float room = (p.t1 - p.t0) - (p.g1 - p.g0), shown = std::clamp(it.barPercent, 0.0f, 1.0f); + const float at = room > 0 ? std::clamp((float(p.down ? y : x) - m_barGrab - p.t0) / room, 0.0f, 1.0f) : 0.0f; + const float to = at * (1 - shown); + if (std::abs(to - std::clamp(it.barStart, 0.0f, 1.0f)) < 1e-4f) + return; + m_barClick = MapWindow::UiClick{ m_pressed }; + m_barClick->barTo = to; + return; + } + const auto now = std::chrono::steady_clock::now(); + if (now < m_barNext) + return; + m_barNext = now + std::chrono::milliseconds(90); + barStep(x, y); + } + void UiLayer::setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown) { m_help = widen(text); @@ -601,21 +705,44 @@ namespace oc4::render break; case Kind::Scrollbar: { - // A scroll bar on the edge of what scrolls: its shaft, and its grip as long as the part - // shown and where it is (the theme's look, or a dark track with a light grip). - const bool down = h >= w; - const size_t d = down ? 0 : 1; - const float length = down ? h : w, grip = std::max(20.0f, length * std::clamp(it.barPercent, 0.0f, 1.0f)); - const float at = std::clamp(it.barStart, 0.0f, 1.0f) * length, from = std::min(at, length - grip); - const float gx0 = down ? x0 : x0 + from, gy0 = down ? y0 + from : y0, gx1 = down ? x1 : gx0 + grip, gy1 = down ? gy0 + grip : y1; - if (!m_shaft[d].empty()) - Theme::draw(o, m_shaft[d], x0, y0, x1, y1); + // A scroll bar on the edge of what scrolls: its shaft, an arrow at each end, and its + // grip as long as the part shown and where it is (the theme's look, or a dark track + // with a light grip); pressed, held or under the mouse as the mouse has them. + const BarParts p = barParts(it); + const size_t d = p.down ? 0 : 1; + const BarLook& look = m_bar[it.style == "__combo" ? 1 : 0]; + const bool held = int(i) == m_pressed && barHeld(); + const BarPart under = hot && !barHeld() ? barPartAt(it, m_mouseX, m_mouseY) : BarPart::None; + const auto along = [&](float a, float b, float& rx0, float& ry0, float& rx1, float& ry1) { + rx0 = p.down ? x0 : a, ry0 = p.down ? a : y0, rx1 = p.down ? x1 : b, ry1 = p.down ? b : y1; + }; + const auto state = [&](BarPart part) { return held && m_barPart == part ? 2 : under == part ? 1 : 0; }; + const auto skin = [](const auto& states, int k) -> const Theme::Skin& { + return !states[size_t(k)].empty() ? states[size_t(k)] : states[0]; + }; + float rx0, ry0, rx1, ry1; + along(p.t0, p.t1, rx0, ry0, rx1, ry1); + const bool paging = held && (m_barPart == BarPart::PageBack || m_barPart == BarPart::PageForward); + if (!look.shaft[d][0].empty()) + Theme::draw(o, skin(look.shaft[d], paging ? 1 : 0), rx0, ry0, rx1, ry1); else o.rect(x0, y0, x1, y1, { 0.05f, 0.06f, 0.09f }, 0.6f, 3); - if (!m_grip[d][0].empty()) - Theme::draw(o, m_grip[d][hot && !m_grip[d][1].empty() ? 1 : 0], gx0, gy0, gx1, gy1); + for (int end = 0; end < 2 && p.t0 > p.a0; ++end) + { + const BarPart part = end == 0 ? BarPart::Back : BarPart::Forward; + const auto& arrow = look.arrow[d * 2 + size_t(end)]; + if (end == 0) + along(p.a0, p.t0, rx0, ry0, rx1, ry1); + else + along(p.t1, p.a1, rx0, ry0, rx1, ry1); + if (!arrow[0].empty()) + Theme::draw(o, skin(arrow, state(part)), rx0, ry0, rx1, ry1); + } + along(p.g0, p.g1, rx0, ry0, rx1, ry1); + if (!look.grip[d][0].empty()) + Theme::draw(o, skin(look.grip[d], state(BarPart::Grip)), rx0, ry0, rx1, ry1); else - o.rect(gx0 + 2, gy0 + 2, gx1 - 2, gy1 - 2, hot ? kHot : kEdge, 0.8f, 3); + o.rect(rx0 + 2, ry0 + 2, rx1 - 2, ry1 - 2, state(BarPart::Grip) ? kHot : kEdge, 0.8f, 3); break; } case Kind::Flag: diff --git a/src/render/UiLayer.h b/src/render/UiLayer.h index f9292882..38022aaf 100644 --- a/src/render/UiLayer.h +++ b/src/render/UiLayer.h @@ -12,6 +12,7 @@ #include "render/Theme.h" #include +#include #include #include #include @@ -57,6 +58,17 @@ namespace oc4::render // A press and its release on the same item make a click. void press(int x, int y, bool right); std::optional release(int x, int y, bool shift, bool ctrl, bool alt); + // A scroll bar pressed with the left button (after press): its arrows step a line and its + // shaft a page, again and again while held (the theme's 250 ms, then every 90 ms; the + // shaft until the grip reaches the mouse); its grip follows the mouse, wherever it goes, + // until the button is let go. holdBar: the mouse moved or time passed. + // What that asks of the screens is taken with takeBarClick (the latest: it stays with the + // bar when the screens are made again before it is taken). + void pressBar(int x, int y); + void holdBar(int x, int y); + void releaseBar() { m_barPart = BarPart::None; } + bool barHeld() const { return m_barPart != BarPart::None; } + std::optional takeBarClick() { return std::exchange(m_barClick, std::nullopt); } void setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown); // The size of a widget's font (FontTypes) as the screens draw it. @@ -71,6 +83,16 @@ namespace oc4::render private: using Item = MapWindow::UiItem; + enum class BarPart { None, Back, Forward, PageBack, PageForward, Grip }; + // A scroll bar's parts along it: its ends, its shaft's (between its arrows) and its grip's. + struct BarParts + { + bool down = true; // (up and down; else across) + float a0 = 0, t0 = 0, t1 = 0, a1 = 0, g0 = 0, g1 = 0; + }; + static BarParts barParts(const Item& it); + BarPart barPartAt(const Item& it, int x, int y) const; + void barStep(int x, int y); bool inside(const Item& item, int x, int y) const; // What can be reached now: nothing clipped away or covered by a screen on top. std::vector reachable() const; @@ -94,8 +116,20 @@ namespace oc4::render Theme::Skin m_dropInner, m_dropBorder, m_dropSelect; // The theme's scroll bars (GFC_Control_StandardScroll_Style): the shaft, up and down and // across, and the grip, plain and under the mouse. - std::array m_shaft; - std::array, 2> m_grip; + // Its arrows (up, down, left, right) plain, under the mouse and pressed. The open pull + // down's list has the combo box's own (SF_CtrlTheme_Civ4_Control_ComboBox_Standard_Scroll_Style): + // look 1. Shaft: plain and pressed, up and across; grip: plain, under the mouse and pressed. + struct BarLook + { + std::array, 2> shaft; + std::array, 2> grip; + std::array, 4> arrow; + }; + std::array m_bar; + BarPart m_barPart = BarPart::None; + float m_barGrab = 0; // (where along the grip it was taken) + std::optional m_barClick; + std::chrono::steady_clock::time_point m_barNext; // (the next step while an arrow or the shaft is held) std::array m_sizes{ 10, 12, 14, 16, 22 }; // the markup's (the theme's) std::vector m_items; int m_hover = -1, m_pressed = -1; From ca2a2957d23c83e637bc1bac00f0410ea5acc3dd Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 08:20:11 +0100 Subject: [PATCH 48/89] Popups: their list's grip follows the mouse while held The engine's popups (PopupPanel) draw their own thin grip by a long list; it took only the wheel. Pressed, it now follows the mouse (anywhere, until let go), as the screens' scroll bars. Co-Authored-By: Claude Opus 5.5 --- src/render/MapWindow.cpp | 14 +++++++++++++- src/render/PopupPanel.cpp | 22 ++++++++++++++++++++-- src/render/PopupPanel.h | 8 ++++++++ 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index 7bb7cd05..fe040db4 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -1130,6 +1130,8 @@ namespace oc4::render ui.hover(x, y); if (ui.barHeld()) ui.holdBar(x, y); + else if (popup.gripHeld()) + popup.dragGrip(y); else if (minimapDrag) jumpFromMinimap(std::clamp(x, int(minimapRect[0]), int(minimapRect[2])), std::clamp(y, int(minimapRect[1]), int(minimapRect[3]))); else if (panning) @@ -1165,7 +1167,17 @@ namespace oc4::render // On a popup: its buttons (the map around it still pans). if (down && popup.contains(x, y)) { - downOnPopup = true; + // (its list's grip follows the mouse while held) + if (left && popup.pressGrip(x, y)) + SDL_CaptureMouse(true); + else + downOnPopup = true; + return; + } + if (!down && popup.gripHeld()) + { + SDL_CaptureMouse(false); + popup.releaseGrip(); return; } // On the main interface's minimap: the camera goes there (and follows while held), as the diff --git a/src/render/PopupPanel.cpp b/src/render/PopupPanel.cpp index e97dfac5..5748be49 100644 --- a/src/render/PopupPanel.cpp +++ b/src/render/PopupPanel.cpp @@ -72,6 +72,7 @@ namespace oc4::render m_items.clear(); m_answered = false; m_scroll = 0; + m_gripHeld = false; m_hover = -1; m_helpItem = -2; m_hoverOk = false; @@ -159,6 +160,21 @@ namespace oc4::render return true; } + bool PopupPanel::pressGrip(int x, int y) + { + m_gripHeld = active() && m_scrollMax > 0 && m_grip.contains(float(x), float(y)); + m_gripGrab = float(y) - m_grip.y0; + return m_gripHeld; + } + + void PopupPanel::dragGrip(int y) + { + const float room = (m_list.y1 - m_list.y0) - (m_grip.y1 - m_grip.y0); + if (!m_gripHeld || room <= 0) + return; + m_scroll = std::clamp((float(y) - m_gripGrab - m_list.y0) / room, 0.0f, 1.0f) * m_scrollMax; + } + bool PopupPanel::key(unsigned virtualKey) { if (!m_view) @@ -376,12 +392,14 @@ namespace oc4::render o.frame(r.x0 - 2, r.y0 + 1, r.x1 + 2, r.y1 - 1, kKeyChoice, 1, 3, 2); } o.unclip(); + m_grip = {}; if (m_scrollMax > 0) { - // Where the list is. + // Where the list is (its grip can be taken a few pixels either side). const float track = m_list.y1 - m_list.y0, thumb = std::max(24.0f, track * listHeight / content); const float ty = m_list.y0 + (track - thumb) * (m_scroll / m_scrollMax); - o.rect(x0 + w - kPadX - 4, ty, x0 + w - kPadX + 1, ty + thumb, kEdge, 0.6f, 2); + o.rect(x0 + w - kPadX - 4, ty, x0 + w - kPadX + 1, ty + thumb, kEdge, m_gripHeld ? 0.9f : 0.6f, 2); + m_grip = { x0 + w - kPadX - 8, ty, x0 + w - kPadX + 5, ty + thumb }; } m_ok = {}; if (m_view->okButton) diff --git a/src/render/PopupPanel.h b/src/render/PopupPanel.h index 3d143252..9f188685 100644 --- a/src/render/PopupPanel.h +++ b/src/render/PopupPanel.h @@ -33,6 +33,11 @@ namespace oc4::render void hover(int x, int y); bool click(int x, int y); bool wheel(int x, int y, int delta); + // Its list's grip pressed (whether it was): the list follows the mouse until let go. + bool pressGrip(int x, int y); + void dragGrip(int y); + void releaseGrip() { m_gripHeld = false; } + bool gripHeld() const { return m_gripHeld; } bool key(unsigned virtualKey); // A character typed (WM_CHAR): into the edit box that has the focus. bool character(wchar_t c); @@ -67,6 +72,9 @@ namespace oc4::render std::optional m_answer; bool m_answered = false; float m_scroll = 0, m_scrollMax = 0; + Rect m_grip; // where the list's grip was drawn (empty: none) + bool m_gripHeld = false; + float m_gripGrab = 0; // (where on it it was taken) Rect m_panel, m_list, m_ok; std::vector m_items; // where each item was drawn (empty: not shown) int m_hover = -1, m_helpItem = -2; From 29854ab0f10d05ddad1d3ab2ebace889fc376eaa Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 11:31:41 +0100 Subject: [PATCH 49/89] Popups: 400 wide, 18 from the right, 19 under the last button, as the original's Measured against the original (Wine, 1600 x 900 and 1280 x 1000; the civic, build and game menu popups): - Every popup's rim ends 18 from the window's right edge (1582 at 1600 wide): the popups are 400 wide (1182-1582), not 396 ending at 1578. - Under a last stone button the original leaves 19 to the bottom rim, 3 more than the window's margin gave. - A stone button is its text's height and 3 (at least 25): with the game's font (Sylfaen, a 22 line) one line is 25 and two lines 47, as the original's; text + 5 made them 27 and 49. Co-Authored-By: Claude Opus 5.5 --- src/render/PopupPanel.cpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/render/PopupPanel.cpp b/src/render/PopupPanel.cpp index 4f58ba5b..d4821a79 100644 --- a/src/render/PopupPanel.cpp +++ b/src/render/PopupPanel.cpp @@ -25,7 +25,7 @@ namespace oc4::render } // (as the game's popups: their width, margins, the choices' pictures, the OK button's height) - constexpr float kWidth = 396, kPadX = 21, kPadTop = 18, kPadBottom = 20, kIcon = 28, kOk = 24; + constexpr float kWidth = 400, kPadX = 21, kPadTop = 18, kPadBottom = 20, kIcon = 28, kOk = 24; constexpr float kStoneLine = 25, kStoneGap = 6, kStoneInset = 9; // (a choice's stone button) constexpr Color kFocus{ 0.45f, 0.62f, 0.95f }; // (the focus rim on the first) constexpr Color kPanel{ 0.05f, 0.06f, 0.09f }, kEdge{ 0.78f, 0.64f, 0.36f }, kText{ 0.97f, 0.97f, 0.97f }, kHot{ 1, 0.83f, 0.49f }; @@ -241,7 +241,7 @@ namespace oc4::render // As the game's: its width, at the right under the top bar (in the middle when narrow). const float w = std::min(kWidth, sw - 40), inner = w - 2 * kPadX; const bool right = sw >= 2.5f * w && !m_view->centered; - const float x0 = right ? sw - 22 - w : (sw - w) / 2; // (Wine at 1600 x 900: its rim at 1182, 79) + const float x0 = right ? sw - 18 - w : (sw - w) / 2; // (Wine at 1600 x 900: its rim 1182-1582 from 77; 1280 wide, the game menu's at 1262) const std::wstring header = widen(m_view->header); std::vector texts(items.size()); std::vector heights(items.size()); @@ -255,9 +255,10 @@ namespace oc4::render { case Kind::Text: heights[i] = o.richHeight(texts[i], inner, m_textSize, false) + 10; break; case Kind::Button: - // (on the theme's stone button, as the original's: 25 high for a line, 6 apart, the - // text 9 in; measured in Wine at 1600 x 900) - heights[i] = stone ? std::max(kIcon * (icon ? 1.0f : 0.0f), std::max(kStoneLine, o.richHeight(texts[i], inner - 2 * kStoneInset - (icon ? kIcon + 5 : 0), m_textSize, false) + 5)) + kStoneGap + // (on the theme's stone button, as the original's: 25 high for a line, the text's + // height and 3 for more (two lines of the game font: 47), 6 apart, the text 9 in; + // measured in Wine at 1600 x 900) + heights[i] = stone ? std::max(kIcon * (icon ? 1.0f : 0.0f), std::max(kStoneLine, o.richHeight(texts[i], inner - 2 * kStoneInset - (icon ? kIcon + 5 : 0), m_textSize, false) + 3)) + kStoneGap : std::max(kIcon, o.richHeight(texts[i], inner - (icon ? kIcon + 5 : 0), m_textSize, false)) + 8; break; case Kind::Radio: @@ -271,8 +272,10 @@ namespace oc4::render const float headerHeight = header.empty() ? 0.0f : o.richHeight(header, inner, m_headerSize, false) + 10; const float okHeight = m_view->okButton ? kOk + 10 : 0.0f; float y0 = right ? 77.0f : 30.0f; - const float listHeight = std::max(0.0f, std::min(content, sh - y0 - 20 - headerHeight - okHeight - kPadTop - kPadBottom)); - const float h = kPadTop + headerHeight + listHeight + okHeight + kPadBottom; + // (the original leaves 19 under a last stone button to the rim: 3 more than the margin) + const float tail = stone && !items.empty() && items.back().kind == Kind::Button && !m_view->okButton ? 3.0f : 0.0f; + const float listHeight = std::max(0.0f, std::min(content, sh - y0 - 20 - headerHeight - okHeight - kPadTop - kPadBottom - tail)); + const float h = kPadTop + headerHeight + listHeight + okHeight + kPadBottom + tail; if (!right) y0 = std::max(30.0f, (sh - h) / 2); m_panel = { x0, y0, x0 + w, y0 + h }; From 149def7d1b15f25321cb311133949ac5a280b2cf Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 11:27:31 +0100 Subject: [PATCH 50/89] Game menu at the top right, as the original's Measured against the original (Wine, plain game, 1600 x 900 and 1280 x 1000): the in-game menu (BUTTONPOPUP_MAIN_MENU, Window_NoTitleBar_Style) is not centred: it sits where the other popups do, under the top bar at the right, its rim 1334-1582 and 1014-1262 from y 77 at the two sizes, so its right edge 18 from the window's and the same size, 248 wide, at both. - The menu style no longer centres the popup; it makes it 248 wide. - popupAddDDS's size is kept: the title is drawn at the 192 x 48 the game asks (it was 64 high), 4 under its place's top. - The menu's separator is a space only (no line; its first button 10 under the title), so the buttons fall where the original's do (156, 188 ... 436). - popupAddGenericButton's DLL_FONT_CENTER_JUSTIFY is kept: the menu's choices are centred on their buttons, as the original's. Other popups are unchanged (a text popup's picture is the same, pixel for pixel). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Interface.cpp | 8 ++++---- apps/oc4core/Interface.h | 2 ++ apps/oc4core/MapCapture.cpp | 4 +++- src/render/MapWindow.h | 4 +++- src/render/PopupPanel.cpp | 39 +++++++++++++++++++++++++++---------- 5 files changed, 41 insertions(+), 16 deletions(-) diff --git a/apps/oc4core/Interface.cpp b/apps/oc4core/Interface.cpp index 97ae45b3..075a26b1 100644 --- a/apps/oc4core/Interface.cpp +++ b/apps/oc4core/Interface.cpp @@ -847,10 +847,10 @@ namespace oc4::host popupOf(pPopup)->okButton = bCreateOkButton; } - void Interface::popupAddDDS(CvPopup* pPopup, const char* szIconFilename, int, int, CvWString szHelpText) + void Interface::popupAddDDS(CvPopup* pPopup, const char* szIconFilename, int iWidth, int iHeight, CvWString szHelpText) { if (pPopup && szIconFilename) - popupOf(pPopup)->items.push_back({ .kind = Popup::Item::Kind::Image, .help = szHelpText, .icon = szIconFilename }); + popupOf(pPopup)->items.push_back({ .kind = Popup::Item::Kind::Image, .help = szHelpText, .icon = szIconFilename, .width = iWidth, .height = iHeight }); } void Interface::popupAddSeparator(CvPopup* pPopup, int) @@ -867,11 +867,11 @@ namespace oc4::host } void Interface::popupAddGenericButton(CvPopup* pPopup, CvWString szText, const char* szIcon, int iButtonId, WidgetTypes eWidgetType, int iData1, - int iData2, bool bOption, PopupControlLayout, unsigned int) + int iData2, bool bOption, PopupControlLayout, unsigned int uiFlags) { if (!pPopup) return; - Popup::Item b{ .kind = Popup::Item::Kind::Button, .text = szText, .icon = szIcon ? szIcon : "", .id = iButtonId }; + Popup::Item b{ .kind = Popup::Item::Kind::Button, .text = szText, .icon = szIcon ? szIcon : "", .id = iButtonId, .flags = uiFlags }; b.widget.m_iData1 = iData1; b.widget.m_iData2 = iData2; b.widget.m_bOption = bOption; diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index e14dd520..60232e68 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -108,6 +108,8 @@ namespace oc4::host Control control = Control::RadioButtons; CvWidgetDataStruct widget{ -1, -1, false, WIDGET_GENERAL }; bool checked = false; // checkbox; the radio item chosen + int width = 0, height = 0; // a picture (popupAddDDS): the size it is asked at + unsigned int flags = 0; // a button: its text's DLL_FONT_* (the game menu's are centred) }; CvPopupInfo* info = nullptr; // owned (deleted through its virtual destructor, in the DLL) int python = -1; // a script's popup: its number there diff --git a/apps/oc4core/MapCapture.cpp b/apps/oc4core/MapCapture.cpp index 491e2537..caee9324 100644 --- a/apps/oc4core/MapCapture.cpp +++ b/apps/oc4core/MapCapture.cpp @@ -1109,7 +1109,7 @@ namespace oc4::host v.serial = popup.serial; v.header = gameMarkup(popup.header.c_str()); v.okButton = popup.okButton; - v.centered = popup.style == "Window_NoTitleBar_Style"; + v.menu = popup.style == "Window_NoTitleBar_Style"; itemOf.clear(); const ButtonPopupTypes type = popup.info ? popup.info->getButtonPopupType() : BUTTONPOPUP_TEXT; for (size_t i = 0; i < popup.items.size(); ++i) @@ -1127,6 +1127,8 @@ namespace oc4::host out.icon = it.icon; out.group = it.kind == Item::Kind::Radio ? int(it.control) * 1000 + it.group : it.group; // (a pulldown's group is not the radio buttons') out.checked = it.checked; + out.width = float(it.width), out.height = float(it.height); + out.centred = (it.flags & DLL_FONT_CENTER_JUSTIFY) != 0; itemOf.push_back(int(i)); } return v; diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..5ad50148 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -151,12 +151,14 @@ namespace oc4::render std::string icon; // a DDS, or ",,,," (64 pixel cells) int group = 0; // radio buttons and checkboxes bool checked = false; + float width = 0, height = 0; // a picture: the size it is asked at (0: its own) + bool centred = false; // a button: its text centred on it }; uint64_t serial = 0; // another popup when it changes std::string header; std::vector items; bool okButton = false; - bool centered = false; // in the middle of the window (the game menu's style), not at the right + bool menu = false; // the game menu's style (Window_NoTitleBar_Style): narrower, at the same place }; void setPopup(const PopupView* popup); // nullptr: none struct PopupAnswer diff --git a/src/render/PopupPanel.cpp b/src/render/PopupPanel.cpp index d4821a79..da2384c5 100644 --- a/src/render/PopupPanel.cpp +++ b/src/render/PopupPanel.cpp @@ -27,6 +27,10 @@ namespace oc4::render // (as the game's popups: their width, margins, the choices' pictures, the OK button's height) constexpr float kWidth = 400, kPadX = 21, kPadTop = 18, kPadBottom = 20, kIcon = 28, kOk = 24; constexpr float kStoneLine = 25, kStoneGap = 6, kStoneInset = 9; // (a choice's stone button) + // The game menu (Window_NoTitleBar_Style): 248 wide, where the other popups are (Wine at + // 1600 x 900 and 1280 x 1000 alike: its rim 1334-1582 and 1014-1262, from 77); its separator + // only a space (no line: the first button 10 under the title). + constexpr float kMenuWidth = 248, kMenuSeparator = 7; constexpr Color kFocus{ 0.45f, 0.62f, 0.95f }; // (the focus rim on the first) constexpr Color kPanel{ 0.05f, 0.06f, 0.09f }, kEdge{ 0.78f, 0.64f, 0.36f }, kText{ 0.97f, 0.97f, 0.97f }, kHot{ 1, 0.83f, 0.49f }; constexpr Color kButton{ 0.13f, 0.16f, 0.22f }, kButtonHover{ 0.24f, 0.31f, 0.44f }, kEditFill{ 0.09f, 0.11f, 0.2f }, kEditRim{ 0.62f, 0.72f, 0.9f }; @@ -238,9 +242,11 @@ namespace oc4::render } const auto& items = m_view->items; const float sw = o.screenWidth(), sh = o.screenHeight(); - // As the game's: its width, at the right under the top bar (in the middle when narrow). - const float w = std::min(kWidth, sw - 40), inner = w - 2 * kPadX; - const bool right = sw >= 2.5f * w && !m_view->centered; + // As the game's: its width, at the right under the top bar (in the middle when narrow). The + // game menu too, narrower. + const bool menu = m_view->menu; + const float w = std::min(menu ? kMenuWidth : kWidth, sw - 40), inner = w - 2 * kPadX; + const bool right = sw >= 2.5f * w; const float x0 = right ? sw - 18 - w : (sw - w) / 2; // (Wine at 1600 x 900: its rim 1182-1582 from 77; 1280 wide, the game menu's at 1262) const std::wstring header = widen(m_view->header); std::vector texts(items.size()); @@ -263,8 +269,8 @@ namespace oc4::render break; case Kind::Radio: case Kind::Check: heights[i] = std::max(26.0f, o.richHeight(texts[i], inner - 30, m_textSize, false) + 8); break; - case Kind::Separator: heights[i] = 12; break; - case Kind::Image: heights[i] = 72; break; + case Kind::Separator: heights[i] = menu ? kMenuSeparator : 12; break; + case Kind::Image: heights[i] = items[i].height > 0 ? items[i].height + 4 : 72; break; // (at the size asked, 4 down) case Kind::Edit: heights[i] = 34; break; } content += heights[i]; @@ -354,7 +360,14 @@ namespace oc4::render o.image(ic->key, ic->bgra, ic->width, ic->height, 1, tx, iy0, tx + kIcon, iy0 + kIcon); tx += kIcon + 5; } - const float tw = x0 + w - kPadX - kStoneInset - tx, th = o.richHeight(texts[i], tw, m_textSize, false); + float tw = x0 + w - kPadX - kStoneInset - tx; + if (item.centred) // (DLL_FONT_CENTER_JUSTIFY: the game menu's) + { + const float natural = std::min(o.richWidth(texts[i], m_textSize, false), tw); + tx += std::round((tw - natural) / 2); + tw = natural + 1; + } + const float th = o.richHeight(texts[i], tw, m_textSize, false); const bool coloured = m_button->coloured; if (coloured) o.setShadow(m_button->shadow[st], m_button->shadowAlpha[st]); @@ -394,7 +407,10 @@ namespace oc4::render o.richBlock(texts[i], r.x0 + 26, r.y0 + 4, r.x1 - r.x0 - 30, m_textSize, false, hot ? kHot : kText); break; } - case Kind::Separator: o.line(r.x0, r.y0 + 6, r.x1, r.y0 + 6, kText, 0.3f); break; + case Kind::Separator: + if (!menu) + o.line(r.x0, r.y0 + 6, r.x1, r.y0 + 6, kText, 0.3f); + break; case Kind::Edit: { // A box to type into, as the game's: dark, a light rim; the one with the focus shows where the text goes. @@ -408,9 +424,12 @@ namespace oc4::render case Kind::Image: if (const ButtonArt::Icon* ic = m_art.icon(item.icon)) { - // (64 high, as wide as its proportions have it: the game menu's title is 4:1) - const float cx = (r.x0 + r.x1) / 2, hw = std::min(32.0f * float(ic->width) / float(std::max(ic->height, 1u)), (r.x1 - r.x0) / 2); - o.image(ic->key, ic->bgra, ic->width, ic->height, 1, cx - hw, r.y0 + 4, cx + hw, r.y0 + 68); + // (at the size the game asks, as the original: the game menu's title 192 x 48; else 64 + // high, as wide as its proportions have it) + const float cx = (r.x0 + r.x1) / 2; + const float ih = item.height > 0 ? item.height : 64; + const float hw = std::min(item.width > 0 ? item.width / 2 : ih / 2 * float(ic->width) / float(std::max(ic->height, 1u)), (r.x1 - r.x0) / 2); + o.image(ic->key, ic->bgra, ic->width, ic->height, 1, std::round(cx - hw), r.y0 + 4, std::round(cx - hw) + 2 * hw, r.y0 + 4 + ih); } break; } From 7033d63c565448ad4ce49fe18c576e63d571daed Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 13:18:46 +0100 Subject: [PATCH 51/89] OpenCiv4 option Quick enemy moves: the others' shown moves in 0.6 s instead of 1 s The original has no such option (its Quick Moves speeds up only the player's own units). With it on, the turn worker waits 150 ms between the other civilizations' updates while one of their moves is shown, instead of the original's 250 ms: a move every 0.6 s, the camera still on each. Off by default, on the options' OpenCiv4 tab, kept in profile.ini as quickEnemyMoves. The game is unchanged (checksums equal). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 2 ++ apps/oc4core/Utility.h | 4 ++++ apps/oc4core/main.cpp | 8 +++++-- apps/oc4core/python/oc4options.py | 40 +++++++++++++++++++++++++++---- tests/player_options_test.py | 5 ++-- 5 files changed, 51 insertions(+), 8 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index efe18e86..34b95d61 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -280,6 +280,8 @@ namespace oc4::host host.def("set_edge_scroll", [&utility](bool on) { utility.setEdgeScroll(on); }); host.def("choose_edge_scroll", [&utility](bool on) { utility.chooseEdgeScroll(on); }); host.def("edge_scroll", [&utility] { return utility.edgeScroll(); }); + host.def("set_quick_enemy_moves", [&utility](bool on) { utility.setQuickEnemyMoves(on); }); + host.def("quick_enemy_moves", [&utility] { return utility.quickEnemyMoves(); }); // The profile's player options (the game core sends them to the active player): 0 the XML's // default, 1 off, 2 on. host.def("set_player_option", [&utility](int option, bool on) { utility.setProfilePlayerOption(option, on); }); diff --git a/apps/oc4core/Utility.h b/apps/oc4core/Utility.h index b01d32be..40ba74be 100644 --- a/apps/oc4core/Utility.h +++ b/apps/oc4core/Utility.h @@ -246,6 +246,9 @@ namespace oc4::host void setAutoEndTurn(bool on) { m_autoEndTurn = on; } void forceAutoEndTurn() { m_forcedAutoEndTurn = true; } void chooseAutoEndTurn(bool on) { m_forcedAutoEndTurn = false; m_autoEndTurn = on; } + // The other civilizations' shown moves at about half the time (OpenCiv4's own option, off). + bool quickEnemyMoves() const { return m_quickEnemyMoves; } + void setQuickEnemyMoves(bool on) { m_quickEnemyMoves = on; } // The mouse at the window's edge scrolls the map (render/EdgeScroll.h; on unless the profile // says off, or --no-edge-scroll / a scripted run for the session until the player chooses). bool edgeScroll() const { return m_edgeScroll.on(); } @@ -434,6 +437,7 @@ namespace oc4::host int m_uiScale = 0, m_forcedUiScale = -1; bool m_wasdPan = false, m_forcedWasdPan = false; bool m_autoEndTurn = false, m_forcedAutoEndTurn = false; + bool m_quickEnemyMoves = false; render::EdgeScrollOption m_edgeScroll; std::array, 64> m_graphicOptions{}; // 0 the XML's default, 1 off, 2 on (set by the window's thread, read by the game's) AudioScripts m_audio{ m_assets }; diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 30f81de7..467397d8 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -441,6 +441,9 @@ namespace // apart while one is on, as the original's engine does; with nothing shown they run flat out. // (Measured in the original under Wine: a game update every 0.26 s, a shown move every 4 updates.) constexpr std::chrono::milliseconds kShownMoveSlice{ 250 }; + // (OpenCiv4's own option Quick enemy moves: 0.6 s a move instead of 1 s; the camera still goes to + // each and the unit's walk ends before the next starts, so the player can follow them) + constexpr std::chrono::milliseconds kQuickShownMoveSlice{ 150 }; bool shownMoveOn() { for (int p = 0; p < MAX_PLAYERS; ++p) @@ -1596,7 +1599,8 @@ namespace if (Clock::now() >= nextShownMoveUpdate) { window.setBusy(true); - worker.start([&session, &game, &nextShownMoveUpdate] { + const auto slice = utility.quickEnemyMoves() ? kQuickShownMoveSlice : kShownMoveSlice; + worker.start([&session, &game, &nextShownMoveUpdate, slice] { const auto until = Clock::now() + std::chrono::milliseconds(100); do if (host::Entities::battleWait()) @@ -1608,7 +1612,7 @@ namespace session.update(); if (wasShown || shownMoveOn()) { - nextShownMoveUpdate = Clock::now() + kShownMoveSlice; + nextShownMoveUpdate = Clock::now() + slice; break; } } diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index dd7e1664..7191e54c 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -47,7 +47,7 @@ def _scales(): 'clock': False, 'hours24': False, 'graphicsLevel': 0, 'renderQuality': 0, 'globeView': 0, 'movieQuality': 0, 'mainMenu': 0, 'antiAliasing': 0, 'uiScale': 0, 'speakers': '', 'musicPath': '', 'voice': False, - 'wasdPan': False, 'autoEndTurn': False, 'edgeScroll': True, + 'wasdPan': False, 'autoEndTurn': False, 'edgeScroll': True, 'quickEnemyMoves': False, } @@ -87,7 +87,7 @@ def _load(): _profile['nosound'][parts[1]] = value == '1' elif parts[0] in ('graphic', 'player'): _profile[parts[0]][int(parts[1])] = value == '1' - elif parts[0] in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): + elif parts[0] in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll', 'quickEnemyMoves'): _profile[parts[0]] = value == '1' elif parts[0] in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale'): _profile[parts[0]] = int(value) @@ -115,7 +115,7 @@ def _save(): lines = ['version=%d' % _VERSION] for key in ('name', 'speakers', 'musicPath'): lines.append('%s=%s' % (key, _profile[key])) - for key in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll'): + for key in ('clock', 'hours24', 'voice', 'wasdPan', 'autoEndTurn', 'edgeScroll', 'quickEnemyMoves'): lines.append('%s=%d' % (key, 1 if _profile[key] else 0)) for key in ('graphicsLevel', 'renderQuality', 'globeView', 'movieQuality', 'mainMenu', 'antiAliasing', 'uiScale'): lines.append('%s=%d' % (key, _profile[key])) @@ -144,6 +144,7 @@ def _applyGraphics(): oc4host.set_wasd_pan(_profile['wasdPan']) oc4host.set_auto_end_turn(_profile['autoEndTurn']) oc4host.set_edge_scroll(_profile['edgeScroll']) + oc4host.set_quick_enemy_moves(_profile['quickEnemyMoves']) except Exception: pass @@ -236,6 +237,31 @@ def _edgeScrollOn(): return _profile['edgeScroll'] + +# Quick enemy moves (openciv4's own option, off as the original has none): the other civilizations' +# moves the Show Enemy / Friendly Moves options show come at about half the time, the camera still +# on each. +QUICK_ENEMY_MOVES_CHECKBOX = 'Oc4QuickEnemyMovesCheckBox' + + +def handleQuickEnemyMovesClicked(args): + on = bool(args[0]) + _profile['quickEnemyMoves'] = on + _save() + try: + oc4host.set_quick_enemy_moves(on) + except Exception: + pass + return 1 + + +def _quickEnemyMovesOn(): + try: + return bool(oc4host.quick_enemy_moves()) + except Exception: + return _profile['quickEnemyMoves'] + + def _applyPlayerOptions(): """The player options the profile has, to the host: the game core sends them to the active player at the start of every game, new or loaded, as the original's profile (a save's own are @@ -518,7 +544,8 @@ def attachTabItem(self, szName, szLabel): def _attachOpenCiv4Tab(self): """OpenCiv4's options, none of the original's: W A S D panning, ending idle turns, edge - scrolling (kept in the profile as wasdPan, autoEndTurn, edgeScroll).""" + scrolling, quicker shown moves of the others (kept in the profile as wasdPan, autoEndTurn, edgeScroll, + quickEnemyMoves).""" self.attachTabItem(OC4_FORM, u'OpenCiv4') self.attachVBox(OC4_FORM, 'Oc4VBox') parent = 'Oc4Panel' @@ -540,6 +567,11 @@ def _attachOpenCiv4Tab(self): EDGE_SCROLL_CHECKBOX, _edgeScrollOn()) self.setToolTip(EDGE_SCROLL_CHECKBOX, u'Moving the mouse to the edge of the screen or window moves the map that way. ' u'Turn it off to pan only with the arrow keys (or W A S D) and the mouse.') + self.attachCheckBox(parent, QUICK_ENEMY_MOVES_CHECKBOX, u'Quick enemy moves', 'oc4options', 'handleQuickEnemyMovesClicked', + QUICK_ENEMY_MOVES_CHECKBOX, _quickEnemyMovesOn()) + self.setToolTip(QUICK_ENEMY_MOVES_CHECKBOX, u'With Show Enemy Moves or Show Friendly Moves on, the other civilizations\' ' + u'units move about twice as fast. The camera still goes to each unit and stays a moment after it arrives. ' + u'The original has no such option: its Quick Moves speeds up only your own units.') def attachVBox(self, parent, name): self._node('vbox', parent, name) def attachHBox(self, parent, name): diff --git a/tests/player_options_test.py b/tests/player_options_test.py index c13debbc..cdf6a35f 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -142,11 +142,12 @@ def main(): check(profile.getPlayerOption(2) and not profile.getPlayerOption(6), "no profile: the XML's defaults") check(host.states[:NUM] == [0] * NUM, "no profile: the host has none chosen") - # The screen's tabs: the game's four, then OpenCiv4's with its three options. + # The screen's tabs: the game's four, then OpenCiv4's with its four options. ctrl = optionsScreen(options) check([label for form, label in ctrl._tabs] == ['Game', 'Graphics', 'Audio', 'Other', 'OpenCiv4'], "tabs: %s" % [l for f, l in ctrl._tabs]) oc4 = [n.name for n in ctrl._nodes.values() if n.kind == 'checkbox' and n.name.startswith('Oc4')] - check(sorted(oc4) == sorted([options.WASD_PAN_CHECKBOX, options.AUTO_END_TURN_CHECKBOX, options.EDGE_SCROLL_CHECKBOX]), "OpenCiv4's options: %s" % oc4) + check(sorted(oc4) == sorted([options.WASD_PAN_CHECKBOX, options.AUTO_END_TURN_CHECKBOX, options.EDGE_SCROLL_CHECKBOX, + options.QUICK_ENEMY_MOVES_CHECKBOX]), "OpenCiv4's options: %s" % oc4) game = [n.name for n in ctrl._byName['GamePanelCenter'].children] check(game == ['GameOptionCheckBox_2', 'GameOptionCheckBox_6', 'LangHBox'], "the Game tab has only the game's: %s" % game) From 5a699d17475529fcd7f19d015e66bd9d63b7726f Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Fri, 20 Nov 2026 23:04:26 +0100 Subject: [PATCH 52/89] World Builder: help for its buttons and palette items; diplomacy mode's window The World Builder's own buttons (WIDGET_WB_...) get the help the original shows for them: every button was hovered in the original under Wine, and each shown text found in the game's text XML (TXT_KEY_WB_..., Save and Load TXT_KEY_ACTION_...). Where two keys say the same in English (Save, Load, Player Mode, Map Mode) the choice is ours. A widget type the game core has no help for goes to the scripts' CvGameInterface.getWidgetHelp (BUG's own widget types). The palette's items show their names. Diplomacy mode's tab control (initWBDiplomacyCtrl...) as the options screen's, its -100..100 sliders in stops that fit. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 11 +++++-- apps/oc4core/python/oc4options.py | 14 +++++++-- apps/oc4core/python/oc4screens.py | 26 ++++++++++++++-- apps/oc4core/python/oc4wb.py | 51 ++++++++++++++++++++++++++++++- 4 files changed, 93 insertions(+), 9 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index a46ef750..9d651d1b 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -1136,12 +1136,17 @@ if _walls: CvWStringBuffer text; CvWidgetDataStruct w{ item.data1, item.data2, item.option, static_cast(item.widget) }; CvDLLWidgetData::getInstance().parseHelp(text, w); - g_help = text.getCString(); - return gameMarkup(text.getCString()); + if (!text.isEmpty()) + { + g_help = text.getCString(); + return gameMarkup(text.getCString()); + } + // (a widget type the game core has no help for, as the World Builder's buttons: the + // script's own help text, else oc4screens.hostWidgetHelp's) } try { - const std::wstring text = toWide(py::module_::import("oc4screens").attr("widgetText")(item.screen, item.name)); + const std::wstring text = toWide(py::module_::import("oc4screens").attr("widgetText")(item.screen, item.name, item.widget != WIDGET_GENERAL ? item.widget : -1, item.data1, item.data2, item.option)); g_help = text; return gameMarkup(text.c_str()); } diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 4b2d7a83..9dea01c9 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -674,8 +674,16 @@ def _place(screen, n, x, y, w, h): elif k in ('hslider', 'vslider'): # (its stops, each a little button: the slider set to the one clicked) stops = n.maximum - n.minimum + 1 - for s in range(stops): - value = n.minimum + s + # (a wide range, as the World Builder diplomacy's -100 to 100: every few values a stop, + # as many as fit, the ends kept) + step = 1 + if k == 'hslider' and stops > max(2, (w - 4) / 4): + step = (stops + (w - 4) / 4 - 1) / max(1, (w - 4) / 4) + values = range(n.minimum, n.maximum + 1, step) + if values[-1] != n.maximum: + values.append(n.maximum) + stops = len(values) + for s, value in enumerate(values): if k == 'hslider': size = max(3, min(10, (w - 4) / max(1, stops) - 1)) bx, by, bw, bh = x + s * (size + 1), y + 2, size, 14 @@ -683,7 +691,7 @@ def _place(screen, n, x, y, w, h): else: bx, by, bw, bh = x + 8, y + 2 + s * 4, 40, 3 on = value >= int(n.value) - bname = 'OptSlider%d' % (n.id * 1000 + s) + bname = 'OptSlider%d' % (n.id * 1000 + value - n.minimum) screen.addCheckBoxGFC(bname, '', '', bx, by, bw, bh, general, -1, -1, '') b = screen._s.get(bname) if b is not None: diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index fcce18b6..099dc94e 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -1980,10 +1980,32 @@ def helpArea(): return None -def widgetText(fileId, name): +def widgetText(fileId, name, widget=-1, data1=-1, data2=-1, option=False): + """A widget's help: the help text the script gave it, else, for a widget type the game core + has no help for (the World Builder's buttons), hostWidgetHelp's.""" s = _screens.get(fileId) w = s.get(name) if s is not None else None - return w.help if w is not None else u'' + text = w.help if w is not None else u'' + if not text and widget >= 0: + text = hostWidgetHelp(widget, data1, data2, option) + return text + + +def hostWidgetHelp(widget, data1, data2, option=False): + """What the original shows for a widget the game core has no help for: the World Builder's + own buttons (oc4wb, as seen in the running original under Wine), else the scripts' CvGameInterface.getWidgetHelp (BUG + answers its own widget types there: the great people bar, the options button, its advisors').""" + text = u'' + try: + import oc4wb + text = oc4wb.widgetHelp(widget, data1, data2) + if not text: + import CvGameInterface + text = CvGameInterface.getWidgetHelp((int(widget), int(data1), int(data2), bool(option))) or u'' + except Exception: + import traceback + traceback.print_exc() + return text def toggle(fileId, name): diff --git a/apps/oc4core/python/oc4wb.py b/apps/oc4core/python/oc4wb.py index d6fc837c..1e0c549f 100644 --- a/apps/oc4core/python/oc4wb.py +++ b/apps/oc4core/python/oc4wb.py @@ -164,6 +164,29 @@ def initWBToolEditCtrlTab(bUnit): def refreshWBEditCtrlReligionButtons(b): _draw() def refreshWBEditCtrlCorporationButtons(b): _draw() +# The diplomacy mode's window (CvWorldBuilderDiplomacyScreen): a tab control, as +# the options screen's (oc4options.CyGTabCtrl, one window of tabs, centred). +_diplomacy = {'ctrl': None} + + +def initWBDiplomacyCtrl(szName, bStatic=True, bCloseButton=False): + import oc4options + _diplomacy['ctrl'] = oc4options.CyGTabCtrl(szName, bStatic, bCloseButton) + + +def getWBToolDiplomacyTabCtrl(): return _diplomacy['ctrl'] + + +def destroyWBDiplomacyCtrl(): + ctrl, _diplomacy['ctrl'] = _diplomacy['ctrl'], None + if ctrl is not None: + ctrl.destroy() + + +def saveDiplomacySettings(): pass +def setDiplomacySettings(): pass + + def isMouseOverGameSurface(): return bool(oc4host.ui_mouse_over_map()) def setFocusToCVG(): pass def getWBSaveExtension(): return '.CivBeyondSwordWBSave' @@ -445,6 +468,10 @@ def _draw(): screen.setImageButtonAt(_add(name, ('item', ctrl, item)), grid, item[2], cx, cy, _ICON, _ICON, general, -1, -1) else: screen.setTextAt(_add(name, ('item', ctrl, item)), grid, item[3][:6], 0, cx, cy + 8, -0.3, _cpe.FontTypes.SMALL_FONT, general, -1, -1) + # (its help: the item's name, as the original's palette shows it under the mouse) + w = screen._s.get(name) + if w is not None: + w.help = _u(item[3]) if _flyout is not None and _flyout.items: mx, my = 300, 200 screen.addPanel(_add('OC4WBFlyout'), u'', u'', True, False, mx, my, 240, 24 * len(_flyout.items) + 12, _cpe.PanelStyles.PANEL_STYLE_MAIN) @@ -540,6 +567,27 @@ def widgetClicked(widget, iData1, iData2): _draw() +def widgetHelp(widget, iData1, iData2): + """The help the original shows for the WorldBuilder's own buttons (WIDGET_WB_...); u'' for any + other widget. Each was seen in the running original under Wine (2026-11-22: every button hovered) + and is the game's text that says exactly that. Where two keys say the same in English (Save, + Load, Player Mode, Map Mode) the one named for the button or its action is used; the screen + can't tell them apart.""" + W = _cpe.WidgetTypes + keys = { + W.WIDGET_WB_SAVE_BUTTON: 'TXT_KEY_ACTION_SAVE', W.WIDGET_WB_LOAD_BUTTON: 'TXT_KEY_ACTION_LOAD', + W.WIDGET_WB_ALL_PLOTS_BUTTON: 'TXT_KEY_WB_CHANGE_ALL_PLOTS', W.WIDGET_WB_ERASE_BUTTON: 'TXT_KEY_WB_ERASE_PLOTS', + W.WIDGET_WB_LANDMARK_BUTTON: 'TXT_KEY_WB_LANDMARK_PLOTS', W.WIDGET_WB_EXIT_BUTTON: 'TXT_KEY_WB_EXIT', + W.WIDGET_WB_UNIT_EDIT_BUTTON: 'TXT_KEY_WB_EDIT_UNIT', W.WIDGET_WB_CITY_EDIT_BUTTON: 'TXT_KEY_WB_EDIT_CITY', + W.WIDGET_WB_NORMAL_PLAYER_TAB_MODE_BUTTON: 'TXT_KEY_WB_NORMAL_PLAYER', W.WIDGET_WB_NORMAL_MAP_TAB_MODE_BUTTON: 'TXT_KEY_WB_NORMAL_MAP', + W.WIDGET_WB_REVEAL_TAB_MODE_BUTTON: 'TXT_KEY_WB_REVEAL_TILE', W.WIDGET_WB_REVEAL_ALL_BUTTON: 'TXT_KEY_WB_REVEAL_ALL', + W.WIDGET_WB_UNREVEAL_ALL_BUTTON: 'TXT_KEY_WB_UNREVEAL_ALL', W.WIDGET_WB_REGENERATE_MAP: 'TXT_KEY_WB_REGENERATE_MAP', + W.WIDGET_WB_DIPLOMACY_MODE_BUTTON: 'TXT_KEY_WB_DIPLOMACY', + } + key = keys.get(widget) + return _text(key) if key else u'' + + def _save(): """The world as a WorldBuilder save (CvWBInterface.writeDesc), into the original's folder of them: Documents\\My Games\\Beyond the Sword\\Saves\\WorldBuilder, named by the time.""" @@ -560,5 +608,6 @@ def _save(): for _name in ('initWBToolPlayerControl', 'getWBToolNormalPlayerTabCtrl', 'addWBPlayerControlTabs', 'getWBToolNormalMapTabCtrl', 'setWBInitialCtrlTabPlacement', 'initWBToolAdvancedStartControl', 'getWBToolAdvancedStartTabCtrl', 'addWBAdvancedStartControlTabs', 'initWBToolEditCtrl', 'getWBToolEditTabCtrl', 'initWBToolEditCtrlTab', 'refreshWBEditCtrlReligionButtons', - 'refreshWBEditCtrlCorporationButtons', 'isMouseOverGameSurface', 'setFocusToCVG', 'getWBSaveExtension', 'CyGFlyoutMenu'): + 'refreshWBEditCtrlCorporationButtons', 'initWBDiplomacyCtrl', 'getWBToolDiplomacyTabCtrl', 'destroyWBDiplomacyCtrl', + 'saveDiplomacySettings', 'setDiplomacySettings', 'isMouseOverGameSurface', 'setFocusToCVG', 'getWBSaveExtension', 'CyGFlyoutMenu'): setattr(_cpe, _name, globals()[_name]) From d5edae8a7a85a029015d576ee9373740ce75da21 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 00:09:52 +0100 Subject: [PATCH 53/89] World Builder: tooltips at the widget, palette items' game help, the edit window as the original's Measured in Wine (BtS 3.19, BUG + BULL, 1600x900): - In the World Builder (no help area: the main interface is hidden) the help is a tooltip in the theme's tooltip box, as wide as its text: beside the screen's buttons (3 px left of the top right ones), under the mouse in the tool windows (12 left, 31 down). - The palette's items show the game core's help of what they place (a unit's, building's, tech's, resource's, terrain's, feature's, promotion's...; an improvement its name), through oc4host.widget_help, their clicks still the palette's. - The unit's and city's edit window: in the middle of the screen with a close box, two tabs (the city's religions, holy cities, corporations and headquarters as rows of its first), edit boxes (Enter tells the script) and spin boxes in the theme's style, sized as Wine's. - The palette keeps its width: tabs that do not fit scroll with two arrows; items that fit without a scroll bar eight to a row. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + apps/oc4core/Screens.cpp | 30 ++- apps/oc4core/Screens.h | 1 + apps/oc4core/python/oc4screens.py | 41 +++- apps/oc4core/python/oc4wb.py | 342 +++++++++++++++++++++--------- src/render/MapWindow.cpp | 4 +- src/render/MapWindow.h | 3 +- src/render/UiLayer.cpp | 9 +- src/render/UiLayer.h | 5 +- 9 files changed, 328 insertions(+), 108 deletions(-) diff --git a/.gitignore b/.gitignore index 9e3c934c..7637531c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ *.user /external/ /mods/ +*.pyc diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 9d651d1b..72ab19ba 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -200,6 +200,14 @@ namespace oc4::host Interface& ui = utility.gameInterface(); // dirty bits, what shows + // The game core's help for a widget type and its data (the World Builder's palette: its + // items' help is a unit's, a building's, ..., though a click on them is the palette's). + host.def("widget_help", [](int type, int data1, int data2) { + CvWStringBuffer text; + CvWidgetDataStruct w{ data1, data2, false, static_cast(type) }; + CvDLLWidgetData::getInstance().parseHelp(text, w); + return std::wstring(text.getCString()); + }); host.def("ui_is_dirty", [&ui](int bit) { return ui.isDirty(static_cast(bit)); }); host.def("ui_set_dirty", [&ui](int bit, bool value) { ui.setDirty(static_cast(bit), value); }); host.def("ui_make_dirty", [&ui] { ui.makeInterfaceDirty(); }); @@ -1104,10 +1112,25 @@ if _walls: m_hovered = hovered; const std::string text = hovered >= 0 && size_t(hovered) < m_items.size() ? help(m_items[size_t(hovered)]) : std::string(); float x = 7, y = float(height) - 172, w = 300; - bool right = true, down = false, framed = false; + bool right = true, down = false, framed = false, fit = false; try { - if (py::object area = py::module_::import("oc4screens").attr("helpArea")(); !area.is_none()) + // (a tooltip at the widget where the original shows one: the World Builder's) + const auto [mx, my] = window.mousePosition(); + const Item* it = hovered >= 0 && size_t(hovered) < m_items.size() ? &m_items[size_t(hovered)] : nullptr; + if (py::object tip = it && !text.empty() ? py::module_::import("oc4screens").attr("tooltipPlace")(it->screen, it->name, it->x0, it->y0, it->x1, it->y1, mx, my, width) + : py::none(); !tip.is_none()) + { + auto t = tip.cast(); + x = t[0].cast(); + y = t[1].cast(); + w = t[2].cast(); + right = t[3].cast(); + down = t[4].cast(); + // (in the theme's tooltip, as Wine's: the map under it at 15 %) + fit = framed = true; + } + else if (py::object area = py::module_::import("oc4screens").attr("helpArea")(); !area.is_none()) { auto t = area.cast(); x = t[0].cast(); @@ -1125,7 +1148,7 @@ if _walls: { printPythonError(e); } - window.setUiHelp(text, x, y, w, right, down, framed); + window.setUiHelp(text, x, y, w, right, down, framed, fit); } } @@ -1217,6 +1240,7 @@ if _walls: info.data1 = t[18].cast(); info.data2 = t[19].cast(); info.option = t[20].cast(); + info.x0 = item.x0, info.y0 = item.y0, info.x1 = item.x1, info.y1 = item.y1; info.checkbox = item.kind == Kind::CheckBox; if (item.kind == Kind::Movie) info.movie = item.texture; diff --git a/apps/oc4core/Screens.h b/apps/oc4core/Screens.h index 5f64207c..2b2825e9 100644 --- a/apps/oc4core/Screens.h +++ b/apps/oc4core/Screens.h @@ -119,6 +119,7 @@ namespace oc4::host int widget = -1, data1 = -1, data2 = -1; bool option = false; bool checkbox = false; + float x0 = 0, y0 = 0, x1 = 0, y1 = 0; // (where it is drawn: a tooltip goes beside it) std::string movie; // (a movie's file) }; void rebuild(render::MapWindow& window); diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 099dc94e..a7b260a5 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -88,7 +88,7 @@ class _Widget(object): __slots__ = ('name', 'kind', 'parent', 'mode', 'x', 'y', 'z', 'w', 'h', 'style', 'pstyle', 'text', 'help', 'tex', 'tex2', 'wt', 'd1', 'd2', 'opt', 'flags', 'font', 'shown', 'enabled', 'state', 'hittest', 'seq', 'vertical', 'scroll', 'children', 'bars', 'lists', 'columns', 'rows', 'headers', 'iconw', 'iconh', 'items', 'selected', 'color', 'size', 'defw', 'defh', 'points', - 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed') + 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed', 'helpWidget') def __init__(self, name, kind): self.name = name @@ -101,6 +101,7 @@ def __init__(self, name, kind): self.pstyle = 0 self.text = u'' self.help = u'' + self.helpWidget = None # (type, data1, data2): its help the game core's for these (oc4wb) self.tex = self.tex2 = '' self.wt, self.d1, self.d2, self.opt = -1, -1, -1, False self.flags = _FONT_LEFT @@ -1887,6 +1888,16 @@ def typeIntoEdit(text): value = value[:-1] elif c in (u'\r', u'\x1b'): _editFocus[0] = None + if c == u'\r' and w.name.startswith('OC4WB'): + # (the World Builder's edit window: Enter tells the script, as the original's) + _set(w, 'text', value) + try: + import oc4wb + oc4wb.editDone(w.name, value) + except Exception: + import traceback + traceback.print_exc() + return break # (the rest of the keys are not the edit box's) elif c >= u' ' and (w.allowed is None or c in w.allowed) and (not w.maxChars or len(value) < w.maxChars): value += c @@ -1980,12 +1991,40 @@ def helpArea(): return None +def tooltipPlace(fileId, name, x0, y0, x1, y1, mx, my, width): + """Where a widget's help goes when it is a tooltip, as the original's, or None (the help area): + (x, y, max width, expand right, expand down). In the World Builder the main interface and its + help area are hidden and the help is a small box at the widget: under the mouse in its tool + window (oc4wb's OC4WB... widgets: 12 px left of the mouse, 31 under it), else beside the + widget, on the side away from the screen's edge (the top right buttons': 3 px left of it, + 3 down). Measured in Wine (BtS 3.19, BUG + BULL, 1600x900).""" + try: + if not oc4host.ui_world_builder(): + return None + except Exception: + return None + name = _str(name) + if name.startswith('OC4WB'): + return (mx - 12, my + 31, 400, True, True) + if (x0 + x1) / 2.0 > width / 2.0: + return (x0 - 3, y0 + 3, 400, False, True) + return (x1 + 3, y0 + 3, 400, True, True) + + def widgetText(fileId, name, widget=-1, data1=-1, data2=-1, option=False): """A widget's help: the help text the script gave it, else, for a widget type the game core has no help for (the World Builder's buttons), hostWidgetHelp's.""" s = _screens.get(fileId) w = s.get(name) if s is not None else None text = w.help if w is not None else u'' + if not text and w is not None and getattr(w, 'helpWidget', None): + # (the game core's help for another widget type than the widget's: the World Builder's + # palette, its items a unit's, a building's, ... help) + try: + text = oc4host.widget_help(*w.helpWidget) + except Exception: + import traceback + traceback.print_exc() if not text and widget >= 0: text = hostWidgetHelp(widget, data1, data2, option) return text diff --git a/apps/oc4core/python/oc4wb.py b/apps/oc4core/python/oc4wb.py index 1e0c549f..3b511991 100644 --- a/apps/oc4core/python/oc4wb.py +++ b/apps/oc4core/python/oc4wb.py @@ -8,6 +8,7 @@ import CvPythonExtensions as _cpe import oc4host +import oc4screens _gc = _cpe.CyGlobalContext() _COLUMNS = 7 # items to a row of a palette @@ -150,14 +151,11 @@ def getWBToolEditTabCtrl(): return _ctrls['edit'] def initWBToolEditCtrlTab(bUnit): - """The edit panel's grids: a unit's promotions; a city's buildings, religions, holy cities, - corporations and headquarters.""" + """The edit window's second tab, as the original's: a unit's promotions, a city's buildings (the + city's religions, holy cities, corporations and headquarters are rows of its first tab).""" e = _ctrls['edit'] - if bUnit: - e.addTabSection(u'Promotions') - else: - for name in (u'Buildings', u'Religions', u'Holy cities', u'Corporations', u'Headquarters'): - e.addTabSection(name) + e.unit = bool(bUnit) + e.addTabSection(_text('TXT_KEY_WB_PROMOTIONS') or u'Promotions' if bUnit else _text('TXT_KEY_WB_BUILDINGS') or u'Buildings') e.enabled = True _draw() @@ -227,8 +225,11 @@ def _art(tag): def _items(ctrl): - """The active section's items: (list, index, button art, label, selected).""" + """The active section's items: (list, index, button art, label, selected, help): help the widget + type and data whose game core help the item shows (the original's palette: a unit's, + building's, tech's, resource's... help), None its name.""" gc = _gc + W = _cpe.WidgetTypes wb = _wb() tab = ctrl.active out = [] @@ -239,7 +240,7 @@ def _items(ctrl): current = -1 if tab == 0: for i in range(gc.getNumUnitInfos()): - out.append((0, i, gc.getUnitInfo(i).getButton(), gc.getUnitInfo(i).getDescription(), i == current)) + out.append((0, i, gc.getUnitInfo(i).getButton(), gc.getUnitInfo(i).getDescription(), i == current, (W.WIDGET_PEDIA_JUMP_TO_UNIT, i))) elif tab == 1: # (as the original's list: a city first, then the buildings, one on: the script # places a city for 0 and building i - 1 for i) @@ -247,16 +248,16 @@ def _items(ctrl): found = gc.getMissionInfo(_cpe.MissionTypes.MISSION_FOUND).getButton() except Exception: found = '' - out.append((0, 0, found, u'City', current == 0)) + out.append((0, 0, found, u'City', current == 0, None)) for i in range(gc.getNumBuildingInfos()): - out.append((0, i + 1, gc.getBuildingInfo(i).getButton(), gc.getBuildingInfo(i).getDescription(), i + 1 == current)) + out.append((0, i + 1, gc.getBuildingInfo(i).getButton(), gc.getBuildingInfo(i).getDescription(), i + 1 == current, (W.WIDGET_PEDIA_JUMP_TO_BUILDING, i))) elif tab == 2: try: team = gc.getTeam(gc.getPlayer(wb.m_iCurrentPlayer).getTeam()) except Exception: team = None for i in range(gc.getNumTechInfos()): - out.append((0, i, gc.getTechInfo(i).getButton(), gc.getTechInfo(i).getDescription(), team is not None and team.isHasTech(i))) + out.append((0, i, gc.getTechInfo(i).getButton(), gc.getTechInfo(i).getDescription(), team is not None and team.isHasTech(i), (W.WIDGET_PEDIA_JUMP_TO_TECH, i))) elif ctrl.kind == 'map': try: current, currentList = wb.m_iNormalMapCurrentIndexes[tab], wb.m_iNormalMapCurrentList[tab] @@ -270,58 +271,61 @@ def _items(ctrl): for i in range(gc.getNumImprovementInfos()): info = gc.getImprovementInfo(i) if not info.isGraphicalOnly(): - out.append((0, k, info.getButton(), info.getDescription(), sel(0, k))) + out.append((0, k, info.getButton(), info.getDescription(), sel(0, k), None)) k += 1 elif tab == 1: for i in range(gc.getNumBonusInfos()): - out.append((0, i, gc.getBonusInfo(i).getButton(), gc.getBonusInfo(i).getDescription(), sel(0, i))) + out.append((0, i, gc.getBonusInfo(i).getButton(), gc.getBonusInfo(i).getDescription(), sel(0, i), (W.WIDGET_PEDIA_JUMP_TO_BONUS, i))) elif tab == 2: for i in range(gc.getNumTerrainInfos()): - out.append((0, i, gc.getTerrainInfo(i).getButton(), gc.getTerrainInfo(i).getDescription(), sel(0, i))) + out.append((0, i, gc.getTerrainInfo(i).getButton(), gc.getTerrainInfo(i).getDescription(), sel(0, i), (W.WIDGET_PEDIA_JUMP_TO_TERRAIN, i))) # (the plot types and the river with the original's own buttons) for i, (name, art) in enumerate(((u'Peak', 'WORLDBUILDER_PLOT_TYPE_MOUNTAIN'), (u'Hills', 'WORLDBUILDER_PLOT_TYPE_HILL'), (u'Flat', 'WORLDBUILDER_PLOT_TYPE_PLAINS'), (u'Water', 'WORLDBUILDER_PLOT_TYPE_OCEAN'))): - out.append((1, i, _art(art), name, sel(1, i))) + out.append((1, i, _art(art), name, sel(1, i), None)) k = 0 for i in range(gc.getNumFeatureInfos()): info = gc.getFeatureInfo(i) for j in range(info.getNumVarieties()): - out.append((2, k, info.getButton(), info.getDescription(), sel(2, k))) + out.append((2, k, info.getButton(), info.getDescription(), sel(2, k), (W.WIDGET_PEDIA_JUMP_TO_FEATURE, i))) k += 1 for i in range(gc.getNumRouteInfos()): - out.append((3, i, gc.getRouteInfo(i).getButton(), gc.getRouteInfo(i).getDescription(), sel(3, i))) - out.append((3, gc.getNumRouteInfos(), _art('WORLDBUILDER_RIVER_PLACEMENT'), u'River', sel(3, gc.getNumRouteInfos()))) + out.append((3, i, gc.getRouteInfo(i).getButton(), gc.getRouteInfo(i).getDescription(), sel(3, i), None)) + out.append((3, gc.getNumRouteInfos(), _art('WORLDBUILDER_RIVER_PLACEMENT'), u'River', sel(3, gc.getNumRouteInfos()), None)) elif tab == 3: for i in range(gc.getMAX_CIV_PLAYERS()): p = gc.getPlayer(i) if p.isEverAlive(): civ = gc.getCivilizationInfo(p.getCivilizationType()) - out.append((0, i, civ.getButton(), p.getCivilizationShortDescription(0), sel(0, i))) + out.append((0, i, civ.getButton(), p.getCivilizationShortDescription(0), sel(0, i), None)) elif ctrl.kind == 'edit': plot = getattr(wb, 'm_pActivePlot', 0) - if not plot or tab < 1: + if not plot: return out - names = ctrl.sections[tab] - if names == u'Promotions': - try: - unit = plot.getUnit(wb.m_iCurrentUnit) - except Exception: - unit = None - for i in range(gc.getNumPromotionInfos()): - out.append((0, i, gc.getPromotionInfo(i).getButton(), gc.getPromotionInfo(i).getDescription(), unit is not None and unit.isHasPromotion(i))) + if getattr(ctrl, 'unit', False): + if tab == 1: + try: + unit = plot.getUnit(wb.m_iCurrentUnit) + except Exception: + unit = None + for i in range(gc.getNumPromotionInfos()): + out.append((0, i, gc.getPromotionInfo(i).getButton(), gc.getPromotionInfo(i).getDescription(), unit is not None and unit.isHasPromotion(i), (W.WIDGET_HELP_PROMOTION, i))) elif plot.isCity(): city = plot.getPlotCity() - if names == u'Buildings': + if tab == 1: for i in range(gc.getNumBuildingInfos()): - out.append((0, i, gc.getBuildingInfo(i).getButton(), gc.getBuildingInfo(i).getDescription(), city.getNumRealBuilding(i) > 0)) - elif names in (u'Religions', u'Holy cities'): - for i in range(gc.getNumReligionInfos()): - on = city.isHasReligion(i) if names == u'Religions' else city.isHolyCityByType(i) - out.append((0, i, gc.getReligionInfo(i).getButton(), gc.getReligionInfo(i).getDescription(), on)) - elif names in (u'Corporations', u'Headquarters'): - for i in range(gc.getNumCorporationInfos()): - on = city.isHasCorporation(i) if names == u'Corporations' else city.isHeadquartersByType(i) - out.append((0, i, gc.getCorporationInfo(i).getButton(), gc.getCorporationInfo(i).getDescription(), on)) + out.append((0, i, gc.getBuildingInfo(i).getButton(), gc.getBuildingInfo(i).getDescription(), city.getNumRealBuilding(i) > 0, (W.WIDGET_PEDIA_JUMP_TO_BUILDING, i))) + elif tab == 0: + # (under the city's data, a row each: its religions, its holy cities, its + # corporations, its headquarters) + for row in ('religion', 'holy'): + for i in range(gc.getNumReligionInfos()): + on = city.isHasReligion(i) if row == 'religion' else city.isHolyCityByType(i) + out.append((row, i, gc.getReligionInfo(i).getButton(), gc.getReligionInfo(i).getDescription(), on, (W.WIDGET_PEDIA_JUMP_TO_RELIGION, i))) + for row in ('corp', 'hq'): + for i in range(gc.getNumCorporationInfos()): + on = city.isHasCorporation(i) if row == 'corp' else city.isHeadquartersByType(i) + out.append((row, i, gc.getCorporationInfo(i).getButton(), gc.getCorporationInfo(i).getDescription(), on, (W.WIDGET_PEDIA_JUMP_TO_CORPORATION, i))) return out @@ -337,17 +341,12 @@ def _chosen(ctrl, item): elif ctrl.kind == 'advanced': si.WorldBuilderOnAdvancedStartBrushSelected((l, i, tab)) elif ctrl.kind == 'edit': - name = ctrl.sections[tab] - if name in (u'Promotions', u'Buildings'): + calls = {'religion': si.WorldBuilderOnWBEditReligionSelected, 'holy': si.WorldBuilderOnWBEditHolyCitySelected, + 'corp': si.WorldBuilderOnWBEditCorporationSelected, 'hq': si.WorldBuilderOnWBEditHeadquartersSelected} + if l in calls: + calls[l]((0, i, tab)) + else: si.WorldBuilderOnWBEditBrushSelected((l, i, tab)) - elif name == u'Religions': - si.WorldBuilderOnWBEditReligionSelected((l, i, tab)) - elif name == u'Holy cities': - si.WorldBuilderOnWBEditHolyCitySelected((l, i, tab)) - elif name == u'Corporations': - si.WorldBuilderOnWBEditCorporationSelected((l, i, tab)) - elif name == u'Headquarters': - si.WorldBuilderOnWBEditHeadquartersSelected((l, i, tab)) # ---------------------------------------------------------------- drawing @@ -413,24 +412,25 @@ def _draw(): _clear(screen) ctrl = _shown() general = _cpe.WidgetTypes.WIDGET_GENERAL - if ctrl is not None: + if ctrl is not None and ctrl.kind == 'edit': + _drawEdit(screen, ctrl) + elif ctrl is not None: dark = u'' % _ROW_TEXT tabs = [] for i, name in enumerate(ctrl.sections): - if not name and ctrl.kind == 'edit' and i == 0: - name = u'Data' try: w = int(oc4screens._textWidth(name, 3)) except Exception: w = 9 * len(name) tabs.append((name, w + 20)) - # (as wide as its tabs need: the map mode's four do not fit the player mode's width) - width = max(_WW, 15 + sum(tw + 1 for name, tw in tabs) + 14) + # (as the original's: as wide as the player mode's, the tabs that do not fit scrolled to + # with two arrows at the right, the map mode's) + width = _WW + scroll = 15 + sum(tw + 1 for name, tw in tabs) + 14 > width + first = min(getattr(ctrl, 'tabFirst', 0), len(tabs) - 1) if scroll else 0 body_w = width - 2 * _BODY_X - # what the edit panel's section holds (a unit's or a city's data) goes over its items - controls = ctrl.kind == 'edit' and ctrl.active < len(ctrl.controls) and ctrl.controls[ctrl.active] items = _items(ctrl) - body_h = (_GRID_H if items else 0) + (_controlsHeight(ctrl.controls[ctrl.active]) if controls else 0) + 6 + body_h = (_GRID_H if items else 0) + 6 height = _BODY_Y + body_h + 8 # (the window: its inside and its frame under the title bar, the title on the bar) for name, y, h, style in (('OC4WBWindow', _TITLE_H, height - _TITLE_H, _WINDOW_INNER), ('OC4WBFrame', _TITLE_H, height - _TITLE_H, _WINDOW_FRAME), @@ -444,34 +444,23 @@ def _draw(): # the tabs, each as wide as its word x = _WX + 15 for i, (name, tw) in enumerate(tabs): + if i < first or (scroll and x + tw > _WX + width - 44): + continue tab = _add('OC4WBTabBack%d' % i) screen.addPanel(tab, u'', u'', True, False, x, _WY + _TAB_Y, tw, _TAB_H, _cpe.PanelStyles.PANEL_STYLE_MAIN) _style(screen, tab, _TAB_SKIN + ('Select' if i == ctrl.active else 'Default')) screen.setText(_add('OC4WBTab%d' % i, ('tab', ctrl, i)), 'Background', dark + name + u'', 1 << 2, x + tw / 2, _WY + _TAB_Y + 4, -0.3, _cpe.FontTypes.GAME_FONT, general, -1, -1) x += tw + 1 + if scroll: + for k, (arrow, d) in enumerate(((u'<', -1), (u'>', 1))): + screen.setText(_add('OC4WBTabScroll%d' % k, ('tabscroll', ctrl, d, len(tabs))), 'Background', u'' + dark + arrow + u'', 1 << 2, + _WX + width - 34 + 14 * k, _WY + _TAB_Y + 3, -0.3, _cpe.FontTypes.TITLE_FONT, general, -1, -1) body = _add('OC4WBBody') screen.addPanel(body, u'', u'', True, False, _WX + _BODY_X, _WY + _BODY_Y, body_w, body_h, _cpe.PanelStyles.PANEL_STYLE_IN) - y = _WY + _BODY_Y + 4 - if controls: - y = _drawControls(screen, ctrl, _WX + _BODY_X + 8, y, body_w - 16) if items: - grid = _add('OC4WBGrid') - screen.addScrollPanel(grid, u'', _WX + _BODY_X + 2, y - 2, body_w - 4, _GRID_H, _cpe.PanelStyles.PANEL_STYLE_EXTERNAL) - for k, item in enumerate(items): - cx, cy = (k % _COLUMNS) * _CELL, (k // _COLUMNS) * _CELL - if item[4]: - screen.attachPanelAt(grid, _add('OC4WBSel%d' % k), u'', u'', False, False, _cpe.PanelStyles.PANEL_STYLE_HUD_HELP, cx - 2, cy - 2, _CELL - 1, _CELL - 1, - general, -1, -1) - name = 'OC4WBItem%d' % k - if item[2]: - screen.setImageButtonAt(_add(name, ('item', ctrl, item)), grid, item[2], cx, cy, _ICON, _ICON, general, -1, -1) - else: - screen.setTextAt(_add(name, ('item', ctrl, item)), grid, item[3][:6], 0, cx, cy + 8, -0.3, _cpe.FontTypes.SMALL_FONT, general, -1, -1) - # (its help: the item's name, as the original's palette shows it under the mouse) - w = screen._s.get(name) - if w is not None: - w.help = _u(item[3]) + _drawGrid(screen, ctrl, items, _WX + _BODY_X + 2, _WY + _BODY_Y + 2, body_w - 4, _GRID_H) + if _flyout is not None and _flyout.items: mx, my = 300, 200 screen.addPanel(_add('OC4WBFlyout'), u'', u'', True, False, mx, my, 240, 24 * len(_flyout.items) + 12, _cpe.PanelStyles.PANEL_STYLE_MAIN) @@ -479,36 +468,179 @@ def _draw(): screen.setText(_add('OC4WBFly%d' % k, ('fly', item)), 'Background', item[0], 0, mx + 10, my + 8 + 24 * k, -0.3, _cpe.FontTypes.GAME_FONT, general, -1, -1) +def _item(screen, ctrl, item, k, parent, cx, cy): + """One item: its button (on the highlight when chosen), its help as the original's palette + shows it under the mouse: the game's help of what it places, else its name as a link.""" + general = _cpe.WidgetTypes.WIDGET_GENERAL + if item[4]: + screen.attachPanelAt(parent, _add('OC4WBSel%d' % k), u'', u'', False, False, _cpe.PanelStyles.PANEL_STYLE_HUD_HELP, cx - 2, cy - 2, _CELL - 1, _CELL - 1, + general, -1, -1) + name = 'OC4WBItem%d' % k + if item[2]: + screen.setImageButtonAt(_add(name, ('item', ctrl, item)), parent, item[2], cx, cy, _ICON, _ICON, general, -1, -1) + else: + screen.setTextAt(_add(name, ('item', ctrl, item)), parent, item[3][:6], 0, cx, cy + 8, -0.3, _cpe.FontTypes.SMALL_FONT, general, -1, -1) + w = screen._s.get(name) + if w is not None: + if item[5]: + w.helpWidget = (int(item[5][0]), int(item[5][1]), -1) + else: + w.help = u'' + _u(item[3]) + u'' + + +def _drawGrid(screen, ctrl, items, x, y, w, h, k0=0): + """Items in a scroll panel: seven to a row beside its scroll bar, or, when they fit without + one, as many as fit (the original's: the map mode's improvements eight).""" + grid = _add('OC4WBGrid%d' % k0) + screen.addScrollPanel(grid, u'', x, y, w, h, _cpe.PanelStyles.PANEL_STYLE_EXTERNAL) + columns = max(_COLUMNS, (w - 6) / _CELL) + if (len(items) + columns - 1) / columns * _CELL > h - 6: + columns = _COLUMNS + for k, item in enumerate(items): + _item(screen, ctrl, item, k0 + k, grid, (k % columns) * _CELL, (k // columns) * _CELL) + + +# The edit window (a unit's or a city's), as the original's (measured in Wine at 1600 x 900): in +# the middle of the screen, the tool window's frame and a title bar with a close box; two tabs; +# its controls 22 in, one under the other: an edit box, a pull down or a spin box 24 high, 8 +# apart; a label 21 high; a button 26; under a city's, its religions, holy cities, corporations +# and headquarters, a row each, 34 apart. A spin box is as wide as its longest value needs. +_EDIT_W = {True: 338, False: 310} # a unit's, a city's +_EDIT_TITLE_H, _EDIT_TAB_Y, _EDIT_BODY_Y, _EDIT_TOP = 26, 37, 65, 78 +_EDIT_ROW, _EDIT_ICON = 34, 30 +_SPIN_UP = 'SF_CtrlTheme_Civ4_Control_SpinBox_UpButton_Style' +_SPIN_DOWN = 'SF_CtrlTheme_Civ4_Control_SpinBox_DownButton_Style' +_CONTROL_H = {'label': 21, 'edit': 24, 'dropdown': 24, 'spinner': 24, 'button': 26} + + +def _gapAfter(controls, n): + if controls[n][0] == 'label' or n + 1 >= len(controls): + return 0 + return 6 if controls[n + 1][0] == 'button' else 8 + + def _controlsHeight(controls): - return sum({'label': 18, 'edit': 22, 'button': 28, 'dropdown': 28, 'spinner': 24}.get(c[0], 0) for c in controls) + 6 + return sum(_CONTROL_H.get(c[0], 0) + _gapAfter(controls, n) for n, c in enumerate(controls)) + + +def _spinWidth(c): + """(a spin box: as wide as the longer of its lowest and highest values, 35 + 11 a figure)""" + return 35 + 11 * max(len('%d' % int(c[4])), len('%d' % int(c[5]))) + + +def _itemsOf(ctrl, tab): + active, ctrl.active = ctrl.active, tab + try: + return _items(ctrl) + finally: + ctrl.active = active -def _drawControls(screen, ctrl, x, y, width): - for k, c in enumerate(ctrl.controls[ctrl.active]): +def _drawEdit(screen, ctrl): + general = _cpe.WidgetTypes.WIDGET_GENERAL + dark = u'' % _ROW_TEXT + unit = bool(getattr(ctrl, 'unit', False)) + controls = ctrl.controls[0] if ctrl.controls else [] + rows = [] if unit else _itemsOf(ctrl, 0) + nrows = len(set(item[0] for item in rows)) + height = _EDIT_TOP + _controlsHeight(controls) + (6 + (nrows - 1) * _EDIT_ROW + _EDIT_ICON + 18 if nrows else 24) + width = _EDIT_W[unit] + try: + RW, RH = screen.getXResolution(), screen.getYResolution() + except Exception: + RW, RH = 1600, 900 + wx, wy = (RW - width) / 2, max(0, (RH - height) / 2) + for name, y, h, style in (('OC4WBWindow', _EDIT_TITLE_H, height - _EDIT_TITLE_H, _WINDOW_INNER), ('OC4WBFrame', _EDIT_TITLE_H, height - _EDIT_TITLE_H, _WINDOW_FRAME), + ('OC4WBTitleBar', 0, _EDIT_TITLE_H, _WINDOW_TITLE)): + screen.addPanel(_add(name), u'', u'', True, False, wx, wy + y, width, h, _cpe.PanelStyles.PANEL_STYLE_MAIN) + _style(screen, name, style) + screen.setLabel(_add('OC4WBTitle'), 'Background', u'' + dark + _text(_TITLES['edit']) + u'', 1 << 0, wx + 10, wy + 4, -0.3, + _cpe.FontTypes.TITLE_FONT, general, -1, -1) + screen.setText(_add('OC4WBClose', ('close',)), 'Background', u'' + dark + u'x', 1 << 2, wx + width - 18, wy + 4, -0.3, + _cpe.FontTypes.TITLE_FONT, general, -1, -1) + # the tabs + x = wx + 13 + for i, name in enumerate(ctrl.sections): + try: + tw = int(oc4screens._textWidth(name, 3)) + 20 + except Exception: + tw = 9 * len(name) + 20 + tab = _add('OC4WBTabBack%d' % i) + screen.addPanel(tab, u'', u'', True, False, x, wy + _EDIT_TAB_Y, tw, _TAB_H, _cpe.PanelStyles.PANEL_STYLE_MAIN) + _style(screen, tab, _TAB_SKIN + ('Select' if i == ctrl.active else 'Default')) + screen.setText(_add('OC4WBTab%d' % i, ('tab', ctrl, i)), 'Background', dark + name + u'', 1 << 2, x + tw / 2, wy + _EDIT_TAB_Y + 4, -0.3, + _cpe.FontTypes.GAME_FONT, general, -1, -1) + x += tw + 1 + screen.addPanel(_add('OC4WBBody'), u'', u'', True, False, wx + 11, wy + _EDIT_BODY_Y, width - 22, height - _EDIT_BODY_Y - 10, _cpe.PanelStyles.PANEL_STYLE_IN) + cx, cw = wx + 22, width - 44 + if ctrl.active == 0: + y = _drawControls(screen, ctrl, controls, cx, wy + _EDIT_TOP, cw) + 6 + row, k, prev = -1, 0, None + for item in rows: + if item[0] != prev: + row, k, prev = row + 1, 0, item[0] + _item(screen, ctrl, item, 1000 + row * 100 + k, 'Background', cx - 1 + k * _EDIT_ROW, y + row * _EDIT_ROW) + k += 1 + else: + items = _itemsOf(ctrl, ctrl.active) + if items: + _drawGrid(screen, ctrl, items, wx + 13, wy + _EDIT_BODY_Y + 4, width - 26, height - _EDIT_BODY_Y - 18) + + +def _drawControls(screen, ctrl, controls, x, y, width): + general = _cpe.WidgetTypes.WIDGET_GENERAL + font = _cpe.FontTypes.GAME_FONT + for k, c in enumerate(controls): kind = c[0] if kind == 'label': - screen.setText(_add('OC4WBCtl%d' % k), 'Background', c[1], 0, x, y, -0.3, _cpe.FontTypes.SMALL_FONT, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1) - y += 18 + screen.setText(_add('OC4WBCtl%d' % k), 'Background', c[1], 0, x - 3, y + 1, -0.3, font, general, -1, -1) elif kind == 'edit': - screen.setText(_add('OC4WBCtl%d' % k), 'Background', c[1], 0, x, y, -0.3, _cpe.FontTypes.GAME_FONT, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1) - y += 22 + name = _add('OC4WBEdit%d' % k, ('edit', c[2], c[3])) + screen.addEditBoxGFC(name, x, y, width, 24, general, -1, -1, font) + screen.setEditBoxString(name, c[1]) elif kind == 'button': - screen.setButtonGFC(_add('OC4WBCtl%d' % k, ('call', c[2], c[3], ())), c[1], '', x, y, width, 24, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1, + screen.setButtonGFC(_add('OC4WBCtl%d' % k, ('call', c[2], c[3], ())), c[1], '', x - 1, y, width + 2, 26, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) - y += 28 elif kind == 'dropdown': name = _add('OC4WBDrop%d' % k, ('drop', c[3], c[4])) - screen.addDropDownBoxGFC(name, x, y, width, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1, _cpe.FontTypes.GAME_FONT) + screen.addDropDownBoxGFC(name, x, y, width, general, -1, -1, font) for i, choice in enumerate(c[2]): screen.addPullDownString(name, choice, i, i, i == c[5]) - y += 28 elif kind == 'spinner': - module, function, lo, hi, step, value = c[2], c[3], c[4], c[5], c[6], c[7] - screen.setText(_add('OC4WBMinus%d' % k, ('spin', ctrl, k, -1)), 'Background', u' - ', 0, x, y, -0.3, _cpe.FontTypes.GAME_FONT, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1) - screen.setText(_add('OC4WBValue%d' % k), 'Background', u'%d' % int(value), 0, x + 50, y, -0.3, _cpe.FontTypes.GAME_FONT, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1) - screen.setText(_add('OC4WBPlus%d' % k, ('spin', ctrl, k, 1)), 'Background', u' + ', 0, x + 110, y, -0.3, _cpe.FontTypes.GAME_FONT, _cpe.WidgetTypes.WIDGET_GENERAL, -1, -1) - y += 24 - return y + 6 + # (an edit box with the value, its up and down buttons at its right) + sw = _spinWidth(c) + name = _add('OC4WBEdit%d' % k, ('spinedit', ctrl, k)) + screen.addEditBoxGFC(name, x, y, sw - 21, 24, general, -1, -1, font) + screen.setEditBoxString(name, u'%d' % int(c[7])) + w = screen._s.get(name) + if w is not None: + w.allowed = u'-0123456789' + for part, d, style, by in (('OC4WBPlus%d', 1, _SPIN_UP, y), ('OC4WBMinus%d', -1, _SPIN_DOWN, y + 12)): + b = _add(part % k, ('spin', ctrl, k, d)) + screen.setButtonGFC(b, u'', '', x + sw - 21, by, 21, 12, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) + _style(screen, b, style) + y += _CONTROL_H.get(kind, 0) + _gapAfter(controls, k) + return y + + +def editDone(name, text): + """Enter in one of the edit window's edit boxes: the script told, as the original's.""" + choice = _choices.get(name) + if choice is None: + return + if choice[0] == 'edit': + _call(choice[1], choice[2], (_u(text),)) + elif choice[0] == 'spinedit': + ctrl, k = choice[1], choice[2] + c = list(ctrl.controls[0][k]) + try: + value = int(text) + except ValueError: + value = int(c[7]) + c[7] = max(c[4], min(c[5], value)) + ctrl.controls[0][k] = tuple(c) + _call(c[2], c[3], (int(c[7]),)) + _draw() # ---------------------------------------------------------------- input @@ -517,13 +649,16 @@ def handleInput(argsList): """A click on one of the palettes' widgets (oc4screens' input tuple: notify, data, ..., the function name at 5, the id at 3).""" notify, data, function, wid = argsList[0], argsList[1], argsList[5], argsList[3] - name = '%s%d' % (function, wid) if function in ('OC4WBTab', 'OC4WBItem', 'OC4WBFly', 'OC4WBCtl', 'OC4WBDrop', 'OC4WBMinus', 'OC4WBPlus') else function + name = '%s%d' % (function, wid) if function in ('OC4WBTab', 'OC4WBItem', 'OC4WBFly', 'OC4WBCtl', 'OC4WBDrop', 'OC4WBMinus', 'OC4WBPlus', 'OC4WBEdit', 'OC4WBTabScroll') else function choice = _choices.get(name) if choice is None: return 1 what = choice[0] if what == 'tab': choice[1].active = choice[2] + elif what == 'tabscroll': + ctrl = choice[1] + ctrl.tabFirst = max(0, min(choice[3] - 1, getattr(ctrl, 'tabFirst', 0) + choice[2])) elif what == 'item': _chosen(choice[1], choice[2]) elif what == 'fly': @@ -538,14 +673,29 @@ def handleInput(argsList): _call(choice[1], choice[2], (int(data),)) elif what == 'spin': ctrl, k, d = choice[1], choice[2], choice[3] - c = list(ctrl.controls[ctrl.active][k]) + c = list(ctrl.controls[0][k]) c[7] = max(c[4], min(c[5], c[7] + d * c[6])) - ctrl.controls[ctrl.active][k] = tuple(c) + ctrl.controls[0][k] = tuple(c) _call(c[2], c[3], (int(c[7]),)) + elif what in ('edit', 'spinedit'): + return 1 # (a click into it: it takes the keys; Enter tells the script, editDone) + elif what == 'close': + _closeEdit() _draw() return 1 +def _closeEdit(): + """The edit window's close box: the window gone, the palette of the mode back.""" + _ctrls['edit'].destroy() + wb = _wb() + try: + wb.m_bCtrlEditUp = False + (_ctrls['map'] if wb.m_bNormalMap else _ctrls['player']).enabled = True + except Exception: + _ctrls['player'].enabled = True + + def widgetClicked(widget, iData1, iData2): """The WorldBuilder's own buttons (WIDGET_WB_...), as the executable answers them.""" import CvScreensInterface as si diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index cd0eb9e0..6fc19ce0 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -2640,9 +2640,9 @@ namespace oc4::render return std::format("camera at {:.1f},{:.1f} (height {:.0f}), {:.1f} plots away, pitch {:.2f}", m->camera.target.x / p, m->camera.target.y / p, m->camera.target.z, m->camera.distance / p, m->camera.pitch); } - void MapWindow::setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed) + void MapWindow::setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed, bool fit) { - m->ui.setHelp(text, x, y, width, expandRight, expandDown, framed); + m->ui.setHelp(text, x, y, width, expandRight, expandDown, framed, fit); } void MapWindow::pressKeys(const std::string& keys) { diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 9c48f056..f38ef4b6 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -351,7 +351,8 @@ namespace oc4::render // Where the mouse is, in window pixels ((-1, -1) before it came in). std::pair mousePosition() const; // The help for what is under the mouse, in the screens' help area. - void setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false); + // fit: a tooltip as wide as its text (up to width), not the help area's width. + void setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false, bool fit = false); // The text shown when the mouse rests on a plot (lines; the game's plot help). void setPlotHelp(std::function help); diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index c7ec4b5a..ee017266 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -279,13 +279,15 @@ namespace oc4::render // A help taller than the room it grows into gets wider, then is kept on the screen. const float room = std::max(m_helpDown ? sh - m_helpY : m_helpY, 100.0f); const float widest = std::max(m_helpRight ? sw - m_helpX : m_helpX, m_helpWidth); - float w = m_helpWidth, h = o.richHeight(text, w - 2 * inX, m_sizes[2], false) + 2 * inY; + // (a tooltip: as wide as its longest line, up to its width) + float w = m_helpFit ? std::min(std::ceil(o.richWidth(text, m_sizes[2], false)) + 2 * inX + 2, m_helpWidth) : m_helpWidth; + float h = o.richHeight(text, w - 2 * inX, m_sizes[2], false) + 2 * inY; while (h > room && w < widest) { w = std::min(w * 1.5f, widest); h = o.richHeight(text, w - 2 * inX, m_sizes[2], false) + 2 * inY; } - const float x = m_helpRight ? m_helpX : m_helpX - w; + const float x = std::clamp(m_helpRight ? m_helpX : m_helpX - w, 0.0f, std::max(sw - w, 0.0f)); const float y = std::clamp(m_helpDown ? m_helpY : m_helpY - h, 0.0f, std::max(sh - h, 0.0f)); if (see) Theme::draw(o, m_hudHelp, x, y, x + w, y + h); @@ -352,9 +354,10 @@ namespace oc4::render return MapWindow::UiClick{ pressed, m_pressedRight, shift, ctrl, alt }; } - void UiLayer::setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed) + void UiLayer::setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed, bool fit) { m_helpFramed = framed; + m_helpFit = fit; m_help = widen(text); m_helpX = x; m_helpY = y; diff --git a/src/render/UiLayer.h b/src/render/UiLayer.h index f00bca73..68f1a54c 100644 --- a/src/render/UiLayer.h +++ b/src/render/UiLayer.h @@ -60,7 +60,8 @@ namespace oc4::render // framed: the help area has art of its own (the city screen's), in the theme's tooltip; // else the main interface's see-through box (PANEL_STYLE_HUD_HELP). - void setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false); + // fit: as wide as its text, up to width (a tooltip at the widget, the World Builder's). + void setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false, bool fit = false); // The size of a widget's font (FontTypes) as the screens draw it. float textSize(int font) const { return fontSize(font); } // The plot's help where the screens show theirs, in the same box (the game's look). @@ -110,7 +111,7 @@ namespace oc4::render bool m_pressedRight = false; std::wstring m_help; float m_helpX = 0, m_helpY = 0, m_helpWidth = 350; - bool m_helpRight = true, m_helpDown = false, m_helpFramed = false; + bool m_helpRight = true, m_helpDown = false, m_helpFramed = false, m_helpFit = false; // A help in the help area: its box, then its text. void drawHelp(Overlay& o, const std::wstring& text); }; From 9ee1241b68c793f597f6592a04f90157e1c7c2b3 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 12:46:22 +0100 Subject: [PATCH 54/89] World Builder: each feature variety with its own button (the forest's leafy, evergreen and snowy) The palette listed a feature once a variety but always with the feature's button. The art defines give each variety its own (CIV4ArtDefines_Feature VarietyButton); a host call reads it (CvArtInfoFeature::getVariety, exported). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 6 ++++++ apps/oc4core/python/oc4wb.py | 8 +++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 72ab19ba..7405d676 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -208,6 +208,12 @@ namespace oc4::host CvDLLWidgetData::getInstance().parseHelp(text, w); return std::wstring(text.getCString()); }); + // A feature variety's button (CIV4ArtDefines_Feature's VarietyButton: the forest's leafy, + // evergreen and snowy ones), as the World Builder's palette shows them; "" for none. + host.def("feature_variety_button", [](int feature, int variety) { + const CvArtInfoFeature* art = feature >= 0 && feature < GC.getNumFeatureInfos() ? GC.getFeatureInfo(static_cast(feature)).getArtInfo() : nullptr; + return art && variety >= 0 && variety < art->getNumVarieties() ? std::string(art->getVariety(variety).getVarietyButton().c_str()) : std::string(); + }); host.def("ui_is_dirty", [&ui](int bit) { return ui.isDirty(static_cast(bit)); }); host.def("ui_set_dirty", [&ui](int bit, bool value) { ui.setDirty(static_cast(bit), value); }); host.def("ui_make_dirty", [&ui] { ui.makeInterfaceDirty(); }); diff --git a/apps/oc4core/python/oc4wb.py b/apps/oc4core/python/oc4wb.py index 3b511991..076cb49a 100644 --- a/apps/oc4core/python/oc4wb.py +++ b/apps/oc4core/python/oc4wb.py @@ -287,7 +287,13 @@ def _items(ctrl): for i in range(gc.getNumFeatureInfos()): info = gc.getFeatureInfo(i) for j in range(info.getNumVarieties()): - out.append((2, k, info.getButton(), info.getDescription(), sel(2, k), (W.WIDGET_PEDIA_JUMP_TO_FEATURE, i))) + # (each variety its own button, as the original's: the forest's leafy, evergreen + # and snowy ones) + try: + button = oc4host.feature_variety_button(i, j) or info.getButton() + except Exception: + button = info.getButton() + out.append((2, k, button, info.getDescription(), sel(2, k), (W.WIDGET_PEDIA_JUMP_TO_FEATURE, i))) k += 1 for i in range(gc.getNumRouteInfos()): out.append((3, i, gc.getRouteInfo(i).getButton(), gc.getRouteInfo(i).getDescription(), sel(3, i), None)) From 5ae664a35662d54a783f3c821c01af697da591d7 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sun, 22 Nov 2026 21:53:41 +0100 Subject: [PATCH 55/89] World Builder: the map mode's tabs as the original's, the next one cut at the arrows Seen in Wine (BtS 3.19 + BUG + BULL, 1600 x 900, the map mode): the tab after the last whole one (Terrains) shows narrowed up to x 272, its word cut there; right of it two small arrows, the right one white, the left one grey while the first tab shows. The palette is 315 wide in player and map mode (its frame's light line at x 313 in both). From Civ4Theme_Tab.thm: the arrows are SF_CtrlTheme_Civ4_Control_Tab_Arrow_ Left/RightButton_Style (Civ4/tab_arrows.tga, 14 x 14 cells: default, rollover, press, disable), 12 x 25 each at the strip's end, which keeps End_Arrow_Indent (30) for them only when the tabs overflow (302 - 30 = 272, the cut seen in Wine). Before, the tabs that did not fit were left out and the arrows were "<" ">" text, so Terrains and Territory were easy to miss. An arrow with nothing more that way is now grey and takes no click. oc4screens widgets get a clipRect (drawn and clicked only inside it) for the cut tab's word. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4screens.py | 5 +++- apps/oc4core/python/oc4wb.py | 46 +++++++++++++++++++++++-------- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index a7b260a5..5d6f1e01 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -86,7 +86,7 @@ def _int(value, default=-1): class _Widget(object): __slots__ = ('name', 'kind', 'parent', 'mode', 'x', 'y', 'z', 'w', 'h', 'style', 'pstyle', 'text', 'help', 'tex', 'tex2', - 'wt', 'd1', 'd2', 'opt', 'flags', 'font', 'shown', 'enabled', 'state', 'hittest', 'seq', 'vertical', 'scroll', 'children', + 'wt', 'd1', 'd2', 'opt', 'flags', 'font', 'shown', 'enabled', 'state', 'hittest', 'seq', 'vertical', 'scroll', 'clipRect', 'children', 'bars', 'lists', 'columns', 'rows', 'headers', 'iconw', 'iconh', 'items', 'selected', 'color', 'size', 'defw', 'defh', 'points', 'offset', 'extent', 'picked', 'hoffset', 'hextent', 'cells', 'sort', 'inset', 'maxChars', 'allowed', 'helpWidget') @@ -113,6 +113,7 @@ def __init__(self, name, kind): self.seq = 0 self.vertical = True self.scroll = False + self.clipRect = None # (x0, y0, x1, y1) on the screen: it drawn and clicked only there (oc4wb's partly shown tab) self.children = [] self.maxChars = 0 # an edit box's: at most this many characters (0: any) self.allowed = None # ... and only these (None: any) @@ -1530,6 +1531,8 @@ def _display_widget(s, w, ox, oy, clip, flow, out, cell=None): table's cell only there (cell: that cell's corner).""" if not w.shown or (w.mode == 'cell') != (cell is not None): return + if w.clipRect is not None: + clip = _clipTo(clip, w.clipRect) if cell is not None: x, y = cell elif w.mode == 'abs': diff --git a/apps/oc4core/python/oc4wb.py b/apps/oc4core/python/oc4wb.py index 076cb49a..1a4891f5 100644 --- a/apps/oc4core/python/oc4wb.py +++ b/apps/oc4core/python/oc4wb.py @@ -387,8 +387,15 @@ def _shown(): _WINDOW_FRAME = '@SF_CtrlTheme_Civ4_Control_Window_Tool_InFrameBorder_Normal_Style|GFC_CtrlTheme_Bitmap_Control_Border_Skin_Full_Default' _TITLE_H = 20 _TAB_SKIN = '@GFC_CtrlTheme_Bitmap_Control_Tab_SkinStyle_Top_Begin_BaseLevel_Single|GFC_CtrlTheme_Bitmap_Control_Tab_Skin_Full_' +# The tabs end 13 px from the window's right edge. When they do not fit there (the map mode's), +# as seen in Wine at 1600 x 900: the theme's End_Arrow_Indent (30, Civ4Theme_Tab.thm) is kept +# for two arrow buttons, and the tab after the last whole one shows up to there, narrowed to end +# there, its word cut. The arrows are the theme's tab arrows (12 x 25 each, the art +# Civ4/tab_arrows.tga 14 x 14 in their middle); an arrow with nothing more that way is grey. +_TAB_ARROWS = ('SF_CtrlTheme_Civ4_Control_Tab_Arrow_LeftButton_Style', 'SF_CtrlTheme_Civ4_Control_Tab_Arrow_RightButton_Style') +_TAB_END, _ARROW_INDENT, _ARROW_X, _ARROW_Y, _ARROW_H = 13, 30, (38, 25), 3, 25 _TITLES = {'player': 'TXT_KEY_WB_PLAYER_MODE', 'map': 'TXT_KEY_WB_MAP_MODE', 'edit': 'TXT_KEY_WB_WORLD_BUILDER_EDIT_CONTROL'} -_WX, _WY, _WW = 0, 0, 318 +_WX, _WY, _WW = 0, 0, 315 # (seen in Wine at 1600 x 900: 315 wide in player and map mode) _TAB_Y, _TAB_H = 31, 28 _BODY_X, _BODY_Y = 12, 59 _GRID_H = 162 # four rows and a half show, as the original's @@ -429,10 +436,13 @@ def _draw(): except Exception: w = 9 * len(name) tabs.append((name, w + 20)) - # (as the original's: as wide as the player mode's, the tabs that do not fit scrolled to - # with two arrows at the right, the map mode's) + # (as the original's: as wide as the player mode's; the tabs that do not fit scrolled to + # with the two arrows at the right, the map mode's) width = _WW - scroll = 15 + sum(tw + 1 for name, tw in tabs) + 14 > width + cut = _WX + width - _TAB_END + scroll = _WX + 15 + sum(tw + 1 for name, tw in tabs) - 1 > cut + if scroll: + cut -= _ARROW_INDENT first = min(getattr(ctrl, 'tabFirst', 0), len(tabs) - 1) if scroll else 0 body_w = width - 2 * _BODY_X items = _items(ctrl) @@ -447,21 +457,35 @@ def _draw(): if title: screen.setLabel(_add('OC4WBTitle'), 'Background', u'' + dark + title + u'', 1 << 0, _WX + 6, _WY + 1, -0.3, _cpe.FontTypes.TITLE_FONT, general, -1, -1) - # the tabs, each as wide as its word + # the tabs, each as wide as its word; the one that does not fit whole cut at the arrows x = _WX + 15 + more = False for i, (name, tw) in enumerate(tabs): - if i < first or (scroll and x + tw > _WX + width - 44): + if i < first: continue + if scroll and x >= cut: + more = True + break + part = scroll and x + tw > cut + more = more or part tab = _add('OC4WBTabBack%d' % i) - screen.addPanel(tab, u'', u'', True, False, x, _WY + _TAB_Y, tw, _TAB_H, _cpe.PanelStyles.PANEL_STYLE_MAIN) + # (the cut one's skin narrowed to the room left, its end showing; its word cut there) + screen.addPanel(tab, u'', u'', True, False, x, _WY + _TAB_Y, cut - x if part else tw, _TAB_H, _cpe.PanelStyles.PANEL_STYLE_MAIN) _style(screen, tab, _TAB_SKIN + ('Select' if i == ctrl.active else 'Default')) - screen.setText(_add('OC4WBTab%d' % i, ('tab', ctrl, i)), 'Background', dark + name + u'', 1 << 2, x + tw / 2, _WY + _TAB_Y + 4, -0.3, + word = _add('OC4WBTab%d' % i, ('tab', ctrl, i)) + screen.setText(word, 'Background', dark + name + u'', 1 << 2, x + tw / 2, _WY + _TAB_Y + 4, -0.3, _cpe.FontTypes.GAME_FONT, general, -1, -1) + w = screen._s.get(word) + if part and w is not None: + w.clipRect = (x, _WY + _TAB_Y, cut, _WY + _TAB_Y + _TAB_H) x += tw + 1 if scroll: - for k, (arrow, d) in enumerate(((u'<', -1), (u'>', 1))): - screen.setText(_add('OC4WBTabScroll%d' % k, ('tabscroll', ctrl, d, len(tabs))), 'Background', u'' + dark + arrow + u'', 1 << 2, - _WX + width - 34 + 14 * k, _WY + _TAB_Y + 3, -0.3, _cpe.FontTypes.TITLE_FONT, general, -1, -1) + for k, d in enumerate((-1, 1)): + b = _add('OC4WBTabScroll%d' % k, ('tabscroll', ctrl, d, len(tabs))) + screen.setButtonGFC(b, u'', '', _WX + width - _ARROW_X[k], _WY + _TAB_Y + _ARROW_Y, 14, _ARROW_H, general, -1, -1, + _cpe.ButtonStyles.BUTTON_STYLE_STANDARD) + _style(screen, b, _TAB_ARROWS[k]) + screen.enable(b, first > 0 if d < 0 else more) body = _add('OC4WBBody') screen.addPanel(body, u'', u'', True, False, _WX + _BODY_X, _WY + _BODY_Y, body_w, body_h, _cpe.PanelStyles.PANEL_STYLE_IN) if items: From 5b329ebc21ad2bda53ee25bc175c2e22c7387f51 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 06:37:55 +0100 Subject: [PATCH 56/89] Options: CivilizationIV.ini's settings on the OpenCiv4 tab No tech splash (NoTechSplash), no event messages on the screen (NoEventMessages), autosave every N turns and keep M (AutoSaveInterval 4, MaxAutoSaves 5) or OpenCiv4's own autosaves, field of view (FIELD_OF_VIEW, 0: GlobalDefines.xml's), a frame cap (SetMaxFrameRate). Kept in profile.ini; number boxes take digits only and are kept as typed. The autosaves as seen in the original under Wine (AutoSaveInterval 2, MaxAutoSaves 3, Saves\single\auto listed at the start of each of 16 turns): AutoSave_Initial_ at the game's start, then a save every interval's turn named AutoSave_ (AutoSave_BC-3920); when one more than the number kept is written, the oldest AutoSave_ goes in the same turn; the initial save is not counted and never deleted. Only BC years were seen, so an AD year's name is our guess. The rule is in AutoSaves.h, with a test. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 9 ++ apps/oc4core/AutoSaves.h | 63 ++++++++++++++ apps/oc4core/Interface.cpp | 9 +- apps/oc4core/Interface.h | 5 +- apps/oc4core/Screens.cpp | 13 +++ apps/oc4core/Utility.h | 5 ++ apps/oc4core/main.cpp | 51 +++++++----- apps/oc4core/python/oc4options.py | 134 ++++++++++++++++++++++++++++++ apps/oc4core/python/oc4screens.py | 7 ++ src/render/MapWindow.cpp | 13 +++ src/render/MapWindow.h | 2 + tests/auto_saves_test.cpp | 73 ++++++++++++++++ tests/ini_options_test.py | 92 ++++++++++++++++++++ tests/player_options_test.py | 4 +- 14 files changed, 456 insertions(+), 24 deletions(-) create mode 100644 apps/oc4core/AutoSaves.h create mode 100644 tests/auto_saves_test.cpp create mode 100644 tests/ini_options_test.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3c95b230..7ccfceaf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -379,12 +379,21 @@ target_link_libraries(auto_end_turn_test PRIVATE oc4_options) add_test(NAME auto_end_turn COMMAND auto_end_turn_test) set_target_properties(auto_end_turn_test PROPERTIES FOLDER "tests") +add_executable(auto_saves_test tests/auto_saves_test.cpp) +target_include_directories(auto_saves_test PRIVATE apps/oc4core) +target_link_libraries(auto_saves_test PRIVATE oc4_options) +add_test(NAME auto_saves COMMAND auto_saves_test) +set_target_properties(auto_saves_test PROPERTIES FOLDER "tests") + # The player options kept in the player's profile, and the options screen's OpenCiv4 tab # (oc4options.py, with a stand-in host). find_package(Python3 COMPONENTS Interpreter QUIET) if(Python3_Interpreter_FOUND) add_test(NAME player_options COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/tests/player_options_test.py ${CMAKE_CURRENT_SOURCE_DIR}/apps/oc4core/python) + # CivilizationIV.ini's settings on the OpenCiv4 tab, kept in the profile. + add_test(NAME ini_options COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/tests/ini_options_test.py + ${CMAKE_CURRENT_SOURCE_DIR}/apps/oc4core/python) endif() add_executable(xml_decode_test tests/xml_decode_test.cpp) diff --git a/apps/oc4core/AutoSaves.h b/apps/oc4core/AutoSaves.h new file mode 100644 index 00000000..c8c027f4 --- /dev/null +++ b/apps/oc4core/AutoSaves.h @@ -0,0 +1,63 @@ +#pragma once +// The game's autosaves as the original makes them (CivilizationIV.ini's AutoSaveInterval and +// MaxAutoSaves; the options' OpenCiv4 tab), as seen in the running original under Wine +// (2026-11-22: interval 2, 3 kept, Saves\single\auto listed at each of 16 turns): the game's first +// turn as AutoSave_Initial_BC-4000, then at the start of every interval's turn (2, 4, 6, ...) +// AutoSave_ (AutoSave_BC-3920); when one more than the number kept is written, the oldest +// AutoSave_ goes. The initial save doesn't count and stays. Interval 0: none, as the ini's +// comment says. Or openciv4's own way: each game its own files, the kept ones in turn. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace oc4::host +{ + struct AutoSaveSettings + { + int interval = 4, kept = 5; // (the ini's defaults; interval 0: no autosaves) + bool openciv4 = false; // openciv4's own (My Games\openciv4\Saves\auto, every 25th turn kept) + }; + + // Whether the game saves at this turn's start (the game's first: its initial save). + inline bool autoSaveDue(const AutoSaveSettings& how, int turn, bool initial) + { + return how.interval > 0 && (initial || turn % how.interval == 0); + } + + // The original's file name: AutoSave_[Initial_]BC-4000.CivBeyondSwordSave. (Only BC years were + // seen; an AD year is written the same way, AD-1250, as our guess.) + inline std::wstring autoSaveName(bool initial, int year) + { + return std::format(L"AutoSave_{}{}-{}.CivBeyondSwordSave", initial ? L"Initial_" : L"", year < 0 ? L"BC" : L"AD", std::abs(year)); + } + + // openciv4's own: _, the kept ones in turn. + inline std::wstring openciv4AutoSaveName(const std::wstring& stem, const AutoSaveSettings& how, int turn) + { + return std::format(L"{}_{}.CivBeyondSwordSave", stem, turn / std::max(1, how.interval) % std::max(1, how.kept)); + } + + // The AutoSave_ saves in the folder beyond the newest kept ones (the oldest first to go); + // not the initial save, nor any other file. + inline std::vector autoSavesBeyond(const std::filesystem::path& folder, int kept) + { + std::vector> saves; + std::error_code ec; + for (const auto& e : std::filesystem::directory_iterator(folder, ec)) + if (const std::wstring name = e.path().filename().wstring(); + e.is_regular_file() && name.starts_with(L"AutoSave_") && !name.starts_with(L"AutoSave_Initial_")) + saves.push_back({ e.last_write_time(), e.path() }); + std::ranges::sort(saves, std::greater{}); + std::vector out; + for (size_t i = size_t(std::max(1, kept)); i < saves.size(); ++i) + out.push_back(saves[i].second); + return out; + } +} diff --git a/apps/oc4core/Interface.cpp b/apps/oc4core/Interface.cpp index 97ae45b3..9acf598d 100644 --- a/apps/oc4core/Interface.cpp +++ b/apps/oc4core/Interface.cpp @@ -214,7 +214,8 @@ namespace oc4::host pszIcon, eFlashColor, iFlashX, iFlashY, bShowOffScreenArrows, bShowOnScreenArrows)); if (ePlayer != GC.getGame().getActivePlayer()) return; - show(szString.c_str(), iLength); + if (!noEventMessages) + show(szString.c_str(), iLength); if (sounds && pszSound && *pszSound) sounds->play(pszSound); } @@ -234,7 +235,11 @@ namespace oc4::host } // (the messages of the last turn again, when a game is loaded: CvPlayer::showMissedMessages) - void Interface::showMessage(CvTalkingHeadMessage& msg) { show(msg.getDescription(), msg.getLength()); } + void Interface::showMessage(CvTalkingHeadMessage& msg) + { + if (!noEventMessages) + show(msg.getDescription(), msg.getLength()); + } void Interface::clearEventMessages() { diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index e14dd520..f2b3a428 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -219,7 +219,10 @@ namespace oc4::host // The tech splash (the scripts' CvTechSplashScreen, with the tech's quote): only with the // game's screens up (Screens::start); without them the game core plays the short sound instead. bool techSplash = false; - bool noTechSplash() override { return !techSplash; } + bool noTechSplash() override { return !techSplash || noTechSplashOption; } + // CivilizationIV.ini's NoTechSplash and NoEventMessages (the options' OpenCiv4 tab): no tech + // splash; the messages not shown on the screen (still in the turn log, their sound played). + bool noTechSplashOption = false, noEventMessages = false; bool isInAdvancedStart() const override { return false; } CvPlot* getLookAtPlot() override { return nullptr; } CvPlot* getGotoPlot() override { return m_gotoPlot; } diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index efe18e86..b405b320 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -448,6 +448,16 @@ namespace oc4::host Sounds& sounds = utility.sounds(); host.def("audio_play", [&sounds](const std::string& tag) { sounds.play(tag); }); host.def("ui_no_tech_splash", [&ui] { return ui.noTechSplash(); }); + // CivilizationIV.ini's settings the original's options screen has not (the options' + // OpenCiv4 tab, oc4options): no tech splash, no event messages on the screen, the autosaves, + // a frame cap. + host.def("set_ini_options", [&ui, &utility](bool noTechSplash, bool noEventMessages, int autoSaveInterval, int autoSavesKept, + bool openciv4AutoSaves, int maxFrameRate) { + ui.noTechSplashOption = noTechSplash; + ui.noEventMessages = noEventMessages; + utility.engine().autoSave = { std::max(0, autoSaveInterval), std::max(1, autoSavesKept), openciv4AutoSaves }; + utility.engine().maxFrameRate = std::max(0, maxFrameRate); + }); host.def("movie_playable", [&utility](const std::string& file) { const auto at = utility.assets().locate(file); return media::available() && at && !at->file.empty(); @@ -722,6 +732,8 @@ if _walls: py::module_::import("CvScreensInterface").attr("showMainInterface")(); m_utility.gameInterface().makeInterfaceDirty(); m_utility.gameInterface().techSplash = true; + // (the profile's field of view, CivilizationIV.ini's FIELD_OF_VIEW, over GlobalDefines.xml's) + py::module_::import("oc4options").attr("applyFieldOfView")(); // (its own errors its own) m_active = true; m_laidOut = m_seenSize = { width, height }; } @@ -923,6 +935,7 @@ if _walls: } } window.setAutoEndTurn(m_utility.autoEndTurn()); + window.setMaxFrameRate(m_utility.engine().maxFrameRate); if (!m_menu) // (the main menu has no map to scroll) window.setEdgeScroll(m_utility.edgeScroll()); g_display = window.uiDisplay(); diff --git a/apps/oc4core/Utility.h b/apps/oc4core/Utility.h index b01d32be..a9f6a25d 100644 --- a/apps/oc4core/Utility.h +++ b/apps/oc4core/Utility.h @@ -3,6 +3,7 @@ // CvDLLUtilityIFaceBase: the engine services the game DLL calls through gDLL. #include "Audio.h" +#include "AutoSaves.h" #include "Diplomacy.h" #include "FAStar.h" #include "Interface.h" @@ -59,6 +60,10 @@ namespace oc4::host onAutoSave(bInitial); } std::function onAutoSave; + // How it saves (AutoSaves.h; the options' OpenCiv4 tab). + AutoSaveSettings autoSave; + // At most this many frames a second (the ini's SetMaxFrameRate; 0: as many as the display shows). + std::atomic maxFrameRate = 0; // The map's display the game's controls switch (Ctrl+R, the unit icons, Ctrl+T): the // window shows them so. diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index d18f8ef5..c2d4fbdc 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -826,30 +826,41 @@ namespace // it was and stays live (the camera moves, the figures move), and nothing here touches // the game. host::TurnWorker worker; - // A game played by hand is saved at each turn's start (Documents\My Games\openciv4\Saves\ - // auto, ten in turn), as the original does; a scripted one is not. + // A game played by hand is saved as the original saves it, or openciv4's own way + // (AutoSaves.h, the options' OpenCiv4 tab); a scripted game is not. if (opt.viewSeconds <= 0) - utility.engine().onAutoSave = [&session, &game](bool) { - PWSTR documents = nullptr; - if (FAILED(SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &documents))) + utility.engine().onAutoSave = [&session, &game, &engine = utility.engine()](bool initial) { + const host::AutoSaveSettings how = engine.autoSave; + const int turn = game.getGameTurn(); + if (!host::autoSaveDue(how, turn, initial)) return; - const fs::path folder = fs::path(documents) / L"My Games" / L"openciv4" / L"Saves" / L"auto"; - CoTaskMemFree(documents); - // (each game its own: the active civilization and the game's map seed in the name; - // every 25th turn kept for good) - std::wstring civ; - if (const PlayerTypes active = game.getActivePlayer(); active != NO_PLAYER) - for (const wchar_t c : std::wstring(GC.getInitCore().getCivShortDesc(active).GetCString())) - civ += std::iswalnum(c) ? c : L'_'; - const std::wstring stem = std::format(L"AutoSave_{}_{:08X}", civ, GC.getInitCore().getMapRandSeed()); - const fs::path path = folder / std::format(L"{}_{}.CivBeyondSwordSave", stem, game.getGameTurn() % 10); - try - { + const auto save = [&](const fs::path& folder, const fs::path& path) { fs::create_directories(folder); session.saveGame(path); - if (game.getGameTurn() % 25 == 0) - fs::copy_file(path, folder / std::format(L"{}_turn{}.CivBeyondSwordSave", stem, game.getGameTurn()), fs::copy_options::overwrite_existing); - std::printf(" autosaved turn %d: %s\n", game.getGameTurn(), path.string().c_str()); + std::printf(" autosaved turn %d: %s\n", turn, path.string().c_str()); + }; + try + { + if (how.openciv4) + { + // (Documents\My Games\openciv4\Saves\auto; the active civilization and the + // game's map seed in the name, every 25th turn kept for good) + const fs::path folder = documentsFolder() / L"My Games" / L"openciv4" / L"Saves" / L"auto"; + std::wstring civ; + if (const PlayerTypes active = game.getActivePlayer(); active != NO_PLAYER) + for (const wchar_t c : std::wstring(GC.getInitCore().getCivShortDesc(active).GetCString())) + civ += std::iswalnum(c) ? c : L'_'; + const std::wstring stem = std::format(L"AutoSave_{}_{:08X}", civ, GC.getInitCore().getMapRandSeed()); + const fs::path path = folder / host::openciv4AutoSaveName(stem, how, turn); + save(folder, path); + if (turn % 25 == 0) + fs::copy_file(path, folder / std::format(L"{}_turn{}.CivBeyondSwordSave", stem, turn), fs::copy_options::overwrite_existing); + return; + } + const fs::path folder = documentsFolder() / L"My Games" / L"Beyond the Sword" / L"Saves" / L"single" / L"auto"; + save(folder, folder / host::autoSaveName(initial, game.getGameTurnYear())); + for (const fs::path& old : host::autoSavesBeyond(folder, how.kept)) + fs::remove(old); } catch (const std::exception& e) { diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index dd7e1664..a713f1f4 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -49,6 +49,15 @@ def _scales(): 'speakers': '', 'musicPath': '', 'voice': False, 'wasdPan': False, 'autoEndTurn': False, 'edgeScroll': True, } +# CivilizationIV.ini's settings the original's options screen has not, on the OpenCiv4 tab with +# the ini's defaults: NoTechSplash, NoEventMessages, AutoSaveInterval, MaxAutoSaves (and +# openciv4's own autosaves), FIELD_OF_VIEW (0: GlobalDefines.xml's), SetMaxFrameRate (0: none). +_INI_FLAGS = ('noTechSplash', 'noEventMessages', 'openciv4AutoSaves') +_INI_NUMBERS = (('autoSaveInterval', 4), ('autoSavesKept', 5), ('fieldOfView', 0), ('maxFrameRate', 0)) +for _k in _INI_FLAGS: + _profile[_k] = False +for _k, _v in _INI_NUMBERS: + _profile[_k] = _v def _path(): @@ -95,6 +104,10 @@ def _load(): _profile[parts[0]] = value elif parts[0] == 'version': version = int(value) + elif parts[0] in _INI_FLAGS: + _profile[parts[0]] = value == '1' + elif parts[0] in dict(_INI_NUMBERS): + _profile[parts[0]] = max(0, int(value)) except (ValueError, IndexError): pass finally: @@ -125,6 +138,10 @@ def _save(): for kind in ('graphic', 'player'): for i, on in sorted(_profile[kind].items()): lines.append('%s.%d=%d' % (kind, i, 1 if on else 0)) + for key in _INI_FLAGS: + lines.append('%s=%d' % (key, 1 if _profile[key] else 0)) + for key, default in _INI_NUMBERS: + lines.append('%s=%d' % (key, _profile[key])) try: f = open(path, 'w') f.write('\n'.join(lines) + '\n') @@ -135,6 +152,7 @@ def _save(): def _applyGraphics(): """The graphic options the profile has, to the host (the game core and the window ask it).""" + _applyIniOptions() try: oc4host.reset_graphic_options() for i, on in _profile['graphic'].items(): @@ -236,6 +254,73 @@ def _edgeScrollOn(): return _profile['edgeScroll'] +# CivilizationIV.ini's settings (see _INI_FLAGS): check boxes and number boxes on the OpenCiv4 tab. +NO_TECH_SPLASH_CHECKBOX = 'Oc4NoTechSplashCheckBox' +NO_EVENT_MESSAGES_CHECKBOX = 'Oc4NoEventMessagesCheckBox' +OPENCIV4_AUTOSAVES_CHECKBOX = 'Oc4AutoSavesCheckBox' +_xmlFieldOfView = [None] # (GlobalDefines.xml's, before the profile's replaced it) + + +def _applyIniOptions(): + try: + oc4host.set_ini_options(_profile['noTechSplash'], _profile['noEventMessages'], _profile['autoSaveInterval'], + _profile['autoSavesKept'], _profile['openciv4AutoSaves'], _profile['maxFrameRate']) + except Exception: + pass + applyFieldOfView() + + +def applyFieldOfView(): + """FIELD_OF_VIEW: a non-zero one replaces GlobalDefines.xml's, as the ini's does (the host + calls this as a game starts; BUG's slider on the map may change it again later).""" + try: + gc = _cpe.CyGlobalContext() + fov = _profile['fieldOfView'] + if fov > 0: + if _xmlFieldOfView[0] is None: + xml = gc.getDefineFLOAT('FIELD_OF_VIEW') + if xml <= 0: + return # (GlobalDefines.xml not read yet: the game's start sets it) + _xmlFieldOfView[0] = xml + gc.setDefineFLOAT('FIELD_OF_VIEW', float(fov)) + elif _xmlFieldOfView[0] is not None: + gc.setDefineFLOAT('FIELD_OF_VIEW', float(_xmlFieldOfView[0])) + _xmlFieldOfView[0] = None + except Exception: + pass + + +def handleIniFlagClicked(args): + """One of the ini's check boxes (its argument the profile's key).""" + _profile[str(args[1])] = bool(args[0]) + _applyIniOptions() + return 1 + + +def handleIniNumberTyped(args): + """One of the ini's number boxes, typed into (its argument the profile's key): digits only, an + empty box 0.""" + digits = ''.join([c for c in u'%s' % (args[0],) if c in u'0123456789']) + _profile[str(args[1])] = int(digits[:6]) if digits else 0 + _applyIniOptions() + return 1 + + +def _editTyped(w): + """oc4screens: an edit box typed into; one of the tab's, its callback with the text.""" + ctrl = _state['ctrl'] + if ctrl is None or not w.name.startswith('OptW'): + return + try: + n = ctrl._nodes.get(int(w.name[4:])) + except ValueError: + return + if n is None or n.kind != 'edit': + return + n.text = w.text + _call(n, (w.text, n.callback[2] if n.callback else n.name)) + + def _applyPlayerOptions(): """The player options the profile has, to the host: the game core sends them to the active player at the start of every game, new or loaded, as the original's profile (a save's own are @@ -540,6 +625,49 @@ def _attachOpenCiv4Tab(self): EDGE_SCROLL_CHECKBOX, _edgeScrollOn()) self.setToolTip(EDGE_SCROLL_CHECKBOX, u'Moving the mouse to the edge of the screen or window moves the map that way. ' u'Turn it off to pan only with the arrow keys (or W A S D) and the mouse.') + self._attachIniOptions(parent) + + def _attachIniOptions(self, parent): + """CivilizationIV.ini's settings the original sets only in its ini (see _INI_FLAGS).""" + self.attachHSeparator(parent, 'Oc4IniSeparator') + self.attachLabel(parent, 'Oc4IniLabel', u'From CivilizationIV.ini') + for name, key, text, tip in ( + (NO_TECH_SPLASH_CHECKBOX, 'noTechSplash', u'No tech splash screens', + u'A new technology is not shown on its own screen with its quote (the ini\'s NoTechSplash).'), + (NO_EVENT_MESSAGES_CHECKBOX, 'noEventMessages', u'No event messages on the screen', + u'The messages are not shown at the top of the map; they are still in the turn log (Ctrl+Tab) and ' + u'their sounds play (the ini\'s NoEventMessages).')): + self.attachCheckBox(parent, name, text, 'oc4options', 'handleIniFlagClicked', key, _profile[key]) + self.setToolTip(name, tip) + for key, before, after, tip in ( + ('autoSaveInterval', u'Autosave every', u'turns (0: never)', + u'The game is saved at the start of every this many turns, and at its first, into Saves\\single\\auto ' + u'(the ini\'s AutoSaveInterval, 4).'), + ('autoSavesKept', u'Keep', u'autosaves', + u'The oldest autosaves beyond this many are deleted (the ini\'s MaxAutoSaves, 5).')): + self._attachNumber(parent, key, before, after, tip) + self.attachCheckBox(parent, OPENCIV4_AUTOSAVES_CHECKBOX, u'OpenCiv4\'s autosaves: each game its own, every 25th turn kept', + 'oc4options', 'handleIniFlagClicked', 'openciv4AutoSaves', _profile['openciv4AutoSaves']) + self.setToolTip(OPENCIV4_AUTOSAVES_CHECKBOX, u'Autosaves go to My Games\\openciv4\\Saves\\auto, named by the civilization ' + u'and the map, the kept ones in turn, and every 25th turn\'s is kept for good. Autosave every 1 turn and keep 10 ' + u'is how OpenCiv4 saved before.') + for key, before, after, tip in ( + ('fieldOfView', u'Field of view', u'degrees (0: the game\'s, 42)', + u'How wide the camera sees; more shows more of the map at once (the ini\'s FIELD_OF_VIEW). BUG\'s slider ' + u'on the map changes it too.'), + ('maxFrameRate', u'At most', u'frames a second (0: no limit)', + u'Fewer frames save battery (the ini\'s SetMaxFrameRate).')): + self._attachNumber(parent, key, before, after, tip) + + def _attachNumber(self, parent, key, before, after, tip): + row = 'Oc4Row' + key + self.attachHBox(parent, row) + self.attachLabel(row, row + 'Before', before) + name = 'Oc4Edit' + key + self.attachEdit(row, name, str(_profile[key]), 'oc4options', 'handleIniNumberTyped', key) + self._byName[name].flags.add('OC4_DIGITS') + self.setToolTip(name, tip) + self.attachLabel(row, row + 'After', after) def attachVBox(self, parent, name): self._node('vbox', parent, name) def attachHBox(self, parent, name): @@ -717,6 +845,8 @@ def _natural(n): return max([_width(i) for i in n.items] or [40]) + 36 if k in ('spacer', 'vsep'): return 12 + if k == 'edit' and 'OC4_DIGITS' in n.flags: + return 64 if k in ('vbox', 'scroll', 'panel'): widths = [_natural(c) for c in n.children] if None in widths: @@ -825,6 +955,9 @@ def _place(screen, n, x, y, w, h): elif k == 'edit': screen.addEditBoxGFC(name, x, y, min(w, 260), 24, general, -1, -1, font) screen.setEditBoxString(name, n.text) + if 'OC4_DIGITS' in n.flags: # (a number box: digits only) + screen.setEditBoxCharacters(name, u'0123456789') + screen.setEditBoxMaxCharCount(name, 4) elif k == 'dropdown': dw = min(w, 260) if 'LAYOUT_RIGHT' in n.flags: @@ -1002,6 +1135,7 @@ def _toggleAlarm(bOn, iHour=0, iMin=0): _cpe.CyGTabCtrl = CyGTabCtrl _cpe.CyUserProfile = _UserProfile oc4screens.beforeDisplay.append(relayout) +oc4screens.editTyped.append(_editTyped) _load() _applyVolumes() _applyGraphics() diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 6307dbdf..37049391 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -39,6 +39,7 @@ def _changed(): _version[0] += 1 +editTyped = [] # (called with an edit box after keys were typed into it: oc4options keeps its numbers) beforeDisplay = [] # (called before the display list is made: oc4options lays its window out) @@ -1891,6 +1892,12 @@ def typeIntoEdit(text): value += c _set(w, 'text', value) _changed() + for f in editTyped: + try: + f(w) + except Exception: + import traceback + traceback.print_exc() def closeDropdown(): diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index f50b1509..0722d234 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -210,6 +211,8 @@ namespace oc4::render std::function popupHelp; bool busy = false; // the game runs on another thread: nothing asked of it bool edgeScroll = false; + int maxFrameRate = 0; // (0: no cap) + std::chrono::steady_clock::time_point nextFrame{}; std::function uiWheel; // the screens' (a table or list scrolled) bool downOnPopup = false; UiLayer ui; @@ -2229,6 +2232,15 @@ namespace oc4::render m.view->update(dt); render(); renderer->present(); + // (a frame cap: the next frame no sooner than its share of the second after this one) + if (maxFrameRate > 0) + { + const auto period = std::chrono::nanoseconds(1'000'000'000LL / maxFrameRate); + const auto done = std::chrono::steady_clock::now(); + if (done < nextFrame) + std::this_thread::sleep_until(nextFrame); + nextFrame = std::max(nextFrame, done - period) + period; + } } float windowDensity() const { return window ? SDL_GetWindowPixelDensity(window) : 1; } @@ -2562,6 +2574,7 @@ namespace oc4::render m->askPlotHelp(); } void MapWindow::setEdgeScroll(bool on) { m->edgeScroll = on; } + void MapWindow::setMaxFrameRate(int fps) { m->maxFrameRate = std::clamp(fps, 0, 1000); } void MapWindow::setSoundHandler(std::function handler) { if (m->view) diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 8603ffbd..9115e4ba 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -180,6 +180,8 @@ namespace oc4::render void askHelp(); // The mouse at the window's edge scrolls the map (off for scripted runs). void setEdgeScroll(bool on); + // At most this many frames a second (CivilizationIV.ini's SetMaxFrameRate; 0: no cap). + void setMaxFrameRate(int fps); // Each terrain's colour on the minimap (BGRA8), by terrain type; empty before the first map. std::vector terrainColors() const; // The sounds the units' animations call for (an audio script's tag, where: plot units). diff --git a/tests/auto_saves_test.cpp b/tests/auto_saves_test.cpp new file mode 100644 index 00000000..73fe676f --- /dev/null +++ b/tests/auto_saves_test.cpp @@ -0,0 +1,73 @@ +// Checks the autosaves' rules (apps/oc4core/AutoSaves.h), as the running original showed them with +// CivilizationIV.ini's AutoSaveInterval and MaxAutoSaves: when, the file names, and which old +// ones go; and openciv4's own names. + +#include "AutoSaves.h" + +#include +#include + +using namespace oc4::host; +namespace fs = std::filesystem; + +namespace +{ + int failures = 0; + + void check(bool ok, const char* what) + { + if (!ok) + { + std::printf("FAILED: %s\n", what); + ++failures; + } + } +} + +int main() +{ + // When: the game's first turn, then every interval's; none with 0. + const AutoSaveSettings ini; // (4, 5) + check(autoSaveDue(ini, 0, true), "the game's first turn"); + check(!autoSaveDue(ini, 1, false) && !autoSaveDue(ini, 3, false) && autoSaveDue(ini, 4, false) && autoSaveDue(ini, 8, false), "every 4th turn"); + check(autoSaveDue({ 1, 10 }, 7, false), "every turn"); + check(!autoSaveDue({ 0, 5 }, 0, true) && !autoSaveDue({ 0, 5 }, 4, false), "interval 0: none, the first neither"); + + // The names: the year as the original writes it. + check(autoSaveName(true, -4000) == L"AutoSave_Initial_BC-4000.CivBeyondSwordSave", "the initial save's name"); + check(autoSaveName(false, -3840) == L"AutoSave_BC-3840.CivBeyondSwordSave", "a BC year"); + check(autoSaveName(false, 1250) == L"AutoSave_AD-1250.CivBeyondSwordSave", "an AD year (not seen: written as a BC one)"); + + // openciv4's own: the kept ones in turn (every turn, 10 kept: as before the option). + check(openciv4AutoSaveName(L"AutoSave_Rome_1", { 1, 10, true }, 23) == L"AutoSave_Rome_1_3.CivBeyondSwordSave", "openciv4's, slot 3"); + check(openciv4AutoSaveName(L"AutoSave_Rome_1", { 4, 5, true }, 24) == L"AutoSave_Rome_1_1.CivBeyondSwordSave", "openciv4's, every 4th, 5 kept"); + + // The oldest AutoSave_ beyond the kept go; the initial save and other files stay (as seen: + // with 3 kept, the 4th AutoSave_ takes the oldest, AutoSave_Initial_ stays). + const fs::path folder = fs::temp_directory_path() / "oc4_auto_saves_test"; + fs::remove_all(folder); + fs::create_directories(folder); + const auto now = fs::file_time_type::clock::now(); + const wchar_t* names[] = { L"AutoSave_Initial_BC-4000.CivBeyondSwordSave", L"AutoSave_BC-3840.CivBeyondSwordSave", + L"AutoSave_BC-3680.CivBeyondSwordSave", L"AutoSave_BC-3520.CivBeyondSwordSave" }; + for (int i = 0; i < 4; ++i) + { + std::ofstream(folder / names[i]) << i; + fs::last_write_time(folder / names[i], now - std::chrono::hours(4 - i)); + } + std::ofstream(folder / L"Mine.CivBeyondSwordSave") << 9; + fs::last_write_time(folder / L"Mine.CivBeyondSwordSave", now - std::chrono::hours(9)); + const std::vector beyond = autoSavesBeyond(folder, 2); + check(beyond.size() == 1 && beyond[0].filename() == names[1], "the oldest AutoSave_ beyond the two kept"); + check(autoSavesBeyond(folder, 3).empty(), "three kept: none to go, the initial save not counted"); + check(autoSavesBeyond(folder, 1).size() == 2, "one kept: the two older go, not the initial one nor the player's"); + fs::remove_all(folder); + + if (failures) + { + std::printf("auto_saves_test: %d failed\n", failures); + return 1; + } + std::printf("auto_saves_test: all passed\n"); + return 0; +} diff --git a/tests/ini_options_test.py b/tests/ini_options_test.py new file mode 100644 index 00000000..170f9ed8 --- /dev/null +++ b/tests/ini_options_test.py @@ -0,0 +1,92 @@ +# Checks the options screen's OpenCiv4 tab for CivilizationIV.ini's settings the original sets only +# in its ini (apps/oc4core/python/oc4options.py): NoTechSplash, NoEventMessages, AutoSaveInterval, +# MaxAutoSaves (and openciv4's own autosaves), FIELD_OF_VIEW, SetMaxFrameRate. Their defaults are +# the ini's, a choice goes to the host and into profile.ini at once, and a restart reads it back. +# +# oc4options runs with player_options_test's stand-ins for the host and the modules it imports. +# python3 ini_options_test.py + +import os +import shutil +import sys +import tempfile + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import player_options_test as po + +check = po.check + + +def start(folder): + host, options = po.start(folder) + host.ini = None + host.set_ini_options = lambda *args: setattr(host, 'ini', args) + defines = {'FIELD_OF_VIEW': 42.0} + context = sys.modules['CvPythonExtensions'].CyGlobalContext + context.getDefineFLOAT = lambda self, name: defines.get(name, 0.0) + context.setDefineFLOAT = lambda self, name, value: defines.__setitem__(name, value) + options._applyIniOptions() + return host, options, defines + + +def typed(options, ctrl, key, text): + """Typed into the number box of the profile's key, as oc4screens tells after the keys.""" + n = ctrl._byName['Oc4Edit' + key] + + class Box(object): + pass + w = Box() + w.name, w.text = 'OptW%d' % n.id, text + options._editTyped(w) + + +def main(): + sys.path.insert(0, sys.argv[1]) + folder = tempfile.mkdtemp() + try: + # No profile: the ini's defaults. + host, options, defines = start(folder) + check(host.ini == (False, False, 4, 5, False, 0), "defaults to the host: %s" % (host.ini,)) + check(defines['FIELD_OF_VIEW'] == 42.0, "the XML's field of view kept") + ctrl = po.optionsScreen(options) + edits = sorted(n.name for n in ctrl._nodes.values() if n.kind == 'edit') + check(edits == sorted('Oc4Edit' + k for k in ('autoSaveInterval', 'autoSavesKept', 'fieldOfView', 'maxFrameRate')), "number boxes: %s" % edits) + check(ctrl._byName['Oc4EditautoSaveInterval'].text == u'4', "the interval box shows 4") + + # Chosen: both check boxes, an autosave every turn, 10 kept, openciv4's, field of view 60, 30 frames. + po.click(options, ctrl, options.NO_TECH_SPLASH_CHECKBOX) + po.click(options, ctrl, options.NO_EVENT_MESSAGES_CHECKBOX) + po.click(options, ctrl, options.OPENCIV4_AUTOSAVES_CHECKBOX) + typed(options, ctrl, 'autoSaveInterval', u'1') + typed(options, ctrl, 'autoSavesKept', u'10') + typed(options, ctrl, 'fieldOfView', u'60') + typed(options, ctrl, 'maxFrameRate', u'3x0') # (digits only) + check(host.ini == (True, True, 1, 10, True, 30), "chosen, to the host: %s" % (host.ini,)) + check(defines['FIELD_OF_VIEW'] == 60.0, "the field of view replaced: %s" % defines['FIELD_OF_VIEW']) + lines = po.profileLines(folder) + check({'noTechSplash=1', 'noEventMessages=1', 'openciv4AutoSaves=1', 'autoSaveInterval=1', 'autoSavesKept=10', + 'fieldOfView=60', 'maxFrameRate=30'} <= lines, "in profile.ini at once: %s" % sorted(lines)) + + # A restart: the profile's again. + host, options, defines = start(folder) + check(host.ini == (True, True, 1, 10, True, 30), "after a restart: %s" % (host.ini,)) + check(defines['FIELD_OF_VIEW'] == 60.0, "after a restart, the field of view: %s" % defines['FIELD_OF_VIEW']) + + # An empty box is 0: no autosaves; the field of view the XML's again. + ctrl = po.optionsScreen(options) + typed(options, ctrl, 'autoSaveInterval', u'') + typed(options, ctrl, 'fieldOfView', u'0') + check(host.ini[2] == 0, "an empty interval: none (%s)" % (host.ini,)) + check(defines['FIELD_OF_VIEW'] == 42.0, "field of view 0: the XML's again (%s)" % defines['FIELD_OF_VIEW']) + finally: + shutil.rmtree(folder, ignore_errors=True) + + if po.failures: + print("ini_options_test: %d failed" % len(po.failures)) + return 1 + print("ini_options_test: all passed") + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/player_options_test.py b/tests/player_options_test.py index c13debbc..5a165b66 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -91,6 +91,7 @@ def start(folder): sys.modules['CvPythonExtensions'] = cpe(host) screens = Anything('oc4screens') screens.beforeDisplay = [] + screens.editTyped = [] screens._text = lambda s: u"%s" % (s,) sys.modules['oc4screens'] = screens # (the game's callbacks module: CvOptionsScreenCallbackInterface.handleGameOptionsClicked) @@ -146,7 +147,8 @@ def main(): ctrl = optionsScreen(options) check([label for form, label in ctrl._tabs] == ['Game', 'Graphics', 'Audio', 'Other', 'OpenCiv4'], "tabs: %s" % [l for f, l in ctrl._tabs]) oc4 = [n.name for n in ctrl._nodes.values() if n.kind == 'checkbox' and n.name.startswith('Oc4')] - check(sorted(oc4) == sorted([options.WASD_PAN_CHECKBOX, options.AUTO_END_TURN_CHECKBOX, options.EDGE_SCROLL_CHECKBOX]), "OpenCiv4's options: %s" % oc4) + check(sorted(oc4) == sorted([options.WASD_PAN_CHECKBOX, options.AUTO_END_TURN_CHECKBOX, options.EDGE_SCROLL_CHECKBOX, + options.NO_TECH_SPLASH_CHECKBOX, options.NO_EVENT_MESSAGES_CHECKBOX, options.OPENCIV4_AUTOSAVES_CHECKBOX]), "OpenCiv4's options: %s" % oc4) game = [n.name for n in ctrl._byName['GamePanelCenter'].children] check(game == ['GameOptionCheckBox_2', 'GameOptionCheckBox_6', 'LangHBox'], "the Game tab has only the game's: %s" % game) From ab18f1d7777d54c0653240ea4e83a8bbd7144eb1 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 06:49:50 +0100 Subject: [PATCH 57/89] Options: the field of view set once a game has started (no defines before) Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 2 +- apps/oc4core/python/oc4options.py | 23 +++++++++++++++-------- tests/ini_options_test.py | 4 +++- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index b405b320..69cfdbf8 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -733,7 +733,7 @@ if _walls: m_utility.gameInterface().makeInterfaceDirty(); m_utility.gameInterface().techSplash = true; // (the profile's field of view, CivilizationIV.ini's FIELD_OF_VIEW, over GlobalDefines.xml's) - py::module_::import("oc4options").attr("applyFieldOfView")(); // (its own errors its own) + py::module_::import("oc4options").attr("gameStarted")(); // (its own errors its own) m_active = true; m_laidOut = m_seenSize = { width, height }; } diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index a713f1f4..d7d2c496 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -267,21 +267,28 @@ def _applyIniOptions(): _profile['autoSavesKept'], _profile['openciv4AutoSaves'], _profile['maxFrameRate']) except Exception: pass - applyFieldOfView() + if _gameStarted[0]: + _applyFieldOfView() -def applyFieldOfView(): - """FIELD_OF_VIEW: a non-zero one replaces GlobalDefines.xml's, as the ini's does (the host - calls this as a game starts; BUG's slider on the map may change it again later).""" +_gameStarted = [False] # (before, the game core has no defines to read) + + +def gameStarted(): + """The host: a game has started (GlobalDefines.xml read); the profile's field of view now.""" + _gameStarted[0] = True + _applyFieldOfView() + + +def _applyFieldOfView(): + """FIELD_OF_VIEW: a non-zero one replaces GlobalDefines.xml's, as the ini's does (BUG's slider + on the map may change it again later).""" try: gc = _cpe.CyGlobalContext() fov = _profile['fieldOfView'] if fov > 0: if _xmlFieldOfView[0] is None: - xml = gc.getDefineFLOAT('FIELD_OF_VIEW') - if xml <= 0: - return # (GlobalDefines.xml not read yet: the game's start sets it) - _xmlFieldOfView[0] = xml + _xmlFieldOfView[0] = gc.getDefineFLOAT('FIELD_OF_VIEW') gc.setDefineFLOAT('FIELD_OF_VIEW', float(fov)) elif _xmlFieldOfView[0] is not None: gc.setDefineFLOAT('FIELD_OF_VIEW', float(_xmlFieldOfView[0])) diff --git a/tests/ini_options_test.py b/tests/ini_options_test.py index 170f9ed8..d5e5f98f 100644 --- a/tests/ini_options_test.py +++ b/tests/ini_options_test.py @@ -25,7 +25,9 @@ def start(folder): context = sys.modules['CvPythonExtensions'].CyGlobalContext context.getDefineFLOAT = lambda self, name: defines.get(name, 0.0) context.setDefineFLOAT = lambda self, name, value: defines.__setitem__(name, value) - options._applyIniOptions() + options._applyIniOptions() # (as at the program's start, the host's stand-in in place now) + check(host.ini is not None and defines['FIELD_OF_VIEW'] == 42.0, "before a game: the host has them, the defines untouched") + options.gameStarted() return host, options, defines From 98cb2d6879f7b86aea8937b36767a4ccfe8ba909 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 06:53:29 +0100 Subject: [PATCH 58/89] Options: the edit box hook optional (other tests' stand-ins for oc4screens have none) Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 3 ++- tests/ini_options_test.py | 11 ++++++++++- tests/player_options_test.py | 1 - 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index d7d2c496..776c6dd6 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -1142,7 +1142,8 @@ def _toggleAlarm(bOn, iHour=0, iMin=0): _cpe.CyGTabCtrl = CyGTabCtrl _cpe.CyUserProfile = _UserProfile oc4screens.beforeDisplay.append(relayout) -oc4screens.editTyped.append(_editTyped) +if isinstance(getattr(oc4screens, 'editTyped', None), list): # (a test's stand-in may not have it) + oc4screens.editTyped.append(_editTyped) _load() _applyVolumes() _applyGraphics() diff --git a/tests/ini_options_test.py b/tests/ini_options_test.py index d5e5f98f..b8b2fd6c 100644 --- a/tests/ini_options_test.py +++ b/tests/ini_options_test.py @@ -18,7 +18,16 @@ def start(folder): - host, options = po.start(folder) + # (oc4screens' hook for typing into an edit box, in player_options_test's stand-in) + real = po.Anything + class Screens(real): + pass + po.Anything = Screens + Screens.editTyped = [] + try: + host, options = po.start(folder) + finally: + po.Anything = real host.ini = None host.set_ini_options = lambda *args: setattr(host, 'ini', args) defines = {'FIELD_OF_VIEW': 42.0} diff --git a/tests/player_options_test.py b/tests/player_options_test.py index 5a165b66..97d0fd83 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -91,7 +91,6 @@ def start(folder): sys.modules['CvPythonExtensions'] = cpe(host) screens = Anything('oc4screens') screens.beforeDisplay = [] - screens.editTyped = [] screens._text = lambda s: u"%s" % (s,) sys.modules['oc4screens'] = screens # (the game's callbacks module: CvOptionsScreenCallbackInterface.handleGameOptionsClicked) From d14b27f4ab9f08a3dd6757be0d5b072d621f56b0 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 07:37:28 +0100 Subject: [PATCH 59/89] Autosaves: the year from CyGame (Windows: the game core does not export getGameTurnYear) Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index c2d4fbdc..ad5799e0 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -858,7 +858,14 @@ namespace return; } const fs::path folder = documentsFolder() / L"My Games" / L"Beyond the Sword" / L"Saves" / L"single" / L"auto"; - save(folder, folder / host::autoSaveName(initial, game.getGameTurnYear())); + // (the year through the scripts' CyGame: the game core does not export getGameTurnYear) + int year; + { + namespace py = pybind11; + py::gil_scoped_acquire gil; + year = py::module_::import("CvPythonExtensions").attr("CyGame")().attr("getGameTurnYear")().cast(); + } + save(folder, folder / host::autoSaveName(initial, year)); for (const fs::path& old : host::autoSavesBeyond(folder, how.kept)) fs::remove(old); } From 1420f644ba5f00a07a817c6bdb663ce9b511da62 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 16:36:47 +0100 Subject: [PATCH 60/89] Bundle: the options PRs together, as tested on the play branch - Quick enemy moves (#137) also speeds the others' walk from #127 to 0.5 s, so each walk ends before the next shown move. - oc4options.py: profile.ini keeps every OpenCiv4 option (#120's ini settings and #137's quickEnemyMoves in _GLOBAL); greyed controls use the node's 'disabled' (#132) where #118 had 'enabled'; _GREY defined once. - minimap_toggles_test.py: reads the loaded profile's own file (#118's Profiles/.ini) as well. - player_options_test.py: the OpenCiv4 tab's options as the bundle has them (#113's single-click city and #130's keep-the-attacker checkboxes in the list). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Interface.cpp | 13 ++++++++++++- apps/oc4core/Interface.h | 2 ++ apps/oc4core/main.cpp | 1 + apps/oc4core/python/oc4options.py | 23 ++++++++++------------- tests/minimap_toggles_test.py | 14 +++++++++++--- tests/player_options_test.py | 22 ++++++++++++++++++++-- 6 files changed, 56 insertions(+), 19 deletions(-) diff --git a/apps/oc4core/Interface.cpp b/apps/oc4core/Interface.cpp index fc205310..f1dec733 100644 --- a/apps/oc4core/Interface.cpp +++ b/apps/oc4core/Interface.cpp @@ -448,6 +448,16 @@ namespace oc4::host m.plots.erase(m.plots.begin(), m.plots.end() - 32); } + namespace + { + std::atomic g_quickShownMoves{ false }; + } + + void Entities::setQuickShownMoves(bool on) + { + g_quickShownMoves = on; + } + void Entities::ExecuteMove(CvUnitEntity* pEntity, float, bool bCombat) { // CvSelectionGroup::groupMove's, once the group's moves this update are done: the original @@ -458,7 +468,8 @@ namespace oc4::host if (!unit || bCombat || unit->getOwner() < 0) return; const CvPlayer& owner = CvPlayerAI::getPlayerNonInl(unit->getOwner()); // (exported: GET_PLAYER inlines a static the Windows DLL does not export) - const float seconds = owner.isHuman() && owner.isOption(PLAYEROPTION_QUICK_MOVES) ? 0.5f : 1.0f; + // (the others' with OpenCiv4's Quick enemy moves too: their walk ends before the next shown move) + const float seconds = (owner.isHuman() && owner.isOption(PLAYEROPTION_QUICK_MOVES)) || (!owner.isHuman() && g_quickShownMoves) ? 0.5f : 1.0f; std::lock_guard lock(g_movementMutex); if (const auto it = g_movements.find(movementKey(unit->getIDInfo())); it != g_movements.end()) it->second.seconds = seconds; diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index fdbc171e..38586823 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -493,6 +493,8 @@ namespace oc4::host // While one is on the game is updated once a battle slice, as its animation goes: // true while it is not yet time for the next update (false: go, counted). static bool battleWait(); + // OpenCiv4's option Quick enemy moves (the main loop's): the others' walks in half the time. + static void setQuickShownMoves(bool on); private: const Interface& m_selection; diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 63e2bfd0..84c669f9 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1747,6 +1747,7 @@ namespace { window.setBusy(true); const auto slice = utility.quickEnemyMoves() ? kQuickShownMoveSlice : kShownMoveSlice; + host::Entities::setQuickShownMoves(utility.quickEnemyMoves()); worker.start([&session, &game, &nextShownMoveUpdate, slice] { const auto until = Clock::now() + std::chrono::milliseconds(100); do diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 6d7f7109..0df5d98f 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -108,7 +108,7 @@ def _path(): # the minimap's toggles). profile.ini keeps the rest, the same whichever profile is loaded: # UserProfile= and OpenCiv4's own options (the keys in _GLOBAL; the ini's settings too). A # profile.ini from before (every option in it) is the profile "openciv4"'s first file. -_GLOBAL = ('UserProfile', 'wasdPan', 'autoEndTurn', 'edgeScroll', 'cityOneClick', 'keepAttacker') +_GLOBAL = ('UserProfile', 'wasdPan', 'autoEndTurn', 'edgeScroll', 'cityOneClick', 'keepAttacker', 'quickEnemyMoves') + _INI_FLAGS + tuple(k for k, v in _INI_NUMBERS) _DEFAULT_NAME = 'openciv4' _BAD = '\\/:*?"<>|' @@ -648,9 +648,6 @@ def _applyVolumes(): pass -_names = [] # (the profiles listed, loadProfileFileNames) -_clock = {'justOn': False} - _deviceCache = {} @@ -685,6 +682,10 @@ def folderChosen(path): _applyVolumes() +_names = [] # (the profiles listed, loadProfileFileNames) +_clock = {'justOn': False} + + class _UserProfile(object): """CyUserProfile: the player's options (one profile, the host's file).""" @@ -693,7 +694,6 @@ def __getattr__(self, name): raise AttributeError(name) return lambda *args, **kwargs: 0 - # the profile itself # the profiles (Profiles/.ini): the Other tab's list, Create New Profile, Delete Profile def getProfileName(self): return _profile['name'] def setProfileName(self, s): _profile['name'] = str(s) @@ -957,7 +957,7 @@ def _node(self, kind, parent, name): n = _Node(self._next, kind, str(name)) # (the original's options OpenCiv4 does not do: greyed, with a tool tip saying so) if n.name in _notDone(): - n.enabled, n.tip = False, _NOT_DONE_TIP + n.disabled, n.tip = True, _NOT_DONE_TIP self._next += 1 self._nodes[n.id] = n self._byName[n.name] = n @@ -983,8 +983,8 @@ def attachTabItem(self, szName, szLabel): def _attachOpenCiv4Tab(self): """OpenCiv4's options, none of the original's: W A S D panning, ending idle turns, edge - scrolling, quicker shown moves of the others (kept in the profile as wasdPan, autoEndTurn, edgeScroll, - quickEnemyMoves).""" + scrolling, opening a city with one click, keeping the camera on an attacker (kept in the profile as + wasdPan, autoEndTurn, edgeScroll, cityOneClick, keepAttacker).""" self.attachTabItem(OC4_FORM, u'OpenCiv4') self.attachVBox(OC4_FORM, 'Oc4VBox') parent = 'Oc4Panel' @@ -1361,7 +1361,7 @@ def _place(screen, n, x, y, w, h): cy += ch + _GAP return # (a control OpenCiv4 does not do: greyed, takes no clicks, its tool tip says why) - grey, ungrey = (_GREY, u'') if not n.enabled else (u'', u'') + grey, ungrey = (_GREY, u'') if n.disabled else (u'', u'') if k == 'label': screen.setLabel(name, 'Background', _FONT + grey + n.text + ungrey + u'', 1 << 0, x, y + 4, 0, font, general, -1, -1) if n.tip: @@ -1399,7 +1399,7 @@ def _place(screen, n, x, y, w, h): screen.addPullDownString(name, item, i, i, i == int(n.value)) if n.tip: _tip(screen, name, n.tip) - if not n.enabled: + if n.disabled: screen.enable(name, False) elif k in ('hslider', 'vslider'): # (the theme's slider: its fill on the side its control flag names, CF_SLIDER_FILL_UP / _DOWN) @@ -1415,9 +1415,6 @@ def _place(screen, n, x, y, w, h): w_.enabled, w_.help = False, _VOICE_TIP -_GREY = u'' - - def _tip(screen, name, text): w = screen._s.get(name) if w is not None: diff --git a/tests/minimap_toggles_test.py b/tests/minimap_toggles_test.py index d1c09a55..64e5f3f1 100644 --- a/tests/minimap_toggles_test.py +++ b/tests/minimap_toggles_test.py @@ -75,8 +75,15 @@ def start(folder): def profileLines(folder): + """profile.ini's lines and the loaded profile's (Profiles/.ini, fix/options-other).""" with open(os.path.join(folder, 'profile.ini')) as f: - return set(f.read().split()) + lines = set(f.read().split()) + name = [l.split('=', 1)[1] for l in lines if l.startswith('UserProfile=')] + own = os.path.join(folder, 'Profiles', (name[0] if name else 'openciv4') + '.ini') + if os.path.isfile(own): + with open(own) as f: + lines |= set(f.read().split()) + return lines def main(): @@ -109,13 +116,14 @@ def main(): host.control(1) host.control(0) host.toggles = [False, False, False, True] # (the host's own start, say a new game) - options._UserProfile().readFromFile('') + options._UserProfile().readFromFile('openciv4') check(host.toggles == [False, True, True, False], "readFromFile gives the host the profile's toggles (%s)" % host.toggles) # The other options are kept beside them. check({'scores=0', 'edgeScroll=1'} <= profileLines(folder), "the rest of the profile is kept") - # A profile written before this change (no toggle keys): the defaults. + # A profile written before this change (no toggle keys, no profiles folder): the defaults. + shutil.rmtree(os.path.join(folder, 'Profiles'), ignore_errors=True) with open(os.path.join(folder, 'profile.ini'), 'w') as f: f.write('name=openciv4\nclock=1\n') host, options = start(folder) diff --git a/tests/player_options_test.py b/tests/player_options_test.py index c2148468..fee22571 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -43,6 +43,13 @@ def __init__(self, path): self.path = path self.states = [0] * 64 self.player = {} # (the active player's options, as sendPlayerOption sets them) + self.cityOneClick = False + + def set_city_one_click(self, on): + self.cityOneClick = bool(on) + + def city_one_click(self): + return self.cityOneClick def profile_path(self): return self.path @@ -153,12 +160,23 @@ def main(): ctrl = optionsScreen(options) check([label for form, label in ctrl._tabs] == ['Game', 'Graphics', 'Audio', 'Other', 'OpenCiv4'], "tabs: %s" % [l for f, l in ctrl._tabs]) oc4 = [n.name for n in ctrl._nodes.values() if n.kind == 'checkbox' and n.name.startswith('Oc4')] - check(sorted(oc4) == sorted([options.WASD_PAN_CHECKBOX, options.AUTO_END_TURN_CHECKBOX, options.EDGE_SCROLL_CHECKBOX, - options.NO_TECH_SPLASH_CHECKBOX, options.NO_EVENT_MESSAGES_CHECKBOX, options.OPENCIV4_AUTOSAVES_CHECKBOX, + check(sorted(oc4) == sorted([options.WASD_PAN_CHECKBOX, options.AUTO_END_TURN_CHECKBOX, options.EDGE_SCROLL_CHECKBOX, options.CITY_ONE_CLICK_CHECKBOX, + options.KEEP_ATTACKER_CHECKBOX, options.NO_TECH_SPLASH_CHECKBOX, options.NO_EVENT_MESSAGES_CHECKBOX, options.OPENCIV4_AUTOSAVES_CHECKBOX, options.QUICK_ENEMY_MOVES_CHECKBOX]), "OpenCiv4's options: %s" % oc4) game = [n.name for n in ctrl._byName['GamePanelCenter'].children] check(game == ['GameOptionCheckBox_2', 'GameOptionCheckBox_6', 'LangHBox'], "the Game tab has only the game's: %s" % game) + # Opening a city with one click: off (the original's double click), kept when chosen. + check(ctrl._byName[options.CITY_ONE_CLICK_CHECKBOX].value is False and not host.cityOneClick, "one click on a city: off by default") + click(options, ctrl, options.CITY_ONE_CLICK_CHECKBOX) + check(host.cityOneClick and 'cityOneClick=1' in profileLines(folder), "one click on a city: on, in profile.ini") + host, options = start(folder) + check(host.cityOneClick, "one click on a city: the profile's after a restart") + click(options, optionsScreen(options), options.CITY_ONE_CLICK_CHECKBOX) + check(not host.cityOneClick and 'cityOneClick=0' in profileLines(folder), "one click on a city: off again") + ctrl = optionsScreen(options) + profile = options._UserProfile() + # Wait at End of Turn off, Quick Moves on: sent to the player and kept at once. click(options, ctrl, 'GameOptionCheckBox_2') click(options, ctrl, 'GameOptionCheckBox_6') From b6b630341ddf10779400fdfe5e9dcf2bb0ed9d7e Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sun, 22 Nov 2026 11:10:05 +0100 Subject: [PATCH 61/89] Options screens: a scroll panel clips what it holds and scrolls it BUG's options tabs (City Screen, Advisors) ran past the bottom of their window: the tab control's scroll panel (attachScrollPanel) was laid out as high as what it held. It now takes the height its window leaves it, as the original's, and its controls go into a scroll panel there: clipped to it, scrolled by the wheel and the scroll bar on its right, which shows only when they are longer (measured in Wine: the bar over the tan panel's right edge, the panel as wide as without it). How far it is scrolled is kept when the screen is laid out again after a click. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 41 ++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 0df5d98f..f4a413ba 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -898,13 +898,14 @@ def setNo(self, b, v=v): # ---------------------------------------------------------------- the tab control class _Node(object): - __slots__ = ('id', 'kind', 'name', 'children', 'text', 'value', 'items', 'callback', 'flags', 'style', 'minimum', 'maximum', 'tip', 'disabled') + __slots__ = ('id', 'kind', 'name', 'children', 'text', 'value', 'items', 'callback', 'flags', 'style', 'minimum', 'maximum', 'tip', 'disabled', 'offset', 'inside') def __init__(self, id, kind, name): self.id, self.kind, self.name = id, kind, name self.children, self.text, self.value, self.items, self.callback = [], u'', 0, (), None self.flags, self.style, self.minimum, self.maximum, self.tip = set(), '', 0, 0, u'' self.disabled = False + self.offset, self.inside = 0, False # (a scroll panel: how far it is scrolled; being laid out inside) _state = {'ctrl': None, 'dirty': False} @@ -1283,6 +1284,8 @@ def _height(n, w): return max([_height(c, cw) for c, cw in zip(n.children, widths)] or [0]) if k == 'panel' and not n.children: return 0 # (an empty one: the resolution's screen picture, none here) + if k == 'scroll' and not n.inside: + return 0 # (a scroll panel: what its box is given, its content scrolls in it) px, py = _pad(n) inner = w - 2 * px h = sum(_height(c, inner) for c in n.children) + _GAP * max(0, len(n.children) - 1) @@ -1339,6 +1342,9 @@ def _place(screen, n, x, y, w, h): _place(screen, c, cx, y, cw, h if _vgrow(c) else _height(c, cw)) cx += cw + _GAP return + if k == 'scroll' and not n.inside: + _scrollPanel(screen, n, name, x, y, w, h) + return if k in ('vbox', 'form', 'panel', 'scroll'): px, py = _pad(n) if k == 'panel' and h > 0: @@ -1415,6 +1421,34 @@ def _place(screen, n, x, y, w, h): w_.enabled, w_.help = False, _VOICE_TIP +def _scrollPanel(screen, n, name, x, y, w, h): + """A scroll panel (attachScrollPanel): what it holds clipped to its box and, when longer, + scrolled there by the wheel and the scroll bar on its right, as the original's (BUG's City + Screen and Advisors tabs; the bar over the right edge of the tan panel, which keeps its width). + Its controls are placed as usual, then moved into an engine scroll panel at the same place.""" + screen.addScrollPanel(name, u'', x, y, w, h, _cpe.PanelStyles.PANEL_STYLE_EMPTY) + panel = screen._s.get(name) + if panel is None: + return + panel.inset = 0 + # (where it was scrolled to: the screen is laid out again after every click) + panel.offset = n.offset + first = len(screen._s.order) + n.inside = True + try: + _place(screen, n, x, y, w, h) + finally: + n.inside = False + for c in screen._s.order[first:]: + cw = screen._s.widgets.get(c) + if cw is None: + continue + cw.parent, cw.mode = name, 'rel' + cw.x, cw.y = cw.x - x, cw.y - y + panel.children.append(c) + del screen._s.order[first:] + + def _tip(screen, name, text): w = screen._s.get(name) if w is not None: @@ -1436,6 +1470,11 @@ def relayout(): if ctrl is not None: # (what was typed into the edit boxes stays: they are made again) for n in ctrl._nodes.values(): + if n.kind == 'scroll': + # (and how far each scroll panel was scrolled) + w_ = _screen()._s.get('OptW%d' % n.id) + if w_ is not None: + n.offset = w_.offset if n.kind == 'edit': w_ = _screen()._s.get('OptW%d' % n.id) if w_ is not None: From 861e5a8c63561098ae6e96a56e4f14a6979db623 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sun, 22 Nov 2026 11:16:27 +0100 Subject: [PATCH 62/89] Options screens: nested scroll panels keep their height; an edit box no longer clips what follows The Audio tab's volume sliders lie in a scroll panel inside the tab's: one inside another is as high as what it holds. An edit box in a clipped panel pushed its clip twice and took one off, so everything drawn after it was cut to the edit box (the Options screen's Other tab showed its clock column only, the Audio tab lost Restore Defaults and Exit). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 10 +++++++--- src/render/UiLayer.cpp | 5 +---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index f4a413ba..80ad6521 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -908,7 +908,7 @@ def __init__(self, id, kind, name): self.offset, self.inside = 0, False # (a scroll panel: how far it is scrolled; being laid out inside) -_state = {'ctrl': None, 'dirty': False} +_state = {'ctrl': None, 'dirty': False, 'scrolling': 0} def _text(s): @@ -1284,8 +1284,10 @@ def _height(n, w): return max([_height(c, cw) for c, cw in zip(n.children, widths)] or [0]) if k == 'panel' and not n.children: return 0 # (an empty one: the resolution's screen picture, none here) - if k == 'scroll' and not n.inside: - return 0 # (a scroll panel: what its box is given, its content scrolls in it) + if k == 'scroll' and not n.inside and not _state['scrolling']: + # (a scroll panel: as high as its box is given, what it holds scrolls in it; one inside + # another, the Audio tab's volume sliders in its panel, as high as what it holds) + return 0 px, py = _pad(n) inner = w - 2 * px h = sum(_height(c, inner) for c in n.children) + _GAP * max(0, len(n.children) - 1) @@ -1435,10 +1437,12 @@ def _scrollPanel(screen, n, name, x, y, w, h): panel.offset = n.offset first = len(screen._s.order) n.inside = True + _state['scrolling'] += 1 try: _place(screen, n, x, y, w, h) finally: n.inside = False + _state['scrolling'] -= 1 for c in screen._s.order[first:]: cw = screen._s.widgets.get(c) if cw is None: diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index a6440822..c29ad02f 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -485,10 +485,7 @@ namespace oc4::render o.clip(it.clipped ? std::max(x0, it.clip[0]) : x0, it.clipped ? std::max(y0, it.clip[1]) : y0, it.clipped ? std::min(x1 - 3, it.clip[2]) : x1 - 3, it.clipped ? std::min(y1, it.clip[3]) : y1); o.richText(text, tx, ty, size, false, colour, a); - if (it.clipped) - o.clip(it.clip[0], it.clip[1], it.clip[2], it.clip[3]); - else - o.unclip(); + o.unclip(); // (back to its own clip, if it has one: the clips are a stack) } else o.richText(text, tx, ty, size, false, colour, a); From 647a3780b47b3284fd3862effdadeedd4abedc6e Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 16:38:18 +0100 Subject: [PATCH 63/89] Bundle: the interface PRs together, as tested on the play branch - The OpenCiv4 tab's 'Open a city with a single click' (#113) once: #113's and #137's option lists each added it. - City bars: the list a click is matched against is emptied before drawOverlay's early return (#109 hides the bars on the city screen; #113 clicks them): no click on a bar not drawn. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 5 ----- src/render/MapView.cpp | 3 ++- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index b8c19190..80ad6521 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -1065,11 +1065,6 @@ def _attachNumber(self, parent, key, before, after, tip): self.setToolTip(name, tip) self.attachLabel(row, row + 'After', after) - self.attachCheckBox(parent, CITY_ONE_CLICK_CHECKBOX, u'Open a city with a single click', 'oc4options', 'handleCityOneClickClicked', - CITY_ONE_CLICK_CHECKBOX, _cityOneClickOn()) - self.setToolTip(CITY_ONE_CLICK_CHECKBOX, u'One click on your city or its name bar opens the city screen. Off, as in the ' - u'original: a click on the name bar selects the city, a double click on the city or its bar opens it.') - def attachVBox(self, parent, name): self._node('vbox', parent, name) def attachHBox(self, parent, name): self._node('hbox', parent, name) diff --git a/src/render/MapView.cpp b/src/render/MapView.cpp index a81abdb0..357d5e42 100644 --- a/src/render/MapView.cpp +++ b/src/render/MapView.cpp @@ -5021,6 +5021,8 @@ float4 PSWater(WaterOut i) : SV_Target // production bars and what is being built where the active player may see them. void MapView::drawOverlay(Overlay& overlay) { + // (no bars drawn, none to click: a city's screen hides them where they were) + m->cityBars.clear(); if (!m->hasMap || !options.banners || !options.cities || options.cityScreen || m->renderer.globe()) return; const float* vp = m->renderer.viewProjection(); @@ -5142,7 +5144,6 @@ float4 PSWater(WaterOut i) : SV_Target } return &out; }; - m->cityBars.clear(); for (const CityView& c : m->map.cities) { if (options.fog && !m->map.plots[size_t(c.x) + size_t(c.y) * size_t(m->map.width)].revealed) From 148ae0630a98b395b8253c20887c79426e9a1755 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 18:26:13 +0100 Subject: [PATCH 64/89] City on the map: a double click as forgiving as the original's The user found opening a city with a double click hard; in the original (BtS under Wine) it is easy. Measured in Wine (backlog #46): a double click on one's city opens it on its plot, on its name bar and on a unit's figure in it; the presses may be up to ~480 ms apart (550 ms: no, as Windows' 500 ms); and a single click on one's city, its plot or a figure in it, leaves the camera where it is, so the second click lands on the city again. OpenCiv4 glided the camera to the plot on the first click, so the second click often landed on another plot; a double click on a figure in the city only selected the unit; and SDL counted the presses by when a frame got round to them, so a slow frame after the first click could split a double click. Now: no glide on a click on one's own city; a double click on a figure in it opens the city; the double click is counted by the presses' own event times (500 ms, within 8 points each way, src/render/DoubleClick.h; a third press starts again, as Windows', so a triple click does not close the screen it opened); and the second click of a double click is taken on what the first was on, whatever moved under the mouse in between. Tested by tests/double_click_test.cpp. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 5 +++ README.md | 5 +++ apps/oc4core/main.cpp | 18 ++++++---- src/render/DoubleClick.h | 41 +++++++++++++++++++++++ src/render/MapWindow.cpp | 30 +++++++++++++++-- tests/double_click_test.cpp | 67 +++++++++++++++++++++++++++++++++++++ 6 files changed, 157 insertions(+), 9 deletions(-) create mode 100644 src/render/DoubleClick.h create mode 100644 tests/double_click_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a900736..6c193491 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -378,6 +378,11 @@ target_include_directories(edge_scroll_test PRIVATE src) add_test(NAME edge_scroll COMMAND edge_scroll_test) set_target_properties(edge_scroll_test PROPERTIES FOLDER "tests") +add_executable(double_click_test tests/double_click_test.cpp) +target_include_directories(double_click_test PRIVATE src) +add_test(NAME double_click COMMAND double_click_test) +set_target_properties(double_click_test PROPERTIES FOLDER "tests") + add_executable(auto_end_turn_test tests/auto_end_turn_test.cpp) target_include_directories(auto_end_turn_test PRIVATE apps/oc4core) target_link_libraries(auto_end_turn_test PRIVATE oc4_options) diff --git a/README.md b/README.md index 310cbeb5..054c4a4e 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,11 @@ Your cities on the map open as in the original: a double click on the city or it its screen, one click on the bar selects the city (what it builds in the bottom panel), and one click on its plot is any plot's (the units there). "Open a city with a single click" on the options' OpenCiv4 tab opens the screen with one click instead (off by default; `cityOneClick` in profile.ini). +A double click is as forgiving as the original's: up to 500 ms between the presses (their own times, +not a frame's), a few points apart, and its second click counts on what the first was on; a click on +your own city (its plot, bar or a unit's figure in it) leaves the camera where it is, as the +original's, so the city stays under the mouse. The rule is `src/render/DoubleClick.h`, tested by +`tests/double_click_test.cpp`. The player options (Options → Game: Wait at End of Turn, Quick Combat, …) are kept in the player's profile, as the original keeps them in its own (`Profiles\.pfl`): a choice is written to diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 8c4d0964..9d5703ef 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1502,10 +1502,12 @@ namespace // One's city, as the original's: a double click on it or its name bar opens its screen // (the units there are in the plot list then), one click on the bar selects the city // (what it builds in the bottom panel); one click on its plot is any plot's (its - // units). On one of the figures in it, as anywhere, its unit. OpenCiv4's option opens - // the screen with one click on either. - if (!click.right && !click.onFigure && !opt.ownInterface && screens.active()) - if (CvCity* city = plot->getPlotCity(); city && city->getOwner() == me) + // units). One click on one of the figures in it is, as anywhere, its unit's; a double + // click there opens the city too (Wine, backlog #46). OpenCiv4's option opens the + // screen with one click on the city or its bar. + CvCity* ownCity = plot->getPlotCity() && plot->getPlotCity()->getOwner() == me ? plot->getPlotCity() : nullptr; + if (!click.right && (!click.onFigure || click.twice) && !opt.ownInterface && screens.active()) + if (CvCity* city = ownCity) { if (click.twice || utility.cityOneClick()) { @@ -1530,9 +1532,11 @@ namespace ui.selectGroup(own, click.shift, click.ctrl, click.alt); else ui.clearSelectionList(); - // (as the original's: the camera goes to the plot clicked, a unit there or not; - // a scripted game told where to look keeps looking there) - if (opt.lookX < 0 || opt.viewSeconds <= 0) + // (as the original's: the camera goes to the plot clicked, a unit there or not, but + // not to one's own city, its plot or a figure in it (Wine, backlog #46: so a double + // click's second click lands where the first did); a scripted game told where to + // look keeps looking there) + if (!ownCity && (opt.lookX < 0 || opt.viewSeconds <= 0 || std::getenv("OC4_FOLLOW_CAMERA"))) window.centerOn(plot->getX(), plot->getY()); } else if (ui.getHeadSelectedUnit()) diff --git a/src/render/DoubleClick.h b/src/render/DoubleClick.h new file mode 100644 index 00000000..f91881be --- /dev/null +++ b/src/render/DoubleClick.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +// The mouse's double click on the map, as forgiving as the original's (BtS under Wine, measured +// 2026-11-21, backlog #46: a second press up to ~480 ms after the first opens one's city, 550 ms +// does not, as Windows' 500 ms). The time is the presses' own (the system's event times), not +// when a frame gets round to them, so a slow frame after the first click cannot split a double +// click. The original lets the mouse move 1 point between the presses; this lets it move a few +// (a trackpad's taps wander): the second click of a double click is taken on what the first was +// on anyway (MapWindow), so nothing moving under the mouse in between matters. + +namespace oc4::render +{ + constexpr uint64_t kDoubleClickNs = 500'000'000; // between the two presses + constexpr float kDoubleClickRadius = 8; // points, each way + + class DoubleClick + { + public: + // A press of the button at that time (nanoseconds) and place (points): 2 for the second of + // a double click, else 1. As Windows', a third press starts again (no triple click: it + // would close the city screen the double click opened). + int press(uint64_t ns, float x, float y) + { + const bool second = m_count == 1 && ns >= m_at && ns - m_at <= kDoubleClickNs && + std::fabs(x - m_x) <= kDoubleClickRadius && std::fabs(y - m_y) <= kDoubleClickRadius; + m_count = second ? 2 : 1; + m_at = ns, m_x = x, m_y = y; + return m_count; + } + // Another button pressed between: no double click across it. + void reset() { m_count = 0; } + + private: + int m_count = 0; + uint64_t m_at = 0; + float m_x = 0, m_y = 0; + }; +} diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index afa9e6b7..fc500bd3 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -4,6 +4,7 @@ #include "render/UiScale.h" #include "render/WasdPan.h" #include "render/EdgeScroll.h" +#include "render/DoubleClick.h" #include "render/PadMap.h" #include "render/Leaderhead.h" @@ -236,6 +237,8 @@ namespace oc4::render int downX = 0, downY = 0; bool downLeft = false; int buttonClicks = 1; // the mouse button's clicks in a row (2: a double click) + DoubleClick doubleClick; // (counts the left button's presses: DoubleClick.h) + std::optional firstClick; // the map click a double click's second click is on std::function plotHelp; ButtonArt art; Theme theme; @@ -1361,6 +1364,8 @@ namespace oc4::render downY = y; downLeft = left; pathCancelled = false; + if (!left || buttonClicks < 2) + firstClick.reset(); // (no double click: what the last click was on is forgotten) } // On a popup: its buttons (the map around it still pans). if (down && popup.contains(x, y)) @@ -1452,11 +1457,23 @@ namespace oc4::render // (a city's bar is over the figures: a click on it is on its city) const bool onBar = view->cityBarAt(float(x), float(y)).has_value(); const auto figure = onBar ? std::nullopt : figureUnder(x, y); - if (const auto p = figure ? *figure : hoveredPlot(); p.first >= 0) + const auto first = std::exchange(firstClick, std::nullopt); + if (downLeft && buttonClicks >= 2 && first) + { + // The second click of a double click: on what the first was on (the city, its bar, + // a figure), whatever moved under the mouse in between (the camera, figures, the bar). + MapWindow::PlotClick c = *first; + c.shift = mods.shift, c.ctrl = mods.ctrl, c.alt = mods.alt; + c.twice = true; + clicks.push_back(c); + } + else if (const auto p = figure ? *figure : hoveredPlot(); p.first >= 0) { clicks.push_back({ p.first, p.second, !downLeft, mods.shift, mods.ctrl, mods.alt, figure.has_value() }); clicks.back().twice = buttonClicks >= 2; clicks.back().onCityBar = onBar; + if (downLeft && buttonClicks < 2) + firstClick = clicks.back(); } } if (down) @@ -2655,7 +2672,16 @@ namespace oc4::render } else if (e.button.button == SDL_BUTTON_LEFT || e.button.button == SDL_BUTTON_RIGHT) { - buttonClicks = e.button.clicks; + // (the double click is counted by the presses' own times: DoubleClick.h; a + // button let go keeps its press's count) + if (e.button.button == SDL_BUTTON_RIGHT) + { + if (down) + doubleClick.reset(); + buttonClicks = 1; + } + else if (down) + buttonClicks = doubleClick.press(e.button.timestamp, e.button.x, e.button.y); if (down) ++inputs; // (a click is the player's too: inputCount) onButton(down && e.button.button == SDL_BUTTON_LEFT, down, x, y); diff --git a/tests/double_click_test.cpp b/tests/double_click_test.cpp new file mode 100644 index 00000000..1be0fa7f --- /dev/null +++ b/tests/double_click_test.cpp @@ -0,0 +1,67 @@ +// Checks the map's double click (src/render/DoubleClick.h): two presses within 500 ms and a few +// points are a double click, a third starts again, and a later, farther or interrupted one is not. + +#include "render/DoubleClick.h" + +#include + +using namespace oc4::render; + +namespace +{ + int failures = 0; + + void check(bool ok, const char* what) + { + if (!ok) + { + std::printf("FAILED: %s\n", what); + ++failures; + } + } + + constexpr uint64_t ms = 1'000'000; +} + +int main() +{ + { + DoubleClick d; + check(d.press(1000 * ms, 100, 100) == 1, "first press: a click"); + check(d.press(1200 * ms, 100, 100) == 2, "200 ms later, same place: a double click"); + check(d.press(1300 * ms, 100, 100) == 1, "a third press: a click again"); + check(d.press(1400 * ms, 100, 100) == 2, "and a fourth the second of a new double click"); + } + { + DoubleClick d; + d.press(0, 50, 50); + check(d.press(480 * ms, 50, 50) == 2, "480 ms (the original opened the city): double"); + d.press(10'000 * ms, 50, 50); + check(d.press(10'000 * ms + 500 * ms, 50, 50) == 2, "500 ms: double"); + d.press(20'000 * ms, 50, 50); + check(d.press(20'000 * ms + 550 * ms, 50, 50) == 1, "550 ms (the original did not): single"); + } + { + DoubleClick d; + d.press(0, 50, 50); + check(d.press(200 * ms, 58, 42) == 2, "8 points each way: double"); + d.press(5000 * ms, 50, 50); + check(d.press(5200 * ms, 59, 50) == 1, "9 points away: single"); + d.press(9000 * ms, 50, 50); + check(d.press(9200 * ms, 50, 108) == 1, "from a city's plot to its bar, 58 points (the original: single)"); + } + { + DoubleClick d; + d.press(0, 50, 50); + d.reset(); + check(d.press(200 * ms, 50, 50) == 1, "the other button pressed between: single"); + } + { + DoubleClick d; + d.press(1000 * ms, 50, 50); + check(d.press(900 * ms, 50, 50) == 1, "a time before the last press: single"); + } + if (failures == 0) + std::printf("double click: all passed\n"); + return failures == 0 ? 0 : 1; +} From 7879df199672f4892e9c6d75ad5d02a09b233c81 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 19:51:57 +0100 Subject: [PATCH 65/89] City on the map: a double click keeps the units selected before it A double click's first click is a click: on one's city it selected the units there (or, on the name bar, none), so the city screen opened with those, and Esc gave them back instead of the unit the player had selected (backlog #35's fix keeps what is selected when the screen opens). The units selected before each left click on the map are now kept, and a double click that opens one's city selects them again first, as the original: in BtS under Wine a worker selected two plots from the city stays selected after a double click on the city's plot, its name bar or a figure in it and Esc, while a single click on the plot selects the unit in the city (backlog #46). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 9d5703ef..a19a3b42 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -774,6 +774,7 @@ namespace std::vector actionIds; // the action of each button the window shows std::optional> pathShown; // where the way the window shows leads + std::optional> selectedBeforeClick; // (the units selected before the last left click on the map) std::pair pathFrom{}; // (the unit it starts from and its plot: the gamepad's plot cursor shows it all the while) std::tuple coloredFor{}; // what was selected when the plots were last coloured uint64_t marksShown = ~0ull; // the marks the window has @@ -1505,12 +1506,29 @@ namespace // units). One click on one of the figures in it is, as anywhere, its unit's; a double // click there opens the city too (Wine, backlog #46). OpenCiv4's option opens the // screen with one click on the city or its bar. + // The first click of a double click is a click (it selects the units there); the city's + // screen then opens with the units selected before it, the ones Esc gives back (Wine, + // backlog #46: on its plot, its bar or a figure in it). CvCity* ownCity = plot->getPlotCity() && plot->getPlotCity()->getOwner() == me ? plot->getPlotCity() : nullptr; + const auto before = std::exchange(selectedBeforeClick, std::nullopt); + if (!click.right && !click.twice) + { + selectedBeforeClick.emplace(); + for (CLLNode* n = ui.headSelectionListNode(); n; n = ui.nextSelectionListNode(n)) + selectedBeforeClick->push_back(n->m_data); + } if (!click.right && (!click.onFigure || click.twice) && !opt.ownInterface && screens.active()) if (CvCity* city = ownCity) { if (click.twice || utility.cityOneClick()) { + if (click.twice && before) + { + ui.clearSelectionList(); + for (const IDInfo& id : *before) + if (CvUnit* u = CvPlayerAI::getPlayerNonInl(id.eOwner).getUnit(id.iID); u && u->getOwner() == me) + ui.insertIntoSelectionList(u, false, false, false, false, true); + } ui.selectCity(city, true); continue; } From 83fb46163c70d52154c9565e2d42854093a92fd3 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sun, 22 Nov 2026 09:43:07 +0100 Subject: [PATCH 66/89] Popups: a choice with a picture is the theme's label button, as the original's The game's "what to build" and "what to research" popups list choices with a picture (popupAddGenericButton with an icon). The original draws those as the theme's GFC_Control_LabelButton_Style, not the stone button: the picture 30 square, the text 4 after it in white, one every 36; gold (SelectText) with the focus, which starts on the first choice and follows the mouse and the arrow keys; RollText while pressed, the content 1 lower. Let go off the pressed choice and nothing is chosen. Return chooses the gold one; the arrows move the focus at once (the map does not pan). A popup is never higher than 477 (Wine's rim 77-553 at 1600 x 900 and 1280 x 1000 alike): what is longer scrolls with its title, the theme's scroll bar 14 wide 20 from the right edge. Choices without a picture keep the stone button. Measured in Wine (plain game and BUG + BULL alike). --keys: "!" and ";" press and let go the left button, and the mouse's keys reach a popup that is up. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 21 ++++--- src/render/MapWindow.cpp | 3 + src/render/PopupPanel.cpp | 119 ++++++++++++++++++++++++++++++++++---- src/render/PopupPanel.h | 14 ++++- 4 files changed, 136 insertions(+), 21 deletions(-) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index a19a3b42..06714f66 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -39,8 +39,9 @@ // popups as they come, the actions the keys run and the widgets clicked; OC4_UI_DUMP= // writes the interface's widgets there when they change. // In --keys, "?" also moves the mouse to that pixel of the window, "/" presses the -// right button there and holds it, "\" lets it go there (a drag, as the mouse's), and "%x" -// types Esc into the window (where '~' is the game's Esc). +// right button there and holds it, "\" lets it go there (a drag, as the mouse's), "!" +// and ";" do the same with the left button, and "%x" types Esc into the window (where '~' +// is the game's Esc). The mouse's ("?", "", "!", ";") reaches a popup up. // // --menu (and no options at all) opens the window on a temporary main menu: a new game, with // the leader, map script, world and difficulty to choose, or a saved one, played as with @@ -1241,10 +1242,13 @@ namespace } auto clicks = window.takeClicks(); // (a scripted game answers what it does not expect with the popup's first button) - if (!script.empty() && script.front() != '#' && script.front() != '\'' && script.front() != '%' && ui.shownPopup() && Clock::now() - typed > std::chrono::milliseconds(1500)) + // (the mouse on the popup, "?", "", "!" and ";", goes to it as it is) + const auto onPopup = [&] { return script.front() == '#' || script.front() == '\'' || script.front() == '%' || + ((script.front() == '?' || script.front() == '<' || script.front() == '!' || script.front() == ';') && script.size() > 1 && script[1] != '{'); }; + if (!script.empty() && !onPopup() && ui.shownPopup() && Clock::now() - typed > std::chrono::milliseconds(1500)) script.insert(0, "#0"); if (const auto now = Clock::now(); player.isTurnActive() && !script.empty() && now - typed > std::chrono::milliseconds(400) && - (script.front() == '#' || script.front() == '\'' || script.front() == '%' || !ui.shownPopup())) // (the rest waits for the popup's answer) + (onPopup() || !ui.shownPopup())) // (the rest waits for the popup's answer) { typed = now; render::MapWindow::PlotClick click; @@ -1310,15 +1314,16 @@ namespace clicks.push_back(click); script.erase(0, close + 1); } - else if (int px = 0, py = 0; (script.front() == '?' || script.front() == '/' || script.front() == '\\') && script.size() > 1 && script[1] == '<' && - script.find('>') != std::string::npos && std::sscanf(script.c_str() + 2, "%d,%d", &px, &py) == 2) + else if (int px = 0, py = 0; (script.front() == '?' || script.front() == '/' || script.front() == '\\' || script.front() == '!' || script.front() == ';') && + script.size() > 1 && script[1] == '<' && script.find('>') != std::string::npos && std::sscanf(script.c_str() + 2, "%d,%d", &px, &py) == 2) { // "?": the mouse moved to that pixel; "/" the right button pressed there and - // held, "\" let go there (a drag, as the mouse's). + // held, "\" let go there (a drag, as the mouse's); "!" and ";" the same + // with the left button. if (script.front() == '?') window.mouseMove(px, py); else - window.mouseButton(px, py, false, script.front() == '/'); + window.mouseButton(px, py, script.front() == '!' || script.front() == ';', script.front() == '/' || script.front() == '!'); script.erase(0, script.find('>') + 1); } else if (int px = 0, py = 0, qx = 0, qy = 0; script.front() == '<' && script.find('>') != std::string::npos && diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index fc500bd3..53a3334c 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -1371,6 +1371,8 @@ namespace oc4::render if (down && popup.contains(x, y)) { downOnPopup = true; + if (left) + popup.press(x, y); // (a choice shows pressed while held) return; } // On the main interface's minimap: the camera goes there (and follows while held), as the @@ -1428,6 +1430,7 @@ namespace oc4::render { if (downLeft && std::abs(x - downX) + std::abs(y - downY) < 5) // (button up messages do not say which) popup.click(x, y); + popup.release(); return; } // The right button held while playing shows the way there; let go, the units go there. diff --git a/src/render/PopupPanel.cpp b/src/render/PopupPanel.cpp index da2384c5..f00e3a36 100644 --- a/src/render/PopupPanel.cpp +++ b/src/render/PopupPanel.cpp @@ -27,6 +27,13 @@ namespace oc4::render // (as the game's popups: their width, margins, the choices' pictures, the OK button's height) constexpr float kWidth = 400, kPadX = 21, kPadTop = 18, kPadBottom = 20, kIcon = 28, kOk = 24; constexpr float kStoneLine = 25, kStoneGap = 6, kStoneInset = 9; // (a choice's stone button) + // A choice with a picture is the theme's label button instead (GFC_Control_LabelButton_Style: + // no stone; Wine at 1600 x 900 and 1280 x 1000 alike): its picture 30 square 2 in, the text 4 + // after it, one every 36 (the picture, the button's margin 2 round it, the item space 2), the + // content 1 lower while pressed. And a popup is never higher than the original's: what is + // longer scrolls, its title too (Wine's rim 77-553 at both sizes, its light line at 550: our + // frame's is 7 over its bottom, so 480), wrapped short of the scroll bar. + constexpr float kLabelIcon = 30, kLabelRow = 36, kLabelInset = 2, kLabelGap = 4, kMaxHeight = 480, kScrollRoom = 20; // The game menu (Window_NoTitleBar_Style): 248 wide, where the other popups are (Wine at // 1600 x 900 and 1280 x 1000 alike: its rim 1334-1582 and 1014-1262, from 77); its separator // only a space (no line: the first button 10 under the title). @@ -83,6 +90,18 @@ namespace oc4::render m_hoverOk = false; m_keyboard = false; m_scrollTo = -1; + m_pressed = -1; + // (the focus starts on the first choice, as the original's: the gold one) + m_selected = -1; + for (size_t i = 0; i < view->items.size() && m_selected < 0; ++i) + if (view->items[i].kind == Kind::Button) + m_selected = int(i); + } + + bool PopupPanel::label(int item) const + { + return m_view && item >= 0 && size_t(item) < m_view->items.size() && m_view->items[size_t(item)].kind == Kind::Button && + !m_view->items[size_t(item)].icon.empty() && m_label != nullptr && m_label->coloured; } void PopupPanel::hover(int x, int y) @@ -101,6 +120,20 @@ namespace oc4::render for (size_t i = 0; i < m_items.size(); ++i) if (m_items[i].contains(fx, fy) && chooses(m_view->items[i].kind)) m_hover = int(i); + // (a choice under the mouse takes the focus, and keeps it when the mouse leaves) + if (m_hover >= 0 && m_view->items[size_t(m_hover)].kind == Kind::Button) + m_selected = m_hover; + } + + void PopupPanel::press(int x, int y) + { + hover(x, y); + m_pressed = m_hover; + } + + void PopupPanel::release() + { + m_pressed = -1; } bool PopupPanel::click(int x, int y) @@ -108,8 +141,11 @@ namespace oc4::render if (!m_view) return false; hover(x, y); + const int pressed = std::exchange(m_pressed, -1); if (m_answered) return true; + if (pressed >= 0 && pressed != m_hover) // (let go off the choice pressed: nothing, as the original's) + return true; if (m_hoverOk) answer(-1); else if (m_hover >= 0) @@ -142,7 +178,8 @@ namespace oc4::render stops.push_back(int(i)); if (m_view->okButton) stops.push_back(kOkStop); - const int current = m_keyboard ? (m_hoverOk ? kOkStop : m_hover) : -1; + // (the keys go on from the focus, the gold choice, when it is a label button) + const int current = m_keyboard ? (m_hoverOk ? kOkStop : m_hover) : label(m_selected) ? m_selected : -1; const auto at = std::ranges::find(stops, current); const int next = navStep(int(stops.size()), m_keyboard && at != stops.end() ? int(at - stops.begin()) : -1, delta); if (next < 0) @@ -151,6 +188,8 @@ namespace oc4::render m_keyboard = true; m_hoverOk = stop == kOkStop; m_hover = m_hoverOk ? -1 : stop; + if (m_hover >= 0 && m_view->items[size_t(m_hover)].kind == Kind::Button) + m_selected = m_hover; m_scrollTo = m_hover; if (m_hover >= 0 && m_view->items[size_t(m_hover)].kind == Kind::Edit) m_focus = m_hover; @@ -185,6 +224,8 @@ namespace oc4::render { if (chosenWithKeys) choose(m_hover); + else if (label(m_selected)) // (the gold choice, as the original's) + choose(m_selected); else if (m_view->okButton) answer(-1); } @@ -236,6 +277,9 @@ namespace oc4::render m_frame = m_theme.skin("SF_CtrlTheme_Civ4_Control_Window_NoTitleBar_InFrameBorder_Normal_Style", "GFC_CtrlTheme_Bitmap_Control_Border_Skin_Full_Default"); m_tooltip = m_theme.skin("GFC_Control_StandardToolTip_Style", "GFC_CtrlTheme_Bitmap_Control_ToolTip_Skin_Inner_Default"); m_button = m_theme.button("BUTTON_STYLE_STANDARD"); + m_label = m_theme.button("BUTTON_STYLE_LABEL"); + m_shaft = m_theme.skin("GFC_Control_StandardScroll_Style", "GFC_CtrlTheme_Bitmap_Control_Scroll_Skin_VShaft_Default"); + m_gripSkin = m_theme.skin("SF_CtrlTheme_Civ4_Control_Scroll_VGripButton_Style", "GFC_CtrlTheme_Bitmap_Control_Button_Skin_Default"); m_headerSize = m_theme.font(4).size; m_textSize = m_theme.font(3).size; m_helpSize = m_theme.font(2).size; @@ -261,6 +305,11 @@ namespace oc4::render { case Kind::Text: heights[i] = o.richHeight(texts[i], inner, m_textSize, false) + 10; break; case Kind::Button: + if (label(int(i))) + { + heights[i] = std::max(kLabelRow, o.richHeight(texts[i], inner - kLabelInset - kLabelIcon - kLabelGap, m_textSize, false) + 2 * kLabelInset + 2); + break; + } // (on the theme's stone button, as the original's: 25 high for a line, the text's // height and 3 for more (two lines of the game font: 47), 6 apart, the text 9 in; // measured in Wine at 1600 x 900) @@ -275,13 +324,24 @@ namespace oc4::render } content += heights[i]; } - const float headerHeight = header.empty() ? 0.0f : o.richHeight(header, inner, m_headerSize, false) + 10; + float headerWidth = inner; + float headerHeight = header.empty() ? 0.0f : o.richHeight(header, headerWidth, m_headerSize, false) + 10; const float okHeight = m_view->okButton ? kOk + 10 : 0.0f; float y0 = right ? 77.0f : 30.0f; // (the original leaves 19 under a last stone button to the rim: 3 more than the margin) const float tail = stone && !items.empty() && items.back().kind == Kind::Button && !m_view->okButton ? 3.0f : 0.0f; - const float listHeight = std::max(0.0f, std::min(content, sh - y0 - 20 - headerHeight - okHeight - kPadTop - kPadBottom - tail)); - const float h = kPadTop + headerHeight + listHeight + okHeight + kPadBottom + tail; + // (no higher than the original's 477, nor than the screen: what does not fit scrolls, the + // title with the rest) + const float room = std::min(kMaxHeight, sh - y0 - 20) - okHeight - kPadTop - kPadBottom - tail; + const bool titleScrolls = headerHeight + content > room; + if (titleScrolls && !header.empty()) + { + headerWidth = inner - kScrollRoom; + headerHeight = o.richHeight(header, headerWidth, m_headerSize, false) + 10; + } + const float scrolled = content + (titleScrolls ? headerHeight : 0.0f); + const float listHeight = std::max(0.0f, std::min(scrolled, room - (titleScrolls ? 0.0f : headerHeight))); + const float h = kPadTop + (titleScrolls ? 0.0f : headerHeight) + listHeight + okHeight + kPadBottom + tail; if (!right) y0 = std::max(30.0f, (sh - h) / 2); m_panel = { x0, y0, x0 + w, y0 + h }; @@ -300,16 +360,16 @@ namespace oc4::render } float y = y0 + kPadTop; - if (!header.empty()) + if (!header.empty() && !titleScrolls) { o.richBlock(header, x0 + kPadX, y, inner, m_headerSize, false, kText); y += headerHeight; } m_list = { x0 + kPadX - 4, y, x0 + w - kPadX + 4, y + listHeight }; - m_scrollMax = std::max(0.0f, content - listHeight); + m_scrollMax = std::max(0.0f, scrolled - listHeight); if (m_scrollTo >= 0 && size_t(m_scrollTo) < items.size()) { - float top = 0; + float top = titleScrolls ? headerHeight : 0.0f; for (int i = 0; i < m_scrollTo; ++i) top += heights[size_t(i)]; if (top < m_scroll) @@ -326,6 +386,12 @@ namespace oc4::render if (items[i].kind == Kind::Button) firstChoice = int(i); float iy = y - m_scroll; + if (titleScrolls) + { + if (!header.empty()) + o.richBlock(header, x0 + kPadX, iy, headerWidth, m_headerSize, false, kText); + iy += headerHeight; + } const float rightEdge = x0 + w - kPadX - (m_scrollMax > 0 ? 10 : 0); for (size_t i = 0; i < items.size(); ++i) { @@ -342,6 +408,27 @@ namespace oc4::render case Kind::Text: o.richBlock(texts[i], r.x0, r.y0 + 4, r.x1 - r.x0, m_textSize, false, kText); break; case Kind::Button: { + if (label(int(i))) + { + // A choice with a picture, as the original's: the theme's label button, no stone. + // Its picture, and its text white; gold with the focus (the first, then the last + // under the mouse or the keys), RollText while pressed, the content then 1 lower. + const bool pressed = int(i) == m_pressed && hot; + const size_t st = pressed ? size_t(Theme::State::Press) : int(i) == m_selected ? size_t(Theme::State::Rollover) : size_t(Theme::State::Default); + const float down = pressed ? 1.0f : 0.0f; + float tx = r.x0 + kLabelInset; + if (const ButtonArt::Icon* ic = m_art.icon(item.icon)) + { + const float iy0 = std::round(r.y0 + (ih - kLabelIcon) / 2) - 2 + down; // (Wine: its top 9 over the text's capitals) + o.image(ic->key, ic->bgra, ic->width, ic->height, 1, tx, iy0, tx + kLabelIcon, iy0 + kLabelIcon); + } + tx += kLabelIcon + kLabelGap; + const float tw = r.x1 - tx, th = o.richHeight(texts[i], tw, m_textSize, false); + o.setShadow(m_label->shadow[st], m_label->shadowAlpha[st]); + o.richBlock(texts[i], tx, std::round(r.y0 + (ih - th) / 2) + down, tw, m_textSize, false, m_label->text[st], m_label->textAlpha[st]); + o.resetShadow(); + break; + } if (stone) { // A choice: the theme's stone button across the window (lit under the mouse), its @@ -434,7 +521,7 @@ namespace oc4::render break; } } - if (m_keyboard && m_hover >= 0 && size_t(m_hover) < m_items.size()) + if (m_keyboard && m_hover >= 0 && size_t(m_hover) < m_items.size() && !label(m_hover)) // (a label button shows it gold) { const Rect& r = m_items[size_t(m_hover)]; o.frame(r.x0 - 2, r.y0 + 1, r.x1 + 2, r.y1 - 1, kKeyChoice, 1, 3, 2); @@ -442,10 +529,20 @@ namespace oc4::render o.unclip(); if (m_scrollMax > 0) { - // Where the list is. - const float track = m_list.y1 - m_list.y0, thumb = std::max(24.0f, track * listHeight / content); + // Where the list is: the theme's scroll bar, as the original's (14 wide, 20 from the + // window's right edge, from 21 under its top to 21 over its bottom when the title scrolls + // too); else a thin grip. + const float track = m_list.y1 - m_list.y0, thumb = std::max(24.0f, track * listHeight / scrolled); const float ty = m_list.y0 + (track - thumb) * (m_scroll / m_scrollMax); - o.rect(x0 + w - kPadX - 4, ty, x0 + w - kPadX + 1, ty + thumb, kEdge, 0.6f, 2); + if (!m_shaft.empty() && !m_gripSkin.empty()) + { + const float bx0 = x0 + w - 34, bx1 = bx0 + 14, by0 = titleScrolls ? y0 + 21 : m_list.y0, by1 = titleScrolls ? y0 + h - 21 : m_list.y1; + const float gy = by0 + (by1 - by0 - thumb) * (m_scroll / m_scrollMax); + Theme::draw(o, m_shaft, bx0, by0, bx1, by1); + Theme::draw(o, m_gripSkin, bx0, gy, bx1, gy + thumb); + } + else + o.rect(x0 + w - kPadX - 4, ty, x0 + w - kPadX + 1, ty + thumb, kEdge, 0.6f, 2); } m_ok = {}; if (m_view->okButton) diff --git a/src/render/PopupPanel.h b/src/render/PopupPanel.h index 3d143252..ce0a5e7f 100644 --- a/src/render/PopupPanel.h +++ b/src/render/PopupPanel.h @@ -31,6 +31,9 @@ namespace oc4::render // Input in window pixels. While it is up the panel takes every click and key; the // wheel only over it. The arrows go through what can be chosen, and Return does it. void hover(int x, int y); + // The left button pressed on it (a choice shows pressed while it is held), and let go. + void press(int x, int y); + void release(); bool click(int x, int y); bool wheel(int x, int y, int delta); bool key(unsigned virtualKey); @@ -39,8 +42,9 @@ namespace oc4::render std::optional takeAnswer() { return std::exchange(m_answer, std::nullopt); } void draw(Overlay& overlay, const std::function& help); - // The keys have chosen something (Tab started it): the arrows are the popup's, not the map's. - bool keyboardChoice() const { return m_keyboard; } + // The keys have chosen something (Tab started it), or the focus is on a choice with a picture + // (the original's arrows move it at once): the arrows are the popup's, not the map's. + bool keyboardChoice() const { return m_keyboard || label(m_selected); } // An edit box has the focus: typing goes into it. bool editing() const { return active() && m_focus >= 0; } @@ -53,12 +57,16 @@ namespace oc4::render void answer(int item); void choose(int item); // as a click on it void moveChoice(int delta); + // A choice with a picture: the theme's label button (its picture and text, no stone). + bool label(int item) const; ButtonArt& m_art; Theme& m_theme; bool m_skinsRead = false; Theme::Skin m_glass, m_frame, m_tooltip; // the theme's window and tooltip (empty: our own look) const Theme::Button* m_button = nullptr; // its standard button + const Theme::Button* m_label = nullptr; // its label button (a choice with a picture) + Theme::Skin m_shaft, m_gripSkin; // its scroll bar float m_headerSize = 22, m_textSize = 16, m_helpSize = 14; // its fonts std::optional m_view; std::vector m_checked; // per item: the radio button chosen, the checkbox ticked @@ -70,6 +78,8 @@ namespace oc4::render Rect m_panel, m_list, m_ok; std::vector m_items; // where each item was drawn (empty: not shown) int m_hover = -1, m_helpItem = -2; + int m_selected = -1; // the choice with the focus (gold): the first, then the last under the mouse or the keys + int m_pressed = -1; // the choice the left button went down on bool m_hoverOk = false; bool m_keyboard = false; // what m_hover says was chosen with the keys, not the mouse int m_scrollTo = -1; // the item to bring into the list at the next draw From 95343f021b27cd38d994f9f697e5f0157b816493 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sun, 22 Nov 2026 10:05:25 +0100 Subject: [PATCH 67/89] Popups: the turn's questions are modal, as the original's While a popup is up the original takes no press outside it: not on the map, its minimap, the main interface's buttons (End Turn, the research bar, the advisors), the action bar; and the wheel scrolls the popup wherever the mouse is (Wine, plain game and BUG alike, the build, research and civic questions). OpenCiv4 let End Turn end the turn, the research bar change it, the map pan and zoom. A screen of its own over the map (Dawn of Man) keeps its clicks. Esc closes none of the turn's questions (what to build, what to research, a new civic), and Space chooses the gold choice as Return does. "Let's see the Big Picture" is back in the research question: the game core opens the tech advisor and asks again when it closes. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/MapCapture.cpp | 9 +++------ src/render/MapWindow.cpp | 15 ++++++++++++++- src/render/MapWindow.h | 1 + src/render/PopupPanel.cpp | 8 ++++++-- src/render/PopupPanel.h | 2 +- src/render/UiLayer.cpp | 6 ++++-- src/render/UiLayer.h | 3 +++ 7 files changed, 32 insertions(+), 12 deletions(-) diff --git a/apps/oc4core/MapCapture.cpp b/apps/oc4core/MapCapture.cpp index 503120d0..04abc8fd 100644 --- a/apps/oc4core/MapCapture.cpp +++ b/apps/oc4core/MapCapture.cpp @@ -1583,15 +1583,12 @@ namespace oc4::host v.menu = popup.style == "Window_NoTitleBar_Style"; itemOf.clear(); const ButtonPopupTypes type = popup.info ? popup.info->getButtonPopupType() : BUTTONPOPUP_TEXT; + // (the original's Esc closes none of the questions a turn waits for: what to build, what to + // research, a new civic; Wine, the plain game and BUG alike) + v.escape = type != BUTTONPOPUP_CHOOSEPRODUCTION && type != BUTTONPOPUP_CHOOSETECH && type != BUTTONPOPUP_CHANGECIVIC; for (size_t i = 0; i < popup.items.size(); ++i) { const Item& it = popup.items[i]; - // In the research popup the buttons that are not a choice open the technology tree: - // not yet. (The production popup's examining the city opens its screen.) - const WidgetTypes w = it.widget.m_eWidgetType; - const bool choice = type != BUTTONPOPUP_CHOOSETECH || w == WIDGET_RESEARCH; - if (it.kind == Item::Kind::Button && !choice) - continue; View::Item& out = v.items.emplace_back(); out.kind = static_cast(it.kind); out.text = it.kind == Item::Kind::Edit ? gameText(it.text.c_str()) : gameMarkup(it.text.c_str()); // (the screens' markup but in an edit box) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index 53a3334c..3a093312 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -1367,7 +1367,7 @@ namespace oc4::render if (!left || buttonClicks < 2) firstClick.reset(); // (no double click: what the last click was on is forgotten) } - // On a popup: its buttons (the map around it still pans). + // On a popup: its buttons. if (down && popup.contains(x, y)) { downOnPopup = true; @@ -1375,6 +1375,12 @@ namespace oc4::render popup.press(x, y); // (a choice shows pressed while held) return; } + // Elsewhere a popup leaves nothing a press, as the original's (Wine, the plain game and BUG + // alike, the build, research and civic questions: the map, its minimap, the main + // interface's buttons, End Turn, the action bar): only a screen of its own over the map + // takes clicks. (a release still ends what was held before it came) + if (down && popup.active() && !(ui.active() && ui.solid(x, y, false))) + return; // On the main interface's minimap: the camera goes there (and follows while held), as the // original's (where the team's map is not centred yet, the minimap and the camera's leash // keep the map's edges hidden). @@ -1508,6 +1514,13 @@ namespace oc4::render void onWheel(int delta) { + // (while a popup is up the wheel scrolls it wherever the mouse is, as the original's; + // a screen of its own over the map keeps its own) + if (popup.active() && !(ui.active() && ui.solid(mouseX, mouseY, false))) + { + popup.wheel(mouseX, mouseY, delta, true); + return; + } if (popup.wheel(mouseX, mouseY, delta)) return; // On the screens: what scrolls there, else nothing (the map only zooms where it shows). diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 61ce31d4..97937f3f 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -173,6 +173,7 @@ namespace oc4::render std::vector items; bool okButton = false; bool menu = false; // the game menu's style (Window_NoTitleBar_Style): narrower, at the same place + bool escape = true; // Esc closes it (not the questions a turn waits for) }; void setPopup(const PopupView* popup); // nullptr: none struct PopupAnswer diff --git a/src/render/PopupPanel.cpp b/src/render/PopupPanel.cpp index f00e3a36..f71adc92 100644 --- a/src/render/PopupPanel.cpp +++ b/src/render/PopupPanel.cpp @@ -195,9 +195,9 @@ namespace oc4::render m_focus = m_hover; } - bool PopupPanel::wheel(int x, int y, int delta) + bool PopupPanel::wheel(int x, int y, int delta, bool anywhere) { - if (!contains(x, y)) + if (!active() || (!anywhere && !contains(x, y))) return false; m_scroll = std::clamp(m_scroll - float(delta) / 120 * 3 * 36, 0.0f, m_scrollMax); hover(x, y); @@ -211,6 +211,8 @@ namespace oc4::render if (m_answered) return true; const bool chosenWithKeys = m_keyboard && m_hover >= 0 && m_view->items[size_t(m_hover)].kind != Kind::Edit; + if (virtualKey == key::Escape && !m_view->escape) + return true; // (the original's questions stay: what to build, research, a new civic) if (virtualKey == key::Escape) { m_answer = MapWindow::PopupAnswer{ .dismissed = true }; @@ -231,6 +233,8 @@ namespace oc4::render } else if (virtualKey == key::Space && chosenWithKeys && m_focus < 0) // (a space is text in an edit box) choose(m_hover); + else if (virtualKey == key::Space && label(m_selected) && m_focus < 0) // (the gold choice, as Return) + choose(m_selected); return true; } diff --git a/src/render/PopupPanel.h b/src/render/PopupPanel.h index ce0a5e7f..b05dc1aa 100644 --- a/src/render/PopupPanel.h +++ b/src/render/PopupPanel.h @@ -35,7 +35,7 @@ namespace oc4::render void press(int x, int y); void release(); bool click(int x, int y); - bool wheel(int x, int y, int delta); + bool wheel(int x, int y, int delta, bool anywhere = false); // (anywhere: not only over it) bool key(unsigned virtualKey); // A character typed (WM_CHAR): into the edit box that has the focus. bool character(wchar_t c); diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index dbb74252..690eec25 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -258,11 +258,13 @@ namespace oc4::render return false; } - bool UiLayer::solid(int x, int y) const + bool UiLayer::solid(int x, int y) const { return solid(x, y, true); } + + bool UiLayer::solid(int x, int y, bool mainInterface) const { for (const Item& it : m_items) { - if (!inside(it, x, y)) + if (!inside(it, x, y) || (!mainInterface && it.mainInterface)) continue; if (it.blocks) return true; // (a screen over the map) diff --git a/src/render/UiLayer.h b/src/render/UiLayer.h index 29752929..2b76a3ae 100644 --- a/src/render/UiLayer.h +++ b/src/render/UiLayer.h @@ -34,6 +34,9 @@ namespace oc4::render int hit(int x, int y) const; // Whether the mouse is on something of the screens (a click there is theirs, not the map's). bool solid(int x, int y) const; + // The same, the main interface left out: a screen of its own (the original's popups leave + // the main interface no clicks, the screens over it theirs). + bool solid(int x, int y, bool mainInterface) const; // Whether the main interface's minimap is what the mouse is on (no button nor screen over it). bool onMainMinimap(int x, int y) const; void hover(int x, int y); From 5fe7d4805104f0637d6e161856e2c9693cc37af8 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sat, 21 Nov 2026 22:38:28 +0100 Subject: [PATCH 68/89] BUG's dot map editor: the city under the mouse drawn full, the clicks the script's As the original's (Wine, BUG Mod, with a worker selected; backlog #68): - CyEngine's Alt forms (fillAreaBorderPlotAlt, addColoredPlotAlt) draw the named colour at the alpha given, in place of the colour's own. BUG draws a city not yet given a colour in COLOR_CLEAR (white, alpha 0) at alpha 1; it was multiplied to nothing. - In Python's pick plot mode (INTERFACEMODE_PYTHON_PICK_PLOT, BUG's editor) a left click keeps the mode and the selected units get no order; a right click leaves the mode, as before. The click used to end the mode, so the next right click moved the selected units. - An interface mode whose info has bHighlightPlot outlines the plot under the mouse in the game core's colour (CvGame::getNewHighlightPlot, getPlotHighlightColor; both DllExport), as the WorldBuilder's brush: green under BUG's editor. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 41 ++++++++++++++++++++++++++++++- apps/oc4core/python/oc4screens.py | 7 ++++-- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index dcb5d5b0..0248f9ed 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -111,6 +111,7 @@ extern char** environ; #include #include #include +#include #include #include @@ -1434,6 +1435,32 @@ namespace } ui.mouseLeft = down[0], ui.mouseRight = down[1]; } + // An interface mode that outlines the plot under the mouse (its InterfaceModeInfo's + // bHighlightPlot: Python's pick plot, ping, sign, the air missions), in the game core's + // colour for it (CvGame::getNewHighlightPlot, getPlotHighlightColor: green; dark grey where + // the units can't go; none where it isn't known or the script can't pick it), as the + // WorldBuilder's brush (Wine: BUG's dot map editor, a green plot under the mouse, backlog #68). + // Asked again only when the mode or the plot changes (pick plot asks the scripts). + static std::tuple highlighted{ -2, -2, -2 }; + if (ui.worldBuilder()) + highlighted = { -2, -2, -2 }; // (the WorldBuilder's brush is drawn in that layer meanwhile) + else + { + const InterfaceModeTypes mode = ui.getInterfaceMode(); + CvPlot* h = ui.mouseOverMap && !opt.ownInterface && mode != NO_INTERFACEMODE && mode != INTERFACEMODE_SELECTION + ? game.getNewHighlightPlot() : nullptr; + if (const std::tuple now{ h ? h->getX() : -1, h ? h->getY() : -1, int(mode) }; now != highlighted) + { + highlighted = now; + utility.engine().clear(AREA_BORDER_LAYER_HIGHLIGHT_PLOT, true); + if (const ColorTypes color = h ? game.getPlotHighlightColor(h) : NO_COLOR; color != NO_COLOR) + { + const NiColorA c = GC.getColorInfo(color).getColor(); + utility.engine().mark({ h->getX(), h->getY(), c.r, c.g, c.b, 0.9f, AREA_BORDER_LAYER_HIGHLIGHT_PLOT, true, false }); + } + changed = true; + } + } window.setWorldBuilder(ui.worldBuilder()); if (ui.worldBuilder()) { @@ -1523,7 +1550,19 @@ namespace click.right = ui.getInterfaceMode() == INTERFACEMODE_SELECTION && head && !own; } // The interface mode wants a plot: its mission there (a right click leaves it). - if (const InterfaceModeTypes mode = ui.getInterfaceMode(); mode != INTERFACEMODE_SELECTION) + // Python's pick plot is the script's: it reads the mouse itself (BUG's dot map editor + // places a city with the left button, takes one away with the right), so a left click + // leaves it on and the selected units get no order, as the original's (Wine, backlog #68). + if (const InterfaceModeTypes mode = ui.getInterfaceMode(); mode == INTERFACEMODE_PYTHON_PICK_PLOT) + { + if (log) + std::printf(" %s at %d,%d: %s\n", GC.getInterfaceModeInfo(mode).getType(), plot->getX(), plot->getY(), + click.right ? "cancelled" : "the script's"); + if (click.right) + ui.setInterfaceMode(INTERFACEMODE_SELECTION); + continue; + } + else if (mode != INTERFACEMODE_SELECTION) { CvSelectionGroup* group = ui.getSelectionList(); if (log) diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index ceb420bb..8d54923a 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -2832,10 +2832,13 @@ def addColoredPlot(self, iX, iY, color, ePlotStyle, eLayer=None): oc4host.engine_mark(_int(iX), _int(iY), float(color.r), float(color.g), float(color.b), float(color.a), _int(eLayer, 0), False, _int(ePlotStyle, -1)) + # (the Alt forms: a colour by its name, at the alpha given, which stands in for the colour's own, + # as the original's: BUG's dot map draws a city not yet given a colour in COLOR_CLEAR, white of + # alpha 0, at alpha 1, and the Wine game shows it white, full (backlog #68)) def addColoredPlotAlt(self, iX, iY, ePlotStyle, eLayer, szColor, fAlpha): c = _namedColor(szColor) if c is not None: - oc4host.engine_mark(_int(iX), _int(iY), c[0], c[1], c[2], c[3] * float(fAlpha), _int(eLayer, 0), False, _int(ePlotStyle, -1)) + oc4host.engine_mark(_int(iX), _int(iY), c[0], c[1], c[2], float(fAlpha), _int(eLayer, 0), False, _int(ePlotStyle, -1)) def clearColoredPlots(self, eLayer): oc4host.engine_clear(_int(eLayer, -1), False) @@ -2845,7 +2848,7 @@ def fillAreaBorderPlot(self, iX, iY, color, eLayer): def fillAreaBorderPlotAlt(self, iX, iY, eLayer, szColor, fAlpha): c = _namedColor(szColor) if c is not None: - oc4host.engine_mark(_int(iX), _int(iY), c[0], c[1], c[2], c[3] * float(fAlpha), _int(eLayer, 0), True) + oc4host.engine_mark(_int(iX), _int(iY), c[0], c[1], c[2], float(fAlpha), _int(eLayer, 0), True) def clearAreaBorderPlots(self, eLayer): oc4host.engine_clear(_int(eLayer, -1), True) From 90c6f7d06d08b3eb63e423787c0590b10e64dfff Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Sun, 22 Nov 2026 10:13:21 +0100 Subject: [PATCH 69/89] BUG's dot map editor: no way for the units drawn while it picks a plot In INTERFACEMODE_PYTHON_PICK_PLOT the right button takes a city away in BUG's editor; the original shows no Go To path for it, neither while the button is held nor for a press begun in that mode and still held after it ends (seen in Wine, backlog #68). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 0248f9ed..8f660e9b 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1673,7 +1673,18 @@ namespace const InterfaceModeTypes pathMode = ui.getInterfaceMode(); window.setGoingTo(playing && pathMode > NO_INTERFACEMODE && pathMode < NUM_INTERFACEMODE_TYPES && GC.getInterfaceModeInfo(pathMode).getGotoPlot() && pathHead && pathHead->getOwner() == me); - if (const auto target = playing ? window.pathTarget() : std::nullopt; target != pathShown || (target && from != pathFrom)) + // None while a script picks a plot (BUG's dot map editor, whose right button takes a city + // away): there the original shows no way to it, neither with the button held nor for a + // press begun in that mode and still held after the mode ends (backlog #68). + static bool pickPress = false; + std::optional> pointed = playing ? window.pathTarget() : std::nullopt; + if (!pointed) + pickPress = false; + else if (ui.getInterfaceMode() == INTERFACEMODE_PYTHON_PICK_PLOT) + pickPress = true; + if (pickPress) + pointed.reset(); + if (const auto target = pointed; target != pathShown || (target && from != pathFrom)) { pathShown = target; pathFrom = from; From 0b633f171a067ce195094e254016ee4538eb9c8c Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 09:21:09 +0100 Subject: [PATCH 70/89] Sounds: the player's music folder and its files' paths as UTF-8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The folder comes from profile.ini as UTF-8, but path(std::string) reads it in the system's code page on Windows: a folder named in what that page can't hold played nothing, and a file such as 東京.mp3 made path::string() throw. The folder now goes through pathFromUtf8, the files' paths come back through utf8Path. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Sounds.cpp | 15 ++++++++------- src/core/FileUtil.cpp | 5 +++++ src/core/FileUtil.h | 2 ++ 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/apps/oc4core/Sounds.cpp b/apps/oc4core/Sounds.cpp index 7c2386a7..33b08091 100644 --- a/apps/oc4core/Sounds.cpp +++ b/apps/oc4core/Sounds.cpp @@ -1,6 +1,7 @@ #include "Sounds.h" #include "audio/Audio.h" +#include "core/FileUtil.h" #include "CvGameCoreDLL.h" @@ -39,19 +40,19 @@ namespace oc4::host std::string g_musicFolder; // (the player's own music; empty: the era's) std::atomic g_folderChanges = 0; - // The music files of a folder (MP3, WAV), by name. + // The music files of a folder (MP3, WAV), by name; the folder and the files' paths in UTF-8. std::vector musicFiles(const std::string& folder) { std::vector out; std::error_code ec; - if (folder.empty() || !std::filesystem::is_directory(folder, ec)) + if (folder.empty() || !std::filesystem::is_directory(pathFromUtf8(folder), ec)) return out; - for (const auto& e : std::filesystem::directory_iterator(folder, ec)) + for (const auto& e : std::filesystem::directory_iterator(pathFromUtf8(folder), ec)) { - std::string ext = e.path().extension().string(); + std::string ext = utf8Path(e.path().extension()); std::ranges::transform(ext, ext.begin(), [](unsigned char c) { return char(std::tolower(c)); }); if ((ext == ".mp3" || ext == ".wav") && e.is_regular_file(ec)) - out.push_back(e.path().string()); + out.push_back(utf8Path(e.path())); } std::ranges::sort(out); return out; @@ -313,10 +314,10 @@ namespace oc4::host if (it == loading.end()) { std::shared_ptr> bytes; - if (std::filesystem::path(file).is_absolute()) + if (pathFromUtf8(file).is_absolute()) { // (the player's own music, from their folder) - std::ifstream in(std::filesystem::path(file), std::ios::binary); + std::ifstream in(pathFromUtf8(file), std::ios::binary); if (!in) return cache[file] = nullptr; bytes = std::make_shared>(); diff --git a/src/core/FileUtil.cpp b/src/core/FileUtil.cpp index 2aeb43a7..fcae501f 100644 --- a/src/core/FileUtil.cpp +++ b/src/core/FileUtil.cpp @@ -32,6 +32,11 @@ namespace oc4 return std::string(s.begin(), s.end()); } + std::filesystem::path pathFromUtf8(const std::string& text) + { + return std::filesystem::path(std::u8string(text.begin(), text.end())); + } + std::string utf8GenericPath(const std::filesystem::path& path) { const std::u8string s = path.generic_u8string(); diff --git a/src/core/FileUtil.h b/src/core/FileUtil.h index 9f488836..558e324b 100644 --- a/src/core/FileUtil.h +++ b/src/core/FileUtil.h @@ -17,4 +17,6 @@ namespace oc4 // system). The game never refers to such names, so they only need not stop a scan. std::string utf8Path(const std::filesystem::path& path); std::string utf8GenericPath(const std::filesystem::path& path); + // A path from UTF-8 text (path(std::string) reads it in the system's code page on Windows). + std::filesystem::path pathFromUtf8(const std::string& text); } From 0a37f3f8ad2d9917858648a95c7c7b2778fc1b56 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 09:21:09 +0100 Subject: [PATCH 71/89] Options: profile names and folders as UTF-8; a profile file written whole Python 2's str(u'...') raised on a profile name or a music folder that isn't ASCII (the error only printed). They are kept as UTF-8 now, and the files are opened by their unicode names (Windows' wide calls, not the code page). A profile file and profile.ini are written beside themselves first and then moved over the old one, so a crash while writing leaves the old file. Tested with such a name and folder. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 72 +++++++++++++++++++++++-------- tests/options_other_test.py | 24 +++++++++++ 2 files changed, 78 insertions(+), 18 deletions(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 80ad6521..5dfbc50f 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -93,6 +93,46 @@ def _path(): return '' +try: + _unicode = unicode +except NameError: # (Python 3, as the tests run it: str is text) + _unicode = None + + +def _utf8(s): + """Text as UTF-8 bytes, as the profile keeps it (Python 2's str(u'...') fails on what isn't ASCII).""" + return s.encode('utf-8') if _unicode is not None and isinstance(s, _unicode) else str(s) + + +def _fs(path): + """A path as the file system calls take it: unicode, so that Windows opens it by its wide name, + not in the system's code page (bytes that aren't UTF-8 are left as they are).""" + if _unicode is None or isinstance(path, _unicode): + return path + try: + return path.decode('utf-8') + except UnicodeDecodeError: + return path + + +def _write(path, text): + """Writes the file whole or not at all: to a file beside it first, then over it (a crash while + writing leaves the old file).""" + path = _fs(path) + tmp = path + '.tmp' + f = open(tmp, 'w') + try: + f.write(text) + finally: + f.close() + try: + os.rename(tmp, path) + except OSError: + # (Windows: no rename over a file that is there) + os.remove(path) + os.rename(tmp, path) + + # The profile's form: 2 since the player options are the player's choices (before, the options # screen wrote every player option it had shown, those it had never read as off). _VERSION = 2 @@ -118,24 +158,24 @@ def _isGlobal(key): def _profilesDir(): - path = _path() - return os.path.join(os.path.dirname(path), 'Profiles') if path else '' + path = _fs(_path()) + return os.path.join(os.path.dirname(path), u'Profiles') if path else u'' def _fileName(name): """The profile's file (a name the file system cannot have: None).""" - name = str(name).strip() + name = _utf8(name).strip() if not name or name in ('.', '..') or [c for c in name if c in _BAD or ord(c) < 32]: return None folder = _profilesDir() - return os.path.join(folder, name + '.ini') if folder else None + return os.path.join(folder, _fs(name) + u'.ini') if folder else None def _profileNames(): """The profiles there are (their files'), sorted as the original lists them.""" folder = _profilesDir() try: - names = [f[:-4] for f in os.listdir(folder) if f.lower().endswith('.ini') and os.path.isfile(os.path.join(folder, f))] + names = [_utf8(f[:-4]) for f in os.listdir(folder) if f.lower().endswith('.ini') and os.path.isfile(os.path.join(folder, f))] except OSError: names = [] return sorted(names, key=lambda n: n.lower()) @@ -172,7 +212,7 @@ def _read(path, which, others=False): (key: value) without taking them.""" rest = {} try: - f = open(path, 'r') + f = open(_fs(path), 'r') except IOError: return rest version = 1 @@ -242,20 +282,16 @@ def _save(name=None): try: if not os.path.isdir(os.path.dirname(own)): os.makedirs(os.path.dirname(own)) - f = open(own, 'w') - f.write('\n'.join(['version=%d' % _VERSION] + [l for l in lines if not _isGlobal(l.split('=', 1)[0])]) + '\n') - f.close() + _write(own, '\n'.join(['version=%d' % _VERSION] + [l for l in lines if not _isGlobal(l.split('=', 1)[0])]) + '\n') ok = True except (IOError, OSError): pass if name == _profile['name']: _profile['UserProfile'] = name try: - f = open(path, 'w') - f.write('\n'.join(['version=%d' % _VERSION, 'UserProfile=%s' % _profile.get('UserProfile', '')] + + _write(path, '\n'.join(['version=%d' % _VERSION, 'UserProfile=%s' % _profile.get('UserProfile', '')] + [l for l in lines if _isGlobal(l.split('=', 1)[0])]) + '\n') - f.close() - except IOError: + except (IOError, OSError): pass return ok @@ -677,7 +713,7 @@ def folderChosen(path): except Exception: import traceback traceback.print_exc() - _profile['musicPath'] = path + _profile['musicPath'] = _utf8(path) _save() _applyVolumes() @@ -696,7 +732,7 @@ def __getattr__(self, name): # the profiles (Profiles/.ini): the Other tab's list, Create New Profile, Delete Profile def getProfileName(self): return _profile['name'] - def setProfileName(self, s): _profile['name'] = str(s) + def setProfileName(self, s): _profile['name'] = _utf8(s) def loadProfileFileNames(self): _names[:] = _profileNames() or [_profile['name']] def getNumProfileFiles(self): return len(_names) def getProfileFileName(self, i): @@ -713,7 +749,7 @@ def readFromFile(self, s): return False _resetProfile() _read(own, lambda key: not _isGlobal(key)) - _profile['name'] = str(s) + _profile['name'] = _utf8(s) _save() _clock['justOn'] = True _applyVolumes() @@ -723,7 +759,7 @@ def readFromFile(self, s): if toggles: toggles() return True - def writeToFile(self, s): return _save(str(s)) + def writeToFile(self, s): return _save(_utf8(s)) def deleteProfileFile(self, s): """Deletes the profile s's file; not the last one (a profile is always loaded).""" own = _fileName(s) @@ -827,7 +863,7 @@ def setPlayerOption(self, i, b): def getVolumeStops(self): return _VOLUME_STOPS def recalculateAudioSettings(self): _applyVolumes() def getMusicPath(self): return _profile['musicPath'] - def setMusicPath(self, s): _profile['musicPath'] = str(s); _save(); _applyVolumes() + def setMusicPath(self, s): _profile['musicPath'] = _utf8(s); _save(); _applyVolumes() def musicPathDialogBox(self): # (the system's folder dialog; the folder chosen comes back to folderChosen) try: diff --git a/tests/options_other_test.py b/tests/options_other_test.py index 5f6969bb..d3a5db9e 100644 --- a/tests/options_other_test.py +++ b/tests/options_other_test.py @@ -224,6 +224,30 @@ def main(): finally: shutil.rmtree(folder, ignore_errors=True) + # A profile and a music folder named in what isn't ASCII, in a folder so named: kept as UTF-8, + # written whole (no file left beside it). + folder = tempfile.mkdtemp(suffix=u'_J\u00f8rgen') + try: + host, options = start(folder) + profile = options._UserProfile() + name = u'\u6771\u4eac' + profile.setProfileName(name) + check(profile.writeToFile(name), "a profile named %r written" % name) + check(os.path.isfile(os.path.join(folder, u'Profiles', name + u'.ini')), "as Profiles/%s.ini" % name) + check(options._utf8(name) in [options._utf8(n) for n in listed(profile)], "and listed: %r" % listed(profile)) + check(profile.readFromFile(name), "and loaded") + music = os.path.join(folder, u'\u6771\u4eac musik') + profile.setMusicPath(music) + check(profile.getMusicPath() == options._utf8(music), "the music folder kept as UTF-8") + host, options = start(folder) + profile = options._UserProfile() + check(profile.getProfileName() == options._utf8(name) and profile.getMusicPath() == options._utf8(music), + "both read back after a restart: %r %r" % (profile.getProfileName(), profile.getMusicPath())) + left = [f for f in os.listdir(folder) + os.listdir(os.path.join(folder, u'Profiles')) if f.endswith(u'.tmp')] + check(not left, "no file left from writing: %r" % left) + finally: + shutil.rmtree(folder, ignore_errors=True) + if failures: print("options_other_test: %d failed" % len(failures)) return 1 From 651df8be5b059fc62fe5bdda712efbc5001c2675 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 09:21:09 +0100 Subject: [PATCH 72/89] Autosaves: none without a Documents folder; the settings behind a lock; one in 25 turns kept - No Documents folder found: no autosave. Before, the path was relative to the working directory, and autoSavesBeyond deleted the AutoSave_ files there. - The settings are set by the options' script and read on the game's thread: now through SharedAutoSaveSettings, behind a mutex. - OpenCiv4's own autosaves kept the turn-25 save only when the interval divided 25; now the first save in each 25 turns is kept (openciv4KeepsForGood, tested). - AutoSaves.h's comment without the date. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/AutoSaves.h | 33 +++++++++++++++++++++++++++++-- apps/oc4core/Screens.cpp | 2 +- apps/oc4core/Utility.h | 2 +- apps/oc4core/main.cpp | 19 ++++++++++++------ apps/oc4core/python/oc4options.py | 4 ++-- tests/auto_saves_test.cpp | 10 ++++++++++ 6 files changed, 58 insertions(+), 12 deletions(-) diff --git a/apps/oc4core/AutoSaves.h b/apps/oc4core/AutoSaves.h index c8c027f4..f1b50def 100644 --- a/apps/oc4core/AutoSaves.h +++ b/apps/oc4core/AutoSaves.h @@ -1,7 +1,7 @@ #pragma once // The game's autosaves as the original makes them (CivilizationIV.ini's AutoSaveInterval and // MaxAutoSaves; the options' OpenCiv4 tab), as seen in the running original under Wine -// (2026-11-22: interval 2, 3 kept, Saves\single\auto listed at each of 16 turns): the game's first +// (interval 2, 3 kept, Saves\single\auto listed at each of 16 turns): the game's first // turn as AutoSave_Initial_BC-4000, then at the start of every interval's turn (2, 4, 6, ...) // AutoSave_ (AutoSave_BC-3920); when one more than the number kept is written, the oldest // AutoSave_ goes. The initial save doesn't count and stays. Interval 0: none, as the ini's @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -22,7 +23,27 @@ namespace oc4::host struct AutoSaveSettings { int interval = 4, kept = 5; // (the ini's defaults; interval 0: no autosaves) - bool openciv4 = false; // openciv4's own (My Games\openciv4\Saves\auto, every 25th turn kept) + bool openciv4 = false; // openciv4's own (My Games\openciv4\Saves\auto, one in 25 turns kept) + }; + + // The settings as the options' script sets them and the game's thread reads them. + class SharedAutoSaveSettings + { + public: + void set(const AutoSaveSettings& how) + { + std::lock_guard lock(m_mutex); + m_how = how; + } + AutoSaveSettings get() const + { + std::lock_guard lock(m_mutex); + return m_how; + } + + private: + mutable std::mutex m_mutex; + AutoSaveSettings m_how; }; // Whether the game saves at this turn's start (the game's first: its initial save). @@ -44,6 +65,14 @@ namespace oc4::host return std::format(L"{}_{}.CivBeyondSwordSave", stem, turn / std::max(1, how.interval) % std::max(1, how.kept)); } + // openciv4's own: whether this turn's save is also kept for good, the first save in each 25 turns + // (turn 25, 50, ... when the interval divides it; else the first save after each). + inline bool openciv4KeepsForGood(const AutoSaveSettings& how, int turn) + { + const int every = std::max(1, how.interval); + return turn > 0 && turn / 25 != (turn - every) / 25; + } + // The AutoSave_ saves in the folder beyond the newest kept ones (the oldest first to go); // not the initial save, nor any other file. inline std::vector autoSavesBeyond(const std::filesystem::path& folder, int kept) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 287c326f..c7d88c3c 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -550,7 +550,7 @@ namespace oc4::host bool openciv4AutoSaves, int maxFrameRate) { ui.noTechSplashOption = noTechSplash; ui.noEventMessages = noEventMessages; - utility.engine().autoSave = { std::max(0, autoSaveInterval), std::max(1, autoSavesKept), openciv4AutoSaves }; + utility.engine().autoSave.set({ std::max(0, autoSaveInterval), std::max(1, autoSavesKept), openciv4AutoSaves }); utility.engine().maxFrameRate = std::max(0, maxFrameRate); }); host.def("movie_playable", [&utility](const std::string& file) { diff --git a/apps/oc4core/Utility.h b/apps/oc4core/Utility.h index 996c6dee..5f7c01d9 100644 --- a/apps/oc4core/Utility.h +++ b/apps/oc4core/Utility.h @@ -61,7 +61,7 @@ namespace oc4::host } std::function onAutoSave; // How it saves (AutoSaves.h; the options' OpenCiv4 tab). - AutoSaveSettings autoSave; + SharedAutoSaveSettings autoSave; // At most this many frames a second (the ini's SetMaxFrameRate; 0: as many as the display shows). std::atomic maxFrameRate = 0; diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 84c669f9..5ac97fc1 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -909,22 +909,29 @@ namespace // (AutoSaves.h, the options' OpenCiv4 tab); a scripted game is not. if (opt.viewSeconds <= 0) utility.engine().onAutoSave = [&session, &game, &engine = utility.engine()](bool initial) { - const host::AutoSaveSettings how = engine.autoSave; + const host::AutoSaveSettings how = engine.autoSave.get(); const int turn = game.getGameTurn(); if (!host::autoSaveDue(how, turn, initial)) return; + // (no Documents folder: no autosave, rather than one beside the working directory) + const fs::path documents = documentsFolder(); + if (documents.empty()) + { + std::printf(" autosave skipped: no Documents folder\n"); + return; + } const auto save = [&](const fs::path& folder, const fs::path& path) { fs::create_directories(folder); session.saveGame(path); - std::printf(" autosaved turn %d: %s\n", turn, path.string().c_str()); + std::printf(" autosaved turn %d: %s\n", turn, utf8Path(path).c_str()); }; try { if (how.openciv4) { // (Documents\My Games\openciv4\Saves\auto; the active civilization and the - // game's map seed in the name, every 25th turn kept for good) - const fs::path folder = documentsFolder() / L"My Games" / L"openciv4" / L"Saves" / L"auto"; + // game's map seed in the name, one save in 25 turns kept for good) + const fs::path folder = documents / L"My Games" / L"openciv4" / L"Saves" / L"auto"; std::wstring civ; if (const PlayerTypes active = game.getActivePlayer(); active != NO_PLAYER) for (const wchar_t c : std::wstring(GC.getInitCore().getCivShortDesc(active).GetCString())) @@ -932,11 +939,11 @@ namespace const std::wstring stem = std::format(L"AutoSave_{}_{:08X}", civ, GC.getInitCore().getMapRandSeed()); const fs::path path = folder / host::openciv4AutoSaveName(stem, how, turn); save(folder, path); - if (turn % 25 == 0) + if (host::openciv4KeepsForGood(how, turn)) fs::copy_file(path, folder / std::format(L"{}_turn{}.CivBeyondSwordSave", stem, turn), fs::copy_options::overwrite_existing); return; } - const fs::path folder = documentsFolder() / L"My Games" / L"Beyond the Sword" / L"Saves" / L"single" / L"auto"; + const fs::path folder = documents / L"My Games" / L"Beyond the Sword" / L"Saves" / L"single" / L"auto"; // (the year through the scripts' CyGame: the game core does not export getGameTurnYear) int year; { diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 5dfbc50f..8f56c040 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -1078,10 +1078,10 @@ def _attachIniOptions(self, parent): ('autoSavesKept', u'Keep', u'autosaves', u'The oldest autosaves beyond this many are deleted (the ini\'s MaxAutoSaves, 5).')): self._attachNumber(parent, key, before, after, tip) - self.attachCheckBox(parent, OPENCIV4_AUTOSAVES_CHECKBOX, u'OpenCiv4\'s autosaves: each game its own, every 25th turn kept', + self.attachCheckBox(parent, OPENCIV4_AUTOSAVES_CHECKBOX, u'OpenCiv4\'s autosaves: each game its own, one in 25 turns kept', 'oc4options', 'handleIniFlagClicked', 'openciv4AutoSaves', _profile['openciv4AutoSaves']) self.setToolTip(OPENCIV4_AUTOSAVES_CHECKBOX, u'Autosaves go to My Games\\openciv4\\Saves\\auto, named by the civilization ' - u'and the map, the kept ones in turn, and every 25th turn\'s is kept for good. Autosave every 1 turn and keep 10 ' + u'and the map, the kept ones in turn, and one save in each 25 turns is kept for good. Autosave every 1 turn and keep 10 ' u'is how OpenCiv4 saved before.') for key, before, after, tip in ( ('fieldOfView', u'Field of view', u'degrees (0: the game\'s, 42)', diff --git a/tests/auto_saves_test.cpp b/tests/auto_saves_test.cpp index 73fe676f..fd848021 100644 --- a/tests/auto_saves_test.cpp +++ b/tests/auto_saves_test.cpp @@ -42,6 +42,16 @@ int main() check(openciv4AutoSaveName(L"AutoSave_Rome_1", { 1, 10, true }, 23) == L"AutoSave_Rome_1_3.CivBeyondSwordSave", "openciv4's, slot 3"); check(openciv4AutoSaveName(L"AutoSave_Rome_1", { 4, 5, true }, 24) == L"AutoSave_Rome_1_1.CivBeyondSwordSave", "openciv4's, every 4th, 5 kept"); + // openciv4's own kept for good: one save in each 25 turns, whatever the interval. + check(openciv4KeepsForGood({ 1, 10, true }, 25) && !openciv4KeepsForGood({ 1, 10, true }, 24) && !openciv4KeepsForGood({ 1, 10, true }, 26), + "every turn: turn 25 kept"); + check(openciv4KeepsForGood({ 5, 5, true }, 50) && !openciv4KeepsForGood({ 5, 5, true }, 45) && !openciv4KeepsForGood({ 5, 5, true }, 55), + "every 5th: turn 50 kept"); + check(openciv4KeepsForGood({ 4, 5, true }, 28) && !openciv4KeepsForGood({ 4, 5, true }, 24) && !openciv4KeepsForGood({ 4, 5, true }, 32) + && openciv4KeepsForGood({ 4, 5, true }, 52) && openciv4KeepsForGood({ 4, 5, true }, 100), + "every 4th: 28, 52, 76, 100 kept (the first after each 25th)"); + check(!openciv4KeepsForGood({ 4, 5, true }, 0), "not the game's first turn"); + // The oldest AutoSave_ beyond the kept go; the initial save and other files stay (as seen: // with 3 kept, the 4th AutoSave_ takes the oldest, AutoSave_Initial_ stays). const fs::path folder = fs::temp_directory_path() / "oc4_auto_saves_test"; From b7aede1413a6c71bbade038352242db4860cf1e5 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 09:21:09 +0100 Subject: [PATCH 73/89] README: the player options go to the profile's own file Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 780316e2..149e3e95 100644 --- a/README.md +++ b/README.md @@ -209,8 +209,8 @@ edge" on the options' OpenCiv4 tab turns it off (on by default). It is kept in p never edge scroll). The rule is `src/render/EdgeScroll.h`, tested by `tests/edge_scroll_test.cpp`. The player options (Options → Game: Wait at End of Turn, Quick Combat, …) are kept in the player's -profile, as the original keeps them in its own (`Profiles\.pfl`): a choice is written to -profile.ini at once (`player.N=`), and every game, new or loaded, starts with the profile's, which +profile, as the original keeps them in its own (`Profiles\.pfl`): a choice is written at +once to the profile's file (`Profiles/.ini` beside profile.ini, `player.N=`), and every game, new or loaded, starts with the profile's, which the game core sends to the active player (a save's own options are overwritten, as in the original). OpenCiv4's own options (W A S D, idle turns, edge scrolling) are on a tab of their own, OpenCiv4, after the original's four. Tested by `tests/player_options_test.py`. From c1567173fab1fccedd74c99ed658be472d36ff34 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 09:21:55 +0100 Subject: [PATCH 74/89] Comments: their sources without dates, no change history Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 7 +++---- tests/auto_saves_test.cpp | 2 +- tests/minimap_toggles_test.py | 2 +- tests/options_other_test.py | 2 +- tests/player_options_test.py | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 8f56c040..4cab6da1 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -626,10 +626,9 @@ def _playerDefault(i): return False -# What the original's Graphics Level sets (Civ4BeyondSword.exe, CyUserProfile.setGraphicsLevel, -# measured in Wine 2026-11-21): the graphic options it switches on and off, the render, globe and -# movie quality (0 high, 1 medium, 2 low) and the anti-aliasing (an index into 0, 2, 4, 8 samples; -# None: as it is). +# What the original's Graphics Level sets (CyUserProfile.setGraphicsLevel, measured in Wine): the +# graphic options it switches on and off, the render, globe and movie quality (0 high, 1 medium, +# 2 low) and the anti-aliasing (an index into 0, 2, 4, 8 samples; None: as it is). _LEVEL_PRESETS = { 0: ((), ('SINGLE_UNIT_GRAPHICS', 'FROZEN_ANIMATIONS', 'EFFECTS_DISABLED', 'GLOBE_VIEW_BUILDINGS_DISABLED', 'LOWRES_TEXTURES'), 0, None), 1: (('SINGLE_UNIT_GRAPHICS', 'GLOBE_VIEW_BUILDINGS_DISABLED'), ('FROZEN_ANIMATIONS', 'EFFECTS_DISABLED', 'LOWRES_TEXTURES'), 1, 1), diff --git a/tests/auto_saves_test.cpp b/tests/auto_saves_test.cpp index fd848021..6c8366ad 100644 --- a/tests/auto_saves_test.cpp +++ b/tests/auto_saves_test.cpp @@ -38,7 +38,7 @@ int main() check(autoSaveName(false, -3840) == L"AutoSave_BC-3840.CivBeyondSwordSave", "a BC year"); check(autoSaveName(false, 1250) == L"AutoSave_AD-1250.CivBeyondSwordSave", "an AD year (not seen: written as a BC one)"); - // openciv4's own: the kept ones in turn (every turn, 10 kept: as before the option). + // openciv4's own: the kept ones in turn (every turn, 10 kept). check(openciv4AutoSaveName(L"AutoSave_Rome_1", { 1, 10, true }, 23) == L"AutoSave_Rome_1_3.CivBeyondSwordSave", "openciv4's, slot 3"); check(openciv4AutoSaveName(L"AutoSave_Rome_1", { 4, 5, true }, 24) == L"AutoSave_Rome_1_1.CivBeyondSwordSave", "openciv4's, every 4th, 5 kept"); diff --git a/tests/minimap_toggles_test.py b/tests/minimap_toggles_test.py index 64e5f3f1..3c4f1b1d 100644 --- a/tests/minimap_toggles_test.py +++ b/tests/minimap_toggles_test.py @@ -122,7 +122,7 @@ def main(): # The other options are kept beside them. check({'scores=0', 'edgeScroll=1'} <= profileLines(folder), "the rest of the profile is kept") - # A profile written before this change (no toggle keys, no profiles folder): the defaults. + # A profile with no toggle keys and no profiles folder: the defaults. shutil.rmtree(os.path.join(folder, 'Profiles'), ignore_errors=True) with open(os.path.join(folder, 'profile.ini'), 'w') as f: f.write('name=openciv4\nclock=1\n') diff --git a/tests/options_other_test.py b/tests/options_other_test.py index d3a5db9e..8c45a0a8 100644 --- a/tests/options_other_test.py +++ b/tests/options_other_test.py @@ -1,5 +1,5 @@ # Checks the options' Other tab (apps/oc4core/python/oc4options.py) against what the original does -# (measured in the Wine game, 2026-11-21, docs/options-other.md): +# (measured in the Wine game, docs/options-other.md): # - profiles: one file each (Profiles/.ini beside profile.ini, the original's Profiles\.pfl), # the loaded one named in profile.ini (the original's CivilizationIV.ini UserProfile); Create New # Profile writes the options under the new name and loads it, the drop-down loads another (its diff --git a/tests/player_options_test.py b/tests/player_options_test.py index fee22571..e591f4ee 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -199,7 +199,7 @@ def main(): profile = options._UserProfile() check(profile.getPlayerOption(2) and not profile.getPlayerOption(6), "defaults kept after a restart") - # A profile written before this change: the XML's defaults, the rest kept. + # A profile with no player options in it: the XML's defaults, the rest kept. with open(os.path.join(folder, 'profile.ini'), 'w') as f: f.write('name=openciv4\nedgeScroll=0\n') host, options = start(folder) From 8ba2c8a7c35ef7e8fe5fe8016789fab6c36dbc9d Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 09:22:11 +0100 Subject: [PATCH 75/89] Comments: their sources without dates or backlog numbers Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 8 ++++---- src/render/DoubleClick.h | 4 ++-- src/render/UiLayer.cpp | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index eb0b667a..23127de0 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1516,11 +1516,11 @@ namespace // (the units there are in the plot list then), one click on the bar selects the city // (what it builds in the bottom panel); one click on its plot is any plot's (its // units). One click on one of the figures in it is, as anywhere, its unit's; a double - // click there opens the city too (Wine, backlog #46). OpenCiv4's option opens the + // click there opens the city too (Wine). OpenCiv4's option opens the // screen with one click on the city or its bar. // The first click of a double click is a click (it selects the units there); the city's - // screen then opens with the units selected before it, the ones Esc gives back (Wine, - // backlog #46: on its plot, its bar or a figure in it). + // screen then opens with the units selected before it, the ones Esc gives back (Wine: + // on its plot, its bar or a figure in it). CvCity* ownCity = plot->getPlotCity() && plot->getPlotCity()->getOwner() == me ? plot->getPlotCity() : nullptr; const auto before = std::exchange(selectedBeforeClick, std::nullopt); if (!click.right && !click.twice) @@ -1563,7 +1563,7 @@ namespace else ui.clearSelectionList(); // (as the original's: the camera goes to the plot clicked, a unit there or not, but - // not to one's own city, its plot or a figure in it (Wine, backlog #46: so a double + // not to one's own city, its plot or a figure in it (Wine: so a double // click's second click lands where the first did); a scripted game told where to // look keeps looking there) if (!ownCity && (opt.lookX < 0 || opt.viewSeconds <= 0 || std::getenv("OC4_FOLLOW_CAMERA"))) diff --git a/src/render/DoubleClick.h b/src/render/DoubleClick.h index f91881be..b8fdf183 100644 --- a/src/render/DoubleClick.h +++ b/src/render/DoubleClick.h @@ -3,8 +3,8 @@ #include #include -// The mouse's double click on the map, as forgiving as the original's (BtS under Wine, measured -// 2026-11-21, backlog #46: a second press up to ~480 ms after the first opens one's city, 550 ms +// The mouse's double click on the map, as forgiving as the original's (BtS under Wine, measured: +// a second press up to ~480 ms after the first opens one's city, 550 ms // does not, as Windows' 500 ms). The time is the presses' own (the system's event times), not // when a frame gets round to them, so a slow frame after the first click cannot split a double // click. The original lets the mouse move 1 point between the presses; this lets it move a few diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index 690eec25..d8ef5b27 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -412,7 +412,7 @@ namespace oc4::render void UiLayer::drawListButton(Overlay& o, const Item& it, bool hot, bool pressed, double clock) { - // As the original draws a multi list's button (measured in Wine, BUG + BULL, 2026-11-20): its + // As the original draws a multi list's button (measured in Wine, BUG + BULL): its // picture whole, the ring over its edge in the HUDBorder colour; under the mouse the fill // glow added (+57 of 255: its inside, the ring, and a soft edge just outside); pressed, a // blue fill half over that; disabled, half way to black (its own picture, the one From a2bc2d7e1151fbf6aaca41d5c35e3b56488d2e6a Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 09:25:25 +0100 Subject: [PATCH 76/89] Play: the mouse buttons seen, the outlined plot and a pick's press kept per game They were static locals in runPlay and so outlived the game: a game loaded from the menu began with the last one's. Now they live with runPlay's other state. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 7ab8f18a..e87a8099 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -778,6 +778,9 @@ namespace std::vector actionIds; // the action of each button the window shows std::optional> pathShown; // where the way the window shows leads std::optional> selectedBeforeClick; // (the units selected before the last left click on the map) + bool heldSeen[2] = {}; // (the mouse buttons a frame saw held, for the scripts' isLeftMouseDown, ...) + std::tuple highlighted{ -2, -2, -2 }; // (the plot the interface mode outlines, and the mode) + bool pickPress = false; // (a press begun while a script picks a plot, still held) std::pair pathFrom{}; // (the unit it starts from and its plot: the gamepad's plot cursor shows it all the while) std::tuple coloredFor{}; // what was selected when the plots were last coloured uint64_t marksShown = ~0ull; // the marks the window has @@ -1416,7 +1419,6 @@ namespace // frame, so that it is seen once. if (!ui.worldBuilder() && !opt.ownInterface) { - static bool heldSeen[2] = {}; const auto [hx, hy] = window.hoveredPlot(); ui.mouseOverMap = hx >= 0 && window.uiHovered() < 0; int px = ui.mouseOverMap ? hx : ui.mouseX, py = ui.mouseOverMap ? hy : ui.mouseY; @@ -1448,7 +1450,6 @@ namespace // the units can't go; none where it isn't known or the script can't pick it), as the // WorldBuilder's brush (Wine: BUG's dot map editor, a green plot under the mouse, backlog #68). // Asked again only when the mode or the plot changes (pick plot asks the scripts). - static std::tuple highlighted{ -2, -2, -2 }; if (ui.worldBuilder()) highlighted = { -2, -2, -2 }; // (the WorldBuilder's brush is drawn in that layer meanwhile) else @@ -1683,7 +1684,6 @@ namespace // None while a script picks a plot (BUG's dot map editor, whose right button takes a city // away): there the original shows no way to it, neither with the button held nor for a // press begun in that mode and still held after the mode ends (backlog #68). - static bool pickPress = false; std::optional> pointed = playing ? window.pathTarget() : std::nullopt; if (!pointed) pickPress = false; From 5d518bc668b4e0cd4bc1cc1e7134bdad53d9d1b4 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 09:25:35 +0100 Subject: [PATCH 77/89] Pick plot: a left click picks the plot for the scripts (onPlotPicked) and ends the mode In INTERFACEMODE_PYTHON_PICK_PLOT a left click did nothing, so a mod other than BUG's dot map stayed in the mode for good. A left click on a plot the scripts can pick (the game core's highlight colour: revealed, canPickPlot) now ends the mode and reports the plot (CvEventReporter::plotPicked, the scripts' onPlotPicked); a right click ends it, as before. Why the original ends it: the shipped mod Gods of Old sets the mode for its prophets and never ends it itself (its CvMainInterface.py, CvEventManager.py onPlotPicked). BUG's dot map editor reads the mouse itself and sets the mode again after each click (CvDotMapOverlayScreen.resetInterfaceMode), later in the same frame, so it stays in the mode as in Wine. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index e87a8099..19c90550 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -77,6 +77,7 @@ #include "CvGameCoreDLL.h" #include "CvArtFileMgr.h" +#include "CvEventReporter.h" #include "CvGameAI.h" #include "CvPopupInfo.h" #include "CvGameTextMgr.h" @@ -1558,16 +1559,24 @@ namespace click.right = ui.getInterfaceMode() == INTERFACEMODE_SELECTION && head && !own; } // The interface mode wants a plot: its mission there (a right click leaves it). - // Python's pick plot is the script's: it reads the mouse itself (BUG's dot map editor - // places a city with the left button, takes one away with the right), so a left click - // leaves it on and the selected units get no order, as the original's (Wine, backlog #68). + // Python's pick plot is the scripts': a left click on a plot they can pick (the game + // core's highlight colour for it: revealed, CvGameInterface.canPickPlot) ends the mode + // and gives them the plot (CvEventReporter::plotPicked, their onPlotPicked), as the + // shipped mods' scripts expect (Gods of Old's prophets set the mode and never end it); + // the selected units get no order. BUG's dot map editor reads the mouse itself (a city + // placed with the left button, taken away with the right) and sets the mode again + // after each click, later in the frame (its screen's update), so it stays on there, as + // in the original under Wine. if (const InterfaceModeTypes mode = ui.getInterfaceMode(); mode == INTERFACEMODE_PYTHON_PICK_PLOT) { + const bool pick = !click.right && game.getPlotHighlightColor(plot) != NO_COLOR; if (log) std::printf(" %s at %d,%d: %s\n", GC.getInterfaceModeInfo(mode).getType(), plot->getX(), plot->getY(), - click.right ? "cancelled" : "the script's"); - if (click.right) + click.right ? "cancelled" : pick ? "picked" : "not to be picked"); + if (click.right || pick) ui.setInterfaceMode(INTERFACEMODE_SELECTION); + if (pick) + CvEventReporter::getInstance().plotPicked(plot); continue; } else if (mode != INTERFACEMODE_SELECTION) From 990e5ef816e3694ea1599d3bc6bc6b6e1d125c29 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 09:25:35 +0100 Subject: [PATCH 78/89] Comments: no backlog numbers or dates Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 4 ++-- apps/oc4core/python/oc4screens.py | 2 +- apps/oc4core/python/oc4wb.py | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 19c90550..82227664 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -1449,7 +1449,7 @@ namespace // bHighlightPlot: Python's pick plot, ping, sign, the air missions), in the game core's // colour for it (CvGame::getNewHighlightPlot, getPlotHighlightColor: green; dark grey where // the units can't go; none where it isn't known or the script can't pick it), as the - // WorldBuilder's brush (Wine: BUG's dot map editor, a green plot under the mouse, backlog #68). + // WorldBuilder's brush (Wine: BUG's dot map editor, a green plot under the mouse). // Asked again only when the mode or the plot changes (pick plot asks the scripts). if (ui.worldBuilder()) highlighted = { -2, -2, -2 }; // (the WorldBuilder's brush is drawn in that layer meanwhile) @@ -1692,7 +1692,7 @@ namespace pathHead && pathHead->getOwner() == me); // None while a script picks a plot (BUG's dot map editor, whose right button takes a city // away): there the original shows no way to it, neither with the button held nor for a - // press begun in that mode and still held after the mode ends (backlog #68). + // press begun in that mode and still held after the mode ends. std::optional> pointed = playing ? window.pathTarget() : std::nullopt; if (!pointed) pickPress = false; diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 8d54923a..a0e6d6da 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -2834,7 +2834,7 @@ def addColoredPlot(self, iX, iY, color, ePlotStyle, eLayer=None): # (the Alt forms: a colour by its name, at the alpha given, which stands in for the colour's own, # as the original's: BUG's dot map draws a city not yet given a colour in COLOR_CLEAR, white of - # alpha 0, at alpha 1, and the Wine game shows it white, full (backlog #68)) + # alpha 0, at alpha 1, and the Wine game shows it white, full) def addColoredPlotAlt(self, iX, iY, ePlotStyle, eLayer, szColor, fAlpha): c = _namedColor(szColor) if c is not None: diff --git a/apps/oc4core/python/oc4wb.py b/apps/oc4core/python/oc4wb.py index 1a4891f5..4e562528 100644 --- a/apps/oc4core/python/oc4wb.py +++ b/apps/oc4core/python/oc4wb.py @@ -749,8 +749,8 @@ def widgetClicked(widget, iData1, iData2): def widgetHelp(widget, iData1, iData2): """The help the original shows for the WorldBuilder's own buttons (WIDGET_WB_...); u'' for any - other widget. Each was seen in the running original under Wine (2026-11-22: every button hovered) - and is the game's text that says exactly that. Where two keys say the same in English (Save, + other widget. Each was seen in the running original under Wine (every button hovered) and is the + game's text that says exactly that. Where two keys say the same in English (Save, Load, Player Mode, Map Mode) the one named for the button or its action is used; the screen can't tell them apart.""" W = _cpe.WidgetTypes From 651060893373cc10d7dd1b2f062b7e6e6c7a97c2 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 10:00:09 +0100 Subject: [PATCH 79/89] World Builder: clicking the cut tab moves the strip a tab on, as the original's Seen in Wine at 1600 x 900 (BUG, map mode): clicking the cut-off Terrains tab selects it and moves the strip one tab, so Bonuses, Terrains and Territory show whole and > turns grey. One click on > or < moves the strip one tab, as before. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4wb.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/oc4core/python/oc4wb.py b/apps/oc4core/python/oc4wb.py index 4e562528..91468fa0 100644 --- a/apps/oc4core/python/oc4wb.py +++ b/apps/oc4core/python/oc4wb.py @@ -472,7 +472,8 @@ def _draw(): # (the cut one's skin narrowed to the room left, its end showing; its word cut there) screen.addPanel(tab, u'', u'', True, False, x, _WY + _TAB_Y, cut - x if part else tw, _TAB_H, _cpe.PanelStyles.PANEL_STYLE_MAIN) _style(screen, tab, _TAB_SKIN + ('Select' if i == ctrl.active else 'Default')) - word = _add('OC4WBTab%d' % i, ('tab', ctrl, i)) + # (clicking the cut one also moves the strip a tab on, as seen in Wine: Terrains then whole) + word = _add('OC4WBTab%d' % i, ('tab', ctrl, i, part)) screen.setText(word, 'Background', dark + name + u'', 1 << 2, x + tw / 2, _WY + _TAB_Y + 4, -0.3, _cpe.FontTypes.GAME_FONT, general, -1, -1) w = screen._s.get(word) @@ -686,6 +687,8 @@ def handleInput(argsList): what = choice[0] if what == 'tab': choice[1].active = choice[2] + if len(choice) > 3 and choice[3]: + choice[1].tabFirst = getattr(choice[1], 'tabFirst', 0) + 1 elif what == 'tabscroll': ctrl = choice[1] ctrl.tabFirst = max(0, min(choice[3] - 1, getattr(ctrl, 'tabFirst', 0) + choice[2])) From dbe00780e349624681ed3acfb93fae7c44693a21 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 10:12:33 +0100 Subject: [PATCH 80/89] Options: profile files read and written as UTF-8, not the system's code page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Windows, Python 3's text-mode open() uses cp1252, so writing a profile named 東京 raised UnicodeEncodeError (windows-x64 CI, options_other). The files are now opened in binary mode with the text encoded as UTF-8, and read back the same way, under the game's Python 2.7 and the tests' Python 3 alike. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 4cab6da1..1f41f7ff 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -115,14 +115,25 @@ def _fs(path): return path +def _bytes(text): + """Text as the files keep it: UTF-8, whatever the system's code page.""" + return text if _unicode is not None and not isinstance(text, _unicode) else text.encode('utf-8') + + +def _textLine(line): + """A line read from a file (bytes) as the profile keeps text: Python 2's UTF-8 str as it is, + Python 3's str decoded.""" + return line if _unicode is not None else line.decode('utf-8', 'replace') + + def _write(path, text): """Writes the file whole or not at all: to a file beside it first, then over it (a crash while - writing leaves the old file).""" + writing leaves the old file). In UTF-8, not the system's code page.""" path = _fs(path) tmp = path + '.tmp' - f = open(tmp, 'w') + f = open(tmp, 'wb') try: - f.write(text) + f.write(_bytes(text)) finally: f.close() try: @@ -212,13 +223,14 @@ def _read(path, which, others=False): (key: value) without taking them.""" rest = {} try: - f = open(_fs(path), 'r') + f = open(_fs(path), 'rb') except IOError: return rest version = 1 player = False try: for line in f: + line = _textLine(line) if '=' not in line: continue key, value = line.strip().split('=', 1) From f3eb0233ae83fbfb7d7db0da19cbc1345622bdc9 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 16:24:39 +0100 Subject: [PATCH 81/89] City screen: the selected units stay selected under it, as the original's Selecting a city let go of the selected units and selected them again when its screen closed. The original keeps them: with a warrior selected, CyInterface().selectCity opens Roma's screen and the warrior is still the head of the selection (seen in Wine, BtS 3.19). selectCity now leaves the selection as it is, and the saved list and its restore are gone. The units take no orders under the screen: CvGame::canHandleAction refuses a unit's action while a city is selected (its "XXX hack!"), which also keeps their buttons off the bottom panel, and the screen's clicks already go to the city (CvGame::handleCityScreenPlot*Picked). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Interface.cpp | 24 ++++-------------------- apps/oc4core/Interface.h | 1 - 2 files changed, 4 insertions(+), 21 deletions(-) diff --git a/apps/oc4core/Interface.cpp b/apps/oc4core/Interface.cpp index 7f25d5f6..9453cef7 100644 --- a/apps/oc4core/Interface.cpp +++ b/apps/oc4core/Interface.cpp @@ -839,17 +839,6 @@ namespace oc4::host if (CvCity* c = cityOf(id); c && c->getOwner() == id.eOwner) c->updateSelectedCity(true); m_citiesShown.clear(); - // The units selected before the screen opened are selected again (those still there and - // the player's), as the original keeps them; the game core picks the next one only if - // none is left. - if (m_selection.getLength() == 0) - for (const IDInfo& id : m_selectionUnderCity) - if (CvUnit* u = unitOf(id); u && u->getOwner() == GC.getGame().getActivePlayer() && !selected(u)) - { - m_selection.insertAtEnd(id); - m_lastSelected = u; - } - m_selectionUnderCity.clear(); } // (the coloured plots too: the city's worked plots are circled only while its screen is up, // and the city may have been selected already, by the first click of a double click on its @@ -868,15 +857,10 @@ namespace oc4::host if (pNewValue) { leaveInterfaceMode(); // (as the original's: a city selected ends Go To) - // A city's screen and selected units go not together: the units are let go (as - // CvGame::selectUnit lets go of the cities), and selected again when the screen closes. - if (!wasUp) - { - m_selectionUnderCity.clear(); - for (CLLNode* n = m_selection.head(); n; n = m_selection.next(n)) - m_selectionUnderCity.push_back(n->m_data); - } - m_selection.clear(); + // The selected units stay selected under the city's screen, as the original's (seen in + // Wine: CyInterface().selectCity with a warrior selected, its head still the warrior). + // They take no orders there: CvGame::canHandleAction refuses a unit's action while a + // city is selected, and the screen's clicks are the city's (main.cpp). m_cities.insertAtEnd(pNewValue->getIDInfo()); m_cityScreen = true; lookAtX = pNewValue->getX(); diff --git a/apps/oc4core/Interface.h b/apps/oc4core/Interface.h index 229b1276..82db2984 100644 --- a/apps/oc4core/Interface.h +++ b/apps/oc4core/Interface.h @@ -417,7 +417,6 @@ namespace oc4::host InterfaceVisibility m_showBeforeWorldBuilder = INTERFACE_SHOW; CLinkList m_cities; std::vector m_citiesShown; // (asked for production when the city screen closes, if idle) - std::vector m_selectionUnderCity; // the units selected when the city screen opened: selected again when it closes bool m_cityScreen = false; void selectionChanged(); // (the dirty bits a new selection sets) void cityScreenChanged(bool wasUp); // (what the main interface hides in the city screen is redrawn) From f10551fe580a8573c2de91967e248549677c65d2 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 16:50:24 +0100 Subject: [PATCH 82/89] City screen: the numpad's moves don't move the units kept under it Since the selected units stay selected under the city screen, the numpad's digits moved them there: the host moves the head unit itself (selectionListMove), past CvGame::canHandleAction, which refuses the units' actions while a city is selected. In the original the numpad does nothing on the city screen opened with a unit selected, and after Esc the unit is still selected and moves (seen in Wine, batch 3). Under the city screen the numpad's digits now do nothing. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/main.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/oc4core/main.cpp b/apps/oc4core/main.cpp index 23127de0..c3550ed9 100644 --- a/apps/oc4core/main.cpp +++ b/apps/oc4core/main.cpp @@ -870,6 +870,11 @@ namespace if (!k.shift && !k.ctrl && !k.alt && k.key > render::key::Numpad0 && k.key <= render::key::Numpad9 && k.key != render::key::Numpad0 + 5) if (CvUnit* unit = ui.getHeadSelectedUnit()) { + // (not under the city screen: the units stay selected there but take no orders, as + // the original's, seen in Wine; the game core refuses their actions while a city is + // selected, CvGame::canHandleAction, and this move is the host's own) + if (ui.isCityScreenUp()) + return; const int d = int(k.key - render::key::Numpad0) - 1; if (CvPlot* to = plotXY(unit->getX(), unit->getY(), d % 3 - 1, d / 3 - 1)) { From cab2a87350167601f9d19e90f64e0b99ed80b8e6 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 19:35:01 +0100 Subject: [PATCH 83/89] Options: each OpenCiv4 option goes to the host on its own At the start, _applyGraphics sent the profile's options to the host in one try. This bundle's host has no set_city_one_click (it comes with the city double click), so the call failed there and Keep attacker and Quick enemy moves from profile.ini never reached the host until the options screen set them. Each call now has its own try, so a host without one of them still gets the rest. player_options_test: a host without set_city_one_click still gets the options after it. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 22 +++++++++++++-------- tests/player_options_test.py | 33 +++++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index 1f41f7ff..ff761ae5 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -336,14 +336,20 @@ def _applyGraphics(): oc4host.reset_graphic_options() for i, on in _profile['graphic'].items(): oc4host.set_graphic_option(int(i), bool(on)) - oc4host.set_ui_scale(_profile['uiScale']) - oc4host.set_graphic_levels(_profile['movieQuality'], _AA_SAMPLES[min(max(_profile['antiAliasing'], 0), len(_AA_SAMPLES) - 1)]) - _applyPlayerOptions() - oc4host.set_wasd_pan(_profile['wasdPan']) - oc4host.set_auto_end_turn(_profile['autoEndTurn']) - oc4host.set_edge_scroll(_profile['edgeScroll']) - oc4host.set_city_one_click(_profile['cityOneClick']) - oc4host.set_keep_attacker(_profile['keepAttacker']) + except Exception: + pass + _applyPlayerOptions() + # (each on its own: a host without one of them, or one that fails, still gets the rest) + for call, args in (('set_ui_scale', (_profile['uiScale'],)), + ('set_graphic_levels', (_profile['movieQuality'], _AA_SAMPLES[min(max(_profile['antiAliasing'], 0), len(_AA_SAMPLES) - 1)])), + ('set_wasd_pan', (_profile['wasdPan'],)), ('set_auto_end_turn', (_profile['autoEndTurn'],)), + ('set_edge_scroll', (_profile['edgeScroll'],)), ('set_city_one_click', (_profile['cityOneClick'],)), + ('set_keep_attacker', (_profile['keepAttacker'],))): + try: + getattr(oc4host, call)(*args) + except Exception: + pass + try: oc4host.set_quick_enemy_moves(_profile['quickEnemyMoves']) except Exception: pass diff --git a/tests/player_options_test.py b/tests/player_options_test.py index e591f4ee..6a1a8672 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -64,6 +64,28 @@ def player_option_state(self, i): return self.states[i] +class OlderHost(Host): + """A host without the call for one of OpenCiv4's options (#148's has no city one click: it comes + with the city double click); it records what the other options got.""" + + def __init__(self, path): + Host.__init__(self, path) + self.got = {} + + def __getattribute__(self, name): + if name in ('set_city_one_click', 'city_one_click'): + raise AttributeError(name) + if name in ('set_keep_attacker', 'set_quick_enemy_moves', 'set_edge_scroll'): + got = object.__getattribute__(self, 'got') + return lambda on: got.__setitem__(name, bool(on)) + return Host.__getattribute__(self, name) + + def __getattr__(self, name): + if name in ('set_city_one_click', 'city_one_click'): + raise AttributeError(name) + return Host.__getattr__(self, name) + + class Info(object): def __init__(self, i): self.i = i @@ -91,9 +113,9 @@ def sendPlayerOption(self, i, on): return m -def start(folder): +def start(folder, hostClass=Host): """The program starting: a new host, oc4options loaded afresh (it reads the profile).""" - host = Host(os.path.join(folder, 'profile.ini')) + host = hostClass(os.path.join(folder, 'profile.ini')) sys.modules['oc4host'] = host sys.modules['CvPythonExtensions'] = cpe(host) screens = Anything('oc4screens') @@ -222,6 +244,13 @@ def main(): click(options, optionsScreen(options), 'GameOptionCheckBox_2') host, options = start(folder) check(not options._UserProfile().getPlayerOption(2), "after that, off is kept") + + # A host without one option's call: the options after it still reach the host at the start. + with open(os.path.join(folder, 'profile.ini'), 'w') as f: + f.write('name=openciv4\nedgeScroll=0\ncityOneClick=1\nkeepAttacker=1\nquickEnemyMoves=1\n') + host, options = start(folder, OlderHost) + check(host.got == {'set_edge_scroll': False, 'set_keep_attacker': True, 'set_quick_enemy_moves': True}, + "a host without set_city_one_click still gets the rest: %s" % host.got) finally: shutil.rmtree(folder, ignore_errors=True) From f3f7336be492a3d437cf4513b408943b558db117 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 19:47:55 +0100 Subject: [PATCH 84/89] Options: the OpenCiv4 tab ends as the game's tabs do, with Restore Defaults and Exit The OpenCiv4 tab's panel ran to the bottom of the window, with no line and no buttons under it. It now has the foot the game's own tabs have (CvOptionsScreen.py: a separator, then a centred row with Restore Defaults and Exit). Its options are in a scroll panel above that, as the game's Other tab does, since they don't all fit above the buttons. Restore Defaults on this tab sets OpenCiv4's options (the tab's check boxes and the CivilizationIV.ini numbers) back to a new profile's, saves the profile and sends them to the host. That is what the game's button does for its own tab's options (CvOptionsScreenCallbackInterface: resetOptions for that tab, refresh, saveProfile). The other tabs' options are kept. Exit is the game's own handleExitButtonInput. setText on an edit box now changes the box as shown too: a redraw keeps what was typed into it, so the reset numbers would have been typed over by the old ones. player_options_test: the tab's foot, and Restore Defaults there. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4options.py | 67 ++++++++++++++++++++++++++++++- tests/player_options_test.py | 24 +++++++++++ 2 files changed, 90 insertions(+), 1 deletion(-) diff --git a/apps/oc4core/python/oc4options.py b/apps/oc4core/python/oc4options.py index ff761ae5..e163e675 100644 --- a/apps/oc4core/python/oc4options.py +++ b/apps/oc4core/python/oc4options.py @@ -582,6 +582,33 @@ def _applyFieldOfView(): pass +# The OpenCiv4 tab's options: its check boxes with their profile keys, then its number boxes' +# (Oc4Edit), which Restore Defaults on that tab sets back to a new profile's. +_OC4_TAB_CHECKBOXES = ((WASD_PAN_CHECKBOX, 'wasdPan'), (AUTO_END_TURN_CHECKBOX, 'autoEndTurn'), (EDGE_SCROLL_CHECKBOX, 'edgeScroll'), + (CITY_ONE_CLICK_CHECKBOX, 'cityOneClick'), (KEEP_ATTACKER_CHECKBOX, 'keepAttacker'), (QUICK_ENEMY_MOVES_CHECKBOX, 'quickEnemyMoves'), + (NO_TECH_SPLASH_CHECKBOX, 'noTechSplash'), (NO_EVENT_MESSAGES_CHECKBOX, 'noEventMessages'), (OPENCIV4_AUTOSAVES_CHECKBOX, 'openciv4AutoSaves')) + + +def handleOc4Reset(args): + """Restore Defaults on the OpenCiv4 tab: OpenCiv4's options as a new profile has them, as the + game's button does for its own tab's (CvOptionsScreenCallbackInterface: resetOptions, refresh, + saveProfile); the other tabs' are kept.""" + fresh = _fresh() + for name, key in _OC4_TAB_CHECKBOXES: + _profile[key] = fresh[key] + for key, default in _INI_NUMBERS: + _profile[key] = fresh[key] + _save() + _applyGraphics() + ctrl = _state['ctrl'] + if ctrl is not None: + for name, key in _OC4_TAB_CHECKBOXES: + ctrl.setValue(name, bool(_profile[key])) + for key, default in _INI_NUMBERS: + ctrl.setText('Oc4Edit' + key, str(_profile[key])) + return 1 + + def handleIniFlagClicked(args): """One of the ini's check boxes (its argument the profile's key).""" _profile[str(args[1])] = bool(args[0]) @@ -964,6 +991,17 @@ def __init__(self, id, kind, name): _state = {'ctrl': None, 'dirty': False, 'scrolling': 0} +def _translate(key, fallback): + """The game's text for a key (CyTranslator), or the fallback without one.""" + try: + text = _cpe.CyTranslator().getText(key, ()) + if text and text != key: + return text + except Exception: + pass + return fallback + + def _text(s): try: return oc4screens._text(s) @@ -1041,8 +1079,13 @@ def _attachOpenCiv4Tab(self): wasdPan, autoEndTurn, edgeScroll, cityOneClick, keepAttacker).""" self.attachTabItem(OC4_FORM, u'OpenCiv4') self.attachVBox(OC4_FORM, 'Oc4VBox') + # (as the game's tabs: the options in a scroll panel, then a line and Restore Defaults and Exit) + self.attachScrollPanel('Oc4VBox', 'Oc4Scroll') + self.setLayoutFlag('Oc4Scroll', 'LAYOUT_SIZE_HEXPANDING') + self.setLayoutFlag('Oc4Scroll', 'LAYOUT_SIZE_VEXPANDING') + self._attachLowerButtons('Oc4VBox', 'Oc4', 'handleOc4Reset') parent = 'Oc4Panel' - self.attachPanel('Oc4VBox', parent) + self.attachPanel('Oc4Scroll', parent) self.setStyle(parent, 'Panel_Tan15_Style') self.setLayoutFlag(parent, 'LAYOUT_SIZE_HEXPANDING') self.setLayoutFlag(parent, 'LAYOUT_SIZE_VEXPANDING') @@ -1076,6 +1119,20 @@ def _attachOpenCiv4Tab(self): u'The original has no such option: its Quick Moves speeds up only your own units.') self._attachIniOptions(parent) + def _attachLowerButtons(self, vbox, prefix, reset): + """A tab's foot as the game's tabs have it (CvOptionsScreen.py): a line, then Restore Defaults + (oc4options' reset) and Exit (the game's own handleExitButtonInput) centred under it.""" + self.attachHSeparator(vbox, prefix + 'ExitSeparator') + row = prefix + 'LowerHBox' + self.attachHBox(vbox, row) + self.setLayoutFlag(row, 'LAYOUT_HCENTER') + self.attachButton(row, prefix + 'OptionsResetButton', _translate('TXT_KEY_OPTIONS_RESET', u'Restore Defaults'), + 'oc4options', reset, prefix + 'OptionsResetButton') + name = prefix + 'OptionsExitButton' + self.attachButton(row, name, _translate('TXT_KEY_PEDIA_SCREEN_EXIT', u'Exit'), + 'CvOptionsScreenCallbackInterface', 'handleExitButtonInput', name) + self.setLayoutFlag(name, 'LAYOUT_HCENTER') + def _attachIniOptions(self, parent): """CivilizationIV.ini's settings the original sets only in its ini (see _INI_FLAGS).""" self.attachHSeparator(parent, 'Oc4IniSeparator') @@ -1205,6 +1262,14 @@ def setText(self, name, text): n = self._byName.get(str(name)) if n is not None: n.text = _text(text) + if n.kind == 'edit': + # (the box as shown too: a redraw keeps what was typed into it) + try: + w = _screen()._s.get('OptW%d' % n.id) + if w is not None: + w.text = n.text + except Exception: + pass _schedule() def getText(self, name): diff --git a/tests/player_options_test.py b/tests/player_options_test.py index 6a1a8672..3cf99063 100644 --- a/tests/player_options_test.py +++ b/tests/player_options_test.py @@ -251,6 +251,30 @@ def main(): host, options = start(folder, OlderHost) check(host.got == {'set_edge_scroll': False, 'set_keep_attacker': True, 'set_quick_enemy_moves': True}, "a host without set_city_one_click still gets the rest: %s" % host.got) + + # The OpenCiv4 tab's foot as the game's tabs': its options scroll above a line, Restore Defaults and Exit. + host, options = start(folder) + ctrl = optionsScreen(options) + vbox = [(n.kind, n.name) for n in ctrl._byName['Oc4VBox'].children] + check(vbox == [('scroll', 'Oc4Scroll'), ('hsep', 'Oc4ExitSeparator'), ('hbox', 'Oc4LowerHBox')], "the OpenCiv4 tab's foot: %s" % vbox) + buttons = [(n.name, n.callback[:2]) for n in ctrl._byName['Oc4LowerHBox'].children] + check(buttons == [('Oc4OptionsResetButton', ('oc4options', 'handleOc4Reset')), + ('Oc4OptionsExitButton', ('CvOptionsScreenCallbackInterface', 'handleExitButtonInput'))], "Restore Defaults and Exit: %s" % buttons) + check([n.name for n in ctrl._byName['Oc4Scroll'].children] == ['Oc4Panel'], "the options in the scroll panel") + # Restore Defaults there: OpenCiv4's options as a new profile's, the other tabs' kept. + click(options, ctrl, options.KEEP_ATTACKER_CHECKBOX) + click(options, ctrl, options.EDGE_SCROLL_CHECKBOX) + click(options, ctrl, options.NO_TECH_SPLASH_CHECKBOX) + options.handleIniNumberTyped((u'9', 'autoSaveInterval')) + click(options, ctrl, 'GameOptionCheckBox_6') + quick = options._UserProfile().getPlayerOption(6) + options._call(ctrl._byName['Oc4OptionsResetButton'], ('Oc4OptionsResetButton',)) + p = options._profile + check(not p['keepAttacker'] and p['edgeScroll'] and not p['noTechSplash'] and p['autoSaveInterval'] == 4, "Restore Defaults: OpenCiv4's options") + check(ctrl._byName[options.KEEP_ATTACKER_CHECKBOX].value is False and ctrl._byName[options.EDGE_SCROLL_CHECKBOX].value is True + and ctrl._byName['Oc4EditautoSaveInterval'].text == u'4', "... shown on the tab") + check(options._UserProfile().getPlayerOption(6) == quick, "... the Game tab's kept") + check({'keepAttacker=0', 'edgeScroll=1', 'autoSaveInterval=4'} <= profileLines(folder), "... and saved") finally: shutil.rmtree(folder, ignore_errors=True) From 93e852610dd6fd7fb7c493c7570f68d980788427 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 20:41:58 +0100 Subject: [PATCH 85/89] Right button held: the buttons are the goto plot's, as the original's With a worker selected and the right button held over another plot, the action buttons showed what the worker could do on its own plot. The glow was already the goto plot's (CvUnit::isActionRecommended reads it), so on a hill the Cottage glowed and no Mine showed. The scripts' action list (ui_actions_to_show, CyInterface().getActionsToShow) and ui_can_handle_action now pass the interface's goto plot to CvGame::canHandleAction, which takes it for the mission plot. Without a held button there is no goto plot, and the core uses the unit's own plot as before. Seen in Wine (BUG + BULL, a worker at 81,71, the right button held without letting go): on a hill, Mine and Windmill; on iron on flat grassland, Mine (glowing); on marble, Quarry (glowing); on its own plot, its own list. The buttons change while the button is still held, before any move. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index 75912578..bf6214d2 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -490,8 +490,10 @@ namespace oc4::host // actions host.def("ui_interface_mode", [&ui] { return int(ui.getInterfaceMode()); }); host.def("ui_set_interface_mode", [&ui](int m) { ui.setInterfaceMode(static_cast(m)); }); - host.def("ui_can_handle_action", [](int action, bool visible) { - return action >= 0 && action < GC.getNumActionInfos() && GC.getGame().canHandleAction(action, nullptr, visible); + // (with the right button held, the actions are those for the goto plot, as the original's: a + // worker's buttons there are that plot's builds; CvGame::canHandleAction takes the plot) + host.def("ui_can_handle_action", [&ui](int action, bool visible) { + return action >= 0 && action < GC.getNumActionInfos() && GC.getGame().canHandleAction(action, ui.getGotoPlot(), visible); }); host.def("ui_actions_to_show", [&ui] { // What the selected units can do, as the action buttons show it: in the game's order. @@ -500,7 +502,7 @@ namespace oc4::host for (int i = 0; i < GC.getNumActionInfos(); ++i) { const CvActionInfo& a = GC.getActionInfo(i); - if (a.isVisible() && a.getControlType() == NO_CONTROL && GC.getGame().canHandleAction(i, nullptr, true)) + if (a.isVisible() && a.getControlType() == NO_CONTROL && GC.getGame().canHandleAction(i, ui.getGotoPlot(), true)) order.push_back({ a.getOrderPriority(), i }); } std::stable_sort(order.begin(), order.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); From 805cacf295194e8352a9ed9ad172c5320e2e2a1d Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 20:58:14 +0100 Subject: [PATCH 86/89] City screen: the help goes beside the widget under the mouse, as the original's The city screen's help area is floating (CvMainInterface.py: setHelpTextArea(390, ..., 0, 0, ..., bFloating True, the transparent popup art, ...)). OpenCiv4 ignored bFloating and drew every help at the area's 0, 0, the screen's top-left, over the top bar: the hurry button's at the bottom right showed its help in the far corner. A floating help area now puts the help beside the widget under the mouse. Seen in Wine (BUG + BULL, Roma's city screen at 1600x900, the mouse on the hurry button, Production Automation, a build in the list and a specialist): the box's right edge is at the widget's left, and its top is at the widget's top. When that would run off the screen below, its bottom is at the widget's bottom instead (the hurry button's). It is as wide as its widest line and wraps at about 240 (the hurry help's longest line, 234 wide, then a break before "a Building"). The main interface's help area on the map isn't floating and is unchanged. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/Screens.cpp | 5 +++-- apps/oc4core/python/oc4screens.py | 7 ++++--- src/render/MapWindow.cpp | 4 ++-- src/render/MapWindow.h | 2 +- src/render/UiLayer.cpp | 23 ++++++++++++++++++++--- src/render/UiLayer.h | 3 ++- 6 files changed, 32 insertions(+), 12 deletions(-) diff --git a/apps/oc4core/Screens.cpp b/apps/oc4core/Screens.cpp index bf6214d2..e13331df 100644 --- a/apps/oc4core/Screens.cpp +++ b/apps/oc4core/Screens.cpp @@ -1261,7 +1261,7 @@ if _walls: m_hovered = hovered; const std::string text = hovered >= 0 && size_t(hovered) < m_items.size() ? help(m_items[size_t(hovered)]) : std::string(); float x = 7, y = float(height) - 172, w = 300; - bool right = true, down = false, framed = false; + bool right = true, down = false, framed = false, floating = false; try { if (py::object area = py::module_::import("oc4screens").attr("helpArea")(); !area.is_none()) @@ -1276,13 +1276,14 @@ if _walls: right = t[4].cast(); down = t[5].cast(); framed = t.size() > 6 && t[6].cast(); + floating = t.size() > 7 && t[7].cast(); } } catch (py::error_already_set& e) { printPythonError(e); } - window.setUiHelp(text, x, y, w, right, down, framed); + window.setUiHelp(text, x, y, w, right, down, framed, floating); } } diff --git a/apps/oc4core/python/oc4screens.py b/apps/oc4core/python/oc4screens.py index 1063a9ce..ee68282b 100644 --- a/apps/oc4core/python/oc4screens.py +++ b/apps/oc4core/python/oc4screens.py @@ -159,7 +159,7 @@ def __init__(self, name, fileId): self.shown = False self.main = False self.dims = None - self.helpArea = None # (x, y, width, minWidth, expandRight, expandDown, framed) + self.helpArea = None # (x, y, width, minWidth, expandRight, expandDown, framed, floating) self.helpText = u'' self.minimap = None self.mm = None # its own minimap's layers (not the main interface's): see _Minimap @@ -972,8 +972,9 @@ def hideEndTurn(self, szName): _set(w, 'shown', False) def setHelpTextArea(self, fWidth, eFont, fX, fY, fZ, bFloating, szArtFile, bExpandRight, bExpandDown, uiFlags, iMinWidth): - # (with art, the city screen's, it is framed; without, the main interface's, see-through) - self._s.helpArea = (int(fX), int(fY), int(fWidth), int(iMinWidth), bool(bExpandRight), bool(bExpandDown), bool(szArtFile)) + # (with art, the city screen's, it is framed; without, the main interface's, see-through; + # floating, the city screen's, it goes beside the widget under the mouse, not at x, y) + self._s.helpArea = (int(fX), int(fY), int(fWidth), int(iMinWidth), bool(bExpandRight), bool(bExpandDown), bool(szArtFile), bool(bFloating)) def setHelpTextString(self, szString): self._s.helpText = _text(szString) diff --git a/src/render/MapWindow.cpp b/src/render/MapWindow.cpp index 3a093312..74e43e18 100644 --- a/src/render/MapWindow.cpp +++ b/src/render/MapWindow.cpp @@ -3113,9 +3113,9 @@ namespace oc4::render return std::format("camera at {:.1f},{:.1f} (height {:.0f}), {:.1f} plots away, pitch {:.2f}", m->camera.target.x / p, m->camera.target.y / p, m->camera.target.z, m->camera.distance / p, m->camera.pitch); } - void MapWindow::setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed) + void MapWindow::setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed, bool floating) { - m->ui.setHelp(text, x, y, width, expandRight, expandDown, framed); + m->ui.setHelp(text, x, y, width, expandRight, expandDown, framed, floating); } void MapWindow::pressKeys(const std::string& keys) { diff --git a/src/render/MapWindow.h b/src/render/MapWindow.h index 97937f3f..ef4674f5 100644 --- a/src/render/MapWindow.h +++ b/src/render/MapWindow.h @@ -393,7 +393,7 @@ namespace oc4::render // Where the mouse is, in window pixels ((-1, -1) before it came in). std::pair mousePosition() const; // The help for what is under the mouse, in the screens' help area. - void setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false); + void setUiHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false, bool floating = false); // The text shown when the mouse rests on a plot (lines; the game's plot help). void setPlotHelp(std::function help); diff --git a/src/render/UiLayer.cpp b/src/render/UiLayer.cpp index d8ef5b27..c8639394 100644 --- a/src/render/UiLayer.cpp +++ b/src/render/UiLayer.cpp @@ -332,8 +332,24 @@ namespace oc4::render w = std::min(w * 1.5f, widest); h = o.richHeight(text, w - 2 * inX, m_sizes[2], false) + 2 * inY; } - const float x = m_helpRight ? m_helpX : m_helpX - w; - const float y = std::clamp(m_helpDown ? m_helpY : m_helpY - h, 0.0f, std::max(sh - h, 0.0f)); + float x = m_helpRight ? m_helpX : m_helpX - w; + float y = std::clamp(m_helpDown ? m_helpY : m_helpY - h, 0.0f, std::max(sh - h, 0.0f)); + if (m_helpFloating && m_hover >= 0 && size_t(m_hover) < m_items.size()) + { + // A floating help area (the city screen's, setHelpTextArea's bFloating): the help beside + // the widget under the mouse, as the original (BUG + BULL in Wine, Roma's screen at + // 1600x900): its right edge at the widget's left (on its right when there is no room), + // its top at the widget's top, or its bottom at the widget's bottom when it would run off + // the screen below (the hurry buttons); as wide as its widest line, wrapped at 240. + const Item& it = m_items[size_t(m_hover)]; + const float ix0 = std::min(it.x0, it.x1), ix1 = std::max(it.x0, it.x1); + constexpr float kWrap = 240; + w = std::min(std::ceil(o.richWidth(text, m_sizes[2], false)) + 2 * inX + 2, kWrap + 2 * inX); + h = o.richHeight(text, w - 2 * inX, m_sizes[2], false) + 2 * inY; + x = ix0 - w >= 0 ? ix0 - w : std::min(ix1, std::max(sw - w, 0.0f)); + y = it.y0 + h <= sh ? it.y0 : it.y1 - h; + y = std::clamp(y, 0.0f, std::max(sh - h, 0.0f)); + } if (see) Theme::draw(o, m_hudHelp, x, y, x + w, y + h); else if (!m_tooltip.empty()) @@ -399,9 +415,10 @@ namespace oc4::render return MapWindow::UiClick{ pressed, m_pressedRight, shift, ctrl, alt }; } - void UiLayer::setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed) + void UiLayer::setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed, bool floating) { m_helpFramed = framed; + m_helpFloating = floating; m_help = widen(text); m_helpX = x; m_helpY = y; diff --git a/src/render/UiLayer.h b/src/render/UiLayer.h index 2b76a3ae..1d6ec921 100644 --- a/src/render/UiLayer.h +++ b/src/render/UiLayer.h @@ -65,7 +65,7 @@ namespace oc4::render // framed: the help area has art of its own (the city screen's), in the theme's tooltip; // else the main interface's see-through box (PANEL_STYLE_HUD_HELP). - void setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false); + void setHelp(const std::string& text, float x, float y, float width, bool expandRight, bool expandDown, bool framed = false, bool floating = false); // The size of a widget's font (FontTypes) as the screens draw it. float textSize(int font) const { return fontSize(font); } // The plot's help where the screens show theirs, in the same box (the game's look). @@ -127,6 +127,7 @@ namespace oc4::render std::wstring m_help; float m_helpX = 0, m_helpY = 0, m_helpWidth = 350; bool m_helpRight = true, m_helpDown = false, m_helpFramed = false; + bool m_helpFloating = false; // (the help area floats: the help goes beside the widget under the mouse) // A help in the help area: its box, then its text. void drawHelp(Overlay& o, const std::wstring& text); }; From 3ccf422b3a3d189b6c5733ecd7e5b503e625e0bb Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 21:34:56 +0100 Subject: [PATCH 87/89] World Builder: the Terrains tab grouped as the original's, no doubled peak and hill The Terrains tab listed every terrain in the XML, the graphical only peak and hill too, so those two showed twice (once more as the plot types). It also ran its four lists together, eight to a row. As in the original, seen in Wine (BUG + BULL, Map Mode's Terrains tab), it now shows four groups, each starting a new row: - the terrains without the graphical only ones (grass, plains, desert, tundra, snow, coast, ocean); - the plot types (peak, hills, flat, water); - the features (ice, jungle, oasis, flood plains, the three forests, fallout); - the routes and the river. TERRAIN_PEAK and TERRAIN_HILL are the ones with bGraphicalOnly 1 (CIV4TerrainInfos.xml); they are the last two, so the other terrains keep their indexes. The other tabs were checked against the Wine pictures (Units, Buildings, Technologies, Improvements, Bonuses) and were already in the original's order and rows. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4wb.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/apps/oc4core/python/oc4wb.py b/apps/oc4core/python/oc4wb.py index 91468fa0..ab73dadb 100644 --- a/apps/oc4core/python/oc4wb.py +++ b/apps/oc4core/python/oc4wb.py @@ -277,8 +277,11 @@ def _items(ctrl): for i in range(gc.getNumBonusInfos()): out.append((0, i, gc.getBonusInfo(i).getButton(), gc.getBonusInfo(i).getDescription(), sel(0, i), (W.WIDGET_PEDIA_JUMP_TO_BONUS, i))) elif tab == 2: + # (as the original's list, seen in Wine: without the graphical only terrains, the peak + # and the hill, which the plot types place; each list on rows of its own) for i in range(gc.getNumTerrainInfos()): - out.append((0, i, gc.getTerrainInfo(i).getButton(), gc.getTerrainInfo(i).getDescription(), sel(0, i), (W.WIDGET_PEDIA_JUMP_TO_TERRAIN, i))) + if not gc.getTerrainInfo(i).isGraphicalOnly(): + out.append((0, i, gc.getTerrainInfo(i).getButton(), gc.getTerrainInfo(i).getDescription(), sel(0, i), (W.WIDGET_PEDIA_JUMP_TO_TERRAIN, i))) # (the plot types and the river with the original's own buttons) for i, (name, art) in enumerate(((u'Peak', 'WORLDBUILDER_PLOT_TYPE_MOUNTAIN'), (u'Hills', 'WORLDBUILDER_PLOT_TYPE_HILL'), (u'Flat', 'WORLDBUILDER_PLOT_TYPE_PLAINS'), (u'Water', 'WORLDBUILDER_PLOT_TYPE_OCEAN'))): @@ -519,16 +522,31 @@ def _item(screen, ctrl, item, k, parent, cx, cy): w.help = u'' + _u(item[3]) + u'' +def _gridPlaces(items, columns): + """Each item's column and row: a section's lists each start a row of their own, as the + original's Terrains tab (seen in Wine: the terrains, the plot types, the features, then the + routes and the river, each on new rows).""" + places, row, col, last = [], 0, 0, None + for item in items: + if last is not None and (item[0] != last or col >= columns): + row, col = row + 1, 0 + places.append((col, row)) + col, last = col + 1, item[0] + return places + + def _drawGrid(screen, ctrl, items, x, y, w, h, k0=0): """Items in a scroll panel: seven to a row beside its scroll bar, or, when they fit without one, as many as fit (the original's: the map mode's improvements eight).""" grid = _add('OC4WBGrid%d' % k0) screen.addScrollPanel(grid, u'', x, y, w, h, _cpe.PanelStyles.PANEL_STYLE_EXTERNAL) columns = max(_COLUMNS, (w - 6) / _CELL) - if (len(items) + columns - 1) / columns * _CELL > h - 6: + places = _gridPlaces(items, columns) + if places and (places[-1][1] + 1) * _CELL > h - 6: columns = _COLUMNS + places = _gridPlaces(items, columns) for k, item in enumerate(items): - _item(screen, ctrl, item, k0 + k, grid, (k % columns) * _CELL, (k // columns) * _CELL) + _item(screen, ctrl, item, k0 + k, grid, places[k][0] * _CELL, places[k][1] * _CELL) # The edit window (a unit's or a city's), as the original's (measured in Wine at 1600 x 900): in From bd2b9ce36b2292aa2e76bc413f8af4206af09ce9 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 21:38:53 +0100 Subject: [PATCH 88/89] World Builder: the techs the player knows framed in yellow, as the original's On the player mode's Technologies tab the original frames each tech the player knows in yellow (seen in Wine, BUG + BULL: wine-wb/pl-techs.png). OpenCiv4 marked them with the faint HUD help panel behind the button, which hardly showed. A known tech is now an image check box that is on, the way the World Builder's chosen tool button is drawn (its picture and the yellow frame, as in Wine). The palette reads CyTeam.isHasTech each time it draws, so the frame follows a tech added or taken away with the brush at once (checked: a click on a known tech takes it away and its frame goes). The other lists keep their look: in Wine the units', buildings', terrains' and the rest's chosen item has no frame. Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4wb.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/oc4core/python/oc4wb.py b/apps/oc4core/python/oc4wb.py index ab73dadb..0b4cc4d9 100644 --- a/apps/oc4core/python/oc4wb.py +++ b/apps/oc4core/python/oc4wb.py @@ -506,11 +506,17 @@ def _item(screen, ctrl, item, k, parent, cx, cy): """One item: its button (on the highlight when chosen), its help as the original's palette shows it under the mouse: the game's help of what it places, else its name as a link.""" general = _cpe.WidgetTypes.WIDGET_GENERAL - if item[4]: + # (the player mode's Technologies: a tech the player knows framed in yellow, as the original's, + # seen in Wine; an image check box that is on, as the tool buttons' chosen one) + known = item[4] and ctrl.kind == 'player' and ctrl.active == 2 + if item[4] and not known: screen.attachPanelAt(parent, _add('OC4WBSel%d' % k), u'', u'', False, False, _cpe.PanelStyles.PANEL_STYLE_HUD_HELP, cx - 2, cy - 2, _CELL - 1, _CELL - 1, general, -1, -1) name = 'OC4WBItem%d' % k - if item[2]: + if known and item[2]: + screen.addCheckBoxGFCAt(parent, _add(name, ('item', ctrl, item)), item[2], u'', cx, cy, _ICON, _ICON, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_LABEL) + screen.setState(name, True) + elif item[2]: screen.setImageButtonAt(_add(name, ('item', ctrl, item)), parent, item[2], cx, cy, _ICON, _ICON, general, -1, -1) else: screen.setTextAt(_add(name, ('item', ctrl, item)), parent, item[3][:6], 0, cx, cy + 8, -0.3, _cpe.FontTypes.SMALL_FONT, general, -1, -1) From 072f8de29c89fd7a99f47018e5a3ef0774a0a138 Mon Sep 17 00:00:00 2001 From: mortenlyhr Date: Mon, 23 Nov 2026 21:41:15 +0100 Subject: [PATCH 89/89] World Builder: a known tech's frame is the original's yellow glow The frame on the techs the player knows was the theme's toggled look, paler and thinner than the original's. It is now the art the original uses for it: the check box's highlight picture BUTTON_HILITE_SQUARE (Art/Interface/Buttons/Button_SELECT.dds, CIV4ArtDefines_Interface.xml), which CvWorldBuilderScreen.py gives its tool buttons' check boxes. Drawn over the tech's button when it is on, it gives the bright yellow glow seen in Wine (BUG + BULL, wine-wb/pl-techs.png). Co-Authored-By: Claude Opus 5.5 --- apps/oc4core/python/oc4wb.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/oc4core/python/oc4wb.py b/apps/oc4core/python/oc4wb.py index 0b4cc4d9..5fce089f 100644 --- a/apps/oc4core/python/oc4wb.py +++ b/apps/oc4core/python/oc4wb.py @@ -507,14 +507,16 @@ def _item(screen, ctrl, item, k, parent, cx, cy): shows it under the mouse: the game's help of what it places, else its name as a link.""" general = _cpe.WidgetTypes.WIDGET_GENERAL # (the player mode's Technologies: a tech the player knows framed in yellow, as the original's, - # seen in Wine; an image check box that is on, as the tool buttons' chosen one) + # seen in Wine; an image check box that is on with the highlight BUTTON_HILITE_SQUARE + # (Button_SELECT.dds), the art CvWorldBuilderScreen.py gives its tool buttons' check boxes) known = item[4] and ctrl.kind == 'player' and ctrl.active == 2 if item[4] and not known: screen.attachPanelAt(parent, _add('OC4WBSel%d' % k), u'', u'', False, False, _cpe.PanelStyles.PANEL_STYLE_HUD_HELP, cx - 2, cy - 2, _CELL - 1, _CELL - 1, general, -1, -1) name = 'OC4WBItem%d' % k if known and item[2]: - screen.addCheckBoxGFCAt(parent, _add(name, ('item', ctrl, item)), item[2], u'', cx, cy, _ICON, _ICON, general, -1, -1, _cpe.ButtonStyles.BUTTON_STYLE_LABEL) + screen.addCheckBoxGFCAt(parent, _add(name, ('item', ctrl, item)), item[2], _art('BUTTON_HILITE_SQUARE'), cx, cy, _ICON, _ICON, general, -1, -1, + _cpe.ButtonStyles.BUTTON_STYLE_LABEL) screen.setState(name, True) elif item[2]: screen.setImageButtonAt(_add(name, ('item', ctrl, item)), parent, item[2], cx, cy, _ICON, _ICON, general, -1, -1)