1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3
4#include "editor.h"
5
6#include "auto_map.h"
7#include "editor_actions.h"
8
9#include <base/color.h>
10#include <base/dbg.h>
11#include <base/fs.h>
12#include <base/io.h>
13#include <base/log.h>
14#include <base/mem.h>
15#include <base/str.h>
16#include <base/time.h>
17
18#include <engine/client.h>
19#include <engine/client/keyboard.h>
20#include <engine/engine.h>
21#include <engine/font_icons.h>
22#include <engine/gfx/image_loader.h>
23#include <engine/gfx/image_manipulation.h>
24#include <engine/graphics.h>
25#include <engine/input.h>
26#include <engine/keys.h>
27#include <engine/shared/config.h>
28#include <engine/storage.h>
29#include <engine/textrender.h>
30
31#include <generated/client_data.h>
32
33#include <game/client/components/camera.h>
34#include <game/client/gameclient.h>
35#include <game/client/lineinput.h>
36#include <game/client/ui.h>
37#include <game/client/ui_listbox.h>
38#include <game/client/ui_scrollregion.h>
39#include <game/editor/editor_history.h>
40#include <game/editor/mapitems/image.h>
41#include <game/editor/mapitems/sound.h>
42#include <game/localization.h>
43
44#include <algorithm>
45#include <chrono>
46#include <iterator>
47#include <limits>
48#include <tuple>
49#include <type_traits>
50#include <unordered_map>
51
52static const char *VANILLA_IMAGES[] = {
53 "bg_cloud1",
54 "bg_cloud2",
55 "bg_cloud3",
56 "desert_doodads",
57 "desert_main",
58 "desert_mountains",
59 "desert_mountains2",
60 "desert_sun",
61 "generic_deathtiles",
62 "generic_unhookable",
63 "grass_doodads",
64 "grass_main",
65 "jungle_background",
66 "jungle_deathtiles",
67 "jungle_doodads",
68 "jungle_main",
69 "jungle_midground",
70 "jungle_unhookables",
71 "moon",
72 "mountains",
73 "snow",
74 "stars",
75 "sun",
76 "winter_doodads",
77 "winter_main",
78 "winter_mountains",
79 "winter_mountains2",
80 "winter_mountains3"};
81
82bool CEditor::IsVanillaImage(const char *pImage)
83{
84 return std::any_of(first: std::begin(arr&: VANILLA_IMAGES), last: std::end(arr&: VANILLA_IMAGES), pred: [pImage](const char *pVanillaImage) { return str_comp(a: pImage, b: pVanillaImage) == 0; });
85}
86
87bool CEditor::CallbackOpenMap(const char *pFilename, int StorageType, void *pUser)
88{
89 CEditor *pEditor = (CEditor *)pUser;
90 if(pEditor->Load(pFilename, StorageType))
91 {
92 pEditor->Map()->m_ValidSaveFilename = StorageType == IStorage::TYPE_SAVE && pEditor->m_FileBrowser.IsValidSaveFilename();
93 if(pEditor->m_Dialog == DIALOG_FILE)
94 {
95 pEditor->OnDialogClose();
96 }
97 return true;
98 }
99 else
100 {
101 pEditor->ShowFileDialogError(pFormat: "Failed to load map from file '%s'.", pFilename);
102 return false;
103 }
104}
105
106bool CEditor::CallbackAppendMap(const char *pFilename, int StorageType, void *pUser)
107{
108 CEditor *pEditor = (CEditor *)pUser;
109 const auto &&ErrorHandler = [pEditor](const char *pErrorMessage) {
110 pEditor->ShowFileDialogError(pFormat: "%s", pErrorMessage);
111 log_error("editor/append", "%s", pErrorMessage);
112 };
113 if(pEditor->Map()->Append(pFilename, StorageType, IgnoreHistory: false, ErrorHandler))
114 {
115 pEditor->OnDialogClose();
116 return true;
117 }
118 else
119 {
120 pEditor->ShowFileDialogError(pFormat: "Failed to load map from file '%s'.", pFilename);
121 return false;
122 }
123}
124
125bool CEditor::CallbackSaveMap(const char *pFilename, int StorageType, void *pUser)
126{
127 dbg_assert(StorageType == IStorage::TYPE_SAVE, "Saving only allowed for IStorage::TYPE_SAVE");
128
129 CEditor *pEditor = static_cast<CEditor *>(pUser);
130 const bool CloseAfterSave = pEditor->m_CloseMapAfterSave;
131 pEditor->m_CloseMapAfterSave = false;
132
133 // Save map to specified file
134 if(pEditor->Save(pFilename))
135 {
136 if(pEditor->Map()->m_aFilename != pFilename)
137 {
138 str_copy(dst&: pEditor->Map()->m_aFilename, src: pFilename);
139 }
140 pEditor->Map()->m_ValidSaveFilename = true;
141 pEditor->Map()->m_Modified = false;
142 pEditor->UpdateMapDisplayNames();
143 pEditor->Map()->m_CloseOnSave = CloseAfterSave;
144 }
145 else
146 {
147 pEditor->ShowFileDialogError(pFormat: "Failed to save map to file '%s'.", pFilename);
148 return false;
149 }
150
151 // Also update autosave if it's older than half the configured autosave interval, so we also have periodic backups.
152 const float Time = pEditor->Client()->GlobalTime();
153 if(g_Config.m_EdAutosaveInterval > 0 && pEditor->Map()->m_LastSaveTime < Time && Time - pEditor->Map()->m_LastSaveTime > 30 * g_Config.m_EdAutosaveInterval)
154 {
155 const auto &&ErrorHandler = [pEditor](const char *pErrorMessage) {
156 pEditor->ShowFileDialogError(pFormat: "%s", pErrorMessage);
157 log_error("editor/autosave", "%s", pErrorMessage);
158 };
159 if(!pEditor->Map()->PerformAutosave(ErrorHandler))
160 return false;
161 }
162
163 pEditor->OnDialogClose();
164 return true;
165}
166
167bool CEditor::CallbackSaveCopyMap(const char *pFilename, int StorageType, void *pUser)
168{
169 dbg_assert(StorageType == IStorage::TYPE_SAVE, "Saving only allowed for IStorage::TYPE_SAVE");
170
171 CEditor *pEditor = static_cast<CEditor *>(pUser);
172
173 if(pEditor->Save(pFilename))
174 {
175 pEditor->OnDialogClose();
176 return true;
177 }
178 else
179 {
180 pEditor->ShowFileDialogError(pFormat: "Failed to save map to file '%s'.", pFilename);
181 return false;
182 }
183}
184
185bool CEditor::CallbackSaveImage(const char *pFilename, int StorageType, void *pUser)
186{
187 dbg_assert(StorageType == IStorage::TYPE_SAVE, "Saving only allowed for IStorage::TYPE_SAVE");
188
189 CEditor *pEditor = static_cast<CEditor *>(pUser);
190
191 std::shared_ptr<CEditorImage> pImg = pEditor->Map()->SelectedImage();
192
193 if(CImageLoader::SavePng(File: pEditor->Storage()->OpenFile(pFilename, Flags: IOFLAG_WRITE, Type: StorageType), pFilename, Image: *pImg))
194 {
195 pEditor->OnDialogClose();
196 return true;
197 }
198 else
199 {
200 pEditor->ShowFileDialogError(pFormat: "Failed to write image to file '%s'.", pFilename);
201 return false;
202 }
203}
204
205bool CEditor::CallbackSaveSound(const char *pFilename, int StorageType, void *pUser)
206{
207 dbg_assert(StorageType == IStorage::TYPE_SAVE, "Saving only allowed for IStorage::TYPE_SAVE");
208
209 CEditor *pEditor = static_cast<CEditor *>(pUser);
210
211 std::shared_ptr<CEditorSound> pSound = pEditor->Map()->SelectedSound();
212
213 IOHANDLE File = pEditor->Storage()->OpenFile(pFilename, Flags: IOFLAG_WRITE, Type: StorageType);
214 if(File)
215 {
216 io_write(io: File, buffer: pSound->m_pData, size: pSound->m_DataSize);
217 io_close(io: File);
218 pEditor->OnDialogClose();
219 return true;
220 }
221 pEditor->ShowFileDialogError(pFormat: "Failed to open file '%s'.", pFilename);
222 return false;
223}
224
225bool CEditor::CallbackCustomEntities(const char *pFilename, int StorageType, void *pUser)
226{
227 CEditor *pEditor = (CEditor *)pUser;
228
229 char aBuf[IO_MAX_PATH_LENGTH];
230 fs_split_file_extension(filename: fs_filename(path: pFilename), name: aBuf, name_size: sizeof(aBuf));
231
232 if(std::find(first: pEditor->m_vSelectEntitiesFiles.begin(), last: pEditor->m_vSelectEntitiesFiles.end(), val: std::string(aBuf)) != pEditor->m_vSelectEntitiesFiles.end())
233 {
234 pEditor->ShowFileDialogError(pFormat: "Custom entities cannot have the same name as default entities.");
235 return false;
236 }
237
238 CImageInfo ImgInfo;
239 if(!pEditor->Graphics()->LoadPng(Image&: ImgInfo, pFilename, StorageType))
240 {
241 pEditor->ShowFileDialogError(pFormat: "Failed to load image from file '%s'.", pFilename);
242 return false;
243 }
244
245 pEditor->m_SelectEntitiesImage = aBuf;
246 pEditor->m_AllowPlaceUnusedTiles = EUnusedEntities::ALLOWED_IMPLICIT;
247 pEditor->m_PreventUnusedTilesWasWarned = false;
248
249 pEditor->Graphics()->UnloadTexture(pIndex: &pEditor->m_EntitiesTexture);
250 pEditor->m_EntitiesTexture = pEditor->Graphics()->LoadTextureRawMove(Image&: ImgInfo, Flags: pEditor->Graphics()->TextureLoadFlags());
251
252 pEditor->OnDialogClose();
253 return true;
254}
255
256void CEditor::DoAudioPreview(CUIRect View, const void *pPlayPauseButtonId, const void *pStopButtonId, const void *pSeekBarId, int SampleId)
257{
258 CUIRect Button, SeekBar;
259 // play/pause button
260 {
261 View.VSplitLeft(Cut: View.h, pLeft: &Button, pRight: &View);
262 if(DoButton_FontIcon(pId: pPlayPauseButtonId, pText: Sound()->IsPlaying(SampleId) ? FontIcon::PAUSE : FontIcon::PLAY, Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "Play/pause audio preview.", Corners: IGraphics::CORNER_ALL) ||
263 (m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_SPACE)))
264 {
265 if(Sound()->IsPlaying(SampleId))
266 {
267 Sound()->Pause(SampleId);
268 }
269 else
270 {
271 if(SampleId != m_ToolbarPreviewSound && m_ToolbarPreviewSound >= 0 && Sound()->IsPlaying(SampleId: m_ToolbarPreviewSound))
272 Sound()->Pause(SampleId: m_ToolbarPreviewSound);
273
274 Sound()->Play(ChannelId: CSounds::CHN_GUI, SampleId, Flags: ISound::FLAG_PREVIEW, Volume: 1.0f);
275 }
276 }
277 }
278 // stop button
279 {
280 View.VSplitLeft(Cut: 2.0f, pLeft: nullptr, pRight: &View);
281 View.VSplitLeft(Cut: View.h, pLeft: &Button, pRight: &View);
282 if(DoButton_FontIcon(pId: pStopButtonId, pText: FontIcon::STOP, Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "Stop audio preview.", Corners: IGraphics::CORNER_ALL))
283 {
284 Sound()->Stop(SampleId);
285 }
286 }
287 // do seekbar
288 {
289 View.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &View);
290 const float Cut = std::min(a: View.w, b: 200.0f);
291 View.VSplitLeft(Cut, pLeft: &SeekBar, pRight: &View);
292 SeekBar.HMargin(Cut: 2.5f, pOtherRect: &SeekBar);
293
294 const float Rounding = 5.0f;
295
296 char aBuffer[64];
297 const float CurrentTime = Sound()->GetSampleCurrentTime(SampleId);
298 const float TotalTime = Sound()->GetSampleTotalTime(SampleId);
299
300 // draw seek bar
301 SeekBar.Draw(Color: ColorRGBA(0, 0, 0, 0.5f), Corners: IGraphics::CORNER_ALL, Rounding);
302
303 // draw filled bar
304 const float Amount = CurrentTime / TotalTime;
305 CUIRect FilledBar = SeekBar;
306 FilledBar.w = 2 * Rounding + (FilledBar.w - 2 * Rounding) * Amount;
307 FilledBar.Draw(Color: ColorRGBA(1, 1, 1, 0.5f), Corners: IGraphics::CORNER_ALL, Rounding);
308
309 // draw time
310 char aCurrentTime[32];
311 str_time_float(secs: CurrentTime, format: ETimeFormat::HOURS, buffer: aCurrentTime, buffer_size: sizeof(aCurrentTime));
312 char aTotalTime[32];
313 str_time_float(secs: TotalTime, format: ETimeFormat::HOURS, buffer: aTotalTime, buffer_size: sizeof(aTotalTime));
314 str_format(buffer: aBuffer, buffer_size: sizeof(aBuffer), format: "%s / %s", aCurrentTime, aTotalTime);
315 Ui()->DoLabel(pRect: &SeekBar, pText: aBuffer, Size: SeekBar.h * 0.70f, Align: TEXTALIGN_MC);
316
317 // do the logic
318 const bool Inside = Ui()->MouseInside(pRect: &SeekBar);
319
320 if(Ui()->CheckActiveItem(pId: pSeekBarId))
321 {
322 if(!Ui()->MouseButton(Index: 0))
323 {
324 Ui()->SetActiveItem(nullptr);
325 }
326 else
327 {
328 const float AmountSeek = std::clamp(val: (Ui()->MouseX() - SeekBar.x - Rounding) / (SeekBar.w - 2 * Rounding), lo: 0.0f, hi: 1.0f);
329 Sound()->SetSampleCurrentTime(SampleId, Time: AmountSeek);
330 }
331 }
332 else if(Ui()->HotItem() == pSeekBarId)
333 {
334 if(Ui()->MouseButton(Index: 0))
335 Ui()->SetActiveItem(pSeekBarId);
336 }
337
338 if(Inside && !Ui()->MouseButton(Index: 0))
339 Ui()->SetHotItem(pSeekBarId);
340 }
341}
342
343void CEditor::DoMapTabs(CUIRect MapTabs)
344{
345 CScrollRegionParams ScrollParams;
346 ScrollParams.m_ScrollbarThickness = 6.0f;
347 ScrollParams.m_ScrollbarMargin = 2.0f;
348 ScrollParams.m_ScrollbarNoOuterMargin = true;
349 ScrollParams.m_ScrollUnit = 140.0f;
350 ScrollParams.m_ScrollHorizontal = true;
351 m_MapTabsScrollRegion.Begin(pClipRect: &MapTabs, pParams: &ScrollParams);
352
353 size_t Index = 0;
354 std::optional<size_t> CloseIndex = std::nullopt;
355 for(const auto &pMap : m_vpMaps)
356 {
357 const float ButtonWidth = std::clamp(val: TextRender()->TextWidth(Size: 10.0f, pText: pMap->m_aDisplayName) + 10.0f, lo: 60.0f, hi: 120.0f);
358
359 CUIRect MapButton;
360 MapTabs.VSplitLeft(Cut: ButtonWidth + 18.0f, pLeft: &MapButton, pRight: &MapTabs);
361 MapTabs.VSplitLeft(Cut: 2.0f, pLeft: nullptr, pRight: &MapTabs);
362 if(m_MapTabsScrollRegion.AddRect(Rect: MapButton, ShouldScrollHere: m_MapTabsRevealSelected && m_SelectedMap == Index))
363 {
364 CUIRect CloseButton;
365 MapButton.VSplitRight(Cut: 18.0f, pLeft: &MapButton, pRight: &CloseButton);
366
367 const bool Saving = IsSaving(pFilename: pMap->m_aFilename);
368
369 char aTooltip[256];
370 str_format(buffer: aTooltip, buffer_size: sizeof(aTooltip), format: "Select map '%s'.", pMap->m_aFilename[0] == '\0' ? "unnamed" : pMap->m_aFilename);
371 const int TabButtonResult = DoButton_Ex(pId: &pMap->m_TabSelectButtonId,
372 pText: pMap->m_aDisplayName, Checked: m_SelectedMap == Index ? 1 : 0, pRect: &MapButton, Flags: BUTTONFLAG_LEFT | BUTTONFLAG_RIGHT | (Saving ? 0 : (int)BUTTONFLAG_MIDDLE),
373 pToolTip: aTooltip, Corners: IGraphics::CORNER_L);
374
375 int CloseButtonResult;
376 if(Saving)
377 {
378 CloseButtonResult = DoButton_Ex(pId: &pMap->m_TabCloseButtonId, pText: "", Checked: 0, pRect: &CloseButton, Flags: BUTTONFLAG_RIGHT, pToolTip: "This map is being saved.", Corners: IGraphics::CORNER_R);
379 Ui()->RenderProgressSpinner(Center: CloseButton.Center(), OuterRadius: 4.0f);
380 }
381 else
382 {
383 const bool ShowCloseIcon = !pMap->m_Modified || Ui()->HotItem() == &pMap->m_TabCloseButtonId;
384 CloseButtonResult = DoButton_FontIcon(pId: &pMap->m_TabCloseButtonId,
385 pText: ShowCloseIcon ? FontIcon::XMARK : FontIcon::CIRCLE, Checked: 0, pRect: &CloseButton, Flags: BUTTONFLAG_ALL,
386 pToolTip: pMap->m_Modified ? "Close the selected map. This map has unsaved changes." : "Close the selected map.", Corners: IGraphics::CORNER_R, FontSize: ShowCloseIcon ? 9.0f : 6.0f);
387 }
388
389 if(TabButtonResult == 1)
390 {
391 m_SelectedMap = Index;
392 m_MapTabsScrollRegion.ScrollHere();
393 Reset();
394 }
395 else if(TabButtonResult == 2 || CloseButtonResult == 2)
396 {
397 m_PopupMapTab.m_pEditor = this;
398 m_PopupMapTab.m_SelectedMap = Index;
399 Ui()->DoPopupMenu(pId: &m_PopupMapTab, X: Ui()->MouseX(), Y: Ui()->MouseY(), Width: 120.0f, Height: 80.0f, pContext: &m_PopupMapTab, pfnFunc: CPopupMapTab::Render);
400 }
401 else if(TabButtonResult == 3 || CloseButtonResult == 1 || CloseButtonResult == 3)
402 {
403 CloseIndex = Index;
404 }
405 }
406
407 ++Index;
408 }
409
410 m_MapTabsRevealSelected = false;
411 m_MapTabsScrollRegion.End();
412
413 if(CloseIndex.has_value())
414 {
415 CloseMap(Index: CloseIndex.value(), Confirm: true);
416 }
417
418 if(m_Dialog == DIALOG_NONE &&
419 CLineInput::GetActiveInput() == nullptr &&
420 Ui()->CheckActiveItem(pId: nullptr))
421 {
422 // Close selected map with Ctrl+F4
423 if(!CloseIndex.has_value() &&
424 Input()->ModifierIsPressed() &&
425 Input()->KeyPress(Key: KEY_F4))
426 {
427 CloseMap(Index: m_SelectedMap, Confirm: true);
428 }
429
430 // Switch between maps with Ctrl+Tab and Ctrl+Shift+Tab
431 if(m_vpMaps.size() > 1 &&
432 Input()->ModifierIsPressed() &&
433 Input()->KeyPress(Key: KEY_TAB))
434 {
435 if(Input()->ShiftIsPressed())
436 {
437 m_SelectedMap = m_SelectedMap == 0 ? m_vpMaps.size() - 1 : m_SelectedMap - 1;
438 }
439 else
440 {
441 m_SelectedMap = m_SelectedMap == m_vpMaps.size() - 1 ? 0 : m_SelectedMap + 1;
442 }
443 m_MapTabsRevealSelected = true;
444 Reset();
445 }
446 }
447}
448
449void CEditor::DoToolbarLayers(CUIRect ToolBar)
450{
451 const bool ModPressed = Input()->ModifierIsPressed();
452 const bool ShiftPressed = Input()->ShiftIsPressed();
453
454 // handle shortcut for info button
455 if(m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_I) && ModPressed && !ShiftPressed)
456 {
457 if(m_ShowTileInfo == SHOW_TILE_HEXADECIMAL)
458 m_ShowTileInfo = SHOW_TILE_DECIMAL;
459 else if(m_ShowTileInfo != SHOW_TILE_OFF)
460 m_ShowTileInfo = SHOW_TILE_OFF;
461 else
462 m_ShowTileInfo = SHOW_TILE_DECIMAL;
463 }
464
465 // handle shortcut for hex button
466 if(m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_I) && ModPressed && ShiftPressed)
467 {
468 m_ShowTileInfo = m_ShowTileInfo == SHOW_TILE_HEXADECIMAL ? SHOW_TILE_OFF : SHOW_TILE_HEXADECIMAL;
469 }
470
471 // handle shortcut for unused button
472 if(m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_U) && ModPressed && m_AllowPlaceUnusedTiles != EUnusedEntities::ALLOWED_IMPLICIT)
473 {
474 if(m_AllowPlaceUnusedTiles == EUnusedEntities::ALLOWED_EXPLICIT)
475 {
476 m_AllowPlaceUnusedTiles = EUnusedEntities::NOT_ALLOWED;
477 }
478 else
479 {
480 m_AllowPlaceUnusedTiles = EUnusedEntities::ALLOWED_EXPLICIT;
481 }
482 }
483
484 CUIRect ToolbarTop, ToolbarBottom;
485 CUIRect Button;
486
487 ToolBar.HSplitMid(pTop: &ToolbarTop, pBottom: &ToolbarBottom, Spacing: 5.0f);
488
489 // top line buttons
490 {
491 // detail button
492 ToolbarTop.VSplitLeft(Cut: 40.0f, pLeft: &Button, pRight: &ToolbarTop);
493 static int s_HqButton = 0;
494 if(DoButton_Editor(pId: &s_HqButton, pText: "HD", Checked: Map()->m_ShowDetail, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[Ctrl+H] Toggle high detail.") ||
495 (m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_H) && ModPressed))
496 {
497 Map()->m_ShowDetail = !Map()->m_ShowDetail;
498 }
499
500 ToolbarTop.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarTop);
501
502 // animation buttons
503 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
504 static char s_JumpStartButton = 0;
505 if(DoButton_FontIcon(pId: &s_JumpStartButton, pText: FontIcon::BACKWARD_STEP, Checked: false, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "Jump to beginning of animation.", Corners: IGraphics::CORNER_L))
506 {
507 Map()->m_EnvelopeEvaluator.m_AnimateTime = 0;
508 Map()->m_EnvelopeEvaluator.m_Animate = false;
509 }
510
511 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
512 static char s_AnimateButton = 0;
513 if(DoButton_FontIcon(pId: &s_AnimateButton, pText: Map()->m_EnvelopeEvaluator.m_Animate ? FontIcon::PAUSE : FontIcon::PLAY, Checked: Map()->m_EnvelopeEvaluator.m_Animate, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[Ctrl+M] Toggle animation.", Corners: IGraphics::CORNER_NONE) ||
514 (m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_M) && ModPressed))
515 {
516 Map()->m_EnvelopeEvaluator.m_AnimateStart = Client()->GlobalTime() - Map()->m_EnvelopeEvaluator.m_AnimateTime;
517 Map()->m_EnvelopeEvaluator.m_Animate = !Map()->m_EnvelopeEvaluator.m_Animate;
518 }
519
520 // animation settings button
521 ToolbarTop.VSplitLeft(Cut: 14.0f, pLeft: &Button, pRight: &ToolbarTop);
522 static char s_AnimateSettingsButton;
523 if(DoButton_FontIcon(pId: &s_AnimateSettingsButton, pText: FontIcon::CIRCLE_CHEVRON_DOWN, Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "Change the animation settings.", Corners: IGraphics::CORNER_R, FontSize: 8.0f))
524 {
525 Map()->m_EnvelopeEvaluator.m_AnimateUpdatePopup = true;
526 static SPopupMenuId s_PopupAnimateSettingsId;
527 Ui()->DoPopupMenu(pId: &s_PopupAnimateSettingsId, X: Button.x, Y: Button.y + Button.h, Width: 150.0f, Height: 37.0f, pContext: this, pfnFunc: PopupAnimateSettings);
528 }
529
530 ToolbarTop.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarTop);
531
532 // proof button
533 ToolbarTop.VSplitLeft(Cut: 40.0f, pLeft: &Button, pRight: &ToolbarTop);
534 if(DoButton_Ex(pId: &m_QuickActionProof, pText: m_QuickActionProof.Label(), Checked: m_QuickActionProof.Active(), pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionProof.Description(), Corners: IGraphics::CORNER_L))
535 {
536 m_QuickActionProof.Call();
537 }
538
539 ToolbarTop.VSplitLeft(Cut: 14.0f, pLeft: &Button, pRight: &ToolbarTop);
540 static int s_ProofModeButton = 0;
541 if(DoButton_FontIcon(pId: &s_ProofModeButton, pText: FontIcon::CIRCLE_CHEVRON_DOWN, Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "Select proof mode.", Corners: IGraphics::CORNER_R, FontSize: 8.0f))
542 {
543 static SPopupMenuId s_PopupProofModeId;
544 Ui()->DoPopupMenu(pId: &s_PopupProofModeId, X: Button.x, Y: Button.y + Button.h, Width: 60.0f, Height: 36.0f, pContext: this, pfnFunc: PopupProofMode);
545 }
546
547 ToolbarTop.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarTop);
548
549 // zoom button
550 ToolbarTop.VSplitLeft(Cut: 40.0f, pLeft: &Button, pRight: &ToolbarTop);
551 static int s_ZoomButton = 0;
552 if(DoButton_Editor(pId: &s_ZoomButton, pText: "Zoom", Checked: Map()->m_PreviewZoom, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "Toggle preview of how layers will be zoomed ingame."))
553 {
554 Map()->m_PreviewZoom = !Map()->m_PreviewZoom;
555 }
556
557 ToolbarTop.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarTop);
558
559 // grid button
560 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
561 static int s_GridButton = 0;
562 if(DoButton_FontIcon(pId: &s_GridButton, pText: FontIcon::BORDER_ALL, Checked: m_QuickActionToggleGrid.Active(), pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionToggleGrid.Description(), Corners: IGraphics::CORNER_L) ||
563 (m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_G) && ModPressed && !ShiftPressed))
564 {
565 m_QuickActionToggleGrid.Call();
566 }
567
568 // grid settings button
569 ToolbarTop.VSplitLeft(Cut: 14.0f, pLeft: &Button, pRight: &ToolbarTop);
570 static char s_GridSettingsButton;
571 if(DoButton_FontIcon(pId: &s_GridSettingsButton, pText: FontIcon::CIRCLE_CHEVRON_DOWN, Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "Change the grid settings.", Corners: IGraphics::CORNER_R, FontSize: 8.0f))
572 {
573 MapView()->MapGrid()->DoSettingsPopup(Position: vec2(Button.x, Button.y + Button.h));
574 }
575
576 ToolbarTop.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarTop);
577
578 // zoom group
579 ToolbarTop.VSplitLeft(Cut: 20.0f, pLeft: &Button, pRight: &ToolbarTop);
580 static int s_ZoomOutButton = 0;
581 if(DoButton_FontIcon(pId: &s_ZoomOutButton, pText: FontIcon::MINUS, Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionZoomOut.Description(), Corners: IGraphics::CORNER_L))
582 {
583 m_QuickActionZoomOut.Call();
584 }
585
586 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
587 static int s_ZoomNormalButton = 0;
588 if(DoButton_FontIcon(pId: &s_ZoomNormalButton, pText: FontIcon::MAGNIFYING_GLASS, Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionResetZoom.Description(), Corners: IGraphics::CORNER_NONE))
589 {
590 m_QuickActionResetZoom.Call();
591 }
592
593 ToolbarTop.VSplitLeft(Cut: 20.0f, pLeft: &Button, pRight: &ToolbarTop);
594 static int s_ZoomInButton = 0;
595 if(DoButton_FontIcon(pId: &s_ZoomInButton, pText: FontIcon::PLUS, Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionZoomIn.Description(), Corners: IGraphics::CORNER_R))
596 {
597 m_QuickActionZoomIn.Call();
598 }
599
600 ToolbarTop.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarTop);
601
602 // undo/redo group
603 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
604 static int s_UndoButton = 0;
605 if(DoButton_FontIcon(pId: &s_UndoButton, pText: FontIcon::UNDO, Checked: m_QuickActionUndo.Disabled() ? -1 : 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionUndo.Description(), Corners: IGraphics::CORNER_L))
606 {
607 m_QuickActionUndo.Call();
608 }
609
610 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
611 static int s_RedoButton = 0;
612 if(DoButton_FontIcon(pId: &s_RedoButton, pText: FontIcon::REDO, Checked: m_QuickActionRedo.Disabled() ? -1 : 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionRedo.Description(), Corners: IGraphics::CORNER_R))
613 {
614 m_QuickActionRedo.Call();
615 }
616
617 ToolbarTop.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarTop);
618
619 // brush manipulation
620 {
621 int Enabled = m_pBrush->IsEmpty() ? -1 : 0;
622
623 // flip buttons
624 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
625 static int s_FlipXButton = 0;
626 if(DoButton_FontIcon(pId: &s_FlipXButton, pText: FontIcon::ARROWS_LEFT_RIGHT, Checked: Enabled, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[N] Flip the brush horizontally.", Corners: IGraphics::CORNER_L) || (Input()->KeyPress(Key: KEY_N) && !ModPressed && m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && !Ui()->IsPopupOpen()))
627 {
628 for(auto &pLayer : m_pBrush->m_vpLayers)
629 pLayer->BrushFlipX();
630 }
631
632 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
633 static int s_FlipyButton = 0;
634 if(DoButton_FontIcon(pId: &s_FlipyButton, pText: FontIcon::ARROWS_UP_DOWN, Checked: Enabled, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[M] Flip the brush vertically.", Corners: IGraphics::CORNER_R) || (Input()->KeyPress(Key: KEY_M) && !ModPressed && m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && !Ui()->IsPopupOpen()))
635 {
636 for(auto &pLayer : m_pBrush->m_vpLayers)
637 pLayer->BrushFlipY();
638 }
639 ToolbarTop.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarTop);
640
641 // rotate buttons
642 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
643 static int s_RotationAmount = 90;
644 bool TileLayer = false;
645 // check for tile layers in brush selection
646 for(auto &pLayer : m_pBrush->m_vpLayers)
647 if(pLayer->m_Type == LAYERTYPE_TILES)
648 {
649 TileLayer = true;
650 s_RotationAmount = std::max(a: 90, b: (s_RotationAmount / 90) * 90);
651 break;
652 }
653
654 static int s_CcwButton = 0;
655 if(DoButton_FontIcon(pId: &s_CcwButton, pText: FontIcon::ARROW_ROTATE_LEFT, Checked: Enabled, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[R] Rotate the brush counter-clockwise.", Corners: IGraphics::CORNER_L) || (Input()->KeyPress(Key: KEY_R) && !ModPressed && m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && !Ui()->IsPopupOpen()))
656 {
657 for(auto &pLayer : m_pBrush->m_vpLayers)
658 pLayer->BrushRotate(Amount: -s_RotationAmount / 360.0f * pi * 2);
659 }
660
661 ToolbarTop.VSplitLeft(Cut: 30.0f, pLeft: &Button, pRight: &ToolbarTop);
662 auto RotationAmountRes = UiDoValueSelector(pId: &s_RotationAmount, pRect: &Button, pLabel: "", Current: s_RotationAmount, Min: TileLayer ? 90 : 1, Max: 359, Step: TileLayer ? 90 : 1, Scale: TileLayer ? 10.0f : 2.0f, pToolTip: "Rotation of the brush in degrees. Use left mouse button to drag and change the value. Hold shift to be more precise.", IsDegree: true, IsHex: false, Corners: IGraphics::CORNER_NONE);
663 s_RotationAmount = RotationAmountRes.m_Value;
664
665 ToolbarTop.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarTop);
666 static int s_CwButton = 0;
667 if(DoButton_FontIcon(pId: &s_CwButton, pText: FontIcon::ARROW_ROTATE_RIGHT, Checked: Enabled, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[T] Rotate the brush clockwise.", Corners: IGraphics::CORNER_R) || (Input()->KeyPress(Key: KEY_T) && !ModPressed && m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && !Ui()->IsPopupOpen()))
668 {
669 for(auto &pLayer : m_pBrush->m_vpLayers)
670 pLayer->BrushRotate(Amount: s_RotationAmount / 360.0f * pi * 2);
671 }
672 }
673
674 // Color pipette and palette
675 {
676 const float PipetteButtonWidth = 30.0f;
677 const float ColorPickerButtonWidth = 20.0f;
678 const float Spacing = 2.0f;
679 const size_t NumColorsShown = std::clamp<int>(val: round_to_int(f: (ToolbarTop.w - PipetteButtonWidth - 40.0f) / (ColorPickerButtonWidth + Spacing)), lo: 1, hi: std::size(m_aSavedColors));
680
681 CUIRect ColorPalette;
682 ToolbarTop.VSplitRight(Cut: NumColorsShown * (ColorPickerButtonWidth + Spacing) + PipetteButtonWidth, pLeft: &ToolbarTop, pRight: &ColorPalette);
683
684 // Pipette button
685 static char s_PipetteButton;
686 ColorPalette.VSplitLeft(Cut: PipetteButtonWidth, pLeft: &Button, pRight: &ColorPalette);
687 ColorPalette.VSplitLeft(Cut: Spacing, pLeft: nullptr, pRight: &ColorPalette);
688 if(DoButton_FontIcon(pId: &s_PipetteButton, pText: FontIcon::EYE_DROPPER, Checked: m_QuickActionPipette.Active(), pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionPipette.Description(), Corners: IGraphics::CORNER_ALL) ||
689 (CLineInput::GetActiveInput() == nullptr && ModPressed && ShiftPressed && Input()->KeyPress(Key: KEY_C)))
690 {
691 m_QuickActionPipette.Call();
692 }
693
694 // Palette color pickers
695 for(size_t i = 0; i < NumColorsShown; ++i)
696 {
697 ColorPalette.VSplitLeft(Cut: ColorPickerButtonWidth, pLeft: &Button, pRight: &ColorPalette);
698 ColorPalette.VSplitLeft(Cut: Spacing, pLeft: nullptr, pRight: &ColorPalette);
699 const auto &&SetColor = [&](ColorRGBA NewColor) {
700 m_aSavedColors[i] = NewColor;
701 };
702 DoColorPickerButton(pId: &m_aSavedColors[i], pRect: &Button, Color: m_aSavedColors[i], SetColor);
703 }
704 }
705 }
706
707 // Bottom line buttons
708 {
709 // refocus button
710 {
711 ToolbarBottom.VSplitLeft(Cut: 50.0f, pLeft: &Button, pRight: &ToolbarBottom);
712 int FocusButtonChecked = MapView()->IsFocused() ? -1 : 1;
713 if(DoButton_Editor(pId: &m_QuickActionRefocus, pText: m_QuickActionRefocus.Label(), Checked: FocusButtonChecked, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionRefocus.Description()) || (m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_HOME)))
714 m_QuickActionRefocus.Call();
715 ToolbarBottom.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarBottom);
716 }
717
718 // brush picker button
719 {
720 ToolbarBottom.VSplitLeft(Cut: 25.0f, pLeft: &Button, pRight: &ToolbarBottom);
721 const int Checked = m_QuickActionBrushPicker.Disabled() ? -1 : (m_ShowPicker ? 1 : 0);
722 if(DoButton_FontIcon(pId: &m_QuickActionBrushPicker, pText: FontIcon::BRUSH, Checked, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionBrushPicker.Description(), Corners: IGraphics::CORNER_ALL))
723 {
724 m_QuickActionBrushPicker.Call();
725 }
726 ToolbarBottom.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarBottom);
727 }
728
729 // tile manipulation
730 {
731 // do tele/tune/switch/speedup button
732 {
733 std::shared_ptr<CLayerTiles> pS = std::static_pointer_cast<CLayerTiles>(r: Map()->SelectedLayerType(Index: 0, Type: LAYERTYPE_TILES));
734 if(pS)
735 {
736 const char *pButtonName = nullptr;
737 CUi::FPopupMenuFunction pfnPopupFunc = nullptr;
738 int Rows = 0;
739 int ExtraWidth = 0;
740 if(pS == Map()->m_pSwitchLayer)
741 {
742 pButtonName = "Switch";
743 pfnPopupFunc = PopupSwitch;
744 Rows = 3;
745 }
746 else if(pS == Map()->m_pSpeedupLayer)
747 {
748 pButtonName = "Speedup";
749 pfnPopupFunc = PopupSpeedup;
750 Rows = 3;
751 }
752 else if(pS == Map()->m_pTuneLayer)
753 {
754 pButtonName = "Tune";
755 pfnPopupFunc = PopupTune;
756 Rows = 2;
757 }
758 else if(pS == Map()->m_pTeleLayer)
759 {
760 pButtonName = "Tele";
761 pfnPopupFunc = PopupTele;
762 Rows = 3;
763 ExtraWidth = 50;
764 }
765
766 if(pButtonName != nullptr)
767 {
768 static char s_aButtonTooltip[64];
769 str_format(buffer: s_aButtonTooltip, buffer_size: sizeof(s_aButtonTooltip), format: "[Ctrl+T] %s", pButtonName);
770
771 ToolbarBottom.VSplitLeft(Cut: 60.0f, pLeft: &Button, pRight: &ToolbarBottom);
772 static int s_ModifierButton = 0;
773 if(DoButton_Ex(pId: &s_ModifierButton, pText: pButtonName, Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: s_aButtonTooltip, Corners: IGraphics::CORNER_ALL) || (m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && ModPressed && Input()->KeyPress(Key: KEY_T)))
774 {
775 static SPopupMenuId s_PopupModifierId;
776 if(!Ui()->IsPopupOpen(pId: &s_PopupModifierId))
777 {
778 Ui()->DoPopupMenu(pId: &s_PopupModifierId, X: Button.x, Y: Button.y + Button.h, Width: 120 + ExtraWidth, Height: 10.0f + Rows * 13.0f, pContext: this, pfnFunc: pfnPopupFunc);
779 }
780 }
781 ToolbarBottom.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &ToolbarBottom);
782 }
783 }
784 }
785 }
786
787 // do add quad/sound button
788 std::shared_ptr<CLayer> pLayer = Map()->SelectedLayer(Index: 0);
789 if(pLayer && (pLayer->m_Type == LAYERTYPE_QUADS || pLayer->m_Type == LAYERTYPE_SOUNDS))
790 {
791 // "Add sound source" button needs more space or the font size will be scaled down
792 ToolbarBottom.VSplitLeft(Cut: (pLayer->m_Type == LAYERTYPE_QUADS) ? 60.0f : 100.0f, pLeft: &Button, pRight: &ToolbarBottom);
793
794 if(pLayer->m_Type == LAYERTYPE_QUADS)
795 {
796 if(DoButton_Editor(pId: &m_QuickActionAddQuad, pText: m_QuickActionAddQuad.Label(), Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionAddQuad.Description()) ||
797 (m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_Q) && ModPressed))
798 {
799 m_QuickActionAddQuad.Call();
800 }
801 }
802 else if(pLayer->m_Type == LAYERTYPE_SOUNDS)
803 {
804 if(DoButton_Editor(pId: &m_QuickActionAddSoundSource, pText: m_QuickActionAddSoundSource.Label(), Checked: 0, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionAddSoundSource.Description()) ||
805 (m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_Q) && ModPressed))
806 {
807 m_QuickActionAddSoundSource.Call();
808 }
809 }
810
811 ToolbarBottom.VSplitLeft(Cut: 5.0f, pLeft: &Button, pRight: &ToolbarBottom);
812 }
813
814 // Brush draw mode button
815 {
816 ToolbarBottom.VSplitLeft(Cut: 65.0f, pLeft: &Button, pRight: &ToolbarBottom);
817 static int s_BrushDrawModeButton = 0;
818 if(DoButton_Editor(pId: &s_BrushDrawModeButton, pText: "Destructive", Checked: m_BrushDrawDestructive, pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: "[Ctrl+D] Toggle brush draw mode: preserve or override existing tiles.") ||
819 (m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Input()->KeyPress(Key: KEY_D) && ModPressed && !ShiftPressed))
820 m_BrushDrawDestructive = !m_BrushDrawDestructive;
821 ToolbarBottom.VSplitLeft(Cut: 5.0f, pLeft: &Button, pRight: &ToolbarBottom);
822 }
823 }
824}
825
826void CEditor::DoToolbarImages(CUIRect ToolBar)
827{
828 CUIRect ToolBarTop, ToolBarBottom;
829 ToolBar.HSplitMid(pTop: &ToolBarTop, pBottom: &ToolBarBottom, Spacing: 5.0f);
830
831 std::shared_ptr<CEditorImage> pSelectedImage = Map()->SelectedImage();
832 if(pSelectedImage != nullptr)
833 {
834 char aLabel[64];
835 str_format(buffer: aLabel, buffer_size: sizeof(aLabel), format: "Size: %" PRIzu " × %" PRIzu, pSelectedImage->m_Width, pSelectedImage->m_Height);
836 Ui()->DoLabel(pRect: &ToolBarBottom, pText: aLabel, Size: 12.0f, Align: TEXTALIGN_ML);
837 }
838}
839
840void CEditor::DoToolbarSounds(CUIRect ToolBar)
841{
842 CUIRect ToolBarTop, ToolBarBottom;
843 ToolBar.HSplitMid(pTop: &ToolBarTop, pBottom: &ToolBarBottom, Spacing: 5.0f);
844
845 std::shared_ptr<CEditorSound> pSelectedSound = Map()->SelectedSound();
846 if(pSelectedSound != nullptr)
847 {
848 if(pSelectedSound->m_SoundId != m_ToolbarPreviewSound && m_ToolbarPreviewSound >= 0 && Sound()->IsPlaying(SampleId: m_ToolbarPreviewSound))
849 Sound()->Stop(SampleId: m_ToolbarPreviewSound);
850 m_ToolbarPreviewSound = pSelectedSound->m_SoundId;
851 }
852 else
853 {
854 m_ToolbarPreviewSound = -1;
855 }
856
857 if(m_ToolbarPreviewSound >= 0)
858 {
859 static int s_PlayPauseButton, s_StopButton, s_SeekBar = 0;
860 DoAudioPreview(View: ToolBarBottom, pPlayPauseButtonId: &s_PlayPauseButton, pStopButtonId: &s_StopButton, pSeekBarId: &s_SeekBar, SampleId: m_ToolbarPreviewSound);
861 }
862}
863
864void CEditor::DoSoundSource(int LayerIndex, CSoundSource *pSource, int Index)
865{
866 static ESoundSourceOp s_Operation = ESoundSourceOp::NONE;
867
868 float CenterX = fx2f(v: pSource->m_Position.x);
869 float CenterY = fx2f(v: pSource->m_Position.y);
870
871 const bool IgnoreGrid = Input()->AltIsPressed();
872
873 if(s_Operation == ESoundSourceOp::NONE)
874 {
875 if(!Ui()->MouseButton(Index: 0))
876 Map()->m_SoundSourceOperationTracker.End();
877 }
878
879 if(Ui()->CheckActiveItem(pId: pSource))
880 {
881 if(s_Operation != ESoundSourceOp::NONE)
882 {
883 Map()->m_SoundSourceOperationTracker.Begin(pSource, Operation: s_Operation, LayerIndex);
884 }
885
886 if(MapView()->MouseDeltaWorld() != vec2(0.0f, 0.0f))
887 {
888 if(s_Operation == ESoundSourceOp::MOVE)
889 {
890 vec2 Pos = MapView()->MouseWorldPos();
891 if(MapView()->MapGrid()->IsEnabled() && !IgnoreGrid)
892 {
893 MapView()->MapGrid()->SnapToGrid(Position&: Pos);
894 }
895 pSource->m_Position.x = f2fx(v: Pos.x);
896 pSource->m_Position.y = f2fx(v: Pos.y);
897 }
898 }
899
900 if(s_Operation == ESoundSourceOp::CONTEXT_MENU)
901 {
902 if(!Ui()->MouseButton(Index: 1))
903 {
904 if(Map()->m_vSelectedLayers.size() == 1)
905 {
906 static SPopupMenuId s_PopupSourceId;
907 Ui()->DoPopupMenu(pId: &s_PopupSourceId, X: Ui()->MouseX(), Y: Ui()->MouseY(), Width: 120, Height: 200, pContext: this, pfnFunc: PopupSource);
908 Ui()->DisableMouseLock();
909 }
910 s_Operation = ESoundSourceOp::NONE;
911 Ui()->SetActiveItem(nullptr);
912 }
913 }
914 else
915 {
916 if(!Ui()->MouseButton(Index: 0))
917 {
918 Ui()->DisableMouseLock();
919 s_Operation = ESoundSourceOp::NONE;
920 Ui()->SetActiveItem(nullptr);
921 }
922 }
923
924 Graphics()->SetColor(r: 1, g: 1, b: 1, a: 1);
925 }
926 else if(Ui()->HotItem() == pSource)
927 {
928 m_pUiGotContext = pSource;
929
930 Graphics()->SetColor(r: 1, g: 1, b: 1, a: 1);
931 str_copy(dst&: m_aTooltip, src: "Left mouse button to move. Hold alt to ignore grid.");
932
933 if(Ui()->MouseButton(Index: 0))
934 {
935 s_Operation = ESoundSourceOp::MOVE;
936
937 Ui()->SetActiveItem(pSource);
938 Map()->m_SelectedSoundSource = Index;
939 }
940
941 if(Ui()->MouseButton(Index: 1))
942 {
943 Map()->m_SelectedSoundSource = Index;
944 s_Operation = ESoundSourceOp::CONTEXT_MENU;
945 Ui()->SetActiveItem(pSource);
946 }
947 }
948 else
949 {
950 Graphics()->SetColor(r: 0, g: 1, b: 0, a: 1);
951 }
952
953 IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f * MapView()->MouseWorldScale(), 5.0f * MapView()->MouseWorldScale());
954 Graphics()->QuadsDraw(pArray: &QuadItem, Num: 1);
955}
956
957void CEditor::UpdateHotSoundSource(const CLayerSounds *pLayer)
958{
959 const vec2 MouseWorld = MapView()->MouseWorldPos();
960
961 float MinDist = 500.0f;
962 const void *pMinSourceId = nullptr;
963
964 const auto UpdateMinimum = [&](vec2 Position, const void *pId) {
965 const float CurrDist = distance_squared(a: Position, b: MouseWorld) / (MapView()->MouseWorldScale() * MapView()->MouseWorldScale());
966 if(CurrDist < MinDist)
967 {
968 MinDist = CurrDist;
969 pMinSourceId = pId;
970 }
971 };
972
973 for(const CSoundSource &Source : pLayer->m_vSources)
974 {
975 UpdateMinimum(vec2(fx2f(v: Source.m_Position.x), fx2f(v: Source.m_Position.y)), &Source);
976 }
977
978 if(pMinSourceId != nullptr)
979 {
980 Ui()->SetHotItem(pMinSourceId);
981 }
982}
983
984void CEditor::PreparePointDrag(const CQuad *pQuad, int QuadIndex, int PointIndex)
985{
986 m_QuadDragOriginalPoints[QuadIndex][PointIndex] = pQuad->m_aPoints[PointIndex];
987}
988
989void CEditor::DoPointDrag(CQuad *pQuad, int QuadIndex, int PointIndex, ivec2 Offset)
990{
991 pQuad->m_aPoints[PointIndex] = m_QuadDragOriginalPoints[QuadIndex][PointIndex] + Offset;
992}
993
994CEditor::EAxis CEditor::GetDragAxis(ivec2 Offset) const
995{
996 if(Input()->ShiftIsPressed())
997 if(absolute(a: Offset.x) < absolute(a: Offset.y))
998 return EAxis::Y;
999 else
1000 return EAxis::X;
1001 else
1002 return EAxis::NONE;
1003}
1004
1005void CEditor::DrawAxis(EAxis Axis, CPoint &OriginalPoint, CPoint &Point) const
1006{
1007 if(Axis == EAxis::NONE)
1008 return;
1009
1010 Graphics()->SetColor(r: 1, g: 0, b: 0.1f, a: 1);
1011 if(Axis == EAxis::X)
1012 {
1013 IGraphics::CQuadItem Line(fx2f(v: OriginalPoint.x + Point.x) / 2.0f, fx2f(v: OriginalPoint.y), fx2f(v: Point.x - OriginalPoint.x), 1.0f * MapView()->MouseWorldScale());
1014 Graphics()->QuadsDraw(pArray: &Line, Num: 1);
1015 }
1016 else if(Axis == EAxis::Y)
1017 {
1018 IGraphics::CQuadItem Line(fx2f(v: OriginalPoint.x), fx2f(v: OriginalPoint.y + Point.y) / 2.0f, 1.0f * MapView()->MouseWorldScale(), fx2f(v: Point.y - OriginalPoint.y));
1019 Graphics()->QuadsDraw(pArray: &Line, Num: 1);
1020 }
1021
1022 // Draw ghost of original point
1023 IGraphics::CQuadItem QuadItem(fx2f(v: OriginalPoint.x), fx2f(v: OriginalPoint.y), 5.0f * MapView()->MouseWorldScale(), 5.0f * MapView()->MouseWorldScale());
1024 Graphics()->QuadsDraw(pArray: &QuadItem, Num: 1);
1025}
1026
1027void CEditor::ComputePointAlignments(const std::shared_ptr<CLayerQuads> &pLayer, CQuad *pQuad, int QuadIndex, int PointIndex, ivec2 Offset, std::vector<SAlignmentInfo> &vAlignments, bool Append) const
1028{
1029 if(!Append)
1030 vAlignments.clear();
1031 if(!g_Config.m_EdAlignQuads)
1032 return;
1033
1034 bool GridEnabled = MapView()->MapGrid()->IsEnabled() && !Input()->AltIsPressed();
1035
1036 // Perform computation from the original position of this point
1037 int Threshold = f2fx(v: std::max(a: 5.0f, b: 10.0f * MapView()->MouseWorldScale()));
1038 CPoint OrigPoint = m_QuadDragOriginalPoints.at(k: QuadIndex)[PointIndex];
1039 // Get the "current" point by applying the offset
1040 CPoint Point = OrigPoint + Offset;
1041
1042 // Save smallest diff on both axis to only keep closest alignments
1043 ivec2 SmallestDiff = ivec2(Threshold + 1, Threshold + 1);
1044 // Store both axis alignments in separate vectors
1045 std::vector<SAlignmentInfo> vAlignmentsX, vAlignmentsY;
1046
1047 // Check if we can align/snap to a specific point
1048 auto &&CheckAlignment = [&](CPoint *pQuadPoint) {
1049 ivec2 DirectedDiff = *pQuadPoint - Point;
1050 ivec2 Diff = ivec2(absolute(a: DirectedDiff.x), absolute(a: DirectedDiff.y));
1051
1052 if(Diff.x <= Threshold && (!GridEnabled || Diff.x == 0))
1053 {
1054 // Only store alignments that have the smallest difference
1055 if(Diff.x < SmallestDiff.x)
1056 {
1057 vAlignmentsX.clear();
1058 SmallestDiff.x = Diff.x;
1059 }
1060
1061 // We can have multiple alignments having the same difference/distance
1062 if(Diff.x == SmallestDiff.x)
1063 {
1064 vAlignmentsX.push_back(x: SAlignmentInfo{
1065 .m_AlignedPoint: *pQuadPoint, // Aligned point
1066 {.m_X: OrigPoint.y}, // Value that can change (which is not snapped), original position
1067 .m_Axis: EAxis::Y, // The alignment axis
1068 .m_PointIndex: PointIndex, // The index of the point
1069 .m_Diff: DirectedDiff.x,
1070 });
1071 }
1072 }
1073
1074 if(Diff.y <= Threshold && (!GridEnabled || Diff.y == 0))
1075 {
1076 // Only store alignments that have the smallest difference
1077 if(Diff.y < SmallestDiff.y)
1078 {
1079 vAlignmentsY.clear();
1080 SmallestDiff.y = Diff.y;
1081 }
1082
1083 if(Diff.y == SmallestDiff.y)
1084 {
1085 vAlignmentsY.push_back(x: SAlignmentInfo{
1086 .m_AlignedPoint: *pQuadPoint,
1087 {.m_X: OrigPoint.x},
1088 .m_Axis: EAxis::X,
1089 .m_PointIndex: PointIndex,
1090 .m_Diff: DirectedDiff.y,
1091 });
1092 }
1093 }
1094 };
1095
1096 // Iterate through all the quads of the current layer
1097 // Check alignment with each point of the quad (corners & pivot)
1098 // Compute an AABB (Axis Aligned Bounding Box) to get the center of the quad
1099 // Check alignment with the center of the quad
1100 for(size_t i = 0; i < pLayer->m_vQuads.size(); i++)
1101 {
1102 auto *pCurrentQuad = &pLayer->m_vQuads[i];
1103 CPoint Min = pCurrentQuad->m_aPoints[0];
1104 CPoint Max = pCurrentQuad->m_aPoints[0];
1105 const bool QuadSelected = Map()->IsQuadSelected(Index: i);
1106
1107 for(int v = 0; v < 5; v++)
1108 {
1109 CPoint *pQuadPoint = &pCurrentQuad->m_aPoints[v];
1110
1111 if(v != 4)
1112 { // Don't use pivot to compute AABB
1113 if(pQuadPoint->x < Min.x)
1114 Min.x = pQuadPoint->x;
1115 if(pQuadPoint->y < Min.y)
1116 Min.y = pQuadPoint->y;
1117 if(pQuadPoint->x > Max.x)
1118 Max.x = pQuadPoint->x;
1119 if(pQuadPoint->y > Max.y)
1120 Max.y = pQuadPoint->y;
1121 }
1122
1123 // Don't check alignment with current point
1124 if(pQuadPoint == &pQuad->m_aPoints[PointIndex])
1125 continue;
1126
1127 // Don't check alignment with other selected points
1128 bool IsCurrentPointSelected = QuadSelected && (Map()->IsQuadCornerSelected(Index: v) || (v == PointIndex && PointIndex == 4));
1129 if(IsCurrentPointSelected)
1130 continue;
1131
1132 CheckAlignment(pQuadPoint);
1133 }
1134
1135 // Don't check alignment with center of selected quads
1136 if(!QuadSelected)
1137 {
1138 CPoint Center = (Min + Max) / 2.0f;
1139 CheckAlignment(&Center);
1140 }
1141 }
1142
1143 // Finally concatenate both alignment vectors into the output
1144 vAlignments.reserve(n: vAlignmentsX.size() + vAlignmentsY.size());
1145 vAlignments.insert(position: vAlignments.end(), first: vAlignmentsX.begin(), last: vAlignmentsX.end());
1146 vAlignments.insert(position: vAlignments.end(), first: vAlignmentsY.begin(), last: vAlignmentsY.end());
1147}
1148
1149void CEditor::ComputePointsAlignments(const std::shared_ptr<CLayerQuads> &pLayer, bool Pivot, ivec2 Offset, std::vector<SAlignmentInfo> &vAlignments) const
1150{
1151 // This method is used to compute alignments from selected points
1152 // and only apply the closest alignment on X and Y to the offset.
1153
1154 vAlignments.clear();
1155 std::vector<SAlignmentInfo> vAllAlignments;
1156
1157 for(int Selected : Map()->m_vSelectedQuads)
1158 {
1159 CQuad *pQuad = &pLayer->m_vQuads[Selected];
1160
1161 if(!Pivot)
1162 {
1163 for(int m = 0; m < 4; m++)
1164 {
1165 if(Map()->IsQuadCornerSelected(Index: m))
1166 {
1167 ComputePointAlignments(pLayer, pQuad, QuadIndex: Selected, PointIndex: m, Offset, vAlignments&: vAllAlignments, Append: true);
1168 }
1169 }
1170 }
1171 else
1172 {
1173 ComputePointAlignments(pLayer, pQuad, QuadIndex: Selected, PointIndex: 4, Offset, vAlignments&: vAllAlignments, Append: true);
1174 }
1175 }
1176
1177 ivec2 SmallestDiff = ivec2(std::numeric_limits<int>::max(), std::numeric_limits<int>::max());
1178 std::vector<SAlignmentInfo> vAlignmentsX, vAlignmentsY;
1179
1180 for(const auto &Alignment : vAllAlignments)
1181 {
1182 int AbsDiff = absolute(a: Alignment.m_Diff);
1183 if(Alignment.m_Axis == EAxis::X)
1184 {
1185 if(AbsDiff < SmallestDiff.y)
1186 {
1187 SmallestDiff.y = AbsDiff;
1188 vAlignmentsY.clear();
1189 }
1190 if(AbsDiff == SmallestDiff.y)
1191 vAlignmentsY.emplace_back(args: Alignment);
1192 }
1193 else if(Alignment.m_Axis == EAxis::Y)
1194 {
1195 if(AbsDiff < SmallestDiff.x)
1196 {
1197 SmallestDiff.x = AbsDiff;
1198 vAlignmentsX.clear();
1199 }
1200 if(AbsDiff == SmallestDiff.x)
1201 vAlignmentsX.emplace_back(args: Alignment);
1202 }
1203 }
1204
1205 vAlignments.reserve(n: vAlignmentsX.size() + vAlignmentsY.size());
1206 vAlignments.insert(position: vAlignments.end(), first: vAlignmentsX.begin(), last: vAlignmentsX.end());
1207 vAlignments.insert(position: vAlignments.end(), first: vAlignmentsY.begin(), last: vAlignmentsY.end());
1208}
1209
1210void CEditor::ComputeAABBAlignments(const std::shared_ptr<CLayerQuads> &pLayer, const SAxisAlignedBoundingBox &AABB, ivec2 Offset, std::vector<SAlignmentInfo> &vAlignments) const
1211{
1212 vAlignments.clear();
1213 if(!g_Config.m_EdAlignQuads)
1214 return;
1215
1216 // This method is a bit different than the point alignment in the way where instead of trying to align 1 point to all quads,
1217 // we try to align 5 points to all quads, these 5 points being 5 points of an AABB.
1218 // Otherwise, the concept is the same, we use the original position of the AABB to make the computations.
1219 int Threshold = f2fx(v: std::max(a: 5.0f, b: 10.0f * MapView()->MouseWorldScale()));
1220 ivec2 SmallestDiff = ivec2(Threshold + 1, Threshold + 1);
1221 std::vector<SAlignmentInfo> vAlignmentsX, vAlignmentsY;
1222
1223 bool GridEnabled = MapView()->MapGrid()->IsEnabled() && !Input()->AltIsPressed();
1224
1225 auto &&CheckAlignment = [&](CPoint &Aligned, int Point) {
1226 CPoint ToCheck = AABB.m_aPoints[Point] + Offset;
1227 ivec2 DirectedDiff = Aligned - ToCheck;
1228 ivec2 Diff = ivec2(absolute(a: DirectedDiff.x), absolute(a: DirectedDiff.y));
1229
1230 if(Diff.x <= Threshold && (!GridEnabled || Diff.x == 0))
1231 {
1232 if(Diff.x < SmallestDiff.x)
1233 {
1234 SmallestDiff.x = Diff.x;
1235 vAlignmentsX.clear();
1236 }
1237
1238 if(Diff.x == SmallestDiff.x)
1239 {
1240 vAlignmentsX.push_back(x: SAlignmentInfo{
1241 .m_AlignedPoint: Aligned,
1242 {.m_X: AABB.m_aPoints[Point].y},
1243 .m_Axis: EAxis::Y,
1244 .m_PointIndex: Point,
1245 .m_Diff: DirectedDiff.x,
1246 });
1247 }
1248 }
1249
1250 if(Diff.y <= Threshold && (!GridEnabled || Diff.y == 0))
1251 {
1252 if(Diff.y < SmallestDiff.y)
1253 {
1254 SmallestDiff.y = Diff.y;
1255 vAlignmentsY.clear();
1256 }
1257
1258 if(Diff.y == SmallestDiff.y)
1259 {
1260 vAlignmentsY.push_back(x: SAlignmentInfo{
1261 .m_AlignedPoint: Aligned,
1262 {.m_X: AABB.m_aPoints[Point].x},
1263 .m_Axis: EAxis::X,
1264 .m_PointIndex: Point,
1265 .m_Diff: DirectedDiff.y,
1266 });
1267 }
1268 }
1269 };
1270
1271 auto &&CheckAABBAlignment = [&](CPoint &QuadMin, CPoint &QuadMax) {
1272 CPoint QuadCenter = (QuadMin + QuadMax) / 2.0f;
1273 CPoint aQuadPoints[5] = {
1274 QuadMin, // Top left
1275 {QuadMax.x, QuadMin.y}, // Top right
1276 {QuadMin.x, QuadMax.y}, // Bottom left
1277 QuadMax, // Bottom right
1278 QuadCenter,
1279 };
1280
1281 // Check all points with all the other points
1282 for(auto &QuadPoint : aQuadPoints)
1283 {
1284 // i is the quad point which is "aligned" and that we want to compare with
1285 for(int j = 0; j < 5; j++)
1286 {
1287 // j is the point we try to align
1288 CheckAlignment(QuadPoint, j);
1289 }
1290 }
1291 };
1292
1293 // Iterate through all quads of the current layer
1294 // Compute AABB of all quads and check if the dragged AABB can be aligned to this AABB.
1295 for(size_t i = 0; i < pLayer->m_vQuads.size(); i++)
1296 {
1297 auto *pCurrentQuad = &pLayer->m_vQuads[i];
1298 if(Map()->IsQuadSelected(Index: i)) // Don't check with other selected quads
1299 continue;
1300
1301 // Get AABB of this quad
1302 CPoint QuadMin = pCurrentQuad->m_aPoints[0], QuadMax = pCurrentQuad->m_aPoints[0];
1303 for(int v = 1; v < 4; v++)
1304 {
1305 QuadMin.x = std::min(a: QuadMin.x, b: pCurrentQuad->m_aPoints[v].x);
1306 QuadMin.y = std::min(a: QuadMin.y, b: pCurrentQuad->m_aPoints[v].y);
1307 QuadMax.x = std::max(a: QuadMax.x, b: pCurrentQuad->m_aPoints[v].x);
1308 QuadMax.y = std::max(a: QuadMax.y, b: pCurrentQuad->m_aPoints[v].y);
1309 }
1310
1311 CheckAABBAlignment(QuadMin, QuadMax);
1312 }
1313
1314 // Finally, concatenate both alignment vectors into the output
1315 vAlignments.reserve(n: vAlignmentsX.size() + vAlignmentsY.size());
1316 vAlignments.insert(position: vAlignments.end(), first: vAlignmentsX.begin(), last: vAlignmentsX.end());
1317 vAlignments.insert(position: vAlignments.end(), first: vAlignmentsY.begin(), last: vAlignmentsY.end());
1318}
1319
1320void CEditor::DrawPointAlignments(const std::vector<SAlignmentInfo> &vAlignments, ivec2 Offset) const
1321{
1322 if(!g_Config.m_EdAlignQuads)
1323 return;
1324
1325 // Drawing an alignment is easy, we convert fixed to float for the aligned point coords
1326 // and we also convert the "changing" value after applying the offset (which might be edited to actually align the value with the alignment).
1327 Graphics()->SetColor(r: 1, g: 0, b: 0.1f, a: 1);
1328 for(const SAlignmentInfo &Alignment : vAlignments)
1329 {
1330 // We don't use IGraphics::CLineItem to draw because we don't want to stop QuadsBegin(), quads work just fine.
1331 if(Alignment.m_Axis == EAxis::X)
1332 { // Alignment on X axis is same Y values but different X values
1333 IGraphics::CQuadItem Line(fx2f(v: Alignment.m_AlignedPoint.x), fx2f(v: Alignment.m_AlignedPoint.y), fx2f(v: Alignment.m_X + Offset.x - Alignment.m_AlignedPoint.x), 1.0f * MapView()->MouseWorldScale());
1334 Graphics()->QuadsDrawTL(pArray: &Line, Num: 1);
1335 }
1336 else if(Alignment.m_Axis == EAxis::Y)
1337 { // Alignment on Y axis is same X values but different Y values
1338 IGraphics::CQuadItem Line(fx2f(v: Alignment.m_AlignedPoint.x), fx2f(v: Alignment.m_AlignedPoint.y), 1.0f * MapView()->MouseWorldScale(), fx2f(v: Alignment.m_Y + Offset.y - Alignment.m_AlignedPoint.y));
1339 Graphics()->QuadsDrawTL(pArray: &Line, Num: 1);
1340 }
1341 }
1342}
1343
1344void CEditor::DrawAABB(const SAxisAlignedBoundingBox &AABB, ivec2 Offset) const
1345{
1346 // Drawing an AABB is simply converting the points from fixed to float
1347 // Then making lines out of quads and drawing them
1348 vec2 TL = {fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_TL].x + Offset.x), fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_TL].y + Offset.y)};
1349 vec2 TR = {fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_TR].x + Offset.x), fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_TR].y + Offset.y)};
1350 vec2 BL = {fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_BL].x + Offset.x), fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_BL].y + Offset.y)};
1351 vec2 BR = {fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_BR].x + Offset.x), fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_BR].y + Offset.y)};
1352 vec2 Center = {fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_CENTER].x + Offset.x), fx2f(v: AABB.m_aPoints[SAxisAlignedBoundingBox::POINT_CENTER].y + Offset.y)};
1353
1354 // We don't use IGraphics::CLineItem to draw because we don't want to stop QuadsBegin(), quads work just fine.
1355 IGraphics::CQuadItem Lines[4] = {
1356 {TL.x, TL.y, TR.x - TL.x, 1.0f * MapView()->MouseWorldScale()},
1357 {TL.x, TL.y, 1.0f * MapView()->MouseWorldScale(), BL.y - TL.y},
1358 {TR.x, TR.y, 1.0f * MapView()->MouseWorldScale(), BR.y - TR.y},
1359 {BL.x, BL.y, BR.x - BL.x, 1.0f * MapView()->MouseWorldScale()},
1360 };
1361 Graphics()->SetColor(r: 1, g: 0, b: 1, a: 1);
1362 Graphics()->QuadsDrawTL(pArray: Lines, Num: 4);
1363
1364 IGraphics::CQuadItem CenterQuad(Center.x, Center.y, 5.0f * MapView()->MouseWorldScale(), 5.0f * MapView()->MouseWorldScale());
1365 Graphics()->QuadsDraw(pArray: &CenterQuad, Num: 1);
1366}
1367
1368void CEditor::QuadSelectionAABB(const std::shared_ptr<CLayerQuads> &pLayer, SAxisAlignedBoundingBox &OutAABB)
1369{
1370 // Compute an englobing AABB of the current selection of quads
1371 CPoint Min{
1372 std::numeric_limits<int>::max(),
1373 std::numeric_limits<int>::max(),
1374 };
1375 CPoint Max{
1376 std::numeric_limits<int>::min(),
1377 std::numeric_limits<int>::min(),
1378 };
1379 for(int Selected : Map()->m_vSelectedQuads)
1380 {
1381 CQuad *pQuad = &pLayer->m_vQuads[Selected];
1382 for(int i = 0; i < 4; i++)
1383 {
1384 auto *pPoint = &pQuad->m_aPoints[i];
1385 Min.x = std::min(a: Min.x, b: pPoint->x);
1386 Min.y = std::min(a: Min.y, b: pPoint->y);
1387 Max.x = std::max(a: Max.x, b: pPoint->x);
1388 Max.y = std::max(a: Max.y, b: pPoint->y);
1389 }
1390 }
1391 CPoint Center = (Min + Max) / 2.0f;
1392 CPoint aPoints[SAxisAlignedBoundingBox::NUM_POINTS] = {
1393 Min, // Top left
1394 {Max.x, Min.y}, // Top right
1395 {Min.x, Max.y}, // Bottom left
1396 Max, // Bottom right
1397 Center,
1398 };
1399 mem_copy(dest: OutAABB.m_aPoints, source: aPoints, size: sizeof(CPoint) * SAxisAlignedBoundingBox::NUM_POINTS);
1400}
1401
1402void CEditor::ApplyAlignments(const std::vector<SAlignmentInfo> &vAlignments, ivec2 &Offset)
1403{
1404 if(vAlignments.empty())
1405 return;
1406
1407 // To find the alignments we simply iterate through the vector of alignments and find the first
1408 // X and Y alignments.
1409 // Then, we use the saved m_Diff to adjust the offset
1410 bvec2 GotAdjust = bvec2(false, false);
1411 ivec2 Adjust = ivec2(0, 0);
1412 for(const SAlignmentInfo &Alignment : vAlignments)
1413 {
1414 if(Alignment.m_Axis == EAxis::X && !GotAdjust.y)
1415 {
1416 GotAdjust.y = true;
1417 Adjust.y = Alignment.m_Diff;
1418 }
1419 else if(Alignment.m_Axis == EAxis::Y && !GotAdjust.x)
1420 {
1421 GotAdjust.x = true;
1422 Adjust.x = Alignment.m_Diff;
1423 }
1424 }
1425
1426 Offset += Adjust;
1427}
1428
1429void CEditor::ApplyAxisAlignment(ivec2 &Offset) const
1430{
1431 // This is used to preserve axis alignment when pressing `Shift`
1432 // Should be called before any other computation
1433 EAxis Axis = GetDragAxis(Offset);
1434 Offset.x = ((Axis == EAxis::NONE || Axis == EAxis::X) ? Offset.x : 0);
1435 Offset.y = ((Axis == EAxis::NONE || Axis == EAxis::Y) ? Offset.y : 0);
1436}
1437
1438static CColor AverageColor(const std::vector<CQuad *> &vpQuads)
1439{
1440 CColor Average = {0, 0, 0, 0};
1441 for(CQuad *pQuad : vpQuads)
1442 {
1443 for(CColor Color : pQuad->m_aColors)
1444 {
1445 Average += Color;
1446 }
1447 }
1448 return Average / std::size(CQuad{}.m_aColors) / vpQuads.size();
1449}
1450
1451void CEditor::DrawQuadPivotHandle(const CQuad *pQuad, bool Selected)
1452{
1453 const void *pId = &pQuad->m_aPoints[4]; // use pivot addr as id
1454 const vec2 Center = vec2(fx2f(v: pQuad->m_aPoints[4].x), fx2f(v: pQuad->m_aPoints[4].y));
1455
1456 // draw selection background
1457 if(Selected)
1458 {
1459 Graphics()->SetColor(r: 0, g: 0, b: 0, a: 1);
1460 IGraphics::CQuadItem QuadItem(Center.x, Center.y, 7.0f * MapView()->MouseWorldScale(), 7.0f * MapView()->MouseWorldScale());
1461 Graphics()->QuadsDraw(pArray: &QuadItem, Num: 1);
1462 }
1463
1464 if(Ui()->CheckActiveItem(pId) || Ui()->HotItem() == pId)
1465 {
1466 Graphics()->SetColor(r: 1, g: 1, b: 1, a: 1);
1467 }
1468 else
1469 {
1470 Graphics()->SetColor(Selected ? ColorRGBA(1.0f, 0.0f, 1.0f, 1.0f) : ColorRGBA(0.0f, 1.0f, 0.0f, 1.0f));
1471 }
1472
1473 IGraphics::CQuadItem QuadItem(Center.x, Center.y, 5.0f * MapView()->MouseWorldScale(), 5.0f * MapView()->MouseWorldScale());
1474 Graphics()->QuadsDraw(pArray: &QuadItem, Num: 1);
1475}
1476
1477void CEditor::DrawQuadPointHandle(const CQuad *pQuad, int PointIndex, bool Selected)
1478{
1479 const void *pId = &pQuad->m_aPoints[PointIndex];
1480 const vec2 Center = vec2(fx2f(v: pQuad->m_aPoints[PointIndex].x), fx2f(v: pQuad->m_aPoints[PointIndex].y));
1481 const bool PointSelected = Selected && Map()->IsQuadCornerSelected(Index: PointIndex);
1482
1483 // draw selection background
1484 if(PointSelected)
1485 {
1486 Graphics()->SetColor(r: 0, g: 0, b: 0, a: 1);
1487 IGraphics::CQuadItem QuadItem(Center.x, Center.y, 7.0f * MapView()->MouseWorldScale(), 7.0f * MapView()->MouseWorldScale());
1488 Graphics()->QuadsDraw(pArray: &QuadItem, Num: 1);
1489 }
1490
1491 if(Ui()->CheckActiveItem(pId) || Ui()->HotItem() == pId)
1492 {
1493 Graphics()->SetColor(r: 1, g: 1, b: 1, a: 1);
1494 }
1495 else
1496 {
1497 Graphics()->SetColor(PointSelected ? ColorRGBA(0.0f, 1.0f, 1.0f, 1.0f) : ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f));
1498 }
1499
1500 IGraphics::CQuadItem QuadItem(Center.x, Center.y, 5.0f * MapView()->MouseWorldScale(), 5.0f * MapView()->MouseWorldScale());
1501 Graphics()->QuadsDraw(pArray: &QuadItem, Num: 1);
1502}
1503
1504void CEditor::DoQuadPivotInteraction(int LayerIndex, const std::shared_ptr<CLayerQuads> &pLayer, CQuad *pQuad, int Index)
1505{
1506 enum
1507 {
1508 OP_NONE = 0,
1509 OP_SELECT,
1510 OP_MOVE_ALL,
1511 OP_MOVE_PIVOT,
1512 OP_ROTATE,
1513 OP_CONTEXT_MENU,
1514 OP_DELETE,
1515 };
1516
1517 // some basic values
1518 const void *pId = &pQuad->m_aPoints[4]; // use pivot addr as id
1519 static std::vector<std::vector<CPoint>> s_vvRotatePoints;
1520 static int s_Operation = OP_NONE;
1521 static vec2 s_MouseStart = vec2(0.0f, 0.0f);
1522 static float s_RotateAngle = 0;
1523 static CPoint s_OriginalPosition;
1524 static std::vector<SAlignmentInfo> s_PivotAlignments; // Alignments per pivot per quad
1525 static std::vector<SAlignmentInfo> s_vAABBAlignments; // Alignments for one AABB (single quad or selection of multiple quads)
1526 static SAxisAlignedBoundingBox s_SelectionAABB; // Selection AABB
1527 static ivec2 s_LastOffset; // Last offset, stored as static so we can use it to draw every frame
1528
1529 // get pivot
1530 const bool IgnoreGrid = Input()->AltIsPressed();
1531
1532 auto &&GetDragOffset = [&]() -> ivec2 {
1533 vec2 Pos = MapView()->MouseWorldPos();
1534 if(MapView()->MapGrid()->IsEnabled() && !IgnoreGrid)
1535 {
1536 MapView()->MapGrid()->SnapToGrid(Position&: Pos);
1537 }
1538 return ivec2(f2fx(v: Pos.x) - s_OriginalPosition.x, f2fx(v: Pos.y) - s_OriginalPosition.y);
1539 };
1540
1541 if(Ui()->CheckActiveItem(pId))
1542 {
1543 if(MapView()->MouseDeltaWorld() != vec2(0.0f, 0.0f))
1544 {
1545 if(s_Operation == OP_SELECT)
1546 {
1547 if(distance_squared(a: s_MouseStart, b: Ui()->MousePos()) > 20.0f)
1548 {
1549 if(!Map()->IsQuadSelected(Index))
1550 Map()->SelectQuad(Index);
1551
1552 s_OriginalPosition = pQuad->m_aPoints[4];
1553
1554 if(Input()->ShiftIsPressed())
1555 {
1556 s_Operation = OP_MOVE_PIVOT;
1557 // When moving, we need to save the original position of all selected pivots
1558 for(int Selected : Map()->m_vSelectedQuads)
1559 {
1560 const CQuad *pCurrentQuad = &pLayer->m_vQuads[Selected];
1561 PreparePointDrag(pQuad: pCurrentQuad, QuadIndex: Selected, PointIndex: 4);
1562 }
1563 }
1564 else
1565 {
1566 s_Operation = OP_MOVE_ALL;
1567 // When moving, we need to save the original position of all selected quads points
1568 for(int Selected : Map()->m_vSelectedQuads)
1569 {
1570 const CQuad *pCurrentQuad = &pLayer->m_vQuads[Selected];
1571 for(size_t v = 0; v < 5; v++)
1572 PreparePointDrag(pQuad: pCurrentQuad, QuadIndex: Selected, PointIndex: v);
1573 }
1574 // And precompute AABB of selection since it will not change during drag
1575 if(g_Config.m_EdAlignQuads)
1576 QuadSelectionAABB(pLayer, OutAABB&: s_SelectionAABB);
1577 }
1578 }
1579 }
1580
1581 // check if we only should move pivot
1582 if(s_Operation == OP_MOVE_PIVOT)
1583 {
1584 Map()->m_QuadTracker.BeginQuadTrack(pLayer, vSelectedQuads: Map()->m_vSelectedQuads, GroupIndex: -1, LayerIndex);
1585
1586 s_LastOffset = GetDragOffset(); // Update offset
1587 ApplyAxisAlignment(Offset&: s_LastOffset); // Apply axis alignment to the offset
1588
1589 ComputePointsAlignments(pLayer, Pivot: true, Offset: s_LastOffset, vAlignments&: s_PivotAlignments);
1590 ApplyAlignments(vAlignments: s_PivotAlignments, Offset&: s_LastOffset);
1591
1592 for(auto &Selected : Map()->m_vSelectedQuads)
1593 {
1594 CQuad *pCurrentQuad = &pLayer->m_vQuads[Selected];
1595 DoPointDrag(pQuad: pCurrentQuad, QuadIndex: Selected, PointIndex: 4, Offset: s_LastOffset);
1596 }
1597 }
1598 else if(s_Operation == OP_MOVE_ALL)
1599 {
1600 Map()->m_QuadTracker.BeginQuadTrack(pLayer, vSelectedQuads: Map()->m_vSelectedQuads, GroupIndex: -1, LayerIndex);
1601
1602 // Compute drag offset
1603 s_LastOffset = GetDragOffset();
1604 ApplyAxisAlignment(Offset&: s_LastOffset);
1605
1606 // Then compute possible alignments with the selection AABB
1607 ComputeAABBAlignments(pLayer, AABB: s_SelectionAABB, Offset: s_LastOffset, vAlignments&: s_vAABBAlignments);
1608 // Apply alignments before drag
1609 ApplyAlignments(vAlignments: s_vAABBAlignments, Offset&: s_LastOffset);
1610 // Then do the drag
1611 for(int Selected : Map()->m_vSelectedQuads)
1612 {
1613 CQuad *pCurrentQuad = &pLayer->m_vQuads[Selected];
1614 for(int v = 0; v < 5; v++)
1615 DoPointDrag(pQuad: pCurrentQuad, QuadIndex: Selected, PointIndex: v, Offset: s_LastOffset);
1616 }
1617 }
1618 else if(s_Operation == OP_ROTATE)
1619 {
1620 Map()->m_QuadTracker.BeginQuadTrack(pLayer, vSelectedQuads: Map()->m_vSelectedQuads, GroupIndex: -1, LayerIndex);
1621
1622 for(size_t i = 0; i < Map()->m_vSelectedQuads.size(); ++i)
1623 {
1624 CQuad *pCurrentQuad = &pLayer->m_vQuads[Map()->m_vSelectedQuads[i]];
1625 for(int v = 0; v < 4; v++)
1626 {
1627 pCurrentQuad->m_aPoints[v] = s_vvRotatePoints[i][v];
1628 }
1629 RotatePoints(Center: pCurrentQuad->m_aPoints[4], pPoints: pCurrentQuad->m_aPoints, NumPoints: 4, Rotation: s_RotateAngle);
1630 }
1631
1632 s_RotateAngle += Ui()->MouseDeltaX() * (Input()->ShiftIsPressed() ? 0.0001f : 0.002f);
1633 }
1634 }
1635
1636 // Draw axis and alignments when moving
1637 if(s_Operation == OP_MOVE_PIVOT || s_Operation == OP_MOVE_ALL)
1638 {
1639 EAxis Axis = GetDragAxis(Offset: s_LastOffset);
1640 DrawAxis(Axis, OriginalPoint&: s_OriginalPosition, Point&: pQuad->m_aPoints[4]);
1641
1642 str_copy(dst&: m_aTooltip, src: "Hold shift to keep alignment on one axis.");
1643 }
1644
1645 if(s_Operation == OP_MOVE_PIVOT)
1646 DrawPointAlignments(vAlignments: s_PivotAlignments, Offset: s_LastOffset);
1647
1648 if(s_Operation == OP_MOVE_ALL)
1649 {
1650 DrawPointAlignments(vAlignments: s_vAABBAlignments, Offset: s_LastOffset);
1651
1652 if(g_Config.m_EdShowQuadsRect)
1653 DrawAABB(AABB: s_SelectionAABB, Offset: s_LastOffset);
1654 }
1655
1656 if(s_Operation == OP_CONTEXT_MENU)
1657 {
1658 if(!Ui()->MouseButton(Index: 1))
1659 {
1660 if(Map()->m_vSelectedLayers.size() == 1)
1661 {
1662 m_QuadPopupContext.m_pEditor = this;
1663 m_QuadPopupContext.m_SelectedQuadIndex = Map()->FindSelectedQuadIndex(Index);
1664 dbg_assert(m_QuadPopupContext.m_SelectedQuadIndex >= 0, "Selected quad index not found for quad popup");
1665 m_QuadPopupContext.m_Color = PackColor(Color: AverageColor(vpQuads: Map()->SelectedQuads()));
1666 Ui()->DoPopupMenu(pId: &m_QuadPopupContext, X: Ui()->MouseX(), Y: Ui()->MouseY(), Width: 120, Height: 251, pContext: &m_QuadPopupContext, pfnFunc: PopupQuad);
1667 Ui()->DisableMouseLock();
1668 }
1669 s_Operation = OP_NONE;
1670 Ui()->SetActiveItem(nullptr);
1671 }
1672 }
1673 else if(s_Operation == OP_DELETE)
1674 {
1675 if(!Ui()->MouseButton(Index: 1))
1676 {
1677 if(Map()->m_vSelectedLayers.size() == 1)
1678 {
1679 Ui()->DisableMouseLock();
1680 Map()->OnModify();
1681 Map()->DeleteSelectedQuads();
1682 }
1683 s_Operation = OP_NONE;
1684 Ui()->SetActiveItem(nullptr);
1685 }
1686 }
1687 else if(s_Operation == OP_ROTATE)
1688 {
1689 if(Ui()->MouseButton(Index: 0))
1690 {
1691 Ui()->DisableMouseLock();
1692 s_Operation = OP_NONE;
1693 Ui()->SetActiveItem(nullptr);
1694 Map()->m_QuadTracker.EndQuadTrack();
1695 }
1696 else if(Ui()->MouseButton(Index: 1))
1697 {
1698 Ui()->DisableMouseLock();
1699 s_Operation = OP_NONE;
1700 Ui()->SetActiveItem(nullptr);
1701
1702 // Reset points to old position
1703 for(size_t i = 0; i < Map()->m_vSelectedQuads.size(); ++i)
1704 {
1705 CQuad *pCurrentQuad = &pLayer->m_vQuads[Map()->m_vSelectedQuads[i]];
1706 for(int v = 0; v < 4; v++)
1707 pCurrentQuad->m_aPoints[v] = s_vvRotatePoints[i][v];
1708 }
1709 }
1710 }
1711 else
1712 {
1713 if(!Ui()->MouseButton(Index: 0))
1714 {
1715 if(s_Operation == OP_SELECT)
1716 {
1717 if(Input()->ShiftIsPressed())
1718 Map()->ToggleSelectQuad(Index);
1719 else
1720 Map()->SelectQuad(Index);
1721 }
1722 else if(s_Operation == OP_MOVE_PIVOT || s_Operation == OP_MOVE_ALL)
1723 {
1724 Map()->m_QuadTracker.EndQuadTrack();
1725 }
1726
1727 Ui()->DisableMouseLock();
1728 s_Operation = OP_NONE;
1729 Ui()->SetActiveItem(nullptr);
1730
1731 s_LastOffset = ivec2();
1732 s_OriginalPosition = ivec2();
1733 s_vAABBAlignments.clear();
1734 s_PivotAlignments.clear();
1735 }
1736 }
1737 }
1738 else if(Input()->KeyPress(Key: KEY_R) && !Map()->m_vSelectedQuads.empty() && m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && !Ui()->IsPopupOpen())
1739 {
1740 Ui()->EnableMouseLock(pId);
1741 Ui()->SetActiveItem(pId);
1742 s_Operation = OP_ROTATE;
1743 s_RotateAngle = 0;
1744
1745 s_vvRotatePoints.clear();
1746 s_vvRotatePoints.resize(sz: Map()->m_vSelectedQuads.size());
1747 for(size_t i = 0; i < Map()->m_vSelectedQuads.size(); ++i)
1748 {
1749 CQuad *pCurrentQuad = &pLayer->m_vQuads[Map()->m_vSelectedQuads[i]];
1750
1751 s_vvRotatePoints[i].resize(sz: 4);
1752 s_vvRotatePoints[i][0] = pCurrentQuad->m_aPoints[0];
1753 s_vvRotatePoints[i][1] = pCurrentQuad->m_aPoints[1];
1754 s_vvRotatePoints[i][2] = pCurrentQuad->m_aPoints[2];
1755 s_vvRotatePoints[i][3] = pCurrentQuad->m_aPoints[3];
1756 }
1757 }
1758 else if(Ui()->HotItem() == pId)
1759 {
1760 m_pUiGotContext = pId;
1761
1762 str_copy(dst&: m_aTooltip, src: "Left mouse button to move. Hold shift to move pivot. Hold alt to ignore grid. Shift+right click to delete.");
1763
1764 if(Ui()->MouseButton(Index: 0))
1765 {
1766 Ui()->SetActiveItem(pId);
1767
1768 s_MouseStart = Ui()->MousePos();
1769 s_Operation = OP_SELECT;
1770 }
1771 else if(Ui()->MouseButtonClicked(Index: 1))
1772 {
1773 if(Input()->ShiftIsPressed())
1774 {
1775 s_Operation = OP_DELETE;
1776
1777 if(!Map()->IsQuadSelected(Index))
1778 Map()->SelectQuad(Index);
1779
1780 Ui()->SetActiveItem(pId);
1781 }
1782 else
1783 {
1784 s_Operation = OP_CONTEXT_MENU;
1785
1786 if(!Map()->IsQuadSelected(Index))
1787 Map()->SelectQuad(Index);
1788
1789 Ui()->SetActiveItem(pId);
1790 }
1791 }
1792 }
1793}
1794
1795void CEditor::DoQuadPointInteraction(int LayerIndex, const std::shared_ptr<CLayerQuads> &pLayer, CQuad *pQuad, int QuadIndex, int PointIndex)
1796{
1797 const void *pId = &pQuad->m_aPoints[PointIndex];
1798 const bool IgnoreGrid = Input()->AltIsPressed();
1799
1800 enum
1801 {
1802 OP_NONE = 0,
1803 OP_SELECT,
1804 OP_MOVEPOINT,
1805 OP_MOVEUV,
1806 OP_CONTEXT_MENU
1807 };
1808
1809 static int s_Operation = OP_NONE;
1810 static vec2 s_MouseStart = vec2(0.0f, 0.0f);
1811 static CPoint s_OriginalPoint;
1812 static std::vector<SAlignmentInfo> s_Alignments; // Alignments
1813 static ivec2 s_LastOffset;
1814
1815 auto &&GetDragOffset = [&]() -> ivec2 {
1816 vec2 Pos = MapView()->MouseWorldPos();
1817 if(MapView()->MapGrid()->IsEnabled() && !IgnoreGrid)
1818 {
1819 MapView()->MapGrid()->SnapToGrid(Position&: Pos);
1820 }
1821 return ivec2(f2fx(v: Pos.x) - s_OriginalPoint.x, f2fx(v: Pos.y) - s_OriginalPoint.y);
1822 };
1823
1824 if(Ui()->CheckActiveItem(pId))
1825 {
1826 if(MapView()->MouseDeltaWorld() != vec2(0.0f, 0.0f))
1827 {
1828 if(s_Operation == OP_SELECT)
1829 {
1830 if(distance_squared(a: s_MouseStart, b: Ui()->MousePos()) > 20.0f)
1831 {
1832 if(!Map()->IsQuadPointSelected(QuadIndex, Index: PointIndex))
1833 Map()->SelectQuadPoint(QuadIndex, Index: PointIndex);
1834
1835 if(Input()->ShiftIsPressed())
1836 {
1837 s_Operation = OP_MOVEUV;
1838 Ui()->EnableMouseLock(pId);
1839 }
1840 else
1841 {
1842 s_Operation = OP_MOVEPOINT;
1843 // Save original positions before moving
1844 s_OriginalPoint = pQuad->m_aPoints[PointIndex];
1845 for(int Selected : Map()->m_vSelectedQuads)
1846 {
1847 for(int m = 0; m < 4; m++)
1848 if(Map()->IsQuadCornerSelected(Index: m))
1849 PreparePointDrag(pQuad: &pLayer->m_vQuads[Selected], QuadIndex: Selected, PointIndex: m);
1850 }
1851 }
1852 }
1853 }
1854
1855 if(s_Operation == OP_MOVEPOINT)
1856 {
1857 Map()->m_QuadTracker.BeginQuadTrack(pLayer, vSelectedQuads: Map()->m_vSelectedQuads, GroupIndex: -1, LayerIndex);
1858
1859 s_LastOffset = GetDragOffset(); // Update offset
1860 ApplyAxisAlignment(Offset&: s_LastOffset); // Apply axis alignment to offset
1861
1862 ComputePointsAlignments(pLayer, Pivot: false, Offset: s_LastOffset, vAlignments&: s_Alignments);
1863 ApplyAlignments(vAlignments: s_Alignments, Offset&: s_LastOffset);
1864
1865 for(int Selected : Map()->m_vSelectedQuads)
1866 {
1867 for(int m = 0; m < 4; m++)
1868 {
1869 if(Map()->IsQuadCornerSelected(Index: m))
1870 {
1871 DoPointDrag(pQuad: &pLayer->m_vQuads[Selected], QuadIndex: Selected, PointIndex: m, Offset: s_LastOffset);
1872 }
1873 }
1874 }
1875 }
1876 else if(s_Operation == OP_MOVEUV)
1877 {
1878 int SelectedPoints = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3);
1879
1880 Map()->m_QuadTracker.BeginQuadPointPropTrack(pLayer, vSelectedQuads: Map()->m_vSelectedQuads, SelectedQuadPoints: SelectedPoints, GroupIndex: -1, LayerIndex);
1881 Map()->m_QuadTracker.AddQuadPointPropTrack(Prop: EQuadPointProp::TEX_U);
1882 Map()->m_QuadTracker.AddQuadPointPropTrack(Prop: EQuadPointProp::TEX_V);
1883
1884 for(int Selected : Map()->m_vSelectedQuads)
1885 {
1886 CQuad *pSelectedQuad = &pLayer->m_vQuads[Selected];
1887 for(int m = 0; m < 4; m++)
1888 {
1889 if(Map()->IsQuadCornerSelected(Index: m))
1890 {
1891 // 0,2;1,3 - line x
1892 // 0,1;2,3 - line y
1893
1894 pSelectedQuad->m_aTexcoords[m].x += f2fx(v: MapView()->MouseDeltaWorld().x * 0.001f);
1895 pSelectedQuad->m_aTexcoords[(m + 2) % 4].x += f2fx(v: MapView()->MouseDeltaWorld().x * 0.001f);
1896
1897 pSelectedQuad->m_aTexcoords[m].y += f2fx(v: MapView()->MouseDeltaWorld().y * 0.001f);
1898 pSelectedQuad->m_aTexcoords[m ^ 1].y += f2fx(v: MapView()->MouseDeltaWorld().y * 0.001f);
1899 }
1900 }
1901 }
1902 }
1903 }
1904
1905 // Draw axis and alignments when dragging
1906 if(s_Operation == OP_MOVEPOINT)
1907 {
1908 Graphics()->SetColor(r: 1, g: 0, b: 0.1f, a: 1);
1909
1910 // Axis
1911 EAxis Axis = GetDragAxis(Offset: s_LastOffset);
1912 DrawAxis(Axis, OriginalPoint&: s_OriginalPoint, Point&: pQuad->m_aPoints[PointIndex]);
1913
1914 // Alignments
1915 DrawPointAlignments(vAlignments: s_Alignments, Offset: s_LastOffset);
1916
1917 str_copy(dst&: m_aTooltip, src: "Hold shift to keep alignment on one axis.");
1918 }
1919
1920 if(s_Operation == OP_CONTEXT_MENU)
1921 {
1922 if(!Ui()->MouseButton(Index: 1))
1923 {
1924 if(Map()->m_vSelectedLayers.size() == 1)
1925 {
1926 if(!Map()->IsQuadSelected(Index: QuadIndex))
1927 Map()->SelectQuad(Index: QuadIndex);
1928
1929 m_PointPopupContext.m_pEditor = this;
1930 m_PointPopupContext.m_SelectedQuadPoint = PointIndex;
1931 m_PointPopupContext.m_SelectedQuadIndex = Map()->FindSelectedQuadIndex(Index: QuadIndex);
1932 dbg_assert(m_PointPopupContext.m_SelectedQuadIndex >= 0, "Selected quad index not found for quad point popup");
1933 Ui()->DoPopupMenu(pId: &m_PointPopupContext, X: Ui()->MouseX(), Y: Ui()->MouseY(), Width: 120, Height: 75, pContext: &m_PointPopupContext, pfnFunc: PopupPoint);
1934 }
1935 Ui()->SetActiveItem(nullptr);
1936 }
1937 }
1938 else
1939 {
1940 if(!Ui()->MouseButton(Index: 0))
1941 {
1942 if(s_Operation == OP_SELECT)
1943 {
1944 if(Input()->ShiftIsPressed())
1945 Map()->ToggleSelectQuadPoint(QuadIndex, Index: PointIndex);
1946 else
1947 Map()->SelectQuadPoint(QuadIndex, Index: PointIndex);
1948 }
1949
1950 if(s_Operation == OP_MOVEPOINT)
1951 {
1952 Map()->m_QuadTracker.EndQuadTrack();
1953 }
1954 else if(s_Operation == OP_MOVEUV)
1955 {
1956 Map()->m_QuadTracker.EndQuadPointPropTrackAll();
1957 }
1958
1959 Ui()->DisableMouseLock();
1960 Ui()->SetActiveItem(nullptr);
1961 }
1962 }
1963 }
1964 else if(Ui()->HotItem() == pId)
1965 {
1966 m_pUiGotContext = pId;
1967
1968 str_copy(dst&: m_aTooltip, src: "Left mouse button to move. Hold shift to move the texture. Hold alt to ignore grid.");
1969
1970 if(Ui()->MouseButton(Index: 0))
1971 {
1972 Ui()->SetActiveItem(pId);
1973
1974 s_MouseStart = Ui()->MousePos();
1975 s_Operation = OP_SELECT;
1976 }
1977 else if(Ui()->MouseButtonClicked(Index: 1))
1978 {
1979 s_Operation = OP_CONTEXT_MENU;
1980
1981 Ui()->SetActiveItem(pId);
1982
1983 if(!Map()->IsQuadPointSelected(QuadIndex, Index: PointIndex))
1984 Map()->SelectQuadPoint(QuadIndex, Index: PointIndex);
1985 }
1986 }
1987}
1988
1989void CEditor::DoQuadEnvelopes(const CLayerQuads *pLayerQuads)
1990{
1991 const std::vector<CQuad> &vQuads = pLayerQuads->m_vQuads;
1992 if(vQuads.empty())
1993 {
1994 return;
1995 }
1996
1997 std::vector<std::pair<const CQuad *, CEnvelope *>> vQuadsWithEnvelopes;
1998 vQuadsWithEnvelopes.reserve(n: vQuads.size());
1999 for(const auto &Quad : vQuads)
2000 {
2001 if(m_ActiveEnvelopePreview != EEnvelopePreview::ALL &&
2002 !(m_ActiveEnvelopePreview == EEnvelopePreview::SELECTED && Quad.m_PosEnv == Map()->m_SelectedEnvelope))
2003 {
2004 continue;
2005 }
2006 if(Quad.m_PosEnv < 0 ||
2007 Quad.m_PosEnv >= (int)Map()->m_vpEnvelopes.size() ||
2008 Map()->m_vpEnvelopes[Quad.m_PosEnv]->m_vPoints.empty())
2009 {
2010 continue;
2011 }
2012 vQuadsWithEnvelopes.emplace_back(args: &Quad, args: Map()->m_vpEnvelopes[Quad.m_PosEnv].get());
2013 }
2014 if(vQuadsWithEnvelopes.empty())
2015 {
2016 return;
2017 }
2018
2019 Map()->SelectedGroup()->MapScreen();
2020
2021 // Draw lines between points
2022 Graphics()->TextureClear();
2023 IGraphics::CLineItemBatch LineItemBatch;
2024 Graphics()->LinesBatchBegin(pBatch: &LineItemBatch);
2025 Graphics()->SetColor(ColorRGBA(0.0f, 1.0f, 1.0f, 0.75f));
2026 for(const auto &[pQuad, pEnvelope] : vQuadsWithEnvelopes)
2027 {
2028 if(pEnvelope->m_vPoints.size() < 2)
2029 {
2030 continue;
2031 }
2032
2033 const CPoint *pPivotPoint = &pQuad->m_aPoints[4];
2034 const vec2 PivotPoint = vec2(fx2f(v: pPivotPoint->x), fx2f(v: pPivotPoint->y));
2035
2036 for(int PointIndex = 0; PointIndex <= (int)pEnvelope->m_vPoints.size() - 2; PointIndex++)
2037 {
2038 const auto &PointStart = pEnvelope->m_vPoints[PointIndex];
2039 const auto &PointEnd = pEnvelope->m_vPoints[PointIndex + 1];
2040 const float PointStartTime = PointStart.m_Time.AsSeconds();
2041 const float PointEndTime = PointEnd.m_Time.AsSeconds();
2042 const float TimeRange = PointEndTime - PointStartTime;
2043
2044 int Steps;
2045 if(PointStart.m_Curvetype == CURVETYPE_BEZIER)
2046 {
2047 Steps = std::clamp(val: round_to_int(f: TimeRange * 10.0f), lo: 50, hi: 150);
2048 }
2049 else
2050 {
2051 Steps = 1;
2052 }
2053 ColorRGBA StartPosition = PointStart.ColorValue();
2054 for(int Step = 1; Step <= Steps; Step++)
2055 {
2056 ColorRGBA EndPosition;
2057 if(Step == Steps)
2058 {
2059 EndPosition = PointEnd.ColorValue();
2060 }
2061 else
2062 {
2063 const float SectionEndTime = PointStartTime + TimeRange * (Step / (float)Steps);
2064 EndPosition = ColorRGBA(0.0f, 0.0f, 0.0f, 0.0f);
2065 pEnvelope->Eval(Time: SectionEndTime, Result&: EndPosition, Channels: 2);
2066 }
2067
2068 const vec2 Pos0 = PivotPoint + vec2(StartPosition.r, StartPosition.g);
2069 const vec2 Pos1 = PivotPoint + vec2(EndPosition.r, EndPosition.g);
2070 const IGraphics::CLineItem Item = IGraphics::CLineItem(Pos0, Pos1);
2071 Graphics()->LinesBatchDraw(pBatch: &LineItemBatch, pArray: &Item, Num: 1);
2072
2073 StartPosition = EndPosition;
2074 }
2075 }
2076 }
2077 Graphics()->LinesBatchEnd(pBatch: &LineItemBatch);
2078
2079 // Draw quads at points
2080 if(pLayerQuads->m_Image >= 0 && pLayerQuads->m_Image < (int)Map()->m_vpImages.size())
2081 {
2082 Graphics()->TextureSet(Texture: Map()->m_vpImages[pLayerQuads->m_Image]->m_Texture);
2083 }
2084 else
2085 {
2086 Graphics()->TextureClear();
2087 }
2088 Graphics()->QuadsBegin();
2089 for(const auto &[pQuad, pEnvelope] : vQuadsWithEnvelopes)
2090 {
2091 for(size_t PointIndex = 0; PointIndex < pEnvelope->m_vPoints.size(); PointIndex++)
2092 {
2093 const CEnvPoint_runtime &EnvPoint = pEnvelope->m_vPoints[PointIndex];
2094 const vec2 Offset = vec2(fx2f(v: EnvPoint.m_aValues[0]), fx2f(v: EnvPoint.m_aValues[1]));
2095 const float Rotation = fx2f(v: EnvPoint.m_aValues[2]) / 180.0f * pi;
2096
2097 const float Alpha =
2098 ((Map()->m_SelectedQuadEnvelope == pQuad->m_PosEnv && Map()->m_SelectedQuadEnvelopePoint == (int)PointIndex) ||
2099 (m_EnvelopeEditor.IsPointOperationActive() && Map()->m_SelectedEnvelope == pQuad->m_PosEnv && Map()->IsEnvPointSelected(Index: PointIndex))) ?
2100 0.65f :
2101 0.35f;
2102 Graphics()->SetColor4(
2103 TopLeft: ColorRGBA(pQuad->m_aColors[0].r, pQuad->m_aColors[0].g, pQuad->m_aColors[0].b, pQuad->m_aColors[0].a).Multiply(Factor: 1.0f / 255.0f).WithMultipliedAlpha(alpha: Alpha),
2104 TopRight: ColorRGBA(pQuad->m_aColors[1].r, pQuad->m_aColors[1].g, pQuad->m_aColors[1].b, pQuad->m_aColors[1].a).Multiply(Factor: 1.0f / 255.0f).WithMultipliedAlpha(alpha: Alpha),
2105 BottomLeft: ColorRGBA(pQuad->m_aColors[3].r, pQuad->m_aColors[3].g, pQuad->m_aColors[3].b, pQuad->m_aColors[3].a).Multiply(Factor: 1.0f / 255.0f).WithMultipliedAlpha(alpha: Alpha),
2106 BottomRight: ColorRGBA(pQuad->m_aColors[2].r, pQuad->m_aColors[2].g, pQuad->m_aColors[2].b, pQuad->m_aColors[2].a).Multiply(Factor: 1.0f / 255.0f).WithMultipliedAlpha(alpha: Alpha));
2107
2108 const CPoint *pPoints;
2109 CPoint aRotated[4];
2110 if(Rotation == 0.0f)
2111 {
2112 pPoints = pQuad->m_aPoints;
2113 }
2114 else
2115 {
2116 std::copy_n(first: pQuad->m_aPoints, n: std::size(aRotated), result: aRotated);
2117 RotatePoints(Center: pQuad->m_aPoints[4], pPoints: aRotated, NumPoints: std::size(aRotated), Rotation);
2118 pPoints = aRotated;
2119 }
2120
2121 Graphics()->QuadsSetSubsetFree(
2122 x0: fx2f(v: pQuad->m_aTexcoords[0].x), y0: fx2f(v: pQuad->m_aTexcoords[0].y),
2123 x1: fx2f(v: pQuad->m_aTexcoords[1].x), y1: fx2f(v: pQuad->m_aTexcoords[1].y),
2124 x2: fx2f(v: pQuad->m_aTexcoords[2].x), y2: fx2f(v: pQuad->m_aTexcoords[2].y),
2125 x3: fx2f(v: pQuad->m_aTexcoords[3].x), y3: fx2f(v: pQuad->m_aTexcoords[3].y));
2126
2127 const IGraphics::CFreeformItem Freeform(
2128 fx2f(v: pPoints[0].x) + Offset.x, fx2f(v: pPoints[0].y) + Offset.y,
2129 fx2f(v: pPoints[1].x) + Offset.x, fx2f(v: pPoints[1].y) + Offset.y,
2130 fx2f(v: pPoints[2].x) + Offset.x, fx2f(v: pPoints[2].y) + Offset.y,
2131 fx2f(v: pPoints[3].x) + Offset.x, fx2f(v: pPoints[3].y) + Offset.y);
2132 Graphics()->QuadsDrawFreeform(pArray: &Freeform, Num: 1);
2133 }
2134 }
2135 Graphics()->QuadsEnd();
2136
2137 // Draw quad envelope point handles
2138 Graphics()->TextureClear();
2139 Graphics()->QuadsBegin();
2140 for(const auto &[pQuad, pEnvelope] : vQuadsWithEnvelopes)
2141 {
2142 for(size_t PointIndex = 0; PointIndex < pEnvelope->m_vPoints.size(); PointIndex++)
2143 {
2144 DoQuadEnvPoint(pQuad, pEnvelope, QuadIndex: pQuad - vQuads.data(), PointIndex);
2145 }
2146 }
2147 Graphics()->QuadsEnd();
2148}
2149
2150void CEditor::DoQuadEnvPoint(const CQuad *pQuad, CEnvelope *pEnvelope, int QuadIndex, int PointIndex)
2151{
2152 CEnvPoint_runtime *pPoint = &pEnvelope->m_vPoints[PointIndex];
2153 const vec2 Center = vec2(fx2f(v: pQuad->m_aPoints[4].x) + fx2f(v: pPoint->m_aValues[0]), fx2f(v: pQuad->m_aPoints[4].y) + fx2f(v: pPoint->m_aValues[1]));
2154 const bool IgnoreGrid = Input()->AltIsPressed();
2155
2156 if(Ui()->CheckActiveItem(pId: pPoint) && Map()->m_CurrentQuadIndex == QuadIndex)
2157 {
2158 if(MapView()->MouseDeltaWorld() != vec2(0.0f, 0.0f))
2159 {
2160 if(m_QuadEnvelopePointOperation == EQuadEnvelopePointOperation::MOVE)
2161 {
2162 vec2 Pos = MapView()->MouseWorldPos();
2163 if(MapView()->MapGrid()->IsEnabled() && !IgnoreGrid)
2164 {
2165 MapView()->MapGrid()->SnapToGrid(Position&: Pos);
2166 }
2167 pPoint->m_aValues[0] = f2fx(v: Pos.x) - pQuad->m_aPoints[4].x;
2168 pPoint->m_aValues[1] = f2fx(v: Pos.y) - pQuad->m_aPoints[4].y;
2169 }
2170 else if(m_QuadEnvelopePointOperation == EQuadEnvelopePointOperation::ROTATE)
2171 {
2172 pPoint->m_aValues[2] += 10 * Ui()->MouseDeltaX();
2173 }
2174 }
2175
2176 if(!Ui()->MouseButton(Index: 0))
2177 {
2178 Ui()->DisableMouseLock();
2179 m_QuadEnvelopePointOperation = EQuadEnvelopePointOperation::NONE;
2180 Ui()->SetActiveItem(nullptr);
2181 Map()->m_SelectedQuadEnvelope = -1;
2182 Map()->m_SelectedQuadEnvelopePoint = -1;
2183 }
2184 else
2185 {
2186 Map()->m_SelectedQuadEnvelope = pQuad->m_PosEnv;
2187 Map()->m_SelectedQuadEnvelopePoint = PointIndex;
2188 }
2189
2190 Graphics()->SetColor(ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f));
2191 }
2192 else if(Ui()->HotItem() == pPoint && Map()->m_CurrentQuadIndex == QuadIndex)
2193 {
2194 Graphics()->SetColor(ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f));
2195 str_copy(dst&: m_aTooltip, src: "Left mouse button to move. Hold ctrl to rotate. Hold alt to ignore grid.");
2196
2197 if(Ui()->MouseButton(Index: 0))
2198 {
2199 if(Input()->ModifierIsPressed())
2200 {
2201 Ui()->EnableMouseLock(pId: pPoint);
2202 m_QuadEnvelopePointOperation = EQuadEnvelopePointOperation::ROTATE;
2203 }
2204 else
2205 {
2206 m_QuadEnvelopePointOperation = EQuadEnvelopePointOperation::MOVE;
2207 }
2208 Map()->SelectQuad(Index: QuadIndex);
2209 Map()->m_SelectedQuadEnvelope = pQuad->m_PosEnv;
2210 Map()->m_SelectedQuadEnvelopePoint = PointIndex;
2211 Ui()->SetActiveItem(pPoint);
2212 }
2213 else
2214 {
2215 Map()->m_SelectedQuadEnvelope = -1;
2216 Map()->m_SelectedQuadEnvelopePoint = -1;
2217 }
2218 }
2219 else
2220 {
2221 Graphics()->SetColor(ColorRGBA(0.0f, 1.0f, 1.0f, 1.0f));
2222 }
2223
2224 IGraphics::CQuadItem QuadItem(Center.x, Center.y, 5.0f * MapView()->MouseWorldScale(), 5.0f * MapView()->MouseWorldScale());
2225 Graphics()->QuadsDraw(pArray: &QuadItem, Num: 1);
2226}
2227
2228void CEditor::UpdateHotQuadPoint(const CLayerQuads *pLayer, const std::vector<bool> &vQuadSelected)
2229{
2230 const vec2 MouseWorld = MapView()->MouseWorldPos();
2231 const float Scale = MapView()->MouseWorldScale();
2232
2233 float MinDist = 500.0f;
2234 const void *pMinPointId = nullptr;
2235 bool MinSelected = false;
2236
2237 const auto UpdateMinimum = [&](vec2 Position, const void *pId, bool Selected) {
2238 const float CurrDist = distance_squared(a: Position, b: MouseWorld) / (Scale * Scale);
2239 // Prefer points of selected quads when they overlap exactly.
2240 if(CurrDist < MinDist || (CurrDist == MinDist && Selected && !MinSelected))
2241 {
2242 MinDist = CurrDist;
2243 pMinPointId = pId;
2244 MinSelected = Selected;
2245 return true;
2246 }
2247 return false;
2248 };
2249
2250 for(const CQuad &Quad : pLayer->m_vQuads)
2251 {
2252 const size_t QuadIndex = &Quad - pLayer->m_vQuads.data();
2253 const bool QuadSelected = QuadIndex < vQuadSelected.size() && vQuadSelected[QuadIndex];
2254
2255 if(m_ShowEnvelopePreview &&
2256 m_ActiveEnvelopePreview != EEnvelopePreview::NONE &&
2257 Quad.m_PosEnv >= 0 &&
2258 Quad.m_PosEnv < (int)Map()->m_vpEnvelopes.size())
2259 {
2260 for(const auto &EnvPoint : Map()->m_vpEnvelopes[Quad.m_PosEnv]->m_vPoints)
2261 {
2262 const vec2 Position = vec2(fx2f(v: Quad.m_aPoints[4].x) + fx2f(v: EnvPoint.m_aValues[0]), fx2f(v: Quad.m_aPoints[4].y) + fx2f(v: EnvPoint.m_aValues[1]));
2263 if(UpdateMinimum(Position, &EnvPoint, QuadSelected) && Ui()->ActiveItem() == nullptr)
2264 {
2265 Map()->m_CurrentQuadIndex = (int)QuadIndex;
2266 }
2267 }
2268 }
2269
2270 for(const auto &Point : Quad.m_aPoints)
2271 {
2272 UpdateMinimum(vec2(fx2f(v: Point.x), fx2f(v: Point.y)), &Point, QuadSelected);
2273 }
2274 }
2275
2276 if(pMinPointId != nullptr)
2277 {
2278 Ui()->SetHotItem(pMinPointId);
2279 }
2280}
2281
2282void CEditor::DoColorPickerButton(const void *pId, const CUIRect *pRect, ColorRGBA Color, const std::function<void(ColorRGBA Color)> &SetColor)
2283{
2284 CUIRect ColorRect;
2285 pRect->Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.5f * Ui()->ButtonColorMul(pId)), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
2286 pRect->Margin(Cut: 1.0f, pOtherRect: &ColorRect);
2287 ColorRect.Draw(Color, Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
2288
2289 const int ButtonResult = DoButtonLogic(pId, Checked: 0, pRect, Flags: BUTTONFLAG_ALL, pToolTip: "Click to show the color picker. Shift+right click to copy color to clipboard. Shift+left click to paste color from clipboard.");
2290 if(Input()->ShiftIsPressed())
2291 {
2292 if(ButtonResult == 1)
2293 {
2294 std::string Clipboard = Input()->GetClipboardText();
2295 if(Clipboard[0] == '#' || Clipboard[0] == '$') // ignore leading # (web color format) and $ (console color format)
2296 Clipboard = Clipboard.substr(pos: 1);
2297 if(str_isallnum_hex(str: Clipboard.c_str()))
2298 {
2299 std::optional<ColorRGBA> ParsedColor = color_parse<ColorRGBA>(pStr: Clipboard.c_str());
2300 if(ParsedColor)
2301 {
2302 m_ColorPickerPopupContext.m_State = EEditState::ONE_GO;
2303 SetColor(ParsedColor.value());
2304 }
2305 }
2306 }
2307 else if(ButtonResult == 2)
2308 {
2309 char aClipboard[9];
2310 str_format(buffer: aClipboard, buffer_size: sizeof(aClipboard), format: "%08X", Color.PackAlphaLast());
2311 Input()->SetClipboardText(aClipboard);
2312 }
2313 }
2314 else if(ButtonResult > 0)
2315 {
2316 if(m_ColorPickerPopupContext.m_ColorMode == CUi::SColorPickerPopupContext::MODE_UNSET)
2317 m_ColorPickerPopupContext.m_ColorMode = CUi::SColorPickerPopupContext::MODE_RGBA;
2318 m_ColorPickerPopupContext.m_RgbaColor = Color;
2319 m_ColorPickerPopupContext.m_HslaColor = color_cast<ColorHSLA>(rgb: Color);
2320 m_ColorPickerPopupContext.m_HsvaColor = color_cast<ColorHSVA>(hsl: m_ColorPickerPopupContext.m_HslaColor);
2321 m_ColorPickerPopupContext.m_Alpha = true;
2322 m_pColorPickerPopupActiveId = pId;
2323 Ui()->ShowPopupColorPicker(X: Ui()->MouseX(), Y: Ui()->MouseY(), pContext: &m_ColorPickerPopupContext);
2324 }
2325
2326 if(Ui()->IsPopupOpen(pId: &m_ColorPickerPopupContext))
2327 {
2328 if(m_pColorPickerPopupActiveId == pId)
2329 SetColor(m_ColorPickerPopupContext.m_RgbaColor);
2330 }
2331 else
2332 {
2333 m_pColorPickerPopupActiveId = nullptr;
2334 if(m_ColorPickerPopupContext.m_State == EEditState::EDITING)
2335 {
2336 m_ColorPickerPopupContext.m_State = EEditState::END;
2337 SetColor(m_ColorPickerPopupContext.m_RgbaColor);
2338 m_ColorPickerPopupContext.m_State = EEditState::NONE;
2339 }
2340 }
2341}
2342
2343bool CEditor::IsAllowPlaceUnusedTiles() const
2344{
2345 // explicit allow and implicit allow
2346 return m_AllowPlaceUnusedTiles != EUnusedEntities::NOT_ALLOWED;
2347}
2348
2349void CEditor::CRenderLayersState::Reset()
2350{
2351 m_Operation = ELayerOperation::NONE;
2352 m_PreviousOperation = ELayerOperation::NONE;
2353 m_pDraggedButton = nullptr;
2354 m_InitialMouseY = 0.0f;
2355 m_InitialCutHeight = 0.0f;
2356 m_ScrollToSelectionNext = false;
2357 m_InitialGroupIndex = 0;
2358 m_vInitialLayerIndices.clear();
2359 m_LayerPopupContext = {};
2360}
2361
2362void CEditor::RenderLayers(CUIRect LayersBox)
2363{
2364 CRenderLayersState &State = m_RenderLayersState;
2365
2366 const float RowHeight = 12.0f;
2367 char aBuf[64];
2368
2369 CUIRect UnscrolledLayersBox = LayersBox;
2370
2371 CScrollRegion &ScrollRegion = Map()->m_EditorUiElements.m_LayersScrollRegion;
2372 CScrollRegionParams ScrollParams;
2373 ScrollParams.m_ScrollbarThickness = 10.0f;
2374 ScrollParams.m_ScrollbarMargin = 3.0f;
2375 ScrollParams.m_ScrollUnit = RowHeight * 5.0f;
2376 ScrollRegion.Begin(pClipRect: &LayersBox, pParams: &ScrollParams);
2377
2378 constexpr float MinDragDistance = 5.0f;
2379 int GroupAfterDraggedLayer = -1;
2380 int LayerAfterDraggedLayer = -1;
2381 bool DraggedPositionFound = false;
2382 bool MoveLayers = false;
2383 bool MoveGroup = false;
2384 bool StartDragLayer = false;
2385 bool StartDragGroup = false;
2386 std::vector<int> vButtonsPerGroup;
2387
2388 auto SetOperation = [&](ELayerOperation Operation) {
2389 if(Operation != State.m_Operation)
2390 {
2391 State.m_PreviousOperation = State.m_Operation;
2392 State.m_Operation = Operation;
2393 if(Operation == ELayerOperation::NONE)
2394 {
2395 State.m_pDraggedButton = nullptr;
2396 }
2397 }
2398 };
2399
2400 vButtonsPerGroup.reserve(n: Map()->m_vpGroups.size());
2401 for(const std::shared_ptr<CLayerGroup> &pGroup : Map()->m_vpGroups)
2402 {
2403 vButtonsPerGroup.push_back(x: pGroup->m_vpLayers.size() + 1);
2404 }
2405
2406 if(State.m_pDraggedButton != nullptr && Ui()->ActiveItem() != State.m_pDraggedButton)
2407 {
2408 SetOperation(ELayerOperation::NONE);
2409 }
2410
2411 if(State.m_Operation == ELayerOperation::LAYER_DRAG || State.m_Operation == ELayerOperation::GROUP_DRAG)
2412 {
2413 float MinDraggableValue = UnscrolledLayersBox.y;
2414 float MaxDraggableValue = MinDraggableValue;
2415 for(int NumButtons : vButtonsPerGroup)
2416 {
2417 MaxDraggableValue += NumButtons * (RowHeight + 2.0f) + 5.0f;
2418 }
2419 MaxDraggableValue += LayersBox.y - UnscrolledLayersBox.y;
2420
2421 if(State.m_Operation == ELayerOperation::GROUP_DRAG)
2422 {
2423 MaxDraggableValue -= vButtonsPerGroup[Map()->m_SelectedGroup] * (RowHeight + 2.0f) + 5.0f;
2424 }
2425 else if(State.m_Operation == ELayerOperation::LAYER_DRAG)
2426 {
2427 MinDraggableValue += RowHeight + 2.0f;
2428 MaxDraggableValue -= Map()->m_vSelectedLayers.size() * (RowHeight + 2.0f) + 5.0f;
2429 }
2430
2431 UnscrolledLayersBox.HSplitTop(Cut: State.m_InitialCutHeight, pTop: nullptr, pBottom: &UnscrolledLayersBox);
2432 UnscrolledLayersBox.y -= State.m_InitialMouseY - Ui()->MouseY();
2433
2434 UnscrolledLayersBox.y = std::clamp(val: UnscrolledLayersBox.y, lo: MinDraggableValue, hi: MaxDraggableValue);
2435
2436 UnscrolledLayersBox.w = LayersBox.w;
2437 }
2438
2439 const bool ScrollToSelection = LayerSelector()->SelectByTile() || State.m_ScrollToSelectionNext;
2440 State.m_ScrollToSelectionNext = false;
2441
2442 // render layers
2443 for(int g = 0; g < (int)Map()->m_vpGroups.size(); g++)
2444 {
2445 if(State.m_Operation == ELayerOperation::LAYER_DRAG && g > 0 && !DraggedPositionFound && Ui()->MouseY() < LayersBox.y + RowHeight / 2)
2446 {
2447 DraggedPositionFound = true;
2448 GroupAfterDraggedLayer = g;
2449
2450 LayerAfterDraggedLayer = Map()->m_vpGroups[g - 1]->m_vpLayers.size();
2451
2452 CUIRect Slot;
2453 LayersBox.HSplitTop(Cut: Map()->m_vSelectedLayers.size() * (RowHeight + 2.0f), pTop: &Slot, pBottom: &LayersBox);
2454 ScrollRegion.AddRect(Rect: Slot);
2455 }
2456
2457 CUIRect Slot, VisibleToggle;
2458 if(State.m_Operation == ELayerOperation::GROUP_DRAG)
2459 {
2460 if(g == Map()->m_SelectedGroup)
2461 {
2462 UnscrolledLayersBox.HSplitTop(Cut: RowHeight, pTop: &Slot, pBottom: &UnscrolledLayersBox);
2463 UnscrolledLayersBox.HSplitTop(Cut: 2.0f, pTop: nullptr, pBottom: &UnscrolledLayersBox);
2464 }
2465 else if(!DraggedPositionFound && Ui()->MouseY() < LayersBox.y + RowHeight * vButtonsPerGroup[g] / 2 + 3.0f)
2466 {
2467 DraggedPositionFound = true;
2468 GroupAfterDraggedLayer = g;
2469
2470 CUIRect TmpSlot;
2471 if(Map()->m_vpGroups[Map()->m_SelectedGroup]->m_Collapse)
2472 LayersBox.HSplitTop(Cut: RowHeight + 7.0f, pTop: &TmpSlot, pBottom: &LayersBox);
2473 else
2474 LayersBox.HSplitTop(Cut: vButtonsPerGroup[Map()->m_SelectedGroup] * (RowHeight + 2.0f) + 5.0f, pTop: &TmpSlot, pBottom: &LayersBox);
2475 ScrollRegion.AddRect(Rect: TmpSlot, ShouldScrollHere: false);
2476 }
2477 }
2478 if(State.m_Operation != ELayerOperation::GROUP_DRAG || g != Map()->m_SelectedGroup)
2479 {
2480 LayersBox.HSplitTop(Cut: RowHeight, pTop: &Slot, pBottom: &LayersBox);
2481
2482 CUIRect TmpRect;
2483 LayersBox.HSplitTop(Cut: 2.0f, pTop: &TmpRect, pBottom: &LayersBox);
2484 ScrollRegion.AddRect(Rect: TmpRect);
2485 }
2486
2487 if(ScrollRegion.AddRect(Rect: Slot))
2488 {
2489 Slot.VSplitLeft(Cut: 15.0f, pLeft: &VisibleToggle, pRight: &Slot);
2490
2491 const int MouseClick = DoButton_FontIcon(pId: &Map()->m_vpGroups[g]->m_Visible, pText: Map()->m_vpGroups[g]->m_Visible ? FontIcon::EYE : FontIcon::EYE_SLASH, Checked: Map()->m_vpGroups[g]->m_Collapse ? 1 : 0, pRect: &VisibleToggle, Flags: BUTTONFLAG_LEFT | BUTTONFLAG_RIGHT, pToolTip: "Left click to toggle visibility. Right click to show this group only.", Corners: IGraphics::CORNER_L, FontSize: 8.0f);
2492 if(MouseClick == 1)
2493 {
2494 Map()->m_vpGroups[g]->m_Visible = !Map()->m_vpGroups[g]->m_Visible;
2495 }
2496 else if(MouseClick == 2)
2497 {
2498 if(Input()->ShiftIsPressed())
2499 {
2500 if(g != Map()->m_SelectedGroup)
2501 Map()->SelectLayer(LayerIndex: 0, GroupIndex: g);
2502 }
2503
2504 int NumActive = 0;
2505 for(auto &Group : Map()->m_vpGroups)
2506 {
2507 if(Group == Map()->m_vpGroups[g])
2508 {
2509 Group->m_Visible = true;
2510 continue;
2511 }
2512
2513 if(Group->m_Visible)
2514 {
2515 Group->m_Visible = false;
2516 NumActive++;
2517 }
2518 }
2519 if(NumActive == 0)
2520 {
2521 for(auto &Group : Map()->m_vpGroups)
2522 {
2523 Group->m_Visible = true;
2524 }
2525 }
2526 }
2527
2528 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "#%d %s", g, Map()->m_vpGroups[g]->m_aName);
2529
2530 bool Clicked;
2531 bool Abrupted;
2532 if(int Result = DoButton_DraggableEx(pId: Map()->m_vpGroups[g].get(), pText: aBuf, Checked: g == Map()->m_SelectedGroup, pRect: &Slot, pClicked: &Clicked, pAbrupted: &Abrupted,
2533 Flags: BUTTONFLAG_LEFT | BUTTONFLAG_RIGHT, pToolTip: Map()->m_vpGroups[g]->m_Collapse ? "Select group. Shift+left click to select all layers. Double click to expand." : "Select group. Shift+left click to select all layers. Double click to collapse.", Corners: IGraphics::CORNER_R))
2534 {
2535 if(State.m_Operation == ELayerOperation::NONE)
2536 {
2537 State.m_InitialMouseY = Ui()->MouseY();
2538 State.m_InitialCutHeight = State.m_InitialMouseY - UnscrolledLayersBox.y;
2539 SetOperation(ELayerOperation::CLICK);
2540
2541 if(g != Map()->m_SelectedGroup)
2542 Map()->SelectLayer(LayerIndex: 0, GroupIndex: g);
2543 }
2544
2545 if(Abrupted)
2546 {
2547 SetOperation(ELayerOperation::NONE);
2548 }
2549
2550 if(State.m_Operation == ELayerOperation::CLICK && absolute(a: Ui()->MouseY() - State.m_InitialMouseY) > MinDragDistance)
2551 {
2552 StartDragGroup = true;
2553 State.m_pDraggedButton = Map()->m_vpGroups[g].get();
2554 }
2555
2556 if(State.m_Operation == ELayerOperation::CLICK && Clicked)
2557 {
2558 if(g != Map()->m_SelectedGroup)
2559 Map()->SelectLayer(LayerIndex: 0, GroupIndex: g);
2560
2561 if(Input()->ShiftIsPressed() && Map()->m_SelectedGroup == g)
2562 {
2563 Map()->m_vSelectedLayers.clear();
2564 for(size_t i = 0; i < Map()->m_vpGroups[g]->m_vpLayers.size(); i++)
2565 {
2566 Map()->AddSelectedLayer(LayerIndex: i);
2567 }
2568 }
2569
2570 if(Result == 2)
2571 {
2572 Ui()->DoPopupMenu(pId: &State.m_PopupGroupId, X: Ui()->MouseX(), Y: Ui()->MouseY(), Width: 145, Height: 256, pContext: this, pfnFunc: PopupGroup);
2573 }
2574
2575 if(!Map()->m_vpGroups[g]->m_vpLayers.empty() && Ui()->DoDoubleClickLogic(pId: Map()->m_vpGroups[g].get()))
2576 Map()->m_vpGroups[g]->m_Collapse ^= 1;
2577
2578 SetOperation(ELayerOperation::NONE);
2579 }
2580
2581 if(State.m_Operation == ELayerOperation::GROUP_DRAG && Clicked)
2582 MoveGroup = true;
2583 }
2584 else if(State.m_pDraggedButton == Map()->m_vpGroups[g].get())
2585 {
2586 SetOperation(ELayerOperation::NONE);
2587 }
2588 }
2589
2590 for(int i = 0; i < (int)Map()->m_vpGroups[g]->m_vpLayers.size(); i++)
2591 {
2592 if(Map()->m_vpGroups[g]->m_Collapse)
2593 continue;
2594
2595 bool IsLayerSelected = false;
2596 if(Map()->m_SelectedGroup == g)
2597 {
2598 for(const auto &Selected : Map()->m_vSelectedLayers)
2599 {
2600 if(Selected == i)
2601 {
2602 IsLayerSelected = true;
2603 break;
2604 }
2605 }
2606 }
2607
2608 if(State.m_Operation == ELayerOperation::GROUP_DRAG && g == Map()->m_SelectedGroup)
2609 {
2610 UnscrolledLayersBox.HSplitTop(Cut: RowHeight + 2.0f, pTop: &Slot, pBottom: &UnscrolledLayersBox);
2611 }
2612 else if(State.m_Operation == ELayerOperation::LAYER_DRAG)
2613 {
2614 if(IsLayerSelected)
2615 {
2616 UnscrolledLayersBox.HSplitTop(Cut: RowHeight + 2.0f, pTop: &Slot, pBottom: &UnscrolledLayersBox);
2617 }
2618 else
2619 {
2620 if(!DraggedPositionFound && Ui()->MouseY() < LayersBox.y + RowHeight / 2)
2621 {
2622 DraggedPositionFound = true;
2623 GroupAfterDraggedLayer = g + 1;
2624 LayerAfterDraggedLayer = i;
2625 for(size_t j = 0; j < Map()->m_vSelectedLayers.size(); j++)
2626 {
2627 LayersBox.HSplitTop(Cut: RowHeight + 2.0f, pTop: nullptr, pBottom: &LayersBox);
2628 ScrollRegion.AddRect(Rect: Slot);
2629 }
2630 }
2631 LayersBox.HSplitTop(Cut: RowHeight + 2.0f, pTop: &Slot, pBottom: &LayersBox);
2632 if(!ScrollRegion.AddRect(Rect: Slot, ShouldScrollHere: ScrollToSelection && IsLayerSelected))
2633 continue;
2634 }
2635 }
2636 else
2637 {
2638 LayersBox.HSplitTop(Cut: RowHeight + 2.0f, pTop: &Slot, pBottom: &LayersBox);
2639 if(!ScrollRegion.AddRect(Rect: Slot, ShouldScrollHere: ScrollToSelection && IsLayerSelected))
2640 continue;
2641 }
2642
2643 Slot.HSplitTop(Cut: RowHeight, pTop: &Slot, pBottom: nullptr);
2644
2645 CUIRect Button;
2646 Slot.VSplitLeft(Cut: 12.0f, pLeft: nullptr, pRight: &Slot);
2647 Slot.VSplitLeft(Cut: 15.0f, pLeft: &VisibleToggle, pRight: &Button);
2648
2649 const int MouseClick = DoButton_FontIcon(pId: &Map()->m_vpGroups[g]->m_vpLayers[i]->m_Visible, pText: Map()->m_vpGroups[g]->m_vpLayers[i]->m_Visible ? FontIcon::EYE : FontIcon::EYE_SLASH, Checked: 0, pRect: &VisibleToggle, Flags: BUTTONFLAG_LEFT | BUTTONFLAG_RIGHT, pToolTip: "Left click to toggle visibility. Right click to show only this layer within its group.", Corners: IGraphics::CORNER_L, FontSize: 8.0f);
2650 if(MouseClick == 1)
2651 {
2652 Map()->m_vpGroups[g]->m_vpLayers[i]->m_Visible = !Map()->m_vpGroups[g]->m_vpLayers[i]->m_Visible;
2653 }
2654 else if(MouseClick == 2)
2655 {
2656 if(Input()->ShiftIsPressed())
2657 {
2658 if(!IsLayerSelected)
2659 Map()->SelectLayer(LayerIndex: i, GroupIndex: g);
2660 }
2661
2662 int NumActive = 0;
2663 for(auto &Layer : Map()->m_vpGroups[g]->m_vpLayers)
2664 {
2665 if(Layer == Map()->m_vpGroups[g]->m_vpLayers[i])
2666 {
2667 Layer->m_Visible = true;
2668 continue;
2669 }
2670
2671 if(Layer->m_Visible)
2672 {
2673 Layer->m_Visible = false;
2674 NumActive++;
2675 }
2676 }
2677 if(NumActive == 0)
2678 {
2679 for(auto &Layer : Map()->m_vpGroups[g]->m_vpLayers)
2680 {
2681 Layer->m_Visible = true;
2682 }
2683 }
2684 }
2685
2686 if(Map()->m_vpGroups[g]->m_vpLayers[i]->m_aName[0])
2687 str_copy(dst&: aBuf, src: Map()->m_vpGroups[g]->m_vpLayers[i]->m_aName);
2688 else
2689 {
2690 if(Map()->m_vpGroups[g]->m_vpLayers[i]->m_Type == LAYERTYPE_TILES)
2691 {
2692 std::shared_ptr<CLayerTiles> pTiles = std::static_pointer_cast<CLayerTiles>(r: Map()->m_vpGroups[g]->m_vpLayers[i]);
2693 str_copy(dst&: aBuf, src: pTiles->m_Image >= 0 ? Map()->m_vpImages[pTiles->m_Image]->m_aName : "Tiles");
2694 }
2695 else if(Map()->m_vpGroups[g]->m_vpLayers[i]->m_Type == LAYERTYPE_QUADS)
2696 {
2697 std::shared_ptr<CLayerQuads> pQuads = std::static_pointer_cast<CLayerQuads>(r: Map()->m_vpGroups[g]->m_vpLayers[i]);
2698 str_copy(dst&: aBuf, src: pQuads->m_Image >= 0 ? Map()->m_vpImages[pQuads->m_Image]->m_aName : "Quads");
2699 }
2700 else if(Map()->m_vpGroups[g]->m_vpLayers[i]->m_Type == LAYERTYPE_SOUNDS)
2701 {
2702 std::shared_ptr<CLayerSounds> pSounds = std::static_pointer_cast<CLayerSounds>(r: Map()->m_vpGroups[g]->m_vpLayers[i]);
2703 str_copy(dst&: aBuf, src: pSounds->m_Sound >= 0 ? Map()->m_vpSounds[pSounds->m_Sound]->m_aName : "Sounds");
2704 }
2705 }
2706
2707 int Checked = IsLayerSelected ? 1 : 0;
2708 if(Map()->m_vpGroups[g]->m_vpLayers[i]->IsEntitiesLayer())
2709 {
2710 Checked += 6;
2711 }
2712
2713 bool Clicked;
2714 bool Abrupted;
2715 if(int Result = DoButton_DraggableEx(pId: Map()->m_vpGroups[g]->m_vpLayers[i].get(), pText: aBuf, Checked, pRect: &Button, pClicked: &Clicked, pAbrupted: &Abrupted,
2716 Flags: BUTTONFLAG_LEFT | BUTTONFLAG_RIGHT, pToolTip: "Select layer. Hold shift to select multiple.", Corners: IGraphics::CORNER_R))
2717 {
2718 if(State.m_Operation == ELayerOperation::NONE)
2719 {
2720 State.m_InitialMouseY = Ui()->MouseY();
2721 State.m_InitialCutHeight = State.m_InitialMouseY - UnscrolledLayersBox.y;
2722
2723 SetOperation(ELayerOperation::CLICK);
2724
2725 if(!Input()->ShiftIsPressed() && !IsLayerSelected)
2726 {
2727 Map()->SelectLayer(LayerIndex: i, GroupIndex: g);
2728 }
2729 }
2730
2731 if(Abrupted)
2732 {
2733 SetOperation(ELayerOperation::NONE);
2734 }
2735
2736 if(State.m_Operation == ELayerOperation::CLICK && absolute(a: Ui()->MouseY() - State.m_InitialMouseY) > MinDragDistance)
2737 {
2738 bool EntitiesLayerSelected = false;
2739 for(int k : Map()->m_vSelectedLayers)
2740 {
2741 if(Map()->m_vpGroups[Map()->m_SelectedGroup]->m_vpLayers[k]->IsEntitiesLayer())
2742 EntitiesLayerSelected = true;
2743 }
2744
2745 if(!EntitiesLayerSelected)
2746 StartDragLayer = true;
2747
2748 State.m_pDraggedButton = Map()->m_vpGroups[g]->m_vpLayers[i].get();
2749 }
2750
2751 if(State.m_Operation == ELayerOperation::CLICK && Clicked)
2752 {
2753 State.m_LayerPopupContext.m_pEditor = this;
2754 if(Result == 1)
2755 {
2756 if(Input()->ShiftIsPressed() && Map()->m_SelectedGroup == g)
2757 {
2758 auto Position = std::find(first: Map()->m_vSelectedLayers.begin(), last: Map()->m_vSelectedLayers.end(), val: i);
2759 if(Position != Map()->m_vSelectedLayers.end())
2760 Map()->m_vSelectedLayers.erase(position: Position);
2761 else
2762 Map()->AddSelectedLayer(LayerIndex: i);
2763 }
2764 else if(!Input()->ShiftIsPressed())
2765 {
2766 Map()->SelectLayer(LayerIndex: i, GroupIndex: g);
2767 }
2768 }
2769 else if(Result == 2)
2770 {
2771 State.m_LayerPopupContext.m_vpLayers.clear();
2772 State.m_LayerPopupContext.m_vLayerIndices.clear();
2773
2774 if(!IsLayerSelected)
2775 {
2776 Map()->SelectLayer(LayerIndex: i, GroupIndex: g);
2777 }
2778
2779 if(Map()->m_vSelectedLayers.size() > 1)
2780 {
2781 // move right clicked layer to first index to render correct popup
2782 if(Map()->m_vSelectedLayers[0] != i)
2783 {
2784 auto Position = std::find(first: Map()->m_vSelectedLayers.begin(), last: Map()->m_vSelectedLayers.end(), val: i);
2785 std::swap(a&: Map()->m_vSelectedLayers[0], b&: *Position);
2786 }
2787
2788 bool AllTile = true;
2789 for(size_t j = 0; AllTile && j < Map()->m_vSelectedLayers.size(); j++)
2790 {
2791 int LayerIndex = Map()->m_vSelectedLayers[j];
2792 if(Map()->m_vpGroups[Map()->m_SelectedGroup]->m_vpLayers[LayerIndex]->m_Type == LAYERTYPE_TILES)
2793 {
2794 State.m_LayerPopupContext.m_vpLayers.push_back(x: std::static_pointer_cast<CLayerTiles>(r: Map()->m_vpGroups[Map()->m_SelectedGroup]->m_vpLayers[Map()->m_vSelectedLayers[j]]));
2795 State.m_LayerPopupContext.m_vLayerIndices.push_back(x: LayerIndex);
2796 }
2797 else
2798 AllTile = false;
2799 }
2800
2801 // Don't allow editing if all selected layers are not tile layers
2802 if(!AllTile)
2803 {
2804 State.m_LayerPopupContext.m_vpLayers.clear();
2805 State.m_LayerPopupContext.m_vLayerIndices.clear();
2806 }
2807 }
2808
2809 Ui()->DoPopupMenu(pId: &State.m_LayerPopupContext, X: Ui()->MouseX(), Y: Ui()->MouseY(), Width: 150, Height: 300, pContext: &State.m_LayerPopupContext, pfnFunc: PopupLayer);
2810 }
2811
2812 SetOperation(ELayerOperation::NONE);
2813 }
2814
2815 if(State.m_Operation == ELayerOperation::LAYER_DRAG && Clicked)
2816 {
2817 MoveLayers = true;
2818 }
2819 }
2820 else if(State.m_pDraggedButton == Map()->m_vpGroups[g]->m_vpLayers[i].get())
2821 {
2822 SetOperation(ELayerOperation::NONE);
2823 }
2824 }
2825
2826 if(State.m_Operation != ELayerOperation::GROUP_DRAG || g != Map()->m_SelectedGroup)
2827 {
2828 LayersBox.HSplitTop(Cut: 5.0f, pTop: &Slot, pBottom: &LayersBox);
2829 ScrollRegion.AddRect(Rect: Slot);
2830 }
2831 }
2832
2833 if(!DraggedPositionFound && State.m_Operation == ELayerOperation::LAYER_DRAG)
2834 {
2835 GroupAfterDraggedLayer = Map()->m_vpGroups.size();
2836 LayerAfterDraggedLayer = Map()->m_vpGroups[GroupAfterDraggedLayer - 1]->m_vpLayers.size();
2837
2838 CUIRect TmpSlot;
2839 LayersBox.HSplitTop(Cut: Map()->m_vSelectedLayers.size() * (RowHeight + 2.0f), pTop: &TmpSlot, pBottom: &LayersBox);
2840 ScrollRegion.AddRect(Rect: TmpSlot);
2841 }
2842
2843 if(!DraggedPositionFound && State.m_Operation == ELayerOperation::GROUP_DRAG)
2844 {
2845 GroupAfterDraggedLayer = Map()->m_vpGroups.size();
2846
2847 CUIRect TmpSlot;
2848 if(Map()->m_vpGroups[Map()->m_SelectedGroup]->m_Collapse)
2849 LayersBox.HSplitTop(Cut: RowHeight + 7.0f, pTop: &TmpSlot, pBottom: &LayersBox);
2850 else
2851 LayersBox.HSplitTop(Cut: vButtonsPerGroup[Map()->m_SelectedGroup] * (RowHeight + 2.0f) + 5.0f, pTop: &TmpSlot, pBottom: &LayersBox);
2852 ScrollRegion.AddRect(Rect: TmpSlot, ShouldScrollHere: false);
2853 }
2854
2855 if(MoveLayers && 1 <= GroupAfterDraggedLayer && GroupAfterDraggedLayer <= (int)Map()->m_vpGroups.size())
2856 {
2857 std::vector<std::shared_ptr<CLayer>> &vpNewGroupLayers = Map()->m_vpGroups[GroupAfterDraggedLayer - 1]->m_vpLayers;
2858 if(0 <= LayerAfterDraggedLayer && LayerAfterDraggedLayer <= (int)vpNewGroupLayers.size())
2859 {
2860 std::vector<std::shared_ptr<CLayer>> vpSelectedLayers;
2861 std::vector<std::shared_ptr<CLayer>> &vpSelectedGroupLayers = Map()->m_vpGroups[Map()->m_SelectedGroup]->m_vpLayers;
2862 std::shared_ptr<CLayer> pNextLayer = nullptr;
2863 if(LayerAfterDraggedLayer < (int)vpNewGroupLayers.size())
2864 pNextLayer = vpNewGroupLayers[LayerAfterDraggedLayer];
2865
2866 std::sort(first: Map()->m_vSelectedLayers.begin(), last: Map()->m_vSelectedLayers.end(), comp: std::greater<>());
2867 for(int k : Map()->m_vSelectedLayers)
2868 {
2869 vpSelectedLayers.insert(position: vpSelectedLayers.begin(), x: vpSelectedGroupLayers[k]);
2870 }
2871 for(int k : Map()->m_vSelectedLayers)
2872 {
2873 vpSelectedGroupLayers.erase(position: vpSelectedGroupLayers.begin() + k);
2874 }
2875
2876 auto InsertPosition = std::find(first: vpNewGroupLayers.begin(), last: vpNewGroupLayers.end(), val: pNextLayer);
2877 int InsertPositionIndex = InsertPosition - vpNewGroupLayers.begin();
2878 vpNewGroupLayers.insert(position: InsertPosition, first: vpSelectedLayers.begin(), last: vpSelectedLayers.end());
2879
2880 int NumSelectedLayers = Map()->m_vSelectedLayers.size();
2881 Map()->m_vSelectedLayers.clear();
2882 for(int i = 0; i < NumSelectedLayers; i++)
2883 Map()->m_vSelectedLayers.push_back(x: InsertPositionIndex + i);
2884
2885 Map()->m_SelectedGroup = GroupAfterDraggedLayer - 1;
2886 Map()->OnModify();
2887 }
2888 }
2889
2890 if(MoveGroup && 0 <= GroupAfterDraggedLayer && GroupAfterDraggedLayer <= (int)Map()->m_vpGroups.size())
2891 {
2892 std::shared_ptr<CLayerGroup> pSelectedGroup = Map()->m_vpGroups[Map()->m_SelectedGroup];
2893 std::shared_ptr<CLayerGroup> pNextGroup = nullptr;
2894 if(GroupAfterDraggedLayer < (int)Map()->m_vpGroups.size())
2895 pNextGroup = Map()->m_vpGroups[GroupAfterDraggedLayer];
2896
2897 Map()->m_vpGroups.erase(position: Map()->m_vpGroups.begin() + Map()->m_SelectedGroup);
2898
2899 auto InsertPosition = std::find(first: Map()->m_vpGroups.begin(), last: Map()->m_vpGroups.end(), val: pNextGroup);
2900 Map()->m_vpGroups.insert(position: InsertPosition, x: pSelectedGroup);
2901
2902 auto Pos = std::find(first: Map()->m_vpGroups.begin(), last: Map()->m_vpGroups.end(), val: pSelectedGroup);
2903 Map()->m_SelectedGroup = Pos - Map()->m_vpGroups.begin();
2904
2905 Map()->OnModify();
2906 }
2907
2908 if(MoveLayers || MoveGroup)
2909 {
2910 SetOperation(ELayerOperation::NONE);
2911 }
2912 if(StartDragLayer)
2913 {
2914 SetOperation(ELayerOperation::LAYER_DRAG);
2915 State.m_InitialGroupIndex = Map()->m_SelectedGroup;
2916 State.m_vInitialLayerIndices = std::vector(Map()->m_vSelectedLayers);
2917 }
2918 if(StartDragGroup)
2919 {
2920 State.m_InitialGroupIndex = Map()->m_SelectedGroup;
2921 SetOperation(ELayerOperation::GROUP_DRAG);
2922 }
2923
2924 if(State.m_Operation == ELayerOperation::LAYER_DRAG || State.m_Operation == ELayerOperation::GROUP_DRAG)
2925 {
2926 if(State.m_pDraggedButton == nullptr)
2927 {
2928 SetOperation(ELayerOperation::NONE);
2929 }
2930 else
2931 {
2932 ScrollRegion.DoEdgeScrolling();
2933 Ui()->SetActiveItem(State.m_pDraggedButton);
2934 }
2935 }
2936
2937 if(Input()->KeyPress(Key: KEY_DOWN) && m_Dialog == DIALOG_NONE && !Ui()->IsPopupOpen() && CLineInput::GetActiveInput() == nullptr && State.m_Operation == ELayerOperation::NONE)
2938 {
2939 if(Input()->ShiftIsPressed())
2940 {
2941 if(Map()->m_vSelectedLayers[Map()->m_vSelectedLayers.size() - 1] < (int)Map()->m_vpGroups[Map()->m_SelectedGroup]->m_vpLayers.size() - 1)
2942 Map()->AddSelectedLayer(LayerIndex: Map()->m_vSelectedLayers[Map()->m_vSelectedLayers.size() - 1] + 1);
2943 }
2944 else
2945 {
2946 Map()->SelectNextLayer();
2947 }
2948 State.m_ScrollToSelectionNext = true;
2949 }
2950 if(Input()->KeyPress(Key: KEY_UP) && m_Dialog == DIALOG_NONE && !Ui()->IsPopupOpen() && CLineInput::GetActiveInput() == nullptr && State.m_Operation == ELayerOperation::NONE)
2951 {
2952 if(Input()->ShiftIsPressed())
2953 {
2954 if(Map()->m_vSelectedLayers[Map()->m_vSelectedLayers.size() - 1] > 0)
2955 Map()->AddSelectedLayer(LayerIndex: Map()->m_vSelectedLayers[Map()->m_vSelectedLayers.size() - 1] - 1);
2956 }
2957 else
2958 {
2959 Map()->SelectPreviousLayer();
2960 }
2961
2962 State.m_ScrollToSelectionNext = true;
2963 }
2964
2965 CUIRect AddGroupButton, CollapseAllButton;
2966 LayersBox.HSplitTop(Cut: RowHeight + 1.0f, pTop: &AddGroupButton, pBottom: &LayersBox);
2967 if(ScrollRegion.AddRect(Rect: AddGroupButton))
2968 {
2969 AddGroupButton.HSplitTop(Cut: RowHeight, pTop: &AddGroupButton, pBottom: nullptr);
2970 if(DoButton_Editor(pId: &State.m_AddGroupButtonId, pText: m_QuickActionAddGroup.Label(), Checked: 0, pRect: &AddGroupButton, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionAddGroup.Description()))
2971 {
2972 m_QuickActionAddGroup.Call();
2973 }
2974 }
2975
2976 LayersBox.HSplitTop(Cut: 5.0f, pTop: nullptr, pBottom: &LayersBox);
2977 LayersBox.HSplitTop(Cut: RowHeight + 1.0f, pTop: &CollapseAllButton, pBottom: &LayersBox);
2978 if(ScrollRegion.AddRect(Rect: CollapseAllButton))
2979 {
2980 size_t TotalCollapsed = 0;
2981 for(const auto &pGroup : Map()->m_vpGroups)
2982 {
2983 if(pGroup->m_vpLayers.empty() || pGroup->m_Collapse)
2984 {
2985 TotalCollapsed++;
2986 }
2987 }
2988
2989 const char *pActionText = TotalCollapsed == Map()->m_vpGroups.size() ? "Expand all" : "Collapse all";
2990
2991 CollapseAllButton.HSplitTop(Cut: RowHeight, pTop: &CollapseAllButton, pBottom: nullptr);
2992 if(DoButton_Editor(pId: &State.m_CollapseAllButtonId, pText: pActionText, Checked: 0, pRect: &CollapseAllButton, Flags: BUTTONFLAG_LEFT, pToolTip: "Expand or collapse all groups."))
2993 {
2994 for(const auto &pGroup : Map()->m_vpGroups)
2995 {
2996 if(TotalCollapsed == Map()->m_vpGroups.size())
2997 pGroup->m_Collapse = false;
2998 else if(!pGroup->m_vpLayers.empty())
2999 pGroup->m_Collapse = true;
3000 }
3001 }
3002 }
3003
3004 ScrollRegion.End();
3005
3006 if(State.m_Operation == ELayerOperation::NONE)
3007 {
3008 if(State.m_PreviousOperation == ELayerOperation::GROUP_DRAG)
3009 {
3010 State.m_PreviousOperation = ELayerOperation::NONE;
3011 Map()->m_EditorHistory.RecordAction(pAction: std::make_shared<CEditorActionEditGroupProp>(args: Map(), args&: Map()->m_SelectedGroup, args: EGroupProp::ORDER, args&: State.m_InitialGroupIndex, args&: Map()->m_SelectedGroup));
3012 }
3013 else if(State.m_PreviousOperation == ELayerOperation::LAYER_DRAG)
3014 {
3015 if(State.m_InitialGroupIndex != Map()->m_SelectedGroup)
3016 {
3017 Map()->m_EditorHistory.RecordAction(pAction: std::make_shared<CEditorActionEditLayersGroupAndOrder>(args: Map(), args&: State.m_InitialGroupIndex, args&: State.m_vInitialLayerIndices, args&: Map()->m_SelectedGroup, args&: Map()->m_vSelectedLayers));
3018 }
3019 else
3020 {
3021 std::vector<std::shared_ptr<IEditorAction>> vpActions;
3022 std::vector<int> vLayerIndices = Map()->m_vSelectedLayers;
3023 std::sort(first: vLayerIndices.begin(), last: vLayerIndices.end());
3024 std::sort(first: State.m_vInitialLayerIndices.begin(), last: State.m_vInitialLayerIndices.end());
3025 for(int k = 0; k < (int)vLayerIndices.size(); k++)
3026 {
3027 int LayerIndex = vLayerIndices[k];
3028 vpActions.push_back(x: std::make_shared<CEditorActionEditLayerProp>(args: Map(), args&: Map()->m_SelectedGroup, args&: LayerIndex, args: ELayerProp::ORDER, args&: State.m_vInitialLayerIndices[k], args&: LayerIndex));
3029 }
3030 Map()->m_EditorHistory.RecordAction(pAction: std::make_shared<CEditorActionBulk>(args: Map(), args&: vpActions, args: nullptr, args: true));
3031 }
3032 State.m_PreviousOperation = ELayerOperation::NONE;
3033 }
3034 }
3035}
3036
3037bool CEditor::ReplaceImage(const char *pFilename, int StorageType, bool CheckDuplicate)
3038{
3039 // check if we have that image already
3040 char aBuf[IO_MAX_PATH_LENGTH];
3041 fs_split_file_extension(filename: fs_filename(path: pFilename), name: aBuf, name_size: sizeof(aBuf));
3042 if(CheckDuplicate)
3043 {
3044 for(const auto &pImage : Map()->m_vpImages)
3045 {
3046 if(!str_comp(a: pImage->m_aName, b: aBuf))
3047 {
3048 ShowFileDialogError(pFormat: "Image named '%s' was already added.", pImage->m_aName);
3049 return false;
3050 }
3051 }
3052 }
3053
3054 CImageInfo ImgInfo;
3055 if(!Graphics()->LoadPng(Image&: ImgInfo, pFilename, StorageType))
3056 {
3057 ShowFileDialogError(pFormat: "Failed to load image from file '%s'.", pFilename);
3058 return false;
3059 }
3060
3061 std::shared_ptr<CEditorImage> pImg = Map()->SelectedImage();
3062 pImg->CEditorImage::Free();
3063 *pImg = std::move(ImgInfo);
3064 str_copy(dst&: pImg->m_aName, src: aBuf);
3065 pImg->m_External = IsVanillaImage(pImage: pImg->m_aName);
3066
3067 ConvertToRgba(Image&: *pImg);
3068 DilateImage(Image: *pImg);
3069
3070 pImg->m_Automapper.Load(pTileName: pImg->m_aName);
3071 int TextureLoadFlag = Graphics()->TextureLoadFlags();
3072 if(pImg->m_Width % 16 != 0 || pImg->m_Height % 16 != 0)
3073 TextureLoadFlag = 0;
3074 pImg->m_Texture = Graphics()->LoadTextureRaw(Image: *pImg, Flags: TextureLoadFlag, pTexName: pFilename);
3075
3076 Map()->SortImages();
3077 Map()->SelectImage(pImage: pImg);
3078 OnDialogClose();
3079 return true;
3080}
3081
3082bool CEditor::ReplaceImageCallback(const char *pFilename, int StorageType, void *pUser)
3083{
3084 return static_cast<CEditor *>(pUser)->ReplaceImage(pFilename, StorageType, CheckDuplicate: true);
3085}
3086
3087bool CEditor::AddImage(const char *pFilename, int StorageType, void *pUser)
3088{
3089 CEditor *pEditor = (CEditor *)pUser;
3090
3091 // check if we have that image already
3092 char aBuf[IO_MAX_PATH_LENGTH];
3093 fs_split_file_extension(filename: fs_filename(path: pFilename), name: aBuf, name_size: sizeof(aBuf));
3094 for(const auto &pImage : pEditor->Map()->m_vpImages)
3095 {
3096 if(!str_comp(a: pImage->m_aName, b: aBuf))
3097 {
3098 pEditor->ShowFileDialogError(pFormat: "Image named '%s' was already added.", pImage->m_aName);
3099 return false;
3100 }
3101 }
3102
3103 if(pEditor->Map()->m_vpImages.size() >= MAX_MAPIMAGES)
3104 {
3105 pEditor->m_PopupEventType = POPEVENT_IMAGE_MAX;
3106 pEditor->m_PopupEventActivated = true;
3107 return false;
3108 }
3109
3110 CImageInfo ImgInfo;
3111 if(!pEditor->Graphics()->LoadPng(Image&: ImgInfo, pFilename, StorageType))
3112 {
3113 pEditor->ShowFileDialogError(pFormat: "Failed to load image from file '%s'.", pFilename);
3114 return false;
3115 }
3116
3117 std::shared_ptr<CEditorImage> pImg = std::make_shared<CEditorImage>(args: pEditor->Map());
3118 *pImg = std::move(ImgInfo);
3119
3120 pImg->m_External = IsVanillaImage(pImage: aBuf);
3121
3122 ConvertToRgba(Image&: *pImg);
3123 DilateImage(Image: *pImg);
3124
3125 int TextureLoadFlag = pEditor->Graphics()->TextureLoadFlags();
3126 if(pImg->m_Width % 16 != 0 || pImg->m_Height % 16 != 0)
3127 TextureLoadFlag = 0;
3128 pImg->m_Texture = pEditor->Graphics()->LoadTextureRaw(Image: *pImg, Flags: TextureLoadFlag, pTexName: pFilename);
3129 str_copy(dst&: pImg->m_aName, src: aBuf);
3130 pImg->m_Automapper.Load(pTileName: pImg->m_aName);
3131 pEditor->Map()->m_vpImages.push_back(x: pImg);
3132 pEditor->Map()->SortImages();
3133 pEditor->Map()->SelectImage(pImage: pImg);
3134 pEditor->OnDialogClose();
3135 return true;
3136}
3137
3138bool CEditor::AddSound(const char *pFilename, int StorageType, void *pUser)
3139{
3140 CEditor *pEditor = (CEditor *)pUser;
3141
3142 // check if we have that sound already
3143 char aBuf[IO_MAX_PATH_LENGTH];
3144 fs_split_file_extension(filename: fs_filename(path: pFilename), name: aBuf, name_size: sizeof(aBuf));
3145 for(const auto &pSound : pEditor->Map()->m_vpSounds)
3146 {
3147 if(!str_comp(a: pSound->m_aName, b: aBuf))
3148 {
3149 pEditor->ShowFileDialogError(pFormat: "Sound named '%s' was already added.", pSound->m_aName);
3150 return false;
3151 }
3152 }
3153
3154 if(pEditor->Map()->m_vpSounds.size() >= MAX_MAPSOUNDS)
3155 {
3156 pEditor->m_PopupEventType = POPEVENT_SOUND_MAX;
3157 pEditor->m_PopupEventActivated = true;
3158 return false;
3159 }
3160
3161 // load external
3162 void *pData;
3163 unsigned DataSize;
3164 if(!pEditor->Storage()->ReadFile(pFilename, Type: StorageType, ppResult: &pData, pResultLen: &DataSize))
3165 {
3166 pEditor->ShowFileDialogError(pFormat: "Failed to open sound file '%s'.", pFilename);
3167 return false;
3168 }
3169
3170 // load sound
3171 const int SoundId = pEditor->Sound()->LoadOpusFromMem(pData, DataSize, ForceLoad: true, pContextName: pFilename);
3172 if(SoundId == -1)
3173 {
3174 free(ptr: pData);
3175 pEditor->ShowFileDialogError(pFormat: "Failed to load sound from file '%s'.", pFilename);
3176 return false;
3177 }
3178
3179 // add sound
3180 std::shared_ptr<CEditorSound> pSound = std::make_shared<CEditorSound>(args: pEditor->Map());
3181 pSound->m_SoundId = SoundId;
3182 pSound->m_DataSize = DataSize;
3183 pSound->m_pData = pData;
3184 str_copy(dst&: pSound->m_aName, src: aBuf);
3185 pEditor->Map()->m_vpSounds.push_back(x: pSound);
3186
3187 pEditor->Map()->SelectSound(pSound);
3188 pEditor->OnDialogClose();
3189 return true;
3190}
3191
3192bool CEditor::ReplaceSound(const char *pFilename, int StorageType, bool CheckDuplicate)
3193{
3194 // check if we have that sound already
3195 char aBuf[IO_MAX_PATH_LENGTH];
3196 fs_split_file_extension(filename: fs_filename(path: pFilename), name: aBuf, name_size: sizeof(aBuf));
3197 if(CheckDuplicate)
3198 {
3199 for(const auto &pSound : Map()->m_vpSounds)
3200 {
3201 if(!str_comp(a: pSound->m_aName, b: aBuf))
3202 {
3203 ShowFileDialogError(pFormat: "Sound named '%s' was already added.", pSound->m_aName);
3204 return false;
3205 }
3206 }
3207 }
3208
3209 // load external
3210 void *pData;
3211 unsigned DataSize;
3212 if(!Storage()->ReadFile(pFilename, Type: StorageType, ppResult: &pData, pResultLen: &DataSize))
3213 {
3214 ShowFileDialogError(pFormat: "Failed to open sound file '%s'.", pFilename);
3215 return false;
3216 }
3217
3218 // load sound
3219 const int SoundId = Sound()->LoadOpusFromMem(pData, DataSize, ForceLoad: true, pContextName: pFilename);
3220 if(SoundId == -1)
3221 {
3222 free(ptr: pData);
3223 ShowFileDialogError(pFormat: "Failed to load sound from file '%s'.", pFilename);
3224 return false;
3225 }
3226
3227 std::shared_ptr<CEditorSound> pSound = Map()->SelectedSound();
3228
3229 if(m_ToolbarPreviewSound == pSound->m_SoundId)
3230 {
3231 m_ToolbarPreviewSound = SoundId;
3232 }
3233
3234 // unload sample
3235 Sound()->UnloadSample(SampleId: pSound->m_SoundId);
3236 free(ptr: pSound->m_pData);
3237
3238 // replace sound
3239 str_copy(dst&: pSound->m_aName, src: aBuf);
3240 pSound->m_SoundId = SoundId;
3241 pSound->m_pData = pData;
3242 pSound->m_DataSize = DataSize;
3243
3244 Map()->SelectSound(pSound);
3245 OnDialogClose();
3246 return true;
3247}
3248
3249bool CEditor::ReplaceSoundCallback(const char *pFilename, int StorageType, void *pUser)
3250{
3251 return static_cast<CEditor *>(pUser)->ReplaceSound(pFilename, StorageType, CheckDuplicate: true);
3252}
3253
3254void CEditor::RenderImagesList(CUIRect ToolBox)
3255{
3256 const float RowHeight = 12.0f;
3257
3258 CScrollRegion &ScrollRegion = Map()->m_EditorUiElements.m_ImagesScrollRegion;
3259 CScrollRegionParams ScrollParams;
3260 ScrollParams.m_ScrollbarThickness = 10.0f;
3261 ScrollParams.m_ScrollbarMargin = 3.0f;
3262 ScrollParams.m_ScrollUnit = RowHeight * 5;
3263 ScrollRegion.Begin(pClipRect: &ToolBox, pParams: &ScrollParams);
3264
3265 bool ScrollToSelection = false;
3266 if(m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && !Map()->m_vpImages.empty())
3267 {
3268 if(Input()->KeyPress(Key: KEY_DOWN))
3269 {
3270 const int OldImage = Map()->m_SelectedImage;
3271 Map()->SelectNextImage();
3272 ScrollToSelection = OldImage != Map()->m_SelectedImage;
3273 }
3274 else if(Input()->KeyPress(Key: KEY_UP))
3275 {
3276 const int OldImage = Map()->m_SelectedImage;
3277 Map()->SelectPreviousImage();
3278 ScrollToSelection = OldImage != Map()->m_SelectedImage;
3279 }
3280 }
3281
3282 for(int e = 0; e < 2; e++) // two passes, first embedded, then external
3283 {
3284 CUIRect Slot;
3285 ToolBox.HSplitTop(Cut: RowHeight + 3.0f, pTop: &Slot, pBottom: &ToolBox);
3286 if(ScrollRegion.AddRect(Rect: Slot))
3287 Ui()->DoLabel(pRect: &Slot, pText: e == 0 ? "Embedded" : "External", Size: 12.0f, Align: TEXTALIGN_MC);
3288
3289 for(int i = 0; i < (int)Map()->m_vpImages.size(); i++)
3290 {
3291 if((e && !Map()->m_vpImages[i]->m_External) ||
3292 (!e && Map()->m_vpImages[i]->m_External))
3293 {
3294 continue;
3295 }
3296
3297 ToolBox.HSplitTop(Cut: RowHeight + 2.0f, pTop: &Slot, pBottom: &ToolBox);
3298 int Selected = Map()->m_SelectedImage == i;
3299 if(!ScrollRegion.AddRect(Rect: Slot, ShouldScrollHere: Selected && ScrollToSelection))
3300 continue;
3301 Slot.HSplitTop(Cut: RowHeight, pTop: &Slot, pBottom: nullptr);
3302
3303 const bool ImageUsed = std::any_of(first: Map()->m_vpGroups.cbegin(), last: Map()->m_vpGroups.cend(), pred: [i](const auto &pGroup) {
3304 return std::any_of(pGroup->m_vpLayers.cbegin(), pGroup->m_vpLayers.cend(), [i](const auto &pLayer) {
3305 if(pLayer->m_Type == LAYERTYPE_QUADS)
3306 return std::static_pointer_cast<CLayerQuads>(pLayer)->m_Image == i;
3307 else if(pLayer->m_Type == LAYERTYPE_TILES)
3308 return std::static_pointer_cast<CLayerTiles>(pLayer)->m_Image == i;
3309 return false;
3310 });
3311 });
3312
3313 if(!ImageUsed)
3314 Selected += 2; // Image is unused
3315
3316 if(Selected < 2 && e == 1)
3317 {
3318 if(!IsVanillaImage(pImage: Map()->m_vpImages[i]->m_aName))
3319 {
3320 Selected += 4; // Image should be embedded
3321 }
3322 }
3323
3324 if(int Result = DoButton_Ex(pId: &Map()->m_vpImages[i], pText: Map()->m_vpImages[i]->m_aName, Checked: Selected, pRect: &Slot,
3325 Flags: BUTTONFLAG_LEFT | BUTTONFLAG_RIGHT, pToolTip: "Select image.", Corners: IGraphics::CORNER_ALL))
3326 {
3327 Map()->m_SelectedImage = i;
3328
3329 if(Result == 2)
3330 {
3331 const int Height = Map()->SelectedImage()->m_External ? 73 : 107;
3332 static SPopupMenuId s_PopupImageId;
3333 Ui()->DoPopupMenu(pId: &s_PopupImageId, X: Ui()->MouseX(), Y: Ui()->MouseY(), Width: 140, Height, pContext: this, pfnFunc: PopupImage);
3334 }
3335 }
3336 }
3337
3338 // separator
3339 ToolBox.HSplitTop(Cut: 5.0f, pTop: &Slot, pBottom: &ToolBox);
3340 if(ScrollRegion.AddRect(Rect: Slot))
3341 {
3342 IGraphics::CLineItem LineItem(Slot.x, Slot.y + Slot.h / 2, Slot.x + Slot.w, Slot.y + Slot.h / 2);
3343 Graphics()->TextureClear();
3344 Graphics()->LinesBegin();
3345 Graphics()->LinesDraw(pArray: &LineItem, Num: 1);
3346 Graphics()->LinesEnd();
3347 }
3348 }
3349
3350 // new image
3351 static int s_AddImageButton = 0;
3352 CUIRect AddImageButton;
3353 ToolBox.HSplitTop(Cut: 5.0f + RowHeight + 1.0f, pTop: &AddImageButton, pBottom: &ToolBox);
3354 if(ScrollRegion.AddRect(Rect: AddImageButton))
3355 {
3356 AddImageButton.HSplitTop(Cut: 5.0f, pTop: nullptr, pBottom: &AddImageButton);
3357 AddImageButton.HSplitTop(Cut: RowHeight, pTop: &AddImageButton, pBottom: nullptr);
3358 if(DoButton_Editor(pId: &s_AddImageButton, pText: m_QuickActionAddImage.Label(), Checked: 0, pRect: &AddImageButton, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionAddImage.Description()))
3359 m_QuickActionAddImage.Call();
3360 }
3361 ScrollRegion.End();
3362}
3363
3364void CEditor::RenderSelectedImage(CUIRect View) const
3365{
3366 std::shared_ptr<CEditorImage> pSelectedImage = Map()->SelectedImage();
3367 if(pSelectedImage == nullptr)
3368 return;
3369
3370 View.Margin(Cut: 10.0f, pOtherRect: &View);
3371 if(View.h < View.w)
3372 View.w = View.h;
3373 else
3374 View.h = View.w;
3375 float Max = std::max(a: pSelectedImage->m_Width, b: pSelectedImage->m_Height);
3376 View.w *= pSelectedImage->m_Width / Max;
3377 View.h *= pSelectedImage->m_Height / Max;
3378 Graphics()->TextureSet(Texture: pSelectedImage->m_Texture);
3379 Graphics()->WrapClamp();
3380 Graphics()->QuadsBegin();
3381 IGraphics::CQuadItem QuadItem(View.x, View.y, View.w, View.h);
3382 Graphics()->QuadsDrawTL(pArray: &QuadItem, Num: 1);
3383 Graphics()->QuadsEnd();
3384 Graphics()->WrapNormal();
3385}
3386
3387void CEditor::RenderSounds(CUIRect ToolBox)
3388{
3389 const float RowHeight = 12.0f;
3390
3391 CScrollRegion &ScrollRegion = Map()->m_EditorUiElements.m_SoundsScrollRegion;
3392 CScrollRegionParams ScrollParams;
3393 ScrollParams.m_ScrollbarThickness = 10.0f;
3394 ScrollParams.m_ScrollbarMargin = 3.0f;
3395 ScrollParams.m_ScrollUnit = RowHeight * 5;
3396 ScrollRegion.Begin(pClipRect: &ToolBox, pParams: &ScrollParams);
3397
3398 bool ScrollToSelection = false;
3399 if(m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && !Map()->m_vpSounds.empty())
3400 {
3401 if(Input()->KeyPress(Key: KEY_DOWN))
3402 {
3403 Map()->SelectNextSound();
3404 ScrollToSelection = true;
3405 }
3406 else if(Input()->KeyPress(Key: KEY_UP))
3407 {
3408 Map()->SelectPreviousSound();
3409 ScrollToSelection = true;
3410 }
3411 }
3412
3413 CUIRect Slot;
3414 ToolBox.HSplitTop(Cut: RowHeight + 3.0f, pTop: &Slot, pBottom: &ToolBox);
3415 if(ScrollRegion.AddRect(Rect: Slot))
3416 Ui()->DoLabel(pRect: &Slot, pText: "Embedded", Size: 12.0f, Align: TEXTALIGN_MC);
3417
3418 for(int i = 0; i < (int)Map()->m_vpSounds.size(); i++)
3419 {
3420 ToolBox.HSplitTop(Cut: RowHeight + 2.0f, pTop: &Slot, pBottom: &ToolBox);
3421 int Selected = Map()->m_SelectedSound == i;
3422 if(!ScrollRegion.AddRect(Rect: Slot, ShouldScrollHere: Selected && ScrollToSelection))
3423 continue;
3424 Slot.HSplitTop(Cut: RowHeight, pTop: &Slot, pBottom: nullptr);
3425
3426 const bool SoundUsed = std::any_of(first: Map()->m_vpGroups.cbegin(), last: Map()->m_vpGroups.cend(), pred: [i](const auto &pGroup) {
3427 return std::any_of(pGroup->m_vpLayers.cbegin(), pGroup->m_vpLayers.cend(), [i](const auto &pLayer) {
3428 if(pLayer->m_Type == LAYERTYPE_SOUNDS)
3429 return std::static_pointer_cast<CLayerSounds>(pLayer)->m_Sound == i;
3430 return false;
3431 });
3432 });
3433
3434 if(!SoundUsed)
3435 Selected += 2; // Sound is unused
3436
3437 if(int Result = DoButton_Ex(pId: &Map()->m_vpSounds[i], pText: Map()->m_vpSounds[i]->m_aName, Checked: Selected, pRect: &Slot,
3438 Flags: BUTTONFLAG_LEFT | BUTTONFLAG_RIGHT, pToolTip: "Select sound.", Corners: IGraphics::CORNER_ALL))
3439 {
3440 Map()->m_SelectedSound = i;
3441
3442 if(Result == 2)
3443 {
3444 static SPopupMenuId s_PopupSoundId;
3445 Ui()->DoPopupMenu(pId: &s_PopupSoundId, X: Ui()->MouseX(), Y: Ui()->MouseY(), Width: 140, Height: 90, pContext: this, pfnFunc: PopupSound);
3446 }
3447 }
3448 }
3449
3450 // separator
3451 ToolBox.HSplitTop(Cut: 5.0f, pTop: &Slot, pBottom: &ToolBox);
3452 if(ScrollRegion.AddRect(Rect: Slot))
3453 {
3454 IGraphics::CLineItem LineItem(Slot.x, Slot.y + Slot.h / 2, Slot.x + Slot.w, Slot.y + Slot.h / 2);
3455 Graphics()->TextureClear();
3456 Graphics()->LinesBegin();
3457 Graphics()->LinesDraw(pArray: &LineItem, Num: 1);
3458 Graphics()->LinesEnd();
3459 }
3460
3461 // new sound
3462 static int s_AddSoundButton = 0;
3463 CUIRect AddSoundButton;
3464 ToolBox.HSplitTop(Cut: 5.0f + RowHeight + 1.0f, pTop: &AddSoundButton, pBottom: &ToolBox);
3465 if(ScrollRegion.AddRect(Rect: AddSoundButton))
3466 {
3467 AddSoundButton.HSplitTop(Cut: 5.0f, pTop: nullptr, pBottom: &AddSoundButton);
3468 AddSoundButton.HSplitTop(Cut: RowHeight, pTop: &AddSoundButton, pBottom: nullptr);
3469 if(DoButton_Editor(pId: &s_AddSoundButton, pText: "Add sound", Checked: 0, pRect: &AddSoundButton, Flags: BUTTONFLAG_LEFT, pToolTip: "Load a new sound to use in the map."))
3470 m_FileBrowser.ShowFileDialog(StorageType: IStorage::TYPE_ALL, FileType: CFileBrowser::EFileType::SOUND, pTitle: "Add sound", pButtonText: "Add", pInitialPath: "mapres", pInitialFilename: "", pfnOpenCallback: AddSound, pOpenCallbackUser: this);
3471 }
3472 ScrollRegion.End();
3473}
3474
3475bool CEditor::CStringKeyComparator::operator()(const char *pLhs, const char *pRhs) const
3476{
3477 return str_comp(a: pLhs, b: pRhs) < 0;
3478}
3479
3480void CEditor::ShowFileDialogError(const char *pFormat, ...)
3481{
3482 char aMessage[1024];
3483 va_list VarArgs;
3484 va_start(VarArgs, pFormat);
3485 str_format_v(buffer: aMessage, buffer_size: sizeof(aMessage), format: pFormat, args: VarArgs);
3486 va_end(VarArgs);
3487
3488 auto ContextIterator = m_PopupMessageContexts.find(x: aMessage);
3489 CUi::SMessagePopupContext *pContext;
3490 if(ContextIterator != m_PopupMessageContexts.end())
3491 {
3492 pContext = ContextIterator->second;
3493 Ui()->ClosePopupMenu(pId: pContext);
3494 }
3495 else
3496 {
3497 pContext = new CUi::SMessagePopupContext();
3498 pContext->ErrorColor();
3499 str_copy(dst&: pContext->m_aMessage, src: aMessage);
3500 m_PopupMessageContexts[pContext->m_aMessage] = pContext;
3501 }
3502 Ui()->ShowPopupMessage(X: Ui()->MouseX(), Y: Ui()->MouseY(), pContext);
3503}
3504
3505void CEditor::RenderModebar(CUIRect View)
3506{
3507 CUIRect Mentions, IngameMoved, ModeButtons, ModeButton;
3508 View.HSplitTop(Cut: 12.0f, pTop: &Mentions, pBottom: &View);
3509 View.HSplitTop(Cut: 12.0f, pTop: &IngameMoved, pBottom: &View);
3510 View.HSplitBottom(Cut: 22.0f, pTop: nullptr, pBottom: &ModeButtons);
3511 const float Width = m_ToolBoxWidth - 5.0f;
3512 ModeButtons.VSplitLeft(Cut: Width, pLeft: &ModeButtons, pRight: nullptr);
3513 const float ButtonWidth = Width / 3;
3514
3515 // mentions
3516 if(m_Mentions)
3517 {
3518 char aBuf[64];
3519 if(m_Mentions == 1)
3520 str_copy(dst&: aBuf, src: Localize(pStr: "1 new mention"));
3521 else if(m_Mentions <= 9)
3522 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: Localize(pStr: "%d new mentions"), m_Mentions);
3523 else
3524 str_copy(dst&: aBuf, src: Localize(pStr: "9+ new mentions"));
3525
3526 TextRender()->TextColor(Color: ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f));
3527 Ui()->DoLabel(pRect: &Mentions, pText: aBuf, Size: 10.0f, Align: TEXTALIGN_MC);
3528 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
3529 }
3530
3531 // ingame moved warning
3532 if(m_IngameMoved)
3533 {
3534 TextRender()->TextColor(Color: ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f));
3535 Ui()->DoLabel(pRect: &IngameMoved, pText: Localize(pStr: "Moved ingame"), Size: 10.0f, Align: TEXTALIGN_MC);
3536 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
3537 }
3538
3539 // mode buttons
3540 {
3541 ModeButtons.VSplitLeft(Cut: ButtonWidth, pLeft: &ModeButton, pRight: &ModeButtons);
3542 static int s_LayersButton = 0;
3543 if(DoButton_FontIcon(pId: &s_LayersButton, pText: FontIcon::LAYER_GROUP, Checked: m_Mode == MODE_LAYERS, pRect: &ModeButton, Flags: BUTTONFLAG_LEFT, pToolTip: "Go to layers management.", Corners: IGraphics::CORNER_L))
3544 {
3545 m_Mode = MODE_LAYERS;
3546 }
3547
3548 ModeButtons.VSplitLeft(Cut: ButtonWidth, pLeft: &ModeButton, pRight: &ModeButtons);
3549 static int s_ImagesButton = 0;
3550 if(DoButton_FontIcon(pId: &s_ImagesButton, pText: FontIcon::IMAGE, Checked: m_Mode == MODE_IMAGES, pRect: &ModeButton, Flags: BUTTONFLAG_LEFT, pToolTip: "Go to images management.", Corners: IGraphics::CORNER_NONE))
3551 {
3552 m_Mode = MODE_IMAGES;
3553 }
3554
3555 ModeButtons.VSplitLeft(Cut: ButtonWidth, pLeft: &ModeButton, pRight: &ModeButtons);
3556 static int s_SoundsButton = 0;
3557 if(DoButton_FontIcon(pId: &s_SoundsButton, pText: FontIcon::MUSIC, Checked: m_Mode == MODE_SOUNDS, pRect: &ModeButton, Flags: BUTTONFLAG_LEFT, pToolTip: "Go to sounds management.", Corners: IGraphics::CORNER_R))
3558 {
3559 m_Mode = MODE_SOUNDS;
3560 }
3561
3562 if(Input()->KeyPress(Key: KEY_LEFT) && m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr)
3563 {
3564 m_Mode = (m_Mode + NUM_MODES - 1) % NUM_MODES;
3565 }
3566 else if(Input()->KeyPress(Key: KEY_RIGHT) && m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr)
3567 {
3568 m_Mode = (m_Mode + 1) % NUM_MODES;
3569 }
3570 }
3571}
3572
3573void CEditor::RenderStatusbar(CUIRect View, CUIRect *pTooltipRect)
3574{
3575 CUIRect Button;
3576 View.VSplitRight(Cut: 100.0f, pLeft: &View, pRight: &Button);
3577 if(DoButton_Editor(pId: &m_QuickActionEnvelopes, pText: m_QuickActionEnvelopes.Label(), Checked: m_QuickActionEnvelopes.Color(), pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionEnvelopes.Description()))
3578 {
3579 m_QuickActionEnvelopes.Call();
3580 }
3581
3582 View.VSplitRight(Cut: 10.0f, pLeft: &View, pRight: nullptr);
3583 View.VSplitRight(Cut: 100.0f, pLeft: &View, pRight: &Button);
3584 if(DoButton_Editor(pId: &m_QuickActionServerSettings, pText: m_QuickActionServerSettings.Label(), Checked: m_QuickActionServerSettings.Color(), pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionServerSettings.Description()))
3585 {
3586 m_QuickActionServerSettings.Call();
3587 }
3588
3589 View.VSplitRight(Cut: 10.0f, pLeft: &View, pRight: nullptr);
3590 View.VSplitRight(Cut: 100.0f, pLeft: &View, pRight: &Button);
3591 if(DoButton_Editor(pId: &m_QuickActionHistory, pText: m_QuickActionHistory.Label(), Checked: m_QuickActionHistory.Color(), pRect: &Button, Flags: BUTTONFLAG_LEFT, pToolTip: m_QuickActionHistory.Description()))
3592 {
3593 m_QuickActionHistory.Call();
3594 }
3595
3596 View.VSplitRight(Cut: 10.0f, pLeft: pTooltipRect, pRight: nullptr);
3597}
3598
3599void CEditor::RenderTooltip(CUIRect TooltipRect)
3600{
3601 if(str_comp(a: m_aTooltip, b: "") == 0)
3602 return;
3603
3604 char aBuf[256];
3605 if(m_pUiGotContext && m_pUiGotContext == Ui()->HotItem())
3606 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s Right click for context menu.", m_aTooltip);
3607 else
3608 str_copy(dst&: aBuf, src: m_aTooltip);
3609
3610 SLabelProperties Props;
3611 Props.m_MaxWidth = TooltipRect.w;
3612 Props.m_EllipsisAtEnd = true;
3613 Ui()->DoLabel(pRect: &TooltipRect, pText: aBuf, Size: 10.0f, Align: TEXTALIGN_ML, LabelProps: Props);
3614}
3615
3616void CEditor::DoEditorDragBar(CUIRect View, CUIRect *pDragBar, EDragSide Side, float *pValue, float MinValue, float MaxValue)
3617{
3618 enum EDragOperation
3619 {
3620 OP_NONE,
3621 OP_DRAGGING,
3622 OP_CLICKED
3623 };
3624 static EDragOperation s_Operation = OP_NONE;
3625 static float s_InitialMouseY = 0.0f;
3626 static float s_InitialMouseOffsetY = 0.0f;
3627 static float s_InitialMouseX = 0.0f;
3628 static float s_InitialMouseOffsetX = 0.0f;
3629
3630 bool IsVertical = Side == EDragSide::TOP || Side == EDragSide::BOTTOM;
3631
3632 if(Ui()->MouseInside(pRect: pDragBar) && Ui()->HotItem() == pDragBar)
3633 m_CursorType = IsVertical ? CURSOR_RESIZE_V : CURSOR_RESIZE_H;
3634
3635 bool Clicked;
3636 bool Abrupted;
3637 if(int Result = DoButton_DraggableEx(pId: pDragBar, pText: "", Checked: 8, pRect: pDragBar, pClicked: &Clicked, pAbrupted: &Abrupted, Flags: 0, pToolTip: "Change the size of the editor by dragging."))
3638 {
3639 if(s_Operation == OP_NONE && Result == 1)
3640 {
3641 s_InitialMouseY = Ui()->MouseY();
3642 s_InitialMouseOffsetY = Ui()->MouseY() - pDragBar->y;
3643 s_InitialMouseX = Ui()->MouseX();
3644 s_InitialMouseOffsetX = Ui()->MouseX() - pDragBar->x;
3645 s_Operation = OP_CLICKED;
3646 }
3647
3648 if(Clicked || Abrupted)
3649 s_Operation = OP_NONE;
3650
3651 if(s_Operation == OP_CLICKED && absolute(a: IsVertical ? Ui()->MouseY() - s_InitialMouseY : Ui()->MouseX() - s_InitialMouseX) > 5.0f)
3652 s_Operation = OP_DRAGGING;
3653
3654 if(s_Operation == OP_DRAGGING)
3655 {
3656 if(Side == EDragSide::TOP)
3657 *pValue = std::clamp(val: s_InitialMouseOffsetY + View.y + View.h - Ui()->MouseY(), lo: MinValue, hi: MaxValue);
3658 else if(Side == EDragSide::RIGHT)
3659 *pValue = std::clamp(val: Ui()->MouseX() - s_InitialMouseOffsetX - View.x + pDragBar->w, lo: MinValue, hi: MaxValue);
3660 else if(Side == EDragSide::BOTTOM)
3661 *pValue = std::clamp(val: Ui()->MouseY() - s_InitialMouseOffsetY - View.y + pDragBar->h, lo: MinValue, hi: MaxValue);
3662 else if(Side == EDragSide::LEFT)
3663 *pValue = std::clamp(val: s_InitialMouseOffsetX + View.x + View.w - Ui()->MouseX(), lo: MinValue, hi: MaxValue);
3664
3665 m_CursorType = IsVertical ? CURSOR_RESIZE_V : CURSOR_RESIZE_H;
3666 }
3667 }
3668}
3669
3670void CEditor::RenderMenubar(CUIRect MenuBar)
3671{
3672 SPopupMenuProperties PopupProperties;
3673 PopupProperties.m_Corners = IGraphics::CORNER_R | IGraphics::CORNER_B;
3674
3675 CUIRect FileButton;
3676 static int s_FileButton = 0;
3677 MenuBar.VSplitLeft(Cut: 60.0f, pLeft: &FileButton, pRight: &MenuBar);
3678 if(DoButton_Ex(pId: &s_FileButton, pText: "File", Checked: 0, pRect: &FileButton, Flags: BUTTONFLAG_LEFT, pToolTip: nullptr, Corners: IGraphics::CORNER_T, FontSize: EditorFontSizes::MENU, Align: TEXTALIGN_ML))
3679 {
3680 static SPopupMenuId s_PopupMenuFileId;
3681 Ui()->DoPopupMenu(pId: &s_PopupMenuFileId, X: FileButton.x, Y: FileButton.y + FileButton.h - 1.0f, Width: 120.0f, Height: 210.0f, pContext: this, pfnFunc: PopupMenuFile, Props: PopupProperties);
3682 }
3683
3684 MenuBar.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &MenuBar);
3685
3686 CUIRect ToolsButton;
3687 static int s_ToolsButton = 0;
3688 MenuBar.VSplitLeft(Cut: 60.0f, pLeft: &ToolsButton, pRight: &MenuBar);
3689 if(DoButton_Ex(pId: &s_ToolsButton, pText: "Tools", Checked: 0, pRect: &ToolsButton, Flags: BUTTONFLAG_LEFT, pToolTip: nullptr, Corners: IGraphics::CORNER_T, FontSize: EditorFontSizes::MENU, Align: TEXTALIGN_ML))
3690 {
3691 static SPopupMenuId s_PopupMenuToolsId;
3692 Ui()->DoPopupMenu(pId: &s_PopupMenuToolsId, X: ToolsButton.x, Y: ToolsButton.y + ToolsButton.h - 1.0f, Width: 200.0f, Height: 78.0f, pContext: this, pfnFunc: PopupMenuTools, Props: PopupProperties);
3693 }
3694
3695 MenuBar.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &MenuBar);
3696
3697 CUIRect SettingsButton;
3698 static int s_SettingsButton = 0;
3699 MenuBar.VSplitLeft(Cut: 60.0f, pLeft: &SettingsButton, pRight: &MenuBar);
3700 if(DoButton_Ex(pId: &s_SettingsButton, pText: "Settings", Checked: 0, pRect: &SettingsButton, Flags: BUTTONFLAG_LEFT, pToolTip: nullptr, Corners: IGraphics::CORNER_T, FontSize: EditorFontSizes::MENU, Align: TEXTALIGN_ML))
3701 {
3702 static SPopupMenuId s_PopupMenuSettingsId;
3703 Ui()->DoPopupMenu(pId: &s_PopupMenuSettingsId, X: SettingsButton.x, Y: SettingsButton.y + SettingsButton.h - 1.0f, Width: 280.0f, Height: 148.0f, pContext: this, pfnFunc: PopupMenuSettings, Props: PopupProperties);
3704 }
3705
3706 CUIRect Info, Help, Close;
3707 MenuBar.VSplitLeft(Cut: 5.0f, pLeft: nullptr, pRight: &MenuBar);
3708 MenuBar.VSplitRight(Cut: 15.0f, pLeft: &MenuBar, pRight: &Close);
3709 MenuBar.VSplitRight(Cut: 5.0f, pLeft: &MenuBar, pRight: nullptr);
3710 MenuBar.VSplitRight(Cut: 15.0f, pLeft: &MenuBar, pRight: &Help);
3711 MenuBar.VSplitRight(Cut: 5.0f, pLeft: &Info, pRight: nullptr);
3712
3713 char aTimeStr[6];
3714 str_timestamp_format(buffer: aTimeStr, buffer_size: sizeof(aTimeStr), format: "%H:%M");
3715
3716 char aBuf[256];
3717 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "X: %.1f, Y: %.1f, Z: %.1f, T: %.1f, A: %.1f, G: %i %s", MapView()->MouseWorldPos().x / 32.0f, MapView()->MouseWorldPos().y / 32.0f, MapView()->Zoom()->GetValue(), Map()->m_EnvelopeEvaluator.m_AnimateTime * Map()->m_EnvelopeEvaluator.m_AnimateSpeed, Map()->m_EnvelopeEvaluator.m_AnimateSpeed, MapView()->MapGrid()->Factor(), aTimeStr);
3718 Ui()->DoLabel(pRect: &Info, pText: aBuf, Size: 10.0f, Align: TEXTALIGN_MR);
3719
3720 static int s_HelpButton = 0;
3721 if(DoButton_Editor(pId: &s_HelpButton, pText: "?", Checked: 0, pRect: &Help, Flags: BUTTONFLAG_LEFT, pToolTip: "[F1] Open the DDNet Wiki page for the map editor in a web browser."))
3722 {
3723 m_QuickActionShowHelp.Call();
3724 }
3725
3726 static int s_CloseButton = 0;
3727 if(DoButton_Editor(pId: &s_CloseButton, pText: "×", Checked: 0, pRect: &Close, Flags: BUTTONFLAG_LEFT, pToolTip: "[Escape] Exit from the editor."))
3728 {
3729 OnClose();
3730 g_Config.m_ClEditor = 0;
3731 }
3732}
3733
3734void CEditor::ShowHelp()
3735{
3736 const char *pLink = Localize(pStr: "https://wiki.ddnet.org/wiki/Mapping");
3737 if(!Client()->ViewLink(pLink))
3738 {
3739 ShowFileDialogError(pFormat: "Failed to open the link '%s' in the default web browser.", pLink);
3740 }
3741}
3742
3743void CEditor::Exit()
3744{
3745 if(HasUnsavedData())
3746 {
3747 m_PopupEventType = POPEVENT_EXIT;
3748 m_PopupEventActivated = true;
3749 }
3750 else
3751 {
3752 OnClose();
3753 g_Config.m_ClEditor = 0;
3754 }
3755}
3756
3757void CEditor::Render()
3758{
3759 // basic start
3760 Graphics()->Clear(r: 0.0f, g: 0.0f, b: 0.0f);
3761 CUIRect View = *Ui()->Screen();
3762 Ui()->MapScreen();
3763 m_CursorType = CURSOR_NORMAL;
3764
3765 float Width = View.w;
3766 float Height = View.h;
3767
3768 // reset tip
3769 str_copy(dst&: m_aTooltip, src: "");
3770
3771 // render checker
3772 RenderBackground(View, Texture: m_CheckerTexture, Size: 32.0f, Brightness: 1.0f);
3773
3774 UpdateBrushPicker();
3775
3776 CUIRect MenuBar, ModeBar, ToolBar, StatusBar, ExtraEditor, ToolBox;
3777 if(m_GuiActive)
3778 {
3779 View.HSplitTop(Cut: 20.0f, pTop: &MenuBar, pBottom: &View);
3780 View.HSplitTop(Cut: 78.0f, pTop: &ToolBar, pBottom: &View);
3781 View.VSplitLeft(Cut: m_ToolBoxWidth, pLeft: &ToolBox, pRight: &View);
3782
3783 View.HSplitBottom(Cut: 16.0f, pTop: &View, pBottom: &StatusBar);
3784 if(!m_ShowPicker && m_ActiveExtraEditor != EXTRAEDITOR_NONE)
3785 View.HSplitBottom(Cut: m_aExtraEditorSplits[(int)m_ActiveExtraEditor], pTop: &View, pBottom: &ExtraEditor);
3786 }
3787 else
3788 {
3789 // hack to get keyboard inputs from toolbar even when GUI is not active
3790 ToolBar.x = -100;
3791 ToolBar.y = -100;
3792 ToolBar.w = 50;
3793 ToolBar.h = 50;
3794 }
3795
3796 // a little hack for now
3797 if(m_Mode == MODE_LAYERS)
3798 MapView()->Render(View);
3799
3800 if(m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr)
3801 {
3802 // handle undo/redo hotkeys
3803 if(Ui()->CheckActiveItem(pId: nullptr))
3804 {
3805 if(Input()->KeyPress(Key: KEY_Z) && Input()->ModifierIsPressed() && !Input()->ShiftIsPressed())
3806 ActiveHistory().Undo();
3807 if((Input()->KeyPress(Key: KEY_Y) && Input()->ModifierIsPressed()) || (Input()->KeyPress(Key: KEY_Z) && Input()->ModifierIsPressed() && Input()->ShiftIsPressed()))
3808 ActiveHistory().Redo();
3809 }
3810
3811 // handle brush save/load hotkeys
3812 for(int i = KEY_1; i <= KEY_0; i++)
3813 {
3814 if(Input()->KeyPress(Key: i))
3815 {
3816 int Slot = i - KEY_1;
3817 if(Input()->ModifierIsPressed() && !m_pBrush->IsEmpty())
3818 {
3819 dbg_msg(sys: "editor", fmt: "saving current brush to %d", Slot);
3820 m_apSavedBrushes[Slot] = std::make_shared<CLayerGroup>(args&: *m_pBrush);
3821 }
3822 else if(m_apSavedBrushes[Slot])
3823 {
3824 dbg_msg(sys: "editor", fmt: "loading brush from slot %d", Slot);
3825 m_pBrush = std::make_shared<CLayerGroup>(args&: *m_apSavedBrushes[Slot]);
3826 }
3827 }
3828 }
3829 }
3830
3831 const float BackgroundBrightness = 0.26f;
3832 const float BackgroundScale = 80.0f;
3833
3834 if(m_GuiActive)
3835 {
3836 RenderBackground(View: MenuBar, Texture: IGraphics::CTextureHandle(), Size: BackgroundScale, Brightness: 0.0f);
3837 MenuBar.Margin(Cut: 2.0f, pOtherRect: &MenuBar);
3838
3839 RenderBackground(View: ToolBox, Texture: g_pData->m_aImages[IMAGE_BACKGROUND_NOISE].m_Id, Size: BackgroundScale, Brightness: BackgroundBrightness);
3840 ToolBox.Margin(Cut: 2.0f, pOtherRect: &ToolBox);
3841
3842 RenderBackground(View: ToolBar, Texture: g_pData->m_aImages[IMAGE_BACKGROUND_NOISE].m_Id, Size: BackgroundScale, Brightness: BackgroundBrightness);
3843 ToolBar.Margin(Cut: 2.0f, pOtherRect: &ToolBar);
3844 ToolBar.VSplitLeft(Cut: m_ToolBoxWidth, pLeft: &ModeBar, pRight: &ToolBar);
3845
3846 RenderBackground(View: StatusBar, Texture: g_pData->m_aImages[IMAGE_BACKGROUND_NOISE].m_Id, Size: BackgroundScale, Brightness: BackgroundBrightness);
3847 StatusBar.Margin(Cut: 2.0f, pOtherRect: &StatusBar);
3848 }
3849
3850 // do the toolbar
3851 {
3852 CUIRect MapTabs;
3853 ToolBar.HSplitTop(Cut: 20.0f, pTop: &MapTabs, pBottom: &ToolBar);
3854 ToolBar.HSplitTop(Cut: 5.0f, pTop: nullptr, pBottom: &ToolBar);
3855 DoMapTabs(MapTabs);
3856 if(m_Mode == MODE_LAYERS)
3857 DoToolbarLayers(ToolBar);
3858 else if(m_Mode == MODE_IMAGES)
3859 DoToolbarImages(ToolBar);
3860 else if(m_Mode == MODE_SOUNDS)
3861 DoToolbarSounds(ToolBar);
3862 }
3863
3864 if(m_Dialog == DIALOG_NONE)
3865 {
3866 const bool ModPressed = Input()->ModifierIsPressed();
3867 const bool ShiftPressed = Input()->ShiftIsPressed();
3868 const bool AltPressed = Input()->AltIsPressed();
3869
3870 if(CLineInput::GetActiveInput() == nullptr)
3871 {
3872 // ctrl+a to append map
3873 if(Input()->KeyPress(Key: KEY_A) && ModPressed)
3874 {
3875 m_QuickActionAppendMap.Call();
3876 }
3877 }
3878
3879 // ctrl+n to create new map
3880 if(Input()->KeyPress(Key: KEY_N) && ModPressed)
3881 {
3882 m_QuickActionNewMap.Call();
3883 }
3884 // ctrl+o or ctrl+l to open
3885 if((Input()->KeyPress(Key: KEY_O) || Input()->KeyPress(Key: KEY_L)) && ModPressed)
3886 {
3887 if(ShiftPressed)
3888 {
3889 if(!m_QuickActionLoadIngameMap.Disabled())
3890 {
3891 m_QuickActionLoadIngameMap.Call();
3892 }
3893 }
3894 else
3895 {
3896 m_QuickActionLoadMap.Call();
3897 }
3898 }
3899
3900 // ctrl+shift+alt+s to save copy
3901 if(Input()->KeyPress(Key: KEY_S) && ModPressed && ShiftPressed && AltPressed)
3902 {
3903 m_QuickActionSaveCopy.Call();
3904 }
3905 // ctrl+shift+s to save as
3906 else if(Input()->KeyPress(Key: KEY_S) && ModPressed && ShiftPressed)
3907 {
3908 m_QuickActionSaveAs.Call();
3909 }
3910 // ctrl+s to save
3911 else if(Input()->KeyPress(Key: KEY_S) && ModPressed)
3912 {
3913 m_QuickActionSave.Call();
3914 }
3915 }
3916
3917 if(m_GuiActive)
3918 {
3919 CUIRect DragBar;
3920 ToolBox.VSplitRight(Cut: 1.0f, pLeft: &ToolBox, pRight: &DragBar);
3921 DragBar.x -= 2.0f;
3922 DragBar.w += 4.0f;
3923 DoEditorDragBar(View: ToolBox, pDragBar: &DragBar, Side: EDragSide::RIGHT, pValue: &m_ToolBoxWidth);
3924
3925 if(m_Mode == MODE_LAYERS)
3926 RenderLayers(LayersBox: ToolBox);
3927 else if(m_Mode == MODE_IMAGES)
3928 {
3929 RenderImagesList(ToolBox);
3930 RenderSelectedImage(View);
3931 }
3932 else if(m_Mode == MODE_SOUNDS)
3933 RenderSounds(ToolBox);
3934 }
3935
3936 Ui()->MapScreen();
3937
3938 CUIRect TooltipRect;
3939 if(m_GuiActive)
3940 {
3941 RenderMenubar(MenuBar);
3942 RenderModebar(View: ModeBar);
3943 if(!m_ShowPicker)
3944 {
3945 if(m_ActiveExtraEditor != EXTRAEDITOR_NONE)
3946 {
3947 RenderBackground(View: ExtraEditor, Texture: g_pData->m_aImages[IMAGE_BACKGROUND_NOISE].m_Id, Size: BackgroundScale, Brightness: BackgroundBrightness);
3948 ExtraEditor.HMargin(Cut: 2.0f, pOtherRect: &ExtraEditor);
3949 ExtraEditor.VSplitRight(Cut: 2.0f, pLeft: &ExtraEditor, pRight: nullptr);
3950 }
3951
3952 static bool s_ShowServerSettingsEditorLast = false;
3953 if(m_ActiveExtraEditor == EXTRAEDITOR_ENVELOPES)
3954 {
3955 m_EnvelopeEditor.Render(View: ExtraEditor);
3956 }
3957 else if(m_ActiveExtraEditor == EXTRAEDITOR_SERVER_SETTINGS)
3958 {
3959 RenderServerSettingsEditor(View: ExtraEditor, ShowServerSettingsEditorLast: s_ShowServerSettingsEditorLast);
3960 }
3961 else if(m_ActiveExtraEditor == EXTRAEDITOR_HISTORY)
3962 {
3963 RenderEditorHistory(View: ExtraEditor);
3964 }
3965 s_ShowServerSettingsEditorLast = m_ActiveExtraEditor == EXTRAEDITOR_SERVER_SETTINGS;
3966 }
3967 RenderStatusbar(View: StatusBar, pTooltipRect: &TooltipRect);
3968 }
3969
3970 RenderPressedKeys(View);
3971 RenderSavingIndicator(View);
3972
3973 if(m_Dialog == DIALOG_MAPSETTINGS_ERROR)
3974 {
3975 static int s_NullUiTarget = 0;
3976 Ui()->SetHotItem(&s_NullUiTarget);
3977 RenderMapSettingsErrorDialog();
3978 }
3979
3980 if(m_PopupEventActivated)
3981 {
3982 static SPopupMenuId s_PopupEventId;
3983 constexpr float PopupWidth = 400.0f;
3984 constexpr float PopupHeight = 150.0f;
3985 Ui()->DoPopupMenu(pId: &s_PopupEventId, X: Width / 2.0f - PopupWidth / 2.0f, Y: Height / 2.0f - PopupHeight / 2.0f, Width: PopupWidth, Height: PopupHeight, pContext: this, pfnFunc: PopupEvent);
3986 m_PopupEventActivated = false;
3987 }
3988
3989 if(m_Dialog == DIALOG_NONE && !Ui()->IsPopupHovered() && Ui()->MouseInside(pRect: &View))
3990 {
3991 // handle zoom hotkeys
3992 if(CLineInput::GetActiveInput() == nullptr)
3993 {
3994 // one keypress should be equivalent to zooming
3995 // three times using mousewheel: 1.1^3 = 1.331
3996 if(Input()->KeyPress(Key: KEY_KP_MINUS))
3997 MapView()->Zoom()->ScaleValue(Factor: 1.331f);
3998 if(Input()->KeyPress(Key: KEY_KP_PLUS))
3999 MapView()->Zoom()->ScaleValue(Factor: 1.0f / 1.331f);
4000 if(Input()->KeyPress(Key: KEY_KP_MULTIPLY))
4001 MapView()->ResetZoom();
4002 }
4003
4004 if(m_pBrush->IsEmpty() || !Input()->ShiftIsPressed())
4005 {
4006 if(Input()->KeyPress(Key: KEY_MOUSE_WHEEL_DOWN))
4007 MapView()->Zoom()->ScaleValue(Factor: 1.1f);
4008 if(Input()->KeyPress(Key: KEY_MOUSE_WHEEL_UP))
4009 MapView()->Zoom()->ScaleValue(Factor: 1.0f / 1.1f);
4010 }
4011 if(!m_pBrush->IsEmpty())
4012 {
4013 bool HasTileAdjustLayer = false;
4014 bool HasSpeedupLayer = false;
4015 for(const auto &pLayer : m_pBrush->m_vpLayers)
4016 {
4017 if(pLayer->m_Type != LAYERTYPE_TILES)
4018 {
4019 continue;
4020 }
4021 std::shared_ptr<CLayerTiles> pTiles = std::static_pointer_cast<CLayerTiles>(r: pLayer);
4022 HasTileAdjustLayer |= pTiles->m_HasTele || pTiles->m_HasSwitch || pTiles->m_HasTune;
4023 HasSpeedupLayer |= pTiles->m_HasSpeedup;
4024 }
4025 if(HasTileAdjustLayer)
4026 {
4027 str_copy(dst&: m_aTooltip, src: "Use Shift+Mouse wheel up/down to adjust the tile numbers. Use Ctrl+F to change all tile numbers to the first unused number.");
4028 }
4029 else if(HasSpeedupLayer)
4030 {
4031 str_copy(dst&: m_aTooltip, src: "Use Shift+Mouse wheel up/down to adjust the angle.");
4032 }
4033
4034 if(Input()->ShiftIsPressed())
4035 {
4036 const int AdjustModifiers = Input()->ModifierIsPressed() ? (Input()->AltIsPressed() ? 2 : 1) : 0;
4037 if(Input()->KeyPress(Key: KEY_MOUSE_WHEEL_DOWN))
4038 AdjustBrushSpecialTiles(UseNextFree: false, AdjustModifiers, AdjustValue: -1);
4039 if(Input()->KeyPress(Key: KEY_MOUSE_WHEEL_UP))
4040 AdjustBrushSpecialTiles(UseNextFree: false, AdjustModifiers, AdjustValue: 1);
4041 }
4042
4043 // Use ctrl+f to replace number in brush with next free
4044 if(Input()->ModifierIsPressed() && Input()->KeyPress(Key: KEY_F))
4045 AdjustBrushSpecialTiles(UseNextFree: true, AdjustModifiers: 0, AdjustValue: 0);
4046 }
4047 }
4048
4049 m_FileBrowser.Render();
4050 m_Prompt.Render();
4051 m_FontTyper.Render();
4052
4053 MapView()->UpdateZoom();
4054
4055 // Cancel color pipette with escape before closing popup menus with escape
4056 if(m_ColorPipetteActive && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ESCAPE))
4057 {
4058 m_ColorPipetteActive = false;
4059 }
4060
4061 Ui()->RenderPopupMenus();
4062 FreeDynamicPopupMenus();
4063
4064 UpdateColorPipette();
4065
4066 if(m_Dialog == DIALOG_NONE && !m_PopupEventActivated && Ui()->ConsumeHotkey(Hotkey: CUi::HOTKEY_ESCAPE))
4067 {
4068 OnClose();
4069 g_Config.m_ClEditor = 0;
4070 }
4071
4072 // The tooltip can be set in popup menus so we have to render the tooltip after the popup menus.
4073 if(m_GuiActive)
4074 RenderTooltip(TooltipRect);
4075
4076 Ui()->RenderBackButton();
4077 RenderMousePointer();
4078}
4079
4080void CEditor::UpdateBrushPicker()
4081{
4082 if(!m_QuickActionBrushPicker.Disabled() &&
4083 m_Dialog == DIALOG_NONE &&
4084 CLineInput::GetActiveInput() == nullptr)
4085 {
4086 if(Input()->ModifierIsPressed())
4087 {
4088 if(Input()->KeyPress(Key: KEY_SPACE))
4089 {
4090 m_ShowPickerToggle = !m_ShowPickerToggle;
4091 }
4092 m_ShowPicker = m_ShowPickerToggle;
4093 }
4094 else
4095 {
4096 const bool SpacePressed = Input()->KeyIsPressed(Key: KEY_SPACE);
4097 m_ShowPicker = m_ShowPickerToggle || SpacePressed;
4098 if(SpacePressed)
4099 {
4100 m_ShowPickerToggle = false;
4101 }
4102 }
4103 }
4104 else
4105 {
4106 m_ShowPicker = false;
4107 m_ShowPickerToggle = false;
4108 }
4109}
4110
4111void CEditor::RenderPressedKeys(CUIRect View)
4112{
4113 if(!g_Config.m_EdShowkeys)
4114 return;
4115
4116 Ui()->MapScreen();
4117 CTextCursor Cursor;
4118 Cursor.SetPosition(vec2(View.x + 10, View.y + View.h - 24 - 10));
4119 Cursor.m_FontSize = 24.0f;
4120
4121 int NKeys = 0;
4122 for(int i = 0; i < KEY_LAST; i++)
4123 {
4124 if(Input()->KeyIsPressed(Key: i))
4125 {
4126 if(NKeys)
4127 TextRender()->TextEx(pCursor: &Cursor, pText: " + ", Length: -1);
4128 TextRender()->TextEx(pCursor: &Cursor, pText: KeyName(Key: i), Length: -1);
4129 NKeys++;
4130 }
4131 }
4132}
4133
4134void CEditor::RenderSavingIndicator(CUIRect View)
4135{
4136 if(m_WriterFinishJobs.empty())
4137 return;
4138
4139 const char *pText = "Saving…";
4140 const float FontSize = 24.0f;
4141
4142 Ui()->MapScreen();
4143 CUIRect Label, Spinner;
4144 View.Margin(Cut: 20.0f, pOtherRect: &View);
4145 View.HSplitBottom(Cut: FontSize, pTop: nullptr, pBottom: &View);
4146 View.VSplitRight(Cut: TextRender()->TextWidth(Size: FontSize, pText) + 2.0f, pLeft: &Spinner, pRight: &Label);
4147 Spinner.VSplitRight(Cut: Spinner.h, pLeft: nullptr, pRight: &Spinner);
4148 Ui()->DoLabel(pRect: &Label, pText, Size: FontSize, Align: TEXTALIGN_MR);
4149 Ui()->RenderProgressSpinner(Center: Spinner.Center(), OuterRadius: 8.0f);
4150}
4151
4152void CEditor::FreeDynamicPopupMenus()
4153{
4154 auto Iterator = m_PopupMessageContexts.begin();
4155 while(Iterator != m_PopupMessageContexts.end())
4156 {
4157 if(!Ui()->IsPopupOpen(pId: Iterator->second))
4158 {
4159 CUi::SMessagePopupContext *pContext = Iterator->second;
4160 Iterator = m_PopupMessageContexts.erase(position: Iterator);
4161 delete pContext;
4162 }
4163 else
4164 ++Iterator;
4165 }
4166}
4167
4168void CEditor::UpdateColorPipette()
4169{
4170 if(!m_ColorPipetteActive)
4171 return;
4172
4173 static char s_PipetteScreenButton;
4174 if(Ui()->HotItem() == &s_PipetteScreenButton)
4175 {
4176 // Read color one pixel to the top and left as we would otherwise not read the correct
4177 // color due to the cursor sprite being rendered over the current mouse position.
4178 const int PixelX = std::clamp<int>(val: round_to_int(f: (Ui()->MouseX() - 1.0f) / Ui()->Screen()->w * Graphics()->ScreenWidth()), lo: 0, hi: Graphics()->ScreenWidth() - 1);
4179 const int PixelY = std::clamp<int>(val: round_to_int(f: (Ui()->MouseY() - 1.0f) / Ui()->Screen()->h * Graphics()->ScreenHeight()), lo: 0, hi: Graphics()->ScreenHeight() - 1);
4180 Graphics()->ReadPixel(Position: ivec2(PixelX, PixelY), pColor: &m_PipetteColor);
4181 }
4182
4183 // Simulate button overlaying the entire screen to intercept all clicks for color pipette.
4184 const int ButtonResult = DoButtonLogic(pId: &s_PipetteScreenButton, Checked: 0, pRect: Ui()->Screen(), Flags: BUTTONFLAG_ALL, pToolTip: "Left click to pick a color from the screen. Right click to cancel pipette mode.");
4185 // Don't handle clicks if we are panning, so the pipette stays active while panning.
4186 // Checking m_pContainerPanned alone is not enough, as this variable is reset when
4187 // panning ends before this function is called.
4188 if(m_pContainerPanned == nullptr && m_pContainerPannedLast == nullptr)
4189 {
4190 if(ButtonResult == 1)
4191 {
4192 char aClipboard[9];
4193 str_format(buffer: aClipboard, buffer_size: sizeof(aClipboard), format: "%08X", m_PipetteColor.PackAlphaLast());
4194 Input()->SetClipboardText(aClipboard);
4195
4196 // Check if any of the saved colors is equal to the picked color and
4197 // bring it to the front of the list instead of adding a duplicate.
4198 int ShiftEnd = (int)std::size(m_aSavedColors) - 1;
4199 for(int i = 0; i < (int)std::size(m_aSavedColors); ++i)
4200 {
4201 if(m_aSavedColors[i].Pack() == m_PipetteColor.Pack())
4202 {
4203 ShiftEnd = i;
4204 break;
4205 }
4206 }
4207 for(int i = ShiftEnd; i > 0; --i)
4208 {
4209 m_aSavedColors[i] = m_aSavedColors[i - 1];
4210 }
4211 m_aSavedColors[0] = m_PipetteColor;
4212 }
4213 if(ButtonResult > 0)
4214 {
4215 m_ColorPipetteActive = false;
4216 }
4217 }
4218}
4219
4220void CEditor::RenderMousePointer()
4221{
4222 if(!m_ShowMousePointer)
4223 return;
4224
4225 if(m_MouseAxisLockState == EAxisLock::HORIZONTAL)
4226 {
4227 m_CursorType = CURSOR_RESIZE_H;
4228 }
4229 else if(m_MouseAxisLockState == EAxisLock::VERTICAL)
4230 {
4231 m_CursorType = CURSOR_RESIZE_V;
4232 }
4233
4234 constexpr float CursorSize = 16.0f;
4235
4236 // Cursor
4237 Graphics()->WrapClamp();
4238 Graphics()->TextureSet(Texture: m_aCursorTextures[m_CursorType]);
4239 Graphics()->QuadsBegin();
4240 if(m_CursorType == CURSOR_RESIZE_V)
4241 {
4242 Graphics()->QuadsSetRotation(Angle: pi / 2.0f);
4243 }
4244 if(m_pUiGotContext == Ui()->HotItem())
4245 {
4246 Graphics()->SetColor(r: 1.0f, g: 0.0f, b: 0.0f, a: 1.0f);
4247 }
4248 const float CursorOffset = m_CursorType == CURSOR_RESIZE_V || m_CursorType == CURSOR_RESIZE_H ? -CursorSize / 2.0f : 0.0f;
4249 IGraphics::CQuadItem QuadItem(Ui()->MouseX() + CursorOffset, Ui()->MouseY() + CursorOffset, CursorSize, CursorSize);
4250 Graphics()->QuadsDrawTL(pArray: &QuadItem, Num: 1);
4251 Graphics()->QuadsEnd();
4252 Graphics()->WrapNormal();
4253
4254 // Pipette color
4255 if(m_ColorPipetteActive)
4256 {
4257 CUIRect PipetteRect = {.x: Ui()->MouseX() + CursorSize, .y: Ui()->MouseY() + CursorSize, .w: 80.0f, .h: 20.0f};
4258 if(PipetteRect.x + PipetteRect.w + 2.0f > Ui()->Screen()->w)
4259 {
4260 PipetteRect.x = Ui()->MouseX() - PipetteRect.w - CursorSize / 2.0f;
4261 }
4262 if(PipetteRect.y + PipetteRect.h + 2.0f > Ui()->Screen()->h)
4263 {
4264 PipetteRect.y = Ui()->MouseY() - PipetteRect.h - CursorSize / 2.0f;
4265 }
4266 PipetteRect.Draw(Color: ColorRGBA(0.2f, 0.2f, 0.2f, 0.7f), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
4267
4268 CUIRect Pipette, Label;
4269 PipetteRect.VSplitLeft(Cut: PipetteRect.h, pLeft: &Pipette, pRight: &Label);
4270 Pipette.Margin(Cut: 2.0f, pOtherRect: &Pipette);
4271 Pipette.Draw(Color: m_PipetteColor, Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
4272
4273 char aLabel[8];
4274 str_format(buffer: aLabel, buffer_size: sizeof(aLabel), format: "#%06X", m_PipetteColor.PackAlphaLast(Alpha: false));
4275 Ui()->DoLabel(pRect: &Label, pText: aLabel, Size: 10.0f, Align: TEXTALIGN_MC);
4276 }
4277}
4278
4279void CEditor::RenderIngameEntities(const CLayerGroup &Group, const CLayerTiles &TilesLayer)
4280{
4281 const CGameClient *pGameClient = (CGameClient *)Kernel()->RequestInterface<IGameClient>();
4282 const float TileSize = 32.f;
4283
4284 const bool DDNetOrCustomEntities = std::find_if(first: std::begin(arr: gs_apModEntitiesNames), last: std::end(arr: gs_apModEntitiesNames),
4285 pred: [&](const char *pEntitiesName) { return str_comp_nocase(a: m_SelectEntitiesImage.c_str(), b: pEntitiesName) == 0 &&
4286 str_comp_nocase(a: pEntitiesName, b: "ddnet") != 0; }) == std::end(arr: gs_apModEntitiesNames);
4287
4288 const bool IsSwitch = TilesLayer.m_HasSwitch;
4289 std::function<std::tuple<unsigned char, unsigned char>(int, int)> GetTile;
4290 std::function<unsigned char(int, int)> GetIndexChecked;
4291 if(IsSwitch)
4292 {
4293 const CLayerSwitch &SwitchLayer = static_cast<const CLayerSwitch &>(TilesLayer);
4294 GetTile = [&](int x, int y) -> std::tuple<unsigned char, unsigned char> {
4295 const CSwitchTile Tile = SwitchLayer.m_pSwitchTile[y * SwitchLayer.m_Width + x];
4296 return {Tile.m_Type - ENTITY_OFFSET, Tile.m_Flags};
4297 };
4298 GetIndexChecked = [&](int x, int y) -> unsigned char {
4299 if(x < 0 || y < 0 || x >= SwitchLayer.m_Width || y >= SwitchLayer.m_Height)
4300 {
4301 return 0;
4302 }
4303 return SwitchLayer.m_pSwitchTile[y * SwitchLayer.m_Width + x].m_Type - ENTITY_OFFSET;
4304 };
4305 }
4306 else
4307 {
4308 GetTile = [&](int x, int y) -> std::tuple<unsigned char, unsigned char> {
4309 const CTile Tile = TilesLayer.m_pTiles[y * TilesLayer.m_Width + x];
4310 return {Tile.m_Index - ENTITY_OFFSET, Tile.m_Flags};
4311 };
4312 GetIndexChecked = [&](int x, int y) -> unsigned char {
4313 if(x < 0 || y < 0 || x >= TilesLayer.m_Width || y >= TilesLayer.m_Height)
4314 {
4315 return 0;
4316 }
4317 return TilesLayer.m_pTiles[y * TilesLayer.m_Width + x].m_Index - ENTITY_OFFSET;
4318 };
4319 }
4320
4321 static const ivec2 DOOR_OFFSETS[] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}};
4322 const ColorRGBA DoorOuterColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClLaserDoorOutlineColor));
4323 const ColorRGBA DoorInnerColor = color_cast<ColorRGBA>(hsl: ColorHSLA(g_Config.m_ClLaserDoorInnerColor));
4324
4325 CScreenRect ScreenRect = Group.Mapping();
4326 const int ExtraBorder = 9; // doors extend beyond the tile on which they are placed
4327 const int StartX = std::max(a: 0, b: (int)std::floor(x: ScreenRect.m_TopLeft.x / TileSize) - ExtraBorder);
4328 const int EndX = std::min(a: TilesLayer.m_Width, b: (int)std::ceil(x: ScreenRect.m_BottomRight.x / TileSize) + ExtraBorder);
4329 const int StartY = std::max(a: 0, b: (int)std::floor(x: ScreenRect.m_TopLeft.y / TileSize) - ExtraBorder);
4330 const int EndY = std::min(a: TilesLayer.m_Height, b: (int)std::ceil(x: ScreenRect.m_BottomRight.y / TileSize) + ExtraBorder);
4331 for(int y = StartY; y < EndY; y++)
4332 {
4333 for(int x = StartX; x < EndX; x++)
4334 {
4335 const auto [Index, Flags] = GetTile(x, y);
4336
4337 if(Index == ENTITY_DOOR)
4338 {
4339 for(const ivec2 Offset : DOOR_OFFSETS)
4340 {
4341 const unsigned char IndexDoorLength = GetIndexChecked(x + Offset.x, y + Offset.y);
4342 if(IndexDoorLength >= ENTITY_LASER_SHORT && IndexDoorLength <= ENTITY_LASER_LONG)
4343 {
4344 const int Length = (IndexDoorLength - ENTITY_LASER_SHORT + 1) * 3;
4345 const vec2 Pos = vec2(x + 0.5f, y + 0.5f);
4346 const vec2 To = Pos + normalize(v: vec2(Offset.x, Offset.y)) * Length;
4347 pGameClient->m_Items.RenderLaser(From: To * TileSize, Pos: Pos * TileSize, OuterColor: DoorOuterColor, InnerColor: DoorInnerColor, TicksBody: 0.0f, TicksHead: 0.0f, Type: LASERTYPE_DOOR);
4348 }
4349 }
4350 }
4351 else if((!IsSwitch && Index >= ENTITY_FLAGSTAND_RED && Index <= ENTITY_FLAGSTAND_BLUE) ||
4352 (Index >= ENTITY_ARMOR_1 && Index <= ENTITY_WEAPON_LASER) ||
4353 (DDNetOrCustomEntities && Index >= ENTITY_ARMOR_SHOTGUN && Index <= ENTITY_ARMOR_LASER))
4354 {
4355 vec2 Pos = vec2(x, y) * TileSize;
4356 vec2 Scale;
4357 int VisualSize;
4358
4359 if(Index == ENTITY_FLAGSTAND_RED)
4360 {
4361 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_SpriteFlagRed);
4362 Scale = vec2(42, 84);
4363 VisualSize = 1;
4364 Pos.y -= (Scale.y / 2.f) * 0.75f;
4365 }
4366 else if(Index == ENTITY_FLAGSTAND_BLUE)
4367 {
4368 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_SpriteFlagBlue);
4369 Scale = vec2(42, 84);
4370 VisualSize = 1;
4371 Pos.y -= (Scale.y / 2.f) * 0.75f;
4372 }
4373 else if(Index == ENTITY_ARMOR_1)
4374 {
4375 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_SpritePickupArmor);
4376 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_HEALTH, ScaleX&: Scale.x, ScaleY&: Scale.y);
4377 VisualSize = 64;
4378 }
4379 else if(Index == ENTITY_HEALTH_1)
4380 {
4381 if(DDNetOrCustomEntities)
4382 {
4383 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_SpritePickupFreeze);
4384 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_FREEZE, ScaleX&: Scale.x, ScaleY&: Scale.y);
4385 }
4386 else
4387 {
4388 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_SpritePickupHealth);
4389 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_HEALTH, ScaleX&: Scale.x, ScaleY&: Scale.y);
4390 }
4391 VisualSize = 64;
4392 }
4393 else if(Index == ENTITY_WEAPON_SHOTGUN)
4394 {
4395 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_aSpritePickupWeapons[WEAPON_SHOTGUN]);
4396 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_SHOTGUN, ScaleX&: Scale.x, ScaleY&: Scale.y);
4397 VisualSize = g_pData->m_Weapons.m_aId[WEAPON_SHOTGUN].m_VisualSize;
4398 }
4399 else if(Index == ENTITY_WEAPON_GRENADE)
4400 {
4401 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_aSpritePickupWeapons[WEAPON_GRENADE]);
4402 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_GRENADE, ScaleX&: Scale.x, ScaleY&: Scale.y);
4403 VisualSize = g_pData->m_Weapons.m_aId[WEAPON_GRENADE].m_VisualSize;
4404 }
4405 else if(Index == ENTITY_POWERUP_NINJA)
4406 {
4407 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_aSpritePickupWeapons[WEAPON_NINJA]);
4408 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_NINJA, ScaleX&: Scale.x, ScaleY&: Scale.y);
4409 VisualSize = 128;
4410 }
4411 else if(Index == ENTITY_WEAPON_LASER)
4412 {
4413 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_aSpritePickupWeapons[WEAPON_LASER]);
4414 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_LASER, ScaleX&: Scale.x, ScaleY&: Scale.y);
4415 VisualSize = g_pData->m_Weapons.m_aId[WEAPON_LASER].m_VisualSize;
4416 }
4417 else if(Index == ENTITY_ARMOR_SHOTGUN)
4418 {
4419 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_SpritePickupArmorShotgun);
4420 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_ARMOR_SHOTGUN, ScaleX&: Scale.x, ScaleY&: Scale.y);
4421 VisualSize = 64;
4422 }
4423 else if(Index == ENTITY_ARMOR_GRENADE)
4424 {
4425 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_SpritePickupArmorGrenade);
4426 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_ARMOR_GRENADE, ScaleX&: Scale.x, ScaleY&: Scale.y);
4427 VisualSize = 64;
4428 }
4429 else if(Index == ENTITY_ARMOR_NINJA)
4430 {
4431 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_SpritePickupArmorNinja);
4432 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_ARMOR_NINJA, ScaleX&: Scale.x, ScaleY&: Scale.y);
4433 VisualSize = 64;
4434 }
4435 else if(Index == ENTITY_ARMOR_LASER)
4436 {
4437 Graphics()->TextureSet(Texture: pGameClient->m_GameSkin.m_SpritePickupArmorLaser);
4438 Graphics()->GetSpriteScale(Id: SPRITE_PICKUP_ARMOR_LASER, ScaleX&: Scale.x, ScaleY&: Scale.y);
4439 VisualSize = 64;
4440 }
4441 else
4442 {
4443 dbg_assert_failed("Unhandled ingame entities index: %d", Index);
4444 }
4445
4446 Graphics()->QuadsBegin();
4447
4448 if(Index != ENTITY_FLAGSTAND_RED &&
4449 Index != ENTITY_FLAGSTAND_BLUE)
4450 {
4451 if(Flags & TILEFLAG_XFLIP)
4452 {
4453 Scale.x = -Scale.x;
4454 }
4455
4456 if(Flags & TILEFLAG_YFLIP)
4457 {
4458 Scale.y = -Scale.y;
4459 }
4460
4461 if(Flags & TILEFLAG_ROTATE)
4462 {
4463 Graphics()->QuadsSetRotation(Angle: 90.f * (pi / 180));
4464
4465 if(Index == ENTITY_POWERUP_NINJA)
4466 {
4467 Pos.y += (Flags & TILEFLAG_XFLIP) ? 10.0f : -10.0f;
4468 }
4469 }
4470 else
4471 {
4472 if(Index == ENTITY_POWERUP_NINJA)
4473 {
4474 Pos.x += (Flags & TILEFLAG_XFLIP) ? 10.0f : -10.0f;
4475 }
4476 }
4477 }
4478
4479 Scale *= VisualSize;
4480 Pos -= (Scale - vec2(TileSize, TileSize)) / 2.0f;
4481 Pos += direction(angle: Client()->GlobalTime() * 2.0f + x + y) * 2.5f;
4482
4483 IGraphics::CQuadItem Quad(Pos.x, Pos.y, Scale.x, Scale.y);
4484 Graphics()->QuadsDrawTL(pArray: &Quad, Num: 1);
4485 Graphics()->QuadsEnd();
4486 }
4487 }
4488 }
4489}
4490
4491void CEditor::Reset()
4492{
4493 Ui()->ClosePopupMenus();
4494 Ui()->SetActiveItem(nullptr);
4495
4496 for(CEditorComponent &Component : m_vComponents)
4497 Component.OnReset();
4498
4499 m_ToolbarPreviewSound = -1;
4500
4501 m_pContainerPanned = nullptr;
4502 m_pContainerPannedLast = nullptr;
4503
4504 m_ActiveEnvelopePreview = EEnvelopePreview::NONE;
4505 m_QuadEnvelopePointOperation = EQuadEnvelopePointOperation::NONE;
4506
4507 m_RenderLayersState.Reset();
4508}
4509
4510void CEditor::AddDefaultMap()
4511{
4512 std::unique_ptr<CEditorMap> pNewMap = std::make_unique<CEditorMap>(args: this);
4513 pNewMap->CreateDefault();
4514 m_vpMaps.push_back(x: std::move(pNewMap));
4515 m_SelectedMap = m_vpMaps.size() - 1;
4516 m_MapTabsRevealSelected = true;
4517 UpdateMapDisplayNames();
4518}
4519
4520void CEditor::CloseMap(size_t Index, bool Confirm)
4521{
4522 if(IsSaving(pFilename: m_vpMaps[Index]->m_aFilename))
4523 {
4524 return;
4525 }
4526
4527 if(Confirm && m_vpMaps[Index]->m_Modified)
4528 {
4529 if(Index != m_SelectedMap)
4530 {
4531 m_SelectedMap = Index;
4532 m_MapTabsRevealSelected = true;
4533 Reset();
4534 }
4535 m_PopupEventType = CEditor::POPEVENT_CLOSE_MAP;
4536 m_PopupEventActivated = true;
4537 return;
4538 }
4539
4540 if(Index == m_SelectedMap)
4541 {
4542 Reset();
4543 }
4544
4545 Ui()->ClosePopupMenu(pId: &m_PopupMapTab);
4546 m_vpMaps.erase(position: m_vpMaps.begin() + Index);
4547 if(m_vpMaps.empty())
4548 {
4549 AddDefaultMap();
4550 }
4551 else
4552 {
4553 UpdateMapDisplayNames();
4554 if(m_SelectedMap > 0 && m_SelectedMap >= Index)
4555 {
4556 --m_SelectedMap;
4557 }
4558 }
4559}
4560
4561IGraphics::CTextureHandle CEditor::GetFrontTexture()
4562{
4563 if(!m_FrontTexture.IsValid())
4564 m_FrontTexture = Graphics()->LoadTexture(pFilename: "editor/front.png", StorageType: IStorage::TYPE_ALL, Flags: Graphics()->TextureLoadFlags());
4565 return m_FrontTexture;
4566}
4567
4568IGraphics::CTextureHandle CEditor::GetTeleTexture()
4569{
4570 if(!m_TeleTexture.IsValid())
4571 m_TeleTexture = Graphics()->LoadTexture(pFilename: "editor/tele.png", StorageType: IStorage::TYPE_ALL, Flags: Graphics()->TextureLoadFlags());
4572 return m_TeleTexture;
4573}
4574
4575IGraphics::CTextureHandle CEditor::GetSpeedupTexture()
4576{
4577 if(!m_SpeedupTexture.IsValid())
4578 m_SpeedupTexture = Graphics()->LoadTexture(pFilename: "editor/speedup.png", StorageType: IStorage::TYPE_ALL, Flags: Graphics()->TextureLoadFlags());
4579 return m_SpeedupTexture;
4580}
4581
4582IGraphics::CTextureHandle CEditor::GetSwitchTexture()
4583{
4584 if(!m_SwitchTexture.IsValid())
4585 m_SwitchTexture = Graphics()->LoadTexture(pFilename: "editor/switch.png", StorageType: IStorage::TYPE_ALL, Flags: Graphics()->TextureLoadFlags());
4586 return m_SwitchTexture;
4587}
4588
4589IGraphics::CTextureHandle CEditor::GetTuneTexture()
4590{
4591 if(!m_TuneTexture.IsValid())
4592 m_TuneTexture = Graphics()->LoadTexture(pFilename: "editor/tune.png", StorageType: IStorage::TYPE_ALL, Flags: Graphics()->TextureLoadFlags());
4593 return m_TuneTexture;
4594}
4595
4596IGraphics::CTextureHandle CEditor::GetEntitiesTexture()
4597{
4598 if(!m_EntitiesTexture.IsValid())
4599 m_EntitiesTexture = Graphics()->LoadTexture(pFilename: "editor/entities/DDNet.png", StorageType: IStorage::TYPE_ALL, Flags: Graphics()->TextureLoadFlags());
4600 return m_EntitiesTexture;
4601}
4602
4603void CEditor::Init()
4604{
4605 m_pInput = Kernel()->RequestInterface<IInput>();
4606 m_pClient = Kernel()->RequestInterface<IClient>();
4607 m_pConfigManager = Kernel()->RequestInterface<IConfigManager>();
4608 m_pConfig = m_pConfigManager->Values();
4609 m_pEngine = Kernel()->RequestInterface<IEngine>();
4610 m_pGraphics = Kernel()->RequestInterface<IGraphics>();
4611 m_pTextRender = Kernel()->RequestInterface<ITextRender>();
4612 m_pStorage = Kernel()->RequestInterface<IStorage>();
4613 m_pSound = Kernel()->RequestInterface<ISound>();
4614 m_UI.Init(pKernel: Kernel());
4615 m_UI.SetDispatchInputCallback([this](const IInput::CEvent &Event) {
4616 OnInput(Event);
4617 });
4618 m_RenderMap.Init(pGraphics: m_pGraphics, pTextRender: m_pTextRender);
4619
4620 Reset();
4621 AddDefaultMap();
4622
4623 m_vComponents.emplace_back(args&: m_MapView);
4624 m_vComponents.emplace_back(args&: m_EnvelopeEditor);
4625 m_vComponents.emplace_back(args&: m_MapSettingsBackend);
4626 m_vComponents.emplace_back(args&: m_LayerSelector);
4627 m_vComponents.emplace_back(args&: m_FileBrowser);
4628 m_vComponents.emplace_back(args&: m_Prompt);
4629 m_vComponents.emplace_back(args&: m_FontTyper);
4630 m_vComponents.emplace_back(args&: m_QuadKnife);
4631 for(CEditorComponent &Component : m_vComponents)
4632 Component.OnInit(pEditor: this);
4633
4634 m_CheckerTexture = Graphics()->LoadTexture(pFilename: "editor/checker.png", StorageType: IStorage::TYPE_ALL);
4635 m_aCursorTextures[CURSOR_NORMAL] = Graphics()->LoadTexture(pFilename: "editor/cursor.png", StorageType: IStorage::TYPE_ALL);
4636 m_aCursorTextures[CURSOR_RESIZE_H] = Graphics()->LoadTexture(pFilename: "editor/cursor_resize.png", StorageType: IStorage::TYPE_ALL);
4637 m_aCursorTextures[CURSOR_RESIZE_V] = m_aCursorTextures[CURSOR_RESIZE_H];
4638
4639 m_pToolsMap = std::make_unique<CEditorMap>(args: this);
4640
4641 m_pTilesetPicker = std::make_shared<CLayerTiles>(args: m_pToolsMap.get(), args: 16, args: 16);
4642 m_pTilesetPicker->MakePalette();
4643 m_pTilesetPicker->m_Readonly = true;
4644 m_pTilesetPicker->m_RenderOverlays = false;
4645
4646 m_pQuadsetPicker = std::make_shared<CLayerQuads>(args: m_pToolsMap.get());
4647 m_pQuadsetPicker->NewQuad(x: 0, y: 0, Width: 64, Height: 64);
4648 m_pQuadsetPicker->m_Readonly = true;
4649
4650 m_pBrush = std::make_shared<CLayerGroup>(args: m_pToolsMap.get());
4651}
4652
4653bool CEditor::HasUnsavedData() const
4654{
4655 return std::any_of(first: m_vpMaps.begin(), last: m_vpMaps.end(), pred: [](const auto &pMap) { return pMap->m_Modified; });
4656}
4657
4658void CEditor::MouseAxisLock(vec2 &CursorRel)
4659{
4660 if(Input()->AltIsPressed())
4661 {
4662 // only lock with the paint brush and inside editor map area to avoid duplicate Alt behavior
4663 if(m_pBrush->IsEmpty() || Ui()->HotItem() != MapView())
4664 return;
4665
4666 const vec2 CurrentWorldPos = MapView()->MouseWorldPos() / 32.0f;
4667
4668 if(m_MouseAxisLockState == EAxisLock::START)
4669 {
4670 m_MouseAxisInitialPos = CurrentWorldPos;
4671 m_MouseAxisLockState = EAxisLock::NONE;
4672 return; // delta would be 0, calculate it in next frame
4673 }
4674
4675 const vec2 Delta = CurrentWorldPos - m_MouseAxisInitialPos;
4676
4677 // lock to axis if moved mouse by 1 block
4678 if(m_MouseAxisLockState == EAxisLock::NONE && (std::abs(x: Delta.x) > 1.0f || std::abs(x: Delta.y) > 1.0f))
4679 {
4680 m_MouseAxisLockState = (std::abs(x: Delta.x) > std::abs(x: Delta.y)) ? EAxisLock::HORIZONTAL : EAxisLock::VERTICAL;
4681 }
4682
4683 if(m_MouseAxisLockState == EAxisLock::HORIZONTAL)
4684 {
4685 CursorRel.y = 0;
4686 }
4687 else if(m_MouseAxisLockState == EAxisLock::VERTICAL)
4688 {
4689 CursorRel.x = 0;
4690 }
4691 }
4692 else
4693 {
4694 m_MouseAxisLockState = EAxisLock::START;
4695 }
4696}
4697
4698void CEditor::HandleAutosave()
4699{
4700 const float Time = Client()->GlobalTime();
4701 const float LastAutosaveUpdateTime = m_LastAutosaveUpdateTime;
4702 m_LastAutosaveUpdateTime = Time;
4703
4704 if(g_Config.m_EdAutosaveInterval == 0)
4705 {
4706 return; // autosave disabled
4707 }
4708
4709 const auto &&ErrorHandler = [this](const char *pErrorMessage) {
4710 ShowFileDialogError(pFormat: "%s", pErrorMessage);
4711 log_error("editor/autosave", "%s", pErrorMessage);
4712 };
4713 for(const auto &pMap : m_vpMaps)
4714 {
4715 if(!pMap->m_ModifiedAuto || pMap->m_LastModifiedTime < 0.0f)
4716 {
4717 continue; // no unsaved changes
4718 }
4719
4720 // Add time to autosave timer if the editor was disabled for more than 10 seconds,
4721 // to prevent autosave from immediately activating when the editor is activated
4722 // after being deactivated for some time.
4723 if(LastAutosaveUpdateTime >= 0.0f && Time - LastAutosaveUpdateTime > 10.0f)
4724 {
4725 pMap->m_LastSaveTime += Time - LastAutosaveUpdateTime;
4726 }
4727
4728 // Check if autosave timer has expired.
4729 if(pMap->m_LastSaveTime >= Time || Time - pMap->m_LastSaveTime < 60 * g_Config.m_EdAutosaveInterval)
4730 {
4731 continue;
4732 }
4733
4734 // Wait for 5 seconds of no modification before saving, to prevent autosave
4735 // from immediately activating when a map is first modified or while user is
4736 // modifying the map, but don't delay the autosave for more than 1 minute.
4737 if(Time - pMap->m_LastModifiedTime < 5.0f && Time - pMap->m_LastSaveTime < 60 * (g_Config.m_EdAutosaveInterval + 1))
4738 {
4739 continue;
4740 }
4741
4742 pMap->PerformAutosave(ErrorHandler);
4743 }
4744}
4745
4746void CEditor::HandleWriterFinishJobs()
4747{
4748 if(m_WriterFinishJobs.empty())
4749 return;
4750
4751 std::shared_ptr<CDataFileWriterFinishJob> pJob = m_WriterFinishJobs.front();
4752 if(!pJob->Done())
4753 return;
4754 m_WriterFinishJobs.pop_front();
4755
4756 const char *pErrorMessage = pJob->ErrorMessage();
4757 if(pErrorMessage[0] != '\0')
4758 {
4759 ShowFileDialogError(pFormat: "%s", pErrorMessage);
4760 return;
4761 }
4762
4763 auto MapIt = std::find_if(first: m_vpMaps.begin(), last: m_vpMaps.end(), pred: [&](const std::unique_ptr<CEditorMap> &pMap) {
4764 return str_comp(a: pMap->m_aFilename, b: pJob->RealFilename()) == 0;
4765 });
4766 if(MapIt != m_vpMaps.end())
4767 {
4768 const auto &pMap = *MapIt;
4769 if(pMap->m_CloseOnSave)
4770 {
4771 dbg_assert(!pMap->m_Modified, "Map to be closed was modified, should be prevented in OnModify");
4772 CloseMap(Index: MapIt - m_vpMaps.begin(), Confirm: false);
4773 }
4774 }
4775
4776 // send rcon.. if we can
4777 if(Client()->RconAuthed() && g_Config.m_EdAutoMapReload)
4778 {
4779 const CServerInfo &CurrentServerInfo = Client()->ServerInfo();
4780 if(net_addr_is_local(addr: &Client()->ServerAddress()))
4781 {
4782 char aMapName[MAX_MAP_LENGTH];
4783 fs_split_file_extension(filename: fs_filename(path: pJob->RealFilename()), name: aMapName, name_size: sizeof(aMapName));
4784 if(!str_comp(a: aMapName, b: CurrentServerInfo.m_aMap))
4785 Client()->Rcon(pLine: "hot_reload");
4786 }
4787 }
4788}
4789
4790bool CEditor::IsSaving(const char *pFilename) const
4791{
4792 return std::any_of(first: std::begin(cont: m_WriterFinishJobs), last: std::end(cont: m_WriterFinishJobs), pred: [&](const std::shared_ptr<CDataFileWriterFinishJob> &Job) {
4793 return str_comp(a: pFilename, b: Job->RealFilename()) == 0;
4794 });
4795}
4796
4797void CEditor::UpdateMapDisplayNames()
4798{
4799 std::unordered_map<std::string, int> Occurrences;
4800 for(const auto &pMap : m_vpMaps)
4801 {
4802 auto It = Occurrences.find(key: pMap->m_aFilename);
4803 if(It == Occurrences.end())
4804 {
4805 Occurrences.emplace(args&: pMap->m_aFilename, args: 1);
4806 }
4807 else
4808 {
4809 It->second++;
4810 }
4811 }
4812 std::unordered_map<std::string, int> Counts;
4813 for(const auto &pMap : m_vpMaps)
4814 {
4815 if(pMap->m_aFilename[0] == '\0')
4816 {
4817 str_copy(dst&: pMap->m_aDisplayName, src: "Unnamed");
4818 str_copy(dst&: pMap->m_aAutosaveName, src: "unnamed");
4819 }
4820 else
4821 {
4822 fs_split_file_extension(filename: fs_filename(path: pMap->m_aFilename), name: pMap->m_aDisplayName, name_size: sizeof(pMap->m_aDisplayName));
4823 str_copy(dst&: pMap->m_aAutosaveName, src: pMap->m_aDisplayName);
4824 }
4825 if(Occurrences[pMap->m_aFilename] <= 1)
4826 {
4827 continue;
4828 }
4829
4830 auto Count = Counts.find(key: pMap->m_aFilename);
4831 if(Count == Counts.end())
4832 {
4833 Count = Counts.emplace(args&: pMap->m_aFilename, args: 1).first;
4834 }
4835 else
4836 {
4837 Count->second++;
4838 }
4839 char aNum[16];
4840 str_format(buffer: aNum, buffer_size: sizeof(aNum), format: " (%d)", Count->second);
4841 str_append(dst&: pMap->m_aDisplayName, src: aNum);
4842 str_format(buffer: aNum, buffer_size: sizeof(aNum), format: "_%02d", Count->second);
4843 str_append(dst&: pMap->m_aAutosaveName, src: aNum);
4844 }
4845}
4846
4847void CEditor::OnUpdate()
4848{
4849 CUIElementBase::Init(pUI: Ui()); // update static pointer because game and editor use separate UI
4850
4851 m_pContainerPannedLast = m_pContainerPanned;
4852
4853 // handle mouse movement
4854 vec2 CursorRel = vec2(0.0f, 0.0f);
4855 IInput::ECursorType CursorType = Input()->CursorRelative(pX: &CursorRel.x, pY: &CursorRel.y);
4856 if(CursorType != IInput::CURSOR_NONE)
4857 {
4858 Ui()->ConvertMouseMove(pX: &CursorRel.x, pY: &CursorRel.y, CursorType);
4859 MouseAxisLock(CursorRel);
4860 Ui()->OnCursorMove(X: CursorRel.x, Y: CursorRel.y);
4861 }
4862
4863 // handle key presses
4864 Input()->ConsumeEvents(Consumer: [&](const IInput::CEvent &Event) {
4865 OnInput(Event);
4866 });
4867
4868 MapView()->UpdateMouseWorld();
4869 LayerSelector()->UpdateHoveredTiles();
4870 HandleAutosave();
4871 HandleWriterFinishJobs();
4872
4873 for(CEditorComponent &Component : m_vComponents)
4874 Component.OnUpdate();
4875}
4876
4877void CEditor::OnInput(const IInput::CEvent &Event)
4878{
4879 if(m_Dialog == DIALOG_NONE && CLineInput::GetActiveInput() == nullptr && Event.m_Key == KEY_F1)
4880 {
4881 if((Event.m_Flags & IInput::FLAG_PRESS) != 0 && (Event.m_Flags & IInput::FLAG_REPEAT) == 0)
4882 {
4883 m_QuickActionShowHelp.Call();
4884 }
4885 return;
4886 }
4887
4888 for(CEditorComponent &Component : m_vComponents)
4889 {
4890 // Events with flag `FLAG_RELEASE` must always be forwarded to all components so keys being
4891 // released can be handled in all components also after some components have been disabled.
4892 if(Component.OnInput(Event) && (Event.m_Flags & ~IInput::FLAG_RELEASE) != 0)
4893 return;
4894 }
4895 Ui()->OnInput(Event);
4896}
4897
4898void CEditor::OnRender()
4899{
4900 Ui()->SetMouseSlow(false);
4901
4902 // toggle gui
4903 if(m_Dialog == DIALOG_NONE &&
4904 CLineInput::GetActiveInput() == nullptr &&
4905 !Input()->ModifierIsPressed() &&
4906 !Input()->ShiftIsPressed() &&
4907 Input()->KeyPress(Key: KEY_TAB))
4908 {
4909 m_GuiActive = !m_GuiActive;
4910 }
4911
4912 if(Input()->KeyPress(Key: KEY_F10))
4913 m_ShowMousePointer = false;
4914
4915 if(Map()->m_EnvelopeEvaluator.m_Animate)
4916 Map()->m_EnvelopeEvaluator.m_AnimateTime = Client()->GlobalTime() - Map()->m_EnvelopeEvaluator.m_AnimateStart;
4917
4918 m_pUiGotContext = nullptr;
4919 Ui()->StartCheck();
4920
4921 Ui()->Update();
4922
4923 Ui()->DoBackButton();
4924
4925 Render();
4926
4927 MapView()->ResetMouseDeltaWorld();
4928
4929 if(Input()->KeyPress(Key: KEY_F10))
4930 {
4931 Graphics()->TakeScreenshot(pFilename: nullptr);
4932 m_ShowMousePointer = true;
4933 }
4934
4935 if(g_Config.m_Debug)
4936 Ui()->DebugRender(X: 2.0f, Y: Ui()->Screen()->h - 27.0f);
4937
4938 Ui()->FinishCheck();
4939 Ui()->ClearHotkeys();
4940 Input()->Clear();
4941
4942 CLineInput::RenderCandidates();
4943
4944#if defined(CONF_DEBUG)
4945 Map()->CheckIntegrity();
4946#endif
4947}
4948
4949void CEditor::OnActivate()
4950{
4951 ResetMentions();
4952 ResetIngameMoved();
4953}
4954
4955void CEditor::OnWindowResize()
4956{
4957 Ui()->OnWindowResize();
4958}
4959
4960void CEditor::OnClose()
4961{
4962 m_ColorPipetteActive = false;
4963
4964 if(m_ToolbarPreviewSound >= 0 && Sound()->IsPlaying(SampleId: m_ToolbarPreviewSound))
4965 Sound()->Pause(SampleId: m_ToolbarPreviewSound);
4966
4967 m_FileBrowser.OnEditorClose();
4968}
4969
4970void CEditor::OnDialogClose()
4971{
4972 m_Dialog = DIALOG_NONE;
4973 m_CloseMapAfterSave = false;
4974 m_FileBrowser.OnDialogClose();
4975}
4976
4977void CEditor::LoadIngameMap()
4978{
4979 CGameClient *pGameClient = (CGameClient *)Kernel()->RequestInterface<IGameClient>();
4980
4981 if(Load(pFilename: pGameClient->Map()->Path(), StorageType: IStorage::TYPE_SAVE))
4982 {
4983 Map()->m_ValidSaveFilename = !str_startswith(str: pGameClient->Map()->Path(), prefix: "downloadedmaps/");
4984 }
4985 else
4986 {
4987 Load(pFilename: pGameClient->Map()->Path(), StorageType: IStorage::TYPE_ALL);
4988 Map()->m_ValidSaveFilename = false;
4989 }
4990
4991 vec2 Center = pGameClient->m_Camera.m_Center;
4992 MapView()->SetWorldOffset(Center);
4993}
4994
4995bool CEditor::Save(const char *pFilename)
4996{
4997 if(IsSaving(pFilename))
4998 {
4999 return false;
5000 }
5001
5002 const auto &&ErrorHandler = [this](const char *pErrorMessage) {
5003 ShowFileDialogError(pFormat: "%s", pErrorMessage);
5004 log_error("editor/save", "%s", pErrorMessage);
5005 };
5006 return Map()->Save(pFilename, ErrorHandler);
5007}
5008
5009bool CEditor::HandleMapDrop(const char *pFilename, int StorageType)
5010{
5011 OnDialogClose();
5012 return Load(pFilename, StorageType);
5013}
5014
5015bool CEditor::Load(const char *pFilename, int StorageType)
5016{
5017 const auto &&ErrorHandler = [this](const char *pErrorMessage) {
5018 ShowFileDialogError(pFormat: "%s", pErrorMessage);
5019 log_error("editor/load", "%s", pErrorMessage);
5020 };
5021
5022 Reset();
5023 std::unique_ptr<CEditorMap> pNewMap = std::make_unique<CEditorMap>(args: this);
5024 const bool Result = pNewMap->Load(pFilename, StorageType, ErrorHandler: std::move(ErrorHandler));
5025 if(Result)
5026 {
5027 m_vpMaps.push_back(x: std::move(pNewMap));
5028 m_SelectedMap = m_vpMaps.size() - 1;
5029 m_MapTabsRevealSelected = true;
5030 UpdateMapDisplayNames();
5031
5032 for(CEditorComponent &Component : m_vComponents)
5033 Component.OnMapLoad();
5034
5035 log_info("editor/load", "Loaded map '%s'", Map()->m_aFilename);
5036 }
5037 return Result;
5038}
5039
5040CEditorMap *CEditor::Map()
5041{
5042 dbg_assert(m_SelectedMap < m_vpMaps.size(), "Invalid m_SelectedMap: %" PRIzu, m_SelectedMap);
5043 return m_vpMaps[m_SelectedMap].get();
5044}
5045
5046const CEditorMap *CEditor::Map() const
5047{
5048 dbg_assert(m_SelectedMap < m_vpMaps.size(), "Invalid m_SelectedMap: %" PRIzu, m_SelectedMap);
5049 return m_vpMaps[m_SelectedMap].get();
5050}
5051
5052CEditorHistory &CEditor::ActiveHistory()
5053{
5054 if(m_ActiveExtraEditor == EXTRAEDITOR_SERVER_SETTINGS)
5055 {
5056 return Map()->m_ServerSettingsHistory;
5057 }
5058 else if(m_ActiveExtraEditor == EXTRAEDITOR_ENVELOPES)
5059 {
5060 return Map()->m_EnvelopeEditorHistory;
5061 }
5062 else
5063 {
5064 return Map()->m_EditorHistory;
5065 }
5066}
5067
5068void CEditor::AdjustBrushSpecialTiles(bool UseNextFree, int AdjustModifiers, int AdjustValue)
5069{
5070 // Adjust m_Angle of speedup or m_Number field of tune, switch and tele tiles by `Adjust` if `UseNextFree` is false
5071 // If `AdjustValue` is 0 and `UseNextFree` is false, then update numbers of brush tiles to global values
5072 // If true, then use the next free number instead
5073
5074 dbg_assert(AdjustValue == -1 || AdjustValue == 0 || AdjustValue == 1, "Invalid AdjustValue: %d", AdjustValue);
5075 auto &&AdjustNumber = [AdjustValue](auto &Number, int Min, int Max) {
5076 const int NumberInt = Number + AdjustValue; // Cast to int so this does not overflow unsigned char for some tiles
5077 if(NumberInt < Min)
5078 {
5079 Number = Max;
5080 }
5081 else if(NumberInt > Max)
5082 {
5083 Number = Min;
5084 }
5085 else
5086 {
5087 Number = NumberInt;
5088 }
5089 };
5090
5091 for(auto &pLayer : m_pBrush->m_vpLayers)
5092 {
5093 if(pLayer->m_Type != LAYERTYPE_TILES)
5094 continue;
5095
5096 std::shared_ptr<CLayerTiles> pLayerTiles = std::static_pointer_cast<CLayerTiles>(r: pLayer);
5097
5098 if(pLayerTiles->m_HasTele && (!UseNextFree || Map()->m_pTeleLayer != nullptr))
5099 {
5100 const int NextFreeTeleNumber = UseNextFree ? Map()->m_pTeleLayer->FindNextFreeNumber(Checkpoint: false) : 0;
5101 const int NextFreeCheckpointNumber = UseNextFree ? Map()->m_pTeleLayer->FindNextFreeNumber(Checkpoint: true) : 0;
5102 std::shared_ptr<CLayerTele> pTeleLayer = std::static_pointer_cast<CLayerTele>(r: pLayer);
5103 for(int y = 0; y < pTeleLayer->m_Height; y++)
5104 {
5105 for(int x = 0; x < pTeleLayer->m_Width; x++)
5106 {
5107 int i = y * pTeleLayer->m_Width + x;
5108 if(!IsValidTeleTile(Index: pTeleLayer->m_pTiles[i].m_Index) || (!UseNextFree && !pTeleLayer->m_pTeleTile[i].m_Number))
5109 continue;
5110
5111 if(UseNextFree)
5112 {
5113 if(IsTeleTileCheckpoint(Index: pTeleLayer->m_pTiles[i].m_Index))
5114 pTeleLayer->m_pTeleTile[i].m_Number = NextFreeCheckpointNumber;
5115 else if(IsTeleTileNumberUsedAny(Index: pTeleLayer->m_pTiles[i].m_Index))
5116 pTeleLayer->m_pTeleTile[i].m_Number = NextFreeTeleNumber;
5117 }
5118 else if(AdjustValue == 0)
5119 {
5120 if(IsTeleTileCheckpoint(Index: pTeleLayer->m_pTiles[i].m_Index))
5121 pTeleLayer->m_pTeleTile[i].m_Number = m_TeleCheckpointNumber;
5122 else if(IsTeleTileNumberUsedAny(Index: pTeleLayer->m_pTiles[i].m_Index))
5123 pTeleLayer->m_pTeleTile[i].m_Number = m_TeleNumber;
5124 }
5125 else if(AdjustModifiers == 0)
5126 {
5127 AdjustNumber(pTeleLayer->m_pTeleTile[i].m_Number, 1, 255);
5128 }
5129 }
5130 }
5131 }
5132 else if(pLayerTiles->m_HasTune && (!UseNextFree || Map()->m_pTuneLayer != nullptr))
5133 {
5134 const int NextFreeNumber = UseNextFree ? Map()->m_pTuneLayer->FindNextFreeNumber() : 0;
5135 std::shared_ptr<CLayerTune> pTuneLayer = std::static_pointer_cast<CLayerTune>(r: pLayer);
5136 for(int y = 0; y < pTuneLayer->m_Height; y++)
5137 {
5138 for(int x = 0; x < pTuneLayer->m_Width; x++)
5139 {
5140 int i = y * pTuneLayer->m_Width + x;
5141 if(!IsValidTuneTile(Index: pTuneLayer->m_pTiles[i].m_Index) || (!UseNextFree && !pTuneLayer->m_pTuneTile[i].m_Number))
5142 continue;
5143
5144 if(UseNextFree)
5145 {
5146 pTuneLayer->m_pTuneTile[i].m_Number = NextFreeNumber;
5147 }
5148 else if(AdjustModifiers == 0)
5149 {
5150 AdjustNumber(pTuneLayer->m_pTuneTile[i].m_Number, 1, 255);
5151 }
5152 }
5153 }
5154 }
5155 else if(pLayerTiles->m_HasSwitch && (!UseNextFree || Map()->m_pSwitchLayer != nullptr))
5156 {
5157 const int NextFreeNumber = UseNextFree ? Map()->m_pSwitchLayer->FindNextFreeNumber() : 0;
5158 std::shared_ptr<CLayerSwitch> pSwitchLayer = std::static_pointer_cast<CLayerSwitch>(r: pLayer);
5159 for(int y = 0; y < pSwitchLayer->m_Height; y++)
5160 {
5161 for(int x = 0; x < pSwitchLayer->m_Width; x++)
5162 {
5163 int i = y * pSwitchLayer->m_Width + x;
5164 if(!IsValidSwitchTile(Index: pSwitchLayer->m_pTiles[i].m_Index) || (!UseNextFree && !pSwitchLayer->m_pSwitchTile[i].m_Number))
5165 continue;
5166
5167 if(UseNextFree)
5168 {
5169 pSwitchLayer->m_pSwitchTile[i].m_Number = NextFreeNumber;
5170 }
5171 else if(AdjustModifiers == 0)
5172 {
5173 AdjustNumber(pSwitchLayer->m_pSwitchTile[i].m_Number, 1, 255);
5174 }
5175 else if(AdjustModifiers == 1)
5176 {
5177 AdjustNumber(pSwitchLayer->m_pSwitchTile[i].m_Delay, 0, 255);
5178 }
5179 }
5180 }
5181 }
5182 else if(pLayerTiles->m_HasSpeedup && !UseNextFree)
5183 {
5184 std::shared_ptr<CLayerSpeedup> pSpeedupLayer = std::static_pointer_cast<CLayerSpeedup>(r: pLayer);
5185 for(int y = 0; y < pSpeedupLayer->m_Height; y++)
5186 {
5187 for(int x = 0; x < pSpeedupLayer->m_Width; x++)
5188 {
5189 int i = y * pSpeedupLayer->m_Width + x;
5190 if(!IsValidSpeedupTile(Index: pSpeedupLayer->m_pTiles[i].m_Index))
5191 continue;
5192
5193 if(AdjustValue == 0)
5194 {
5195 pSpeedupLayer->m_pSpeedupTile[i].m_Angle = m_SpeedupAngle;
5196 pSpeedupLayer->m_SpeedupAngle = m_SpeedupAngle;
5197 }
5198 else if(AdjustModifiers == 0)
5199 {
5200 AdjustNumber(pSpeedupLayer->m_pSpeedupTile[i].m_Angle, 0, 359);
5201 }
5202 else if(AdjustModifiers == 1)
5203 {
5204 AdjustNumber(pSpeedupLayer->m_pSpeedupTile[i].m_Force, 1, 255);
5205 }
5206 else if(AdjustModifiers == 2)
5207 {
5208 AdjustNumber(pSpeedupLayer->m_pSpeedupTile[i].m_MaxSpeed, 0, 255);
5209 }
5210 }
5211 }
5212 }
5213 }
5214}
5215
5216IEditor *CreateEditor() { return new CEditor; }
5217