Compare commits

...

283 Commits

Author SHA1 Message Date
Alistair Lynn 7ef8706ed2 Add: Setting to uniformly slow the acceleration and braking of realistic trains
This does not affect the maximum speed.
5 hours ago
Jonathan G Rennison 0351734729 Fix narrowing warning using packet GetDeserialisationPosition 5 hours ago
Jonathan G Rennison 7997430688 Add various missing includes 5 hours ago
Jonathan G Rennison f09f412c43 Add hash table index to EngineOverrideManager
Use for EngineOverrideManager::GetID lookups
5 hours ago
Jonathan G Rennison 556722399a Move EngineOverrideManager to separate header 5 hours ago
Jonathan G Rennison b42d12deb2 Add do/while wrappers around grfmsg/GrfMsg 5 hours ago
Jonathan G Rennison 32b8ec34ff Merge branch 'master' into jgrpp
# Conflicts:
#	src/autoreplace_gui.cpp
#	src/build_vehicle_gui.cpp
#	src/cheat_gui.cpp
#	src/company_gui.cpp
#	src/debug.cpp
#	src/engine_gui.h
#	src/error_gui.cpp
#	src/group_gui.cpp
#	src/industry_cmd.cpp
#	src/industry_gui.cpp
#	src/misc_gui.cpp
#	src/network/network_gui.cpp
#	src/newgrf.cpp
#	src/newgrf_debug_gui.cpp
#	src/newgrf_gui.cpp
#	src/order_gui.cpp
#	src/rail_gui.cpp
#	src/road_gui.cpp
#	src/saveload/saveload.cpp
#	src/screenshot_gui.cpp
#	src/sound/win32_s.cpp
#	src/statusbar_gui.cpp
#	src/strgen/strgen.cpp
#	src/table/newgrf_debug_data.h
#	src/timetable_gui.cpp
#	src/toolbar_gui.cpp
#	src/town_gui.cpp
#	src/vehicle_gui.cpp
#	src/video/sdl2_v.cpp
#	src/video/sdl_v.cpp
#	src/viewport.cpp
5 hours ago
Jonathan G Rennison c6c7191b16 Avoid unnecessary allocation of temporaries in layout line cache 1 day ago
Jonathan G Rennison 99e6b75337 Move NewGRF sprite dump declarations to new header file 1 day ago
Jonathan G Rennison dc6ba9b9d8 Move NewGRF shadow copy groups into internal header 1 day ago
Jonathan G Rennison 56356bb761 Change container type for several uses of std::map/std::set 1 day ago
Jonathan G Rennison 853ed272be Merge branch 'master' into jgrpp
# Conflicts:
#	src/airport_gui.cpp
#	src/blitter/32bpp_optimized.cpp
#	src/blitter/32bpp_simple.cpp
#	src/blitter/32bpp_sse2.cpp
#	src/blitter/8bpp_optimized.cpp
#	src/blitter/8bpp_simple.cpp
#	src/blitter/null.cpp
#	src/build_vehicle_gui.cpp
#	src/company_gui.cpp
#	src/crashlog.cpp
#	src/dropdown.cpp
#	src/dropdown_type.h
#	src/genworld_gui.cpp
#	src/gfx.cpp
#	src/main_gui.cpp
#	src/newgrf_debug_gui.cpp
#	src/news_gui.cpp
#	src/news_type.h
#	src/openttd.cpp
#	src/order_gui.cpp
#	src/settings.cpp
#	src/settings_gui.cpp
#	src/signs.cpp
#	src/smallmap_gui.cpp
#	src/spritecache.cpp
#	src/spriteloader/grf.cpp
#	src/texteff.cpp
#	src/toolbar_gui.cpp
#	src/town_cmd.cpp
#	src/vehicle.cpp
#	src/vehicle_gui.cpp
#	src/video/opengl.cpp
#	src/viewport.cpp
#	src/waypoint_cmd.cpp
#	src/zoom_type.h
1 day ago
Jonathan G Rennison cb1e41fc88 Remove use of memcmp in CheckCaches 2 days ago
Jonathan G Rennison 2b539a2d37 Fix water infrastructure total when changing owner of object on water 3 days ago
Jonathan G Rennison 1e9fb74451 Merge branch 'master' into jgrpp
# Conflicts:
#	.github/workflows/release-windows.yml
#	src/autoreplace_gui.cpp
#	src/cargotype.cpp
#	src/company_base.h
#	src/company_cmd.cpp
#	src/company_gui.cpp
#	src/currency.h
#	src/date_gui.cpp
#	src/dropdown.cpp
#	src/dropdown_func.h
#	src/dropdown_type.h
#	src/game/game_gui.cpp
#	src/genworld.cpp
#	src/genworld_gui.cpp
#	src/ground_vehicle.hpp
#	src/group_gui.cpp
#	src/house.h
#	src/industry_gui.cpp
#	src/network/network_client.cpp
#	src/network/network_server.cpp
#	src/network/network_type.h
#	src/newgrf_class_func.h
#	src/newgrf_house.cpp
#	src/newgrf_roadstop.h
#	src/openttd.cpp
#	src/order_gui.cpp
#	src/saveload/saveload.cpp
#	src/saveload/saveload.h
#	src/screenshot_gui.cpp
#	src/settings_gui.cpp
#	src/settings_type.h
#	src/slider.cpp
#	src/smallmap_gui.cpp
#	src/station_cmd.cpp
#	src/stdafx.h
#	src/survey.cpp
#	src/tile_map.h
#	src/town_cmd.cpp
#	src/town_gui.cpp
#	src/vehicle.cpp
#	src/vehicle_gui.cpp
#	src/vehicle_gui_base.h
3 days ago
Jonathan G Rennison cbea3b8b46 Add console command to merge two companies 3 days ago
Jonathan G Rennison f2f8692fb2 Add setting to allow track editing to ignore realistic braking restrictions 3 days ago
Jonathan G Rennison 7874fb7a12 Add public key auth support for settings_access console command 5 days ago
Jonathan G Rennison 84a0dd326f Merge branch 'master' into jgrpp
# Conflicts:
#	src/console_cmds.cpp
#	src/network/core/config.h
#	src/network/core/packet.h
#	src/network/core/tcp.cpp
#	src/network/core/tcp_game.cpp
#	src/network/core/tcp_game.h
#	src/network/network_client.cpp
#	src/network/network_client.h
#	src/network/network_gui.h
#	src/network/network_server.cpp
#	src/network/network_server.h
#	src/table/settings/network_secrets_settings.ini
5 days ago
Jonathan G Rennison effaf6acc4 Allow removing reservation boundary signal in realistic braking
All other operations were permitted so only disallowing removal
was not useful and could be trivially bypassed
6 days ago
Jonathan G Rennison 431a6a1262 Allow sorting by average order occupancy in shared order group mode
See: #698
6 days ago
Jonathan G Rennison d39bdd352b Merge PR #700 into jgrpp 6 days ago
pvillaverde dc465000f7 🌐 Update Galician Translations 2024-05-26 6 days ago
Jonathan G Rennison 1d70c781c6 Fix vehicle window showing profit last year in wallclock timekeeping mode 1 week ago
Qwest8K 6dfe5c4da9
Update: Russian translation (#695)
Russian localization update
1 week ago
Jonathan G Rennison a8d830aa3e Fix signal side when using both sides signal style with no-entry signals 1 week ago
Jonathan G Rennison a24d72f0d7 Fix flag values in CustomSignalSpriteContextFlags 1 week ago
Jonathan G Rennison 8907b9aa31 Reduce diff with upstream for console command functionality 2 weeks ago
Jonathan G Rennison 88d7be1d99 Change FormatArrayAsHex to be uppercase by default
To match upstream
2 weeks ago
Jonathan G Rennison 48910a8b7d Version: Committing version data for tag: jgrpp-0.59.1 2 weeks ago
Jonathan G Rennison 5e971bfc02 Fix abstract filetype not being set for network client join savegames 2 weeks ago
Jonathan G Rennison fc5b3b90b4 Remove incorrect assertion as temporary fix for #692
See: https://github.com/OpenTTD/OpenTTD/issues/12651
2 weeks ago
Rubidium 1d13ac7280 Fix #12655, 4f6d75f: inconsistent state in client list and potential crash after client leaves
(cherry picked from commit f939e81bf0)
2 weeks ago
Peter Nelson f62eb72fcb Fix #12685: nullptr dereference when checking for equal loaded/loading groups. (#12686)
Always treat empty groups as non-equal. Given that the case of both being empty is handled earlier, they cannot both be equal and empty.

Additionally if a loaded or loading set are all the same, only add one reference.

(cherry picked from commit 856ec901ca)
2 weeks ago
Jonathan G Rennison 3df3ed6690 Reduce frequency of brake overheating breakdowns
Decay overheat state more quickly
Avoid double-triggering overheating
Make overheating speed-dependent
2 weeks ago
Jonathan G Rennison 66d03530dc Adjust handling of vehicle subspeed with realistic braking
In particular when descending a steep slope with insufficient braking
2 weeks ago
Jonathan G Rennison 6d1f3b673e Fix non-percentage servicing interval when using wallclock mode 2 weeks ago
Jonathan G Rennison 89902c8ab1 Fix advisory max speed being higher than strict max for reservation end
In GetCurrentMaxSpeedInfoInternal
2 weeks ago
Jonathan G Rennison 242e87652b Fix setting display for industry cargo scaling 2 weeks ago
Jonathan G Rennison b81da24a64 Fix setting default value for industry cargo scaling mode in old saves 2 weeks ago
Jonathan G Rennison bdd1d36bd9 Fix road vehicle restart loading at same station when using implicit orders 3 weeks ago
TELK b1faf3d39f Update: Korean translation 3 weeks ago
TELK d3fc9997d1
Update: Korean translation up to 0.59.0 (#689)
* Update: Korean translation up to 0.59.0

* Update: Korean translation up to fc4ea241

* Update: Korean translation / missing ones
3 weeks ago
Peter Nelson d7f029344f Codechange: Don't delete news items or NewGRF window when EffectVehicle is deleted. (#12334)
EffectVehicles never create news and can't be debugged, so searching for news items and windows to delete just wastes time.

(cherry picked from commit 737e3feaf0)
3 weeks ago
Jonathan G Rennison fc4ea241b0 Merge branch 'master' into jgrpp 3 weeks ago
Jonathan G Rennison 6d4f616706 Fix crash when sorting by capacity in autoreplace window
Move capacity cache into GUIList sort parameter

See: #690
3 weeks ago
Jonathan G Rennison 5e24882c18 Use template specialisation for GUIList parameter reference/init behaviour 3 weeks ago
Jonathan G Rennison 18a42664fc Merge branch 'master' into jgrpp
Remove 'byte' typedef
3 weeks ago
Jonathan G Rennison f1c0f864f5 Add setting to shorten vehicle view status text 4 weeks ago
Jonathan G Rennison 0a0b42a931 Bump OpenTTD content version to 14.1 4 weeks ago
Jonathan G Rennison 3e57319c0b Fix SDL keycode to vkey mapping 4 weeks ago
Jonathan G Rennison eccffec758 Version: Committing version data for tag: jgrpp-0.59.0 4 weeks ago
Peter Nelson 6de4fa921c Change: Use standard padding for company password window.
Also use now-established OnResize pattern for setting height of password warning widget.

(cherry picked from commit 0090431e99b8301c9e3ee14fb3435075708294d5)
4 weeks ago
Jonathan G Rennison f993e30850 Take cargo refit into account in build vehicle window capacity sort modes 4 weeks ago
Jonathan G Rennison 1e5c96ef87 De-duplicate filling TestedEngineDetails in build vehicle windows 4 weeks ago
Jonathan G Rennison fe374a1db0 Allow sorting by cargo capacity/running cost in dual pane train purchase window 4 weeks ago
Jonathan G Rennison 126173a839 Fix text filter in dual-pane purchase window with GRF custom names 4 weeks ago
Jonathan G Rennison 6dab30f928 Documentation: Remove random_bits variable from road stops (NML) 4 weeks ago
Jonathan G Rennison 6ef682cf44 Documentation: Fix typo 4 weeks ago
Jonathan G Rennison a413ddfd82 Readme: Expand introduction section a bit 4 weeks ago
Jonathan G Rennison 4f7fa73140 Readme: Remove various things which have been upstreamed 4 weeks ago
Jonathan G Rennison e89a40994a Reduce diff with upstream for fileio.cpp 4 weeks ago
Peter Nelson a2bd2efec1 Codechange: Remove support for links in tar files. (#12571)
This was a feature to support the original 32bpp sprite system and is no longer relevant.

(cherry picked from commit ef55cc7979)

# Conflicts:
#	src/fileio.cpp
4 weeks ago
Loïc Guilloux 716ba5fd2a Fix #12584: Improved error handling during tar scan (#12586)
(cherry picked from commit 99b74c1064)

# Conflicts:
#	src/fileio.cpp
4 weeks ago
Peter Nelson 8769318653 Codechange: Ensure SDLK mappings stay in the expected order. (#12608)
Add a constexpr constructor that ensures at compile-time that the source SDLK range matches the target range.

(cherry picked from commit 90029beb49)

# Conflicts:
#	src/video/sdl2_v.cpp
#	src/video/sdl_v.cpp
4 weeks ago
Fen fd183914c8 Fix 2d27e8e: Update numpad keycodes for SDL2, making it usable (#12596)
* Fix 2d27e8e: Update numpad keycodes for SDL2, making it usable

* Cleanup: List sdl2 numpad mappings individually

(cherry picked from commit 2559bdfa6f)
4 weeks ago
Jonathan G Rennison f1334b9854 Documentation: Fix typo 1 month ago
Calvin Sykes 69cb68a3e2 Override remain at station behaviour for road vehicles with explicit stop direction set
(cherry picked from commit 8f8d635baf3dc1506de206a3378498bedfd020bf)

See: #686
1 month ago
Jonathan G Rennison 247b40c95b Adjust setting texts for show running costs per year setting 1 month ago
Jonathan G Rennison d90c540f9e Enable economy day length scaling in wallclock timekeeping mode 1 month ago
Jonathan G Rennison 9a07f14f56 Show running costs in calendar years by default 1 month ago
Jonathan G Rennison c5cd598217 Debug: Log number of GRFs at level sl=2 when loading a game
Add helper to get the number of non-static GRFs in a GRF config
1 month ago
Jonathan G Rennison adc7840f01 Scheduled dispatch: Caveat text for number of vehicles required 1 month ago
Jonathan G Rennison a14f850f33 Debug: Show unreachable error groups in sprite dump when show details enabled 1 month ago
Peter Nelson 96ddabb30c Codechange: Remove write-only spec_id from RoadStopSpec. (#12582)
Comment is incorrect about its value too.

(cherry picked from commit 72c55128d2)
1 month ago
Jonathan G Rennison 991b7a958e Do not reset lateness on auto-timetable congestion detection, when using scheduled dispatch 1 month ago
TELK b39bd33c1c
Update: Korean translation up to 980de73 (#688)
* Update: ko-KR / Colouring some setting

* Update: Korean translation - time

* Update: Korean translation up to 980de735
1 month ago
Jonathan G Rennison 29871e412c Fix 69e7c1697: Add missing include for MSVC 1 month ago
Jonathan G Rennison ce40e85ccc Fix ROADSTOP_DRAW_MODE_WAYP_GROUND when used with RSF_DRAW_MODE_REGISTER 1 month ago
Jonathan G Rennison 07cfa5f602 Fix documentation comment for RSF_DRAW_MODE_REGISTER 1 month ago
Jonathan G Rennison 980de7353d TBTR: Fix replacement servicing condition when using infinite money 1 month ago
Jonathan G Rennison 69e7c1697e Win32: Increase buffer size and count in wave out sound driver
Ensure that wave structs are zero-inited and buffers are freed
1 month ago
Jonathan G Rennison 3136f08b86 Debug: Fix display of engine cargo age period and reliability decay speed 1 month ago
Jonathan G Rennison 33baceaef7 Maintain timer sort invariants when changing period
See: https://github.com/OpenTTD/OpenTTD/issues/12509
1 month ago
Jonathan G Rennison 674642f9cc Add a priority field to TimerGameTick::TPeriod
Use this as the primary sort key for TimerGameTick::TPeriod,
to avoid container sort order changes on timer period saveload.
1 month ago
Jonathan G Rennison d5b8f51bf9 Rename variable to fix Windows header name collision 1 month ago
Jonathan G Rennison 71227f61d8 Use MoveFileExW to implement FioRenameFile on Windows
This is to allow renaming over an existing file
1 month ago
Jonathan G Rennison 083d91a582 Remove use of shell API function for rename 1 month ago
Peter Nelson 653e217bb1 Fix: Signature validation did not close its file. (#12479)
(cherry picked from commit 3316b27496)
1 month ago
Peter Nelson 8fdc91bd9f Fix a29766d: Wrong scrolling dropdown list position with RTL. (#12412)
(cherry picked from commit 9750826590)
1 month ago
Loïc Guilloux 54093fb8b2 Fix: [Win32] Force font mapper to only use TrueType fonts (#12406)
(cherry picked from commit 11aa3694fa)
1 month ago
Jonathan G Rennison 98dc6c3c81 Fix NewGRF byte order when using -q 1 month ago
Peter Nelson ae16df2d61 Fix #12497: Add workaround for motion_counter being implemented correctly.
#12229 stopped updating motion_counter for non-engine parts of trains, and in doing so accidentally followed the spec for NewGRF var 46, which breaks NewGRFs that used to... accidentally work.

Make var 46 return motion_counter of the first engine, regardless of self or parent scope. This means var 46 is always in sync with the head engine, and avoids further changes to when motion_counter is updated.

(cherry picked from commit 9539b02455f672e11f3ac32302a00cffa5507770)
1 month ago
Jonathan G Rennison 6056a00222 Fix incorrect train weight used for infrastructure sharing track fees 1 month ago
Jonathan G Rennison 0150f8f570 Merge branch 'master' into jgrpp
# Conflicts:
#	src/network/network_server.cpp
1 month ago
Jonathan G Rennison e17c6da46a Fix industry cargoes when loading newer vanilla savegames 1 month ago
Jonathan G Rennison d70c824056 Linkgraph: Increase effect strength of distance scaling setting
Updates: 3d049895
1 month ago
Jonathan G Rennison d52d447603 Update station/industry nearby lists in BuildOilRig
See: https://github.com/OpenTTD/OpenTTD/issues/12506
1 month ago
Jonathan G Rennison 41543498f4 Fix ships leaving dots behind in viewport map mode
Fixes: 57db9a41
2 months ago
Jonathan G Rennison 1e38e513ae Fix EnginesDailyLoop being called on new economy day instead of calendar 2 months ago
Jonathan G Rennison 0dcbcedbac Fix ScriptRail::BuildSignal when using realistic braking with block signals 2 months ago
FedelloKirfed 46d71463d9 🌐 Update Galician Translations 2024-04-14 2 months ago
Jonathan G Rennison 40644f21d4 Version: Committing version data for tag: jgrpp-0.58.3 2 months ago
Jonathan G Rennison 6642b7e12c Temporary fix for click/tooltip alignment of cargo lines in industry chains window
See: #681
See: https://github.com/OpenTTD/OpenTTD/issues/12465
2 months ago
Jonathan G Rennison 8e0fa32d33 Fix merge/editing error in IndustryCargoesWindow 2 months ago
Jonathan G Rennison 3d04989507 Link graph: Change distance scaling algorithm in demand scaler
Fix erratic scaling and increase effect at large setting values
2 months ago
Peter Nelson 90ca3515da
Fix #12459, f6a88e4: Crashes when deleting news messages. (#12460)
The updated logic in f6a88e4 for deleting news messages did things in the wrong order.
2 months ago
Jonathan G Rennison 3712b84d2e Fix narrowing conversion warnings 2 months ago
Peter Nelson 2976a46d06
Fix 54be756: Terminating NUL byte was not skipped in ReadString(). (#12462) 2 months ago
Rubidium 883d3e7a9f Codechange: use std::span instead of pointer + length 2 months ago
Peter Nelson 54be756aae
Codechange: Pass NewGRF strings as std::string_view instead of char *. (#12461) 2 months ago
Peter Nelson dc7c2bb30d
Fix: Draw continuation lines for engine variant hierarchy tree. (#12434) 2 months ago
Peter Nelson de4e00c93f
Codechange: Pass by reference to UpdateWidgetSize. (#12457)
These parameters are always provided and not optional.
2 months ago
translators b5ad28022d Update: Translations from eints
english (au): 5 changes by krysclarke
chinese (simplified): 1 change by WenSimEHRP
catalan: 7 changes by J0anJosep
portuguese (brazilian): 27 changes by pasantoro
2 months ago
Peter Nelson 1b127628cb
Codechange: Use dynamic_cast with FindWindowById. (#12458)
Missed from 74e09ab.
2 months ago
Rubidium bf0cb3c43f Codechange: let lengthof fail when anything that isn't a C-style array is passed
(cherry picked from commit 97bea563d7)
2 months ago
Jonathan G Rennison 28e74005d0 Remove various uses of lengthof on std::array 2 months ago
Rubidium 919830db7a Fix: do not use lengthof() for non C-style arrays
(cherry picked from commit c544a2be0a)
2 months ago
Peter Nelson c5b854a422 Codechange: Avoid lengthof() on std::array.
(cherry picked from commit 295508fc53)
2 months ago
Peter Nelson 9b830e9eb2 Fix: Aircraft crash counter was too low to reach ground. (#12425)
Aircraft can float above the ground when crashed as the counter limit to reach the ground is too low.

Instead reset the counter until the aircraft reaches the ground, then continue the timer.

(cherry picked from commit 83da886093)
2 months ago
Peter Nelson cc6322e0a3 Fix #12233: Mini order list overlaps vehicle group name. (#12423)
Move mini order list down one line to make room.

(cherry picked from commit e8c78df39e)
2 months ago
Peter Nelson df03366cf5 Fix #12114: Viewport coords of crashed aircraft not updated when falling. (#12424)
This results in the aircraft glitching as the wrong viewport area is drawn.

(cherry picked from commit d11622b9a0)
2 months ago
Peter Nelson 7e28605830 Fix: Use reinterpret_cast instead of C-style cast to align pointers. 2 months ago
Peter Nelson 4daf95b878 Fix: Use static_cast instead of C-cast to avoid hidden errors. 2 months ago
Peter Nelson cdfffb551c Fix: sym->sym accidentally changed to sym prevented keys working with SDL. 2 months ago
Peter Nelson 74e09abf76
Codechange: Use dynamic_cast instead of C-cast after FindWindowById. (#12448)
dynamic_cast was used in most places, but not all.
2 months ago
Rubidium 4e6d4fcf32 Codechange: replace for loops with endof with range-based for loops 2 months ago
translators 095bdf32fe Update: Translations from eints
greek: 5 changes by gh658804
finnish: 7 changes by hpiirai
ukrainian: 56 changes by Quantom2, 14 changes by imlystyi
latvian: 14 changes by lexuslatvia
portuguese: 14 changes by azulcosta
portuguese (brazilian): 10 changes by pasantoro
polish: 5 changes by pAter-exe
2 months ago
Rubidium 62f5c595f3 Codechange: use range-based for loops and let count be correct count 2 months ago
rubidium42 4718971ccc Codechange: use std::size instead of lengthof for town names 2 months ago
Peter Nelson 995fca58a2
Codechange: Use begin/end instead of endof for some industry arrays. (#12447) 2 months ago
Rubidium d7fa614a9d Codechange: use range-based for loop for debug levels and fix global variable naming 2 months ago
Rubidium 1fcf1a136d Codechange: use single function returning std::span over two functions that return size and begin 2 months ago
Jonathan G Rennison 89e3b009c3 Fix changing sprite alignment in sprite aligner window 2 months ago
translators 0f6bf90731 Update: Translations from eints 2 months ago
Peter Nelson eb094a953c
Codefix: Social Plugins widget parts were not constexpr. (#12443)
Widget lists were made constexpr except these.
2 months ago
Peter Nelson 34ba969c74
Change: Display more useful information in sprite aligner than sprite ID. (#12439)
Sprite IDs are not useful information given they change don't refer to anything outside the loaded game.

Instead, include the filename and nfo line at minimum, and include action A or action 5 sprite replacement information if applicable.
2 months ago
Peter Nelson fbdf26800b
Codechange: Use std::initializer_list and range-for for credits window. (#12431)
Replaces C-style array, indexed looping, and char * strings.
2 months ago
Peter Nelson a4c2f0778a
Codechange: Use range-for to iterate keycode-to-name lookups. (#12429)
Replaces C-style looping.
2 months ago
Peter Nelson b905209421
Fix: Viewport signs assume small font is smaller than normal font. (#12422)
If the small font is set to a larger size than the normal font for some reason, viewport signs would be drawn incorrect as the area marked dirty only considered the normal size font.
2 months ago
Peter Nelson 830c9e2de8 Codechange: Simplify iteration of framerate performance elements. 2 months ago
Rubidium 97bea563d7 Codechange: let lengthof fail when anything that isn't a C-style array is passed 2 months ago
Rubidium c544a2be0a Fix: do not use lengthof() for non C-style arrays 2 months ago
translators eaafc57de6 Update: Translations from eints
swedish: 6 changes by joeax910
norwegian (bokmal): 2 changes by eriksorngard
chinese (simplified): 2 changes by WenSimEHRP
dutch: 2 changes by Afoklala
2 months ago
Peter Nelson 8e881471c1 Codechange: Pass replacement blitter name as string_view instead char *. 2 months ago
Peter Nelson 6771dbe62b Codechange: Use range-for to find replacement blitter. 2 months ago
Peter Nelson a866166673
Codechange: Use initializer_list and range-for for OpenTTD title. (#12430)
Replaces C-style array and looping.
2 months ago
Peter Nelson 2cc700d606
Codechange: Replace colour_dropdown array with StringID arithmetic. (#12426)
This assumes that the string colours are in order, but that is already assumed elsewhere.

Removes old C-style array access.
2 months ago
Peter Nelson 83da886093
Fix: Aircraft crash counter was too low to reach ground. (#12425)
Aircraft can float above the ground when crashed as the counter limit to reach the ground is too low.

Instead reset the counter until the aircraft reaches the ground, then continue the timer.
2 months ago
Jonathan G Rennison 1a6a4c9a6c Fix path-only signal cycle mode being ignored when using realistic braking 2 months ago
Peter Nelson e8c78df39e
Fix #12233: Mini order list overlaps vehicle group name. (#12423)
Move mini order list down one line to make room.
2 months ago
Peter Nelson d11622b9a0
Fix #12114: Viewport coords of crashed aircraft not updated when falling. (#12424)
This results in the aircraft glitching as the wrong viewport area is drawn.
2 months ago
translators df3e5ade11 Update: Translations from eints
korean: 2 changes by telk5093
portuguese (brazilian): 1 change by pasantoro
2 months ago
Peter Nelson 7572cfd103 Codechange: Redefine ZOOM_LVL so that ZOOM_LVL_NORMAL is 1x zoom.
This matches expectations of what normal zoom means.
2 months ago
Peter Nelson 9854553e10 Codechange: ZOOM_LVL_SHIFT/BASE are not actually ZOOM_LVLs.
Rename to ZOOM_BASE_SHIFT and ZOOM_BASE respectively, and derive from ZOOM_LVL instead of numeric value.
2 months ago
Peter Nelson 3c94e81665 Codechange: Use ZOOM_LVL_MIN to refer to first zoom level.
Many uses of ZOOM_LVL_NORMAL actually just want the first zoom level slot, so use ZOOM_LVL_MIN to make this clearer.
2 months ago
Peter Nelson 7c322ebcf1 Codechange: Define a ZOOM_LVL for minimum text effect visibility. 2 months ago
Peter Nelson 197fb00d31
Fix #12395: Ensure president name widget is tall enough. (#12419) 2 months ago
Peter Nelson 338def1b06
Fix: Segfault when using -q without providing a . character. (#12418)
Use std::filesystem::path to find extension instead of strrchr.
2 months ago
Peter Nelson f6a88e40a4
Codechange: Use std::list for News Items. (#12338) 2 months ago
translators 08cf106fc6 Update: Translations from eints
english (us): 2 changes by 2TallTyler
finnish: 2 changes by hpiirai
ukrainian: 2 changes by Quantom2
danish: 2 changes by beruic
portuguese (brazilian): 22 changes by pasantoro
2 months ago
Jonathan G Rennison a9dbd793b4 Implement Vehicle::GetCargoTile for (multi-part) ships 2 months ago
Loïc Guilloux 3cf43de059 Fix #12415, 9c49a61, df400ef: Aircraft::tile is valid only for front vehicle (#12416)
(cherry picked from commit 243c6bead3)

# Conflicts:
#	src/economy.cpp
2 months ago
Loïc Guilloux 243c6bead3
Fix #12415, 9c49a61, df400ef: Aircraft::tile is valid only for front vehicle (#12416) 2 months ago
translators 931aa39018 Update: Translations from eints
english (au): 2 changes by krysclarke
swedish: 2 changes by joeax910
greek: 2 changes by gh658804
russian: 3 changes by its5Q
catalan: 2 changes by J0anJosep
spanish: 2 changes by MontyMontana
portuguese: 2 changes by azulcosta
portuguese (brazilian): 27 changes by pasantoro
polish: 2 changes by pAter-exe
2 months ago
Peter Nelson 9750826590
Fix a29766d: Wrong scrolling dropdown list position with RTL. (#12412) 2 months ago
translators 72b5c6a591 Update: Translations from eints
vietnamese: 1 change by KhoiCanDev
greek: 83 changes by gh658804
german: 3 changes by Wuzzy2
ukrainian: 54 changes by Quantom2
spanish: 4 changes by MontyMontana
portuguese (brazilian): 2 changes by pasantoro
2 months ago
Peter Nelson 2047c27445 Codechange: Move drop down list item definitions to separate header.
This reduces the scope of the definitions which are no longer needed to create the common lists.
2 months ago
Peter Nelson 56cac21086 Codechange: Use functions to create common drop down list items. 2 months ago
Loïc Guilloux 11aa3694fa
Fix: [Win32] Force font mapper to only use TrueType fonts (#12406) 2 months ago
Peter Nelson f79ec7955a Codechange: Explicitly reset old industry data before loading games. 2 months ago
Peter Nelson 3de8853e29 Codechange: Store accepted and produced cargo in vector instead of array.
Most industries do not use the full 16 slots, so this can save a little memory and iteration time.
2 months ago
Peter Nelson bd2a92331b Codechange: Use inline and std::array for old industry structures.
This avoids separate declaration/definition, and less C-style arrays.
2 months ago
Peter Nelson 00e0021e3a Codechange: Don't assume accepted/produced slot exists. 2 months ago
Peter Nelson 295508fc53 Codechange: Avoid lengthof() on std::array. 2 months ago
Peter Nelson f6b38e8e06 Codechange: Remove optional MakeCargo() parameters that are never changed.
Default values are always used, so don't need to be parameters.
2 months ago
Peter Nelson e4fc8ef595 Codechange: Use std::span for industry cargo window instead of pointer + length. 2 months ago
merni-ns 6f36f3d714
Fix #11055: Make saveload failure error messages consistent with others (#12247)
The save/load error messages were combined using string parameters, rather than using the built-in functionality of error dialogs.
2 months ago
merni-ns 92a171c3e0
Doc: Improve the output and documentation of the font command. (#12392)
Now that the default font =/= sprite font, there is a different way to invoke the sprite font, and default size applies to default (not sprite).
Also, interface scaling now affects the font size.
2 months ago
Peter Nelson d68e5159e1
Feature: Allow base sounds set to be changed mid-game. (#12399) 2 months ago
translators 3d2a8fb60c Update: Translations from eints
welsh: 5 changes by Ansbaradigeidfran
ukrainian: 11 changes by StepanIvasyn
catalan: 1 change by J0anJosep
portuguese (brazilian): 69 changes by pasantoro
2 months ago
Peter Nelson d683ec0183
Codechange: Move dropdown and slider out of widgets directory. (#12403)
Also shuffle headers to place widget includes near end.

This leaves the widgets directory solely for defining Widget IDs.
2 months ago
Jonathan G Rennison 0008e7d769 Fix velocity unit names used in cargo payments graph window 2 months ago
Jonathan G Rennison 4d47eee48d Lang: Update tiles/day and tiles/sec unit name strings 2 months ago
Jonathan G Rennison 6e689c2b93 Fix tiles/day speed unit in wallclock mode 2 months ago
Jonathan G Rennison e041fb8b25 Fix industry window production last month string in wallclock mode 2 months ago
Jonathan G Rennison 9dc332ca59 Fix choppy audio playback of sound effects on Windows
Increase default audio buffer size

See: #680
See: 25aeb1c5
2 months ago
Rubidium d5e28a904d Fix fb9d4af: use different nonces for key exchange and stream encryption 2 months ago
translators 9954187680 Update: Translations from eints
greek: 172 changes by gh658804
ukrainian: 18 changes by StepanIvasyn
portuguese (brazilian): 9 changes by pasantoro
2 months ago
Jonathan G Rennison 083a05a179 Adjust case of vehicle list window drop down items 2 months ago
Jonathan G Rennison d31359f4d2 Saveload: Fix doc comment for SlXvGetFeatureName 2 months ago
Patric Stout 77f02faf15
Codefix 977aba73be: also update comment about removal of is_random (#12400) 2 months ago
Jonathan G Rennison 98f1fb2722 Saveload: Fix NGRF chunks being saved with incorrect table SL_ARR format
Array length prefix was missing

See also: https://github.com/OpenTTD/bananas-api/pull/456
2 months ago
translators 340c2802da Update: Translations from eints
ukrainian: 14 changes by StepanIvasyn
dutch: 3 changes by Afoklala
portuguese (brazilian): 34 changes by pasantoro
2 months ago
Patric Stout e866ca8adc
Cleanup 69d5b9d3: actually clean up all remnants of "no-thread" builds (#12398) 2 months ago
Patric Stout c0308acb03
Fix: "-q" displays NewGRF IDs in the wrong byte-order (#12397) 2 months ago
Jonathan G Rennison 9f7d25e02d TBTR: Fix head state migration when using start/stop callbacks
Don't run start/stop callbacks during head state migration
2 months ago
Jonathan G Rennison 3439d208d7 TBTR: Fix cost estimation of replacement when using wagon attach callbacks
Do not CMD_SELL_VEHICLE in cost estimation, just use the vehicle values
2 months ago
Peter Nelson 8d312b305b
Codechange: Replace currency macros with functions. (#12396) 2 months ago
translators e21c12afeb Update: Translations from eints
finnish: 39 changes by hpiirai
ukrainian: 23 changes by StepanIvasyn
danish: 1 change by bscargo
french: 1 change by Lishouuu
portuguese: 1 change by azulcosta
portuguese (brazilian): 100 changes by pasantoro
2 months ago
Peter Nelson e16b982b6a Codechange: Use iteration when dealing with all HouseSpecs. 2 months ago
Peter Nelson 3e83dcedfd Codechange: Allocate houses dynamically instead of from a fixed array.
This uses vectors for HouseSpecs and global/town building counts.
2 months ago
Peter Nelson 8746be8bf2
Codechange: Use FindVehiclesWithOrder when removing a road stop. (#12144) 2 months ago
frosch 907cb4fc53
Fix: [Script] ScriptSubsidy::GetExpireDate should return an economy-date (#12372) 2 months ago
Michael Lutz 8fb7d74dfe Fix eabb9db: Drag building of road stops should not allow mixing z levels. 2 months ago
Michael Lutz 69acc132ca Fix #12387, eabb9db: [NewGRF] Wrong tile offset passed to rail station CB 149 (slope check) 2 months ago
Loïc Guilloux 71087bb6d3
Change: [CI] Always use latest stable Xcode (#12390) 2 months ago
translators ca53e134be Update: Translations from eints
swedish: 14 changes by sereneavatar
finnish: 2 changes by hpiirai
ukrainian: 18 changes by StepanIvasyn
latvian: 4 changes by lexuslatvia
portuguese (brazilian): 13 changes by pasantoro
2 months ago
Jonathan G Rennison 433484cda3
Fix #12388: Vehicle::CopyVehicleConfigAndStatistics not releasing unit number (#12389) 2 months ago
translators b8b01818ca Update: Translations from eints
english (au): 1 change by krysclarke
norwegian (bokmal): 1 change by eriksorngard
spanish (mexican): 32 changes by rgonzalez-py
english (us): 3 changes by 2TallTyler
russian: 3 changes by Ln-Wolf
ukrainian: 18 changes by StepanIvasyn
lithuanian: 6 changes by dziugas1959
portuguese (brazilian): 11 changes by pasantoro
2 months ago
translators 575336ef43 Update: Translations from eints
swedish: 20 changes by joeax910
greek: 182 changes by gh658804
ukrainian: 11 changes by StepanIvasyn
slovak: 45 changes by puco
lithuanian: 14 changes by dziugas1959
portuguese (brazilian): 11 changes by pasantoro
2 months ago
Rubidium 8e12bd35ae Fix: server shutdown and newgame packets should be stable
The server sends shutdown and newgame (reboot) packets to any connected client.
This can be useful, so you can tell clients that are trying to join that the
server is restarting. However, that means that packets can be sent before a
version check has been done.
So, these packets should be in the stable packet range instead of the one that
is unstable and guarded by a version check.
2 months ago
Peter Nelson 4751179dc5
Codefix: Remove unused class member and extraneous spaces. (#12378) 2 months ago
Rubidium 9aa6669266 Fix: inconsistent check for client authorized status 2 months ago
Rubidium 84bbe235e4 Fix: do not send chat to clients that have not authorized yet 2 months ago
Tyler Trahan f71ada4f30
Fix #12268: Capitalize "Wait to unbunch" order string (#12375) 2 months ago
SamuXarick f845b4bbc3
Fix: Changing NPF max search nodes while in-game had no effect (#12194) 2 months ago
translators 40a75e0b8d Update: Translations from eints
swedish: 19 changes by joeax910
norwegian (bokmal): 2 changes by eriksorngard
ukrainian: 6 changes by StepanIvasyn
french: 3 changes by ottdfevr
portuguese (brazilian): 23 changes by pasantoro
polish: 1 change by pAter-exe
2 months ago
Peter Nelson 97c1738541
Fix #12368: Incorrect offset for click position within industry chain window. (#12370) 2 months ago
Peter Nelson eebfb83aa2
Fix 2fd9096: Label for fruit incorrectly changed to `FRUI` from `FRUT`. (#12367) 2 months ago
Tyler Trahan 8928f4979a
Change: Add dividers in vehicle group action dropdown (#12284) 2 months ago
Rubidium caa7c44052 Cleanup: remove checks for old MSVC versions 2 months ago
Rubidium d09b5aaeba Codechange: use int32_t instead of uint16_t for scroll bar position/size/capacity 2 months ago
Rubidium c01bf06ee1 Codefix: some minor errors in tcp-game protocol documentation 2 months ago
translators 018944dc20 Update: Translations from eints
english (au): 2 changes by krysclarke
vietnamese: 1 change by KhoiCanDev
chinese (simplified): 9 changes by WenSimEHRP
greek: 152 changes by gh658804
russian: 3 changes by Ln-Wolf
finnish: 2 changes by hpiirai
ukrainian: 9 changes by StepanIvasyn
danish: 2 changes by bscargo
portuguese: 5 changes by azulcosta
portuguese (brazilian): 35 changes by pasantoro
2 months ago
Peter Nelson 668186ca5b
Codechange: Remove macros involved with NewGRFClass. (#12363)
Use direct class instantiation instead.
2 months ago
Peter Nelson ff35288ddf
Fix: Don't let CT_INVALID map to valid cargo type. (#12364) 2 months ago
glx22 02c00f3e3e Change: [Script] Use economy time for ScriptDate 2 months ago
glx22 704e871a0e Revert bbdbf9a: ScriptTimeMode was not the best solution for economy/calendar support 2 months ago
frosch 603154899a
Add: [SDL2] Driver parameter 'no_mouse_capture' to ease interactive debugging (#12336) 2 months ago
Rubidium 0f25eaa271 Fix: crash to desktop when attempting to join a company while not joined (yet) 2 months ago
Jonathan G Rennison 515303b8be Fix #12092: Incorrect x-axis in cargo payment graph window 2 months ago
Tyler Trahan 2732b3d6c6
Change: Show unbunching action in timetable window (#12351) 2 months ago
Peter Nelson ea74ca0a76
Fix #12347: Crash attempting to find catchment tiles of a station with no catchment area. (#12348) 2 months ago
Rubidium f599108c16 Codechange: move 'months_empty' to CompanyProperties 2 months ago
translators 4321cca5fb Update: Translations from eints
vietnamese: 1 change by KhoiCanDev
chinese (simplified): 1 change by WenSimEHRP
ukrainian: 11 changes by StepanIvasyn
catalan: 1 change by J0anJosep
danish: 1 change by bscargo
dutch: 3 changes by Afoklala
portuguese (brazilian): 58 changes by pasantoro
2 months ago
Peter Nelson df2ee7b06c
Cleanup: Remove old SaveLoad workarounds for MS VS 2017. (#12355) 2 months ago
Rubidium e904122441 Codefix: follow coding style 2 months ago
merni-ns 7457f8d0ff
Codefix: Incorrect pluralisation in last service/service interval texts (#12352) 2 months ago
raddari 5751da7809
Fix #7982: Show existing coverage with unambiguous adjacent station (#12346)
When hovering a tile containing a station, show existing coverage for
that station even when adjacent to a different station.

Co-authored-by: Peter Nelson <peter@fuzzle.org>
2 months ago
translators e141734e54 Update: Translations from eints
english (au): 1 change by krysclarke
norwegian (bokmal): 1 change by eriksorngard
english (us): 1 change by 2TallTyler
korean: 3 changes by telk5093
german: 1 change by Wuzzy2
finnish: 3 changes by hpiirai
ukrainian: 12 changes by StepanIvasyn
portuguese (brazilian): 81 changes by pasantoro
polish: 1 change by pAter-exe
2 months ago
Jonathan G Rennison 2189607c34 Codechange: Reduce size of class WaterRegion
The tile patch array is 256 bytes and is not needed for the majority
of water regions, change it to be optional via std::unique_ptr
2 months ago
Jonathan G Rennison e42aec5a89 Fix #12305: Crash with large positive sprite x offset in engine preview window 2 months ago
translators 0eaeeaabb6 Update: Translations from eints
russian: 2 changes by Ln-Wolf
catalan: 2 changes by J0anJosep
portuguese (brazilian): 23 changes by pasantoro
2 months ago
Tyler Trahan 704d3b8a9b
Fix #12342: Add missing ellipsis to town generation error string (#12343) 2 months ago
translators 00a09af1fd Update: Translations from eints
english (us): 2 changes by 2TallTyler
vietnamese: 2 changes by KhoiCanDev
german: 2 changes by Wuzzy2
ukrainian: 2 changes by StepanIvasyn
portuguese (brazilian): 9 changes by pasantoro
2 months ago
Owen Rudge d4a6ee9554 Change: [CI] Use Azure Code Signing for Windows build 2 months ago
translators 3a3d8f3b53 Update: Translations from eints
english (au): 2 changes by krysclarke
norwegian (bokmal): 2 changes by eriksorngard
chinese (simplified): 31 changes by lysinelai
greek: 7 changes by Xertoveizer
ukrainian: 14 changes by StepanIvasyn
danish: 2 changes by bscargo
lithuanian: 15 changes by dziugas1959
spanish: 2 changes by MontyMontana
french: 2 changes by glx22
portuguese (brazilian): 52 changes by pasantoro
polish: 2 changes by pAter-exe
2 months ago
Peter Nelson 737e3feaf0
Codechange: Don't delete news items or NewGRF window when EffectVehicle is deleted. (#12334)
EffectVehicles never create news and can't be debugged, so searching for news items and windows to delete just wastes time.
2 months ago
Rubidium 7580eac2d5 Codechange: create helper class for useful NetworkAuthorizedKeys functions 2 months ago
Peter Nelson 2485de9462
Codefix: Widget should be passed as WidgetID type. (#12332) 2 months ago
Peter Nelson 107c208d87
Codechange: Use single list for hierarchical group lists. (#12330)
Replace both group list implementations (vehicle group list and company colour group list) with a single implementation, using a struct to hold the group and indentation level instead of two separate lists. Parts that were previously duplicated are now shared.
2 months ago
translators ec3c8d3462 Update: Translations from eints
ukrainian: 12 changes by StepanIvasyn
portuguese (brazilian): 21 changes by pasantoro
polish: 52 changes by pAter-exe
2 months ago
Rubidium 4af089b9be Feature: console command to change authorized keys 3 months ago
Rubidium b7dfa3eb90 Feature: authorized key authentication for rcon 3 months ago
Rubidium 1cf8799810 Feature: encrypt the connection between game server and client 3 months ago
Rubidium d26629c15b Codechange: make encoded length of packet size and type more explicit 3 months ago
Rubidium 5706801ea7 Feature: authenticate to the server without sending the password
Either using password-authentication key exchange or via authorized keys
3 months ago
Rubidium dd532cbc77 Codechange: add setting for authorized/secret/public keys 3 months ago
Rubidium fb9d4afa5c Codechange: add set of classes providing authentication and encryption 3 months ago
Peter Nelson 88cf99017a
Fix #12302: Allow empty train engines to use an invalid cargo type. (#12325)
The cargo type will be forced to the first available type (usually passengers) instead of the engine being disabled.
3 months ago
Peter Nelson 322ca6ef54 Codechange: Shuffle members of Vehicle to reduce size.
This reduces space wasted due to member alignment.
3 months ago
Peter Nelson 3fc7b3b9a0 Codechange: Cache train curve speed limit can be stored in 16 bits.
Cache curve speed modifier and max curve speed are both 16 bit values so can be stored in 16 bit types instead of 32 bit types.
3 months ago
Patric Stout f08da1d373
Codechange: the "no revision detected" string is with four zeros (norev0000) (#12328) 3 months ago
Peter Nelson ab94c8b511
Codechange: Iterate order lists instead of vehicles to find if any vehicle visits a station. (#12315)
This reduces the search time as shared orders are only searched once and non-front vehicles are skipped.
3 months ago
translators 6c5a8f55df Update: Translations from eints
norwegian (bokmal): 58 changes by eriksorngard
vietnamese: 45 changes by KhoiCanDev
greek: 21 changes by Xertoveizer
ukrainian: 5 changes by StepanIvasyn
tamil: 24 changes by merni-ns
lithuanian: 7 changes by dziugas1959
portuguese (brazilian): 61 changes by pasantoro
polish: 21 changes by aefoes
3 months ago
frosch a886bd9666
Fix #12319, 3a676a5: Some SSE blitters were broken due to ODR violations (#12322) 3 months ago
Patric Stout a3cfd23cf9
Codechange: rename byte to uint8_t (#12308) 3 months ago
Loïc Guilloux bd7120bae4
Fix #12316, 268e512: Support for enum storage type in GenerateWidget.cmake (#12321) 3 months ago
merni-ns af1bd43b30
Codefix 4c0dca1: [CI] Fix typo in workflow file (#12318) 3 months ago
Peter Nelson 0058ebe472
Codechange: Check cheap station-facility-filter before expensive in-use-filter. (#12317) 3 months ago
Loïc Guilloux 818a57c9af
Codechange: Actually use LIT_NONE (#12314) 3 months ago
SamuXarick d7c5e9e8ab Codechange: Where the ship comes from is already known
This simplifies the handling of variables.

`ChooseShipTrack` is called upon entering `tile`, and looking further back to the caller, it can be deduced that `v->tile` matches `src_tile`. With that said, `enterdir` can also be removed, as it's not used anywhere else.

`CreateRandomPath` and `GetRandomFollowUpTrackdir` is being fed `src_tile` as it's 2nd parameter. This could be eliminated, as `v` is also being passed to it. Just use `v->tile` in those functions.
3 months ago
Patric Stout 7f49b6f25a
Codefix: allow preview label on PRs against release branches too (#12310) 3 months ago
Patric Stout 5f4f9334ce
Codefix f1e999ec: use RandomRange(l) instead of _random.Next(l) (#12274) 3 months ago
merni-ns 4c0dca1411
Codechange: [CI] Move Release CI build to MacOS runner (#12309) 3 months ago
Rubidium fe12d38024 Codechange: split initiating of joining and identification of the client 3 months ago
Rubidium 15d02f51ed Codechange: use span to send bytes to Packet and add span recv function 3 months ago
Rubidium b6c75dec3a Codechange: explicitly allow only one state in initial handshake/authorization 3 months ago
Rubidium 26d1d5d6e7 Codechange: move decision whether to check NewGRFs to SendNewGRFCheck, just like for sending game/company passwords 3 months ago
Rubidium 6eff879e49 Codechange: pass the socket handler that is going to send the packet into the packet 3 months ago
Rubidium 3c488e1eb8 Codechange: don't check things outside the lock, that could change while waiting on the lock 3 months ago
Rubidium ec4104ec6c Codechange: do not pass the socket when the receiver already knows it 3 months ago

@ -30,15 +30,10 @@ jobs:
fail-fast: false
matrix:
include:
- name: Clang - Debug
- name: Clang
compiler: clang-15
cxxcompiler: clang++-15
libraries: libsdl2-dev
- name: Clang - Release
compiler: clang-15
cxxcompiler: clang++-15
libraries: libsdl2-dev
extra-cmake-parameters: -DCMAKE_BUILD_TYPE=RelWithDebInfo -DOPTION_USE_ASSERTS=OFF
- name: GCC - SDL2
compiler: gcc
cxxcompiler: g++
@ -66,10 +61,16 @@ jobs:
fail-fast: false
matrix:
include:
- arch: arm64
- name: arm64 - Debug
arch: arm64
full_arch: arm64
extra-cmake-parameters: -DCMAKE_BUILD_TYPE=Debug
- name: arm64 - Release
arch: arm64
full_arch: arm64
extra-cmake-parameters: -DCMAKE_BUILD_TYPE=RelWithDebInfo -DOPTION_USE_ASSERTS=OFF
name: Mac OS (${{ matrix.arch }})
name: Mac OS (${{ matrix.name }})
uses: ./.github/workflows/ci-macos.yml
secrets: inherit
@ -77,6 +78,7 @@ jobs:
with:
arch: ${{ matrix.arch }}
full_arch: ${{ matrix.full_arch }}
extra-cmake-parameters: ${{ matrix.extra-cmake-parameters }}
windows:
strategy:

@ -9,6 +9,10 @@ on:
full_arch:
required: true
type: string
extra-cmake-parameters:
required: false
type: string
default: ""
env:
CTEST_OUTPUT_ON_FAILURE: 1
@ -78,6 +82,7 @@ jobs:
-DCMAKE_OSX_ARCHITECTURES=${{ inputs.full_arch }} \
-DVCPKG_TARGET_TRIPLET=${{ inputs.arch }}-osx \
-DCMAKE_TOOLCHAIN_FILE=${{ runner.temp }}/vcpkg/scripts/buildsystems/vcpkg.cmake \
${{ inputs.extra-cmake-parameters }} \
# EOF
echo "::endgroup::"

@ -7,6 +7,7 @@ on:
- synchronize
branches:
- master
- release/**
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}

@ -94,22 +94,6 @@ jobs:
with:
arch: ${{ matrix.host }}
- name: Import code signing certificate
if: ${{ false }} # Disabled
shell: powershell
# If this is run on a fork, there may not be a certificate set up - continue in this case
continue-on-error: true
run: |
$tempFile = [System.IO.Path]::GetTempFileName()
$bytes = [System.Convert]::FromBase64String($env:WINDOWS_CERTIFICATE_P12)
[IO.File]::WriteAllBytes($tempFile, $bytes)
$pwd = ConvertTo-SecureString $env:WINDOWS_CERTIFICATE_PASSWORD -AsPlainText -Force
Import-PfxCertificate -FilePath $tempFile -CertStoreLocation Cert:\CurrentUser\My -Password $pwd
Remove-Item $tempFile
env:
WINDOWS_CERTIFICATE_P12: ${{ secrets.WINDOWS_CERTIFICATE_P12 }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
- name: Build (with installer)
if: inputs.is_tag == 'true'
shell: bash
@ -126,7 +110,6 @@ jobs:
-DHOST_BINARY_DIR=${GITHUB_WORKSPACE}/build-host \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DOPTION_SURVEY_KEY=${{ inputs.survey_key }} \
-DWINDOWS_CERTIFICATE_COMMON_NAME="${WINDOWS_CERTIFICATE_COMMON_NAME}" \
# EOF
echo "::endgroup::"
@ -134,7 +117,12 @@ jobs:
cmake --build . --target openttd
echo "::endgroup::"
env:
WINDOWS_CERTIFICATE_COMMON_NAME: ${{ secrets.WINDOWS_CERTIFICATE_COMMON_NAME }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_CODESIGN_ACCOUNT_NAME: ${{ secrets.AZURE_CODESIGN_ACCOUNT_NAME }}
AZURE_CODESIGN_ENDPOINT: ${{ secrets.AZURE_CODESIGN_ENDPOINT }}
AZURE_CODESIGN_PROFILE_NAME: ${{ secrets.AZURE_CODESIGN_PROFILE_NAME }}
- name: Build (without installer)
if: inputs.is_tag != 'true'
@ -151,7 +139,6 @@ jobs:
-DHOST_BINARY_DIR=${GITHUB_WORKSPACE}/build-host \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DOPTION_SURVEY_KEY=${{ inputs.survey_key }} \
-DWINDOWS_CERTIFICATE_COMMON_NAME="${WINDOWS_CERTIFICATE_COMMON_NAME}" \
# EOF
echo "::endgroup::"
@ -159,7 +146,12 @@ jobs:
cmake --build . --target openttd
echo "::endgroup::"
env:
WINDOWS_CERTIFICATE_COMMON_NAME: ${{ secrets.WINDOWS_CERTIFICATE_COMMON_NAME }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_CODESIGN_ACCOUNT_NAME: ${{ secrets.AZURE_CODESIGN_ACCOUNT_NAME }}
AZURE_CODESIGN_ENDPOINT: ${{ secrets.AZURE_CODESIGN_ENDPOINT }}
AZURE_CODESIGN_PROFILE_NAME: ${{ secrets.AZURE_CODESIGN_PROFILE_NAME }}
- name: Create bundles
shell: bash
@ -184,13 +176,15 @@ jobs:
- name: Sign installer
if: ${{ false }} # inputs.is_tag == 'true'
shell: bash
# If this is run on a fork, there may not be a certificate set up - continue in this case
continue-on-error: true
run: |
cd ${GITHUB_WORKSPACE}/build/bundles
../../os/windows/sign.bat *.exe "${WINDOWS_CERTIFICATE_COMMON_NAME}"
${GITHUB_WORKSPACE}/os/windows/sign.bat "${GITHUB_WORKSPACE}/build/bundles"
env:
WINDOWS_CERTIFICATE_COMMON_NAME: ${{ secrets.WINDOWS_CERTIFICATE_COMMON_NAME }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_CODESIGN_ACCOUNT_NAME: ${{ secrets.AZURE_CODESIGN_ACCOUNT_NAME }}
AZURE_CODESIGN_ENDPOINT: ${{ secrets.AZURE_CODESIGN_ENDPOINT }}
AZURE_CODESIGN_PROFILE_NAME: ${{ secrets.AZURE_CODESIGN_PROFILE_NAME }}
- name: Store bundles
uses: actions/upload-artifact@v4

@ -1,2 +1,2 @@
jgrpp-0.58.2 20240328 0 64a67d8821b190934b89cf86f9113414927e9cfc 1 0 2024
3ee6e8b554665d66faffae2f50bf57e5e74e66ac4983062b0480695ff21d8bb1 -
jgrpp-0.59.1 20240519 0 5e971bfc026aa9a58773d89c583e78765156b9e4 1 0 2024
f0d82005ae0e64dc0f833d5cbd6776afb06c9a513cc83119ce8fd0a2e5be097b -

@ -248,7 +248,7 @@ Templates are a very powerful C++ tool, but they can easily confuse beginners. T
* Templates are to be documented in a very clear and verbose manner. Never assume anything in the documentation.
* the template keyword and the template layout get a separate line. typenames are either "T" or preceded by a "T", integers get a single capital letter or a descriptive name preceded by "T".
```c++
template <typename T, typename Tsomething, int N, byte Tnumber_of_something>
template <typename T, typename Tsomething, int N, uint8_t Tnumber_of_something>
int Func();
```

@ -110,9 +110,6 @@ builds.
- `-DOPTION_USE_ASSERTS=OFF`: disable asserts. Use with care, as assert
statements capture early signs of trouble. Release builds have them
disabled by default.
- `-DOPTION_USE_THREADS=OFF`: disable the use of threads. This will block
the interface in many places, and in general gives a worse experience of
the game. Use with care.
- `-DOPTION_TOOLS_ONLY=ON`: only build tools like `strgen`. Does not build
the game itself. Useful for cross-compiling.

@ -1,6 +1,10 @@
## JGR's Patchpack version 0.58.2
## JGR's Patchpack version 0.59.1
This is a collection of patches applied to [OpenTTD](http://www.openttd.org/)
This is a collection of features and other modifications applied to [OpenTTD](http://www.openttd.org/).
It's a separate version of the game which can be installed and played alongside the standard game, not a loadable mod (NewGRF, script, or so on).
This is mainly intended to be used by players who are already familiar with the standard game and how to play it.
It is not aimed at beginner/novice players. Some features and settings are there for very experienced players and so may have a steep learning curve.
* * *
@ -16,14 +20,14 @@ section "Licensing" below for details,
See [below](#openttd) for the original OpenTTD readme.
The thread for this patchpack can be found [here](http://www.tt-forums.net/viewtopic.php?f=33&t=73469).
See [jgrpp-changelog.md](jgrpp-changelog.md) for the changelog.
See the [wiki](https://github.com/JGRennison/OpenTTD-patches/wiki) for guides on how to use some of the included features.
See [installation.md](/installation.md) for instructions on how to install.
The TT-Forums thread for this patchpack can be found [here](http://www.tt-forums.net/viewtopic.php?f=33&t=73469).
(Nearly all of the patches which are listed below have been modified, fixed or extended in some way, and so are not the same as the originals which are linked).
#### Railways and Trains
@ -116,7 +120,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* Open train vehicle details window on total cargo tab if shift pressed.
* Add news/advice setting to warn if no depot order in vehicle schedule.
* [Add buttons to collapse/expand all groups](http://www.tt-forums.net/viewtopic.php?f=33&t=74365).
* Add a menu item to the vehicle list to assign all listed vehicles to a new group.
* Add a setting to include the train length and group name in the vehicle details window.
* Add a setting for whether to open the new vehicle GUI when share-cloning.
* Add setting to disable mass action buttons for top-level vehicle lists.
@ -132,7 +135,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* [Automated timetables and separation](http://www.tt-forums.net/viewtopic.php?f=33&t=46391).
* Allow clearing of timetable time fields which are at 0. Allow explicitly setting timetable time fields to 0 without clearing them.
* Allow changing/clearing the timetabled waiting time and max speed of all of a vehicle's orders at once.
* Add client setting to show the remainder ticks in timetable, after dividing to days or minutes.
* Add a company setting to control the number of ticks used in auto-fill timetable rounding.
* [Cargo type orders](https://www.tt-forums.net/viewtopic.php?p=1047749).
@ -167,7 +169,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* [Departure boards](https://www.tt-forums.net/viewtopic.php?f=33&t=49956).
* Add road waypoints.
* Add NewGRF road stops.
* Add a setting to increase the station catchment radius.
* Station rating: track "last visited vehicle type" separately per cargo.
* Add setting to scale station cargo capacity and rating tolerance by size.
@ -188,7 +189,6 @@ See [installation.md](/installation.md) for instructions on how to install.
#### Towns
* [Town cargo generation factor](http://www.tt-forums.net/viewtopic.php?t=46399).
* [Rating in town label](http://www.tt-forums.net/viewtopic.php?f=33&t=42598).
* [Random town road reconstruction](https://www.tt-forums.net/viewtopic.php?f=33&t=36438). This defaults to off.
* Add very and extremely slow options to town growth rate setting.
@ -205,7 +205,6 @@ See [installation.md](/installation.md) for instructions on how to install.
#### Industries
* Industry cargo generation factor.
* Allow linking only inputs or outputs to the smallmap and map mode viewports in the industry chain window.
#### Map and Landscaping
@ -215,7 +214,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* Add a new tree placement mode (perfect).
* [Minimum town distance](https://www.tt-forums.net/viewtopic.php?f=33&t=33625).
* Add map generation settings to control river/lake, rocky patch, and tropic zone generation.
* Add generation of wide rivers.
* Add settings to customise the size of town zones, and city zones.
* Add setting to show purchased land using clear tile ground sprites (dirt, grass, snow, desert, etc).
@ -223,7 +221,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* Enable building rivers in game. Off by default.
* Add a setting to disable removing sea/rivers.
* Allow building objects by area (1x1 objects only).
* Allow purchasing a region of tiles at once, by dragging.
* Add setting to control if and how land purchasing is permitted.
* Add a company rate limit for land purchasing.
@ -305,7 +302,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* Add setting to allow non server admins to use the money cheat in multiplayer.
* Allow clicking the money text in the cheats window to enter a quantity.
* Add cheats to set inflation income and cost factors.
* Add cheat to set all station ratings to 100%.
* Add cheat to set all town local authority ratings to Outstanding.
#### Cargo Distribution and Link Graph
@ -324,7 +320,6 @@ See [installation.md](/installation.md) for instructions on how to install.
#### Console and Scripts
* Add basic tab-completion to the console window.
* Add console commands for conditional execution from game date.
* [Daily/monthly/yearly scripts](http://www.tt-forums.net/viewtopic.php?f=33&t=49595)

@ -171,10 +171,10 @@ elseif(WIN32)
set(CPACK_PACKAGE_FILE_NAME "openttd-#CPACK_PACKAGE_VERSION#-windows-${CPACK_SYSTEM_NAME}")
if(WINDOWS_CERTIFICATE_COMMON_NAME)
if(DEFINED ENV{AZURE_CODESIGN_PROFILE_NAME})
add_custom_command(TARGET openttd
POST_BUILD
COMMAND "${CMAKE_SOURCE_DIR}/os/windows/sign.bat" "$<TARGET_FILE:openttd>" "${WINDOWS_CERTIFICATE_COMMON_NAME}"
COMMAND "${CMAKE_SOURCE_DIR}/os/windows/sign.bat" "${BINARY_DESTINATION_DIR}"
)
endif()
elseif(UNIX)

@ -57,13 +57,6 @@ function(set_options)
option(OPTION_DEDICATED "Build dedicated server only (no GUI)" OFF)
option(OPTION_INSTALL_FHS "Install with Filesystem Hierarchy Standard folders" ${DEFAULT_OPTION_INSTALL_FHS})
option(OPTION_USE_ASSERTS "Use assertions; leave enabled for nightlies, betas, and RCs" ON)
if(EMSCRIPTEN)
# Although pthreads is supported, it is not in a way yet that is
# useful for us.
option(OPTION_USE_THREADS "Use threads" OFF)
else()
option(OPTION_USE_THREADS "Use threads" ON)
endif()
option(OPTION_USE_NSIS "Use NSIS to create windows installer; enable only for stable releases" OFF)
option(OPTION_TOOLS_ONLY "Build only tools target" OFF)
option(OPTION_DOCS_ONLY "Build only docs target" OFF)
@ -85,7 +78,6 @@ function(show_options)
message(STATUS "Option Dedicated - ${OPTION_DEDICATED}")
message(STATUS "Option Install FHS - ${OPTION_INSTALL_FHS}")
message(STATUS "Option Use assert - ${OPTION_USE_ASSERTS}")
message(STATUS "Option Use threads - ${OPTION_USE_THREADS}")
message(STATUS "Option Use NSIS - ${OPTION_USE_NSIS}")
if(OPTION_SURVEY_KEY)
@ -109,10 +101,6 @@ function(add_definitions_based_on_options)
add_definitions(-DDEDICATED)
endif()
if(NOT OPTION_USE_THREADS)
add_definitions(-DNO_THREADS)
endif()
if(OPTION_USE_ASSERTS)
add_definitions(-DWITH_ASSERT)
else()

@ -56,11 +56,14 @@ foreach(ENUM IN LISTS ENUM_LINES)
endif()
# Check for enum match
if("${LINE}" MATCHES "^ *enum *${ENUM_PATTERN} *\{")
if("${LINE}" MATCHES "^ *enum *${ENUM_PATTERN}( *: *[^ ]*)? *\{")
# REGEX REPLACE does a REGEX MATCHALL and fails if an empty string is matched
string(REGEX MATCH "[^ ]*" RESULT "${LINE}")
string(REPLACE "${RESULT}" "" RM_INDENT "${LINE}")
string(REGEX MATCH " *: *[^ ]*" RESULT "${LINE}")
string(REPLACE "${RESULT}" "" LINE "${LINE}")
set(ACTIVE 1)
if(ACTIVE_COMMENT GREATER 0)
string(APPEND ${PLACE_HOLDER} "\n${COMMENT}")

@ -129,8 +129,8 @@
<tr><td>stop_type</td><td>RST_TYPE_XXX</td><td>XXX = BUS | TRUCK | WAYPOINT (<b>Not in standard specification</b>)</td></tr>
<tr><td>terrain_type</td><td>TILETYPE_XXX</td><td>XXX = NORMAL | DESERT | RAIN_FOREST | SNOW</td></tr>
<tr><td>tile_slope</td><td>SLOPE_XXX</td><td>See <a href="https://newgrf-specs.tt-wiki.net/wiki/NML:List_of_tile_slopes">tile slopes</a> for an overview of possible values</td></tr>
<tr><td>has_road</td><td>0 | 1</td><td>1 is this road stop has road</td></tr>
<tr><td>has_tram</td><td>0 | 1</td><td>1 is this road stop has tram</td></tr>
<tr><td>has_road</td><td>0 | 1</td><td>1 if this road stop has road</td></tr>
<tr><td>has_tram</td><td>0 | 1</td><td>1 if this road stop has tram</td></tr>
<tr><td>road_type</td><td>road type | 0xFF</td><td>Road type. If there is no road the value will be 0xFF. If the roadtype has no entry in the roadtype translation table of the GRF, this value will be 0xFF. If no translation table is present, the raw value will be returned.</td></tr>
<tr><td>tram_type</td><td>tram type | 0xFF</td><td>Tram type. If there is no tram the value will be 0xFF. If the tramtype has no entry in the tramtype translation table of the GRF, this value will be 0xFF. If no translation table is present, the raw value will be returned.</td></tr>
<tr><td>town_manhattan_dist</td><td></td><td>Manhattan distance to the associated town</td></tr>
@ -142,7 +142,6 @@
<tr><td>company_colour2</td><td>COLOUR_XXX</td><td></td></tr>
<tr><td>animation_frame</td><td>0..255</td><td>Animation frame of the current tile</td></tr>
<tr><td>waiting_triggers</td><td>0..255</td><td>Waiting triggers</td></tr>
<tr><td>random_bits</td><td>0..16777215</td><td>All random bits</td></tr>
<tr><td>random_bits_tile</td><td>0..255</td><td>Random bits (per tile), see also <a href="https://newgrf-specs.tt-wiki.net/wiki/NML:Stations#Base_station_variables">random_bits_station</a></td></tr>
<tr><td>one_way_info<br /><b>Not in standard specification</b></td><td>RST_OWI_XXX</td><td>One-way road information of drive-through stop tile<br />XXX = TWO_WAY | WEST_BOUND | EAST_BOUND | NO_ENTRY</td></tr>
<tr><td>one_way_info_inferred<br /><b>Not in standard specification</b></td><td>RST_OWI_XXX</td><td>Inferred one-way road information of drive-through stop tile<br />XXX = TWO_WAY | WEST_BOUND | EAST_BOUND | NO_ENTRY</td></tr>

@ -74,7 +74,7 @@
<ul>
<li>The number of houses in the town changes</li>
<li>When the game is loaded</li>
<li>When settings, NewGRFs or other relavant game configuration is changed</li>
<li>When settings, NewGRFs or other relevant game configuration is changed</li>
</ul>
</p>

@ -105,7 +105,7 @@
<ul>
<li>The number of houses in the town changes</li>
<li>When the game is loaded</li>
<li>When settings, NewGRFs or other relavant game configuration is changed</li>
<li>When settings, NewGRFs or other relevant game configuration is changed</li>
</ul>
</p>

@ -2,6 +2,59 @@
* * *
### v0.59.1 (2024-05-20)
* Fix crash when sorting by capacity in autoreplace window.
* Fix non-percentage servicing interval when using wallclock mode.
* Fix road vehicles skipping orders when using implicit orders.
* Fix setting default value for industry cargo scaling mode when loading old savegames.
* Fix setting display for industry cargo scaling.
* Fix crash which could occur when using autorenew/autoreplace wagon removal with leading engines longer than the train length limit.
* Fix crash which could occur with loading certain GRFs.
* Fix multiplayer desync when joining a server after previously loading a scenario.
* Fix keyboard input issues on Linux/SDL.
* Realistic braking:
* Fix accuracy issues with realistic acceleration and braking when a train is underpowered for ascending or descending a steep slope.
* Reduce sensitivity of train brakes overheated breakdown.
* Add setting to shorten vehicle view status text.
* Bump trunk base from commit bd7120bae41b6e7ac86c664c8220b59cd57242bb to commit 88cf99017a26f887230d2c14d057a97bbf077f7c.
### v0.59.0 (2024-05-05)
* Fix loading recent vanilla savegame versions resulting in incorrect industry cargoes.
* Fix incorrect station catchment/acceptance which could occur when an oil rig/water industry completed construction, which could cause multiplayer desyncs.
* Fix AI construction of block signals when using realistic braking.
* Fix incorrect train weights being used for calculating infrastructure sharing track fees.
* Fix vehicles leaving dots behind in viewport map mode in some cases.
* Fix NewGRF train motion animations for some NewGRFs which use articulated engines.
* Fix template-based train replacement not triggering replacements for companies nominally in debt when using the infinite money setting.
* Fix text filters in dual-pane train purchase window when using NewGRFs with variable vehicle names.
* Road vehicles no longer remaining loading when the next order is for the same station if the next order has a different required direction.
* Enable the cargo capacity/running cost sort mode in the dual pane train purchase window.
* The vehicle capacity sort modes in the build vehicle windows now take into account the selected refit cargo.
* Timekeeping:
* The day length factor setting is now enabled in wallclock timekeeping mode. This scales the economy speed, but not the calendar speed.
* Fix timing of engine preview offers in wallclock timekeeping mode.
* Scheduled dispatch:
* When using scheduled dispatch and timetable automation at the same time, vehicle lateness values are no longer reset when congestion is detected.
* The number of vehicles required text is now clarified to be an estimate.
* Further increase effect size of cargo dist effect of distance on demand setting for values greater than 100%.
* Further reduce the possibility of stuttering when playing sound effects on Windows.
* Bump trunk base from commit 3e625b5b1a81b00f774ca87b48d3e4f4e9d014c3 to commit bd7120bae41b6e7ac86c664c8220b59cd57242bb.
### v0.58.3 (2024-04-10)
* Fix stuttering when playing sound effects on Windows.
* Fix incorrect cargo payment calculations for cargo in the mail compartment of aircraft and in non-first parts of multi-part ships.
* Fix path-only signal cycle mode being ignored when using realistic braking.
* Template-based train replacement:
* Fix replacement failing when using NewGRFs with complex wagon attachment and/or start/stop restrictions.
* Fix incorrect cost estimation when using NewGRFs with complex start/stop restrictions.
* Wallclock timekeeping mode:
* Fix game units (tiles/second) being shown as tiles/day.
* Fix time units shown for past production in the industry window.
* Fix cargo dist effect of distance on demand setting for values greater than 100%. (The scaling/demand allocation algorithm has been adjusted in general).
* Fix velocity units used in cargo payments graph x-axis label.
* Fix click/tooltip alignment of cargo lines in the industry chains window.
* Fix changing sprite alignments in the sprite aligner window not being applied as expected.
### v0.58.2 (2024-03-28)
* Fix crash with some GRFs when the maximum sprite resolution setting was set to 2x.
* Fix crash which could occur when clearing a crashed road vehicle from a drive-through road stop.

@ -1,18 +1,2 @@
@echo off
REM Signing script
REM Arguments: sign.bat exe_to_sign certificate_subject_name
REM This is a loose wrapper around the Microsoft signtool application (included in the Windows SDK).
REM See https://docs.microsoft.com/en-us/dotnet/framework/tools/signtool-exe for more details.
REM Path to signtool.exe
IF NOT DEFINED SIGNTOOL_PATH (SET SIGNTOOL_PATH=signtool)
REM URL of the timestamp server
IF NOT DEFINED SIGNTOOL_TIMESTAMP_URL (SET SIGNTOOL_TIMESTAMP_URL=http://timestamp.digicert.com)
REM Sign with SHA-1 for Windows 7 and below
"%SIGNTOOL_PATH%" sign -v -n %2 -t %SIGNTOOL_TIMESTAMP_URL% -fd sha1 %1
REM Sign with SHA-256 for Windows 8 and above
"%SIGNTOOL_PATH%" sign -v -n %2 -tr %SIGNTOOL_TIMESTAMP_URL% -fd sha256 -td sha256 -as %1
pwsh -File "%~dp0sign_azure.ps1" %1

@ -0,0 +1,40 @@
# Signing script for Azure Code Signing
# Arguments: sign_azure.ps1 path_to_sign
#
# Environment variables must be set up before use:
#
# AZURE_TENANT_ID
# AZURE_CLIENT_ID
# AZURE_CLIENT_SECRET
# AZURE_CODESIGN_ACCOUNT_NAME
# AZURE_CODESIGN_ENDPOINT
# AZURE_CODESIGN_PROFILE_NAME
Param
(
# Files folder
[Parameter(Mandatory=$true, Position=0)]
$FilesFolder
)
if (!$Env:AZURE_CODESIGN_ENDPOINT -or !$Env:AZURE_CODESIGN_ACCOUNT_NAME -or !$Env:AZURE_CODESIGN_PROFILE_NAME -or
!$Env:AZURE_TENANT_ID -or !$Env:AZURE_CLIENT_ID -or !$Env:AZURE_CLIENT_SECRET)
{
"Code signing variables not found; most likely running in a fork. Skipping signing."
exit
}
Install-Module -Name AzureCodeSigning -Scope CurrentUser -RequiredVersion 0.3.0 -Force -Repository PSGallery
$params = @{}
$params["Endpoint"] = $Env:AZURE_CODESIGN_ENDPOINT
$params["CodeSigningAccountName"] = $Env:AZURE_CODESIGN_ACCOUNT_NAME
$params["CertificateProfileName"] = $Env:AZURE_CODESIGN_PROFILE_NAME
$params["FilesFolder"] = $FilesFolder
$params["FilesFolderFilter"] = "exe"
$params["FileDigest"] = "SHA256"
$params["TimestampRfc3161"] = "http://timestamp.acs.microsoft.com"
$params["TimestampDigest"] = "SHA256"
Invoke-AzureCodeSigning @params

@ -59,8 +59,8 @@
static const size_t MD5_HASH_BYTES = 16;
/** Container for storing a MD5 hash/checksum/digest. */
struct MD5Hash : std::array<byte, MD5_HASH_BYTES> {
MD5Hash() : std::array<byte, MD5_HASH_BYTES>{} {}
struct MD5Hash : std::array<uint8_t, MD5_HASH_BYTES> {
MD5Hash() : std::array<uint8_t, MD5_HASH_BYTES>{} {}
/**
* Exclusively-or the given hash into this hash.

@ -147,6 +147,10 @@ add_files(
dock_gui.cpp
driver.cpp
driver.h
dropdown.cpp
dropdown_common_type.h
dropdown_func.h
dropdown_type.h
economy.cpp
economy_base.h
economy_func.h
@ -161,6 +165,7 @@ add_files(
engine_func.h
engine_gui.cpp
engine_gui.h
engine_override.h
engine_type.h
error.h
error_gui.cpp
@ -258,6 +263,7 @@ add_files(
music_gui.cpp
newgrf.cpp
newgrf.h
newgrf_act5.h
newgrf_airport.cpp
newgrf_airport.h
newgrf_airporttiles.cpp
@ -280,6 +286,7 @@ add_files(
newgrf_config.h
newgrf_debug.h
newgrf_debug_gui.cpp
newgrf_dump.h
newgrf_engine.cpp
newgrf_engine.h
newgrf_extension.cpp
@ -420,6 +427,8 @@ add_files(
signs_func.h
signs_gui.cpp
signs_type.h
slider.cpp
slider_func.h
slope_func.h
slope_type.h
smallmap_colours.h

@ -127,20 +127,20 @@ struct AIConfigWindow : public Window {
}
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_AIC_DECREASE_NUMBER:
case WID_AIC_INCREASE_NUMBER:
case WID_AIC_DECREASE_INTERVAL:
case WID_AIC_INCREASE_INTERVAL:
*size = maxdim(*size, NWidgetScrollbar::GetHorizontalDimension());
size = maxdim(size, NWidgetScrollbar::GetHorizontalDimension());
break;
case WID_AIC_LIST:
this->line_height = GetCharacterHeight(FS_NORMAL) + padding.height;
resize->height = this->line_height;
size->height = 8 * this->line_height;
resize.height = this->line_height;
size.height = 8 * this->line_height;
break;
}
}

@ -67,22 +67,24 @@ int GetAircraftFlightLevel(T *v, bool takeoff = false);
struct AircraftCache {
uint32_t cached_max_range_sqr; ///< Cached squared maximum range.
uint16_t cached_max_range; ///< Cached maximum range.
byte image_movement_state; ///< Cached image aircraft movement state
uint8_t image_movement_state; ///< Cached image aircraft movement state
bool operator==(const AircraftCache &) const = default;
};
/**
* Aircraft, helicopters, rotors and their shadows belong to this class.
*/
struct Aircraft final : public SpecializedVehicle<Aircraft, VEH_AIRCRAFT> {
uint16_t crashed_counter; ///< Timer for handling crash animations.
byte pos; ///< Next desired position of the aircraft.
byte previous_pos; ///< Previous desired position of the aircraft.
StationID targetairport; ///< Airport to go to next.
byte state; ///< State of the airport. @see AirportMovementStates
uint16_t crashed_counter; ///< Timer for handling crash animations.
uint8_t pos; ///< Next desired position of the aircraft.
uint8_t previous_pos; ///< Previous desired position of the aircraft.
StationID targetairport; ///< Airport to go to next.
uint8_t state; ///< State of the airport. @see AirportMovementStates
Direction last_direction;
byte number_consecutive_turns; ///< Protection to prevent the aircraft of making a lot of turns in order to reach a specific point.
byte turn_counter; ///< Ticks between each turn to prevent > 45 degree turns.
byte flags; ///< Aircraft flags. @see AirVehicleFlags
uint8_t number_consecutive_turns; ///< Protection to prevent the aircraft of making a lot of turns in order to reach a specific point.
uint8_t turn_counter; ///< Ticks between each turn to prevent > 45 degree turns.
uint8_t flags; ///< Aircraft flags. @see AirVehicleFlags
AircraftCache acache;
@ -114,6 +116,7 @@ struct Aircraft final : public SpecializedVehicle<Aircraft, VEH_AIRCRAFT> {
void OnPeriodic() override;
uint Crash(bool flooded = false) override;
TileIndex GetOrderStationLocation(StationID station) override;
TileIndex GetCargoTile() const override { return this->First()->tile; }
ClosestDepot FindClosestDepot() override;
/**
@ -145,6 +148,6 @@ void GetRotorImage(const Aircraft *v, EngineImageType image_type, VehicleSpriteS
Station *GetTargetAirportIfValid(const Aircraft *v);
void HandleMissingAircraftOrders(Aircraft *v);
const char *AirportMovementStateToString(byte state);
const char *AirportMovementStateToString(uint8_t state);
#endif /* AIRCRAFT_H */

@ -692,7 +692,7 @@ static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE,
* ~ acceleration * 77 (km-ish/h / 256)
*/
uint spd = v->acceleration * 77;
byte t;
uint8_t t;
/* Adjust speed limits by plane speed factor to prevent taxiing
* and take-off speeds being too low. */
@ -710,7 +710,7 @@ static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE,
speed_limit = v->vcache.cached_max_speed;
}
v->subspeed = (t = v->subspeed) + (byte)spd;
v->subspeed = (t = v->subspeed) + (uint8_t)spd;
/* Aircraft's current speed is used twice so that very fast planes are
* forced to slow down rapidly in the short distance needed. The magic
@ -737,7 +737,7 @@ static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE,
spd = v->GetOldAdvanceSpeed(spd);
spd += v->progress;
v->progress = (byte)spd;
v->progress = (uint8_t)spd;
return spd >> 8;
}
@ -861,7 +861,7 @@ template int GetAircraftFlightLevel(Aircraft *v, bool takeoff);
* @param rotation The rotation of the airport.
* @return The index of the entry point
*/
static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
static uint8_t AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
{
assert(v != nullptr);
assert(apc != nullptr);
@ -1269,10 +1269,13 @@ static bool HandleCrashedAircraft(Aircraft *v)
if (v->crashed_counter < 500 && st == nullptr && ((v->crashed_counter % 3) == 0) ) {
int z = GetSlopePixelZ(Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE), Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE));
v->z_pos -= 1;
if (v->z_pos == z) {
if (v->z_pos <= z) {
v->crashed_counter = 500;
v->z_pos++;
v->z_pos = z + 1;
} else {
v->crashed_counter = 0;
}
SetAircraftPosition(v, v->x_pos, v->y_pos, v->z_pos);
}
if (v->crashed_counter < 650) {
@ -1772,7 +1775,7 @@ static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
/* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
* if it is an airplane, look for LANDING, for helicopter HELILANDING
* it is possible to choose from multiple landing runways, so loop until a free one is found */
byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
uint8_t landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
const AirportFTA *current = apc->layout[v->pos].next;
while (current != nullptr) {
if (current->heading == landingtype) {
@ -1919,8 +1922,8 @@ static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
const AirportFTA *current = &apc->layout[v->pos];
/* we have arrived in an important state (eg terminal, hangar, etc.) */
if (current->heading == v->state) {
byte prev_pos = v->pos; // location could be changed in state, so save it before-hand
byte prev_state = v->state;
uint8_t prev_pos = v->pos; // location could be changed in state, so save it before-hand
uint8_t prev_state = v->state;
_aircraft_state_handlers[v->state](v, apc);
if (v->state != FLYING) v->previous_pos = prev_pos;
if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
@ -2056,7 +2059,7 @@ static const MovementTerminalMapping _airport_terminal_mapping[] = {
* @param last_terminal Terminal number to stop examining.
* @return A terminal or helipad has been found, and has been assigned to the aircraft.
*/
static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
static bool FreeTerminal(Aircraft *v, uint8_t i, uint8_t last_terminal)
{
assert(last_terminal <= lengthof(_airport_terminal_mapping));
Station *st = Station::Get(v->targetairport);
@ -2256,8 +2259,8 @@ bool Aircraft::Tick()
}
if (HasBit(this->vcache.cached_veh_flags, VCF_REDRAW_ON_SPEED_CHANGE)) {
extern byte MapAircraftMovementState(const Aircraft *v);
byte state = MapAircraftMovementState(this);
extern uint8_t MapAircraftMovementState(const Aircraft *v);
uint8_t state = MapAircraftMovementState(this);
if (state != this->acache.image_movement_state) {
this->InvalidateImageCacheOfChain();
this->acache.image_movement_state = state;
@ -2314,7 +2317,7 @@ void UpdateAirplanesOnNewStation(const Station *st)
if (!st->airport.HasHangar()) RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, st->index, true);
}
const char *AirportMovementStateToString(byte state)
const char *AirportMovementStateToString(uint8_t state)
{
#define AMS(s) case s: return #s;
switch (state) {

@ -110,12 +110,12 @@ AirportMovingData RotateAirportMovingData(const AirportMovingData *orig, Directi
AirportFTAClass::AirportFTAClass(
const AirportMovingData *moving_data_,
const byte *terminals_,
const byte num_helipads_,
const byte *entry_points_,
const uint8_t *terminals_,
const uint8_t num_helipads_,
const uint8_t *entry_points_,
Flags flags_,
const AirportFTAbuildup *apFA,
byte delta_z_
uint8_t delta_z_
) :
moving_data(moving_data_),
terminals(terminals_),
@ -204,7 +204,7 @@ static AirportFTA *AirportBuildAutomata(uint nofelements, const AirportFTAbuildu
* @param airport_type %Airport type to query FTA from. @see AirportTypes
* @return Finite state machine of the airport.
*/
const AirportFTAClass *GetAirport(const byte airport_type)
const AirportFTAClass *GetAirport(const uint8_t airport_type)
{
if (airport_type == AT_DUMMY) return &_airportfta_dummy;
return AirportSpec::Get(airport_type)->fsm;
@ -215,7 +215,7 @@ const AirportFTAClass *GetAirport(const byte airport_type)
* @param hangar_tile The tile on which the vehicle is build
* @return The position (index in airport node array) where the aircraft ends up
*/
byte GetVehiclePosOnBuild(TileIndex hangar_tile)
uint8_t GetVehiclePosOnBuild(TileIndex hangar_tile)
{
const Station *st = Station::GetByTile(hangar_tile);
const AirportFTAClass *apc = st->airport.GetFTA();

@ -152,12 +152,12 @@ public:
AirportFTAClass(
const AirportMovingData *moving_data,
const byte *terminals,
const byte num_helipads,
const byte *entry_points,
const uint8_t *terminals,
const uint8_t num_helipads,
const uint8_t *entry_points,
Flags flags,
const AirportFTAbuildup *apFA,
byte delta_z
uint8_t delta_z
);
~AirportFTAClass();
@ -167,7 +167,7 @@ public:
* @param position Element number to get movement data about.
* @return Pointer to the movement data.
*/
const AirportMovingData *MovingData(byte position) const
const AirportMovingData *MovingData(uint8_t position) const
{
assert(position < nofelements);
return &moving_data[position];
@ -175,12 +175,12 @@ public:
const AirportMovingData *moving_data; ///< Movement data.
struct AirportFTA *layout; ///< state machine for airport
const byte *terminals; ///< %Array with the number of terminal groups, followed by the number of terminals in each group.
const byte num_helipads; ///< Number of helipads on this airport. When 0 helicopters will go to normal terminals.
const uint8_t *terminals; ///< %Array with the number of terminal groups, followed by the number of terminals in each group.
const uint8_t num_helipads; ///< Number of helipads on this airport. When 0 helicopters will go to normal terminals.
Flags flags; ///< Flags for this airport type.
byte nofelements; ///< number of positions the airport consists of
const byte *entry_points; ///< when an airplane arrives at this airport, enter it at position entry_point, index depends on direction
byte delta_z; ///< Z adjustment for helicopter pads
uint8_t nofelements; ///< number of positions the airport consists of
const uint8_t *entry_points; ///< when an airplane arrives at this airport, enter it at position entry_point, index depends on direction
uint8_t delta_z; ///< Z adjustment for helicopter pads
};
DECLARE_ENUM_AS_BIT_SET(AirportFTAClass::Flags)
@ -190,12 +190,12 @@ DECLARE_ENUM_AS_BIT_SET(AirportFTAClass::Flags)
struct AirportFTA {
AirportFTA *next; ///< possible extra movement choices from this position
uint64_t block; ///< 64 bit blocks (st->airport.flags), should be enough for the most complex airports
byte position; ///< the position that an airplane is at
byte next_position; ///< next position from this position
byte heading; ///< heading (current orders), guiding an airplane to its target on an airport
uint8_t position; ///< the position that an airplane is at
uint8_t next_position; ///< next position from this position
uint8_t heading; ///< heading (current orders), guiding an airplane to its target on an airport
};
const AirportFTAClass *GetAirport(const byte airport_type);
byte GetVehiclePosOnBuild(TileIndex hangar_tile);
const AirportFTAClass *GetAirport(const uint8_t airport_type);
uint8_t GetVehiclePosOnBuild(TileIndex hangar_tile);
#endif /* AIRPORT_H */

@ -22,7 +22,8 @@
#include "station_type.h"
#include "newgrf_airport.h"
#include "newgrf_callbacks.h"
#include "widgets/dropdown_type.h"
#include "dropdown_type.h"
#include "dropdown_func.h"
#include "core/geometry_func.hpp"
#include "hotkeys.h"
#include "vehicle_func.h"
@ -36,11 +37,11 @@
static AirportClassID _selected_airport_class; ///< the currently visible airport class
static int _selected_airport_index; ///< the index of the selected airport in the current class or -1
static byte _selected_airport_layout; ///< selected airport layout number.
static uint8_t _selected_airport_layout; ///< selected airport layout number.
static void ShowBuildAirportPicker(Window *parent);
SpriteID GetCustomAirportSprite(const AirportSpec *as, byte layout);
SpriteID GetCustomAirportSprite(const AirportSpec *as, uint8_t layout);
void CcBuildAirport(const CommandCost &result, TileIndex tile, uint32_t p1, uint32_t p2, uint64_t p3, uint32_t cmd)
{
@ -233,7 +234,7 @@ class BuildAirportWindow : public PickerWindowBase {
DropDownList list;
for (uint i = 0; AirportClass::IsClassIDValid((AirportClassID)i); i++) {
list.push_back(std::make_unique<DropDownListStringItem>(AirportClass::Get((AirportClassID)i)->name, i, false));
list.push_back(MakeDropDownListStringItem(AirportClass::Get((AirportClassID)i)->name, i, false));
}
return list;
@ -308,7 +309,7 @@ public:
}
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_AP_CLASS_DROPDOWN: {
@ -318,7 +319,7 @@ public:
}
d.width += padding.width;
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
@ -327,11 +328,11 @@ public:
const AirportSpec *as = AirportSpec::Get(i);
if (!as->enabled) continue;
size->width = std::max(size->width, GetStringBoundingBox(as->name).width + padding.width);
size.width = std::max(size.width, GetStringBoundingBox(as->name).width + padding.width);
}
this->line_height = GetCharacterHeight(FS_NORMAL) + padding.height;
size->height = 5 * this->line_height;
size.height = 5 * this->line_height;
break;
}
@ -339,13 +340,13 @@ public:
for (int i = 0; i < NUM_AIRPORTS; i++) {
const AirportSpec *as = AirportSpec::Get(i);
if (!as->enabled) continue;
for (byte layout = 0; layout < as->num_table; layout++) {
for (uint8_t layout = 0; layout < as->num_table; layout++) {
SpriteID sprite = GetCustomAirportSprite(as, layout);
if (sprite != 0) {
Dimension d = GetSpriteSize(sprite);
d.width += WidgetDimensions::scaled.framerect.Horizontal();
d.height += WidgetDimensions::scaled.framerect.Vertical();
*size = maxdim(d, *size);
size = maxdim(d, size);
}
}
}
@ -355,12 +356,12 @@ public:
for (int i = NEW_AIRPORT_OFFSET; i < NUM_AIRPORTS; i++) {
const AirportSpec *as = AirportSpec::Get(i);
if (!as->enabled) continue;
for (byte layout = 0; layout < as->num_table; layout++) {
for (uint8_t layout = 0; layout < as->num_table; layout++) {
StringID string = GetAirportTextCallback(as, layout, CBID_AIRPORT_ADDITIONAL_TEXT);
if (string == STR_UNDEFINED) continue;
Dimension d = GetStringMultiLineBoundingBox(string, *size);
*size = maxdim(d, *size);
Dimension d = GetStringMultiLineBoundingBox(string, size);
size = maxdim(d, size);
}
}
break;

@ -8,6 +8,7 @@
/** @file articulated_vehicles.cpp Implementation of articulated vehicles. */
#include "stdafx.h"
#include "articulated_vehicles.h"
#include "core/bitmath_func.hpp"
#include "core/random_func.hpp"
#include "train.h"
@ -141,15 +142,23 @@ void GetArticulatedPartsEngineIDs(EngineID engine_type, bool purchase_window, st
* Returns the default (non-refitted) capacity of a specific EngineID.
* @param engine the EngineID of interest
* @param cargo_type returns the default cargo type, if needed
* @param attempt_refit cargo ID to attempt to use
* @return capacity
*/
static inline uint16_t GetVehicleDefaultCapacity(EngineID engine, CargoID *cargo_type)
static inline uint16_t GetVehicleDefaultCapacity(EngineID engine, CargoID *cargo_type, CargoID attempt_refit = INVALID_CARGO)
{
const Engine *e = Engine::Get(engine);
CargoID cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : INVALID_CARGO);
CargoID cargo = INVALID_CARGO;
if (e->CanCarryCargo()) {
if (attempt_refit != INVALID_CARGO && HasBit(e->info.refit_mask, attempt_refit)) {
cargo = attempt_refit;
} else {
cargo = e->GetDefaultCargoType();
}
}
if (cargo_type != nullptr) *cargo_type = cargo;
if (cargo == INVALID_CARGO) return 0;
return e->GetDisplayDefaultCapacity();
return e->GetDisplayDefaultCapacity(nullptr, cargo);
}
/**
@ -175,16 +184,20 @@ static inline CargoTypes GetAvailableVehicleCargoTypes(EngineID engine, bool inc
/**
* Get the capacity of the parts of a given engine.
* @param engine The engine to get the capacities from.
* @param attempt_refit Attempt to get capacity when refitting to this cargo.
* @return The cargo capacities.
*/
CargoArray GetCapacityOfArticulatedParts(EngineID engine)
CargoArray GetCapacityOfArticulatedParts(EngineID engine, CargoID attempt_refit)
{
CargoArray capacity{};
const Engine *e = Engine::Get(engine);
CargoID cargo_type;
uint16_t cargo_capacity = GetVehicleDefaultCapacity(engine, &cargo_type);
if (cargo_type < NUM_CARGO) capacity[cargo_type] = cargo_capacity;
auto get_engine_cargo = [&capacity, attempt_refit](EngineID eng) {
CargoID cargo_type;
uint16_t cargo_capacity = GetVehicleDefaultCapacity(eng, &cargo_type, attempt_refit);
if (cargo_type < NUM_CARGO) capacity[cargo_type] += cargo_capacity;
};
get_engine_cargo(engine);
if (!e->IsArticulatedCallbackVehicleType()) return capacity;
@ -194,8 +207,7 @@ CargoArray GetCapacityOfArticulatedParts(EngineID engine)
EngineID artic_engine = GetNextArticulatedPart(i, engine);
if (artic_engine == INVALID_ENGINE) break;
cargo_capacity = GetVehicleDefaultCapacity(artic_engine, &cargo_type);
if (cargo_type < NUM_CARGO) capacity[cargo_type] += cargo_capacity;
get_engine_cargo(artic_engine);
}
return capacity;

@ -16,7 +16,7 @@
uint CountArticulatedParts(EngineID engine_type, bool purchase_window);
void GetArticulatedPartsEngineIDs(EngineID engine_type, bool purchase_window, std::vector<EngineID> &ids);
CargoArray GetCapacityOfArticulatedParts(EngineID engine);
CargoArray GetCapacityOfArticulatedParts(EngineID engine, CargoID attempt_refit = INVALID_CARGO);
CargoTypes GetCargoTypesOfArticulatedParts(EngineID engine);
void AddArticulatedParts(Vehicle *first);
void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type, CargoTypes *union_mask, CargoTypes *intersection_mask);

@ -343,7 +343,7 @@ static CommandCost BuildReplacementMultiPartShipSimple(EngineID e, const Vehicle
for (; v != nullptr && old != nullptr; v = v->Next(), old = old->Next()) {
if (old->cargo_type == INVALID_CARGO) continue;
byte subtype = GetBestFittingSubType(old, v, old->cargo_type);
uint8_t subtype = GetBestFittingSubType(old, v, old->cargo_type);
CommandCost refit_cost = DoCommand(0, v->index, old->cargo_type | (subtype << 8) | (1 << 16), DC_EXEC, GetCmdRefitVeh(v));
if (refit_cost.Succeeded()) cost.AddCost(refit_cost);
}
@ -396,7 +396,7 @@ static CommandCost BuildReplacementMultiPartShip(EngineID e, const Vehicle *old_
CargoID c = FindFirstBit(available);
assert(old_cargo_vehs[c] != nullptr);
byte subtype = GetBestFittingSubType(old_cargo_vehs[c], v, c);
uint8_t subtype = GetBestFittingSubType(old_cargo_vehs[c], v, c);
CommandCost refit_cost = DoCommand(0, v->index, c | (subtype << 8) | (1 << 16), DC_EXEC, GetCmdRefitVeh(v));
if (refit_cost.Succeeded()) cost.AddCost(refit_cost);
}
@ -453,7 +453,7 @@ static CommandCost BuildReplacementMultiPartShip(EngineID e, const Vehicle *old_
if (c == INVALID_CARGO) continue;
assert(old_cargo_vehs[c] != nullptr);
byte subtype = GetBestFittingSubType(old_cargo_vehs[c], v, c);
uint8_t subtype = GetBestFittingSubType(old_cargo_vehs[c], v, c);
CommandCost refit_cost = DoCommand(0, v->index, c | (subtype << 8) | (1 << 16), DC_EXEC, GetCmdRefitVeh(v));
if (refit_cost.Succeeded()) cost.AddCost(refit_cost);
}
@ -514,7 +514,7 @@ static CommandCost BuildReplacementVehicle(const Vehicle *old_veh, Vehicle **new
/* Refit the vehicle if needed */
if (refit_cargo != CARGO_NO_REFIT) {
byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
uint8_t subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
@ -557,8 +557,9 @@ static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after,
* @param old_head The old front vehicle (no wagons attached anymore)
* @param new_head The new head of the completely replaced vehicle chain
* @param flags the command flags to use
* @param start_stop_check whether to run the start-stop check
*/
CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags)
CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoCommandFlag flags, bool start_stop_check)
{
CommandCost cost = CommandCost();
@ -569,7 +570,7 @@ CommandCost CopyHeadSpecificThings(Vehicle *old_head, Vehicle *new_head, DoComma
if (cost.Succeeded() && old_head != new_head) cost.AddCost(DoCommand(0, old_head->group_id, new_head->index, DC_EXEC, CMD_ADD_VEHICLE_GROUP));
/* Perform start/stop check whether the new vehicle suits newgrf restrictions etc. */
if (cost.Succeeded()) {
if (start_stop_check && cost.Succeeded()) {
/* Start the vehicle, might be denied by certain things */
assert((new_head->vehstatus & VS_STOPPED) != 0);
cost.AddCost(CmdStartStopVehicle(new_head, true));
@ -777,7 +778,6 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
/* Sell superfluous new vehicles that could not be inserted. */
if (cost.Succeeded() && wagon_removal) {
assert(Train::From(new_head)->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
for (auto it = std::next(std::begin(replacements)); it != std::end(replacements); ++it) {
Vehicle *wagon = it->new_veh;
if (wagon == nullptr) continue;
@ -797,7 +797,7 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
}
/* The new vehicle chain is constructed, now take over orders and everything... */
if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags, true));
if (cost.Succeeded()) {
/* Success ! */
@ -864,7 +864,7 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
*nothing_to_do = false;
/* The new vehicle is constructed, now take over orders and everything... */
cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));
cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags, true));
if (cost.Succeeded()) {
/* The new vehicle is constructed, now take over cargo */

@ -97,7 +97,7 @@ inline CommandCost RemoveEngineReplacementForCompany(Company *c, EngineID engine
bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company);
CommandCost CopyHeadSpecificThings(Vehicle*, Vehicle*, DoCommandFlag);
CommandCost CopyHeadSpecificThings(Vehicle*, Vehicle*, DoCommandFlag, bool start_stop_check);
bool AutoreplaceMultiPartShipWouldSucceed(EngineID e, const Vehicle *old_veh, CargoTypes all_cargoes);

@ -24,15 +24,14 @@
#include "core/geometry_func.hpp"
#include "rail_gui.h"
#include "road_gui.h"
#include "widgets/dropdown_func.h"
#include "dropdown_type.h"
#include "dropdown_func.h"
#include "widgets/autoreplace_widget.h"
#include "safeguards.h"
void DrawEngineList(VehicleType type, const Rect &r, const GUIEngineList &eng_list, const Scrollbar &sb, EngineID selected_id, bool show_count, GroupID selected_group);
static bool EngineNumberSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineNumberSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
return Engine::Get(a.engine_id)->list_position < Engine::Get(b.engine_id)->list_position;
}
@ -83,7 +82,7 @@ class ReplaceVehicleWindow : public Window {
bool reset_sel_engine; ///< Also reset #sel_engine while updating left and/or right and no valid engine selected.
GroupID sel_group; ///< Group selected to replace.
int details_height; ///< Minimal needed height of the details panels, in text lines (found so far).
byte sort_criteria; ///< Criteria of sorting vehicles.
uint8_t sort_criteria; ///< Criteria of sorting vehicles.
bool descending_sort_order; ///< Order of sorting vehicles.
bool show_hidden_engines; ///< Whether to show the hidden engines.
RailType sel_railtype; ///< Type of rail tracks selected. #INVALID_RAILTYPE to show all.
@ -111,27 +110,6 @@ class ReplaceVehicleWindow : public Window {
return true;
}
void AddChildren(const GUIEngineList &source, GUIEngineList &target, EngineID parent, int indent, int side)
{
for (const auto &item : source) {
if (item.variant_id != parent || item.engine_id == parent) continue;
const Engine *e = Engine::Get(item.engine_id);
EngineDisplayFlags flags = item.flags;
if (e->display_last_variant != INVALID_ENGINE) flags &= ~EngineDisplayFlags::Shaded;
target.emplace_back(e->display_last_variant == INVALID_ENGINE ? item.engine_id : e->display_last_variant, item.engine_id, flags, indent);
/* Add variants if not folded */
if ((item.flags & (EngineDisplayFlags::HasVariants | EngineDisplayFlags::IsFolded)) == EngineDisplayFlags::HasVariants) {
/* Add this engine again as a child */
if ((item.flags & EngineDisplayFlags::Shaded) == EngineDisplayFlags::None) {
target.emplace_back(item.engine_id, item.engine_id, EngineDisplayFlags::None, indent + 1);
}
AddChildren(source, target, item.engine_id, indent + 1, side);
}
}
}
/**
* Generate an engines list
* @param draw_left true if generating the left list, otherwise false
@ -141,7 +119,7 @@ class ReplaceVehicleWindow : public Window {
std::vector<EngineID> variants;
EngineID selected_engine = INVALID_ENGINE;
VehicleType type = (VehicleType)this->window_number;
byte side = draw_left ? 0 : 1;
uint8_t side = draw_left ? 0 : 1;
GUIEngineList list;
@ -205,7 +183,7 @@ class ReplaceVehicleWindow : public Window {
this->engines[side].clear();
if (side == 1) {
AddChildren(list, this->engines[side], INVALID_ENGINE, 0, side);
GUIEngineListAddChildren(this->engines[side], list);
} else {
this->engines[side].swap(list);
}
@ -315,26 +293,26 @@ public:
this->sel_group = id_g;
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_RV_SORT_ASCENDING_DESCENDING: {
Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
case WID_RV_LEFT_MATRIX:
case WID_RV_RIGHT_MATRIX:
resize->height = GetEngineListHeight((VehicleType)this->window_number);
size->height = (this->window_number <= VEH_ROAD ? 8 : 4) * resize->height;
resize.height = GetEngineListHeight((VehicleType)this->window_number);
size.height = (this->window_number <= VEH_ROAD ? 8 : 4) * resize.height;
break;
case WID_RV_LEFT_DETAILS:
case WID_RV_RIGHT_DETAILS:
size->height = GetCharacterHeight(FS_NORMAL) * this->details_height + padding.height;
size.height = GetCharacterHeight(FS_NORMAL) * this->details_height + padding.height;
break;
case WID_RV_TRAIN_WAGONREMOVE_TOGGLE: {
@ -345,7 +323,7 @@ public:
d = maxdim(d, GetStringBoundingBox(str));
d.width += padding.width;
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
@ -354,7 +332,7 @@ public:
d = maxdim(d, GetStringBoundingBox(STR_REPLACE_WAGONS));
d.width += padding.width;
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
@ -363,7 +341,7 @@ public:
d = maxdim(d, GetStringBoundingBox(STR_REPLACE_NOT_REPLACING_VEHICLE_SELECTED));
d.width += padding.width;
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
@ -374,7 +352,7 @@ public:
}
d.width += padding.width;
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
@ -385,7 +363,7 @@ public:
}
d.width += padding.width;
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
@ -396,7 +374,7 @@ public:
}
d.width += padding.width;
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
}
@ -562,8 +540,8 @@ public:
case WID_RV_TRAIN_ENGINEWAGON_DROPDOWN: {
DropDownList list;
list.push_back(std::make_unique<DropDownListStringItem>(STR_REPLACE_ENGINES, 1, false));
list.push_back(std::make_unique<DropDownListStringItem>(STR_REPLACE_WAGONS, 0, false));
list.push_back(MakeDropDownListStringItem(STR_REPLACE_ENGINES, 1));
list.push_back(MakeDropDownListStringItem(STR_REPLACE_WAGONS, 0));
ShowDropDownList(this, std::move(list), this->replace_engines ? 1 : 0, WID_RV_TRAIN_ENGINEWAGON_DROPDOWN);
break;
}
@ -606,7 +584,7 @@ public:
case WID_RV_LEFT_MATRIX:
case WID_RV_RIGHT_MATRIX: {
byte click_side;
uint8_t click_side;
if (widget == WID_RV_LEFT_MATRIX) {
click_side = 0;
} else {

@ -314,7 +314,7 @@ static const uint NUM_SONGS_PLAYLIST = 32;
/* Functions to read DOS music CAT files, similar to but not quite the same as sound effect CAT files */
char *GetMusicCatEntryName(const std::string &filename, size_t entrynum);
byte *GetMusicCatEntryData(const std::string &filename, size_t entrynum, size_t &entrylen);
uint8_t *GetMusicCatEntryData(const std::string &filename, size_t entrynum, size_t &entrylen);
enum MusicTrackType {
MTT_STANDARDMIDI, ///< Standard MIDI file
@ -324,7 +324,7 @@ enum MusicTrackType {
/** Metadata about a music track. */
struct MusicSongInfo {
std::string songname; ///< name of song displayed in UI
byte tracknr; ///< track number of song displayed in UI
uint8_t tracknr; ///< track number of song displayed in UI
std::string filename; ///< file on disk containing song (when used in MusicSet class)
MusicTrackType filetype; ///< decoder required for song file
int cat_index; ///< entry index in CAT file, for filetype==MTT_MPSMIDI
@ -338,7 +338,7 @@ struct MusicSet : BaseSet<MusicSet, NUM_SONGS_AVAILABLE, false> {
/** Data about individual songs in set. */
MusicSongInfo songinfo[NUM_SONGS_AVAILABLE];
/** Number of valid songs in set. */
byte num_available;
uint8_t num_available;
bool FillSetDetails(const IniFile &ini, const std::string &path, const std::string &full_filename);
};

@ -80,8 +80,8 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
std::vector<RoadStopSpecList> roadstop_speclist; ///< List of road stop specs of this station
uint16_t random_bits; ///< Random bits assigned to this station
byte waiting_triggers; ///< Waiting triggers (NewGRF) for this station
byte delete_ctr; ///< Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is deleted.
uint8_t waiting_triggers; ///< Waiting triggers (NewGRF) for this station
uint8_t delete_ctr; ///< Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is deleted.
uint8_t cached_anim_triggers; ///< NOSAVE: Combined animation trigger bitmask, used to determine if trigger processing should happen.
uint8_t cached_roadstop_anim_triggers; ///< NOSAVE: Combined animation trigger bitmask for road stops, used to determine if trigger processing should happen.
CargoTypes cached_cargo_triggers; ///< NOSAVE: Combined cargo trigger bitmask
@ -119,7 +119,7 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
* @param available will return false if ever the variable asked for does not exist
* @return the value stored in the corresponding variable
*/
virtual uint32_t GetNewGRFVariable(const struct ResolverObject &object, uint16_t variable, byte parameter, bool *available) const = 0;
virtual uint32_t GetNewGRFVariable(const struct ResolverObject &object, uint16_t variable, uint8_t parameter, bool *available) const = 0;
/**
* Update the coordinated of the sign (as shown in the viewport).
@ -195,7 +195,7 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
return (this->facilities & facilities) != 0;
}
inline byte GetRoadStopRandomBits(TileIndex tile) const
inline uint8_t GetRoadStopRandomBits(TileIndex tile) const
{
for (const RoadStopTileData &tile_data : this->custom_roadstop_tile_data) {
if (tile_data.tile == tile) return tile_data.random_bits;
@ -203,7 +203,7 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
return 0;
}
inline byte GetRoadStopAnimationFrame(TileIndex tile) const
inline uint8_t GetRoadStopAnimationFrame(TileIndex tile) const
{
for (const RoadStopTileData &tile_data : this->custom_roadstop_tile_data) {
if (tile_data.tile == tile) return tile_data.animation_frame;
@ -212,11 +212,11 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
}
private:
bool SetRoadStopTileData(TileIndex tile, byte data, bool animation);
bool SetRoadStopTileData(TileIndex tile, uint8_t data, bool animation);
public:
inline void SetRoadStopRandomBits(TileIndex tile, byte random_bits) { this->SetRoadStopTileData(tile, random_bits, false); }
inline bool SetRoadStopAnimationFrame(TileIndex tile, byte frame) { return this->SetRoadStopTileData(tile, frame, true); }
inline void SetRoadStopRandomBits(TileIndex tile, uint8_t random_bits) { this->SetRoadStopTileData(tile, random_bits, false); }
inline bool SetRoadStopAnimationFrame(TileIndex tile, uint8_t frame) { return this->SetRoadStopTileData(tile, frame, true); }
void RemoveRoadStopTileData(TileIndex tile);
static void PostDestructor(size_t index);

@ -36,14 +36,14 @@ inline void Blitter_32bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
const uint16_t *src_n = (const uint16_t *)(src->data + src->offset[zoom][1]);
for (uint i = bp->skip_top; i != 0; i--) {
src_px = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
src_px = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
}
Colour *dst = (Colour *)bp->dst + bp->top * bp->pitch + bp->left;
uint16_t *anim = this->anim_buf + this->ScreenToAnimOffset((uint32_t *)bp->dst) + bp->top * this->anim_buf_pitch + bp->left;
const byte *remap = bp->remap; // store so we don't have to access it via bp every time
const uint8_t *remap = bp->remap; // store so we don't have to access it via bp every time
const int width = bp->width;
const int pitch = bp->pitch;
const int anim_pitch = this->anim_buf_pitch;
@ -54,10 +54,10 @@ inline void Blitter_32bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
Colour *dst_ln = dst + pitch;
uint16_t *anim_ln = anim + anim_pitch;
const Colour *src_px_ln = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
const Colour *src_px_ln = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_px++;
const uint16_t *src_n_ln = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
const uint16_t *src_n_ln = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
src_n += 2;
Colour *dst_end = dst;

@ -33,7 +33,7 @@ template <BlitterMode mode, Blitter_32bppSSE2::ReadMode read_mode, Blitter_32bpp
GNU_TARGET("sse4.1")
inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom)
{
const byte * const remap = bp->remap;
const uint8_t * const remap = bp->remap;
Colour *dst_line = (Colour *) bp->dst + bp->top * bp->pitch + bp->left;
uint16_t *anim_line = this->anim_buf + this->ScreenToAnimOffset((uint32_t *)bp->dst) + bp->top * this->anim_buf_pitch + bp->left;
int effective_width = bp->width;
@ -42,7 +42,7 @@ inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom
const Blitter_32bppSSE_Base::SpriteData * const sd = (const Blitter_32bppSSE_Base::SpriteData *) bp->sprite;
const SpriteInfo * const si = &sd->infos[zoom];
const MapValue *src_mv_line = (const MapValue *) &sd->data[si->mv_offset] + bp->skip_top * si->sprite_width;
const Colour *src_rgba_line = (const Colour *) ((const byte *) &sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size);
const Colour *src_rgba_line = (const Colour *) ((const uint8_t *) &sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size);
if (read_mode != RM_WITH_MARGIN) {
src_rgba_line += bp->skip_left;
@ -104,20 +104,20 @@ inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom
if (animated) {
/* Remap colours. */
const byte m0 = mvX2;
const uint8_t m0 = mvX2;
if (m0 >= PALETTE_ANIM_START) {
const Colour c0 = (this->LookupColourInPalette(m0).data & 0x00FFFFFF) | (src[0].data & 0xFF000000);
InsertFirstUint32(AdjustBrightneSSE(c0, (byte) (mvX2 >> 8)).data, srcABCD);
InsertFirstUint32(AdjustBrightneSSE(c0, (uint8_t) (mvX2 >> 8)).data, srcABCD);
}
const byte m1 = mvX2 >> 16;
const uint8_t m1 = mvX2 >> 16;
if (m1 >= PALETTE_ANIM_START) {
const Colour c1 = (this->LookupColourInPalette(m1).data & 0x00FFFFFF) | (src[1].data & 0xFF000000);
InsertSecondUint32(AdjustBrightneSSE(c1, (byte) (mvX2 >> 24)).data, srcABCD);
InsertSecondUint32(AdjustBrightneSSE(c1, (uint8_t) (mvX2 >> 24)).data, srcABCD);
}
/* Update anim buffer. */
const byte a0 = src[0].a;
const byte a1 = src[1].a;
const uint8_t a0 = src[0].a;
const uint8_t a1 = src[1].a;
uint32_t anim01 = 0;
if (a0 == 255) {
if (a1 == 255) {
@ -185,9 +185,9 @@ bmno_full_transparency:
__m128i dstABCD = _mm_loadl_epi64((__m128i*) dst);
/* Remap colours. */
const uint m0 = (byte) mvX2;
const uint m0 = (uint8_t) mvX2;
const uint r0 = remap[m0];
const uint m1 = (byte) (mvX2 >> 16);
const uint m1 = (uint8_t) (mvX2 >> 16);
const uint r1 = remap[m1];
if (mvX2 & 0x00FF00FF) {
#define CMOV_REMAP(m_colour, m_colour_init, m_src, m_m) \
@ -195,7 +195,7 @@ bmno_full_transparency:
Colour m_colour = m_colour_init; \
{ \
const Colour srcm = (Colour) (m_src); \
const uint m = (byte) (m_m); \
const uint m = (uint8_t) (m_m); \
const uint r = remap[m]; \
const Colour cmap = (this->LookupColourInPalette(r).data & 0x00FFFFFF) | (srcm.data & 0xFF000000); \
m_colour = r == 0 ? m_colour : cmap; \
@ -225,8 +225,8 @@ bmno_full_transparency:
/* Update anim buffer. */
if (animated) {
const byte a0 = src[0].a;
const byte a1 = src[1].a;
const uint8_t a0 = src[0].a;
const uint8_t a1 = src[1].a;
uint32_t anim01 = mvX2 & 0xFF00FF00;
if (a0 == 255) {
anim01 |= r0;
@ -437,7 +437,7 @@ bmcr_alpha_blend_single_brightness:
next_line:
if (mode != BM_TRANSPARENT && mode != BM_TRANSPARENT_REMAP) src_mv_line += si->sprite_width;
src_rgba_line = (const Colour*) ((const byte*) src_rgba_line + si->sprite_line_size);
src_rgba_line = (const Colour*) ((const uint8_t*) src_rgba_line + si->sprite_line_size);
dst_line += bp->pitch;
anim_line += this->anim_buf_pitch;
}

@ -41,26 +41,26 @@ inline void Blitter_32bppOptimized::Draw(const Blitter::BlitterParams *bp, ZoomL
/* skip upper lines in src_px and src_n */
for (uint i = bp->skip_top; i != 0; i--) {
src_px = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
src_px = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
}
/* skip lines in dst */
Colour *dst = (Colour *)bp->dst + bp->top * bp->pitch + bp->left;
/* store so we don't have to access it via bp every time (compiler assumes pointer aliasing) */
const byte *remap = bp->remap;
const uint8_t *remap = bp->remap;
for (int y = 0; y < bp->height; y++) {
/* next dst line begins here */
Colour *dst_ln = dst + bp->pitch;
/* next src line begins here */
const Colour *src_px_ln = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
const Colour *src_px_ln = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_px++;
/* next src_n line begins here */
const uint16_t *src_n_ln = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
const uint16_t *src_n_ln = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
src_n += 2;
/* we will end this line when we reach this point */
@ -317,9 +317,9 @@ template <bool Tpal_to_rgb> Sprite *Blitter_32bppOptimized::EncodeInternal(const
ZoomLevel zoom_max;
uint8_t missing_zoom_levels = 0;
if (sprite[ZOOM_LVL_NORMAL].type == SpriteType::Font) {
zoom_min = ZOOM_LVL_NORMAL;
zoom_max = ZOOM_LVL_NORMAL;
if (sprite[ZOOM_LVL_MIN].type == SpriteType::Font) {
zoom_min = ZOOM_LVL_MIN;
zoom_max = ZOOM_LVL_MIN;
} else {
zoom_min = _settings_client.gui.zoom_min;
zoom_max = (ZoomLevel) std::min(_settings_client.gui.zoom_max, ZOOM_LVL_DRAW_SPR);
@ -459,8 +459,8 @@ template <bool Tpal_to_rgb> Sprite *Blitter_32bppOptimized::EncodeInternal(const
dst_n_ln = (uint32_t *)dst_n;
}
lengths[z][0] = (byte *)dst_px_ln - (byte *)dst_px_orig[z]; // all are aligned to 4B boundary
lengths[z][1] = (byte *)dst_n_ln - (byte *)dst_n_orig[z];
lengths[z][0] = (uint8_t *)dst_px_ln - (uint8_t *)dst_px_orig[z]; // all are aligned to 4B boundary
lengths[z][1] = (uint8_t *)dst_n_ln - (uint8_t *)dst_n_orig[z];
px_buffer_next = (Colour *)dst_px_ln;
n_buffer_next = (uint16_t *)dst_n_ln;
@ -478,10 +478,10 @@ template <bool Tpal_to_rgb> Sprite *Blitter_32bppOptimized::EncodeInternal(const
missing_zoom_levels = UINT8_MAX;
}
dest_sprite->height = sprite[ZOOM_LVL_NORMAL].height;
dest_sprite->width = sprite[ZOOM_LVL_NORMAL].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_NORMAL].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_NORMAL].y_offs;
dest_sprite->height = sprite[ZOOM_LVL_MIN].height;
dest_sprite->width = sprite[ZOOM_LVL_MIN].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_MIN].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_MIN].y_offs;
dest_sprite->next = nullptr;
dest_sprite->missing_zoom_levels = missing_zoom_levels;

@ -19,7 +19,7 @@ public:
struct SpriteData {
BlitterSpriteFlags flags;
uint32_t offset[ZOOM_LVL_SPR_COUNT][2]; ///< Offsets (from .data) to streams for different zoom levels, and the normal and remap image information.
byte data[]; ///< Data, all zoomlevels.
uint8_t data[]; ///< Data, all zoomlevels.
};
Blitter_32bppOptimized()

@ -137,19 +137,19 @@ void Blitter_32bppSimple::DrawColourMappingRect(void *dst, int width, int height
Sprite *Blitter_32bppSimple::Encode(const SpriteLoader::SpriteCollection &sprite, AllocatorProc *allocator)
{
Blitter_32bppSimple::Pixel *dst;
Sprite *dest_sprite = (Sprite *)allocator(sizeof(*dest_sprite) + (size_t)sprite[ZOOM_LVL_NORMAL].height * (size_t)sprite[ZOOM_LVL_NORMAL].width * sizeof(*dst));
Sprite *dest_sprite = (Sprite *)allocator(sizeof(*dest_sprite) + (size_t)sprite[ZOOM_LVL_MIN].height * (size_t)sprite[ZOOM_LVL_MIN].width * sizeof(*dst));
dest_sprite->height = sprite[ZOOM_LVL_NORMAL].height;
dest_sprite->width = sprite[ZOOM_LVL_NORMAL].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_NORMAL].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_NORMAL].y_offs;
dest_sprite->height = sprite[ZOOM_LVL_MIN].height;
dest_sprite->width = sprite[ZOOM_LVL_MIN].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_MIN].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_MIN].y_offs;
dest_sprite->next = nullptr;
dest_sprite->missing_zoom_levels = 0;
dst = (Blitter_32bppSimple::Pixel *)dest_sprite->data;
SpriteLoader::CommonPixel *src = (SpriteLoader::CommonPixel *)sprite[ZOOM_LVL_NORMAL].data;
SpriteLoader::CommonPixel *src = (SpriteLoader::CommonPixel *)sprite[ZOOM_LVL_MIN].data;
for (int i = 0; i < sprite[ZOOM_LVL_NORMAL].height * sprite[ZOOM_LVL_NORMAL].width; i++) {
for (int i = 0; i < sprite[ZOOM_LVL_MIN].height * sprite[ZOOM_LVL_MIN].width; i++) {
if (src->m == 0) {
dst[i].r = src->r;
dst[i].g = src->g;

@ -26,10 +26,10 @@ Sprite *Blitter_32bppSSE_Base::Encode(const SpriteLoader::SpriteCollection &spri
* Second uint32_t of a line = the number of transparent pixels from the right.
* Then all RGBA then all MV.
*/
ZoomLevel zoom_min = ZOOM_LVL_NORMAL;
ZoomLevel zoom_max = ZOOM_LVL_NORMAL;
ZoomLevel zoom_min = ZOOM_LVL_MIN;
ZoomLevel zoom_max = ZOOM_LVL_MIN;
uint8_t missing_zoom_levels = 0;
if (sprite[ZOOM_LVL_NORMAL].type != SpriteType::Font) {
if (sprite[ZOOM_LVL_MIN].type != SpriteType::Font) {
zoom_min = _settings_client.gui.zoom_min;
zoom_max = (ZoomLevel) std::min(_settings_client.gui.zoom_max, ZOOM_LVL_DRAW_SPR);
if (zoom_max == zoom_min) zoom_max = ZOOM_LVL_DRAW_SPR;
@ -62,10 +62,10 @@ Sprite *Blitter_32bppSSE_Base::Encode(const SpriteLoader::SpriteCollection &spri
}
Sprite *dst_sprite = (Sprite *) allocator(sizeof(Sprite) + sizeof(SpriteData) + all_sprites_size);
dst_sprite->height = sprite[ZOOM_LVL_NORMAL].height;
dst_sprite->width = sprite[ZOOM_LVL_NORMAL].width;
dst_sprite->x_offs = sprite[ZOOM_LVL_NORMAL].x_offs;
dst_sprite->y_offs = sprite[ZOOM_LVL_NORMAL].y_offs;
dst_sprite->height = sprite[ZOOM_LVL_MIN].height;
dst_sprite->width = sprite[ZOOM_LVL_MIN].width;
dst_sprite->x_offs = sprite[ZOOM_LVL_MIN].x_offs;
dst_sprite->y_offs = sprite[ZOOM_LVL_MIN].y_offs;
dst_sprite->next = nullptr;
dst_sprite->missing_zoom_levels = missing_zoom_levels;
memcpy(dst_sprite->data, &sd, sizeof(SpriteData));
@ -142,7 +142,7 @@ Sprite *Blitter_32bppSSE_Base::Encode(const SpriteLoader::SpriteCollection &spri
(*dst_rgba_line).data = nb_pix_transp;
Colour *nb_right = dst_rgba_line + 1;
dst_rgba_line = (Colour*) ((byte*) dst_rgba_line + sd.infos[z].sprite_line_size);
dst_rgba_line = (Colour*) ((uint8_t*) dst_rgba_line + sd.infos[z].sprite_line_size);
/* Count the number of transparent pixels from the right. */
dst_rgba = dst_rgba_line - 1;

@ -61,7 +61,7 @@ public:
struct SpriteData {
BlitterSpriteFlags flags;
SpriteInfo infos[ZOOM_LVL_SPR_COUNT];
byte data[]; ///< Data, all zoomlevels.
uint8_t data[]; ///< Data, all zoomlevels.
};
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, AllocatorProc *allocator);

@ -10,10 +10,17 @@
#ifndef BLITTER_32BPP_SSE_FUNC_HPP
#define BLITTER_32BPP_SSE_FUNC_HPP
/* ATTENTION
* This file is compiled multiple times with different defines for SSE_VERSION and MARGIN_NORMAL_THRESHOLD.
* Be careful when declaring things with external linkage.
* Use internal linkage instead, i.e. "static".
*/
#define INTERNAL_LINKAGE static
#ifdef WITH_SSE
GNU_TARGET(SSE_TARGET)
inline void InsertFirstUint32(const uint32_t value, __m128i &into)
INTERNAL_LINKAGE inline void InsertFirstUint32(const uint32_t value, __m128i &into)
{
#if (SSE_VERSION >= 4)
into = _mm_insert_epi32(into, value, 0);
@ -24,7 +31,7 @@ inline void InsertFirstUint32(const uint32_t value, __m128i &into)
}
GNU_TARGET(SSE_TARGET)
inline void InsertSecondUint32(const uint32_t value, __m128i &into)
INTERNAL_LINKAGE inline void InsertSecondUint32(const uint32_t value, __m128i &into)
{
#if (SSE_VERSION >= 4)
into = _mm_insert_epi32(into, value, 1);
@ -35,7 +42,7 @@ inline void InsertSecondUint32(const uint32_t value, __m128i &into)
}
GNU_TARGET(SSE_TARGET)
inline void LoadUint64(const uint64_t value, __m128i &into)
INTERNAL_LINKAGE inline void LoadUint64(const uint64_t value, __m128i &into)
{
#ifdef POINTER_IS_64BIT
into = _mm_cvtsi64_si128(value);
@ -50,7 +57,7 @@ inline void LoadUint64(const uint64_t value, __m128i &into)
}
GNU_TARGET(SSE_TARGET)
inline __m128i PackUnsaturated(__m128i from, const __m128i &mask)
INTERNAL_LINKAGE inline __m128i PackUnsaturated(__m128i from, const __m128i &mask)
{
#if (SSE_VERSION == 2)
from = _mm_and_si128(from, mask); // PAND, wipe high bytes to keep low bytes when packing
@ -61,7 +68,7 @@ inline __m128i PackUnsaturated(__m128i from, const __m128i &mask)
}
GNU_TARGET(SSE_TARGET)
inline __m128i DistributeAlpha(const __m128i from, const __m128i &mask)
INTERNAL_LINKAGE inline __m128i DistributeAlpha(const __m128i from, const __m128i &mask)
{
#if (SSE_VERSION == 2)
__m128i alphaAB = _mm_shufflelo_epi16(from, 0x3F); // PSHUFLW, put alpha1 in front of each rgb1
@ -73,7 +80,7 @@ inline __m128i DistributeAlpha(const __m128i from, const __m128i &mask)
}
GNU_TARGET(SSE_TARGET)
inline __m128i AlphaBlendTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &pack_mask, const __m128i &alpha_mask)
INTERNAL_LINKAGE inline __m128i AlphaBlendTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &pack_mask, const __m128i &alpha_mask)
{
__m128i srcAB = _mm_unpacklo_epi8(src, _mm_setzero_si128()); // PUNPCKLBW, expand each uint8_t into uint16
__m128i dstAB = _mm_unpacklo_epi8(dst, _mm_setzero_si128());
@ -97,7 +104,7 @@ inline __m128i AlphaBlendTwoPixels(__m128i src, __m128i dst, const __m128i &dist
* rgb = rgb * ((256/4) * 4 - (alpha/4)) / ((256/4) * 4)
*/
GNU_TARGET(SSE_TARGET)
inline __m128i DarkenTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &tr_nom_base)
INTERNAL_LINKAGE inline __m128i DarkenTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &tr_nom_base)
{
__m128i srcAB = _mm_unpacklo_epi8(src, _mm_setzero_si128());
__m128i dstAB = _mm_unpacklo_epi8(dst, _mm_setzero_si128());
@ -111,7 +118,7 @@ inline __m128i DarkenTwoPixels(__m128i src, __m128i dst, const __m128i &distribu
IGNORE_UNINITIALIZED_WARNING_START
GNU_TARGET(SSE_TARGET)
static Colour ReallyAdjustBrightness(Colour colour, uint8_t brightness)
INTERNAL_LINKAGE Colour ReallyAdjustBrightness(Colour colour, uint8_t brightness)
{
uint64_t c16 = colour.b | (uint64_t) colour.g << 16 | (uint64_t) colour.r << 32;
c16 *= brightness;
@ -145,7 +152,7 @@ IGNORE_UNINITIALIZED_WARNING_STOP
/** ReallyAdjustBrightness() is not called that often.
* Inlining this function implies a far jump, which has a huge latency.
*/
inline Colour AdjustBrightneSSE(Colour colour, uint8_t brightness)
INTERNAL_LINKAGE inline Colour AdjustBrightneSSE(Colour colour, uint8_t brightness)
{
/* Shortcut for normal brightness. */
if (likely(brightness == Blitter_32bppBase::DEFAULT_BRIGHTNESS)) return colour;
@ -154,7 +161,7 @@ inline Colour AdjustBrightneSSE(Colour colour, uint8_t brightness)
}
GNU_TARGET(SSE_TARGET)
inline __m128i AdjustBrightnessOfTwoPixels([[maybe_unused]] __m128i from, [[maybe_unused]] uint32_t brightness)
INTERNAL_LINKAGE inline __m128i AdjustBrightnessOfTwoPixels([[maybe_unused]] __m128i from, [[maybe_unused]] uint32_t brightness)
{
#if (SSE_VERSION < 3)
NOT_REACHED();
@ -214,7 +221,7 @@ inline void Blitter_32bppSSSE3::Draw(const Blitter::BlitterParams *bp, ZoomLevel
inline void Blitter_32bppSSE4::Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom)
#endif
{
const byte * const remap = bp->remap;
const uint8_t * const remap = bp->remap;
Colour *dst_line = (Colour *) bp->dst + bp->top * bp->pitch + bp->left;
int effective_width = bp->width;
@ -222,7 +229,7 @@ inline void Blitter_32bppSSE4::Draw(const Blitter::BlitterParams *bp, ZoomLevel
const SpriteData * const sd = (const SpriteData *) bp->sprite;
const SpriteInfo * const si = &sd->infos[zoom];
const MapValue *src_mv_line = (const MapValue *) &sd->data[si->mv_offset] + bp->skip_top * si->sprite_width;
const Colour *src_rgba_line = (const Colour *) ((const byte *) &sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size);
const Colour *src_rgba_line = (const Colour *) ((const uint8_t *) &sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size);
uint32_t bm_normal_brightness = 0;
if (mode == BM_NORMAL_WITH_BRIGHTNESS) {
@ -313,7 +320,7 @@ inline void Blitter_32bppSSE4::Draw(const Blitter::BlitterParams *bp, ZoomLevel
Colour m_colour = m_colour_init; \
{ \
const Colour srcm = (Colour) (m_src); \
const uint m = (byte) (m_m); \
const uint m = (uint8_t) (m_m); \
const uint r = remap[m]; \
const Colour cmap = (this->LookupColourInPalette(r).data & 0x00FFFFFF) | (srcm.data & 0xFF000000); \
m_colour = r == 0 ? m_colour : cmap; \
@ -496,7 +503,7 @@ bmcr_alpha_blend_single_brightness:
next_line:
if (mode == BM_COLOUR_REMAP || mode == BM_CRASH_REMAP || mode == BM_COLOUR_REMAP_WITH_BRIGHTNESS) src_mv_line += si->sprite_width;
src_rgba_line = (const Colour*) ((const byte*) src_rgba_line + si->sprite_line_size);
src_rgba_line = (const Colour*) ((const uint8_t*) src_rgba_line + si->sprite_line_size);
dst_line += bp->pitch;
}
}

@ -10,6 +10,12 @@
#ifndef BLITTER_32BPP_SSE_TYPE_H
#define BLITTER_32BPP_SSE_TYPE_H
/* ATTENTION
* This file is compiled multiple times with different defines for SSE_VERSION.
* Be careful when declaring things with external linkage.
* Use internal linkage instead, i.e. "static".
*/
#ifdef WITH_SSE
#include "32bpp_simple.hpp"
@ -22,7 +28,7 @@
#endif
#define META_LENGTH 2 ///< Number of uint32_t inserted before each line of pixels in a sprite.
#define MARGIN_NORMAL_THRESHOLD (zoom == ZOOM_LVL_OUT_32X ? 8 : 4) ///< Minimum width to use margins with BM_NORMAL.
#define MARGIN_NORMAL_THRESHOLD (zoom == ZOOM_LVL_OUT_8X ? 8 : 4) ///< Minimum width to use margins with BM_NORMAL.
#define MARGIN_REMAP_THRESHOLD 4 ///< Minimum width to use margins with BM_COLOUR_REMAP.
#undef ALIGN

@ -167,8 +167,8 @@ inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
/* skip upper lines in src_px and src_n */
for (uint i = bp->skip_top; i != 0; i--) {
src_px = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
src_px = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
}
/* skip lines in dst */
@ -177,7 +177,7 @@ inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
uint8_t *anim = VideoDriver::GetInstance()->GetAnimBuffer() + ((uint32_t *)bp->dst - (uint32_t *)_screen.dst_ptr) + bp->top * bp->pitch + bp->left;
/* store so we don't have to access it via bp everytime (compiler assumes pointer aliasing) */
const byte *remap = bp->remap;
const uint8_t *remap = bp->remap;
for (int y = 0; y < bp->height; y++) {
/* next dst line begins here */
@ -185,11 +185,11 @@ inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
uint8_t *anim_ln = anim + bp->pitch;
/* next src line begins here */
const Colour *src_px_ln = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
const Colour *src_px_ln = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_px++;
/* next src_n line begins here */
const uint16_t *src_n_ln = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
const uint16_t *src_n_ln = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
src_n += 2;
/* we will end this line when we reach this point */

@ -129,9 +129,9 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri
ZoomLevel zoom_min;
ZoomLevel zoom_max;
if (sprite[ZOOM_LVL_NORMAL].type == SpriteType::Font) {
zoom_min = ZOOM_LVL_NORMAL;
zoom_max = ZOOM_LVL_NORMAL;
if (sprite[ZOOM_LVL_MIN].type == SpriteType::Font) {
zoom_min = ZOOM_LVL_MIN;
zoom_max = ZOOM_LVL_MIN;
} else {
zoom_min = _settings_client.gui.zoom_min;
zoom_max = (ZoomLevel) std::min(_settings_client.gui.zoom_max, ZOOM_LVL_DRAW_SPR);
@ -148,10 +148,10 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri
/* Don't allocate memory each time, but just keep some
* memory around as this function is called quite often
* and the memory usage is quite low. */
static ReusableBuffer<byte> temp_buffer;
static ReusableBuffer<uint8_t> temp_buffer;
SpriteData *temp_dst = (SpriteData *)temp_buffer.Allocate(memory);
memset(temp_dst, 0, sizeof(*temp_dst));
byte *dst = temp_dst->data;
uint8_t *dst = temp_dst->data;
/* Make the sprites per zoom-level */
for (ZoomLevel i = zoom_min; i <= zoom_max; i++) {
@ -167,7 +167,7 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri
uint trans = 0;
uint pixels = 0;
uint last_colour = 0;
byte *count_dst = nullptr;
uint8_t *count_dst = nullptr;
/* Store the scaled image */
const SpriteLoader::CommonPixel *src = &sprite[i].data[y * sprite[i].width];
@ -214,7 +214,7 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri
}
}
uint size = dst - (byte *)temp_dst;
uint size = dst - (uint8_t *)temp_dst;
/* Safety check, to make sure we guessed the size correctly */
assert(size < memory);
@ -222,10 +222,10 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri
/* Allocate the exact amount of memory we need */
Sprite *dest_sprite = (Sprite *)allocator(sizeof(*dest_sprite) + size);
dest_sprite->height = sprite[ZOOM_LVL_NORMAL].height;
dest_sprite->width = sprite[ZOOM_LVL_NORMAL].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_NORMAL].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_NORMAL].y_offs;
dest_sprite->height = sprite[ZOOM_LVL_MIN].height;
dest_sprite->width = sprite[ZOOM_LVL_MIN].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_MIN].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_MIN].y_offs;
dest_sprite->next = nullptr;
dest_sprite->missing_zoom_levels = 0;
memcpy(dest_sprite->data, temp_dst, size);

@ -19,7 +19,7 @@ public:
/** Data stored about a (single) sprite. */
struct SpriteData {
uint32_t offset[ZOOM_LVL_SPR_COUNT]; ///< Offsets (from .data) to streams for different zoom levels.
byte data[]; ///< Data, all zoomlevels.
uint8_t data[]; ///< Data, all zoomlevels.
};
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override;

@ -65,18 +65,18 @@ void Blitter_8bppSimple::Draw(Blitter::BlitterParams *bp, BlitterMode mode, Zoom
Sprite *Blitter_8bppSimple::Encode(const SpriteLoader::SpriteCollection &sprite, AllocatorProc *allocator)
{
Sprite *dest_sprite;
dest_sprite = (Sprite *)allocator(sizeof(*dest_sprite) + (size_t)sprite[ZOOM_LVL_NORMAL].height * (size_t)sprite[ZOOM_LVL_NORMAL].width);
dest_sprite = (Sprite *)allocator(sizeof(*dest_sprite) + (size_t)sprite[ZOOM_LVL_MIN].height * (size_t)sprite[ZOOM_LVL_MIN].width);
dest_sprite->height = sprite[ZOOM_LVL_NORMAL].height;
dest_sprite->width = sprite[ZOOM_LVL_NORMAL].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_NORMAL].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_NORMAL].y_offs;
dest_sprite->height = sprite[ZOOM_LVL_MIN].height;
dest_sprite->width = sprite[ZOOM_LVL_MIN].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_MIN].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_MIN].y_offs;
dest_sprite->next = nullptr;
dest_sprite->missing_zoom_levels = 0;
/* Copy over only the 'remap' channel, as that is what we care about in 8bpp */
for (int i = 0; i < sprite[ZOOM_LVL_NORMAL].height * sprite[ZOOM_LVL_NORMAL].width; i++) {
dest_sprite->data[i] = sprite[ZOOM_LVL_NORMAL].data[i].m;
for (int i = 0; i < sprite[ZOOM_LVL_MIN].height * sprite[ZOOM_LVL_MIN].width; i++) {
dest_sprite->data[i] = sprite[ZOOM_LVL_MIN].data[i].m;
}
return dest_sprite;

@ -58,7 +58,7 @@ public:
/** Parameters related to blitting. */
struct BlitterParams {
const void *sprite; ///< Pointer to the sprite how ever the encoder stored it
const byte *remap; ///< XXX -- Temporary storage for remap array
const uint8_t *remap; ///< XXX -- Temporary storage for remap array
int brightness_adjust; ///< Brightness adjustment
int skip_left; ///< How much pixels of the source to skip on the left (based on zoom of dst)

@ -94,7 +94,7 @@ public:
* @param name the blitter to select.
* @post Sets the blitter so GetCurrentBlitter() returns it too.
*/
static Blitter *SelectBlitter(const std::string &name)
static Blitter *SelectBlitter(const std::string_view name)
{
BlitterFactory *b = GetBlitterFactory(name);
if (b == nullptr) return nullptr;
@ -112,17 +112,17 @@ public:
* @param name the blitter factory to select.
* @return The blitter factory, or nullptr when there isn't one with the wanted name.
*/
static BlitterFactory *GetBlitterFactory(const std::string &name)
static BlitterFactory *GetBlitterFactory(const std::string_view name)
{
#if defined(DEDICATED)
const char *default_blitter = "null";
const std::string_view default_blitter = "null";
#elif defined(WITH_COCOA)
const char *default_blitter = "32bpp-anim";
const std::string_view default_blitter = "32bpp-anim";
#else
const char *default_blitter = "8bpp-optimized";
const std::string_view default_blitter = "8bpp-optimized";
#endif
if (GetBlitters().empty()) return nullptr;
const char *bname = name.empty() ? default_blitter : name.c_str();
const std::string_view bname = name.empty() ? default_blitter : name;
for (auto &it : GetBlitters()) {
BlitterFactory *b = it.second;

@ -20,10 +20,10 @@ Sprite *Blitter_Null::Encode(const SpriteLoader::SpriteCollection &sprite, Alloc
Sprite *dest_sprite;
dest_sprite = (Sprite *)allocator(sizeof(*dest_sprite));
dest_sprite->height = sprite[ZOOM_LVL_NORMAL].height;
dest_sprite->width = sprite[ZOOM_LVL_NORMAL].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_NORMAL].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_NORMAL].y_offs;
dest_sprite->height = sprite[ZOOM_LVL_MIN].height;
dest_sprite->width = sprite[ZOOM_LVL_MIN].width;
dest_sprite->x_offs = sprite[ZOOM_LVL_MIN].x_offs;
dest_sprite->y_offs = sprite[ZOOM_LVL_MIN].y_offs;
dest_sprite->next = nullptr;
dest_sprite->missing_zoom_levels = 0;

@ -39,7 +39,7 @@ static inline bool EndOfBuffer(BmpBuffer *buffer)
return buffer->pos == buffer->read;
}
static inline byte ReadByte(BmpBuffer *buffer)
static inline uint8_t ReadByte(BmpBuffer *buffer)
{
if (buffer->read < 0) return 0;
@ -83,9 +83,9 @@ static inline void SetStreamOffset(BmpBuffer *buffer, int offset)
static inline bool BmpRead1(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x, y, i;
byte pad = GB(4 - info->width / 8, 0, 2);
byte *pixel_row;
byte b;
uint8_t pad = GB(4 - info->width / 8, 0, 2);
uint8_t *pixel_row;
uint8_t b;
for (y = info->height; y > 0; y--) {
x = 0;
pixel_row = &data->bitmap[(y - 1) * info->width];
@ -110,9 +110,9 @@ static inline bool BmpRead1(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
static inline bool BmpRead4(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x, y;
byte pad = GB(4 - info->width / 2, 0, 2);
byte *pixel_row;
byte b;
uint8_t pad = GB(4 - info->width / 2, 0, 2);
uint8_t *pixel_row;
uint8_t b;
for (y = info->height; y > 0; y--) {
x = 0;
pixel_row = &data->bitmap[(y - 1) * info->width];
@ -140,12 +140,12 @@ static inline bool BmpRead4Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x = 0;
uint y = info->height - 1;
byte *pixel = &data->bitmap[y * info->width];
uint8_t *pixel = &data->bitmap[y * info->width];
while (y != 0 || x < info->width) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
byte n = ReadByte(buffer);
byte c = ReadByte(buffer);
uint8_t n = ReadByte(buffer);
uint8_t c = ReadByte(buffer);
if (n == 0) {
switch (c) {
case 0: // end of line
@ -159,8 +159,8 @@ static inline bool BmpRead4Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
case 2: { // delta
if (EndOfBuffer(buffer)) return false;
byte dx = ReadByte(buffer);
byte dy = ReadByte(buffer);
uint8_t dx = ReadByte(buffer);
uint8_t dy = ReadByte(buffer);
/* Check for over- and underflow. */
if (x + dx >= info->width || x + dx < x || dy > y) return false;
@ -175,7 +175,7 @@ static inline bool BmpRead4Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
uint i = 0;
while (i++ < c) {
if (EndOfBuffer(buffer) || x >= info->width) return false;
byte b = ReadByte(buffer);
uint8_t b = ReadByte(buffer);
*pixel++ = GB(b, 4, 4);
x++;
if (i++ < c) {
@ -214,8 +214,8 @@ static inline bool BmpRead8(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint i;
uint y;
byte pad = GB(4 - info->width, 0, 2);
byte *pixel;
uint8_t pad = GB(4 - info->width, 0, 2);
uint8_t *pixel;
for (y = info->height; y > 0; y--) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
pixel = &data->bitmap[(y - 1) * info->width];
@ -233,12 +233,12 @@ static inline bool BmpRead8Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x = 0;
uint y = info->height - 1;
byte *pixel = &data->bitmap[y * info->width];
uint8_t *pixel = &data->bitmap[y * info->width];
while (y != 0 || x < info->width) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
byte n = ReadByte(buffer);
byte c = ReadByte(buffer);
uint8_t n = ReadByte(buffer);
uint8_t c = ReadByte(buffer);
if (n == 0) {
switch (c) {
case 0: // end of line
@ -252,8 +252,8 @@ static inline bool BmpRead8Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
case 2: { // delta
if (EndOfBuffer(buffer)) return false;
byte dx = ReadByte(buffer);
byte dy = ReadByte(buffer);
uint8_t dx = ReadByte(buffer);
uint8_t dy = ReadByte(buffer);
/* Check for over- and underflow. */
if (x + dx >= info->width || x + dx < x || dy > y) return false;
@ -294,8 +294,8 @@ static inline bool BmpRead8Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
static inline bool BmpRead24(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x, y;
byte pad = GB(4 - info->width * 3, 0, 2);
byte *pixel_row;
uint8_t pad = GB(4 - info->width * 3, 0, 2);
uint8_t *pixel_row;
for (y = info->height; y > 0; y--) {
pixel_row = &data->bitmap[(y - 1) * info->width * 3];
for (x = 0; x < info->width; x++) {
@ -395,7 +395,7 @@ bool BmpReadBitmap(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
assert(info != nullptr && data != nullptr);
data->bitmap = CallocT<byte>(static_cast<size_t>(info->width) * info->height * ((info->bpp == 24) ? 3 : 1));
data->bitmap = CallocT<uint8_t>(static_cast<size_t>(info->width) * info->height * ((info->bpp == 24) ? 3 : 1));
/* Load image */
SetStreamOffset(buffer, info->offset);

@ -24,13 +24,13 @@ struct BmpInfo {
struct BmpData {
Colour *palette;
byte *bitmap;
uint8_t *bitmap;
};
#define BMP_BUFFER_SIZE 1024
struct BmpBuffer {
byte data[BMP_BUFFER_SIZE];
uint8_t data[BMP_BUFFER_SIZE];
int pos;
int read;
FILE *file;

@ -96,12 +96,12 @@ public:
this->Window::Close();
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
if (widget == WID_BEM_MESSAGE) {
*size = GetStringBoundingBox(STR_MISSING_GRAPHICS_ERROR);
size->width += WidgetDimensions::scaled.frametext.Horizontal();
size->height += WidgetDimensions::scaled.frametext.Vertical();
size = GetStringBoundingBox(STR_MISSING_GRAPHICS_ERROR);
size.width += WidgetDimensions::scaled.frametext.Horizontal();
size.height += WidgetDimensions::scaled.frametext.Vertical();
}
}
@ -210,7 +210,7 @@ public:
this->Window::Close();
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
/* We cache the button size. This is safe as no reinit can happen here. */
if (this->button_size.width == 0) {
@ -222,13 +222,13 @@ public:
switch (widget) {
case WID_BAFD_QUESTION:
/* The question is twice as wide as the buttons, and determine the height based on the width. */
size->width = this->button_size.width * 2;
size->height = GetStringHeight(STR_MISSING_GRAPHICS_SET_MESSAGE, size->width - WidgetDimensions::scaled.frametext.Horizontal()) + WidgetDimensions::scaled.frametext.Vertical();
size.width = this->button_size.width * 2;
size.height = GetStringHeight(STR_MISSING_GRAPHICS_SET_MESSAGE, size.width - WidgetDimensions::scaled.frametext.Horizontal()) + WidgetDimensions::scaled.frametext.Vertical();
break;
case WID_BAFD_YES:
case WID_BAFD_NO:
*size = this->button_size;
size = this->button_size;
break;
}
}

@ -63,7 +63,7 @@ enum BridgeSpecCtrlFlags {
*/
struct BridgeSpec {
CalTime::Year avail_year; ///< the year where it becomes available
byte min_length; ///< the minimum length (not counting start and end tile)
uint8_t min_length; ///< the minimum length (not counting start and end tile)
uint16_t max_length; ///< the maximum length (not counting start and end tile)
uint16_t price; ///< the price multiplier
uint16_t speed; ///< maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
@ -72,9 +72,9 @@ struct BridgeSpec {
StringID material; ///< the string that contains the bridge description
StringID transport_name[2]; ///< description of the bridge, when built for road or rail
PalSpriteID **sprite_table; ///< table of sprites for drawing the bridge
byte flags; ///< bit 0 set: disable drawing of far pillars.
byte ctrl_flags; ///< control flags
byte pillar_flags[12]; ///< bridge pillar flags: 6 x pairs of x and y flags
uint8_t flags; ///< bit 0 set: disable drawing of far pillars.
uint8_t ctrl_flags; ///< control flags
uint8_t pillar_flags[12]; ///< bridge pillar flags: 6 x pairs of x and y flags
};
extern BridgeSpec _bridge[MAX_BRIDGES];

@ -18,7 +18,7 @@
#include "gfx_func.h"
#include "tunnelbridge.h"
#include "sortlist_type.h"
#include "widgets/dropdown_func.h"
#include "dropdown_func.h"
#include "core/geometry_func.hpp"
#include "cmd_helper.h"
#include "tunnelbridge_map.h"
@ -189,14 +189,14 @@ public:
this->Window::Close();
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_BBS_DROPDOWN_ORDER: {
Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
case WID_BBS_DROPDOWN_CRITERIA: {
@ -206,7 +206,7 @@ public:
}
d.width += padding.width;
d.height += padding.height;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
case WID_BBS_BRIDGE_LIST: {
@ -216,11 +216,11 @@ public:
sprite_dim = maxdim(sprite_dim, GetScaledSpriteSize(bridge_data.spec->sprite));
text_dim = maxdim(text_dim, GetStringBoundingBox(GetBridgeSelectString(bridge_data)));
}
resize->height = std::max(sprite_dim.height, text_dim.height) + padding.height; // Max of both sizes + account for matrix edges.
resize.height = std::max(sprite_dim.height, text_dim.height) + padding.height; // Max of both sizes + account for matrix edges.
this->icon_width = sprite_dim.width; // Width of bridge icon.
size->width = this->icon_width + WidgetDimensions::scaled.hsep_normal + text_dim.width + padding.width;
size->height = 4 * resize->height; // Smallest bridge gui is 4 entries high in the matrix.
size.width = this->icon_width + WidgetDimensions::scaled.hsep_normal + text_dim.width + padding.width;
size.height = 4 * resize.height; // Smallest bridge gui is 4 entries high in the matrix.
break;
}
}
@ -373,7 +373,7 @@ static WindowDesc _build_bridge_desc(__FILE__, __LINE__,
* @param transport_type The transport type
* @param road_rail_type The road/rail type
*/
void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type)
void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, uint8_t road_rail_type)
{
CloseWindowByClass(WC_BUILD_BRIDGE);

@ -79,7 +79,7 @@ int GetBridgeHeight(TileIndex t)
return h + 1 + ApplyFoundationToSlope(f, tileh);
}
std::unordered_map<TileIndex, LongBridgeSignalStorage> _long_bridge_signal_sim_map;
robin_hood::unordered_flat_map<TileIndex, LongBridgeSignalStorage> _long_bridge_signal_sim_map;
SignalState GetBridgeEntranceSimulatedSignalStateExtended(TileIndex t, uint16_t signal)
{

@ -360,7 +360,7 @@ inline bool IsCustomBridgeHeadTile(TileIndex t)
inline TrackBits GetBridgeReservationTrackBits(TileIndex t)
{
assert_tile(IsRailBridgeHeadTile(t), t);
byte track_b = GB(_m[t].m2, 0, 3);
uint8_t track_b = GB(_m[t].m2, 0, 3);
Track track = (Track)(track_b - 1); // map array saves Track+1
if (track_b == 0) return TRACK_BIT_NONE;
return (TrackBits)(TrackToTrackBits(track) | (HasBit(_m[t].m2, 3) ? TrackToTrackBits(TrackToOppositeTrack(track)) : 0));
@ -378,7 +378,7 @@ inline void SetBridgeReservationTrackBits(TileIndex t, TrackBits b)
assert(!TracksOverlap(b));
Track track = RemoveFirstTrack(&b);
SB(_m[t].m2, 0, 3, track == INVALID_TRACK ? 0 : track + 1);
SB(_m[t].m2, 3, 1, (byte)(b != TRACK_BIT_NONE));
SB(_m[t].m2, 3, 1, (uint8_t)(b != TRACK_BIT_NONE));
}

@ -15,15 +15,21 @@
#include "signal_type.h"
#include "core/bitmath_func.hpp"
#include "3rdparty/cpp-btree/btree_set.h"
#include "3rdparty/robin_hood/robin_hood.h"
#include <vector>
#include <unordered_map>
struct LongBridgeSignalStorage {
std::vector<uint64_t> signal_red_bits;
LongBridgeSignalStorage() = default;
LongBridgeSignalStorage(const LongBridgeSignalStorage &other) = delete;
LongBridgeSignalStorage(LongBridgeSignalStorage &&other) = default;
LongBridgeSignalStorage& operator=(const LongBridgeSignalStorage &other) = delete;
LongBridgeSignalStorage& operator=(LongBridgeSignalStorage &&other) = default;
};
extern std::unordered_map<TileIndex, LongBridgeSignalStorage> _long_bridge_signal_sim_map;
extern robin_hood::unordered_flat_map<TileIndex, LongBridgeSignalStorage> _long_bridge_signal_sim_map;
extern btree::btree_set<uint32_t> _bridge_signal_style_map;

File diff suppressed because it is too large Load Diff

@ -22,7 +22,7 @@ using CargoLabel = StrongType::Typedef<uint32_t, struct CargoLabelTag, StrongTyp
/**
* Cargo slots to indicate a cargo type within a game.
*/
using CargoID = byte;
using CargoID = uint8_t;
/**
* Available types of cargo
@ -149,7 +149,7 @@ struct CargoArray : std::array<uint, NUM_CARGO> {
/** Types of cargo source and destination */
enum class SourceType : byte {
enum class SourceType : uint8_t {
Industry, ///< Source/destination is an industry
Town, ///< Source/destination is a town
Headquarters, ///< Source/destination are company headquarters

@ -19,7 +19,7 @@
#include <vector>
/** Town growth effect when delivering cargo. */
enum TownAcceptanceEffect : byte {
enum TownAcceptanceEffect : uint8_t {
TAE_BEGIN = 0,
TAE_NONE = TAE_BEGIN, ///< Cargo has no effect.
TAE_PASSENGERS, ///< Cargo behaves passenger-like.
@ -32,7 +32,7 @@ enum TownAcceptanceEffect : byte {
};
/** Town effect when producing cargo. */
enum TownProductionEffect : byte {
enum TownProductionEffect : uint8_t {
TPE_NONE, ///< Town will not produce this cargo type.
TPE_PASSENGERS, ///< Cargo behaves passenger-like for production.
TPE_MAIL, ///< Cargo behaves mail-like for production.
@ -61,7 +61,7 @@ enum CargoClass {
CC_SPECIAL = 1 << 15, ///< Special bit used for livery refit tricks instead of normal cargoes.
};
static const byte INVALID_CARGO_BITNUM = 0xFF; ///< Constant representing invalid cargo
static const uint8_t INVALID_CARGO_BITNUM = 0xFF; ///< Constant representing invalid cargo
static const uint TOWN_PRODUCTION_DIVISOR = 256;

@ -330,7 +330,7 @@ struct CheatWindow : Window {
}
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
if (widget != WID_C_PANEL) return;
@ -379,8 +379,8 @@ struct CheatWindow : Window {
this->line_height = std::max<uint>(this->line_height, SETTING_BUTTON_HEIGHT);
this->line_height = std::max<uint>(this->line_height, GetCharacterHeight(FS_NORMAL)) + WidgetDimensions::scaled.framerect.Vertical();
size->width = width + WidgetDimensions::scaled.hsep_wide * 4 + this->box.width + SETTING_BUTTON_WIDTH /* stuff on the left */ + WidgetDimensions::scaled.hsep_wide * 2 /* extra spacing on right */;
size->height = WidgetDimensions::scaled.framerect.Vertical() + this->line_height * lines;
size.width = width + WidgetDimensions::scaled.hsep_wide * 4 + this->box.width + SETTING_BUTTON_WIDTH /* stuff on the left */ + WidgetDimensions::scaled.hsep_wide * 2 /* extra spacing on right */;
size.height = WidgetDimensions::scaled.framerect.Vertical() + this->line_height * lines;
}
void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
@ -507,7 +507,7 @@ struct CheatWindow : Window {
}
if (ce->mode == CNM_MONEY) {
if (!_networking) *ce->been_used = true;
DoCommandPEx(0, 0, 0, (std::strtoll(str, nullptr, 10) / _currency->rate), IsNetworkSettingsAdmin() ? CMD_MONEY_CHEAT_ADMIN : CMD_MONEY_CHEAT);
DoCommandPEx(0, 0, 0, (std::strtoll(str, nullptr, 10) / GetCurrency().rate), IsNetworkSettingsAdmin() ? CMD_MONEY_CHEAT_ADMIN : CMD_MONEY_CHEAT);
return;
}

@ -46,12 +46,12 @@ static CommandCost ClearTile_Clear(TileIndex tile, DoCommandFlag flags)
return price;
}
SpriteID GetSpriteIDForClearLand(const Slope slope, byte set)
SpriteID GetSpriteIDForClearLand(const Slope slope, uint8_t set)
{
return SPR_FLAT_BARE_LAND + SlopeToSpriteOffset(slope) + set * 19;
}
void DrawClearLandTile(const TileInfo *ti, byte set)
void DrawClearLandTile(const TileInfo *ti, uint8_t set)
{
DrawGroundSprite(GetSpriteIDForClearLand(ti->tileh, set), PAL_NONE);
}
@ -173,7 +173,7 @@ static void DrawTile_Clear(TileInfo *ti, DrawTileProcParams params)
break;
case CLEAR_FIELDS:
if (params.min_visible_height <= 4 * ZOOM_LVL_BASE) {
if (params.min_visible_height <= (4 * ZOOM_BASE)) {
DrawGroundSprite(GetSpriteIDForFields(ti->tileh, GetFieldType(ti->tile)), PAL_NONE);
DrawClearLandFence(ti);
}

@ -13,9 +13,9 @@
#include "tile_cmd.h"
void DrawHillyLandTile(const TileInfo *ti);
void DrawClearLandTile(const TileInfo *ti, byte set);
void DrawClearLandTile(const TileInfo *ti, uint8_t set);
SpriteID GetSpriteIDForClearLand(const Slope slope, byte set);
SpriteID GetSpriteIDForClearLand(const Slope slope, uint8_t set);
SpriteID GetSpriteIDForHillyLand(const Slope slope, const uint rough_index);
SpriteID GetSpriteIDForRocks(const Slope slope, const uint tile_hash);
SpriteID GetSpriteIDForFields(const Slope slope, const uint field_type);

@ -1119,7 +1119,7 @@ CommandCost DoCommandPInternal(TileIndex tile, uint32_t p1, uint32_t p2, uint64_
_additional_cash_required = 0;
/* Get pointer to command handler */
byte cmd_id = cmd & CMD_ID_MASK;
uint cmd_id = cmd & CMD_ID_MASK;
assert(cmd_id < lengthof(_command_proc_table));
const Command &command = _command_proc_table[cmd_id];
@ -1177,10 +1177,10 @@ CommandCost DoCommandPInternal(TileIndex tile, uint32_t p1, uint32_t p2, uint64_
if (_debug_desync_level >= 1) {
std::string aux_str;
if (aux_data != nullptr) {
std::vector<byte> buffer;
std::vector<uint8_t> buffer;
CommandSerialisationBuffer serialiser(buffer, SHRT_MAX);
aux_data->Serialise(serialiser);
aux_str = FormatArrayAsHex(buffer);
aux_str = FormatArrayAsHex(buffer, false);
}
std::string text_buf;
if (text != nullptr) {

@ -25,7 +25,7 @@ struct CommandDeserialisationBuffer : public BufferDeserialisationHelper<Command
CommandDeserialisationBuffer(const uint8_t *buffer, size_t size) : buffer(buffer), size(size) {}
const byte *GetDeserialisationBuffer() const { return this->buffer; }
const uint8_t *GetDeserialisationBuffer() const { return this->buffer; }
size_t GetDeserialisationBufferSize() const { return this->size; }
size_t &GetDeserialisationPosition() { return this->pos; }
@ -44,17 +44,17 @@ struct CommandDeserialisationBuffer : public BufferDeserialisationHelper<Command
};
struct CommandSerialisationBuffer : public BufferSerialisationHelper<CommandSerialisationBuffer> {
std::vector<byte> &buffer;
std::vector<uint8_t> &buffer;
size_t limit;
CommandSerialisationBuffer(std::vector<byte> &buffer, size_t limit) : buffer(buffer), limit(limit) {}
CommandSerialisationBuffer(std::vector<uint8_t> &buffer, size_t limit) : buffer(buffer), limit(limit) {}
std::vector<byte> &GetSerialisationBuffer() { return this->buffer; }
std::vector<uint8_t> &GetSerialisationBuffer() { return this->buffer; }
size_t GetSerialisationLimit() const { return this->limit; }
};
struct CommandAuxiliarySerialised : public CommandAuxiliaryBase {
std::vector<byte> serialised_data;
std::vector<uint8_t> serialised_data;
CommandAuxiliaryBase *Clone() const override
{

@ -50,6 +50,8 @@ struct CompanyInfrastructure {
uint32_t GetTramTotal() const;
char *Dump(char *buffer, const char *last) const;
bool operator==(const CompanyInfrastructure &) const = default;
};
class FreeUnitIDGenerator {
@ -65,7 +67,7 @@ private:
std::vector<BitmapStorage> used_bitmap;
};
enum CompanyBankruptcyFlags : byte {
enum CompanyBankruptcyFlags : uint8_t {
CBRF_NONE = 0x0,
CBRF_SALE = 0x1, ///< the company has been marked for sale
CBRF_SALE_ONLY = 0x2, ///< the company has been marked for sale without being in a bankruptcy state first
@ -88,13 +90,13 @@ struct CompanyProperties {
CompanyManagerFace face; ///< Face description of the president.
Money money; ///< Money owned by the company.
byte money_fraction; ///< Fraction of money of the company, too small to represent in #money.
uint8_t money_fraction; ///< Fraction of money of the company, too small to represent in #money.
Money current_loan; ///< Amount of money borrowed from the bank.
Money max_loan; ///< Max allowed amount of the loan or COMPANY_MAX_LOAN_DEFAULT.
Colours colour; ///< Company colour.
byte block_preview; ///< Number of quarters that the company is not allowed to get new exclusive engine previews (see CompaniesGenStatistics).
uint8_t block_preview; ///< Number of quarters that the company is not allowed to get new exclusive engine previews (see CompaniesGenStatistics).
TileIndex location_of_HQ; ///< Northern tile of HQ; #INVALID_TILE when there is none.
TileIndex last_build_coordinate; ///< Coordinate of the last build thing by this company.
@ -105,7 +107,8 @@ struct CompanyProperties {
int32_t display_inaugurated_period;///< Wallclock display period of starting the company.
YearDelta age_years; ///< Number of economy years that the company has been operational.
byte months_of_bankruptcy; ///< Number of months that the company is unable to pay its debts
uint8_t months_empty = 0; ///< NOSAVE: Number of months this company has not had a client in multiplayer.
uint8_t months_of_bankruptcy; ///< Number of months that the company is unable to pay its debts
CompanyID bankrupt_last_asked; ///< Which company was most recently asked about buying it?
CompanyBankruptcyFlags bankrupt_flags; ///< bankruptcy flags
CompanyMask bankrupt_asked; ///< which companies were asked about buying it?
@ -127,7 +130,7 @@ struct CompanyProperties {
std::array<Expenses, 3> yearly_expenses{}; ///< Expenses of the company for the last three years.
CompanyEconomyEntry cur_economy; ///< Economic data of the company of this quarter.
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]; ///< Economic data of the company of the last #MAX_HISTORY_QUARTERS quarters.
byte num_valid_stat_ent; ///< Number of valid statistical entries in #old_economy.
uint8_t num_valid_stat_ent; ///< Number of valid statistical entries in #old_economy.
Livery livery[LS_END];

@ -37,7 +37,6 @@
#include "story_base.h"
#include "zoning.h"
#include "tbtr_template_vehicle_func.h"
#include "widgets/statusbar_widget.h"
#include "core/backup_type.hpp"
#include "debug_desync.h"
#include "timer/timer.h"
@ -45,6 +44,8 @@
#include "tilehighlight_func.h"
#include "plans_func.h"
#include "widgets/statusbar_widget.h"
#include "table/strings.h"
#include <vector>
@ -323,10 +324,10 @@ void SubtractMoneyFromCompany(const CommandCost &cost)
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
{
Company *c = Company::Get(company);
byte m = c->money_fraction;
uint8_t m = c->money_fraction;
Money cost = cst.GetCost();
c->money_fraction = m - (byte)cost;
c->money_fraction = m - (uint8_t)cost;
cost >>= 8;
if (c->money_fraction > m) cost++;
if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
@ -473,7 +474,7 @@ bad_town_name:;
}
/** Sorting weights for the company colours. */
static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
static const uint8_t _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
/** Similar colours, so we can try to prevent same coloured companies. */
static const Colours _similar_colour[COLOUR_END][2] = {
{ COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
@ -668,7 +669,7 @@ Company *DoStartupNewCompany(DoStartupNewCompanyFlag flags, CompanyID company)
}
/** Start a new competitor company if possible. */
TimeoutTimer<TimerGameTick> _new_competitor_timeout(0, []() {
TimeoutTimer<TimerGameTick> _new_competitor_timeout({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, 0 }, []() {
if (_game_mode == GM_MENU || !AI::CanStartNew()) return;
if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
@ -850,7 +851,7 @@ void OnTick_Companies(bool main_tick)
/* Randomize a bit when the AI is actually going to start; ranges from 87.5% .. 112.5% of indicated value. */
timeout += ScriptObject::GetRandomizer(OWNER_NONE).Next(timeout / 4) - timeout / 8;
_new_competitor_timeout.Reset(std::max(1, timeout));
_new_competitor_timeout.Reset({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, static_cast<uint>(std::max(1, timeout)) });
}
}
@ -931,6 +932,7 @@ void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
* - bits 0..15: CompanyCtrlAction
* - bits 16..23: CompanyID
* - bits 24..31: CompanyRemoveReason (with CCA_DELETE)
* - bits 24..31: CompanyID to merge (with CCA_MERGE)
* @param p2 ClientID
* @param text unused
* @return the cost of this operation or an error
@ -1071,6 +1073,38 @@ CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32_t p1, uin
break;
}
case CCA_MERGE: {
Company *c = Company::GetIfValid(company_id);
if (c == nullptr) return CMD_ERROR;
CompanyID to_merge_id = (CompanyID)GB(p1, 24, 8);
if (to_merge_id == company_id) return CMD_ERROR;
Company *to_merge = Company::GetIfValid(to_merge_id);
if (to_merge == nullptr) return CMD_ERROR;
if (!(flags & DC_EXEC)) return CommandCost();
SubtractMoneyFromAnyCompany(c, CommandCost(EXPENSES_OTHER, to_merge->current_loan - to_merge->money));
DEBUG(desync, 1, "merge_companies: %s, company_id: %u, merged_company_id: %u", debug_date_dumper().HexDate(), company_id, to_merge_id);
CompanyNewsInformation *cni = new CompanyNewsInformation(to_merge, c);
SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
SetDParam(1, STR_NEWS_MERGER_TAKEOVER_TITLE);
SetDParamStr(2, cni->company_name);
SetDParamStr(3, cni->other_company_name);
AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
AI::BroadcastNewEvent(new ScriptEventCompanyMerger(to_merge_id, company_id));
Game::NewEvent(new ScriptEventCompanyMerger(to_merge_id, company_id));
ChangeOwnershipOfCompanyItems(to_merge_id, company_id);
PostAcquireCompany(to_merge);
break;
}
default: return CMD_ERROR;
}
@ -1312,6 +1346,7 @@ CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32_t p1,
}
}
InvalidateWindowClassesData(WC_COMPANY, 1);
MarkWholeScreenDirty();
CompanyAdminUpdate(c);
}

@ -23,7 +23,8 @@
#include "company_manager_face.h"
#include "strings_func.h"
#include "date_func.h"
#include "widgets/dropdown_type.h"
#include "dropdown_type.h"
#include "dropdown_common_type.h"
#include "tilehighlight_func.h"
#include "company_base.h"
#include "core/geometry_func.hpp"
@ -37,7 +38,7 @@
#include "station_func.h"
#include "zoom_func.h"
#include "sortlist_type.h"
#include "group_gui_list.h"
#include "group_gui.h"
#include "core/backup_type.hpp"
#include "widgets/company_widget.h"
@ -386,29 +387,29 @@ struct CompanyFinancesWindow : Window {
}
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_CF_EXPS_CATEGORY:
size->width = GetMaxCategoriesWidth();
size->height = GetTotalCategoriesHeight();
size.width = GetMaxCategoriesWidth();
size.height = GetTotalCategoriesHeight();
break;
case WID_CF_EXPS_PRICE1:
case WID_CF_EXPS_PRICE2:
case WID_CF_EXPS_PRICE3:
size->height = GetTotalCategoriesHeight();
size.height = GetTotalCategoriesHeight();
[[fallthrough]];
case WID_CF_BALANCE_VALUE:
case WID_CF_LOAN_VALUE:
case WID_CF_OWN_VALUE:
SetDParamMaxValue(0, this->max_money);
size->width = std::max(GetStringBoundingBox(STR_FINANCES_NEGATIVE_INCOME).width, GetStringBoundingBox(STR_FINANCES_POSITIVE_INCOME).width) + padding.width;
size.width = std::max(GetStringBoundingBox(STR_FINANCES_NEGATIVE_INCOME).width, GetStringBoundingBox(STR_FINANCES_POSITIVE_INCOME).width) + padding.width;
break;
case WID_CF_INTEREST_RATE:
size->height = GetCharacterHeight(FS_NORMAL);
size.height = GetCharacterHeight(FS_NORMAL);
break;
}
}
@ -530,12 +531,12 @@ struct CompanyFinancesWindow : Window {
if (this->query_widget == WID_CF_INCREASE_LOAN) {
const Company *c = Company::Get((CompanyID)this->window_number);
Money amount = std::min<Money>(std::strtoull(str, nullptr, 10) / _currency->rate, _economy.max_loan - c->current_loan);
Money amount = std::min<Money>(std::strtoull(str, nullptr, 10) / GetCurrency().rate, _economy.max_loan - c->current_loan);
amount = LOAN_INTERVAL * CeilDivT<Money>(amount, LOAN_INTERVAL);
DoCommandP(0, amount >> 32, (amount & 0xFFFFFFFC) | 2, CMD_INCREASE_LOAN | CMD_MSG(STR_ERROR_CAN_T_BORROW_ANY_MORE_MONEY));
} else if (this->query_widget == WID_CF_REPAY_LOAN) {
const Company *c = Company::Get((CompanyID)this->window_number);
Money amount = std::min<Money>(std::strtoull(str, nullptr, 10) / _currency->rate, c->current_loan);
Money amount = std::min<Money>(std::strtoull(str, nullptr, 10) / GetCurrency().rate, c->current_loan);
amount = LOAN_INTERVAL * CeilDivT<Money>(amount, LOAN_INTERVAL);
DoCommandP(0, amount >> 32, (amount & 0xFFFFFFFC) | 2, CMD_DECREASE_LOAN | CMD_MSG(STR_ERROR_CAN_T_REPAY_LOAN));
}
@ -592,26 +593,6 @@ void ShowCompanyFinances(CompanyID company)
new CompanyFinancesWindow(&_company_finances_desc, company);
}
/* List of colours for the livery window */
static const StringID _colour_dropdown[] = {
STR_COLOUR_DARK_BLUE,
STR_COLOUR_PALE_GREEN,
STR_COLOUR_PINK,
STR_COLOUR_YELLOW,
STR_COLOUR_RED,
STR_COLOUR_LIGHT_BLUE,
STR_COLOUR_GREEN,
STR_COLOUR_DARK_GREEN,
STR_COLOUR_BLUE,
STR_COLOUR_CREAM,
STR_COLOUR_MAUVE,
STR_COLOUR_PURPLE,
STR_COLOUR_ORANGE,
STR_COLOUR_BROWN,
STR_COLOUR_GREY,
STR_COLOUR_WHITE,
};
/* Association of liveries to livery classes */
static const LiveryClass _livery_class[LS_END] = {
LC_OTHER,
@ -629,7 +610,7 @@ static const LiveryClass _livery_class[LS_END] = {
template <SpriteID TSprite = SPR_SQUARE>
class DropDownListColourItem : public DropDownIcon<DropDownString<DropDownListItem>> {
public:
DropDownListColourItem(int colour, bool masked) : DropDownIcon<DropDownString<DropDownListItem>>(TSprite, GENERAL_SPRITE_COLOUR(colour % COLOUR_END), colour < COLOUR_END ? _colour_dropdown[colour] : STR_COLOUR_DEFAULT, colour, masked)
DropDownListColourItem(int colour, bool masked) : DropDownIcon<DropDownString<DropDownListItem>>(TSprite, GENERAL_SPRITE_COLOUR(colour % COLOUR_END), colour < COLOUR_END ? (STR_COLOUR_DARK_BLUE + colour) : STR_COLOUR_DEFAULT, colour, masked)
{
}
};
@ -643,7 +624,6 @@ private:
uint rows;
uint line_height;
GUIGroupList groups;
std::vector<int> indents;
Scrollbar *vscroll;
void ShowColourDropDownMenu(uint32_t widget)
@ -651,7 +631,7 @@ private:
uint32_t used_colours = 0;
const Livery *livery, *default_livery = nullptr;
bool primary = widget == WID_SCL_PRI_COL_DROPDOWN;
byte default_col = 0;
uint8_t default_col = 0;
/* Disallow other company colours for the primary colour */
if (this->livery_class < LC_GROUP_RAIL && HasBit(this->sel, LS_DEFAULT) && primary) {
@ -688,11 +668,11 @@ private:
default_col = (primary ? default_livery->colour1 : default_livery->colour2) + COLOUR_END;
list.push_back(std::make_unique<DropDownListColourItem<>>(default_col, false));
}
for (uint i = 0; i < lengthof(_colour_dropdown); i++) {
list.push_back(std::make_unique<DropDownListColourItem<>>(i, HasBit(used_colours, i)));
for (Colours colour = COLOUR_BEGIN; colour != COLOUR_END; colour++) {
list.push_back(std::make_unique<DropDownListColourItem<>>(colour, HasBit(used_colours, colour)));
}
byte sel;
uint8_t sel;
if (default_livery == nullptr || HasBit(livery->in_use, primary ? 0 : 1)) {
sel = primary ? livery->colour1 : livery->colour2;
} else {
@ -701,37 +681,16 @@ private:
ShowDropDownList(this, std::move(list), sel, widget);
}
void AddChildren(GUIGroupList &source, GroupID parent, int indent)
{
for (const Group *g : source) {
if (g->parent != parent) continue;
this->groups.push_back(g);
this->indents.push_back(indent);
AddChildren(source, g->index, indent + 1);
}
}
void BuildGroupList(CompanyID owner)
{
if (!this->groups.NeedRebuild()) return;
this->groups.clear();
this->indents.clear();
if (this->livery_class >= LC_GROUP_RAIL) {
GUIGroupList list;
VehicleType vtype = (VehicleType)(this->livery_class - LC_GROUP_RAIL);
for (const Group *g : Group::Iterate()) {
if (g->owner == owner && g->vehicle_type == vtype) {
list.push_back(g);
}
}
list.ForceResort();
SortGUIGroupList(list);
AddChildren(list, INVALID_GROUP, 0);
BuildGuiGroupList(this->groups, false, owner, vtype);
}
this->groups.shrink_to_fit();
@ -795,14 +754,14 @@ public:
/* Position scrollbar to selected group */
for (uint i = 0; i < this->rows; i++) {
if (this->groups[i]->index == sel) {
if (this->groups[i].group->index == sel) {
this->vscroll->SetPosition(i - this->vscroll->GetCapacity() / 2);
break;
}
}
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_SCL_SPACER_DROPDOWN: {
@ -820,7 +779,7 @@ public:
}
}
size->width = std::max(size->width, 5 + d.width + padding.width);
size.width = std::max(size.width, 5 + d.width + padding.width);
break;
}
@ -829,15 +788,15 @@ public:
this->square = GetSpriteSize(SPR_SQUARE);
this->line_height = std::max(this->square.height, (uint)GetCharacterHeight(FS_NORMAL)) + padding.height;
size->height = 5 * this->line_height;
resize->width = 1;
resize->height = this->line_height;
size.height = 5 * this->line_height;
resize.width = 1;
resize.height = this->line_height;
break;
}
case WID_SCL_SEC_COL_DROPDOWN:
if (!_loaded_newgrf_features.has_2CC) {
size->width = 0;
size.width = 0;
break;
}
[[fallthrough]];
@ -845,10 +804,10 @@ public:
case WID_SCL_PRI_COL_DROPDOWN: {
this->square = GetSpriteSize(SPR_SQUARE);
int string_padding = this->square.width + WidgetDimensions::scaled.hsep_normal + padding.width;
for (const StringID *id = _colour_dropdown; id != endof(_colour_dropdown); id++) {
size->width = std::max(size->width, GetStringBoundingBox(*id).width + string_padding);
for (Colours colour = COLOUR_BEGIN; colour != COLOUR_END; colour++) {
size.width = std::max(size.width, GetStringBoundingBox(STR_COLOUR_DARK_BLUE + colour).width + string_padding);
}
size->width = std::max(size->width, GetStringBoundingBox(STR_COLOUR_DEFAULT).width + string_padding);
size.width = std::max(size.width, GetStringBoundingBox(STR_COLOUR_DEFAULT).width + string_padding);
break;
}
}
@ -965,11 +924,11 @@ public:
}
}
} else {
uint max = static_cast<uint>(std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->groups.size()));
for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
const Group *g = this->groups[i];
auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->groups);
for (auto it = first; it != last; ++it) {
const Group *g = it->group;
SetDParam(0, g->index);
draw_livery(STR_GROUP_NAME, g->livery, this->sel == g->index, false, this->indents[i] * WidgetDimensions::scaled.hsep_indent);
draw_livery(STR_GROUP_NAME, g->livery, this->sel == g->index, false, it->indent * WidgetDimensions::scaled.hsep_indent);
}
if (this->vscroll->GetCount() == 0) {
@ -1012,7 +971,7 @@ public:
this->BuildGroupList((CompanyID)this->window_number);
if (!this->groups.empty()) {
this->sel = this->groups[0]->index;
this->sel = this->groups[0].group->index;
}
}
@ -1029,10 +988,10 @@ public:
break;
case WID_SCL_MATRIX: {
uint row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SCL_MATRIX);
if (row >= this->rows) return;
if (this->livery_class < LC_GROUP_RAIL) {
uint row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, widget);
if (row >= this->rows) return;
LiveryScheme j = (LiveryScheme)row;
for (LiveryScheme scheme = LS_BEGIN; scheme <= j && scheme < LS_END; scheme++) {
@ -1046,7 +1005,10 @@ public:
this->sel = 1 << j;
}
} else {
this->sel = this->groups[row]->index;
auto it = this->vscroll->GetScrolledItemFromWidget(this->groups, pt.y, this, widget);
if (it == std::end(this->groups)) return;
this->sel = it->group->index;
}
this->SetDirty();
break;
@ -1099,7 +1061,7 @@ public:
if (!Group::IsValidID(this->sel)) {
this->sel = INVALID_GROUP;
if (!this->groups.empty()) this->sel = this->groups[0]->index;
if (!this->groups.empty()) this->sel = this->groups[0].group->index;
}
this->SetDirty();
@ -1486,31 +1448,31 @@ public:
this->number_dim = number_dim;
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_SCMF_HAS_MOUSTACHE_EARRING_TEXT:
*size = maxdim(*size, GetStringBoundingBox(STR_FACE_EARRING));
*size = maxdim(*size, GetStringBoundingBox(STR_FACE_MOUSTACHE));
size = maxdim(size, GetStringBoundingBox(STR_FACE_EARRING));
size = maxdim(size, GetStringBoundingBox(STR_FACE_MOUSTACHE));
break;
case WID_SCMF_TIE_EARRING_TEXT:
*size = maxdim(*size, GetStringBoundingBox(STR_FACE_EARRING));
*size = maxdim(*size, GetStringBoundingBox(STR_FACE_TIE));
size = maxdim(size, GetStringBoundingBox(STR_FACE_EARRING));
size = maxdim(size, GetStringBoundingBox(STR_FACE_TIE));
break;
case WID_SCMF_LIPS_MOUSTACHE_TEXT:
*size = maxdim(*size, GetStringBoundingBox(STR_FACE_LIPS));
*size = maxdim(*size, GetStringBoundingBox(STR_FACE_MOUSTACHE));
size = maxdim(size, GetStringBoundingBox(STR_FACE_LIPS));
size = maxdim(size, GetStringBoundingBox(STR_FACE_MOUSTACHE));
break;
case WID_SCMF_FACE:
*size = maxdim(*size, GetScaledSpriteSize(SPR_GRADIENT));
size = maxdim(size, GetScaledSpriteSize(SPR_GRADIENT));
break;
case WID_SCMF_HAS_MOUSTACHE_EARRING:
case WID_SCMF_HAS_GLASSES:
*size = this->yesno_dim;
size = this->yesno_dim;
break;
case WID_SCMF_EYECOLOUR:
@ -1523,7 +1485,7 @@ public:
case WID_SCMF_COLLAR:
case WID_SCMF_TIE_EARRING:
case WID_SCMF_GLASSES:
*size = this->number_dim;
size = this->number_dim;
break;
}
}
@ -1914,7 +1876,7 @@ struct CompanyInfrastructureWindow : Window
}
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
const Company *c = Company::Get((CompanyID)this->window_number);
@ -1922,24 +1884,24 @@ struct CompanyInfrastructureWindow : Window
case WID_CI_DESC: {
uint rail_lines = 1; // Starts at 1 because a line is also required for the section title
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_RAIL_SECT).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_RAIL_SECT).width);
for (const auto &rt : _sorted_railtypes) {
if (HasBit(this->railtypes, rt)) {
rail_lines++;
size->width = std::max(size->width, GetStringBoundingBox(GetRailTypeInfo(rt)->strings.name).width + WidgetDimensions::scaled.hsep_indent);
size.width = std::max(size.width, GetStringBoundingBox(GetRailTypeInfo(rt)->strings.name).width + WidgetDimensions::scaled.hsep_indent);
}
}
if (this->railtypes != RAILTYPES_NONE) {
rail_lines++;
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_SIGNALS).width + WidgetDimensions::scaled.hsep_indent);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_SIGNALS).width + WidgetDimensions::scaled.hsep_indent);
}
uint road_lines = 1; // Starts at 1 because a line is also required for the section title
uint tram_lines = 1;
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_ROAD_SECT).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_TRAM_SECT).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_ROAD_SECT).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_TRAM_SECT).width);
for (const auto &rt : _sorted_roadtypes) {
if (HasBit(this->roadtypes, rt)) {
@ -1948,18 +1910,18 @@ struct CompanyInfrastructureWindow : Window
} else {
tram_lines++;
}
size->width = std::max(size->width, GetStringBoundingBox(GetRoadTypeInfo(rt)->strings.name).width + WidgetDimensions::scaled.hsep_indent);
size.width = std::max(size.width, GetStringBoundingBox(GetRoadTypeInfo(rt)->strings.name).width + WidgetDimensions::scaled.hsep_indent);
}
}
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_WATER_SECT).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_CANALS).width + WidgetDimensions::scaled.hsep_indent);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_WATER_SECT).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_CANALS).width + WidgetDimensions::scaled.hsep_indent);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_STATION_SECT).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_STATIONS).width + WidgetDimensions::scaled.hsep_indent);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_AIRPORTS).width + WidgetDimensions::scaled.hsep_indent);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_STATION_SECT).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_STATIONS).width + WidgetDimensions::scaled.hsep_indent);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_INFRASTRUCTURE_VIEW_AIRPORTS).width + WidgetDimensions::scaled.hsep_indent);
size->width += padding.width;
size.width += padding.width;
uint total_height = ((rail_lines + road_lines + tram_lines + 2 + 3) * GetCharacterHeight(FS_NORMAL)) + (4 * WidgetDimensions::scaled.vsep_sparse);
@ -1968,9 +1930,9 @@ struct CompanyInfrastructureWindow : Window
this->vscroll->SetCount(total_height);
size->height = std::max(size->height, std::min<uint>(8 * GetCharacterHeight(FS_NORMAL), total_height));
size.height = std::max(size.height, std::min<uint>(8 * GetCharacterHeight(FS_NORMAL), total_height));
uint target_height = std::min<uint>(40 * GetCharacterHeight(FS_NORMAL), total_height);
this->height_extra = (target_height > size->height) ? (target_height - size->height) : 0;
this->height_extra = (target_height > size.height) ? (target_height - size.height) : 0;
break;
}
@ -2005,13 +1967,13 @@ struct CompanyInfrastructureWindow : Window
if (_settings_game.economy.infrastructure_maintenance) {
SetDParamMaxValue(0, this->GetTotalMaintenanceCost() * 12); // Convert to per year
this->total_width = GetStringBoundingBox(EconTime::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR).width + WidgetDimensions::scaled.hsep_indent * 2;
size->width = std::max(size->width, this->total_width);
size.width = std::max(size.width, this->total_width);
SetDParamMaxValue(0, max_cost * 12); // Convert to per year
count_width += std::max(this->total_width, GetStringBoundingBox(EconTime::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR).width);
}
size->width = std::max(size->width, count_width);
size.width = std::max(size.width, count_width);
break;
}
}
@ -2365,7 +2327,7 @@ struct CompanyWindow : Window
/* Owners of company */
{
int plane = SZSP_HORIZONTAL;
for (uint i = 0; i < lengthof(c->share_owners); i++) {
for (size_t i = 0; i < std::size(c->share_owners); i++) {
if (c->share_owners[i] != INVALID_COMPANY) {
plane = 0;
break;
@ -2394,11 +2356,11 @@ struct CompanyWindow : Window
this->DrawWidgets();
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_C_FACE:
*size = maxdim(*size, GetScaledSpriteSize(SPR_GRADIENT));
size = maxdim(size, GetScaledSpriteSize(SPR_GRADIENT));
break;
case WID_C_DESC_COLOUR_SCHEME_EXAMPLE: {
@ -2406,31 +2368,31 @@ struct CompanyWindow : Window
Dimension d = GetSpriteSize(SPR_VEH_BUS_SW_VIEW, &offset);
d.width -= offset.x;
d.height -= offset.y;
*size = maxdim(*size, d);
size = maxdim(size, d);
break;
}
case WID_C_DESC_COMPANY_VALUE:
SetDParam(0, INT64_MAX); // Arguably the maximum company value
size->width = GetStringBoundingBox(STR_COMPANY_VIEW_COMPANY_VALUE).width;
size.width = GetStringBoundingBox(STR_COMPANY_VIEW_COMPANY_VALUE).width;
break;
case WID_C_DESC_VEHICLE_COUNTS:
SetDParamMaxValue(0, 5000); // Maximum number of vehicles
for (uint i = 0; i < lengthof(_company_view_vehicle_count_strings); i++) {
size->width = std::max(size->width, GetStringBoundingBox(_company_view_vehicle_count_strings[i]).width + padding.width);
size.width = std::max(size.width, GetStringBoundingBox(_company_view_vehicle_count_strings[i]).width + padding.width);
}
break;
case WID_C_DESC_INFRASTRUCTURE_COUNTS:
SetDParamMaxValue(0, UINT_MAX);
size->width = GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_RAIL).width;
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_ROAD).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_WATER).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_STATION).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_AIRPORT).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_NONE).width);
size->width += padding.width;
size.width = GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_RAIL).width;
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_ROAD).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_WATER).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_STATION).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_AIRPORT).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_NONE).width);
size.width += padding.width;
break;
case WID_C_DESC_OWNERS: {
@ -2438,7 +2400,7 @@ struct CompanyWindow : Window
SetDParamMaxValue(0, 75);
SetDParam(1, c2->index);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_SHARES_OWNED_BY).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_SHARES_OWNED_BY).width);
}
break;
}
@ -2451,20 +2413,20 @@ struct CompanyWindow : Window
case WID_C_HOSTILE_TAKEOVER:
case WID_C_COMPANY_PASSWORD:
case WID_C_COMPANY_JOIN:
size->width = GetStringBoundingBox(STR_COMPANY_VIEW_VIEW_HQ_BUTTON).width;
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_BUILD_HQ_BUTTON).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_RELOCATE_HQ).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_BUTTON).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_GIVE_MONEY_BUTTON).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_HOSTILE_TAKEOVER_BUTTON).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_PASSWORD).width);
size->width = std::max(size->width, GetStringBoundingBox(STR_COMPANY_VIEW_JOIN).width);
size->width += padding.width;
size.width = GetStringBoundingBox(STR_COMPANY_VIEW_VIEW_HQ_BUTTON).width;
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_BUILD_HQ_BUTTON).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_RELOCATE_HQ).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_BUTTON).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_GIVE_MONEY_BUTTON).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_HOSTILE_TAKEOVER_BUTTON).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_PASSWORD).width);
size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_JOIN).width);
size.width += padding.width;
break;
case WID_C_HAS_PASSWORD:
if (_networking) *size = maxdim(*size, GetSpriteSize(SPR_LOCK));
if (_networking) size = maxdim(size, GetSpriteSize(SPR_LOCK));
break;
}
}
@ -2604,6 +2566,14 @@ struct CompanyWindow : Window
}
}
void OnResize() override
{
NWidgetResizeBase *wid = this->GetWidget<NWidgetResizeBase>(WID_C_FACE_TITLE);
SetDParam(0, this->owner);
int y = GetStringHeight(STR_COMPANY_VIEW_PRESIDENT_MANAGER_TITLE, wid->current_x);
if (wid->UpdateVerticalSize(y)) this->ReInit(0, 0);
}
void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
{
switch (widget) {
@ -2636,7 +2606,7 @@ struct CompanyWindow : Window
}
case WID_C_BUILD_HQ:
if ((byte)this->window_number != _local_company) return;
if ((uint8_t)this->window_number != _local_company) return;
if (this->IsWidgetLowered(WID_C_BUILD_HQ)) {
ResetObjectToPlace();
this->RaiseButtons();
@ -2730,7 +2700,7 @@ struct CompanyWindow : Window
default: NOT_REACHED();
case WID_C_GIVE_MONEY:
DoCommandPEx(0, this->window_number, 0, (std::strtoull(str, nullptr, 10) / _currency->rate), CMD_GIVE_MONEY | CMD_MSG(STR_ERROR_CAN_T_GIVE_MONEY), CcGiveMoney);
DoCommandPEx(0, this->window_number, 0, (std::strtoull(str, nullptr, 10) / GetCurrency().rate), CMD_GIVE_MONEY | CMD_MSG(STR_ERROR_CAN_T_GIVE_MONEY), CcGiveMoney);
break;
case WID_C_PRESIDENT_NAME:
@ -2747,7 +2717,6 @@ struct CompanyWindow : Window
}
}
/**
* Some data on this window has become invalid.
* @param data Information about the changed data.
@ -2755,25 +2724,30 @@ struct CompanyWindow : Window
*/
void OnInvalidateData(int data = 0, bool gui_scope = true) override
{
if (this->window_number == _local_company) return;
if (_settings_game.economy.allow_shares) { // Shares are allowed
const Company *c = Company::Get(this->window_number);
/* If all shares are owned by someone (none by nobody), disable buy button */
this->SetWidgetDisabledState(WID_C_BUY_SHARE, GetAmountOwnedBy(c, INVALID_OWNER) == 0 ||
/* Only 25% left to buy. If the company is human, disable buying it up.. TODO issues! */
(GetAmountOwnedBy(c, INVALID_OWNER) == 1 && !c->is_ai) ||
/* Spectators cannot do anything of course */
_local_company == COMPANY_SPECTATOR);
if (this->window_number != _local_company) {
if (_settings_game.economy.allow_shares) { // Shares are allowed
const Company *c = Company::Get(this->window_number);
/* If all shares are owned by someone (none by nobody), disable buy button */
this->SetWidgetDisabledState(WID_C_BUY_SHARE, GetAmountOwnedBy(c, INVALID_OWNER) == 0 ||
/* Only 25% left to buy. If the company is human, disable buying it up.. TODO issues! */
(GetAmountOwnedBy(c, INVALID_OWNER) == 1 && !c->is_ai) ||
/* Spectators cannot do anything of course */
_local_company == COMPANY_SPECTATOR);
/* If the company doesn't own any shares, disable sell button */
this->SetWidgetDisabledState(WID_C_SELL_SHARE, (GetAmountOwnedBy(c, _local_company) == 0) ||
/* Spectators cannot do anything of course */
_local_company == COMPANY_SPECTATOR);
} else { // Shares are not allowed, disable buy/sell buttons
this->DisableWidget(WID_C_BUY_SHARE);
this->DisableWidget(WID_C_SELL_SHARE);
}
}
/* If the company doesn't own any shares, disable sell button */
this->SetWidgetDisabledState(WID_C_SELL_SHARE, (GetAmountOwnedBy(c, _local_company) == 0) ||
/* Spectators cannot do anything of course */
_local_company == COMPANY_SPECTATOR);
} else { // Shares are not allowed, disable buy/sell buttons
this->DisableWidget(WID_C_BUY_SHARE);
this->DisableWidget(WID_C_SELL_SHARE);
if (gui_scope && data == 1) {
/* Manually call OnResize to adjust minimum height of president name widget. */
OnResize();
}
}
};
@ -2833,18 +2807,18 @@ struct BuyCompanyWindow : Window {
this->Window::Close();
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_BC_FACE:
*size = GetScaledSpriteSize(SPR_GRADIENT);
size = GetScaledSpriteSize(SPR_GRADIENT);
break;
case WID_BC_QUESTION:
const Company *c = Company::Get((CompanyID)this->window_number);
SetDParam(0, c->index);
SetDParam(1, this->company_value);
size->height = GetStringHeight(this->hostile_takeover ? STR_BUY_COMPANY_HOSTILE_TAKEOVER : STR_BUY_COMPANY_MESSAGE, size->width);
size.height = GetStringHeight(this->hostile_takeover ? STR_BUY_COMPANY_HOSTILE_TAKEOVER : STR_BUY_COMPANY_MESSAGE, size.width);
break;
}
}

@ -54,9 +54,9 @@ DECLARE_POSTFIX_INCREMENT(CompanyManagerFaceVariable)
/** Information about the valid values of CompanyManagerFace bitgroups as well as the sprites to draw */
struct CompanyManagerFaceBitsInfo {
byte offset; ///< Offset in bits into the CompanyManagerFace
byte length; ///< Number of bits used in the CompanyManagerFace
byte valid_values[GE_END]; ///< The number of valid values per gender/ethnicity
uint8_t offset; ///< Offset in bits into the CompanyManagerFace
uint8_t length; ///< Number of bits used in the CompanyManagerFace
uint8_t valid_values[GE_END]; ///< The number of valid values per gender/ethnicity
SpriteID first_sprite[GE_END]; ///< The first sprite per gender/ethnicity
};

@ -15,7 +15,7 @@
/**
* Enum for all companies/owners.
*/
enum Owner : byte {
enum Owner : uint8_t {
/* All companies below MAX_COMPANIES are playable
* companies, above, they are special, computer controlled 'companies' */
OWNER_BEGIN = 0x00, ///< First owner
@ -47,7 +47,7 @@ static const uint MIN_COMPETITORS_INTERVAL = 0; ///< The minimum interval (in
static const uint MAX_COMPETITORS_INTERVAL = 500; ///< The maximum interval (in minutes) between competitors.
/** Define basic enum properties */
template <> struct EnumPropsT<Owner> : MakeEnumPropsT<Owner, byte, OWNER_BEGIN, OWNER_END, INVALID_OWNER> {};
template <> struct EnumPropsT<Owner> : MakeEnumPropsT<Owner, uint8_t, OWNER_BEGIN, OWNER_END, INVALID_OWNER> {};
typedef Owner CompanyID;
@ -71,6 +71,7 @@ enum CompanyCtrlAction {
CCA_NEW_AI, ///< Create a new AI company.
CCA_DELETE, ///< Delete a company.
CCA_SALE, ///< Offer a company for sale.
CCA_MERGE, ///< Merge companies.
CCA_END, ///< Sentinel for end.
};

@ -13,6 +13,7 @@
#include "network/network_func.h"
#include "network/network_admin.h"
#include "debug.h"
#include "debug_fmt.h"
#include "console_func.h"
#include "settings_type.h"
@ -49,18 +50,16 @@ void IConsoleInit()
IConsoleStdLibRegister();
}
static void IConsoleWriteToLogFile(const char *string)
static void IConsoleWriteToLogFile(const std::string &string)
{
if (_iconsole_output_file != nullptr) {
/* if there is an console output file ... also print it there */
log_prefix prefix_writer;
const char *header = prefix_writer.GetLogPrefix();
if ((strlen(header) != 0 && fwrite(header, strlen(header), 1, _iconsole_output_file) != 1) ||
fwrite(string, strlen(string), 1, _iconsole_output_file) != 1 ||
fwrite("\n", 1, 1, _iconsole_output_file) != 1) {
try {
fmt::print(_iconsole_output_file, "{}{}\n", log_prefix().GetLogPrefix(), string);
} catch (const std::system_error &) {
fclose(_iconsole_output_file);
_iconsole_output_file = nullptr;
IConsolePrintF(CC_DEFAULT, "cannot write to log file");
IConsolePrint(CC_ERROR, "Cannot write to console log file; closing the log file.");
}
}
}
@ -68,7 +67,7 @@ static void IConsoleWriteToLogFile(const char *string)
bool CloseConsoleLogIfActive()
{
if (_iconsole_output_file != nullptr) {
IConsolePrintF(CC_DEFAULT, "file output complete");
IConsolePrint(CC_INFO, "Console log file closed.");
fclose(_iconsole_output_file);
_iconsole_output_file = nullptr;
return true;
@ -89,10 +88,10 @@ void IConsoleFree()
* as well as to a logfile. If the network server is a dedicated server, all activities
* are also logged. All lines to print are added to a temporary buffer which can be
* used as a history to print them onscreen
* @param colour_code the colour of the command. Red in case of errors, etc.
* @param string the message entered or output on the console (notice, error, etc.)
* @param colour_code The colour of the command.
* @param string The message to output on the console (notice, error, etc.)
*/
void IConsolePrint(TextColour colour_code, const char *string)
void IConsolePrint(TextColour colour_code, const std::string &string)
{
assert(IsValidConsoleColour(colour_code));
@ -113,13 +112,13 @@ void IConsolePrint(TextColour colour_code, const char *string)
if (_network_dedicated) {
NetworkAdminConsole("console", str);
fprintf(stdout, "%s%s\n", log_prefix().GetLogPrefix(), str.c_str());
fmt::print("{}{}\n", log_prefix().GetLogPrefix(), str);
fflush(stdout);
IConsoleWriteToLogFile(str.c_str());
IConsoleWriteToLogFile(str);
return;
}
IConsoleWriteToLogFile(str.c_str());
IConsoleWriteToLogFile(str);
IConsoleGUIPrint(colour_code, std::move(str));
}
@ -133,35 +132,14 @@ void CDECL IConsolePrintF(TextColour colour_code, const char *format, ...)
assert(IsValidConsoleColour(colour_code));
va_list va;
char buf[ICON_MAX_STREAMSIZE];
va_start(va, format);
vseprintf(buf, lastof(buf), format, va);
std::string buf = stdstr_vfmt(format, va);
va_end(va);
IConsolePrint(colour_code, buf);
}
/**
* It is possible to print warnings to the console. These are mostly
* errors or mishaps, but non-fatal. You need at least a level 1 (developer) for
* debugging messages to show up
*/
void IConsoleWarning(const char *string)
{
if (_settings_client.gui.developer == 0) return;
IConsolePrintF(CC_WARNING, "WARNING: %s", string);
}
/**
* It is possible to print error information to the console. This can include
* game errors, or errors in general you would want the user to notice
*/
void IConsoleError(const char *string)
{
IConsolePrintF(CC_ERROR, "ERROR: %s", string);
}
/**
* Change a string into its number representation. Supports
* decimal and hexadecimal numbers as well as 'on'/'off' 'true'/'false'
@ -227,7 +205,7 @@ std::string RemoveUnderscores(std::string name)
/* static */ void IConsole::AliasRegister(const std::string &name, const std::string &cmd)
{
auto result = IConsole::Aliases().try_emplace(RemoveUnderscores(name), name, cmd);
if (!result.second) IConsoleError("an alias with this name already exists; insertion aborted");
if (!result.second) IConsolePrint(CC_ERROR, "An alias with the name '{}' already exists.", name);
}
/**
@ -249,14 +227,14 @@ std::string RemoveUnderscores(std::string name)
* @param tokencount the number of parameters passed
* @param *tokens are the parameters given to the original command (0 is the first param)
*/
static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[ICON_TOKEN_COUNT], const uint recurse_count)
static void IConsoleAliasExec(const IConsoleAlias *alias, uint8_t tokencount, char *tokens[ICON_TOKEN_COUNT], const uint recurse_count)
{
std::string alias_buffer;
DEBUG(console, 6, "Requested command is an alias; parsing...");
Debug(console, 6, "Requested command is an alias; parsing...");
if (recurse_count > ICON_MAX_RECURSE) {
IConsoleError("Too many alias expansions, recursion limit reached. Aborting");
IConsolePrint(CC_ERROR, "Too many alias expansions, recursion limit reached.");
return;
}
@ -301,8 +279,8 @@ static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char
int param = *cmdptr - 'A';
if (param < 0 || param >= tokencount) {
IConsoleError("too many or wrong amount of parameters passed to alias, aborting");
IConsolePrintF(CC_WARNING, "Usage of alias '%s': %s", alias->name.c_str(), alias->cmdline.c_str());
IConsolePrint(CC_ERROR, "Too many or wrong amount of parameters passed to alias.");
IConsolePrint(CC_HELP, "Usage of alias '{}': '{}'.", alias->name, alias->cmdline);
return;
}
@ -320,7 +298,7 @@ static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char
}
if (alias_buffer.size() >= ICON_MAX_STREAMSIZE - 1) {
IConsoleError("Requested alias execution would overflow execution buffer");
IConsolePrint(CC_ERROR, "Requested alias execution would overflow execution buffer.");
return;
}
}
@ -346,12 +324,12 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
for (cmdptr = command_string.c_str(); *cmdptr != '\0'; cmdptr++) {
if (!IsValidChar(*cmdptr, CS_ALPHANUMERAL)) {
IConsolePrintF(CC_ERROR, "Command '%s' contains malformed characters.", command_string.c_str());
IConsolePrint(CC_ERROR, "Command '{}' contains malformed characters.", command_string);
return;
}
}
DEBUG(console, 4, "Executing cmdline: '%s'", command_string.c_str());
Debug(console, 4, "Executing cmdline: '{}'", command_string);
memset(&tokens, 0, sizeof(tokens));
memset(&tokenstream, 0, sizeof(tokenstream));
@ -361,7 +339,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
* of characters in our stream or the max amount of tokens we can handle */
for (cmdptr = command_string.c_str(), t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) {
if (tstream_i >= lengthof(tokenstream)) {
IConsoleError("command line too long");
IConsolePrint(CC_ERROR, "Command line too long.");
return;
}
@ -382,7 +360,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
longtoken = !longtoken;
if (!foundtoken) {
if (t_index >= lengthof(tokens)) {
IConsoleError("command line too long");
IConsolePrint(CC_ERROR, "Command line too long.");
return;
}
tokens[t_index++] = &tokenstream[tstream_i];
@ -400,7 +378,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
if (!foundtoken) {
if (t_index >= lengthof(tokens)) {
IConsoleError("command line too long");
IConsolePrint(CC_ERROR, "Command line too long.");
return;
}
tokens[t_index++] = &tokenstream[tstream_i - 1];
@ -411,7 +389,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
}
for (uint i = 0; i < lengthof(tokens) && tokens[i] != nullptr; i++) {
DEBUG(console, 8, "Token %d is: '%s'", i, tokens[i]);
Debug(console, 8, "Token {} is: '{}'", i, tokens[i]);
}
IConsoleCmdExecTokens(t_index, tokens, recurse_count);
@ -450,5 +428,5 @@ void IConsoleCmdExecTokens(uint token_count, char *tokens[], const uint recurse_
return;
}
IConsoleError("command not found");
IConsolePrint(CC_ERROR, "Command '{}' not found.", tokens[0]);
}

File diff suppressed because it is too large Load Diff

@ -11,6 +11,7 @@
#define CONSOLE_FUNC_H
#include "console_type.h"
#include "core/format.hpp"
/* console modes */
extern IConsoleModes _iconsole_mode;
@ -21,10 +22,30 @@ void IConsoleFree();
void IConsoleClose();
/* console output */
void IConsolePrint(TextColour colour_code, const char *string);
void IConsolePrint(TextColour colour_code, const std::string &string);
/**
* Handle the printing of text entered into the console or redirected there
* by any other means. Text can be redirected to other clients in a network game
* as well as to a logfile. If the network server is a dedicated server, all activities
* are also logged. All lines to print are added to a temporary buffer which can be
* used as a history to print them onscreen
* @param colour_code The colour of the command.
* @param format_string The formatting string to tell what to do with the remaining arguments.
* @param first_arg The first argument to the format.
* @param other_args The other arguments to the format.
* @tparam A The type of the first argument.
* @tparam Args The types of the other arguments.
*/
template <typename A, typename ... Args>
inline void IConsolePrint(TextColour colour_code, fmt::format_string<A, Args...> format, A first_arg, Args&&... other_args)
{
/* The separate first_arg argument is added to aid overloading.
* Otherwise the calls that do no need formatting will still use this function. */
IConsolePrint(colour_code, fmt::format(format, std::forward<A>(first_arg), std::forward<Args>(other_args)...));
}
void CDECL IConsolePrintF(TextColour colour_code, const char *format, ...) WARN_FORMAT(2, 3);
void IConsoleWarning(const char *string);
void IConsoleError(const char *string);
/* Parser */
void IConsoleCmdExec(const std::string &command_string, const uint recurse_count = 0);

@ -31,7 +31,7 @@ enum ConsoleHookResult {
* If you want to handle multiple words as one, enclose them in double-quotes
* eg. 'say "hello everybody"'
*/
typedef bool IConsoleCmdProc(byte argc, char *argv[]);
typedef bool IConsoleCmdProc(uint8_t argc, char *argv[]);
typedef ConsoleHookResult IConsoleHook(bool echo);
struct IConsoleCmd {
IConsoleCmd(const std::string &name, IConsoleCmdProc *proc, IConsoleHook *hook, bool unlisted) : name(name), proc(proc), hook(hook), unlisted(unlisted) {}

@ -23,6 +23,7 @@ enum IConsoleModes {
static const TextColour CC_DEFAULT = TC_SILVER; ///< Default colour of the console.
static const TextColour CC_ERROR = TC_RED; ///< Colour for error lines.
static const TextColour CC_WARNING = TC_LIGHT_BLUE; ///< Colour for warning lines.
static const TextColour CC_HELP = TC_LIGHT_BLUE; ///< Colour for help lines.
static const TextColour CC_INFO = TC_YELLOW; ///< Colour for information lines.
static const TextColour CC_DEBUG = TC_LIGHT_BROWN; ///< Colour for debug output.
static const TextColour CC_COMMAND = TC_GOLD; ///< Colour for the console's commands.

@ -94,14 +94,14 @@ public:
* @param size the amount of bytes to allocate.
* @return the given amounts of bytes zeroed.
*/
inline void *operator new(size_t size) { return CallocT<byte>(size); }
inline void *operator new(size_t size) { return CallocT<uint8_t>(size); }
/**
* Memory allocator for an array of class instances.
* @param size the amount of bytes to allocate.
* @return the given amounts of bytes zeroed.
*/
inline void *operator new[](size_t size) { return CallocT<byte>(size); }
inline void *operator new[](size_t size) { return CallocT<uint8_t>(size); }
/**
* Memory release for a single class instance.

@ -49,7 +49,7 @@ inline bool ShouldLogUpdateStateChecksum()
return _networking && (!_network_server || (NetworkClientSocket::IsValidID(0) && NetworkClientSocket::Get(0)->status != NetworkClientSocket::STATUS_INACTIVE));
}
# define DEBUG_UPDATESTATECHECKSUM(str, ...) if (ShouldLogUpdateStateChecksum()) DEBUG(statecsum, 0, "%s; %04x; %02x; " OTTD_PRINTFHEX64PAD "; %s:%d " str, \
debug_date_dumper().HexDate(), _frame_counter, (byte)_current_company, _state_checksum.state, __FILE__, __LINE__, __VA_ARGS__);
debug_date_dumper().HexDate(), _frame_counter, (uint8_t)_current_company, _state_checksum.state, __FILE__, __LINE__, __VA_ARGS__);
#else
# define DEBUG_UPDATESTATECHECKSUM(str, ...)
#endif /* RANDOM_DEBUG */

@ -49,7 +49,7 @@
* other templates below. Here we have only forward declaration. For each enum type
* we will create specialization derived from MakeEnumPropsT<>.
* i.e.:
* template <> struct EnumPropsT<Track> : MakeEnumPropsT<Track, byte, TRACK_BEGIN, TRACK_END, INVALID_TRACK> {};
* template <> struct EnumPropsT<Track> : MakeEnumPropsT<Track, uint8_t, TRACK_BEGIN, TRACK_END, INVALID_TRACK> {};
*/
template <typename Tenum_t> struct EnumPropsT;
@ -58,7 +58,7 @@ template <typename Tenum_t> struct EnumPropsT;
* from outsize. It is used as base class of several EnumPropsT specializations each
* dedicated to one of commonly used enumeration types.
* @param Tenum_t enumeration type that you want to describe
* @param Tstorage_t what storage type would be sufficient (i.e. byte)
* @param Tstorage_t what storage type would be sufficient (i.e. uint8_t)
* @param Tbegin first valid value from the contiguous range (i.e. TRACK_BEGIN)
* @param Tend one past the last valid value from the contiguous range (i.e. TRACK_END)
* @param Tinvalid value used as invalid value marker (i.e. INVALID_TRACK)
@ -67,7 +67,7 @@ template <typename Tenum_t> struct EnumPropsT;
template <typename Tenum_t, typename Tstorage_t, Tenum_t Tbegin, Tenum_t Tend, Tenum_t Tinvalid, uint Tnum_bits = 8 * sizeof(Tstorage_t)>
struct MakeEnumPropsT {
typedef Tenum_t type; ///< enum type (i.e. Trackdir)
typedef Tstorage_t storage; ///< storage type (i.e. byte)
typedef Tstorage_t storage; ///< storage type (i.e. uint8_t)
static const Tenum_t begin = Tbegin; ///< lowest valid value (i.e. TRACKDIR_BEGIN)
static const Tenum_t end = Tend; ///< one after the last valid value (i.e. TRACKDIR_END)
static const Tenum_t invalid = Tinvalid; ///< what value is used as invalid value (i.e. INVALID_TRACKDIR)

@ -25,7 +25,7 @@
template <typename T>
constexpr T abs(const T a)
{
return (a < (T)0) ? -a : a;
return (a < static_cast<T>(0)) ? -a : a;
}
/**
@ -41,7 +41,7 @@ constexpr T Align(const T x, uint n)
{
assert((n & (n - 1)) == 0 && n != 0);
n--;
return (T)((x + n) & ~((T)n));
return static_cast<T>((x + n) & ~static_cast<T>(n));
}
/**
@ -57,8 +57,8 @@ constexpr T Align(const T x, uint n)
template <typename T>
constexpr T *AlignPtr(T *x, uint n)
{
static_assert(sizeof(size_t) == sizeof(void *));
return reinterpret_cast<T *>(Align((size_t)x, n));
static_assert(sizeof(uintptr_t) == sizeof(void *));
return reinterpret_cast<T *>(Align(reinterpret_cast<uintptr_t>(x), n));
}
/**
@ -254,7 +254,7 @@ constexpr T Delta(const T a, const T b)
template <typename T>
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
{
return (size_t)(x - base) < size;
return static_cast<size_t>(x - base) < size;
}
/**
@ -271,9 +271,9 @@ template <typename T, std::enable_if_t<std::disjunction_v<std::is_convertible<T,
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
{
if constexpr (std::is_base_of_v<StrongTypedefBase, T>) {
return (size_t)(x.base() - min) < (max - min);
return static_cast<size_t>(x.base() - min) < (max - min);
} else {
return (size_t)(x - min) < (max - min);
return static_cast<size_t>(x - min) < (max - min);
}
}

@ -46,7 +46,7 @@ inline void MemMoveT(T *destination, const T *source, size_t num = 1)
* @param num number of items to be set (!not number of bytes!)
*/
template <typename T>
inline void MemSetT(T *ptr, byte value, size_t num = 1)
inline void MemSetT(T *ptr, uint8_t value, size_t num = 1)
{
memset(ptr, value, num * sizeof(T));
}

@ -138,7 +138,7 @@ public:
inline constexpr OverflowSafeInt operator * (const int factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
inline constexpr OverflowSafeInt operator * (const uint factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
inline constexpr OverflowSafeInt operator * (const uint16_t factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
inline constexpr OverflowSafeInt operator * (const byte factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
inline constexpr OverflowSafeInt operator * (const uint8_t factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
/* Operators for division. */
inline constexpr OverflowSafeInt& operator /= (const int64_t divisor) { this->m_value /= divisor; return *this; }
@ -197,11 +197,11 @@ template <class T> inline constexpr OverflowSafeInt<T> operator - (const uint a
template <class T> inline constexpr OverflowSafeInt<T> operator * (const uint a, const OverflowSafeInt<T> b) { return b * a; }
template <class T> inline constexpr OverflowSafeInt<T> operator / (const uint a, const OverflowSafeInt<T> b) { return (OverflowSafeInt<T>)a / (int)b; }
/* Sometimes we got byte operator OverflowSafeInt instead of vice versa. Handle that properly. */
template <class T> inline constexpr OverflowSafeInt<T> operator + (const byte a, const OverflowSafeInt<T> b) { return b + (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator - (const byte a, const OverflowSafeInt<T> b) { return -b + (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator * (const byte a, const OverflowSafeInt<T> b) { return b * (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator / (const byte a, const OverflowSafeInt<T> b) { return (OverflowSafeInt<T>)a / (int)b; }
/* Sometimes we got uint8_t operator OverflowSafeInt instead of vice versa. Handle that properly. */
template <class T> inline constexpr OverflowSafeInt<T> operator + (const uint8_t a, const OverflowSafeInt<T> b) { return b + (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator - (const uint8_t a, const OverflowSafeInt<T> b) { return -b + (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator * (const uint8_t a, const OverflowSafeInt<T> b) { return b * (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator / (const uint8_t a, const OverflowSafeInt<T> b) { return (OverflowSafeInt<T>)a / (int)b; }
typedef OverflowSafeInt<int64_t> OverflowSafeInt64;
typedef OverflowSafeInt<int32_t> OverflowSafeInt32;

@ -125,9 +125,9 @@ DEFINE_POOL_METHOD(inline void *)::AllocateItem(size_t size, size_t index, Pool:
memset((void *)item, 0, sizeof(Titem));
}
} else if (Tzero) {
item = (Titem *)CallocT<byte>(size);
item = (Titem *)CallocT<uint8_t>(size);
} else {
item = (Titem *)MallocT<byte>(size);
item = (Titem *)MallocT<uint8_t>(size);
}
this->data[index] = Tops::PutPtr(item, param);
SetBit(this->free_bitmap[index / 64], index % 64);

@ -87,7 +87,7 @@ void SetRandomSeed(uint32_t seed)
uint32_t DoRandom(int line, const char *file)
{
if (_networking && (!_network_server || (NetworkClientSocket::IsValidID(0) && NetworkClientSocket::Get(0)->status != NetworkClientSocket::STATUS_INACTIVE))) {
DEBUG(random, 0, "%s; %04x; %02x; %s:%d", debug_date_dumper().HexDate(), _frame_counter, (byte)_current_company, file, line);
DEBUG(random, 0, "%s; %04x; %02x; %s:%d", debug_date_dumper().HexDate(), _frame_counter, (uint8_t)_current_company, file, line);
}
return _random.Next();

@ -25,7 +25,7 @@
template <class T>
class ring_buffer
{
std::unique_ptr<byte, FreeDeleter> data;
std::unique_ptr<uint8_t, FreeDeleter> data;
uint32_t head = 0;
uint32_t count = 0;
uint32_t mask = (uint32_t)-1;
@ -219,11 +219,11 @@ public:
void construct_from(const U &other)
{
uint32_t cap = round_up_size((uint32_t)other.size());
this->data.reset(MallocT<byte>(cap * sizeof(T)));
this->data.reset(MallocT<uint8_t>(cap * sizeof(T)));
this->mask = cap - 1;
this->head = 0;
this->count = (uint32_t)other.size();
byte *ptr = this->data.get();
uint8_t *ptr = this->data.get();
for (const T &item : other) {
new (ptr) T(item);
ptr += sizeof(T);
@ -259,12 +259,12 @@ public:
if (!other.empty()) {
if (other.size() > this->capacity()) {
uint32_t cap = round_up_size(other.count);
this->data.reset(MallocT<byte>(cap * sizeof(T)));
this->data.reset(MallocT<uint8_t>(cap * sizeof(T)));
this->mask = cap - 1;
}
this->head = 0;
this->count = other.count;
byte *ptr = this->data.get();
uint8_t *ptr = this->data.get();
for (const T &item : other) {
new (ptr) T(item);
ptr += sizeof(T);
@ -341,8 +341,8 @@ private:
void reallocate(uint32_t new_cap)
{
const uint32_t cap = round_up_size(new_cap);
byte *new_buf = MallocT<byte>(cap * sizeof(T));
byte *pos = new_buf;
uint8_t *new_buf = MallocT<uint8_t>(cap * sizeof(T));
uint8_t *pos = new_buf;
for (T &item : *this) {
new (pos) T(std::move(item));
item.~T();
@ -522,8 +522,8 @@ private:
if (this->count + num > (uint32_t)this->capacity()) {
/* grow container */
const uint32_t cap = round_up_size(this->count + num);
byte *new_buf = MallocT<byte>(cap * sizeof(T));
byte *write_to = new_buf;
uint8_t *new_buf = MallocT<uint8_t>(cap * sizeof(T));
uint8_t *write_to = new_buf;
const uint32_t end = this->head + this->count;
for (uint32_t idx = this->head; idx != end; idx++) {
if (idx == pos) {

@ -16,7 +16,7 @@
* @param bytes_to_write The amount of bytes we want to try to write.
* @return True iff the given amount of bytes can be written to the packet.
*/
[[maybe_unused]] static bool BufferCanWriteToPacket(const std::vector<byte> &buffer, size_t limit, size_t bytes_to_write)
[[maybe_unused]] static bool BufferCanWriteToPacket(const std::vector<uint8_t> &buffer, size_t limit, size_t bytes_to_write)
{
return buffer.size() + bytes_to_write <= limit;
}
@ -37,7 +37,7 @@
* Package a boolean in the packet.
* @param data The data to send.
*/
void BufferSend_bool(std::vector<byte> &buffer, size_t limit, bool data)
void BufferSend_bool(std::vector<uint8_t> &buffer, size_t limit, bool data)
{
BufferSend_uint8(buffer, limit, data ? 1 : 0);
}
@ -46,7 +46,7 @@ void BufferSend_bool(std::vector<byte> &buffer, size_t limit, bool data)
* Package a 8 bits integer in the packet.
* @param data The data to send.
*/
void BufferSend_uint8(std::vector<byte> &buffer, size_t limit, uint8_t data)
void BufferSend_uint8(std::vector<uint8_t> &buffer, size_t limit, uint8_t data)
{
assert(BufferCanWriteToPacket(buffer, limit, sizeof(data)));
buffer.emplace_back(data);
@ -56,7 +56,7 @@ void BufferSend_uint8(std::vector<byte> &buffer, size_t limit, uint8_t data)
* Package a 16 bits integer in the packet.
* @param data The data to send.
*/
void BufferSend_uint16(std::vector<byte> &buffer, size_t limit, uint16_t data)
void BufferSend_uint16(std::vector<uint8_t> &buffer, size_t limit, uint16_t data)
{
assert(BufferCanWriteToPacket(buffer, limit, sizeof(data)));
buffer.insert(buffer.end(), {
@ -69,7 +69,7 @@ void BufferSend_uint16(std::vector<byte> &buffer, size_t limit, uint16_t data)
* Package a 32 bits integer in the packet.
* @param data The data to send.
*/
void BufferSend_uint32(std::vector<byte> &buffer, size_t limit, uint32_t data)
void BufferSend_uint32(std::vector<uint8_t> &buffer, size_t limit, uint32_t data)
{
assert(BufferCanWriteToPacket(buffer, limit, sizeof(data)));
buffer.insert(buffer.end(), {
@ -84,7 +84,7 @@ void BufferSend_uint32(std::vector<byte> &buffer, size_t limit, uint32_t data)
* Package a 64 bits integer in the packet.
* @param data The data to send.
*/
void BufferSend_uint64(std::vector<byte> &buffer, size_t limit, uint64_t data)
void BufferSend_uint64(std::vector<uint8_t> &buffer, size_t limit, uint64_t data)
{
assert(BufferCanWriteToPacket(buffer, limit, sizeof(data)));
buffer.insert(buffer.end(), {
@ -104,7 +104,7 @@ void BufferSend_uint64(std::vector<byte> &buffer, size_t limit, uint64_t data)
* the string + '\0'. No size-byte or something.
* @param data The string to send
*/
void BufferSend_string(std::vector<byte> &buffer, size_t limit, const std::string_view data)
void BufferSend_string(std::vector<uint8_t> &buffer, size_t limit, const std::string_view data)
{
assert(BufferCanWriteToPacket(buffer, limit, data.size() + 1));
buffer.insert(buffer.end(), data.begin(), data.end());
@ -119,7 +119,7 @@ void BufferSend_string(std::vector<byte> &buffer, size_t limit, const std::strin
* @param end The end of the buffer to send.
* @return The number of bytes that were added to this packet.
*/
size_t BufferSend_binary_until_full(std::vector<byte> &buffer, size_t limit, const byte *begin, const byte *end)
size_t BufferSend_binary_until_full(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *begin, const uint8_t *end)
{
size_t amount = std::min<size_t>(end - begin, limit - buffer.size());
buffer.insert(buffer.end(), begin, begin + amount);
@ -130,7 +130,7 @@ size_t BufferSend_binary_until_full(std::vector<byte> &buffer, size_t limit, con
* Sends a binary data over the network.
* @param data The data to send
*/
void BufferSend_binary(std::vector<byte> &buffer, size_t limit, const byte *data, const size_t size)
void BufferSend_binary(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *data, const size_t size)
{
assert(data != nullptr);
assert(BufferCanWriteToPacket(buffer, limit, size));
@ -142,7 +142,7 @@ void BufferSend_binary(std::vector<byte> &buffer, size_t limit, const byte *data
* The data is length prefixed with a uint16.
* @param data The string to send
*/
void BufferSend_buffer(std::vector<byte> &buffer, size_t limit, const byte *data, const size_t size)
void BufferSend_buffer(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *data, const size_t size)
{
assert(size <= UINT16_MAX);
assert(BufferCanWriteToPacket(buffer, limit, size + 2));

@ -18,15 +18,15 @@
#include <string>
#include <limits>
void BufferSend_bool (std::vector<byte> &buffer, size_t limit, bool data);
void BufferSend_uint8 (std::vector<byte> &buffer, size_t limit, uint8_t data);
void BufferSend_uint16(std::vector<byte> &buffer, size_t limit, uint16_t data);
void BufferSend_uint32(std::vector<byte> &buffer, size_t limit, uint32_t data);
void BufferSend_uint64(std::vector<byte> &buffer, size_t limit, uint64_t data);
void BufferSend_string(std::vector<byte> &buffer, size_t limit, const std::string_view data);
size_t BufferSend_binary_until_full(std::vector<byte> &buffer, size_t limit, const byte *begin, const byte *end);
void BufferSend_binary(std::vector<byte> &buffer, size_t limit, const byte *data, const size_t size);
void BufferSend_buffer(std::vector<byte> &buffer, size_t limit, const byte *data, const size_t size);
void BufferSend_bool (std::vector<uint8_t> &buffer, size_t limit, bool data);
void BufferSend_uint8 (std::vector<uint8_t> &buffer, size_t limit, uint8_t data);
void BufferSend_uint16(std::vector<uint8_t> &buffer, size_t limit, uint16_t data);
void BufferSend_uint32(std::vector<uint8_t> &buffer, size_t limit, uint32_t data);
void BufferSend_uint64(std::vector<uint8_t> &buffer, size_t limit, uint64_t data);
void BufferSend_string(std::vector<uint8_t> &buffer, size_t limit, const std::string_view data);
size_t BufferSend_binary_until_full(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *begin, const uint8_t *end);
void BufferSend_binary(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *data, const size_t size);
void BufferSend_buffer(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *data, const size_t size);
template <typename T>
struct BufferSerialisationHelper {
@ -66,30 +66,30 @@ struct BufferSerialisationHelper {
BufferSend_string(self->GetSerialisationBuffer(), self->GetSerialisationLimit(), data);
}
size_t Send_binary_until_full(const byte *begin, const byte *end)
size_t Send_binary_until_full(const uint8_t *begin, const uint8_t *end)
{
T *self = static_cast<T *>(this);
return BufferSend_binary_until_full(self->GetSerialisationBuffer(), self->GetSerialisationLimit(), begin, end);
}
void Send_binary(const byte *data, const size_t size)
void Send_binary(const uint8_t *data, const size_t size)
{
T *self = static_cast<T *>(this);
BufferSend_binary(self->GetSerialisationBuffer(), self->GetSerialisationLimit(), data, size);
}
void Send_binary(std::span<const byte> data)
void Send_binary(std::span<const uint8_t> data)
{
this->Send_binary(data.data(), data.size());
}
void Send_buffer(const byte *data, const size_t size)
void Send_buffer(const uint8_t *data, const size_t size)
{
T *self = static_cast<T *>(this);
BufferSend_buffer(self->GetSerialisationBuffer(), self->GetSerialisationLimit(), data, size);
}
void Send_buffer(const std::vector<byte> &data)
void Send_buffer(const std::vector<uint8_t> &data)
{
this->Send_buffer(data.data(), data.size());
}
@ -100,7 +100,7 @@ void BufferRecvStringValidate(std::string &buffer, StringValidationSettings sett
template <typename T>
struct BufferDeserialisationHelper {
private:
const byte *GetBuffer()
const uint8_t *GetBuffer()
{
return static_cast<T *>(this)->GetDeserialisationBuffer();
}
@ -253,7 +253,7 @@ public:
* @param buffer The buffer to put the data into.
* @param size The size of the data.
*/
void Recv_binary(byte *buffer, size_t size)
void Recv_binary(uint8_t *buffer, size_t size)
{
if (!this->CanRecvBytes(size, true)) return;
@ -267,7 +267,7 @@ public:
* Reads binary data.
* @param buffer The buffer to put the data into.
*/
void Recv_binary(std::span<byte> buffer)
void Recv_binary(std::span<uint8_t> buffer)
{
this->Recv_binary(buffer.data(), buffer.size());
}
@ -331,11 +331,11 @@ public:
};
struct BufferSerialiser : public BufferSerialisationHelper<BufferSerialiser> {
std::vector<byte> &buffer;
std::vector<uint8_t> &buffer;
BufferSerialiser(std::vector<byte> &buffer) : buffer(buffer) {}
BufferSerialiser(std::vector<uint8_t> &buffer) : buffer(buffer) {}
std::vector<byte> &GetSerialisationBuffer() { return this->buffer; }
std::vector<uint8_t> &GetSerialisationBuffer() { return this->buffer; }
size_t GetSerialisationLimit() const { return std::numeric_limits<size_t>::max(); }
};

@ -498,19 +498,17 @@ char *CrashLog::LogGamelog(char *buffer, const char *last) const
*/
char *CrashLog::LogRecentNews(char *buffer, const char *last) const
{
uint total = 0;
for (NewsItem *news = _latest_news; news != nullptr; news = news->prev) {
total++;
}
uint total = static_cast<uint>(GetNews().size());
uint show = std::min<uint>(total, 32);
buffer += seprintf(buffer, last, "Recent news messages (%u of %u):\n", show, total);
int i = 0;
for (NewsItem *news = _latest_news; i < 32 && news != nullptr; news = news->prev, i++) {
CalTime::YearMonthDay ymd = CalTime::ConvertDateToYMD(news->date);
for (const auto &news : GetNews()) {
CalTime::YearMonthDay ymd = CalTime::ConvertDateToYMD(news.date);
buffer += seprintf(buffer, last, "(%i-%02i-%02i) StringID: %u, Type: %u, Ref1: %u, %u, Ref2: %u, %u\n",
ymd.year.base(), ymd.month + 1, ymd.day, news->string_id, news->type,
news->reftype1, news->ref1, news->reftype2, news->ref2);
ymd.year.base(), ymd.month + 1, ymd.day, news.string_id, news.type,
news.reftype1, news.ref1, news.reftype2, news.ref2);
if (++i > 32) break;
}
buffer += seprintf(buffer, last, "\n");
return buffer;

@ -25,7 +25,7 @@
* | | Euro year | | | | name
* | | | | | | | | */
/** The original currency specifications. */
static const CurrencySpec origin_currency_specs[CURRENCY_END] = {
static const std::array<CurrencySpec, CURRENCY_END> origin_currency_specs = {{
{ 1, "", CF_NOEURO, "\u00a3", "", "GBP", 0, STR_GAME_OPTIONS_CURRENCY_GBP }, ///< british pound
{ 2, "", CF_NOEURO, "$", "", "USD", 0, STR_GAME_OPTIONS_CURRENCY_USD }, ///< american dollar
{ 2, "", CF_ISEURO, "\u20ac", "", "EUR", 0, STR_GAME_OPTIONS_CURRENCY_EUR }, ///< euro
@ -70,10 +70,10 @@ static const CurrencySpec origin_currency_specs[CURRENCY_END] = {
{ 5, "", CF_NOEURO, "RM", "", "MYR", 0, STR_GAME_OPTIONS_CURRENCY_MYR }, ///< Malaysian Ringgit
{ 1, "", 2014, "", NBSP "Ls", "LVL", 1, STR_GAME_OPTIONS_CURRENCY_LVL }, ///< latvian lats
{ 400, "", 2002, "", "$00", "PTE", 1, STR_GAME_OPTIONS_CURRENCY_PTE }, ///< portuguese escudo
};
}};
/** Array of currencies used by the system */
CurrencySpec _currency_specs[CURRENCY_END];
std::array<CurrencySpec, CURRENCY_END> _currency_specs;
/**
* This array represent the position of OpenTTD's currencies,
@ -81,7 +81,7 @@ CurrencySpec _currency_specs[CURRENCY_END];
* When a grf sends currencies, they are based on the order defined by TTDPatch.
* So, we must reindex them to our own order.
*/
const byte TTDPatch_To_OTTDIndex[] =
const uint8_t TTDPatch_To_OTTDIndex[] =
{
CURRENCY_GBP,
CURRENCY_USD,
@ -112,7 +112,7 @@ const byte TTDPatch_To_OTTDIndex[] =
* @param grfcurr_id currency id coming from newgrf
* @return the corrected index
*/
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id)
uint8_t GetNewgrfCurrencyIdConverted(uint8_t grfcurr_id)
{
return (grfcurr_id >= lengthof(TTDPatch_To_OTTDIndex)) ? grfcurr_id : TTDPatch_To_OTTDIndex[grfcurr_id];
}

@ -11,8 +11,9 @@
#define CURRENCY_H
#include "date_type.h"
#include "string_func.h"
#include "settings_type.h"
#include "strings_type.h"
#include <array>
static const int CF_NOEURO = 0; ///< Currency never switches to the Euro (as far as known).
static const int CF_ISEURO = 1; ///< Currency _is_ the Euro.
@ -87,26 +88,40 @@ struct CurrencySpec {
* It is not a spec from Newgrf,
* rather a way to let users do what they want with custom currency
*/
byte symbol_pos;
uint8_t symbol_pos;
StringID name;
CurrencySpec() = default;
CurrencySpec(uint16_t rate, const char *separator, CalTime::Year to_euro, const char *prefix, const char *suffix, const char *code, byte symbol_pos, StringID name) :
CurrencySpec(uint16_t rate, const char *separator, CalTime::Year to_euro, const char *prefix, const char *suffix, const char *code, uint8_t symbol_pos, StringID name) :
rate(rate), separator(separator), to_euro(to_euro), prefix(prefix), suffix(suffix), code(code), symbol_pos(symbol_pos), name(name)
{
}
};
extern CurrencySpec _currency_specs[CURRENCY_END];
extern std::array<CurrencySpec, CURRENCY_END> _currency_specs;
/* XXX small hack, but makes the rest of the code a bit nicer to read */
#define _custom_currency (_currency_specs[CURRENCY_CUSTOM])
#define _currency ((const CurrencySpec*)&_currency_specs[GetGameSettings().locale.currency])
/**
* Get the custom currency.
* @return Reference to custom currency.
*/
inline CurrencySpec &GetCustomCurrency()
{
return _currency_specs[CURRENCY_CUSTOM];
}
/**
* Get the currently selected currency.
* @return Read-only reference to the current currency.
*/
inline const CurrencySpec &GetCurrency()
{
return _currency_specs[GetGameSettings().locale.currency];
}
uint64_t GetMaskOfAllowedCurrencies();
void CheckSwitchToEuro();
void ResetCurrencies(bool preserve_custom = true);
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id);
uint8_t GetNewgrfCurrencyIdConverted(uint8_t grfcurr_id);
#endif /* CURRENCY_H */

@ -436,6 +436,8 @@ static void OnNewEconomyMonth()
*/
static void OnNewCalendarDay()
{
EnginesDailyLoop();
if (!_settings_time.time_in_minutes || _settings_client.gui.date_with_time > 0) {
SetWindowWidgetDirty(WC_STATUS_BAR, 0, WID_S_LEFT);
}
@ -455,7 +457,6 @@ static void OnNewEconomyDay()
IndustryDailyLoop();
StationDailyLoop();
EnginesDailyLoop();
ClearOutOfDateSignalSpeedRestrictions();
if (_quit_after_days > 0) {
@ -466,7 +467,7 @@ static void OnNewEconomyDay()
}
}
static void IncreaseCalendarDate()
void IncreaseCalendarDate()
{
/* If calendar day progress is frozen, don't try to advance time. */
if (CalTime::IsCalendarFrozen()) return;

@ -15,8 +15,9 @@
#include "date_gui.h"
#include "core/geometry_func.hpp"
#include "settings_type.h"
#include "dropdown_type.h"
#include "dropdown_func.h"
#include "widgets/dropdown_type.h"
#include "widgets/date_widget.h"
#include "safeguards.h"
@ -81,14 +82,14 @@ struct SetDateWindow : Window {
case WID_SD_DAY:
for (uint i = 0; i < 31; i++) {
list.push_back(std::make_unique<DropDownListStringItem>(STR_DAY_NUMBER_1ST + i, i + 1, false));
list.push_back(MakeDropDownListStringItem(STR_DAY_NUMBER_1ST + i, i + 1));
}
selected = this->date.day;
break;
case WID_SD_MONTH:
for (uint i = 0; i < 12; i++) {
list.push_back(std::make_unique<DropDownListStringItem>(STR_MONTH_JAN + i, i, false));
list.push_back(MakeDropDownListStringItem(STR_MONTH_JAN + i, i));
}
selected = this->date.month;
break;
@ -96,7 +97,7 @@ struct SetDateWindow : Window {
case WID_SD_YEAR:
for (EconTime::Year i = this->min_year; i <= this->max_year; i++) {
SetDParam(0, i);
list.push_back(std::make_unique<DropDownListStringItem>(STR_JUST_INT, i.base(), false));
list.push_back(MakeDropDownListStringItem(STR_JUST_INT, i.base()));
}
selected = this->date.year.base();
break;
@ -105,7 +106,7 @@ struct SetDateWindow : Window {
ShowDropDownList(this, std::move(list), selected, widget);
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
Dimension d = {0, 0};
switch (widget) {
@ -131,7 +132,7 @@ struct SetDateWindow : Window {
d.width += padding.width;
d.height += padding.height;
*size = d;
size = d;
}
void SetStringParameters(WidgetID widget) const override
@ -206,7 +207,7 @@ struct SetMinutesWindow : SetDateWindow
case WID_SD_DAY:
for (uint i = 0; i < 60; i++) {
SetDParam(0, i);
list.emplace_back(new DropDownListStringItem(STR_JUST_INT, i, false));
list.push_back(MakeDropDownListStringItem(STR_JUST_INT, i, false));
}
selected = this->minutes.ClockMinute();
break;
@ -214,7 +215,7 @@ struct SetMinutesWindow : SetDateWindow
case WID_SD_MONTH:
for (uint i = 0; i < 24; i++) {
SetDParam(0, i);
list.emplace_back(new DropDownListStringItem(STR_JUST_INT, i, false));
list.push_back(MakeDropDownListStringItem(STR_JUST_INT, i, false));
}
selected = this->minutes.ClockHour();
@ -224,7 +225,7 @@ struct SetMinutesWindow : SetDateWindow
ShowDropDownList(this, std::move(list), selected, widget);
}
virtual void UpdateWidgetSize(WidgetID widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
virtual void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
{
Dimension d = {0, 0};
switch (widget) {
@ -247,7 +248,7 @@ struct SetMinutesWindow : SetDateWindow
d.width += padding.width;
d.height += padding.height;
*size = d;
size = d;
}
virtual void SetStringParameters(WidgetID widget) const override

@ -82,7 +82,7 @@ struct DebugLevel {
};
#define DEBUG_LEVEL(x) { #x, &_debug_##x##_level }
static const DebugLevel debug_level[] = {
static const DebugLevel _debug_levels[] = {
DEBUG_LEVEL(driver),
DEBUG_LEVEL(grf),
DEBUG_LEVEL(map),
@ -106,7 +106,7 @@ struct DebugLevel {
DEBUG_LEVEL(random),
DEBUG_LEVEL(statecsum),
#endif
};
};
#undef DEBUG_LEVEL
/**
@ -117,20 +117,17 @@ struct DebugLevel {
*/
char *DumpDebugFacilityNames(char *buf, char *last)
{
size_t length = 0;
for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
if (length == 0) {
bool written = false;
for (const auto &debug_level : _debug_levels) {
if (!written) {
buf = strecpy(buf, "List of debug facility names:\n", last);
} else {
buf = strecpy(buf, ", ", last);
length += 2;
}
buf = strecpy(buf, i->name, last);
length += strlen(i->name);
}
if (length > 0) {
buf = strecpy(buf, "\n\n", last);
buf = strecpy(buf, debug_level.name, last);
written = true;
}
buf = strecpy(buf, "\n\n", last);
return buf;
}
@ -243,13 +240,11 @@ void SetDebugString(const char *s, void (*error_func)(const char *))
/* Global debugging level? */
if (*s >= '0' && *s <= '9') {
const DebugLevel *i;
v = std::strtoul(s, &end, 0);
s = end;
for (i = debug_level; i != endof(debug_level); ++i) {
new_levels[i->name] = v;
for (const auto &debug_level : _debug_levels) {
new_levels[debug_level.name] = v;
}
}
@ -264,9 +259,9 @@ void SetDebugString(const char *s, void (*error_func)(const char *))
/* check debugging levels */
const DebugLevel *found = nullptr;
for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
if (s == t + strlen(i->name) && strncmp(t, i->name, s - t) == 0) {
found = i;
for (const auto &debug_level : _debug_levels) {
if (s == t + strlen(debug_level.name) && strncmp(t, debug_level.name, s - t) == 0) {
found = &debug_level;
break;
}
}
@ -285,10 +280,10 @@ void SetDebugString(const char *s, void (*error_func)(const char *))
}
/* Apply the changes after parse is successful */
for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
const auto &nl = new_levels.find(i->name);
for (const auto &debug_level : _debug_levels) {
const auto &nl = new_levels.find(debug_level.name);
if (nl != new_levels.end()) {
*i->level = nl->second;
*debug_level.level = nl->second;
}
}
}
@ -301,8 +296,8 @@ void SetDebugString(const char *s, void (*error_func)(const char *))
std::string GetDebugString()
{
std::string result;
for (size_t i = 0; i < lengthof(debug_level); i++) {
result += stdstr_fmt("%s%s=%d", i == 0 ? "" : ", ", debug_level[i].name, *(debug_level[i].level));
for (const auto &debug_level : _debug_levels) {
result += stdstr_fmt("%s%s=%d", result.empty() ? "" : ", ", debug_level.name, *(debug_level.level));
}
return result;
}

@ -123,8 +123,6 @@ private:
char buffer[24];
};
const char *GetLogPrefix();
void ClearDesyncMsgLog();
void LogDesyncMsg(std::string msg);
char *DumpDesyncMsgLog(char *buffer, const char *last);

@ -302,13 +302,13 @@ public:
}
}
virtual void UpdateWidgetSize(WidgetID widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
virtual void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
{
switch (widget) {
case WID_DB_LIST:
resize->height = DeparturesWindow::entry_height;
size->height = 2 * resize->height;
size->width = this->min_width;
resize.height = DeparturesWindow::entry_height;
size.height = 2 * resize.height;
size.width = this->min_width;
break;
}
}

@ -655,7 +655,7 @@ struct DepotWindow : Window {
this->flag_size = maxdim(GetScaledSpriteSize(SPR_FLAG_VEH_STOPPED), GetScaledSpriteSize(SPR_FLAG_VEH_RUNNING));
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_D_MATRIX: {
@ -681,18 +681,18 @@ struct DepotWindow : Window {
}
int base_width = this->count_width + this->header_width + padding.width;
resize->height = std::max<uint>(this->cell_size.height, min_height + padding.height);
resize.height = std::max<uint>(this->cell_size.height, min_height + padding.height);
if (this->type == VEH_TRAIN) {
resize->width = 1;
size->width = base_width + 2 * ScaleSpriteTrad(29); // about 2 parts
size->height = resize->height * 6;
resize.width = 1;
size.width = base_width + 2 * ScaleSpriteTrad(29); // about 2 parts
size.height = resize.height * 6;
} else {
resize->width = base_width + this->cell_size.extend_left + this->cell_size.extend_right;
size->width = resize->width * (this->type == VEH_ROAD ? 5 : 3);
size->height = resize->height * (this->type == VEH_ROAD ? 5 : 3);
resize.width = base_width + this->cell_size.extend_left + this->cell_size.extend_right;
size.width = resize.width * (this->type == VEH_ROAD ? 5 : 3);
size.height = resize.height * (this->type == VEH_ROAD ? 5 : 3);
}
fill->width = resize->width;
fill->height = resize->height;
fill.width = resize.width;
fill.height = resize.height;
break;
}
}
@ -1146,7 +1146,7 @@ static void DepotSellAllConfirmationCallback(Window *win, bool confirmed)
if (confirmed) {
DepotWindow *w = (DepotWindow*)win;
TileIndex tile = w->window_number;
byte vehtype = w->type;
uint8_t vehtype = w->type;
DoCommandP(tile, vehtype, 0, CMD_DEPOT_SELL_ALL_VEHICLES);
}
}

@ -21,7 +21,7 @@
* your viewport and not rotated by 45 degrees left or right to get
* a "north" used in you games.
*/
enum Direction : byte {
enum Direction : uint8_t {
DIR_BEGIN = 0, ///< Used to iterate
DIR_N = 0, ///< North
DIR_NE = 1, ///< Northeast
@ -39,7 +39,7 @@ enum Direction : byte {
DECLARE_POSTFIX_INCREMENT(Direction)
/** Define basic enum properties */
template <> struct EnumPropsT<Direction> : MakeEnumPropsT<Direction, byte, DIR_BEGIN, DIR_END, INVALID_DIR, 3> {};
template <> struct EnumPropsT<Direction> : MakeEnumPropsT<Direction, uint8_t, DIR_BEGIN, DIR_END, INVALID_DIR, 3> {};
/**
@ -59,7 +59,7 @@ template <> struct EnumPropsT<Direction> : MakeEnumPropsT<Direction, byte, DIR_B
* modulo DIR_END or use the #ChangeDirDiff(DirDiff, DirDiff) function.
* @see ChangeDirDiff(DirDiff, DirDiff)
*/
enum DirDiff : byte {
enum DirDiff : uint8_t {
DIRDIFF_SAME = 0, ///< Both directions faces to the same direction
DIRDIFF_45RIGHT = 1, ///< Angle of 45 degrees right
DIRDIFF_90RIGHT = 2, ///< Angle of 90 degrees right
@ -74,7 +74,7 @@ enum DirDiff : byte {
*
* This enumeration is used for the 4 direction of the tile-edges.
*/
enum DiagDirection : byte {
enum DiagDirection : uint8_t {
DIAGDIR_BEGIN = 0, ///< Used for iterations
DIAGDIR_NE = 0, ///< Northeast, upper right on your monitor
DIAGDIR_SE = 1, ///< Southeast
@ -87,7 +87,7 @@ DECLARE_POSTFIX_INCREMENT(DiagDirection)
DECLARE_ENUM_AS_ADDABLE(DiagDirection)
/** Define basic enum properties */
template <> struct EnumPropsT<DiagDirection> : MakeEnumPropsT<DiagDirection, byte, DIAGDIR_BEGIN, DIAGDIR_END, INVALID_DIAGDIR, 2> {};
template <> struct EnumPropsT<DiagDirection> : MakeEnumPropsT<DiagDirection, uint8_t, DIAGDIR_BEGIN, DIAGDIR_END, INVALID_DIAGDIR, 2> {};
/**
@ -119,14 +119,14 @@ DECLARE_POSTFIX_INCREMENT(DiagDirDiff)
* (and south-east edge). The Y axis must be so the one which goes
* align the north-east edge (and south-west) edge.
*/
enum Axis : byte {
enum Axis : uint8_t {
AXIS_X = 0, ///< The X axis
AXIS_Y = 1, ///< The y axis
AXIS_END, ///< Used for iterations
INVALID_AXIS = 0xFF, ///< Flag for an invalid Axis
};
/** Helper information for extract tool. */
template <> struct EnumPropsT<Axis> : MakeEnumPropsT<Axis, byte, AXIS_X, AXIS_END, INVALID_AXIS, 1> {};
template <> struct EnumPropsT<Axis> : MakeEnumPropsT<Axis, uint8_t, AXIS_X, AXIS_END, INVALID_AXIS, 1> {};
DECLARE_ENUM_AS_ADDABLE(Axis)
#endif /* DIRECTION_TYPE_H */

@ -963,11 +963,11 @@ static const Disaster _disasters[] = {
void DoDisaster()
{
byte buf[lengthof(_disasters)];
uint8_t buf[lengthof(_disasters)];
byte j = 0;
uint8_t j = 0;
for (size_t i = 0; i != lengthof(_disasters); i++) {
if (CalTime::CurYear() >= _disasters[i].min_year && CalTime::CurYear() < _disasters[i].max_year) buf[j++] = (byte)i;
if (CalTime::CurYear() >= _disasters[i].min_year && CalTime::CurYear() < _disasters[i].max_year) buf[j++] = (uint8_t)i;
}
if (j == 0) return;

@ -37,7 +37,7 @@ enum DisasterSubType {
struct DisasterVehicle final : public SpecializedVehicle<DisasterVehicle, VEH_DISASTER> {
SpriteID image_override; ///< Override for the default disaster vehicle sprite.
VehicleID big_ufo_destroyer_target; ///< The big UFO that this destroyer is supposed to bomb.
byte flags; ///< Flags about the state of the vehicle, @see AirVehicleFlags
uint8_t flags; ///< Flags about the state of the vehicle, @see AirVehicleFlags
uint16_t state; ///< Action stage of the disaster vehicle.
/** For use by saveload. */

@ -529,13 +529,13 @@ public:
UpdateDocksDirection();
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
switch (widget) {
case WID_BDD_X:
case WID_BDD_Y:
size->width = ScaleGUITrad(96) + WidgetDimensions::scaled.fullbevel.Horizontal();
size->height = ScaleGUITrad(64) + WidgetDimensions::scaled.fullbevel.Vertical();
size.width = ScaleGUITrad(96) + WidgetDimensions::scaled.fullbevel.Horizontal();
size.height = ScaleGUITrad(64) + WidgetDimensions::scaled.fullbevel.Vertical();
break;
}
}

@ -7,19 +7,50 @@
/** @file dropdown.cpp Implementation of the dropdown widget. */
#include "../stdafx.h"
#include "../window_gui.h"
#include "../string_func.h"
#include "../strings_func.h"
#include "../window_func.h"
#include "../guitimer_func.h"
#include "../zoom_func.h"
#include "stdafx.h"
#include "dropdown_type.h"
#include "dropdown_func.h"
#include "dropdown_common_type.h"
#include "string_func.h"
#include "strings_func.h"
#include "window_gui.h"
#include "window_func.h"
#include "guitimer_func.h"
#include "zoom_func.h"
#include "dropdown_widget.h"
#include "widgets/dropdown_widget.h"
#include "../safeguards.h"
#include "safeguards.h"
std::unique_ptr<DropDownListItem> MakeDropDownListDividerItem()
{
return std::make_unique<DropDownListDividerItem>(-1);
}
std::unique_ptr<DropDownListItem> MakeDropDownListStringItem(StringID str, int value, bool masked, bool shaded)
{
return std::make_unique<DropDownListStringItem>(str, value, masked, shaded);
}
std::unique_ptr<DropDownListItem> MakeDropDownListStringItem(const std::string &str, int value, bool masked, bool shaded)
{
return std::make_unique<DropDownListStringItem>(str, value, masked, shaded);
}
std::unique_ptr<DropDownListItem> MakeDropDownListIconItem(SpriteID sprite, PaletteID palette, StringID str, int value, bool masked, bool shaded)
{
return std::make_unique<DropDownListIconItem>(sprite, palette, str, value, masked, shaded);
}
std::unique_ptr<DropDownListItem> MakeDropDownListIconItem(const Dimension &dim, SpriteID sprite, PaletteID palette, StringID str, int value, bool masked, bool shaded)
{
return std::make_unique<DropDownListIconItem>(dim, sprite, palette, str, value, masked, shaded);
}
std::unique_ptr<DropDownListItem> MakeDropDownListCheckedItem(bool checked, StringID str, int value, bool masked, bool shaded)
{
return std::make_unique<DropDownListCheckedItem>(checked, str, value, masked, shaded);
}
static constexpr NWidgetPart _nested_dropdown_menu_widgets[] = {
NWidget(NWID_HORIZONTAL),
@ -44,7 +75,7 @@ struct DropdownWindow : Window {
Rect wi_rect; ///< Rect of the button that opened the dropdown.
DropDownList list; ///< List with dropdown menu items.
int selected_result; ///< Result value of the selected item in the list.
byte click_delay = 0; ///< Timer to delay selection.
uint8_t click_delay = 0; ///< Timer to delay selection.
bool drag_mode = true;
DropDownModeFlags mode_flags; ///< Mode flags.
int scrolling = 0; ///< If non-zero, auto-scroll the item list (one time).
@ -154,7 +185,12 @@ struct DropdownWindow : Window {
this->position.y = button_rect.bottom + 1;
}
this->position.x = (_current_text_dir == TD_RTL) ? button_rect.right + 1 - (int)widget_dim.width : button_rect.left;
if (_current_text_dir == TD_RTL) {
/* In case the list is wider than the parent button, the list should be right aligned to the button and overflow to the left. */
this->position.x = button_rect.right + 1 - (int)(widget_dim.width + (list_dim.height > widget_dim.height ? NWidgetScrollbar::GetVerticalDimension().width : 0));
} else {
this->position.x = button_rect.left;
}
this->items_dim = widget_dim;
this->GetWidget<NWidgetStacked>(WID_DM_SHOW_SCROLL)->SetDisplayedPlane(list_dim.height > widget_dim.height ? 0 : SZSP_NONE);
@ -167,9 +203,9 @@ struct DropdownWindow : Window {
if (this->position.y < button_rect.top && list_dim.height > widget_dim.height) this->vscroll->UpdatePosition(INT_MAX);
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
{
if (widget == WID_DM_ITEMS) *size = this->items_dim;
if (widget == WID_DM_ITEMS) size = this->items_dim;
}
Point OnInitialPosition([[maybe_unused]] int16_t sm_width, [[maybe_unused]] int16_t sm_height, [[maybe_unused]] int window_number) override
@ -446,7 +482,7 @@ void ShowDropDownMenu(Window *w, const StringID *strings, int selected, WidgetID
for (uint i = 0; strings[i] != INVALID_STRING_ID; i++) {
if (i >= 32 || !HasBit(hidden_mask, i)) {
list.push_back(std::make_unique<DropDownListStringItem>(strings[i], i, i < 32 && HasBit(disabled_mask, i)));
list.push_back(MakeDropDownListStringItem(strings[i], i, i < 32 && HasBit(disabled_mask, i)));
}
}

@ -5,65 +5,25 @@
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file dropdown_type.h Types related to the drop down widget. */
#ifndef WIDGETS_DROPDOWN_TYPE_H
#define WIDGETS_DROPDOWN_TYPE_H
#include "../window_type.h"
#include "../gfx_func.h"
#include "../gfx_type.h"
#include "../string_func.h"
#include "../strings_func.h"
#include "../table/strings.h"
#include "../window_gui.h"
#include <vector>
enum DropDownSyncFocus {
DDSF_NONE = 0,
DDSF_NOTIFY_RECV_FOCUS = 1 << 0,
DDSF_NOTIFY_LOST_FOCUS = 1 << 1,
DDSF_FOCUS_PARENT_ON_SELECT = 1 << 2,
DDSF_SHARED = DDSF_NOTIFY_RECV_FOCUS | DDSF_FOCUS_PARENT_ON_SELECT,
};
DECLARE_ENUM_AS_BIT_SET(DropDownSyncFocus)
/**
* Base list item class from which others are derived.
*/
class DropDownListItem {
public:
int result; ///< Result value to return to window on selection.
bool masked; ///< Masked and unselectable item.
bool shaded; ///< Shaded item, affects text colour.
TextColour colour_flags = TC_BEGIN;
explicit DropDownListItem(int result, bool masked = false, bool shaded = false) : result(result), masked(masked), shaded(shaded) {}
virtual ~DropDownListItem() = default;
/** @file dropdown_common_type.h Common drop down list components. */
virtual bool Selectable() const { return true; }
virtual uint Height() const { return 0; }
virtual uint Width() const { return 0; }
#ifndef DROPDOWN_COMMON_TYPE_H
#define DROPDOWN_COMMON_TYPE_H
virtual void Draw(const Rect &full, const Rect &, bool, Colours bg_colour) const
{
if (this->masked) GfxFillRect(full, GetColourGradient(bg_colour, SHADE_LIGHT), FILLRECT_CHECKER);
}
TextColour GetColour(bool sel) const
{
if (this->shaded) return (sel ? TC_SILVER : TC_GREY) | TC_NO_SHADE;
return (sel ? TC_WHITE : TC_BLACK) | this->colour_flags;
}
};
#include "gfx_func.h"
#include "gfx_type.h"
#include "palette_func.h"
#include "string_func.h"
#include "strings_func.h"
#include "table/strings.h"
#include "window_gui.h"
/**
* Drop down divider component.
* @tparam TBase Base component.
* @tparam TFs Font size -- used to determine height.
*/
template<class TBase, FontSize TFs = FS_NORMAL>
template <class TBase, FontSize TFs = FS_NORMAL>
class DropDownDivider : public TBase {
public:
template <typename... Args>
@ -89,7 +49,7 @@ public:
* @tparam TFs Font size.
* @tparam TEnd Position string at end if true, or start if false.
*/
template<class TBase, FontSize TFs = FS_NORMAL, bool TEnd = false>
template <class TBase, FontSize TFs = FS_NORMAL, bool TEnd = false>
class DropDownString : public TBase {
std::string string; ///< String to be drawn.
Dimension dim; ///< Dimensions of string.
@ -149,7 +109,7 @@ public:
* @tparam TBase Base component.
* @tparam TEnd Position icon at end if true, or start if false.
*/
template<class TBase, bool TEnd = false>
template <class TBase, bool TEnd = false>
class DropDownIcon : public TBase {
SpriteID sprite; ///< Sprite ID to be drawn.
PaletteID palette; ///< Palette ID to use.
@ -187,7 +147,7 @@ public:
* @tparam TFs Font size.
* @tparam TEnd Position checkmark at end if true, or start if false.
*/
template<class TBase, bool TEnd = false, FontSize TFs = FS_NORMAL>
template <class TBase, bool TEnd = false, FontSize TFs = FS_NORMAL>
class DropDownCheck : public TBase {
bool checked; ///< Is item checked.
Dimension dim; ///< Dimension of checkmark.
@ -211,43 +171,10 @@ public:
}
};
/**
* Drop down unselectable component.
* @tparam TBase Base component.
*/
template<class TBase>
class DropDownUnselectable : public TBase {
public:
template <typename... Args>
explicit DropDownUnselectable(Args&&... args) : TBase(std::forward<Args>(args)...) {}
bool Selectable() const override { return false; }
};
/* Commonly used drop down list items. */
using DropDownListDividerItem = DropDownDivider<DropDownListItem>;
using DropDownListStringItem = DropDownString<DropDownListItem>;
using DropDownListIconItem = DropDownIcon<DropDownString<DropDownListItem>>;
using DropDownListCheckedItem = DropDownCheck<DropDownString<DropDownListItem>>;
/**
* A drop down list is a collection of drop down list items.
*/
typedef std::vector<std::unique_ptr<const DropDownListItem>> DropDownList;
enum DropDownModeFlags : uint8_t {
DDMF_NONE = 0,
DDMF_INSTANT_CLOSE = 1 << 0, ///< Close the window when the mouse button is raised.
DDMF_PERSIST = 1 << 1, ///< Dropdown menu will persist.
};
DECLARE_ENUM_AS_BIT_SET(DropDownModeFlags)
void ShowDropDownListAt(Window *w, DropDownList &&list, int selected, WidgetID button, Rect wi_rect, Colours wi_colour, DropDownModeFlags mode_flags = DDMF_NONE, DropDownSyncFocus sync_parent_focus = DDSF_NONE);
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width = 0, DropDownModeFlags mode_flags = DDMF_NONE, DropDownSyncFocus sync_parent_focus = DDSF_NONE);
Dimension GetDropDownListDimension(const DropDownList &list);
void ReplaceDropDownList(Window *parent, DropDownList &&list);
#endif /* WIDGETS_DROPDOWN_TYPE_H */
#endif /* DROPDOWN_COMMON_TYPE_H */

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save