OpenTTD Source 20261112-master-gbcbec5e63f
newgrf_debug_gui.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * 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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "core/backup_type.hpp"
13#include "window_gui.h"
14#include "window_func.h"
15#include "spritecache.h"
16#include "string_func.h"
17#include "strings_func.h"
18#include "textbuf_gui.h"
19#include "vehicle_gui.h"
20#include "zoom_func.h"
22
23#include "engine_base.h"
24#include "industry.h"
25#include "object_base.h"
26#include "station_base.h"
27#include "town.h"
28#include "vehicle_base.h"
29#include "train.h"
30#include "roadveh.h"
31
32#include "newgrf_act5.h"
33#include "newgrf_airport.h"
34#include "newgrf_airporttiles.h"
35#include "newgrf_badge.h"
36#include "newgrf_debug.h"
37#include "newgrf_object.h"
38#include "newgrf_spritegroup.h"
39#include "newgrf_station.h"
40#include "newgrf_town.h"
41#include "newgrf_railtype.h"
42#include "newgrf_industries.h"
44
46
47#include "table/strings.h"
48
49#include "safeguards.h"
50
53
59static inline uint GetFeatureIndex(uint window_number)
60{
61 return GB(window_number, 0, 24);
62}
63
71static inline uint GetInspectWindowNumber(GrfSpecFeature feature, uint index)
72{
73 assert((index >> 24) == 0);
74 return (to_underlying(feature) << 24) | index;
75}
76
77static inline uint GetInspectWindowNumber(GrfSpecFeature feature, ConvertibleThroughBase auto index) { return GetInspectWindowNumber(feature, index.base()); }
78
83enum class NIType : uint8_t {
86};
87
88using NIReadProc = uint32_t(const void *b);
89
91struct NIProperty {
92 std::string_view name;
93 NIReadProc *read_proc;
94 uint8_t prop;
96};
97
98
120
123 std::string_view name;
124 uint8_t var;
125};
126
128class NIHelper {
129public:
131 virtual ~NIHelper() = default;
132
138 virtual bool IsInspectable(uint index) const = 0;
139
145 virtual uint GetParent(uint index) const = 0;
146
152 virtual const void *GetInstance(uint index) const = 0;
153
159 virtual const void *GetSpec(uint index) const = 0;
160
166 virtual std::string GetName(uint index) const = 0;
167
173 virtual GrfID GetGRFID(uint index) const = 0;
174
180 virtual std::span<const BadgeID> GetBadges(uint index) const = 0;
181
190 virtual uint Resolve(uint index, uint var, uint param, bool &avail) const = 0;
191
196 virtual bool PSAWithParameter() const
197 {
198 return false;
199 }
200
207 virtual const std::span<int32_t> GetPSA([[maybe_unused]] uint index, [[maybe_unused]] GrfID grfid) const
208 {
209 return {};
210 }
211};
212
213
215struct NIFeature {
216 std::span<const NIProperty> properties;
217 std::span<const NICallback> callbacks;
218 std::span<const NIVariable> variables;
219 std::unique_ptr<const NIHelper> helper;
220};
221
222/* Load all the NewGRF debug data; externalised as it is just a huge bunch of tables. */
224
230static inline GrfSpecFeature GetFeatureNum(uint window_number)
231{
232 return (GrfSpecFeature)GB(window_number, 24, 8);
233}
234
240static inline const NIFeature *GetFeature(uint window_number)
241{
242 GrfSpecFeature idx = GetFeatureNum(window_number);
243 return idx < GrfSpecFeature::FakeEnd ? _nifeatures[idx] : nullptr;
244}
245
252static inline const NIHelper &GetFeatureHelper(uint window_number)
253{
254 return *GetFeature(window_number)->helper;
255}
256
258struct NewGRFInspectWindow : Window {
261
264
266 uint chain_index = 0;
267
270
271 Scrollbar *vscroll = nullptr;
272
278 static bool HasVariableParameter(uint variable)
279 {
280 return IsInsideBS(variable, 0x60, 0x20);
281 }
282
288 {
289 this->caller_grfid = grfid;
290 this->SetDirty();
291 }
292
297 bool HasChainIndex() const
298 {
299 GrfSpecFeature f = GetFeatureNum(this->window_number);
301 }
302
308 {
309 switch (GetFeatureNum(this->window_number)) {
314 default: NOT_REACHED();
315 }
316 }
317
322 uint GetFeatureIndex() const
323 {
324 uint index = ::GetFeatureIndex(this->window_number);
325 if (this->chain_index > 0) {
326 assert(this->HasChainIndex());
327 const Vehicle *v = Vehicle::Get(index);
328 v = v->Move(this->chain_index);
329 if (v != nullptr) index = v->index.base();
330 }
331 return index;
332 }
333
338 {
339 if (this->chain_index == 0) return;
340
341 assert(this->HasChainIndex());
342
344 v = v->Move(this->chain_index);
345 if (v == nullptr) this->chain_index = 0;
346 }
347
349 {
350 this->CreateNestedTree();
351 this->vscroll = this->GetScrollbar(WID_NGRFI_SCROLLBAR);
352 this->FinishInitNested(wno);
353
354 this->vscroll->SetCount(0);
355 this->SetWidgetDisabledState(WID_NGRFI_PARENT, GetFeatureHelper(this->window_number).GetParent(this->GetFeatureIndex()) == UINT32_MAX);
356
357 this->OnInvalidateData(0, true);
358 }
359
360 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
361 {
362 if (widget != WID_NGRFI_CAPTION) return this->Window::GetWidgetString(widget, stringid);
363
365 }
366
367 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
368 {
369 switch (widget) {
371 assert(this->HasChainIndex());
373 break;
374
376 fill.height = resize.height = std::max(11, GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_normal);
377 resize.width = 1;
378
379 size.height = 5 * resize.height + WidgetDimensions::scaled.frametext.Vertical();
380 break;
381 }
382 }
383
390 void DrawString(const Rect &r, int offset, const std::string &string) const
391 {
392 offset -= this->vscroll->GetPosition();
393 if (offset < 0 || offset >= this->vscroll->GetCapacity()) return;
394
395 ::DrawString(r.Shrink(WidgetDimensions::scaled.frametext).Shrink(0, offset * this->resize.step_height, 0, 0), string, TextColour::Black);
396 }
397
402 void DrawVehicleChainWidget(const Rect &r) const
403 {
404 const Vehicle *v = Vehicle::Get(this->GetFeatureIndex());
405 int total_width = 0;
406 int sel_start = 0;
407 int sel_end = 0;
408 for (const Vehicle *u = v->First(); u != nullptr; u = u->Next()) {
409 if (u == v) sel_start = total_width;
410 switch (u->type) {
411 case VehicleType::Train: total_width += Train::From(u)->GetDisplayImageWidth(); break;
412 case VehicleType::Road: total_width += RoadVehicle::From(u)->GetDisplayImageWidth(); break;
413 default: NOT_REACHED();
414 }
415 if (u == v) sel_end = total_width;
416 }
417
419 int width = br.Width();
420 int skip = 0;
421 if (total_width > width) {
422 int sel_center = (sel_start + sel_end) / 2;
423 if (sel_center > width / 2) skip = std::min(total_width - width, sel_center - width / 2);
424 }
425
427 int y = CentreBounds(br.top, br.bottom, h);
428 DrawVehicleImage(v->First(), br, VehicleID::Invalid(), EngineImageType::InDetails, skip);
429
430 /* Highlight the articulated part (this is different to the whole-vehicle highlighting of DrawVehicleImage */
431 if (_current_text_dir == TD_RTL) {
432 DrawFrameRect(r.right - sel_end + skip, y, r.right - sel_start + skip, y + h, Colours::White, FrameFlag::BorderOnly);
433 } else {
434 DrawFrameRect(r.left + sel_start - skip, y, r.left + sel_end - skip, y + h, Colours::White, FrameFlag::BorderOnly);
435 }
436 }
437
438 std::string GetPropertyString(const NIProperty &nip, uint value) const
439 {
440 switch (nip.type) {
441 case NIType::Integer: return GetString(STR_JUST_INT, value);
442 case NIType::Cargo: return GetString(IsValidCargoType(static_cast<CargoType>(value)) ? CargoSpec::Get(value)->name : STR_QUANTITY_N_A);
443 default: NOT_REACHED();
444 }
445 }
446
451 void DrawMainPanelWidget(const Rect &r) const
452 {
453 uint index = this->GetFeatureIndex();
454 const NIFeature *nif = GetFeature(this->window_number);
455 const NIHelper &nih = *nif->helper;
456 const void *base = nih.GetInstance(index);
457 const void *base_spec = nih.GetSpec(index);
458
459 uint i = 0;
460 if (!nif->variables.empty()) {
461 this->DrawString(r, i++, "Variables:");
462 for (const NIVariable &niv : nif->variables) {
463 bool avail = true;
464 uint param = HasVariableParameter(niv.var) ? NewGRFInspectWindow::var60params[GetFeatureNum(this->window_number)][niv.var - 0x60] : 0;
465 uint value = nih.Resolve(index, niv.var, param, avail);
466
467 if (!avail) continue;
468
469 if (HasVariableParameter(niv.var)) {
470 this->DrawString(r, i++, fmt::format(" {:02x}[{:02x}]: {:08x} ({})", niv.var, param, value, niv.name));
471 } else {
472 this->DrawString(r, i++, fmt::format(" {:02x}: {:08x} ({})", niv.var, value, niv.name));
473 }
474 }
475 }
476
477 auto psa = nih.GetPSA(index, this->caller_grfid);
478 if (!psa.empty()) {
479 if (nih.PSAWithParameter()) {
480 this->DrawString(r, i++, fmt::format("Persistent storage [{}]:", FormatArrayAsHex(this->caller_grfid)));
481 } else {
482 this->DrawString(r, i++, "Persistent storage:");
483 }
484 assert(psa.size() % 4 == 0);
485 for (size_t j = 0; j < psa.size(); j += 4) {
486 this->DrawString(r, i++, fmt::format(" {}: {} {} {} {}", j, psa[j], psa[j + 1], psa[j + 2], psa[j + 3]));
487 }
488 }
489
490 auto badges = nih.GetBadges(index);
491 if (!badges.empty()) {
492 this->DrawString(r, i++, "Badges:");
493 for (const BadgeID &badge_index : badges) {
494 const Badge *badge = GetBadge(badge_index);
495 this->DrawString(r, i++, fmt::format(" {}: {}", StrMakeValid(badge->label), GetString(badge->name)));
496 }
497 }
498
499 if (!nif->properties.empty()) {
500 this->DrawString(r, i++, "Properties:");
501 for (const NIProperty &nip : nif->properties) {
502 uint32_t value = nip.read_proc(base);
503 this->DrawString(r, i++, fmt::format(" {:02x}: {} ({})", nip.prop, this->GetPropertyString(nip, value), nip.name));
504 }
505 }
506
507 if (!nif->callbacks.empty()) {
508 this->DrawString(r, i++, "Callbacks:");
509 for (const NICallback &nic : nif->callbacks) {
510 if (!std::holds_alternative<std::monostate>(nic.cb_bit)) {
511 uint32_t value = nic.read_proc(base_spec);
512
513 struct visitor {
514 uint32_t value;
515
516 bool operator()(const std::monostate &) { return false; }
517 bool operator()(const VehicleCallbackMask &bit) { return static_cast<VehicleCallbackMasks>(this->value).Test(bit); }
518 bool operator()(const StationCallbackMask &bit) { return static_cast<StationCallbackMasks>(this->value).Test(bit); }
519 bool operator()(const RoadStopCallbackMask &bit) { return static_cast<RoadStopCallbackMasks>(this->value).Test(bit); }
520 bool operator()(const HouseCallbackMask &bit) { return static_cast<HouseCallbackMasks>(this->value).Test(bit); }
521 bool operator()(const CanalCallbackMask &bit) { return static_cast<CanalCallbackMasks>(this->value).Test(bit); }
522 bool operator()(const CargoCallbackMask &bit) { return static_cast<CargoCallbackMasks>(this->value).Test(bit); }
523 bool operator()(const IndustryCallbackMask &bit) { return static_cast<IndustryCallbackMasks>(this->value).Test(bit); }
524 bool operator()(const IndustryTileCallbackMask &bit) { return static_cast<IndustryTileCallbackMasks>(this->value).Test(bit); }
525 bool operator()(const ObjectCallbackMask &bit) { return static_cast<ObjectCallbackMasks>(this->value).Test(bit); }
526 bool operator()(const AirportTileCallbackMask &bit) { return static_cast<AirportTileCallbackMasks>(this->value).Test(bit); }
527 };
528
529 if (!std::visit(visitor{value}, nic.cb_bit)) continue;
530 this->DrawString(r, i++, fmt::format(" {:03x}: {}", nic.cb_id, nic.name));
531 } else {
532 this->DrawString(r, i++, fmt::format(" {:03x}: {} (unmasked)", nic.cb_id, nic.name));
533 }
534 }
535 }
536
537 /* Not nice and certainly a hack, but it beats duplicating
538 * this whole function just to count the actual number of
539 * elements. Especially because they need to be redrawn. */
540 const_cast<NewGRFInspectWindow*>(this)->vscroll->SetCount(i);
541 }
542
543 void DrawWidget(const Rect &r, WidgetID widget) const override
544 {
545 switch (widget) {
547 this->DrawVehicleChainWidget(r);
548 break;
549
551 this->DrawMainPanelWidget(r);
552 break;
553 }
554 }
555
556 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
557 {
558 switch (widget) {
559 case WID_NGRFI_PARENT: {
560 const NIHelper &nih = GetFeatureHelper(this->window_number);
561 uint index = nih.GetParent(this->GetFeatureIndex());
562 ::ShowNewGRFInspectWindow(GetFeatureNum(index), ::GetFeatureIndex(index), nih.GetGRFID(this->GetFeatureIndex()));
563 break;
564 }
565
567 if (this->chain_index > 0) {
568 this->chain_index--;
569 this->InvalidateData();
570 }
571 break;
572
574 if (this->HasChainIndex()) {
575 uint index = this->GetFeatureIndex();
576 Vehicle *v = Vehicle::Get(index);
577 if (v != nullptr && v->Next() != nullptr) {
578 this->chain_index++;
579 this->InvalidateData();
580 }
581 }
582 break;
583
584 case WID_NGRFI_MAINPANEL: {
585 /* Does this feature have variables? */
586 const NIFeature *nif = GetFeature(this->window_number);
587 if (nif->variables.empty()) return;
588
589 /* Get the line, make sure it's within the boundaries. */
590 int32_t line = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NGRFI_MAINPANEL, WidgetDimensions::scaled.frametext.top);
591 if (line == INT32_MAX) return;
592
593 /* Find the variable related to the line */
594 for (const NIVariable &niv : nif->variables) {
595 if (--line != 0) continue; // 0 because of the "Variables:" line
596
597 if (!HasVariableParameter(niv.var)) break;
598
599 this->current_edit_param = niv.var;
600 ShowQueryString({}, STR_NEWGRF_INSPECT_QUERY_CAPTION, 9, this, CS_HEXADECIMAL, {});
601 }
602 }
603 }
604 }
605
606 void OnQueryTextFinished(std::optional<std::string> str) override
607 {
608 if (!str.has_value()) return;
609
610 auto val = ParseInteger<uint32_t>(*str, 16, true);
611 if (!val.has_value()) return;
612 NewGRFInspectWindow::var60params[GetFeatureNum(this->window_number)][this->current_edit_param - 0x60] = *val;
613 this->SetDirty();
614 }
615
616 void OnResize() override
617 {
618 this->vscroll->SetCapacityFromWidget(this, WID_NGRFI_MAINPANEL, WidgetDimensions::scaled.frametext.Vertical());
619 }
620
626 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
627 {
628 if (!gui_scope) return;
629 if (this->HasChainIndex()) {
630 this->ValidateChainIndex();
631 this->SetWidgetDisabledState(WID_NGRFI_VEH_PREV, this->chain_index == 0);
633 this->SetWidgetDisabledState(WID_NGRFI_VEH_NEXT, v == nullptr || v->Next() == nullptr);
634 }
635 }
636};
637
638static constexpr std::initializer_list<NWidgetPart> _nested_newgrf_inspect_chain_widgets = {
641 NWidget(WWT_CAPTION, Colours::Grey, WID_NGRFI_CAPTION), SetStringTip(STR_NEWGRF_INSPECT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
645 EndContainer(),
651 EndContainer(),
652 EndContainer(),
658 EndContainer(),
659 EndContainer(),
660};
661
662static constexpr std::initializer_list<NWidgetPart> _nested_newgrf_inspect_widgets = {
665 NWidget(WWT_CAPTION, Colours::Grey, WID_NGRFI_CAPTION), SetStringTip(STR_NEWGRF_INSPECT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
666 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_NGRFI_PARENT), SetStringTip(STR_NEWGRF_INSPECT_PARENT_BUTTON, STR_NEWGRF_INSPECT_PARENT_TOOLTIP),
670 EndContainer(),
676 EndContainer(),
677 EndContainer(),
678};
679
682 WindowPosition::Automatic, "newgrf_inspect_chain", 400, 300,
683 WindowClass::NewGRFInspect, WindowClass::None,
684 {},
685 _nested_newgrf_inspect_chain_widgets
686);
687
690 WindowPosition::Automatic, "newgrf_inspect", 400, 300,
691 WindowClass::NewGRFInspect, WindowClass::None,
692 {},
693 _nested_newgrf_inspect_widgets
694);
695
705void ShowNewGRFInspectWindow(GrfSpecFeature feature, uint index, const GrfID grfid)
706{
707 if (!IsNewGRFInspectable(feature, index)) return;
708
709 WindowNumber wno = GetInspectWindowNumber(feature, index);
712 w->SetCallerGRFID(grfid);
713}
714
724{
725 if (feature == GrfSpecFeature::Invalid) return;
726
727 WindowNumber wno = GetInspectWindowNumber(feature, index);
728 InvalidateWindowData(WindowClass::NewGRFInspect, wno);
729}
730
740{
741 if (feature == GrfSpecFeature::Invalid) return;
742
743 WindowNumber wno = GetInspectWindowNumber(feature, index);
744 CloseWindowById(WindowClass::NewGRFInspect, wno);
745
746 /* Reinitialise the land information window to remove the "debug" sprite if needed.
747 * Note: Since we might be called from a command here, it is important to not execute
748 * the invalidation immediately. The landinfo window tests commands itself. */
749 InvalidateWindowData(WindowClass::LandInfo, 0, 1);
750}
751
761bool IsNewGRFInspectable(GrfSpecFeature feature, uint index)
762{
763 const NIFeature *nif = GetFeature(GetInspectWindowNumber(feature, index));
764 if (nif == nullptr) return false;
765 return nif->helper->IsInspectable(index);
766}
767
793
794
795/**** Sprite Aligner ****/
796
798struct SpriteAlignerWindow : Window {
800 Scrollbar *vscroll = nullptr;
801 std::map<SpriteID, Coord2D<int16_t>> offs_start_map{};
802
803 static inline ZoomLevel zoom = ZoomLevel::End;
804 static bool centre;
805 static bool crosshair;
806 const Action5Type *act5_type = nullptr;
807
808 SpriteAlignerWindow(WindowDesc &desc, WindowNumber wno) : Window(desc)
809 {
810 /* On first opening, set initial zoom to current zoom level. */
811 if (SpriteAlignerWindow::zoom == ZoomLevel::End) SpriteAlignerWindow::zoom = _gui_zoom;
812 SpriteAlignerWindow::zoom = Clamp(SpriteAlignerWindow::zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max);
813
814 /* Oh yes, we assume there is at least one normal sprite! */
815 while (GetSpriteType(this->current_sprite) != SpriteType::Normal) this->current_sprite++;
816 this->SelectAction5Type();
817
818 this->CreateNestedTree();
819 this->vscroll = this->GetScrollbar(WID_SA_SCROLLBAR);
820 this->vscroll->SetCount(_newgrf_debug_sprite_picker.sprites.size());
821 this->FinishInitNested(wno);
822
823 this->SetWidgetLoweredState(WID_SA_CENTRE, SpriteAlignerWindow::centre);
824 this->SetWidgetLoweredState(WID_SA_CROSSHAIR, SpriteAlignerWindow::crosshair);
825
826 this->InvalidateData(0, true);
827 }
828
829 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
830 {
831 const Sprite *spr = GetSprite(this->current_sprite, SpriteType::Normal);
832 switch (widget) {
833 case WID_SA_CAPTION:
834 if (this->act5_type != nullptr) {
835 return GetString(STR_SPRITE_ALIGNER_CAPTION_ACTION5,
836 this->act5_type - GetAction5Types().data(),
837 this->current_sprite - this->act5_type->sprite_base,
838 GetOriginFile(this->current_sprite)->GetSimplifiedFilename(),
839 GetSpriteLocalID(this->current_sprite));
840 }
841 if (this->current_sprite < SPR_OPENTTD_BASE) {
842 return GetString(STR_SPRITE_ALIGNER_CAPTION_ACTIONA,
843 this->current_sprite,
844 GetOriginFile(this->current_sprite)->GetSimplifiedFilename(),
845 GetSpriteLocalID(this->current_sprite));
846 }
847 return GetString(STR_SPRITE_ALIGNER_CAPTION_NO_ACTION,
848 GetOriginFile(this->current_sprite)->GetSimplifiedFilename(),
849 GetSpriteLocalID(this->current_sprite));
850
852 return GetString(STR_SPRITE_ALIGNER_OFFSETS_ABS, UnScaleByZoom(spr->x_offs, SpriteAlignerWindow::zoom), UnScaleByZoom(spr->y_offs, SpriteAlignerWindow::zoom));
853
854 case WID_SA_OFFSETS_REL: {
855 /* Relative offset is new absolute offset - starting absolute offset.
856 * Show 0, 0 as the relative offsets if entry is not in the map (meaning they have not been changed yet).
857 */
858 const auto key_offs_pair = this->offs_start_map.find(this->current_sprite);
859 if (key_offs_pair != this->offs_start_map.end()) {
860 return GetString(STR_SPRITE_ALIGNER_OFFSETS_REL,
861 UnScaleByZoom(spr->x_offs - key_offs_pair->second.x, SpriteAlignerWindow::zoom),
862 UnScaleByZoom(spr->y_offs - key_offs_pair->second.y, SpriteAlignerWindow::zoom));
863 }
864
865 return GetString(STR_SPRITE_ALIGNER_OFFSETS_REL, 0, 0);
866 }
867
868 default:
869 return this->Window::GetWidgetString(widget, stringid);
870 }
871 }
872
873 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
874 {
875 switch (widget) {
876 case WID_SA_SPRITE:
877 size.height = ScaleGUITrad(200);
878 break;
879
880 case WID_SA_LIST: {
881 Dimension d = {};
882 for (const auto &spritefile : GetCachedSpriteFiles()) {
883 d = maxdim(d, GetStringBoundingBox(GetString(STR_SPRITE_ALIGNER_SPRITE, spritefile->GetSimplifiedFilename(), GetParamMaxDigits(6))));
884 }
885 size.width = d.width + padding.width;
886 fill.height = resize.height = GetCharacterHeight(FontSize::Normal) + padding.height;
887 resize.width = 1;
888 break;
889 }
890
891 default:
892 break;
893 }
894 }
895
896 void DrawWidget(const Rect &r, WidgetID widget) const override
897 {
898 switch (widget) {
899 case WID_SA_SPRITE: {
900 /* Center the sprite ourselves */
901 const Sprite *spr = GetSprite(this->current_sprite, SpriteType::Normal);
903 int x;
904 int y;
905 if (SpriteAlignerWindow::centre) {
906 x = -UnScaleByZoom(spr->x_offs, SpriteAlignerWindow::zoom) + (ir.Width() - UnScaleByZoom(spr->width, SpriteAlignerWindow::zoom)) / 2;
907 y = -UnScaleByZoom(spr->y_offs, SpriteAlignerWindow::zoom) + (ir.Height() - UnScaleByZoom(spr->height, SpriteAlignerWindow::zoom)) / 2;
908 } else {
909 x = ir.Width() / 2;
910 y = ir.Height() / 2;
911 }
912
913 DrawPixelInfo new_dpi;
914 if (!FillDrawPixelInfo(&new_dpi, ir)) break;
915 AutoRestoreBackup dpi_backup(_cur_dpi, &new_dpi);
916
917 DrawSprite(this->current_sprite, PAL_NONE, x, y, nullptr, SpriteAlignerWindow::zoom);
918
919 Rect outline = {0, 0, UnScaleByZoom(spr->width, SpriteAlignerWindow::zoom) - 1, UnScaleByZoom(spr->height, SpriteAlignerWindow::zoom) - 1};
920 outline = outline.Translate(x + UnScaleByZoom(spr->x_offs, SpriteAlignerWindow::zoom), y + UnScaleByZoom(spr->y_offs, SpriteAlignerWindow::zoom));
921 DrawRectOutline(outline.Expand(1), PC_LIGHT_BLUE, 1, 1);
922
923 if (SpriteAlignerWindow::crosshair) {
924 GfxDrawLine(x, 0, x, ir.Height() - 1, PC_WHITE, 1, 1);
925 GfxDrawLine(0, y, ir.Width() - 1, y, PC_WHITE, 1, 1);
926 }
927 break;
928 }
929
930 case WID_SA_LIST: {
931 /* Don't redraw sprite list while it is still being filled by picker. */
932 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW) break;
933
934 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget);
935 int step_size = nwid->resize_y;
936
938
939 Rect ir = r.Shrink(WidgetDimensions::scaled.matrix);
940 auto [first, last] = this->vscroll->GetVisibleRangeIterators(list);
941 for (auto it = first; it != last; ++it) {
942 const SpriteFile *file = GetOriginFile(*it);
943 if (file == nullptr) {
945 } else {
946 DrawString(ir, GetString(STR_SPRITE_ALIGNER_SPRITE, file->GetSimplifiedFilename(), GetSpriteLocalID(*it)), *it == this->current_sprite ? TextColour::White : TextColour::Black);
947 }
948 ir.top += step_size;
949 }
950 break;
951 }
952 }
953 }
954
955 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
956 {
957 switch (widget) {
958 case WID_SA_PREVIOUS:
959 do {
960 this->current_sprite = (this->current_sprite == 0 ? GetMaxSpriteID() : this->current_sprite) - 1;
961 } while (GetSpriteType(this->current_sprite) != SpriteType::Normal);
962 this->SelectAction5Type();
963 this->SetDirty();
964 break;
965
966 case WID_SA_GOTO:
967 ShowQueryString({}, STR_SPRITE_ALIGNER_GOTO_CAPTION, 7, this, CS_NUMERAL, {});
968 break;
969
970 case WID_SA_NEXT:
971 do {
972 this->current_sprite = (this->current_sprite + 1) % GetMaxSpriteID();
973 } while (GetSpriteType(this->current_sprite) != SpriteType::Normal);
974 this->SelectAction5Type();
975 this->SetDirty();
976 break;
977
978 case WID_SA_PICKER:
980 _newgrf_debug_sprite_picker.mode = SPM_WAIT_CLICK;
981 this->SetDirty();
982 break;
983
984 case WID_SA_LIST: {
985 auto it = this->vscroll->GetScrolledItemFromWidget(_newgrf_debug_sprite_picker.sprites, pt.y, this, widget);
986 if (it != _newgrf_debug_sprite_picker.sprites.end()) {
987 SpriteID spr = *it;
988 if (GetSpriteType(spr) == SpriteType::Normal) this->current_sprite = spr;
989 }
990 this->SelectAction5Type();
991 this->SetDirty();
992 break;
993 }
994
995 case WID_SA_UP:
996 case WID_SA_DOWN:
997 case WID_SA_LEFT:
998 case WID_SA_RIGHT: {
999 /*
1000 * Yes... this is a hack.
1001 *
1002 * No... I don't think it is useful to make this less of a hack.
1003 *
1004 * If you want to align sprites, you just need the number. Generally
1005 * the sprite caches are big enough to not remove the sprite from the
1006 * cache. If that's not the case, just let the NewGRF developer
1007 * increase the cache size instead of storing thousands of offsets
1008 * for the incredibly small chance that it's actually going to be
1009 * used by someone and the sprite cache isn't big enough for that
1010 * particular NewGRF developer.
1011 */
1012 Sprite *spr = const_cast<Sprite *>(GetSprite(this->current_sprite, SpriteType::Normal));
1013
1014 /* Remember the original offsets of the current sprite, if not already in mapping. */
1015 if (this->offs_start_map.count(this->current_sprite) == 0) {
1016 this->offs_start_map[this->current_sprite] = {spr->x_offs, spr->y_offs};
1017 }
1018 int amt = ScaleByZoom(IsCtrlPressed() ? 8 : 1, SpriteAlignerWindow::zoom);
1019 switch (widget) {
1020 /* Move eight units at a time if ctrl is pressed. */
1021 case WID_SA_UP: spr->y_offs -= amt; break;
1022 case WID_SA_DOWN: spr->y_offs += amt; break;
1023 case WID_SA_LEFT: spr->x_offs -= amt; break;
1024 case WID_SA_RIGHT: spr->x_offs += amt; break;
1025 }
1026 /* Of course, we need to redraw the sprite, but where is it used?
1027 * Everywhere is a safe bet. */
1029 break;
1030 }
1031
1032 case WID_SA_RESET_REL:
1033 /* Reset the starting offsets for the current sprite. */
1034 this->offs_start_map.erase(this->current_sprite);
1035 this->SetDirty();
1036 break;
1037
1038 case WID_SA_CENTRE:
1039 SpriteAlignerWindow::centre = !SpriteAlignerWindow::centre;
1040 this->SetWidgetLoweredState(widget, SpriteAlignerWindow::centre);
1041 this->SetDirty();
1042 break;
1043
1044 case WID_SA_CROSSHAIR:
1045 SpriteAlignerWindow::crosshair = !SpriteAlignerWindow::crosshair;
1046 this->SetWidgetLoweredState(widget, SpriteAlignerWindow::crosshair);
1047 this->SetDirty();
1048 break;
1049
1050 default:
1052 SpriteAlignerWindow::zoom = static_cast<ZoomLevel>(widget - WID_SA_ZOOM);
1053 this->InvalidateData(0, true);
1054 }
1055 break;
1056 }
1057 }
1058
1059 void OnQueryTextFinished(std::optional<std::string> str) override
1060 {
1061 if (!str.has_value()) return;
1062
1063 auto value = ParseInteger(*str, 10, true);
1064 if (!value.has_value()) return;
1065 this->current_sprite = *value;
1066 if (this->current_sprite >= GetMaxSpriteID()) this->current_sprite = 0;
1067 while (GetSpriteType(this->current_sprite) != SpriteType::Normal) {
1068 this->current_sprite = (this->current_sprite + 1) % GetMaxSpriteID();
1069 }
1070 this->SelectAction5Type();
1071 this->SetDirty();
1072 }
1073
1079 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1080 {
1081 if (!gui_scope) return;
1082 if (data == 1) {
1083 /* Sprite picker finished */
1085 this->vscroll->SetCount(_newgrf_debug_sprite_picker.sprites.size());
1086 }
1087
1088 SpriteAlignerWindow::zoom = Clamp(SpriteAlignerWindow::zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max);
1090 this->SetWidgetsDisabledState(z < _settings_client.gui.zoom_min || z > _settings_client.gui.zoom_max, WID_SA_ZOOM + to_underlying(z));
1091 this->SetWidgetsLoweredState(SpriteAlignerWindow::zoom == z, WID_SA_ZOOM + to_underlying(z));
1092 }
1093 }
1094
1095 void OnResize() override
1096 {
1097 this->vscroll->SetCapacityFromWidget(this, WID_SA_LIST);
1098 }
1099
1100private:
1101 void SelectAction5Type()
1102 {
1103 const auto act5types = GetAction5Types();
1104 for (auto it = std::begin(act5types); it != std::end(act5types); ++it) {
1105 if (it->sprite_base <= this->current_sprite && this->current_sprite < it->sprite_base + it->max_sprites) {
1106 this->act5_type = &*it;
1107 return;
1108 }
1109 }
1110 this->act5_type = nullptr;
1111 }
1112};
1113
1114bool SpriteAlignerWindow::centre = true;
1115bool SpriteAlignerWindow::crosshair = true;
1116
1117static constexpr std::initializer_list<NWidgetPart> _nested_sprite_aligner_widgets = {
1123 EndContainer(),
1128 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SA_PREVIOUS), SetStringTip(STR_SPRITE_ALIGNER_PREVIOUS_BUTTON, STR_SPRITE_ALIGNER_PREVIOUS_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1129 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SA_GOTO), SetStringTip(STR_SPRITE_ALIGNER_GOTO_BUTTON, STR_SPRITE_ALIGNER_GOTO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1130 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SA_NEXT), SetStringTip(STR_SPRITE_ALIGNER_NEXT_BUTTON, STR_SPRITE_ALIGNER_NEXT_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1131 EndContainer(),
1133 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
1134 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_SA_UP), SetSpriteTip(SPR_ARROW_UP, STR_SPRITE_ALIGNER_MOVE_TOOLTIP), SetResize(0, 0), SetMinimalSize(11, 11),
1135 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
1136 EndContainer(),
1139 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(0, 1),
1140 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_SA_LEFT), SetSpriteTip(SPR_ARROW_LEFT, STR_SPRITE_ALIGNER_MOVE_TOOLTIP), SetResize(0, 0), SetMinimalSize(11, 11),
1141 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(0, 1),
1142 EndContainer(),
1143 NWidget(WWT_PANEL, Colours::DarkBlue, WID_SA_SPRITE), SetToolTip(STR_SPRITE_ALIGNER_SPRITE_TOOLTIP), SetResize(1, 1), SetFill(1, 1),
1144 EndContainer(),
1146 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(0, 1),
1147 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_SA_RIGHT), SetSpriteTip(SPR_ARROW_RIGHT, STR_SPRITE_ALIGNER_MOVE_TOOLTIP), SetResize(0, 0), SetMinimalSize(11, 11),
1148 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(0, 1),
1149 EndContainer(),
1150 EndContainer(),
1152 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
1153 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_SA_DOWN), SetSpriteTip(SPR_ARROW_DOWN, STR_SPRITE_ALIGNER_MOVE_TOOLTIP), SetResize(0, 0), SetMinimalSize(11, 11),
1154 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(1, 0),
1155 EndContainer(),
1159 NWidget(WWT_TEXTBTN_2, Colours::Grey, WID_SA_CENTRE), SetStringTip(STR_SPRITE_ALIGNER_CENTRE_OFFSET), SetFill(1, 0), SetResize(1, 0),
1160 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SA_RESET_REL), SetStringTip(STR_SPRITE_ALIGNER_RESET_BUTTON, STR_SPRITE_ALIGNER_RESET_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1161 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SA_CROSSHAIR), SetStringTip(STR_SPRITE_ALIGNER_CROSSHAIR), SetFill(1, 0), SetResize(1, 0),
1162 EndContainer(),
1163 EndContainer(),
1165 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SA_PICKER), SetStringTip(STR_SPRITE_ALIGNER_PICKER_BUTTON, STR_SPRITE_ALIGNER_PICKER_TOOLTIP), SetFill(1, 0),
1169 EndContainer(),
1171 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SA_ZOOM + to_underlying(ZoomLevel::In4x)), SetStringTip(STR_CONFIG_SETTING_ZOOM_LVL_MIN), SetFill(1, 0),
1172 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SA_ZOOM + to_underlying(ZoomLevel::In2x)), SetStringTip(STR_CONFIG_SETTING_ZOOM_LVL_IN_2X), SetFill(1, 0),
1173 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SA_ZOOM + to_underlying(ZoomLevel::Normal)), SetStringTip(STR_CONFIG_SETTING_ZOOM_LVL_NORMAL), SetFill(1, 0),
1174 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SA_ZOOM + to_underlying(ZoomLevel::Out2x)), SetStringTip(STR_CONFIG_SETTING_ZOOM_LVL_OUT_2X), SetFill(1, 0),
1175 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SA_ZOOM + to_underlying(ZoomLevel::Out4x)), SetStringTip(STR_CONFIG_SETTING_ZOOM_LVL_OUT_4X), SetFill(1, 0),
1176 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SA_ZOOM + to_underlying(ZoomLevel::Out8x)), SetStringTip(STR_CONFIG_SETTING_ZOOM_LVL_OUT_8X), SetFill(1, 0),
1177 EndContainer(),
1178 EndContainer(),
1179 EndContainer(),
1181 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1183 EndContainer(),
1184 EndContainer(),
1185};
1186
1189 WindowPosition::Automatic, "sprite_aligner", 400, 300,
1190 WindowClass::SpriteAligner, WindowClass::None,
1191 {},
1192 _nested_sprite_aligner_widgets
1193);
1194
Class for backupping variables and making sure they are restored later.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
std::string label
Label of badge.
StringID name
Short name.
Iterate a range of enum values.
Flat set implementation that uses a sorted vector for storage.
Helper class to wrap some functionality/queries in.
virtual std::span< const BadgeID > GetBadges(uint index) const =0
Get the list of badges of this item.
virtual uint Resolve(uint index, uint var, uint param, bool &avail) const =0
Resolve (action2) variable for a given index.
virtual const void * GetSpec(uint index) const =0
Get (NewGRF) specs given an index.
virtual bool IsInspectable(uint index) const =0
Is the item with the given index inspectable?
virtual const void * GetInstance(uint index) const =0
Get the instance given an index.
virtual ~NIHelper()=default
Ensure the destructor of the sub classes are called as well.
virtual const std::span< int32_t > GetPSA(uint index, GrfID grfid) const
Gets the span containing the persistent storage.
virtual std::string GetName(uint index) const =0
Get the name of this item.
virtual bool PSAWithParameter() const
Used to decide if the PSA needs a parameter or not.
virtual GrfID GetGRFID(uint index) const =0
Get the GRFID of the file that includes this item.
virtual uint GetParent(uint index) const =0
Get the parent "window_number" of a given instance.
Baseclass for nested widgets.
uint resize_y
Vertical resize step (0 means not resizable).
const std::string & GetSimplifiedFilename() const
Get the simplified filename of the opened file.
Scrollbar data structure.
size_type GetCapacity() const
Gets the number of visible elements of the scrollbar.
void SetCount(size_t num)
Sets the number of elements in the list.
auto GetScrolledItemFromWidget(Tcontainer &container, int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Return an iterator pointing to the element of a scrolled widget that a user clicked in.
size_type GetScrolledRowFromWidget(int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Compute the row of a scrolled widget that a user clicked in.
Definition widget.cpp:2474
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition widget.cpp:2548
auto GetVisibleRangeIterators(Tcontainer &container) const
Get a pair of iterators for the range of visible elements in a container.
size_type GetPosition() const
Gets the position of the first visible element in the list.
RandomAccessFile with some extra information specific for sprite files.
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
A type is considered 'convertible through base()' when it has a 'base()' function that returns someth...
VehicleCellSize GetVehicleImageCellSize(VehicleType type, EngineImageType image_type)
Get the GUI cell size for a vehicle image.
Base class for engines.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
@ ForceRight
Force align to the right.
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
void DrawRectOutline(const Rect &r, PixelColour colour, int width, int dash)
Draw the outline of a Rect.
Definition gfx.cpp:459
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
ZoomLevel _gui_zoom
GUI Zoom level.
Definition gfx.cpp:57
bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
Set up a clipping area for only drawing into a certain area.
Definition gfx.cpp:1567
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
@ Normal
The most basic (normal) sprite.
Definition gfx_type.h:405
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
@ White
White.
Definition gfx_type.h:300
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ DarkBlue
Dark blue.
Definition gfx_type.h:285
@ Grey
Grey.
Definition gfx_type.h:299
@ NoShade
Do not add shading to this text colour.
Definition gfx_type.h:342
@ White
White colour.
Definition gfx_type.h:330
@ Grey
Grey colour.
Definition gfx_type.h:332
@ Black
Black colour.
Definition gfx_type.h:334
constexpr NWidgetPart SetMatrixDataTip(uint32_t cols, uint32_t rows, StringID tip={})
Widget part function for setting the data and tooltip of WWT_MATRIX widgets.
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetSpriteTip(SpriteID sprite, StringID tip={})
Widget part function for setting the sprite and tooltip.
constexpr NWidgetPart SetResizeWidgetTypeTip(ResizeWidgetType widget_type, StringID tip)
Widget part function for setting the resize widget type and tooltip.
constexpr NWidgetPart SetPIP(uint8_t pre, uint8_t inter, uint8_t post)
Widget part function for setting a pre/inter/post spaces.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetPadding(uint8_t top, uint8_t right, uint8_t bottom, uint8_t left)
Widget part function for setting additional space around a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetArrowWidgetTypeTip(ArrowWidgetType widget_type, StringID tip={})
Widget part function for setting the arrow widget type and tooltip.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
Base of all industries.
#define Point
Macro that prevents name conflicts between included headers.
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
void ShowQueryString(std::string_view str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
Show a query popup window with a textbox in it.
GrfSpecFeature
Definition newgrf.h:81
@ RoadStops
Road stops feature.
Definition newgrf.h:102
@ RailTypes
Rail types feature.
Definition newgrf.h:98
@ Trains
Trains feature.
Definition newgrf.h:82
@ RoadVehicles
Road vehicles feature.
Definition newgrf.h:83
@ RoadTypes
Road types feature.
Definition newgrf.h:100
@ Invalid
An invalid spec feature.
Definition newgrf.h:112
@ Ships
Ships feature.
Definition newgrf.h:84
@ Houses
Houses feature.
Definition newgrf.h:89
@ FakeEnd
End of the fake features.
Definition newgrf.h:108
@ Stations
Stations feature.
Definition newgrf.h:86
@ Aircraft
Aircraft feature.
Definition newgrf.h:85
@ IndustryTiles
Industry tiles feature.
Definition newgrf.h:91
@ Objects
Objects feature.
Definition newgrf.h:97
@ AirportTiles
Airport tiles feature.
Definition newgrf.h:99
std::span< const Action5Type > GetAction5Types()
Get list of all action 5 types.
Information about NewGRF Action 5.
NewGRF handling of airports.
NewGRF handling of airport tiles.
Badge * GetBadge(BadgeID index)
Get a badge if it exists.
Functions related to NewGRF badges.
AirportTileCallbackMask
Callback masks for airport tiles.
StationCallbackMask
Callback masks for stations.
EnumBitSet< VehicleCallbackMask, uint16_t > VehicleCallbackMasks
Bitset of VehicleCallbackMask elements.
VehicleCallbackMask
Callback masks for vehicles, indicates which callbacks are used by a vehicle.
CargoCallbackMask
Callback masks for cargoes.
IndustryCallbackMask
Callback masks for Industries.
EnumBitSet< ObjectCallbackMask, uint8_t > ObjectCallbackMasks
Bitset of ObjectCallbackMask elements.
EnumBitSet< HouseCallbackMask, uint16_t > HouseCallbackMasks
Bitset of HouseCallbackMask elements.
CanalCallbackMask
Callback masks for canals.
EnumBitSet< AirportTileCallbackMask, uint8_t > AirportTileCallbackMasks
Bitset of AirportTileCallbackMask elements.
ObjectCallbackMask
Callback masks for objects.
EnumBitSet< CargoCallbackMask, uint8_t > CargoCallbackMasks
Bitset of CargoCallbackMask elements.
EnumBitSet< CanalCallbackMask, uint8_t > CanalCallbackMasks
Bitset of CanalCallbackMask elements.
RoadStopCallbackMask
Callback masks for road stops.
EnumBitSet< StationCallbackMask, uint16_t > StationCallbackMasks
Bitset of StationCallbackMask elements.
IndustryTileCallbackMask
Callback masks for industry tiles.
EnumBitSet< IndustryTileCallbackMask, uint8_t > IndustryTileCallbackMasks
Bitset of IndustryTileCallbackMask elements.
HouseCallbackMask
Callback masks for houses.
EnumBitSet< IndustryCallbackMask, uint16_t > IndustryCallbackMasks
Bitset of IndustryCallbackMask elements.
EnumBitSet< RoadStopCallbackMask, uint8_t > RoadStopCallbackMasks
Bitset of RoadStopCallbackMask elements.
Functions/types related to NewGRF debugging.
NewGrfDebugSpritePicker _newgrf_debug_sprite_picker
The sprite picker.
Data 'tables' for NewGRF debugging.
static const EnumIndexArray< const NIFeature *, GrfSpecFeature, GrfSpecFeature::FakeEnd > _nifeatures
Table with all NIFeatures.
static uint GetInspectWindowNumber(GrfSpecFeature feature, uint index)
Get the window number for the inspect window given a feature and index.
static WindowDesc _newgrf_inspect_desc(WindowPosition::Automatic, "newgrf_inspect", 400, 300, WindowClass::NewGRFInspect, WindowClass::None, {}, _nested_newgrf_inspect_widgets)
Window definition for the NewGRF inspection window.
NIType
The type of a property to show.
@ Integer
The property is a simple integer.
@ Cargo
The property is a cargo.
void ShowSpriteAlignerWindow()
Show the window for aligning sprites.
GrfSpecFeature GetGrfSpecFeature(TileIndex tile)
Get the GrfSpecFeature associated with the tile.
void InvalidateNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Invalidate the inspect window for a given feature and index.
static const NIFeature * GetFeature(uint window_number)
Get the NIFeature related to the window number.
void ShowNewGRFInspectWindow(GrfSpecFeature feature, uint index, const GrfID grfid)
Show the inspect window for a given feature and index.
static WindowDesc _sprite_aligner_desc(WindowPosition::Automatic, "sprite_aligner", 400, 300, WindowClass::SpriteAligner, WindowClass::None, {}, _nested_sprite_aligner_widgets)
Window definition for the sprite aligner window.
bool IsNewGRFInspectable(GrfSpecFeature feature, uint index)
Can we inspect the data given a certain feature and index.
static const NIHelper & GetFeatureHelper(uint window_number)
Get the NIHelper related to the window number.
static uint GetFeatureIndex(uint window_number)
Get the feature index related to the window number.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
static WindowDesc _newgrf_inspect_chain_desc(WindowPosition::Automatic, "newgrf_inspect_chain", 400, 300, WindowClass::NewGRFInspect, WindowClass::None, {}, _nested_newgrf_inspect_chain_widgets)
Window definition for the NewGRF chain inspection window.
static GrfSpecFeature GetFeatureNum(uint window_number)
Get the feature number related to the window number.
NewGrfDebugSpritePicker _newgrf_debug_sprite_picker
The sprite picker.
Types related to the newgrf debug widgets.
@ WID_NGRFI_VEH_CHAIN
Display for vehicle chain.
@ WID_NGRFI_PARENT
Inspect the parent.
@ WID_NGRFI_MAINPANEL
Panel widget containing the actual data.
@ WID_NGRFI_VEH_NEXT
Go to next vehicle in chain.
@ WID_NGRFI_CAPTION
The caption bar of course.
@ WID_NGRFI_VEH_PREV
Go to previous vehicle in chain.
@ WID_NGRFI_SCROLLBAR
Scrollbar.
@ WID_SA_NEXT
Skip to the next sprite.
@ WID_SA_CAPTION
Caption of the window.
@ WID_SA_SPRITE
The actual sprite.
@ WID_SA_PICKER
Sprite picker.
@ WID_SA_SCROLLBAR
Scrollbar for sprite list.
@ WID_SA_OFFSETS_ABS
The sprite offsets (absolute).
@ WID_SA_PREVIOUS
Skip to the previous sprite.
@ WID_SA_OFFSETS_REL
The sprite offsets (relative).
@ WID_SA_CROSSHAIR
Toggle crosshair.
@ WID_SA_GOTO
Go to a given sprite.
@ WID_SA_DOWN
Move the sprite down.
@ WID_SA_ZOOM
Zoom level buttons (from ZoomLevel::Begin to ZoomLevel::Max).
@ WID_SA_UP
Move the sprite up.
@ WID_SA_RESET_REL
Reset relative sprite offset.
@ WID_SA_LIST
Queried sprite list.
@ WID_SA_RIGHT
Move the sprite to the right.
@ WID_SA_LEFT
Move the sprite to the left.
@ WID_SA_CENTRE
Toggle centre sprite.
Functions for NewGRF industries.
NewGRF handling of industry tiles.
Functions related to NewGRF objects.
NewGRF handling of rail types.
Action 2 handling.
Header file for NewGRF stations.
Functions to handle the town part of NewGRF towns.
Label< struct GrfIDTag > GrfID
The unique identifier of a NewGRF.
Definition newgrf_type.h:17
Base for all objects.
static constexpr PixelColour PC_WHITE
White palette colour.
static constexpr PixelColour PC_LIGHT_BLUE
Light blue palette colour.
bool IsLevelCrossing(Tile t)
Return whether a tile is a level crossing.
Definition road_map.h:69
Road vehicle states.
A number of safeguards to prevent using unsafe methods.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
SpriteType GetSpriteType(SpriteID sprite)
Get the sprite type of a given sprite.
SpriteID GetMaxSpriteID()
Get a reasonable (upper bound) estimate of the maximum SpriteID used in OpenTTD; there will be no spr...
std::span< const std::unique_ptr< SpriteFile > > GetCachedSpriteFiles()
Get the list of cached SpriteFiles.
SpriteFile * GetOriginFile(SpriteID sprite)
Get the SpriteFile of a given sprite.
uint32_t GetSpriteLocalID(SpriteID sprite)
Get the GRF-local sprite id of a given sprite.
Functions to cache sprites in memory.
static const SpriteID SPR_ARROW_RIGHT
Definition sprites.h:88
static const SpriteID SPR_OPENTTD_BASE
Definition sprites.h:60
static const SpriteID SPR_ARROW_LEFT
Definition sprites.h:87
static const SpriteID SPR_ARROW_DOWN
Definition sprites.h:85
static const SpriteID SPR_ARROW_UP
Definition sprites.h:86
Base classes/functions for stations.
StationType GetStationType(Tile t)
Get the station type of this tile.
Definition station_map.h:42
@ Rail
Railways/train station.
@ Bus
Road stop for busses.
@ Truck
Road stop for trucks.
@ Airport
Airports and heliports, excluding the ones on oil rigs.
Definition of base types and functions in a cross-platform compatible way.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:76
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
Definition string.cpp:118
Parse strings.
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
Functions related to low-level strings.
@ CS_HEXADECIMAL
Only hexadecimal characters.
Definition string_type.h:30
@ CS_NUMERAL
Only numeric ones.
Definition string_type.h:26
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
uint64_t GetParamMaxDigits(uint count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:217
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
@ TD_RTL
Text is written right-to-left by default.
Information about a single action 5 type.
Definition newgrf_act5.h:23
SpriteID sprite_base
Load the sprites starting from this sprite.
Definition newgrf_act5.h:25
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
Data about how and where to blit pixels.
Definition gfx_type.h:157
Container for the text colour and some text colour related flags for drawing.
Definition gfx_type.h:349
Representation of the available callbacks with information on when they actually apply.
std::string_view name
The human readable name of the callback.
uint16_t cb_id
The number of the callback.
NIReadProc * read_proc
Callback proc to get the actual variable from memory.
std::variant< std::monostate, VehicleCallbackMask, StationCallbackMask, RoadStopCallbackMask, HouseCallbackMask, CanalCallbackMask, CargoCallbackMask, IndustryCallbackMask, IndustryTileCallbackMask, ObjectCallbackMask, AirportTileCallbackMask > cb_bit
The bit that needs to be set for this callback to be enabled.
Container for all information for a given feature.
std::span< const NICallback > callbacks
The callbacks associated with this feature.
std::span< const NIVariable > variables
The variables associated with this feature.
std::span< const NIProperty > properties
The properties associated with this feature.
std::unique_ptr< const NIHelper > helper
The class container all helper functions.
Representation of the data from a NewGRF property.
NIReadProc * read_proc
Callback proc to get the actual variable from memory.
NIType type
Type of property for chosing the appropriate representation.
std::string_view name
A (human readable) name for the property.
uint8_t prop
The number of the property.
Representation on the NewGRF variables.
Window used for inspecting NewGRFs.
GrfID caller_grfid
GRFID of the caller of this window, 0 if it has no caller.
static EnumIndexArray< std::array< uint32_t, 0x20 >, GrfSpecFeature, GrfSpecFeature::FakeEnd > var60params
The value for the variable 60 parameters.
static bool HasVariableParameter(uint variable)
Check whether the given variable has a parameter.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void DrawMainPanelWidget(const Rect &r) const
Helper function to draw the main panel widget.
void SetCallerGRFID(GrfID grfid)
Set the GRFID of the item opening this window.
void ValidateChainIndex()
Ensure that this->chain_index is in range.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
void DrawString(const Rect &r, int offset, const std::string &string) const
Helper function to draw a string (line) in the window.
bool HasChainIndex() const
Check whether this feature has chain index, i.e.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void DrawVehicleChainWidget(const Rect &r) const
Helper function to draw the vehicle chain widget.
VehicleType GetVehicleTypeForWindow() const
Get the vehicle type corresponding to the grf feature for this window.
uint GetFeatureIndex() const
Get the feature index.
uint8_t current_edit_param
The currently edited parameter, to update the right one.
void OnResize() override
Called after the window got resized.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
uint chain_index
For ground vehicles: Index in vehicle chain.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
Spritepicker of SpriteAligner.
static Vehicle * Get(auto index)
Specification of a rectangle with absolute coordinates of all edges.
int Width() const
Get width of Rect.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
int Height() const
Get height of Rect.
Rect Translate(int x, int y) const
Copy and translate Rect by x,y pixels.
Rect Expand(int s) const
Copy and expand Rect by s pixels.
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a road vehicle image in the GUI.
static Train * From(Vehicle *v)
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
const Action5Type * act5_type
Sprite Area of current selected sprite.
void OnResize() override
Called after the window got resized.
SpriteID current_sprite
The currently shown sprite.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
std::map< SpriteID, Coord2D< int16_t > > offs_start_map
Mapping of starting offsets for the sprites which have been aligned in the sprite aligner window.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
Data structure describing a sprite.
uint16_t width
Width of the sprite.
uint16_t height
Height of the sprite.
int16_t y_offs
Number of pixels to shift the sprite downwards.
int16_t x_offs
Number of pixels to shift the sprite to the right.
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a train vehicle image in the GUI.
uint height
Vehicle cell height.
Definition vehicle_gui.h:83
Vehicle data structure.
Vehicle * Move(int n)
Get the vehicle at offset n of this vehicle chain.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Vehicle * Next() const
Get the next vehicle of this vehicle.
High level window description.
Definition window_gui.h:171
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
Definition window.cpp:3317
void RaiseWidget(WidgetID widget_index)
Marks a widget as raised.
Definition window_gui.h:468
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
virtual void ShowNewGRFInspectWindow() const
Show the NewGRF inspection window.
Definition window_gui.h:894
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void SetWidgetsDisabledState(bool disab_stat, Args... widgets)
Sets the enabled/disabled status of a list of widgets.
Definition window_gui.h:514
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
void SetWidgetsLoweredState(bool lowered_stat, Args... widgets)
Sets the lowered/raised status of a list of widgets.
Definition window_gui.h:525
void SetWidgetLoweredState(WidgetID widget_index, bool lowered_stat)
Sets the lowered/raised status of a widget.
Definition window_gui.h:440
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
void LowerWidget(WidgetID widget_index)
Marks a widget as lowered.
Definition window_gui.h:459
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
int height
Height of the window (number of pixels down in y direction).
Definition window_gui.h:311
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
Stuff related to the text buffer GUI.
static TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition tile_map.h:96
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
@ Station
A tile of a station or airport.
Definition tile_type.h:54
@ Object
Contains objects such as transmitters and owned land.
Definition tile_type.h:59
@ Industry
Part of an industry.
Definition tile_type.h:57
@ Railway
A tile with railway.
Definition tile_type.h:50
@ House
A house by a town.
Definition tile_type.h:52
@ Road
A tile with road and/or tram tracks.
Definition tile_type.h:51
Base of the town class.
Base for the train class.
Base class for all vehicles.
void DrawVehicleImage(const Vehicle *v, const Rect &r, VehicleID selection, EngineImageType image_type, int skip)
Draws an image of a vehicle chain.
Functions related to the vehicle's GUIs.
@ InDepot
Vehicle drawn in depot.
@ InDetails
Vehicle drawn in vehicle details, refit window, ...
VehicleType
Available vehicle types.
@ Ship
Ship vehicle type.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
Draw frame rectangle.
Definition widget.cpp:308
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ WWT_PUSHIMGBTN
Normal push-button (no toggle button) with image caption.
@ WWT_PUSHARROWBTN
Normal push-button (no toggle button) with arrow caption.
@ WWT_LABEL
Centered label.
Definition widget_type.h:48
@ NWID_SPACER
Invisible widget that takes some space.
Definition widget_type.h:70
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_TEXTBTN
(Toggle) Button with text
Definition widget_type.h:44
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_STICKYBOX
Sticky box (at top-right of a window, after WWT_DEFSIZEBOX).
Definition widget_type.h:57
@ WWT_MATRIX
Grid of rows and columns.
Definition widget_type.h:50
@ WWT_SHADEBOX
Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX).
Definition widget_type.h:55
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ WWT_TEXTBTN_2
(Toggle) Button with diff text when clicked
Definition widget_type.h:45
@ WWT_EMPTY
Empty widget, place holder to reserve space in widget tree.
Definition widget_type.h:37
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX).
Definition widget_type.h:56
@ NWID_HORIZONTAL_LTR
Horizontal container that doesn't change the order of the widgets for RTL languages.
Definition widget_type.h:67
@ EqualSize
Containers should keep all their (resizing) children equally large.
@ Decrease
Arrow to the left or in case of RTL to the right.
Definition widget_type.h:20
@ Increase
Arrow to the right or in case of RTL to the left.
Definition widget_type.h:21
@ HideBevel
Bevel of resize box is hidden.
Definition widget_type.h:29
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
@ BorderOnly
Draw border only, no background.
Definition window_gui.h:25
Twindow * AllocateWindowDescFront(WindowDesc &desc, WindowNumber window_number, Targs... extra_arguments)
Open a new window.
@ Automatic
Find a place automatically.
Definition window_gui.h:145
int WidgetID
Widget ID.
Definition window_type.h:21
Functions related to zooming.
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:22
int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:34
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:20
@ In2x
Zoomed 2 times in.
Definition zoom_type.h:25
@ End
End for iteration.
Definition zoom_type.h:31
@ Out2x
Zoomed 2 times out.
Definition zoom_type.h:27
@ Normal
The normal zoom level.
Definition zoom_type.h:26
@ In4x
Zoomed 4 times in.
Definition zoom_type.h:24
@ Out8x
Zoomed 8 times out.
Definition zoom_type.h:29
@ Out4x
Zoomed 4 times out.
Definition zoom_type.h:28