1#include "touch_controls.h"
2
3#include <base/color.h>
4#include <base/dbg.h>
5#include <base/io.h>
6#include <base/log.h>
7#include <base/str.h>
8#include <base/time.h>
9
10#include <engine/client.h>
11#include <engine/console.h>
12#include <engine/external/json-parser/json.h>
13#include <engine/shared/config.h>
14#include <engine/shared/jsonwriter.h>
15#include <engine/shared/localization.h>
16
17#include <game/client/components/camera.h>
18#include <game/client/components/chat.h>
19#include <game/client/components/console.h>
20#include <game/client/components/controls.h>
21#include <game/client/components/emoticon.h>
22#include <game/client/components/menus.h>
23#include <game/client/components/spectator.h>
24#include <game/client/components/voting.h>
25#include <game/client/gameclient.h>
26#include <game/localization.h>
27
28#include <algorithm>
29#include <cstdlib>
30#include <functional>
31#include <iterator>
32#include <queue>
33
34using namespace std::chrono_literals;
35
36// TODO: Add combined weapon picker button that shows all currently available weapons
37// TODO: Add "joystick-aim-relative", a virtual joystick that moves the mouse pointer relatively. And add "aim-relative" ingame direct touch input.
38// TODO: Add "choice" predefined behavior which shows a selection popup for 2 or more other behaviors?
39// TODO: Support changing labels of menu buttons (or support overriding label for all predefined button behaviors)?
40
41static constexpr const char *const ACTION_NAMES[] = {Localizable(pStr: "Aim"), Localizable(pStr: "Fire"), Localizable(pStr: "Hook")};
42static constexpr const char *const ACTION_SWAP_NAMES[] = {/* unused */ "", Localizable(pStr: "Active: Fire"), Localizable(pStr: "Active: Hook")};
43static constexpr const char *const ACTION_COMMANDS[] = {/* unused */ "", "+fire", "+hook"};
44
45static constexpr std::chrono::milliseconds LONG_TOUCH_DURATION = 500ms;
46static constexpr std::chrono::milliseconds BIND_REPEAT_INITIAL_DELAY = 250ms;
47static constexpr std::chrono::nanoseconds BIND_REPEAT_RATE = std::chrono::nanoseconds(1s) / 15;
48
49static constexpr const char *const CONFIGURATION_FILENAME = "touch_controls.json";
50
51/* This is required for the localization script to find the labels of the default bind buttons specified in the configuration file:
52Localizable("Move left") Localizable("Move right") Localizable("Jump") Localizable("Prev. weapon") Localizable("Next weapon")
53Localizable("Zoom out") Localizable("Default zoom") Localizable("Zoom in") Localizable("Scoreboard") Localizable("Chat") Localizable("Team chat")
54Localizable("Vote yes") Localizable("Vote no") Localizable("Toggle dummy")
55*/
56
57CTouchControls::CTouchButton::CTouchButton(CTouchControls *pTouchControls) :
58 m_pTouchControls(pTouchControls),
59 m_UnitRect({.m_X: 0, .m_Y: 0, .m_W: BUTTON_SIZE_MINIMUM, .m_H: BUTTON_SIZE_MINIMUM}),
60 m_Shape(EButtonShape::RECT),
61 m_pBehavior(nullptr),
62 m_VisibilityCached(false)
63{
64}
65
66CTouchControls::CTouchButton::CTouchButton(CTouchButton &&Other) noexcept :
67 m_pTouchControls(Other.m_pTouchControls),
68 m_UnitRect(Other.m_UnitRect),
69 m_Shape(Other.m_Shape),
70 m_vVisibilities(Other.m_vVisibilities),
71 m_pBehavior(std::move(Other.m_pBehavior)),
72 m_VisibilityCached(false)
73{
74 Other.m_pTouchControls = nullptr;
75 UpdatePointers();
76 UpdateScreenFromUnitRect();
77}
78
79CTouchControls::CTouchButton &CTouchControls::CTouchButton::operator=(CTouchButton &&Other) noexcept
80{
81 if(this == &Other)
82 {
83 return *this;
84 }
85 m_pTouchControls = Other.m_pTouchControls;
86 Other.m_pTouchControls = nullptr;
87 m_UnitRect = Other.m_UnitRect;
88 m_Shape = Other.m_Shape;
89 m_vVisibilities = Other.m_vVisibilities;
90 m_pBehavior = std::move(Other.m_pBehavior);
91 m_VisibilityCached = false;
92 UpdatePointers();
93 UpdateScreenFromUnitRect();
94 return *this;
95}
96
97void CTouchControls::CTouchButton::UpdatePointers()
98{
99 m_pBehavior->Init(pTouchButton: this);
100}
101
102void CTouchControls::CTouchButton::UpdateScreenFromUnitRect()
103{
104 m_ScreenRect = m_pTouchControls->CalculateScreenFromUnitRect(Unit: m_UnitRect, Shape: m_Shape);
105}
106
107CUIRect CTouchControls::CalculateScreenFromUnitRect(CUnitRect Unit, EButtonShape Shape) const
108{
109 Unit = CalculateHitbox(Rect: Unit, Shape);
110 const vec2 ScreenSize = CalculateScreenSize();
111 CUIRect ScreenRect;
112 ScreenRect.x = Unit.m_X * ScreenSize.x / BUTTON_SIZE_SCALE;
113 ScreenRect.y = Unit.m_Y * ScreenSize.y / BUTTON_SIZE_SCALE;
114 ScreenRect.w = Unit.m_W * ScreenSize.x / BUTTON_SIZE_SCALE;
115 ScreenRect.h = Unit.m_H * ScreenSize.y / BUTTON_SIZE_SCALE;
116 return ScreenRect;
117}
118
119CTouchControls::CUnitRect CTouchControls::CalculateHitbox(const CUnitRect &Rect, EButtonShape Shape) const
120{
121 switch(Shape)
122 {
123 case EButtonShape::RECT: return Rect;
124 case EButtonShape::CIRCLE:
125 {
126 const vec2 ScreenSize = CalculateScreenSize();
127 CUnitRect Hitbox = Rect;
128 if(ScreenSize.x * Rect.m_W < ScreenSize.y * Rect.m_H)
129 {
130 Hitbox.m_Y += (ScreenSize.y * Rect.m_H - ScreenSize.x * Rect.m_W) / 2 / ScreenSize.y;
131 Hitbox.m_H = ScreenSize.x * Rect.m_W / ScreenSize.y;
132 }
133 else if(ScreenSize.x * Rect.m_W > ScreenSize.y * Rect.m_H)
134 {
135 Hitbox.m_X += (ScreenSize.x * Rect.m_W - ScreenSize.y * Rect.m_H) / 2 / ScreenSize.x;
136 Hitbox.m_W = ScreenSize.y * Rect.m_H / ScreenSize.x;
137 }
138 return Hitbox;
139 }
140 default: dbg_assert_failed("Unhandled shape");
141 }
142}
143
144void CTouchControls::CTouchButton::UpdateBackgroundCorners()
145{
146 if(m_Shape != EButtonShape::RECT)
147 {
148 m_BackgroundCorners = IGraphics::CORNER_NONE;
149 return;
150 }
151
152 // Determine rounded corners based on button layout
153 m_BackgroundCorners = IGraphics::CORNER_ALL;
154
155 if(m_UnitRect.m_X == 0)
156 {
157 m_BackgroundCorners &= ~IGraphics::CORNER_L;
158 }
159 if(m_UnitRect.m_X + m_UnitRect.m_W == BUTTON_SIZE_SCALE)
160 {
161 m_BackgroundCorners &= ~IGraphics::CORNER_R;
162 }
163 if(m_UnitRect.m_Y == 0)
164 {
165 m_BackgroundCorners &= ~IGraphics::CORNER_T;
166 }
167 if(m_UnitRect.m_Y + m_UnitRect.m_H == BUTTON_SIZE_SCALE)
168 {
169 m_BackgroundCorners &= ~IGraphics::CORNER_B;
170 }
171
172 const auto &&PointInOrOnRect = [](ivec2 Point, CUnitRect Rect) {
173 return Point.x >= Rect.m_X && Point.x <= Rect.m_X + Rect.m_W && Point.y >= Rect.m_Y && Point.y <= Rect.m_Y + Rect.m_H;
174 };
175 for(const CTouchButton &OtherButton : m_pTouchControls->m_vTouchButtons)
176 {
177 if(&OtherButton == this || OtherButton.m_Shape != EButtonShape::RECT || !OtherButton.IsVisible())
178 continue;
179
180 if((m_BackgroundCorners & IGraphics::CORNER_TL) && PointInOrOnRect(ivec2(m_UnitRect.m_X, m_UnitRect.m_Y), OtherButton.m_UnitRect))
181 {
182 m_BackgroundCorners &= ~IGraphics::CORNER_TL;
183 }
184 if((m_BackgroundCorners & IGraphics::CORNER_TR) && PointInOrOnRect(ivec2(m_UnitRect.m_X + m_UnitRect.m_W, m_UnitRect.m_Y), OtherButton.m_UnitRect))
185 {
186 m_BackgroundCorners &= ~IGraphics::CORNER_TR;
187 }
188 if((m_BackgroundCorners & IGraphics::CORNER_BL) && PointInOrOnRect(ivec2(m_UnitRect.m_X, m_UnitRect.m_Y + m_UnitRect.m_H), OtherButton.m_UnitRect))
189 {
190 m_BackgroundCorners &= ~IGraphics::CORNER_BL;
191 }
192 if((m_BackgroundCorners & IGraphics::CORNER_BR) && PointInOrOnRect(ivec2(m_UnitRect.m_X + m_UnitRect.m_W, m_UnitRect.m_Y + m_UnitRect.m_H), OtherButton.m_UnitRect))
193 {
194 m_BackgroundCorners &= ~IGraphics::CORNER_BR;
195 }
196 if(m_BackgroundCorners == IGraphics::CORNER_NONE)
197 {
198 break;
199 }
200 }
201}
202
203vec2 CTouchControls::CTouchButton::ClampTouchPosition(vec2 TouchPosition) const
204{
205 switch(m_Shape)
206 {
207 case EButtonShape::RECT:
208 {
209 TouchPosition.x = std::clamp(val: TouchPosition.x, lo: m_ScreenRect.x, hi: m_ScreenRect.x + m_ScreenRect.w);
210 TouchPosition.y = std::clamp(val: TouchPosition.y, lo: m_ScreenRect.y, hi: m_ScreenRect.y + m_ScreenRect.h);
211 break;
212 }
213 case EButtonShape::CIRCLE:
214 {
215 const vec2 Center = m_ScreenRect.Center();
216 const float MaxLength = minimum(a: m_ScreenRect.w, b: m_ScreenRect.h) / 2.0f;
217 const vec2 TouchDirection = TouchPosition - Center;
218 const float Length = length(a: TouchDirection);
219 if(Length > MaxLength)
220 {
221 TouchPosition = normalize_pre_length(v: TouchDirection, len: Length) * MaxLength + Center;
222 }
223 break;
224 }
225 default:
226 dbg_assert_failed("Unhandled shape");
227 }
228 return TouchPosition;
229}
230
231bool CTouchControls::CTouchButton::IsInside(vec2 TouchPosition) const
232{
233 switch(m_Shape)
234 {
235 case EButtonShape::RECT:
236 return m_ScreenRect.Inside(Point: TouchPosition);
237 case EButtonShape::CIRCLE:
238 return distance(a: TouchPosition, b: m_ScreenRect.Center()) <= minimum(a: m_ScreenRect.w, b: m_ScreenRect.h) / 2.0f;
239 default:
240 dbg_assert_failed("Unhandled shape");
241 return false;
242 }
243}
244
245void CTouchControls::CTouchButton::UpdateVisibilityGame()
246{
247 const bool PrevVisibility = m_VisibilityCached;
248 m_VisibilityCached = std::all_of(first: m_vVisibilities.begin(), last: m_vVisibilities.end(), pred: [&](CButtonVisibility Visibility) {
249 return m_pTouchControls->m_aVisibilityFunctions[(int)Visibility.m_Type].m_Function() == Visibility.m_Parity;
250 });
251 if(m_VisibilityCached && !PrevVisibility)
252 {
253 m_VisibilityStartTime = time_get_nanoseconds();
254 }
255}
256
257void CTouchControls::CTouchButton::UpdateVisibilityEditor()
258{
259 const bool PrevVisibility = m_VisibilityCached;
260 m_VisibilityCached = std::all_of(first: m_vVisibilities.begin(), last: m_vVisibilities.end(), pred: [&](CButtonVisibility Visibility) {
261 return m_pTouchControls->m_aVirtualVisibilities[(int)Visibility.m_Type] == Visibility.m_Parity;
262 });
263 if(m_VisibilityCached && !PrevVisibility)
264 {
265 m_VisibilityStartTime = time_get_nanoseconds();
266 }
267}
268
269bool CTouchControls::CTouchButton::IsVisible() const
270{
271 return m_VisibilityCached;
272}
273
274// TODO: Optimization: Use text and quad containers for rendering
275void CTouchControls::CTouchButton::Render(std::optional<bool> Selected, std::optional<CUnitRect> Rect) const
276{
277 dbg_assert(m_pBehavior != nullptr, "Touch button behavior is nullptr");
278 CUIRect ScreenRect;
279 if(Rect.has_value())
280 ScreenRect = m_pTouchControls->CalculateScreenFromUnitRect(Unit: *Rect, Shape: m_Shape);
281 else
282 ScreenRect = m_ScreenRect;
283
284 ColorRGBA ButtonColor;
285 // "Selected" can decide which color to use, while not disturbing the original color check.
286 ButtonColor = m_pBehavior->IsActive() || Selected.value_or(u: false) ? m_pTouchControls->m_BackgroundColorActive : m_pTouchControls->m_BackgroundColorInactive;
287 if(!Selected.value_or(u: true))
288 ButtonColor = m_pTouchControls->m_BackgroundColorInactive;
289 switch(m_Shape)
290 {
291 case EButtonShape::RECT:
292 {
293 ScreenRect.Draw(Color: ButtonColor, Corners: m_pTouchControls->m_EditingActive ? IGraphics::CORNER_NONE : m_BackgroundCorners, Rounding: 10.0f);
294 break;
295 }
296 case EButtonShape::CIRCLE:
297 {
298 const vec2 Center = ScreenRect.Center();
299 const float Radius = minimum(a: ScreenRect.w, b: ScreenRect.h) / 2.0f;
300 m_pTouchControls->Graphics()->TextureClear();
301 m_pTouchControls->Graphics()->QuadsBegin();
302 m_pTouchControls->Graphics()->SetColor(ButtonColor);
303 m_pTouchControls->Graphics()->DrawCircle(CenterX: Center.x, CenterY: Center.y, Radius, Segments: maximum(a: round_truncate(f: Radius / 4.0f) & ~1, b: 32));
304 m_pTouchControls->Graphics()->QuadsEnd();
305 break;
306 }
307 default:
308 dbg_assert_failed("Unhandled shape");
309 }
310
311 const float FontSize = 22.0f;
312 CButtonLabel LabelData = m_pBehavior->GetLabel();
313 CUIRect LabelRect;
314 ScreenRect.Margin(Cut: 10.0f, pOtherRect: &LabelRect);
315 SLabelProperties LabelProps;
316 LabelProps.m_MaxWidth = LabelRect.w;
317 if(LabelData.m_Type == CButtonLabel::EType::ICON)
318 {
319 m_pTouchControls->TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
320 m_pTouchControls->TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH | ETextRenderFlags::TEXT_RENDER_FLAG_NO_X_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_Y_BEARING);
321 m_pTouchControls->Ui()->DoLabel(pRect: &LabelRect, pText: LabelData.m_pLabel, Size: FontSize, Align: TEXTALIGN_MC, LabelProps);
322 m_pTouchControls->TextRender()->SetRenderFlags(0);
323 m_pTouchControls->TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
324 }
325 else
326 {
327 const char *pLabel = LabelData.m_Type == CButtonLabel::EType::LOCALIZED ? Localize(pStr: LabelData.m_pLabel) : LabelData.m_pLabel;
328 m_pTouchControls->Ui()->DoLabel(pRect: &LabelRect, pText: pLabel, Size: FontSize, Align: TEXTALIGN_MC, LabelProps);
329 }
330}
331
332void CTouchControls::CTouchButton::WriteToConfiguration(CJsonWriter *pWriter)
333{
334 char aBuf[256];
335
336 pWriter->BeginObject();
337
338 pWriter->WriteAttribute(pName: "x");
339 pWriter->WriteIntValue(Value: m_UnitRect.m_X);
340 pWriter->WriteAttribute(pName: "y");
341 pWriter->WriteIntValue(Value: m_UnitRect.m_Y);
342 pWriter->WriteAttribute(pName: "w");
343 pWriter->WriteIntValue(Value: m_UnitRect.m_W);
344 pWriter->WriteAttribute(pName: "h");
345 pWriter->WriteIntValue(Value: m_UnitRect.m_H);
346
347 pWriter->WriteAttribute(pName: "shape");
348 pWriter->WriteStrValue(pValue: SHAPE_NAMES[(int)m_Shape]);
349
350 pWriter->WriteAttribute(pName: "visibilities");
351 pWriter->BeginArray();
352 for(CButtonVisibility Visibility : m_vVisibilities)
353 {
354 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s%s", Visibility.m_Parity ? "" : "-", m_pTouchControls->m_aVisibilityFunctions[(int)Visibility.m_Type].m_pId);
355 pWriter->WriteStrValue(pValue: aBuf);
356 }
357 pWriter->EndArray();
358
359 pWriter->WriteAttribute(pName: "behavior");
360 pWriter->BeginObject();
361 m_pBehavior->WriteToConfiguration(pWriter);
362 pWriter->EndObject();
363
364 pWriter->EndObject();
365}
366
367void CTouchControls::CTouchButtonBehavior::Init(CTouchButton *pTouchButton)
368{
369 m_pTouchButton = pTouchButton;
370 m_pTouchControls = pTouchButton->m_pTouchControls;
371}
372
373void CTouchControls::CTouchButtonBehavior::Reset()
374{
375 m_Active = false;
376}
377
378void CTouchControls::CTouchButtonBehavior::SetActive(const IInput::CTouchFingerState &FingerState)
379{
380 const vec2 ScreenSize = m_pTouchControls->CalculateScreenSize();
381 const CUIRect ButtonScreenRect = m_pTouchButton->m_ScreenRect;
382 const vec2 Position = (m_pTouchButton->ClampTouchPosition(TouchPosition: FingerState.m_Position * ScreenSize) - ButtonScreenRect.TopLeft()) / ButtonScreenRect.Size();
383 const vec2 Delta = FingerState.m_Delta * ScreenSize / ButtonScreenRect.Size();
384 if(!m_Active)
385 {
386 m_Active = true;
387 m_ActivePosition = Position;
388 m_AccumulatedDelta = Delta;
389 m_ActivationStartTime = time_get_nanoseconds();
390 m_Finger = FingerState.m_Finger;
391 OnActivate();
392 }
393 else if(m_Finger == FingerState.m_Finger)
394 {
395 m_ActivePosition = Position;
396 m_AccumulatedDelta += Delta;
397 OnUpdate();
398 }
399 else
400 {
401 dbg_assert_failed("Touch button must be inactive or use same finger");
402 }
403}
404
405void CTouchControls::CTouchButtonBehavior::SetInactive(bool ByFinger)
406{
407 if(m_Active)
408 {
409 m_Active = false;
410 OnDeactivate(ByFinger);
411 }
412}
413
414bool CTouchControls::CTouchButtonBehavior::IsActive() const
415{
416 return m_Active;
417}
418
419bool CTouchControls::CTouchButtonBehavior::IsActive(const IInput::CTouchFinger &Finger) const
420{
421 return m_Active && m_Finger == Finger;
422}
423
424void CTouchControls::CPredefinedTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
425{
426 pWriter->WriteAttribute(pName: "type");
427 pWriter->WriteStrValue(pValue: BEHAVIOR_TYPE);
428
429 pWriter->WriteAttribute(pName: "id");
430 pWriter->WriteStrValue(pValue: m_pId);
431}
432
433// Ingame menu button: always opens ingame menu.
434CTouchControls::CButtonLabel CTouchControls::CIngameMenuTouchButtonBehavior::GetLabel() const
435{
436 return {.m_Type: CButtonLabel::EType::ICON, .m_pLabel: "\xEF\x85\x8E"};
437}
438
439void CTouchControls::CIngameMenuTouchButtonBehavior::OnDeactivate(bool ByFinger)
440{
441 if(!ByFinger)
442 return;
443 m_pTouchControls->GameClient()->m_Menus.SetActive(true);
444}
445
446// Extra menu button:
447// - Short press: show/hide additional buttons (toggle extra-menu visibilities)
448// - Long press: open ingame menu
449CTouchControls::CExtraMenuTouchButtonBehavior::CExtraMenuTouchButtonBehavior(int Number) :
450 CPredefinedTouchButtonBehavior(BEHAVIOR_ID),
451 m_Number(Number)
452{
453 if(m_Number == 0)
454 {
455 str_copy(dst&: m_aLabel, src: "\xEF\x83\x89");
456 }
457 else
458 {
459 str_format(buffer: m_aLabel, buffer_size: sizeof(m_aLabel), format: "\xEF\x83\x89%d", m_Number + 1);
460 }
461}
462
463CTouchControls::CButtonLabel CTouchControls::CExtraMenuTouchButtonBehavior::GetLabel() const
464{
465 if(m_Active && time_get_nanoseconds() - m_ActivationStartTime >= LONG_TOUCH_DURATION)
466 {
467 return {.m_Type: CButtonLabel::EType::ICON, .m_pLabel: "\xEF\x95\x90"};
468 }
469 else
470 {
471 return {.m_Type: CButtonLabel::EType::ICON, .m_pLabel: m_aLabel};
472 }
473}
474
475void CTouchControls::CExtraMenuTouchButtonBehavior::OnDeactivate(bool ByFinger)
476{
477 if(!ByFinger)
478 return;
479 if(time_get_nanoseconds() - m_ActivationStartTime >= LONG_TOUCH_DURATION)
480 {
481 m_pTouchControls->GameClient()->m_Menus.SetActive(true);
482 }
483 else
484 {
485 m_pTouchControls->m_aExtraMenuActive[m_Number] = !m_pTouchControls->m_aExtraMenuActive[m_Number];
486 }
487}
488
489void CTouchControls::CExtraMenuTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
490{
491 CPredefinedTouchButtonBehavior::WriteToConfiguration(pWriter);
492
493 pWriter->WriteAttribute(pName: "number");
494 pWriter->WriteIntValue(Value: m_Number + 1);
495}
496
497// Emoticon button: keeps the emoticon HUD open, next touch in emoticon HUD will close it again.
498CTouchControls::CButtonLabel CTouchControls::CEmoticonTouchButtonBehavior::GetLabel() const
499{
500 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: Localizable(pStr: "Emoticon")};
501}
502
503void CTouchControls::CEmoticonTouchButtonBehavior::OnDeactivate(bool ByFinger)
504{
505 if(!ByFinger)
506 return;
507 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: "+emote", ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
508}
509
510// Spectate button: keeps the spectate menu open, next touch in spectate menu will close it again.
511CTouchControls::CButtonLabel CTouchControls::CSpectateTouchButtonBehavior::GetLabel() const
512{
513 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: Localizable(pStr: "Spectator mode")};
514}
515
516void CTouchControls::CSpectateTouchButtonBehavior::OnDeactivate(bool ByFinger)
517{
518 if(!ByFinger)
519 return;
520 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: "+spectate", ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
521}
522
523// Swap action button:
524// - If joystick is currently active with one action: activate the other action.
525// - Else: swap active action.
526CTouchControls::CButtonLabel CTouchControls::CSwapActionTouchButtonBehavior::GetLabel() const
527{
528 if(m_ActiveAction != NUM_ACTIONS)
529 {
530 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_ActiveAction]};
531 }
532 else if(m_pTouchControls->m_JoystickPressCount != 0)
533 {
534 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_pTouchControls->NextActiveAction(Action: m_pTouchControls->m_ActionSelected)]};
535 }
536 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_SWAP_NAMES[m_pTouchControls->m_ActionSelected]};
537}
538
539void CTouchControls::CSwapActionTouchButtonBehavior::OnActivate()
540{
541 if(m_pTouchControls->m_JoystickPressCount != 0)
542 {
543 m_ActiveAction = m_pTouchControls->NextActiveAction(Action: m_pTouchControls->m_ActionSelected);
544 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
545 }
546 else
547 {
548 m_pTouchControls->m_ActionSelected = m_pTouchControls->NextActiveAction(Action: m_pTouchControls->m_ActionSelected);
549 }
550}
551
552void CTouchControls::CSwapActionTouchButtonBehavior::OnDeactivate(bool ByFinger)
553{
554 if(m_ActiveAction != NUM_ACTIONS)
555 {
556 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
557 m_ActiveAction = NUM_ACTIONS;
558 }
559}
560
561// Use action button: always uses the active action.
562CTouchControls::CButtonLabel CTouchControls::CUseActionTouchButtonBehavior::GetLabel() const
563{
564 if(m_ActiveAction != NUM_ACTIONS)
565 {
566 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_ActiveAction]};
567 }
568 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_pTouchControls->m_ActionSelected]};
569}
570
571void CTouchControls::CUseActionTouchButtonBehavior::OnActivate()
572{
573 m_ActiveAction = m_pTouchControls->m_ActionSelected;
574 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
575}
576
577void CTouchControls::CUseActionTouchButtonBehavior::OnDeactivate(bool ByFinger)
578{
579 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
580 m_ActiveAction = NUM_ACTIONS;
581}
582
583// Generic joystick button behavior: aim with virtual joystick and use action (defined by subclass).
584CTouchControls::CButtonLabel CTouchControls::CJoystickTouchButtonBehavior::GetLabel() const
585{
586 if(m_ActiveAction != NUM_ACTIONS)
587 {
588 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_ActiveAction]};
589 }
590 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[SelectedAction()]};
591}
592
593void CTouchControls::CJoystickTouchButtonBehavior::OnActivate()
594{
595 m_ActiveAction = SelectedAction();
596 OnUpdate();
597 if(m_ActiveAction != ACTION_AIM)
598 {
599 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
600 }
601 m_pTouchControls->m_JoystickPressCount++;
602}
603
604void CTouchControls::CJoystickTouchButtonBehavior::OnDeactivate(bool ByFinger)
605{
606 if(m_ActiveAction != ACTION_AIM)
607 {
608 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
609 }
610 m_ActiveAction = NUM_ACTIONS;
611 m_pTouchControls->m_JoystickPressCount--;
612}
613
614void CTouchControls::CJoystickTouchButtonBehavior::OnUpdate()
615{
616 CControls &Controls = m_pTouchControls->GameClient()->m_Controls;
617 if(m_pTouchControls->GameClient()->m_Snap.m_SpecInfo.m_Active)
618 {
619 vec2 WorldScreenSize;
620 m_pTouchControls->Graphics()->CalcScreenParams(Aspect: m_pTouchControls->Graphics()->ScreenAspect(), Zoom: m_pTouchControls->GameClient()->m_Camera.m_Zoom, pWidth: &WorldScreenSize.x, pHeight: &WorldScreenSize.y);
621 Controls.m_aMousePos[g_Config.m_ClDummy] += -m_AccumulatedDelta * WorldScreenSize;
622 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::RELATIVE;
623 Controls.m_aMousePos[g_Config.m_ClDummy].x = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].x, lo: -201.0f * 32, hi: (m_pTouchControls->Collision()->GetWidth() + 201.0f) * 32.0f);
624 Controls.m_aMousePos[g_Config.m_ClDummy].y = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].y, lo: -201.0f * 32, hi: (m_pTouchControls->Collision()->GetHeight() + 201.0f) * 32.0f);
625 m_AccumulatedDelta = vec2(0.0f, 0.0f);
626 }
627 else
628 {
629 const vec2 AbsolutePosition = (m_ActivePosition - vec2(0.5f, 0.5f)) * 2.0f;
630 Controls.m_aMousePos[g_Config.m_ClDummy] = AbsolutePosition * (Controls.GetMaxMouseDistance() - Controls.GetMinMouseDistance()) + normalize(v: AbsolutePosition) * Controls.GetMinMouseDistance();
631 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::ABSOLUTE;
632 if(length(a: Controls.m_aMousePos[g_Config.m_ClDummy]) < 0.001f)
633 {
634 Controls.m_aMousePos[g_Config.m_ClDummy].x = 0.001f;
635 Controls.m_aMousePos[g_Config.m_ClDummy].y = 0.0f;
636 }
637 }
638}
639
640// Joystick that uses the active action.
641void CTouchControls::CJoystickActionTouchButtonBehavior::Init(CTouchButton *pTouchButton)
642{
643 CPredefinedTouchButtonBehavior::Init(pTouchButton);
644}
645
646int CTouchControls::CJoystickActionTouchButtonBehavior::SelectedAction() const
647{
648 return m_pTouchControls->m_ActionSelected;
649}
650
651// Joystick that only aims.
652int CTouchControls::CJoystickAimTouchButtonBehavior::SelectedAction() const
653{
654 return ACTION_AIM;
655}
656
657// Joystick that always uses fire.
658int CTouchControls::CJoystickFireTouchButtonBehavior::SelectedAction() const
659{
660 return ACTION_FIRE;
661}
662
663// Joystick that always uses hook.
664int CTouchControls::CJoystickHookTouchButtonBehavior::SelectedAction() const
665{
666 return ACTION_HOOK;
667}
668
669// Bind button behavior that executes a command like a bind.
670CTouchControls::CButtonLabel CTouchControls::CBindTouchButtonBehavior::GetLabel() const
671{
672 return {.m_Type: m_LabelType, .m_pLabel: m_Label.c_str()};
673}
674
675void CTouchControls::CBindTouchButtonBehavior::OnActivate()
676{
677 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: m_Command.c_str(), ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
678 m_Repeating = false;
679}
680
681void CTouchControls::CBindTouchButtonBehavior::OnDeactivate(bool ByFinger)
682{
683 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: m_Command.c_str(), ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
684}
685
686void CTouchControls::CBindTouchButtonBehavior::OnUpdate()
687{
688 const auto Now = time_get_nanoseconds();
689 if(m_Repeating)
690 {
691 m_AccumulatedRepeatingTime += Now - m_LastUpdateTime;
692 m_LastUpdateTime = Now;
693 if(m_AccumulatedRepeatingTime >= BIND_REPEAT_RATE)
694 {
695 m_AccumulatedRepeatingTime -= BIND_REPEAT_RATE;
696 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: m_Command.c_str(), ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
697 }
698 }
699 else if(Now - m_ActivationStartTime >= BIND_REPEAT_INITIAL_DELAY)
700 {
701 m_Repeating = true;
702 m_LastUpdateTime = Now;
703 m_AccumulatedRepeatingTime = 0ns;
704 }
705}
706
707void CTouchControls::CBindTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
708{
709 pWriter->WriteAttribute(pName: "type");
710 pWriter->WriteStrValue(pValue: BEHAVIOR_TYPE);
711
712 pWriter->WriteAttribute(pName: "label");
713 pWriter->WriteStrValue(pValue: m_Label.c_str());
714
715 pWriter->WriteAttribute(pName: "label-type");
716 pWriter->WriteStrValue(pValue: LABEL_TYPE_NAMES[(int)m_LabelType]);
717
718 pWriter->WriteAttribute(pName: "command");
719 pWriter->WriteStrValue(pValue: m_Command.c_str());
720}
721
722// Bind button behavior that switches between executing one of two or more console commands.
723CTouchControls::CButtonLabel CTouchControls::CBindToggleTouchButtonBehavior::GetLabel() const
724{
725 const auto &ActiveCommand = m_vCommands[m_ActiveCommandIndex];
726 return {.m_Type: ActiveCommand.m_LabelType, .m_pLabel: ActiveCommand.m_Label.c_str()};
727}
728
729void CTouchControls::CBindToggleTouchButtonBehavior::OnActivate()
730{
731 m_pTouchControls->Console()->ExecuteLine(pStr: m_vCommands[m_ActiveCommandIndex].m_Command.c_str(), ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
732 m_ActiveCommandIndex = (m_ActiveCommandIndex + 1) % m_vCommands.size();
733}
734
735void CTouchControls::CBindToggleTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
736{
737 pWriter->WriteAttribute(pName: "type");
738 pWriter->WriteStrValue(pValue: BEHAVIOR_TYPE);
739
740 pWriter->WriteAttribute(pName: "commands");
741 pWriter->BeginArray();
742
743 for(const auto &Command : m_vCommands)
744 {
745 pWriter->BeginObject();
746
747 pWriter->WriteAttribute(pName: "label");
748 pWriter->WriteStrValue(pValue: Command.m_Label.c_str());
749
750 pWriter->WriteAttribute(pName: "label-type");
751 pWriter->WriteStrValue(pValue: LABEL_TYPE_NAMES[(int)Command.m_LabelType]);
752
753 pWriter->WriteAttribute(pName: "command");
754 pWriter->WriteStrValue(pValue: Command.m_Command.c_str());
755
756 pWriter->EndObject();
757 }
758
759 pWriter->EndArray();
760}
761
762void CTouchControls::OnInit()
763{
764 InitVisibilityFunctions();
765 if(!LoadConfigurationFromFile(StorageType: IStorage::TYPE_ALL))
766 {
767 Client()->AddWarning(Warning: SWarning(Localize(pStr: "Error loading touch controls"), Localize(pStr: "Could not load touch controls from file. See local console for details.")));
768 }
769}
770
771void CTouchControls::OnReset()
772{
773 ResetButtons();
774 m_EditingActive = false;
775}
776
777void CTouchControls::OnWindowResize()
778{
779 ResetButtons();
780 for(CTouchButton &TouchButton : m_vTouchButtons)
781 {
782 TouchButton.UpdateScreenFromUnitRect();
783 }
784}
785
786bool CTouchControls::OnTouchState(const std::vector<IInput::CTouchFingerState> &vTouchFingerStates)
787{
788 if(!g_Config.m_ClTouchControls)
789 return false;
790 if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)
791 return false;
792 if(GameClient()->m_Chat.IsActive() ||
793 GameClient()->m_GameConsole.IsActive() ||
794 GameClient()->m_Menus.IsActive() ||
795 GameClient()->m_Emoticon.IsActive() ||
796 GameClient()->m_Spectator.IsActive() ||
797 m_PreviewAllButtons)
798 {
799 ResetButtons();
800 return false;
801 }
802
803 if(m_EditingActive)
804 UpdateButtonsEditor(vTouchFingerStates);
805 else
806 UpdateButtonsGame(vTouchFingerStates);
807 return true;
808}
809
810void CTouchControls::OnRender()
811{
812 if(!g_Config.m_ClTouchControls)
813 return;
814 if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)
815 return;
816 if(GameClient()->m_Chat.IsActive() ||
817 GameClient()->m_Emoticon.IsActive() ||
818 GameClient()->m_Spectator.IsActive())
819 {
820 return;
821 }
822
823 const vec2 ScreenSize = CalculateScreenSize();
824 Graphics()->MapScreen(TopLeftX: 0.0f, TopLeftY: 0.0f, BottomRightX: ScreenSize.x, BottomRightY: ScreenSize.y);
825
826 if(m_EditingActive)
827 {
828 RenderButtonsEditor();
829 return;
830 }
831 // If not editing, deselect it.
832 m_pSelectedButton = nullptr;
833 m_pSampleButton = nullptr;
834 m_UnsavedChanges = false;
835 RenderButtonsGame();
836}
837
838bool CTouchControls::LoadConfigurationFromFile(int StorageType)
839{
840 void *pFileData;
841 unsigned FileLength;
842 if(!Storage()->ReadFile(pFilename: CONFIGURATION_FILENAME, Type: StorageType, ppResult: &pFileData, pResultLen: &FileLength))
843 {
844 log_error("touch_controls", "Failed to read configuration from '%s'", CONFIGURATION_FILENAME);
845 return false;
846 }
847
848 const bool Result = ParseConfiguration(pFileData, FileLength);
849 free(ptr: pFileData);
850 return Result;
851}
852
853bool CTouchControls::LoadConfigurationFromClipboard()
854{
855 std::string Clipboard = Input()->GetClipboardText();
856 return ParseConfiguration(pFileData: Clipboard.c_str(), FileLength: Clipboard.size());
857}
858
859bool CTouchControls::SaveConfigurationToFile()
860{
861 IOHANDLE File = Storage()->OpenFile(pFilename: CONFIGURATION_FILENAME, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
862 if(!File)
863 {
864 log_error("touch_controls", "Failed to open '%s' for writing configuration", CONFIGURATION_FILENAME);
865 return false;
866 }
867
868 CJsonFileWriter Writer(File);
869 WriteConfiguration(pWriter: &Writer);
870 return true;
871}
872
873void CTouchControls::SaveConfigurationToClipboard()
874{
875 CJsonStringWriter Writer;
876 WriteConfiguration(pWriter: &Writer);
877 std::string ConfigurationString = Writer.GetOutputString();
878 Input()->SetClipboardText(ConfigurationString.c_str());
879}
880
881void CTouchControls::InitVisibilityFunctions()
882{
883 m_aVisibilityFunctions[(int)EButtonVisibility::INGAME].m_pId = "ingame";
884 m_aVisibilityFunctions[(int)EButtonVisibility::INGAME].m_Function = [&]() {
885 return !GameClient()->m_Snap.m_SpecInfo.m_Active;
886 };
887 m_aVisibilityFunctions[(int)EButtonVisibility::ZOOM_ALLOWED].m_pId = "zoom-allowed";
888 m_aVisibilityFunctions[(int)EButtonVisibility::ZOOM_ALLOWED].m_Function = [&]() {
889 return GameClient()->m_Camera.ZoomAllowed();
890 };
891 m_aVisibilityFunctions[(int)EButtonVisibility::VOTE_ACTIVE].m_pId = "vote-active";
892 m_aVisibilityFunctions[(int)EButtonVisibility::VOTE_ACTIVE].m_Function = [&]() {
893 return GameClient()->m_Voting.IsVoting();
894 };
895 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_ALLOWED].m_pId = "dummy-allowed";
896 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_ALLOWED].m_Function = [&]() {
897 return Client()->DummyAllowed();
898 };
899 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_CONNECTED].m_pId = "dummy-connected";
900 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_CONNECTED].m_Function = [&]() {
901 return Client()->DummyConnected();
902 };
903 m_aVisibilityFunctions[(int)EButtonVisibility::RCON_AUTHED].m_pId = "rcon-authed";
904 m_aVisibilityFunctions[(int)EButtonVisibility::RCON_AUTHED].m_Function = [&]() {
905 return Client()->RconAuthed();
906 };
907 m_aVisibilityFunctions[(int)EButtonVisibility::DEMO_PLAYER].m_pId = "demo-player";
908 m_aVisibilityFunctions[(int)EButtonVisibility::DEMO_PLAYER].m_Function = [&]() {
909 return Client()->State() == IClient::STATE_DEMOPLAYBACK;
910 };
911 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_1].m_pId = "extra-menu";
912 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_1].m_Function = [&]() {
913 return m_aExtraMenuActive[0];
914 };
915 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_2].m_pId = "extra-menu-2";
916 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_2].m_Function = [&]() {
917 return m_aExtraMenuActive[1];
918 };
919 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_3].m_pId = "extra-menu-3";
920 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_3].m_Function = [&]() {
921 return m_aExtraMenuActive[2];
922 };
923 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_4].m_pId = "extra-menu-4";
924 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_4].m_Function = [&]() {
925 return m_aExtraMenuActive[3];
926 };
927 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_5].m_pId = "extra-menu-5";
928 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_5].m_Function = [&]() {
929 return m_aExtraMenuActive[4];
930 };
931}
932
933int CTouchControls::NextActiveAction(int Action) const
934{
935 switch(Action)
936 {
937 case ACTION_FIRE:
938 return ACTION_HOOK;
939 case ACTION_HOOK:
940 return ACTION_FIRE;
941 default:
942 dbg_assert_failed("Action invalid for NextActiveAction");
943 }
944}
945
946int CTouchControls::NextDirectTouchAction() const
947{
948 if(GameClient()->m_Snap.m_SpecInfo.m_Active)
949 {
950 switch(m_DirectTouchSpectate)
951 {
952 case EDirectTouchSpectateMode::DISABLED:
953 return NUM_ACTIONS;
954 case EDirectTouchSpectateMode::AIM:
955 return ACTION_AIM;
956 default:
957 dbg_assert_failed("m_DirectTouchSpectate invalid");
958 }
959 }
960 else
961 {
962 switch(m_DirectTouchIngame)
963 {
964 case EDirectTouchIngameMode::DISABLED:
965 return NUM_ACTIONS;
966 case EDirectTouchIngameMode::ACTION:
967 return m_ActionSelected;
968 case EDirectTouchIngameMode::AIM:
969 return ACTION_AIM;
970 case EDirectTouchIngameMode::FIRE:
971 return ACTION_FIRE;
972 case EDirectTouchIngameMode::HOOK:
973 return ACTION_HOOK;
974 default:
975 dbg_assert_failed("m_DirectTouchIngame invalid");
976 }
977 }
978}
979
980void CTouchControls::UpdateButtonsGame(const std::vector<IInput::CTouchFingerState> &vTouchFingerStates)
981{
982 // Update cached button visibilities and store time that buttons become visible.
983 for(CTouchButton &TouchButton : m_vTouchButtons)
984 {
985 TouchButton.UpdateVisibilityGame();
986 }
987
988 const int DirectTouchAction = NextDirectTouchAction();
989 const vec2 ScreenSize = CalculateScreenSize();
990
991 std::vector<IInput::CTouchFingerState> vRemainingTouchFingerStates = vTouchFingerStates;
992
993 if(!m_vStaleFingers.empty())
994 {
995 // Remove stale fingers that are not pressed anymore.
996 m_vStaleFingers.erase(
997 first: std::remove_if(first: m_vStaleFingers.begin(), last: m_vStaleFingers.end(), pred: [&](const IInput::CTouchFinger &Finger) {
998 return std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
999 return TouchFingerState.m_Finger == Finger;
1000 }) == vRemainingTouchFingerStates.end();
1001 }),
1002 last: m_vStaleFingers.end());
1003 // Prevent stale fingers from activating touch buttons and direct touch.
1004 vRemainingTouchFingerStates.erase(
1005 first: std::remove_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1006 return std::find_if(first: m_vStaleFingers.begin(), last: m_vStaleFingers.end(), pred: [&](const IInput::CTouchFinger &Finger) {
1007 return TouchFingerState.m_Finger == Finger;
1008 }) != m_vStaleFingers.end();
1009 }),
1010 last: vRemainingTouchFingerStates.end());
1011 }
1012
1013 // Remove remaining finger states for fingers which are responsible for active actions
1014 // and release action when the finger responsible for it is not pressed down anymore.
1015 bool GotDirectFingerState = false; // Whether DirectFingerState is valid
1016 IInput::CTouchFingerState DirectFingerState{}; // The finger that will be used to update the mouse position
1017 for(int Action = ACTION_AIM; Action < NUM_ACTIONS; ++Action)
1018 {
1019 if(!m_aDirectTouchActionStates[Action].m_Active)
1020 {
1021 continue;
1022 }
1023
1024 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1025 return TouchFingerState.m_Finger == m_aDirectTouchActionStates[Action].m_Finger;
1026 });
1027 if(ActiveFinger == vRemainingTouchFingerStates.end() || DirectTouchAction == NUM_ACTIONS)
1028 {
1029 m_aDirectTouchActionStates[Action].m_Active = false;
1030 if(Action != ACTION_AIM)
1031 {
1032 Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[Action], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
1033 }
1034 }
1035 else
1036 {
1037 if(Action == m_DirectTouchLastAction)
1038 {
1039 GotDirectFingerState = true;
1040 DirectFingerState = *ActiveFinger;
1041 }
1042 vRemainingTouchFingerStates.erase(position: ActiveFinger);
1043 }
1044 }
1045
1046 // Update touch button states after the active action fingers were removed from the vector
1047 // so that current cursor movement can cross over touch buttons without activating them.
1048
1049 // Activate visible, inactive buttons with hovered finger. Deactivate previous button being
1050 // activated by the same finger. Touch buttons are only activated if they became visible
1051 // before the respective touch finger was pressed down, to prevent repeatedly activating
1052 // overlapping buttons of excluding visibilities.
1053 for(CTouchButton &TouchButton : m_vTouchButtons)
1054 {
1055 if(!TouchButton.IsVisible() || TouchButton.m_pBehavior->IsActive())
1056 {
1057 continue;
1058 }
1059 const auto FingerInsideButton = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1060 return TouchButton.m_VisibilityStartTime < TouchFingerState.m_PressTime &&
1061 TouchButton.IsInside(TouchPosition: TouchFingerState.m_Position * ScreenSize);
1062 });
1063 if(FingerInsideButton == vRemainingTouchFingerStates.end())
1064 {
1065 continue;
1066 }
1067 const auto OtherHoveredTouchButton = std::find_if(first: m_vTouchButtons.begin(), last: m_vTouchButtons.end(), pred: [&](const CTouchButton &Button) {
1068 return &Button != &TouchButton && Button.IsVisible() && Button.IsInside(TouchPosition: FingerInsideButton->m_Position * ScreenSize);
1069 });
1070 if(OtherHoveredTouchButton != m_vTouchButtons.end())
1071 {
1072 // Do not activate any button if multiple overlapping buttons are hovered.
1073 // TODO: Prevent overlapping buttons entirely when parsing the button configuration?
1074 vRemainingTouchFingerStates.erase(position: FingerInsideButton);
1075 continue;
1076 }
1077 auto PrevActiveTouchButton = std::find_if(first: m_vTouchButtons.begin(), last: m_vTouchButtons.end(), pred: [&](const CTouchButton &Button) {
1078 return Button.m_pBehavior->IsActive(Finger: FingerInsideButton->m_Finger);
1079 });
1080 if(PrevActiveTouchButton != m_vTouchButtons.end())
1081 {
1082 PrevActiveTouchButton->m_pBehavior->SetInactive(true);
1083 }
1084 TouchButton.m_pBehavior->SetActive(*FingerInsideButton);
1085 }
1086
1087 // Deactivate touch buttons only when the respective finger is released, so touch buttons
1088 // are kept active also if the finger is moved outside the button.
1089 for(CTouchButton &TouchButton : m_vTouchButtons)
1090 {
1091 if(!TouchButton.IsVisible())
1092 {
1093 if(TouchButton.m_pBehavior->IsActive())
1094 {
1095 // Remember fingers responsible for buttons that were deactivated due to becoming invisible,
1096 // to ensure that these fingers will not activate direct touch input or touch buttons.
1097 m_vStaleFingers.push_back(x: TouchButton.m_pBehavior->m_Finger);
1098 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1099 return TouchFingerState.m_Finger == TouchButton.m_pBehavior->m_Finger;
1100 });
1101 // ActiveFinger could be released during this progress.
1102 if(ActiveFinger != vRemainingTouchFingerStates.end())
1103 vRemainingTouchFingerStates.erase(position: ActiveFinger);
1104 }
1105 TouchButton.m_pBehavior->SetInactive(false);
1106 continue;
1107 }
1108 if(!TouchButton.m_pBehavior->IsActive())
1109 {
1110 continue;
1111 }
1112 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1113 return TouchFingerState.m_Finger == TouchButton.m_pBehavior->m_Finger;
1114 });
1115 if(ActiveFinger == vRemainingTouchFingerStates.end())
1116 {
1117 TouchButton.m_pBehavior->SetInactive(true);
1118 }
1119 else
1120 {
1121 // Update the already active touch button with the current finger state
1122 TouchButton.m_pBehavior->SetActive(*ActiveFinger);
1123 }
1124 }
1125
1126 // Remove remaining fingers for active buttons after updating the buttons.
1127 for(CTouchButton &TouchButton : m_vTouchButtons)
1128 {
1129 if(!TouchButton.m_pBehavior->IsActive())
1130 {
1131 continue;
1132 }
1133 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1134 return TouchFingerState.m_Finger == TouchButton.m_pBehavior->m_Finger;
1135 });
1136 dbg_assert(ActiveFinger != vRemainingTouchFingerStates.end(), "Active button finger not found");
1137 vRemainingTouchFingerStates.erase(position: ActiveFinger);
1138 }
1139
1140 // TODO: Support standard gesture to zoom (enabled separately for ingame and spectator)
1141
1142 // Activate action if there is an unhandled pressed down finger.
1143 int ActivateAction = NUM_ACTIONS;
1144 if(DirectTouchAction != NUM_ACTIONS && !vRemainingTouchFingerStates.empty() && !m_aDirectTouchActionStates[DirectTouchAction].m_Active)
1145 {
1146 GotDirectFingerState = true;
1147 DirectFingerState = vRemainingTouchFingerStates[0];
1148 vRemainingTouchFingerStates.erase(position: vRemainingTouchFingerStates.begin());
1149 m_aDirectTouchActionStates[DirectTouchAction].m_Active = true;
1150 m_aDirectTouchActionStates[DirectTouchAction].m_Finger = DirectFingerState.m_Finger;
1151 m_DirectTouchLastAction = DirectTouchAction;
1152 ActivateAction = DirectTouchAction;
1153 }
1154
1155 // Update mouse position based on the finger responsible for the last active action.
1156 if(GotDirectFingerState)
1157 {
1158 const float Zoom = GameClient()->m_Snap.m_SpecInfo.m_Active ? GameClient()->m_Camera.m_Zoom : 1.0f;
1159 vec2 WorldScreenSize;
1160 Graphics()->CalcScreenParams(Aspect: Graphics()->ScreenAspect(), Zoom, pWidth: &WorldScreenSize.x, pHeight: &WorldScreenSize.y);
1161 CControls &Controls = GameClient()->m_Controls;
1162 if(GameClient()->m_Snap.m_SpecInfo.m_Active)
1163 {
1164 Controls.m_aMousePos[g_Config.m_ClDummy] += -DirectFingerState.m_Delta * WorldScreenSize;
1165 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::RELATIVE;
1166 Controls.m_aMousePos[g_Config.m_ClDummy].x = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].x, lo: -201.0f * 32, hi: (Collision()->GetWidth() + 201.0f) * 32.0f);
1167 Controls.m_aMousePos[g_Config.m_ClDummy].y = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].y, lo: -201.0f * 32, hi: (Collision()->GetHeight() + 201.0f) * 32.0f);
1168 }
1169 else
1170 {
1171 Controls.m_aMousePos[g_Config.m_ClDummy] = (DirectFingerState.m_Position - vec2(0.5f, 0.5f)) * WorldScreenSize;
1172 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::ABSOLUTE;
1173 }
1174 }
1175
1176 // Activate action after the mouse position is set.
1177 if(ActivateAction != ACTION_AIM && ActivateAction != NUM_ACTIONS)
1178 {
1179 Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[ActivateAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
1180 }
1181}
1182
1183void CTouchControls::ResetButtons()
1184{
1185 for(CTouchButton &TouchButton : m_vTouchButtons)
1186 {
1187 TouchButton.m_pBehavior->Reset();
1188 }
1189 for(CActionState &ActionState : m_aDirectTouchActionStates)
1190 {
1191 ActionState.m_Active = false;
1192 }
1193}
1194
1195void CTouchControls::RenderButtonsGame()
1196{
1197 for(CTouchButton &TouchButton : m_vTouchButtons)
1198 {
1199 TouchButton.UpdateVisibilityGame();
1200 }
1201 for(CTouchButton &TouchButton : m_vTouchButtons)
1202 {
1203 if(!TouchButton.IsVisible())
1204 {
1205 continue;
1206 }
1207 TouchButton.UpdateBackgroundCorners();
1208 TouchButton.UpdateScreenFromUnitRect();
1209 TouchButton.Render();
1210 }
1211}
1212
1213vec2 CTouchControls::CalculateScreenSize() const
1214{
1215 const float ScreenHeight = 400.0f * 3.0f;
1216 const float ScreenWidth = ScreenHeight * Graphics()->ScreenAspect();
1217 return vec2(ScreenWidth, ScreenHeight);
1218}
1219
1220bool CTouchControls::ParseConfiguration(const void *pFileData, unsigned FileLength)
1221{
1222 json_settings JsonSettings{};
1223 char aError[256];
1224 json_value *pConfiguration = json_parse_ex(settings: &JsonSettings, json: static_cast<const json_char *>(pFileData), length: FileLength, error: aError);
1225
1226 if(pConfiguration == nullptr)
1227 {
1228 log_error("touch_controls", "Failed to parse configuration (invalid json): '%s'", aError);
1229 return false;
1230 }
1231 if(pConfiguration->type != json_object)
1232 {
1233 log_error("touch_controls", "Failed to parse configuration: root must be an object");
1234 json_value_free(pConfiguration);
1235 return false;
1236 }
1237
1238 std::optional<EDirectTouchIngameMode> ParsedDirectTouchIngame = ParseDirectTouchIngameMode(pModeValue: &(*pConfiguration)["direct-touch-ingame"]);
1239 if(!ParsedDirectTouchIngame.has_value())
1240 {
1241 json_value_free(pConfiguration);
1242 return false;
1243 }
1244
1245 std::optional<EDirectTouchSpectateMode> ParsedDirectTouchSpectate = ParseDirectTouchSpectateMode(pModeValue: &(*pConfiguration)["direct-touch-spectate"]);
1246 if(!ParsedDirectTouchSpectate.has_value())
1247 {
1248 json_value_free(pConfiguration);
1249 return false;
1250 }
1251
1252 std::optional<ColorRGBA> ParsedBackgroundColorInactive =
1253 ParseColor(pColorValue: &(*pConfiguration)["background-color-inactive"], pAttributeName: "background-color-inactive", DefaultColor: ColorRGBA(0.0f, 0.0f, 0.0f, 0.25f));
1254 if(!ParsedBackgroundColorInactive.has_value())
1255 {
1256 json_value_free(pConfiguration);
1257 return false;
1258 }
1259
1260 std::optional<ColorRGBA> ParsedBackgroundColorActive =
1261 ParseColor(pColorValue: &(*pConfiguration)["background-color-active"], pAttributeName: "background-color-active", DefaultColor: ColorRGBA(0.2f, 0.2f, 0.2f, 0.25f));
1262 if(!ParsedBackgroundColorActive.has_value())
1263 {
1264 json_value_free(pConfiguration);
1265 return false;
1266 }
1267
1268 const json_value &TouchButtons = (*pConfiguration)["touch-buttons"];
1269 if(TouchButtons.type != json_array)
1270 {
1271 log_error("touch_controls", "Failed to parse configuration: attribute 'touch-buttons' must specify an array");
1272 json_value_free(pConfiguration);
1273 return false;
1274 }
1275
1276 std::vector<CTouchButton> vParsedTouchButtons;
1277 vParsedTouchButtons.reserve(n: TouchButtons.u.array.length);
1278 for(unsigned ButtonIndex = 0; ButtonIndex < TouchButtons.u.array.length; ++ButtonIndex)
1279 {
1280 std::optional<CTouchButton> ParsedButton = ParseButton(pButtonObject: &TouchButtons[ButtonIndex]);
1281 if(!ParsedButton.has_value())
1282 {
1283 log_error("touch_controls", "Failed to parse configuration: could not parse button at index '%d'", ButtonIndex);
1284 json_value_free(pConfiguration);
1285 return false;
1286 }
1287
1288 vParsedTouchButtons.push_back(x: std::move(ParsedButton.value()));
1289 }
1290
1291 // Parsing successful. Apply parsed configuration.
1292 m_DirectTouchIngame = ParsedDirectTouchIngame.value();
1293 m_DirectTouchSpectate = ParsedDirectTouchSpectate.value();
1294 m_BackgroundColorInactive = ParsedBackgroundColorInactive.value();
1295 m_BackgroundColorActive = ParsedBackgroundColorActive.value();
1296
1297 m_vTouchButtons = std::move(vParsedTouchButtons);
1298 for(CTouchButton &TouchButton : m_vTouchButtons)
1299 {
1300 TouchButton.UpdatePointers();
1301 TouchButton.UpdateScreenFromUnitRect();
1302 }
1303
1304 json_value_free(pConfiguration);
1305
1306 // If successfully parsing buttons, deselect it.
1307 m_pSelectedButton = nullptr;
1308 m_pSampleButton = nullptr;
1309 m_UnsavedChanges = false;
1310
1311 return true;
1312}
1313
1314std::optional<CTouchControls::EDirectTouchIngameMode> CTouchControls::ParseDirectTouchIngameMode(const json_value *pModeValue)
1315{
1316 // TODO: Remove json_boolean backwards compatibility
1317 const json_value &DirectTouchIngame = *pModeValue;
1318 if(DirectTouchIngame.type != json_boolean && DirectTouchIngame.type != json_string)
1319 {
1320 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-ingame' must specify a string");
1321 return {};
1322 }
1323 if(DirectTouchIngame.type == json_boolean)
1324 {
1325 return DirectTouchIngame.u.boolean ? EDirectTouchIngameMode::ACTION : EDirectTouchIngameMode::DISABLED;
1326 }
1327 EDirectTouchIngameMode ParsedDirectTouchIngame = EDirectTouchIngameMode::NUM_STATES;
1328 for(int CurrentMode = (int)EDirectTouchIngameMode::DISABLED; CurrentMode < (int)EDirectTouchIngameMode::NUM_STATES; ++CurrentMode)
1329 {
1330 if(str_comp(a: DirectTouchIngame.u.string.ptr, b: DIRECT_TOUCH_INGAME_MODE_NAMES[CurrentMode]) == 0)
1331 {
1332 ParsedDirectTouchIngame = (EDirectTouchIngameMode)CurrentMode;
1333 break;
1334 }
1335 }
1336 if(ParsedDirectTouchIngame == EDirectTouchIngameMode::NUM_STATES)
1337 {
1338 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-ingame' specifies unknown value '%s'", DirectTouchIngame.u.string.ptr);
1339 return {};
1340 }
1341 return ParsedDirectTouchIngame;
1342}
1343
1344std::optional<CTouchControls::EDirectTouchSpectateMode> CTouchControls::ParseDirectTouchSpectateMode(const json_value *pModeValue)
1345{
1346 // TODO: Remove json_boolean backwards compatibility
1347 const json_value &DirectTouchSpectate = *pModeValue;
1348 if(DirectTouchSpectate.type != json_boolean && DirectTouchSpectate.type != json_string)
1349 {
1350 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-spectate' must specify a string");
1351 return {};
1352 }
1353 if(DirectTouchSpectate.type == json_boolean)
1354 {
1355 return DirectTouchSpectate.u.boolean ? EDirectTouchSpectateMode::AIM : EDirectTouchSpectateMode::DISABLED;
1356 }
1357 EDirectTouchSpectateMode ParsedDirectTouchSpectate = EDirectTouchSpectateMode::NUM_STATES;
1358 for(int CurrentMode = (int)EDirectTouchSpectateMode::DISABLED; CurrentMode < (int)EDirectTouchSpectateMode::NUM_STATES; ++CurrentMode)
1359 {
1360 if(str_comp(a: DirectTouchSpectate.u.string.ptr, b: DIRECT_TOUCH_SPECTATE_MODE_NAMES[CurrentMode]) == 0)
1361 {
1362 ParsedDirectTouchSpectate = (EDirectTouchSpectateMode)CurrentMode;
1363 break;
1364 }
1365 }
1366 if(ParsedDirectTouchSpectate == EDirectTouchSpectateMode::NUM_STATES)
1367 {
1368 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-spectate' specifies unknown value '%s'", DirectTouchSpectate.u.string.ptr);
1369 return {};
1370 }
1371 return ParsedDirectTouchSpectate;
1372}
1373
1374std::optional<ColorRGBA> CTouchControls::ParseColor(const json_value *pColorValue, const char *pAttributeName, std::optional<ColorRGBA> DefaultColor) const
1375{
1376 const json_value &Color = *pColorValue;
1377 if(Color.type == json_none && DefaultColor.has_value())
1378 {
1379 return DefaultColor;
1380 }
1381 if(Color.type != json_string)
1382 {
1383 log_error("touch_controls", "Failed to parse configuration: attribute '%s' must specify a string", pAttributeName);
1384 return {};
1385 }
1386 std::optional<ColorRGBA> ParsedColor = color_parse<ColorRGBA>(pStr: Color.u.string.ptr);
1387 if(!ParsedColor.has_value())
1388 {
1389 log_error("touch_controls", "Failed to parse configuration: attribute '%s' specifies invalid color value '%s'", pAttributeName, Color.u.string.ptr);
1390 return {};
1391 }
1392 return ParsedColor;
1393}
1394
1395std::optional<CTouchControls::CTouchButton> CTouchControls::ParseButton(const json_value *pButtonObject)
1396{
1397 const json_value &ButtonObject = *pButtonObject;
1398 if(ButtonObject.type != json_object)
1399 {
1400 log_error("touch_controls", "Failed to parse touch button: must be an object");
1401 return {};
1402 }
1403
1404 const auto &&ParsePositionSize = [&](const char *pAttribute, int &ParsedValue, int Min, int Max) {
1405 const json_value &AttributeValue = ButtonObject[pAttribute];
1406 if(AttributeValue.type != json_integer || !in_range<json_int_t>(a: AttributeValue.u.integer, lower: Min, upper: Max))
1407 {
1408 log_error("touch_controls", "Failed to parse touch button: attribute '%s' must specify an integer between '%d' and '%d'", pAttribute, Min, Max);
1409 return false;
1410 }
1411 ParsedValue = AttributeValue.u.integer;
1412 return true;
1413 };
1414 CUnitRect ParsedUnitRect;
1415 if(!ParsePositionSize("w", ParsedUnitRect.m_W, BUTTON_SIZE_MINIMUM, BUTTON_SIZE_MAXIMUM) ||
1416 !ParsePositionSize("h", ParsedUnitRect.m_H, BUTTON_SIZE_MINIMUM, BUTTON_SIZE_MAXIMUM))
1417 {
1418 return {};
1419 }
1420 if(!ParsePositionSize("x", ParsedUnitRect.m_X, 0, BUTTON_SIZE_SCALE - ParsedUnitRect.m_W) ||
1421 !ParsePositionSize("y", ParsedUnitRect.m_Y, 0, BUTTON_SIZE_SCALE - ParsedUnitRect.m_H))
1422 {
1423 return {};
1424 }
1425
1426 const json_value &Shape = ButtonObject["shape"];
1427 if(Shape.type != json_string)
1428 {
1429 log_error("touch_controls", "Failed to parse touch button: attribute 'shape' must specify a string");
1430 return {};
1431 }
1432 EButtonShape ParsedShape = EButtonShape::NUM_SHAPES;
1433 for(int CurrentShape = (int)EButtonShape::RECT; CurrentShape < (int)EButtonShape::NUM_SHAPES; ++CurrentShape)
1434 {
1435 if(str_comp(a: Shape.u.string.ptr, b: SHAPE_NAMES[CurrentShape]) == 0)
1436 {
1437 ParsedShape = (EButtonShape)CurrentShape;
1438 break;
1439 }
1440 }
1441 if(ParsedShape == EButtonShape::NUM_SHAPES)
1442 {
1443 log_error("touch_controls", "Failed to parse touch button: attribute 'shape' specifies unknown value '%s'", Shape.u.string.ptr);
1444 return {};
1445 }
1446
1447 const json_value &Visibilities = ButtonObject["visibilities"];
1448 if(Visibilities.type != json_array)
1449 {
1450 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' must specify an array");
1451 return {};
1452 }
1453 std::vector<CButtonVisibility> vParsedVisibilities;
1454 vParsedVisibilities.reserve(n: Visibilities.u.array.length);
1455 for(unsigned VisibilityIndex = 0; VisibilityIndex < Visibilities.u.array.length; ++VisibilityIndex)
1456 {
1457 const json_value &Visibility = Visibilities[VisibilityIndex];
1458 if(Visibility.type != json_string)
1459 {
1460 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' does not specify string at index '%d'", VisibilityIndex);
1461 return {};
1462 }
1463 EButtonVisibility ParsedVisibility = EButtonVisibility::NUM_VISIBILITIES;
1464 const bool ParsedParity = Visibility.u.string.ptr[0] != '-';
1465 const char *pVisibilityString = ParsedParity ? Visibility.u.string.ptr : &Visibility.u.string.ptr[1];
1466 for(int CurrentVisibility = (int)EButtonVisibility::INGAME; CurrentVisibility < (int)EButtonVisibility::NUM_VISIBILITIES; ++CurrentVisibility)
1467 {
1468 if(str_comp(a: pVisibilityString, b: m_aVisibilityFunctions[CurrentVisibility].m_pId) == 0)
1469 {
1470 ParsedVisibility = (EButtonVisibility)CurrentVisibility;
1471 break;
1472 }
1473 }
1474 if(ParsedVisibility == EButtonVisibility::NUM_VISIBILITIES)
1475 {
1476 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' specifies unknown value '%s' at index '%d'", pVisibilityString, VisibilityIndex);
1477 return {};
1478 }
1479 const bool VisibilityAlreadyUsed = std::any_of(first: vParsedVisibilities.begin(), last: vParsedVisibilities.end(), pred: [&](CButtonVisibility OtherParsedVisibility) {
1480 return OtherParsedVisibility.m_Type == ParsedVisibility;
1481 });
1482 if(VisibilityAlreadyUsed)
1483 {
1484 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' specifies duplicate value '%s' at '%d'", pVisibilityString, VisibilityIndex);
1485 return {};
1486 }
1487 vParsedVisibilities.emplace_back(args&: ParsedVisibility, args: ParsedParity);
1488 }
1489
1490 std::unique_ptr<CTouchButtonBehavior> pParsedBehavior = ParseBehavior(pBehaviorObject: &ButtonObject["behavior"]);
1491 if(pParsedBehavior == nullptr)
1492 {
1493 log_error("touch_controls", "Failed to parse touch button: failed to parse attribute 'behavior' (see details above)");
1494 return {};
1495 }
1496
1497 CTouchButton Button(this);
1498 Button.m_UnitRect = ParsedUnitRect;
1499 Button.m_Shape = ParsedShape;
1500 Button.m_vVisibilities = std::move(vParsedVisibilities);
1501 Button.m_pBehavior = std::move(pParsedBehavior);
1502 return Button;
1503}
1504
1505std::unique_ptr<CTouchControls::CTouchButtonBehavior> CTouchControls::ParseBehavior(const json_value *pBehaviorObject)
1506{
1507 const json_value &BehaviorObject = *pBehaviorObject;
1508 if(BehaviorObject.type != json_object)
1509 {
1510 log_error("touch_controls", "Failed to parse touch button behavior: must be an object");
1511 return nullptr;
1512 }
1513
1514 const json_value &BehaviorType = BehaviorObject["type"];
1515 if(BehaviorType.type != json_string)
1516 {
1517 log_error("touch_controls", "Failed to parse touch button behavior: attribute 'type' must specify a string");
1518 return nullptr;
1519 }
1520
1521 if(str_comp(a: BehaviorType.u.string.ptr, b: CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE) == 0)
1522 {
1523 return ParsePredefinedBehavior(pBehaviorObject: &BehaviorObject);
1524 }
1525 else if(str_comp(a: BehaviorType.u.string.ptr, b: CBindTouchButtonBehavior::BEHAVIOR_TYPE) == 0)
1526 {
1527 return ParseBindBehavior(pBehaviorObject: &BehaviorObject);
1528 }
1529 else if(str_comp(a: BehaviorType.u.string.ptr, b: CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE) == 0)
1530 {
1531 return ParseBindToggleBehavior(pBehaviorObject: &BehaviorObject);
1532 }
1533 else
1534 {
1535 log_error("touch_controls", "Failed to parse touch button behavior: attribute 'type' specifies unknown value '%s'", BehaviorType.u.string.ptr);
1536 return nullptr;
1537 }
1538}
1539
1540std::unique_ptr<CTouchControls::CPredefinedTouchButtonBehavior> CTouchControls::ParsePredefinedBehavior(const json_value *pBehaviorObject)
1541{
1542 const json_value &BehaviorObject = *pBehaviorObject;
1543 const json_value &PredefinedId = BehaviorObject["id"];
1544 if(PredefinedId.type != json_string)
1545 {
1546 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'id' must specify a string", CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE);
1547 return nullptr;
1548 }
1549
1550 class CBehaviorFactory
1551 {
1552 public:
1553 const char *m_pId;
1554 std::function<std::unique_ptr<CPredefinedTouchButtonBehavior>(const json_value *pBehaviorObject)> m_Factory;
1555 };
1556 static const CBehaviorFactory BEHAVIOR_FACTORIES[] = {
1557 {.m_pId: CIngameMenuTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CIngameMenuTouchButtonBehavior>(); }},
1558 {.m_pId: CExtraMenuTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [&](const json_value *pBehavior) { return ParseExtraMenuBehavior(pBehaviorObject: pBehavior); }},
1559 {.m_pId: CEmoticonTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CEmoticonTouchButtonBehavior>(); }},
1560 {.m_pId: CSpectateTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CSpectateTouchButtonBehavior>(); }},
1561 {.m_pId: CSwapActionTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CSwapActionTouchButtonBehavior>(); }},
1562 {.m_pId: CUseActionTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CUseActionTouchButtonBehavior>(); }},
1563 {.m_pId: CJoystickActionTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickActionTouchButtonBehavior>(); }},
1564 {.m_pId: CJoystickAimTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickAimTouchButtonBehavior>(); }},
1565 {.m_pId: CJoystickFireTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickFireTouchButtonBehavior>(); }},
1566 {.m_pId: CJoystickHookTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickHookTouchButtonBehavior>(); }}};
1567 for(const CBehaviorFactory &BehaviorFactory : BEHAVIOR_FACTORIES)
1568 {
1569 if(str_comp(a: PredefinedId.u.string.ptr, b: BehaviorFactory.m_pId) == 0)
1570 {
1571 return BehaviorFactory.m_Factory(&BehaviorObject);
1572 }
1573 }
1574
1575 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'id' specifies unknown value '%s'", CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE, PredefinedId.u.string.ptr);
1576 return nullptr;
1577}
1578
1579std::unique_ptr<CTouchControls::CExtraMenuTouchButtonBehavior> CTouchControls::ParseExtraMenuBehavior(const json_value *pBehaviorObject)
1580{
1581 const json_value &BehaviorObject = *pBehaviorObject;
1582 const json_value &MenuNumber = BehaviorObject["number"];
1583 // TODO: Remove json_none backwards compatibility
1584 if(MenuNumber.type != json_none && (MenuNumber.type != json_integer || !in_range<json_int_t>(a: MenuNumber.u.integer, lower: 1, upper: MAX_EXTRA_MENU_NUMBER)))
1585 {
1586 log_error("touch_controls", "Failed to parse touch button behavior of type '%s' and ID '%s': attribute 'number' must specify an integer between '%d' and '%d'",
1587 CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE, CExtraMenuTouchButtonBehavior::BEHAVIOR_ID, 1, MAX_EXTRA_MENU_NUMBER);
1588 return nullptr;
1589 }
1590 int ParsedMenuNumber = MenuNumber.type == json_none ? 0 : (MenuNumber.u.integer - 1);
1591
1592 return std::make_unique<CExtraMenuTouchButtonBehavior>(args&: ParsedMenuNumber);
1593}
1594
1595std::unique_ptr<CTouchControls::CBindTouchButtonBehavior> CTouchControls::ParseBindBehavior(const json_value *pBehaviorObject)
1596{
1597 const json_value &BehaviorObject = *pBehaviorObject;
1598 const json_value &Label = BehaviorObject["label"];
1599 if(Label.type != json_string)
1600 {
1601 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'label' must specify a string", CBindTouchButtonBehavior::BEHAVIOR_TYPE);
1602 return nullptr;
1603 }
1604
1605 const json_value &LabelType = BehaviorObject["label-type"];
1606 if(LabelType.type != json_string && LabelType.type != json_none)
1607 {
1608 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'label-type' must specify a string", CBindTouchButtonBehavior::BEHAVIOR_TYPE);
1609 return {};
1610 }
1611 CButtonLabel::EType ParsedLabelType = CButtonLabel::EType::NUM_TYPES;
1612 if(LabelType.type == json_none)
1613 {
1614 ParsedLabelType = CButtonLabel::EType::PLAIN;
1615 }
1616 else
1617 {
1618 for(int CurrentType = (int)CButtonLabel::EType::PLAIN; CurrentType < (int)CButtonLabel::EType::NUM_TYPES; ++CurrentType)
1619 {
1620 if(str_comp(a: LabelType.u.string.ptr, b: LABEL_TYPE_NAMES[CurrentType]) == 0)
1621 {
1622 ParsedLabelType = (CButtonLabel::EType)CurrentType;
1623 break;
1624 }
1625 }
1626 }
1627 if(ParsedLabelType == CButtonLabel::EType::NUM_TYPES)
1628 {
1629 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'label-type' specifies unknown value '%s'", CBindTouchButtonBehavior::BEHAVIOR_TYPE, LabelType.u.string.ptr);
1630 return {};
1631 }
1632
1633 const json_value &Command = BehaviorObject["command"];
1634 if(Command.type != json_string)
1635 {
1636 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'command' must specify a string", CBindTouchButtonBehavior::BEHAVIOR_TYPE);
1637 return nullptr;
1638 }
1639
1640 return std::make_unique<CBindTouchButtonBehavior>(args: Label.u.string.ptr, args&: ParsedLabelType, args: Command.u.string.ptr);
1641}
1642
1643std::unique_ptr<CTouchControls::CBindToggleTouchButtonBehavior> CTouchControls::ParseBindToggleBehavior(const json_value *pBehaviorObject)
1644{
1645 const json_value &CommandsObject = (*pBehaviorObject)["commands"];
1646 if(CommandsObject.type != json_array || CommandsObject.u.array.length < 2)
1647 {
1648 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'commands' must specify an array with at least 2 entries", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE);
1649 return {};
1650 }
1651
1652 std::vector<CTouchControls::CBindToggleTouchButtonBehavior::CCommand> vCommands;
1653 vCommands.reserve(n: CommandsObject.u.array.length);
1654 for(unsigned CommandIndex = 0; CommandIndex < CommandsObject.u.array.length; ++CommandIndex)
1655 {
1656 const json_value &CommandObject = CommandsObject[CommandIndex];
1657 if(CommandObject.type != json_object)
1658 {
1659 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'commands' must specify an array of objects", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1660 return nullptr;
1661 }
1662
1663 const json_value &Label = CommandObject["label"];
1664 if(Label.type != json_string)
1665 {
1666 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'label' must specify a string", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1667 return nullptr;
1668 }
1669
1670 const json_value &LabelType = CommandObject["label-type"];
1671 if(LabelType.type != json_string && LabelType.type != json_none)
1672 {
1673 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'label-type' must specify a string", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1674 return {};
1675 }
1676 CButtonLabel::EType ParsedLabelType = CButtonLabel::EType::NUM_TYPES;
1677 if(LabelType.type == json_none)
1678 {
1679 ParsedLabelType = CButtonLabel::EType::PLAIN;
1680 }
1681 else
1682 {
1683 for(int CurrentType = (int)CButtonLabel::EType::PLAIN; CurrentType < (int)CButtonLabel::EType::NUM_TYPES; ++CurrentType)
1684 {
1685 if(str_comp(a: LabelType.u.string.ptr, b: LABEL_TYPE_NAMES[CurrentType]) == 0)
1686 {
1687 ParsedLabelType = (CButtonLabel::EType)CurrentType;
1688 break;
1689 }
1690 }
1691 }
1692 if(ParsedLabelType == CButtonLabel::EType::NUM_TYPES)
1693 {
1694 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'label-type' specifies unknown value '%s'", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex, LabelType.u.string.ptr);
1695 return {};
1696 }
1697
1698 const json_value &Command = CommandObject["command"];
1699 if(Command.type != json_string)
1700 {
1701 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'command' must specify a string", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1702 return nullptr;
1703 }
1704 vCommands.emplace_back(args: Label.u.string.ptr, args&: ParsedLabelType, args: Command.u.string.ptr);
1705 }
1706 return std::make_unique<CBindToggleTouchButtonBehavior>(args: std::move(vCommands));
1707}
1708
1709void CTouchControls::WriteConfiguration(CJsonWriter *pWriter)
1710{
1711 pWriter->BeginObject();
1712
1713 pWriter->WriteAttribute(pName: "direct-touch-ingame");
1714 pWriter->WriteStrValue(pValue: DIRECT_TOUCH_INGAME_MODE_NAMES[(int)m_DirectTouchIngame]);
1715
1716 pWriter->WriteAttribute(pName: "direct-touch-spectate");
1717 pWriter->WriteStrValue(pValue: DIRECT_TOUCH_SPECTATE_MODE_NAMES[(int)m_DirectTouchSpectate]);
1718
1719 char aColor[9];
1720 str_format(buffer: aColor, buffer_size: sizeof(aColor), format: "%08X", m_BackgroundColorInactive.PackAlphaLast());
1721 pWriter->WriteAttribute(pName: "background-color-inactive");
1722 pWriter->WriteStrValue(pValue: aColor);
1723
1724 str_format(buffer: aColor, buffer_size: sizeof(aColor), format: "%08X", m_BackgroundColorActive.PackAlphaLast());
1725 pWriter->WriteAttribute(pName: "background-color-active");
1726 pWriter->WriteStrValue(pValue: aColor);
1727
1728 pWriter->WriteAttribute(pName: "touch-buttons");
1729 pWriter->BeginArray();
1730 for(CTouchButton &TouchButton : m_vTouchButtons)
1731 {
1732 TouchButton.WriteToConfiguration(pWriter);
1733 }
1734 pWriter->EndArray();
1735
1736 pWriter->EndObject();
1737}
1738
1739// This is called when the checkbox "Edit touch controls" is selected, so virtual visibility could be set as the real visibility on entering.
1740void CTouchControls::ResetVirtualVisibilities()
1741{
1742 // Update virtual visibilities.
1743 for(int Visibility = (int)EButtonVisibility::INGAME; Visibility < (int)EButtonVisibility::NUM_VISIBILITIES; ++Visibility)
1744 m_aVirtualVisibilities[Visibility] = m_aVisibilityFunctions[Visibility].m_Function();
1745}
1746
1747void CTouchControls::UpdateButtonsEditor(const std::vector<IInput::CTouchFingerState> &vTouchFingerStates)
1748{
1749 std::vector<CUnitRect> vVisibleButtonRects;
1750 const vec2 ScreenSize = CalculateScreenSize();
1751 bool LongPress = false;
1752 for(CTouchButton &TouchButton : m_vTouchButtons)
1753 {
1754 TouchButton.UpdateVisibilityEditor();
1755 }
1756
1757 if(vTouchFingerStates.empty())
1758 m_PreventSaving = false;
1759
1760 // Remove if the finger deleted has released.
1761 if(!m_vDeletedFingerState.empty())
1762 {
1763 const auto &Remove = std::remove_if(first: m_vDeletedFingerState.begin(), last: m_vDeletedFingerState.end(), pred: [&vTouchFingerStates](const auto &TargetState) {
1764 return std::none_of(vTouchFingerStates.begin(), vTouchFingerStates.end(), [&](const auto &State) {
1765 return State.m_Finger == TargetState.m_Finger;
1766 });
1767 });
1768 m_vDeletedFingerState.erase(first: Remove, last: m_vDeletedFingerState.end());
1769 }
1770 // Delete fingers if they are press later. So they cant be the longpress finger.
1771 if(vTouchFingerStates.size() > 1)
1772 {
1773 std::for_each(first: vTouchFingerStates.begin() + 1, last: vTouchFingerStates.end(), f: [&](const auto &State) {
1774 m_vDeletedFingerState.push_back(State);
1775 });
1776 }
1777
1778 // If released, and there is finger on screen, and the "first finger" is not deleted(new finger), then it can be a LongPress candidate.
1779 if(!vTouchFingerStates.empty() && !std::any_of(first: m_vDeletedFingerState.begin(), last: m_vDeletedFingerState.end(), pred: [&vTouchFingerStates](const auto &State) {
1780 return vTouchFingerStates[0].m_Finger == State.m_Finger;
1781 }))
1782 {
1783 // If has different finger, reset the accumulated delta.
1784 if(m_LongPressFingerState.has_value() && (*m_LongPressFingerState).m_Finger != vTouchFingerStates[0].m_Finger)
1785 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1786 // Update the LongPress candidate state.
1787 m_LongPressFingerState = vTouchFingerStates[0];
1788 }
1789 // If no suitable finger for long press, then clear it.
1790 else
1791 {
1792 m_LongPressFingerState = std::nullopt;
1793 }
1794
1795 // Find long press button. LongPress == true means the first fingerstate long pressed.
1796 if(m_LongPressFingerState.has_value())
1797 {
1798 m_AccumulatedDelta += (*m_LongPressFingerState).m_Delta;
1799 // If slided, then delete.
1800 if(length(a: m_AccumulatedDelta) > 0.005f)
1801 {
1802 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1803 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1804 m_LongPressFingerState = std::nullopt;
1805 m_PreventSaving = true;
1806 }
1807 // Till now, this else contains: if the finger hasn't slided, have no fingers that remain pressed down when it pressed, hasn't been a longpress already, the candidate is always the first finger.
1808 else
1809 {
1810 const auto Now = time_get_nanoseconds();
1811 if(!m_PreventSaving && Now - (*m_LongPressFingerState).m_PressTime > LONG_TOUCH_DURATION)
1812 {
1813 LongPress = true;
1814 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1815 // LongPress will be used this frame for sure, so reset delta.
1816 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1817 }
1818 }
1819 }
1820
1821 // Update active and zoom fingerstate. The first finger will be used for moving button.
1822 if(!vTouchFingerStates.empty())
1823 m_ActiveFingerState = vTouchFingerStates[0];
1824 else
1825 {
1826 m_ActiveFingerState = std::nullopt;
1827 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1828 m_pSampleButton->m_UnitRect = (*m_ShownRect);
1829 }
1830 // Only the second finger will be used for zooming button.
1831 if(vTouchFingerStates.size() > 1)
1832 {
1833 // If zoom finger is pressed now, reset the zoom startpos
1834 if(!m_ZoomFingerState.has_value())
1835 m_ZoomStartPos = m_ActiveFingerState.value().m_Position - vTouchFingerStates[1].m_Position;
1836 m_ZoomFingerState = vTouchFingerStates[1];
1837 m_PreventSaving = true;
1838
1839 // If Zooming started, update it's x,y value so it's width and height could be calculated correctly.
1840 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1841 {
1842 m_pSampleButton->m_UnitRect.m_X = m_ShownRect->m_X;
1843 m_pSampleButton->m_UnitRect.m_Y = m_ShownRect->m_Y;
1844 }
1845 }
1846 else
1847 {
1848 m_ZoomFingerState = std::nullopt;
1849 m_ZoomStartPos = vec2(0.0f, 0.0f);
1850 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1851 {
1852 m_pSampleButton->m_UnitRect.m_W = m_ShownRect->m_W;
1853 m_pSampleButton->m_UnitRect.m_H = m_ShownRect->m_H;
1854 }
1855 }
1856 for(auto &TouchButton : m_vTouchButtons)
1857 {
1858 if(TouchButton.m_VisibilityCached)
1859 {
1860 if(m_pSelectedButton == &TouchButton)
1861 continue;
1862 // Only Long Pressed finger "in visible button" is used for selecting a button.
1863 if(LongPress && !vTouchFingerStates.empty() && TouchButton.IsInside(TouchPosition: (*m_LongPressFingerState).m_Position * ScreenSize))
1864 {
1865 // If m_pSelectedButton changes, Confirm if saving changes, then change.
1866 // LongPress used.
1867 LongPress = false;
1868 // Note: Even after the popup is opened by ChangeSelectedButtonWhile..., the fingerstate still exists. So we have to add it to m_vDeletedFingerState.
1869 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1870 m_LongPressFingerState = std::nullopt;
1871 if(m_UnsavedChanges)
1872 {
1873 // Update sample button before saving, or sample button's position value might be not updated.
1874 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1875 m_pSampleButton->m_UnitRect = *m_ShownRect;
1876 m_PopupParam.m_KeepMenuOpen = false;
1877 m_PopupParam.m_pOldSelectedButton = m_pSelectedButton;
1878 m_PopupParam.m_pNewSelectedButton = &TouchButton;
1879 m_PopupParam.m_PopupType = EPopupType::BUTTON_CHANGED;
1880 GameClient()->m_Menus.SetActive(true);
1881 // End the function.
1882 return;
1883 }
1884 m_pSelectedButton = &TouchButton;
1885 // Update illegal position when Long press the button. Or later it will keep saying unsavedchanges.
1886 if(IsRectOverlapping(MyRect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape))
1887 {
1888 std::optional<CUnitRect> FreeRect = UpdatePosition(MyRect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape);
1889 m_UnsavedChanges = true;
1890 if(!FreeRect.has_value())
1891 {
1892 m_PopupParam.m_PopupType = EPopupType::NO_SPACE;
1893 m_PopupParam.m_KeepMenuOpen = true;
1894 GameClient()->m_Menus.SetActive(true);
1895 return;
1896 }
1897 TouchButton.m_UnitRect = FreeRect.value();
1898 TouchButton.UpdateScreenFromUnitRect();
1899 }
1900 m_aIssueParam[(int)EIssueType::CACHE_SETTINGS].m_pTargetButton = m_pSelectedButton;
1901 m_aIssueParam[(int)EIssueType::CACHE_SETTINGS].m_Resolved = false;
1902 RemakeSampleButton();
1903 UpdateSampleButton(SrcButton: *m_pSelectedButton);
1904 // Don't insert the long pressed button. It is selected button now.
1905 continue;
1906 }
1907 // Insert visible but not selected buttons.
1908 vVisibleButtonRects.emplace_back(args: CalculateHitbox(Rect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape));
1909 }
1910 // If selected button not visible, unselect it.
1911 else if(m_pSelectedButton == &TouchButton && !GameClient()->m_Menus.IsActive())
1912 {
1913 m_PopupParam.m_PopupType = EPopupType::BUTTON_INVISIBLE;
1914 GameClient()->m_Menus.SetActive(true);
1915 return;
1916 }
1917 }
1918
1919 // Nothing left to do if no button selected.
1920 if(m_pSampleButton == nullptr)
1921 return;
1922
1923 // If LongPress == true, LongPress finger has to be outside of all visible buttons.(Except m_pSampleButton. This button hasn't been checked)
1924 if(LongPress)
1925 {
1926 // LongPress should be set to false, but to pass clang-tidy check, this shouldn't be set now
1927 // LongPress = false;
1928 bool IsInside = CalculateScreenFromUnitRect(Unit: *m_ShownRect).Inside(Point: m_LongPressFingerState->m_Position * ScreenSize);
1929 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1930 m_LongPressFingerState = std::nullopt;
1931 if(m_UnsavedChanges && !IsInside)
1932 {
1933 m_pSampleButton->m_UnitRect = *m_ShownRect;
1934 m_PopupParam.m_pNewSelectedButton = nullptr;
1935 m_PopupParam.m_pOldSelectedButton = m_pSelectedButton;
1936 m_PopupParam.m_KeepMenuOpen = false;
1937 m_PopupParam.m_PopupType = EPopupType::BUTTON_CHANGED;
1938 GameClient()->m_Menus.SetActive(true);
1939 }
1940 else if(!IsInside)
1941 {
1942 m_UnsavedChanges = false;
1943 ResetButtonPointers();
1944 // No need for caching settings issue. So the issue is set to finished.
1945 m_aIssueParam[(int)EIssueType::CACHE_SETTINGS].m_Resolved = true;
1946 m_aIssueParam[(int)EIssueType::SAVE_SETTINGS].m_Resolved = true;
1947 m_aIssueParam[(int)EIssueType::CACHE_POSITION].m_Resolved = true;
1948 }
1949 }
1950
1951 if(m_pSampleButton != nullptr)
1952 {
1953 if(m_ActiveFingerState.has_value() && m_ZoomFingerState == std::nullopt)
1954 {
1955 vec2 UnitXYDelta = m_ActiveFingerState->m_Delta * BUTTON_SIZE_SCALE;
1956 m_pSampleButton->m_UnitRect.m_X += UnitXYDelta.x;
1957 m_pSampleButton->m_UnitRect.m_Y += UnitXYDelta.y;
1958 auto Hitbox = CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape);
1959 m_ShownRect = FindPositionXY(vVisibleButtonRects, MyRect: Hitbox);
1960 dbg_assert(m_ShownRect.has_value(), "Unexpected nullopt in m_ShownRect. Original rect: %d %d %d %d", Hitbox.m_X, Hitbox.m_Y, Hitbox.m_W, Hitbox.m_H);
1961 if(m_pSelectedButton != nullptr)
1962 {
1963 unsigned Movement = std::abs(x: m_pSelectedButton->m_UnitRect.m_X - m_ShownRect->m_X) + std::abs(x: m_pSelectedButton->m_UnitRect.m_Y - m_ShownRect->m_Y);
1964 if(Movement > 10000)
1965 {
1966 // Moved a lot, meaning changes made.
1967 m_UnsavedChanges = true;
1968 }
1969 }
1970 }
1971 else if(m_ActiveFingerState.has_value() && m_ZoomFingerState.has_value())
1972 {
1973 m_ShownRect = m_pSampleButton->m_UnitRect;
1974 vec2 UnitWHDelta;
1975 UnitWHDelta.x = (std::abs(x: m_ActiveFingerState.value().m_Position.x - m_ZoomFingerState.value().m_Position.x) - std::abs(x: m_ZoomStartPos.x)) * BUTTON_SIZE_SCALE;
1976 UnitWHDelta.y = (std::abs(x: m_ActiveFingerState.value().m_Position.y - m_ZoomFingerState.value().m_Position.y) - std::abs(x: m_ZoomStartPos.y)) * BUTTON_SIZE_SCALE;
1977 m_ShownRect->m_W = m_pSampleButton->m_UnitRect.m_W + UnitWHDelta.x;
1978 m_ShownRect->m_H = m_pSampleButton->m_UnitRect.m_H + UnitWHDelta.y;
1979 m_ShownRect->m_W = std::clamp(val: m_ShownRect->m_W, lo: BUTTON_SIZE_MINIMUM, hi: BUTTON_SIZE_MAXIMUM);
1980 m_ShownRect->m_H = std::clamp(val: m_ShownRect->m_H, lo: BUTTON_SIZE_MINIMUM, hi: BUTTON_SIZE_MAXIMUM);
1981 if(m_ShownRect->m_W + m_ShownRect->m_X > BUTTON_SIZE_SCALE)
1982 m_ShownRect->m_W = BUTTON_SIZE_SCALE - m_ShownRect->m_X;
1983 if(m_ShownRect->m_H + m_ShownRect->m_Y > BUTTON_SIZE_SCALE)
1984 m_ShownRect->m_H = BUTTON_SIZE_SCALE - m_ShownRect->m_Y;
1985 // Clamp the biggest W and H so they won't overlap with other buttons. Known as "FindPositionWH".
1986 std::optional<int> BiggestW;
1987 std::optional<int> BiggestH;
1988 std::optional<int> LimitH, LimitW;
1989 for(const auto &Rect : vVisibleButtonRects)
1990 {
1991 // If Overlap
1992 if(!(Rect.m_X + Rect.m_W <= m_ShownRect->m_X || m_ShownRect->m_X + m_ShownRect->m_W <= Rect.m_X || Rect.m_Y + Rect.m_H <= m_ShownRect->m_Y || m_ShownRect->m_Y + m_ShownRect->m_H <= Rect.m_Y))
1993 {
1994 // Calculate the biggest Height and Width it could have.
1995 LimitH = Rect.m_Y - m_ShownRect->m_Y;
1996 LimitW = Rect.m_X - m_ShownRect->m_X;
1997 if(LimitH < BUTTON_SIZE_MINIMUM)
1998 LimitH = std::nullopt;
1999 if(LimitW < BUTTON_SIZE_MINIMUM)
2000 LimitW = std::nullopt;
2001 if(LimitH.has_value() && LimitW.has_value())
2002 {
2003 if(std::abs(x: *LimitH - m_ShownRect->m_H) < std::abs(x: *LimitW - m_ShownRect->m_W))
2004 {
2005 BiggestH = std::min(a: *LimitH, b: BiggestH.value_or(u: BUTTON_SIZE_SCALE));
2006 }
2007 else
2008 {
2009 BiggestW = std::min(a: *LimitW, b: BiggestW.value_or(u: BUTTON_SIZE_SCALE));
2010 }
2011 }
2012 else
2013 {
2014 if(LimitH.has_value())
2015 BiggestH = std::min(a: *LimitH, b: BiggestH.value_or(u: BUTTON_SIZE_SCALE));
2016 else if(LimitW.has_value())
2017 BiggestW = std::min(a: *LimitW, b: BiggestW.value_or(u: BUTTON_SIZE_SCALE));
2018 else
2019 {
2020 /*
2021 * LimitH and W can be nullopt at the same time, because two buttons may be overlapping.
2022 * Holding for long press while another finger is pressed.
2023 * Then it will instantly enter zoom mode while buttons are overlapping with each other.
2024 */
2025 auto Hitbox = CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape);
2026 m_ShownRect = FindPositionXY(vVisibleButtonRects, MyRect: Hitbox);
2027 dbg_assert(m_ShownRect.has_value(), "Unexpected nullopt in m_ShownRect. Original rect: %d %d %d %d", Hitbox.m_X, Hitbox.m_Y, Hitbox.m_W, Hitbox.m_H);
2028 BiggestW = std::nullopt;
2029 BiggestH = std::nullopt;
2030 break;
2031 }
2032 }
2033 }
2034 }
2035 m_ShownRect->m_W = BiggestW.value_or(u&: m_ShownRect->m_W);
2036 m_ShownRect->m_H = BiggestH.value_or(u&: m_ShownRect->m_H);
2037 m_UnsavedChanges = true;
2038 }
2039 // No finger on screen, then show it as is.
2040 else
2041 {
2042 m_ShownRect = m_pSampleButton->m_UnitRect;
2043 }
2044 // Finished moving, no finger on screen.
2045 if(vTouchFingerStates.empty())
2046 {
2047 m_AccumulatedDelta = vec2(0.0f, 0.0f);
2048 std::optional<CUnitRect> OldRect = m_ShownRect;
2049 auto Hitbox = CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape);
2050 m_ShownRect = FindPositionXY(vVisibleButtonRects, MyRect: Hitbox);
2051 dbg_assert(m_ShownRect.has_value(), "Unexpected nullopt in m_ShownRect. Original rect: %d %d %d %d", Hitbox.m_X, Hitbox.m_Y, Hitbox.m_W, Hitbox.m_H);
2052 m_UnsavedChanges |= OldRect != m_ShownRect;
2053 m_pSampleButton->m_UnitRect = (*m_ShownRect);
2054 m_aIssueParam[(int)EIssueType::CACHE_POSITION].m_pTargetButton = m_pSampleButton.get();
2055 m_aIssueParam[(int)EIssueType::CACHE_POSITION].m_Resolved = false;
2056 m_pSampleButton->UpdateScreenFromUnitRect();
2057 }
2058 if(m_ShownRect->m_X == -1)
2059 {
2060 m_UnsavedChanges = true;
2061 m_PopupParam.m_PopupType = EPopupType::NO_SPACE;
2062 m_PopupParam.m_KeepMenuOpen = true;
2063 GameClient()->m_Menus.SetActive(true);
2064 return;
2065 }
2066 m_pSampleButton->UpdateScreenFromUnitRect();
2067 }
2068}
2069
2070void CTouchControls::RenderButtonsEditor()
2071{
2072 for(auto &TouchButton : m_vTouchButtons)
2073 {
2074 if(&TouchButton == m_pSelectedButton)
2075 continue;
2076 TouchButton.UpdateVisibilityEditor();
2077 if(TouchButton.m_VisibilityCached || m_PreviewAllButtons)
2078 {
2079 TouchButton.UpdateScreenFromUnitRect();
2080 TouchButton.Render(Selected: false);
2081 }
2082 }
2083
2084 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
2085 {
2086 m_pSampleButton->Render(Selected: true, Rect: m_ShownRect);
2087 }
2088}
2089
2090std::optional<CTouchControls::CUnitRect> CTouchControls::FindPositionXY(std::vector<CUnitRect> &vVisibleButtonRects, CUnitRect MyRect)
2091{
2092 // Border clamp
2093 MyRect.m_X = std::clamp(val: MyRect.m_X, lo: 0, hi: BUTTON_SIZE_SCALE - MyRect.m_W);
2094 MyRect.m_Y = std::clamp(val: MyRect.m_Y, lo: 0, hi: BUTTON_SIZE_SCALE - MyRect.m_H);
2095 // Not overlapping with any rects
2096 {
2097 bool IfOverlap = std::any_of(first: vVisibleButtonRects.begin(), last: vVisibleButtonRects.end(), pred: [&MyRect](const auto &Rect) {
2098 return MyRect.IsOverlap(Other: Rect);
2099 });
2100 if(!IfOverlap)
2101 return MyRect;
2102 }
2103 if(vVisibleButtonRects != m_vLastUpdateRects || MyRect.m_W != m_LastWidth || MyRect.m_H != m_LastHeight)
2104 {
2105 m_LastWidth = MyRect.m_W;
2106 m_LastHeight = MyRect.m_H;
2107 m_vLastUpdateRects = vVisibleButtonRects;
2108 BuildPositionXY(vVisibleButtonRects: m_vLastUpdateRects, MyRect);
2109 }
2110 std::optional<CUnitRect> Result;
2111 CUnitRect SampleRect;
2112 for(const ivec2 &Target : m_vTargets)
2113 {
2114 SampleRect = {.m_X: Target.x, .m_Y: Target.y, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2115 if(!Result.has_value() || MyRect.Distance(Other: Result.value()) > MyRect.Distance(Other: SampleRect))
2116 Result = SampleRect;
2117 }
2118 int BestXPosition = -BUTTON_SIZE_SCALE, BestYPosition = -BUTTON_SIZE_SCALE, Cur = 0;
2119 std::vector<CUnitRect> vTargetRects;
2120 vTargetRects.reserve(n: m_vLastUpdateRects.size());
2121 std::copy_if(first: m_vXSortedRects.begin(), last: m_vXSortedRects.end(), result: std::back_inserter(x&: vTargetRects), pred: [&](const CUnitRect &Rect) {
2122 return !(Rect.m_Y + Rect.m_H <= MyRect.m_Y || MyRect.m_Y + MyRect.m_H <= Rect.m_Y);
2123 });
2124 for(const CUnitRect &Rect : vTargetRects)
2125 {
2126 if(Cur >= Rect.m_X + Rect.m_W)
2127 continue;
2128 SampleRect = {.m_X: Cur, .m_Y: MyRect.m_Y, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2129 if(Cur + MyRect.m_W <= BUTTON_SIZE_SCALE && !SampleRect.IsOverlap(Other: Rect))
2130 {
2131 BestXPosition = std::abs(x: Cur - MyRect.m_X) < std::abs(x: BestXPosition - MyRect.m_X) ? Cur : BestXPosition;
2132 BestXPosition = std::abs(x: Rect.m_X - MyRect.m_W - MyRect.m_X) < std::abs(x: BestXPosition - MyRect.m_X) ? Rect.m_X - MyRect.m_W : BestXPosition;
2133 }
2134 Cur = Rect.m_X + Rect.m_W;
2135 }
2136 if(Cur + MyRect.m_W <= BUTTON_SIZE_SCALE)
2137 {
2138 BestXPosition = std::abs(x: Cur - MyRect.m_X) < std::abs(x: BestXPosition - MyRect.m_X) ? Cur : BestXPosition;
2139 }
2140
2141 vTargetRects.clear();
2142 std::copy_if(first: m_vYSortedRects.begin(), last: m_vYSortedRects.end(), result: std::back_inserter(x&: vTargetRects), pred: [&](const CUnitRect &Rect) {
2143 return !(Rect.m_X + Rect.m_W <= MyRect.m_X || MyRect.m_X + MyRect.m_W <= Rect.m_X);
2144 });
2145 Cur = 0;
2146 for(const CUnitRect &Rect : vTargetRects)
2147 {
2148 if(Cur >= Rect.m_Y + Rect.m_H)
2149 continue;
2150 SampleRect = {.m_X: MyRect.m_X, .m_Y: Cur, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2151 if(Cur + MyRect.m_H <= BUTTON_SIZE_SCALE && !SampleRect.IsOverlap(Other: Rect))
2152 {
2153 BestYPosition = std::abs(x: Cur - MyRect.m_Y) < std::abs(x: BestYPosition - MyRect.m_Y) ? Cur : BestYPosition;
2154 BestYPosition = std::abs(x: Rect.m_Y - MyRect.m_H - MyRect.m_Y) < std::abs(x: BestYPosition - MyRect.m_Y) ? Rect.m_Y - MyRect.m_H : BestYPosition;
2155 }
2156 Cur = Rect.m_Y + Rect.m_H;
2157 }
2158 if(Cur + MyRect.m_H <= BUTTON_SIZE_SCALE)
2159 {
2160 BestYPosition = std::abs(x: Cur - MyRect.m_Y) < std::abs(x: BestYPosition - MyRect.m_Y) ? Cur : BestYPosition;
2161 }
2162
2163 if(BestXPosition != -BUTTON_SIZE_SCALE)
2164 {
2165 SampleRect = {.m_X: BestXPosition, .m_Y: MyRect.m_Y, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2166 if(!Result.has_value() || MyRect.Distance(Other: Result.value()) > MyRect.Distance(Other: SampleRect))
2167 Result = SampleRect;
2168 }
2169 if(BestYPosition != -BUTTON_SIZE_SCALE)
2170 {
2171 SampleRect = {.m_X: MyRect.m_X, .m_Y: BestYPosition, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2172 if(!Result.has_value() || MyRect.Distance(Other: Result.value()) > MyRect.Distance(Other: SampleRect))
2173 Result = SampleRect;
2174 }
2175 return Result;
2176}
2177
2178void CTouchControls::BuildPositionXY(std::vector<CUnitRect> vVisibleButtonRects, CUnitRect MyRect)
2179{
2180 m_vTargets.clear();
2181 m_vTargets.reserve(n: vVisibleButtonRects.size() * 4);
2182 m_vXSortedRects = m_vYSortedRects = vVisibleButtonRects;
2183 std::sort(first: m_vXSortedRects.begin(), last: m_vXSortedRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2184 return Lhs.m_X < Rhs.m_X;
2185 });
2186 std::sort(first: m_vYSortedRects.begin(), last: m_vYSortedRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2187 return Lhs.m_Y < Rhs.m_Y;
2188 });
2189 std::sort(first: vVisibleButtonRects.begin(), last: vVisibleButtonRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2190 return Lhs.m_X < Rhs.m_X;
2191 });
2192 class CTree
2193 {
2194 public:
2195 void Init(const std::vector<CUnitRect> &vRects)
2196 {
2197 m_vOrder.reserve(n: vRects.size() * 2);
2198 for(const CUnitRect &Rect : vRects)
2199 {
2200 m_vOrder.emplace_back(args: Rect.m_Y);
2201 m_vOrder.emplace_back(args: Rect.m_Y + Rect.m_H);
2202 }
2203 m_vOrder.emplace_back(args: 0);
2204 m_vOrder.emplace_back(args: BUTTON_SIZE_SCALE);
2205 std::sort(first: m_vOrder.begin(), last: m_vOrder.end());
2206 m_vOrder.erase(first: std::unique(first: m_vOrder.begin(), last: m_vOrder.end()), last: m_vOrder.end());
2207 m_vTree.resize(sz: m_vOrder.size() * 4, c: {-1, -1, 0, 0});
2208 New(Start: 0, End: m_vOrder.size() - 2, Cur: 0);
2209 m_vZone.reserve(n: m_vTree.size());
2210 }
2211 void New(int Start, int End, unsigned Cur)
2212 {
2213 if(m_vTree[Cur].x != -1)
2214 return;
2215 m_vTree[Cur].x = Start;
2216 m_vTree[Cur].y = End;
2217 m_vTree[Cur].z = 0;
2218 m_vTree[Cur].w = 0;
2219 }
2220 void Add(int Start, int End, unsigned Cur)
2221 {
2222 m_vTree[Cur].z++;
2223 if(m_vTree[Cur].x == Start && m_vTree[Cur].y == End)
2224 {
2225 m_vTree[Cur].w++;
2226 return;
2227 }
2228 int Mid = (m_vTree[Cur].x + m_vTree[Cur].y) / 2;
2229 New(Start: Mid + 1, End: m_vTree[Cur].y, Cur: Cur * 2 + 2);
2230 New(Start: m_vTree[Cur].x, End: Mid, Cur: Cur * 2 + 1);
2231 if(Start <= Mid)
2232 {
2233 Add(Start, End: minimum<int>(a: Mid, b: End), Cur: Cur * 2 + 1);
2234 }
2235 if(End >= Mid + 1)
2236 {
2237 Add(Start: maximum<int>(a: Mid + 1, b: Start), End, Cur: Cur * 2 + 2);
2238 }
2239 }
2240 void Delete(int Start, int End, unsigned Cur)
2241 {
2242 m_vTree[Cur].z--;
2243 if(m_vTree[Cur].x == Start && m_vTree[Cur].y == End)
2244 {
2245 m_vTree[Cur].w--;
2246 return;
2247 }
2248 int Mid = (m_vTree[Cur].x + m_vTree[Cur].y) / 2;
2249 if(Start <= Mid)
2250 {
2251 Delete(Start, End: minimum<int>(a: Mid, b: End), Cur: Cur * 2 + 1);
2252 }
2253 if(End >= Mid + 1)
2254 {
2255 Delete(Start: maximum<int>(a: Mid + 1, b: Start), End, Cur: Cur * 2 + 2);
2256 }
2257 }
2258 void InnerQuery(unsigned Start)
2259 {
2260 std::vector<unsigned> vStack;
2261 vStack.reserve(n: BUTTON_SIZE_SCALE / BUTTON_SIZE_MINIMUM);
2262 vStack.push_back(x: Start);
2263 while(!vStack.empty())
2264 {
2265 unsigned Cur = vStack.back();
2266 vStack.pop_back();
2267 if(m_vTree[Cur].w > 0)
2268 {
2269 m_vZone.emplace_back(args&: m_vTree[Cur].x, args&: m_vTree[Cur].y);
2270 continue;
2271 }
2272 if(m_vTree[Cur].x == m_vTree[Cur].y || m_vTree[Cur].z == 0)
2273 continue;
2274 if(m_vTree[Cur * 2 + 2].x != -1 && m_vTree[Cur * 2 + 2].z > 0)
2275 {
2276 vStack.push_back(x: (Cur << 1) + 2);
2277 }
2278 if(m_vTree[Cur * 2 + 1].x != -1 && m_vTree[Cur * 2 + 1].z > 0)
2279 {
2280 vStack.push_back(x: (Cur << 1) + 1);
2281 }
2282 }
2283 }
2284 std::vector<ivec2> Query(int Length)
2285 {
2286 m_vZone.clear();
2287 InnerQuery(Start: 0);
2288 if(m_vZone.empty())
2289 {
2290 return {{0, BUTTON_SIZE_SCALE}};
2291 }
2292
2293 // Inverse discretization
2294 for(ivec2 &Zone : m_vZone)
2295 {
2296 Zone.x = m_vOrder[Zone.x];
2297 Zone.y = m_vOrder[Zone.y + 1];
2298 }
2299 if(m_vZone[0].x < Length)
2300 m_vZone[0].x = 0;
2301 // Merge segments.
2302 for(unsigned Index = 1; Index < m_vZone.size(); Index++)
2303 {
2304 if(m_vZone[Index - 1].y + Length <= m_vZone[Index].x)
2305 continue;
2306 m_vZone[Index].x = m_vZone[Index - 1].x;
2307 m_vZone[Index - 1].x = -1;
2308 }
2309 if(m_vZone.back().y + Length > BUTTON_SIZE_SCALE)
2310 m_vZone.back().y = BUTTON_SIZE_SCALE;
2311 m_vZone.erase(first: std::remove_if(first: m_vZone.begin(), last: m_vZone.end(), pred: [](const ivec2 &Zone) { return Zone.x == -1; }),
2312 last: m_vZone.end());
2313 // Result stores obstacles, now turn it into free spaces.
2314 std::vector<ivec2> vFree;
2315 vFree.reserve(n: m_vZone.size());
2316 if(m_vZone[0].x != 0)
2317 vFree.emplace_back(args: 0, args&: m_vZone[0].x);
2318 for(unsigned Index = 1; Index < m_vZone.size(); Index++)
2319 {
2320 vFree.emplace_back(args&: m_vZone[Index - 1].y, args&: m_vZone[Index].x);
2321 }
2322 if(m_vZone.back().y != BUTTON_SIZE_SCALE)
2323 vFree.emplace_back(args&: m_vZone.back().y, args: BUTTON_SIZE_SCALE);
2324 return vFree;
2325 }
2326 ivec2 Discretization(int Start, int End)
2327 {
2328 ivec2 Result;
2329 auto It = std::lower_bound(first: m_vOrder.begin(), last: m_vOrder.end(), val: Start);
2330 Result.x = std::distance(first: m_vOrder.begin(), last: It);
2331 It = std::lower_bound(first: m_vOrder.begin(), last: m_vOrder.end(), val: End);
2332 Result.y = std::distance(first: m_vOrder.begin(), last: It) - 1;
2333 return Result;
2334 }
2335
2336 private:
2337 std::vector<int> m_vOrder;
2338 std::vector<ivec4> m_vTree;
2339 std::vector<ivec2> m_vZone;
2340 } Tree;
2341
2342 std::set<int> CandidateX;
2343 for(const CUnitRect &Rect : vVisibleButtonRects)
2344 {
2345 // Rect right border.
2346 int Pos = Rect.m_X + Rect.m_W;
2347 if(Pos + MyRect.m_W <= BUTTON_SIZE_SCALE)
2348 CandidateX.insert(x: Pos);
2349 // Rect left border.
2350 Pos = Rect.m_X - MyRect.m_W;
2351 if(Pos >= 0)
2352 CandidateX.insert(x: Pos);
2353 }
2354 CandidateX.insert(position: CandidateX.begin(), x: 0);
2355 CandidateX.insert(x: BUTTON_SIZE_SCALE - MyRect.m_W);
2356 Tree.Init(vRects: vVisibleButtonRects);
2357
2358 auto Cmp = [&vVisibleButtonRects](int Lhs, int Rhs) -> bool {
2359 return vVisibleButtonRects[Lhs].m_X + vVisibleButtonRects[Lhs].m_W > vVisibleButtonRects[Rhs].m_X + vVisibleButtonRects[Rhs].m_W;
2360 };
2361 std::priority_queue<int, std::vector<int>, decltype(Cmp)> Out(Cmp);
2362
2363 unsigned Index = 0;
2364
2365 for(int CurrentX : CandidateX)
2366 {
2367 while(Index < vVisibleButtonRects.size() && vVisibleButtonRects[Index].m_X < CurrentX + MyRect.m_W)
2368 {
2369 auto Segment = Tree.Discretization(Start: vVisibleButtonRects[Index].m_Y, End: vVisibleButtonRects[Index].m_Y + vVisibleButtonRects[Index].m_H);
2370 Tree.Add(Start: Segment.x, End: Segment.y, Cur: 0);
2371 Out.emplace(args: Index++);
2372 }
2373 while(!Out.empty() && vVisibleButtonRects[Out.top()].m_X + vVisibleButtonRects[Out.top()].m_W <= CurrentX)
2374 {
2375 auto Segment = Tree.Discretization(Start: vVisibleButtonRects[Out.top()].m_Y, End: vVisibleButtonRects[Out.top()].m_Y + vVisibleButtonRects[Out.top()].m_H);
2376 Tree.Delete(Start: Segment.x, End: Segment.y, Cur: 0);
2377 Out.pop();
2378 }
2379 auto Spaces = Tree.Query(Length: MyRect.m_H);
2380 for(ivec2 &Space : Spaces)
2381 {
2382 m_vTargets.emplace_back(args&: CurrentX, args&: Space.x);
2383 m_vTargets.emplace_back(args&: CurrentX, args: Space.y - MyRect.m_H);
2384 }
2385 }
2386}
2387
2388// Create a new button and push_back to m_vTouchButton, then return a pointer.
2389CTouchControls::CTouchButton *CTouchControls::NewButton()
2390{
2391 // Ensure m_pSelectedButton doesn't go wild.
2392 int Target = -1;
2393 if(m_pSelectedButton != nullptr)
2394 Target = std::distance(first: m_vTouchButtons.data(), last: m_pSelectedButton);
2395 CTouchButton NewButton(this);
2396 NewButton.m_pBehavior = std::make_unique<CBindTouchButtonBehavior>(args: "", args: CButtonLabel::EType::PLAIN, args: "");
2397 // So the vector's elements might be moved. If moved all button's m_VisibilityCached will be set to false. This should be prevented.
2398 std::vector<bool> vCachedVisibilities;
2399 vCachedVisibilities.reserve(n: m_vTouchButtons.size());
2400 for(const auto &Button : m_vTouchButtons)
2401 {
2402 vCachedVisibilities.emplace_back(args: Button.m_VisibilityCached);
2403 }
2404 for(unsigned Iterator = 0; Iterator < vCachedVisibilities.size(); Iterator++)
2405 {
2406 m_vTouchButtons[Iterator].m_VisibilityCached = vCachedVisibilities[Iterator];
2407 }
2408 m_vTouchButtons.push_back(x: std::move(NewButton));
2409 if(Target != -1)
2410 m_pSelectedButton = &m_vTouchButtons[Target];
2411 return &m_vTouchButtons.back();
2412}
2413
2414void CTouchControls::DeleteSelectedButton()
2415{
2416 if(m_pSelectedButton != nullptr)
2417 {
2418 auto DeleteIt = m_vTouchButtons.begin() + (m_pSelectedButton - m_vTouchButtons.data());
2419 m_vTouchButtons.erase(position: DeleteIt);
2420 }
2421 ResetButtonPointers();
2422 m_UnsavedChanges = false;
2423}
2424
2425bool CTouchControls::IsRectOverlapping(CUnitRect MyRect, EButtonShape Shape) const
2426{
2427 MyRect = CalculateHitbox(Rect: MyRect, Shape);
2428 for(const auto &TouchButton : m_vTouchButtons)
2429 {
2430 if(m_pSelectedButton == &TouchButton)
2431 continue;
2432 bool IsVisible = std::all_of(first: TouchButton.m_vVisibilities.begin(), last: TouchButton.m_vVisibilities.end(), pred: [&](const auto &Visibility) {
2433 return Visibility.m_Parity == m_aVirtualVisibilities[(int)Visibility.m_Type];
2434 });
2435 if(IsVisible && MyRect.IsOverlap(Other: CalculateHitbox(Rect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape)))
2436 return true;
2437 }
2438 return false;
2439}
2440
2441std::optional<CTouchControls::CUnitRect> CTouchControls::UpdatePosition(CUnitRect MyRect, EButtonShape Shape, bool Ignore)
2442{
2443 MyRect = CalculateHitbox(Rect: MyRect, Shape);
2444 std::vector<CUnitRect> vVisibleButtonRects;
2445 for(const auto &TouchButton : m_vTouchButtons)
2446 {
2447 if(m_pSelectedButton == &TouchButton && !Ignore)
2448 continue;
2449 bool IsVisible = std::all_of(first: TouchButton.m_vVisibilities.begin(), last: TouchButton.m_vVisibilities.end(), pred: [&](const auto &Visibility) {
2450 return Visibility.m_Parity == m_aVirtualVisibilities[(int)Visibility.m_Type];
2451 });
2452 if(!IsVisible)
2453 continue;
2454 vVisibleButtonRects.emplace_back(args: CalculateHitbox(Rect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape));
2455 }
2456 return FindPositionXY(vVisibleButtonRects, MyRect);
2457}
2458
2459void CTouchControls::ResetButtonPointers()
2460{
2461 m_pSelectedButton = nullptr;
2462 m_pSampleButton = nullptr;
2463 m_ShownRect = std::nullopt;
2464}
2465
2466// After sending the type, the popup should be reset immediately.
2467CTouchControls::CPopupParam CTouchControls::RequiredPopup()
2468{
2469 CPopupParam ReturnPopup = m_PopupParam;
2470 // Reset type so it won't be called for multiple times.
2471 m_PopupParam.m_PopupType = EPopupType::NUM_POPUPS;
2472 return ReturnPopup;
2473}
2474
2475// Return true if any issue is not finished.
2476bool CTouchControls::AnyIssueNotResolved() const
2477{
2478 return std::any_of(first: m_aIssueParam.begin(), last: m_aIssueParam.end(), pred: [](const auto &Issue) {
2479 return !Issue.m_Resolved;
2480 });
2481}
2482
2483std::array<CTouchControls::CIssueParam, (unsigned)CTouchControls::EIssueType::NUM_ISSUES> CTouchControls::Issues()
2484{
2485 std::array<CIssueParam, (unsigned)EIssueType::NUM_ISSUES> aUnresolvedIssues;
2486 for(int Issue = 0; Issue < (int)EIssueType::NUM_ISSUES; Issue++)
2487 {
2488 aUnresolvedIssues[Issue] = m_aIssueParam[Issue];
2489 m_aIssueParam[Issue].m_Resolved = true;
2490 }
2491 return aUnresolvedIssues;
2492}
2493
2494// Make it look like the button, only have bind behavior. This is only used on m_pSampleButton.
2495void CTouchControls::UpdateSampleButton(const CTouchButton &SrcButton)
2496{
2497 dbg_assert(m_pSampleButton != nullptr, "Sample button not created");
2498 m_pSampleButton->m_UnitRect = SrcButton.m_UnitRect;
2499 m_pSampleButton->m_Shape = SrcButton.m_Shape;
2500 m_pSampleButton->m_vVisibilities = SrcButton.m_vVisibilities;
2501 CButtonLabel Label = SrcButton.m_pBehavior->GetLabel();
2502 m_pSampleButton->m_pBehavior = std::make_unique<CBindTouchButtonBehavior>(args&: Label.m_pLabel, args&: Label.m_Type, args: "");
2503 m_pSampleButton->UpdatePointers();
2504 m_pSampleButton->m_UnitRect = CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape);
2505 m_pSampleButton->UpdateScreenFromUnitRect();
2506}
2507
2508std::vector<CTouchControls::CTouchButton *> CTouchControls::GetButtonsEditor()
2509{
2510 std::vector<CTouchButton *> vpButtons;
2511 vpButtons.reserve(n: m_vTouchButtons.size());
2512 for(auto &TouchButton : m_vTouchButtons)
2513 {
2514 TouchButton.UpdateVisibilityEditor();
2515 vpButtons.emplace_back(args: &TouchButton);
2516 }
2517 return vpButtons;
2518}
2519
2520float CTouchControls::CUnitRect::Distance(const CUnitRect &Other) const
2521{
2522 vec2 Delta;
2523 Delta.x = Other.m_X + Other.m_W / 2.0f - m_X - m_W / 2.0f;
2524 Delta.y = Other.m_Y + Other.m_H / 2.0f - m_Y - m_H / 2.0f;
2525 return length(a: Delta / BUTTON_SIZE_SCALE);
2526}
2527