/
Map.cpp
1588 lines (1286 loc) · 43.3 KB
/
Map.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Map.h"
#include "i18n.h"
#include <ostream>
#include <fstream>
#include "itextstream.h"
#include "iscenegraph.h"
#include "icameraview.h"
#include "imodel.h"
#include "igrid.h"
#include "ifilesystem.h"
#include "ifiletypes.h"
#include "iselectiongroup.h"
#include "ifilter.h"
#include "icounter.h"
#include "iradiant.h"
#include "imapresource.h"
#include "imapinfofile.h"
#include "iaasfile.h"
#include "igame.h"
#include "imru.h"
#include "imapformat.h"
#include "registry/registry.h"
#include "entitylib.h"
#include "gamelib.h"
#include "os/path.h"
#include "os/file.h"
#include "time/ScopeTimer.h"
#include "brush/BrushModule.h"
#include "scene/BasicRootNode.h"
#include "scene/PrefabBoundsAccumulator.h"
#include "map/MapFileManager.h"
#include "map/MapPositionManager.h"
#include "map/MapResource.h"
#include "map/algorithm/Import.h"
#include "map/algorithm/Export.h"
#include "scene/Traverse.h"
#include "map/algorithm/MapExporter.h"
#include "model/export/ModelExporter.h"
#include "model/export/ModelScalePreserver.h"
#include "messages/ScopedLongRunningOperation.h"
#include "messages/FileOverwriteConfirmation.h"
#include "messages/FileSaveConfirmation.h"
#include "messages/MapOperationMessage.h"
#include "selection/algorithm/Primitives.h"
#include "selection/algorithm/Group.h"
#include "scene/Group.h"
#include "selection/algorithm/Transformation.h"
#include "module/StaticModule.h"
#include "command/ExecutionNotPossible.h"
#include "MapPropertyInfoFileModule.h"
#include "messages/NotificationMessage.h"
#include <fmt/format.h>
#include "messages/MapFileOperation.h"
#include "scene/ChildPrimitives.h"
#include "scene/merge/GraphComparer.h"
#include "scene/merge/MergeOperation.h"
#include "scene/merge/ThreeWayMergeOperation.h"
#include "scene/merge/MergeLib.h"
namespace map
{
namespace
{
const char* const MAP_UNNAMED_STRING = N_("unnamed.map");
}
Map::Map() :
_lastCopyMapName(""),
_modified(false),
_saveInProgress(false),
_shutdownListener(0)
{}
void Map::clearMapResource()
{
// Map is unnamed or load failed, reset map resource node to empty
_resource->clear();
_resource->getRootNode()->getUndoChangeTracker().setSavedChangeCount();
// Rename the map to "unnamed" in any case to avoid overwriting the failed map
setMapName(_(MAP_UNNAMED_STRING));
}
void Map::connectToRootNode()
{
_modifiedStatusListener.disconnect();
_undoEventListener.disconnect();
_layerHierarchyChangedListener.disconnect();
_modifiedStatusListener = _resource->signal_modifiedStatusChanged().connect(
[this](bool newStatus) { setModified(newStatus); }
);
if (!_resource->getRootNode()) return;
_undoEventListener = _resource->getRootNode()->getUndoSystem().signal_undoEvent().connect(
sigc::mem_fun(*this, &Map::onUndoEvent)
);
// This is a workaround - changing layer hierarchies is not an undoable operation
// and this by hitting undo or redo the status might be reset to "unmodified" anytime
_layerHierarchyChangedListener = _resource->getRootNode()->getLayerManager()
.signal_layerHierarchyChanged().connect(sigc::mem_fun(*this, &Map::onLayerHierarchyChanged));
}
void Map::onLayerHierarchyChanged()
{
setModified(true);
}
void Map::onUndoEvent(IUndoSystem::EventType type, const std::string& operationName)
{
switch (type)
{
case IUndoSystem::EventType::OperationRecorded:
OperationMessage::Send(operationName);
break;
case IUndoSystem::EventType::OperationUndone:
_mapPostUndoSignal.emit();
OperationMessage::Send(fmt::format(_("Undo: {0}"), operationName));
break;
case IUndoSystem::EventType::OperationRedone:
_mapPostRedoSignal.emit();
OperationMessage::Send(fmt::format(_("Redo: {0}"), operationName));
break;
}
}
void Map::loadMapResourceFromPath(const std::string& path)
{
// Create a MapLocation defining a physical file, and forward the call
loadMapResourceFromLocation(MapLocation{path, false, ""});
}
void Map::loadMapResourceFromArchive(const std::string& archive, const std::string& archiveRelativePath)
{
// Create a MapLocation defining an archive file, and forward the call
loadMapResourceFromLocation(MapLocation{ archive, true, archiveRelativePath });
}
void Map::loadMapResourceFromLocation(const MapLocation& location)
{
rMessage() << "Loading map from " << location.path <<
(location.isArchive ? " [" + location.archiveRelativePath + "]" : "") << std::endl;
// Map loading started
emitMapEvent(MapLoading);
// Abort any ongoing merge
abortMergeOperation();
_resource = location.isArchive ?
GlobalMapResourceManager().createFromArchiveFile(location.path, location.archiveRelativePath) :
GlobalMapResourceManager().createFromPath(location.path);
assert(_resource);
try
{
util::ScopeTimer timer("map load");
if (isUnnamed() || !_resource->load())
{
clearMapResource();
}
}
catch (const IMapResource::OperationException& ex)
{
radiant::NotificationMessage::SendError(ex.what());
clearMapResource();
}
connectToRootNode();
// Take the new node and insert it as map root
GlobalSceneGraph().setRoot(_resource->getRootNode());
// Traverse the scenegraph and find the worldspawn
findWorldspawn();
// Associate the Scenegaph with the global RenderSystem
// This usually takes a while since all editor textures are loaded - display a dialog to inform the user
{
radiant::ScopedLongRunningOperation blocker(_("Loading textures..."));
assignRenderSystem(GlobalSceneGraph().root());
}
// Update layer visibility of all nodes
scene::UpdateNodeVisibilityWalker updater(_resource->getRootNode()->getLayerManager());
_resource->getRootNode()->traverse(updater);
// Map loading finished, emit the signal
emitMapEvent(MapLoaded);
OperationMessage::Send(_("Map loaded"));
rMessage() << "--- LoadMapFile ---\n";
rMessage() << _mapName << "\n";
rMessage() << GlobalCounters().getCounter(counterBrushes).get() << " brushes\n";
rMessage() << GlobalCounters().getCounter(counterPatches).get() << " patches\n";
rMessage() << GlobalCounters().getCounter(counterEntities).get() << " entities\n";
// Let the filtersystem update the filtered status of all instances
GlobalFilterSystem().update();
// Clear the modified flag
setModified(false);
}
void Map::assignRenderSystem(const scene::IMapRootNodePtr& root)
{
root->setRenderSystem(std::dynamic_pointer_cast<RenderSystem>(
module::GlobalModuleRegistry().getModule(MODULE_RENDERSYSTEM)));
}
void Map::finishMergeOperation()
{
if (getEditMode() != EditMode::Merge)
{
rWarning() << "Not in merge edit mode, cannot finish any operation" << std::endl;
return;
}
if (!_mergeOperation)
{
rError() << "Cannot merge, no active operation attached to this map." << std::endl;
return;
}
// Prepare the scene, let the merge nodes know about the upcoming merge
// and remove them from the scene, to leave it untouched
for (const auto& mergeActionNode : _mergeActionNodes)
{
mergeActionNode->prepareForMerge();
scene::removeNodeFromParent(mergeActionNode);
// Clear any references this node holds
mergeActionNode->clear();
}
_mergeActionNodes.clear();
// At this point the scene should look the same as before the merge
{
UndoableCommand cmd("mergeMap");
_mergeOperation->applyActions();
cleanupMergeOperation();
}
setEditMode(EditMode::Normal);
emitMapEvent(IMap::MapMergeOperationFinished);
}
void Map::cleanupMergeOperation()
{
for (const auto& mergeActionNode : _mergeActionNodes)
{
// If the node is already removed from the scene, this does nothing
scene::removeNodeFromParent(mergeActionNode);
// Clear any references this node holds
mergeActionNode->clear();
}
_mergeOperationListener.disconnect();
_mergeActionNodes.clear();
_mergeOperation.reset();
}
void Map::abortMergeOperation()
{
bool mergeWasActive = _mergeOperation != nullptr;
// Remove the nodes and switch back to normal without applying the operation
cleanupMergeOperation();
setEditMode(EditMode::Normal);
if (mergeWasActive)
{
emitMapEvent(IMap::MapMergeOperationAborted);
}
}
scene::merge::IMergeOperation::Ptr Map::getActiveMergeOperation()
{
return _editMode == EditMode::Merge ? _mergeOperation : scene::merge::IMergeOperation::Ptr();
}
void Map::setMapName(const std::string& newName)
{
bool mapNameChanged = _mapName != newName;
// Store the name into the member
_mapName = newName;
// Update the map resource's root node, if there is one
if (_resource)
{
_resource->rename(newName);
}
if (mapNameChanged)
{
// Fire the signal to any observers
signal_mapNameChanged().emit();
}
}
sigc::signal<void()>& Map::signal_mapNameChanged()
{
return _mapNameChangedSignal;
}
std::string Map::getMapName() const {
return _mapName;
}
bool Map::isUnnamed() const {
return _mapName == _(MAP_UNNAMED_STRING);
}
namespace
{
bool pointfileNameMatch(const std::string& candidate, const std::string& mapStem)
{
// A matching point file either has an identical stem to the map file, or the map file stem
// with an underscore suffix (e.g. "mapfile_portal_123_456.lin")
return string::iequals(candidate, mapStem) || string::istarts_with(candidate, mapStem + "_");
}
} // namespace
void Map::forEachPointfile(PointfileFunctor func) const
{
static const char* LIN_EXT = ".lin";
const fs::path map(getMapName());
const fs::path mapDir = map.parent_path();
const fs::path mapStem = map.stem();
// Don't bother trying to iterate over a missing map directory, this will
// just throw an exception.
if (!fs::is_directory(mapDir))
return;
// Iterate over files in the map directory, putting them in a sorted set
std::set<fs::path> paths;
for (const auto& entry: fs::directory_iterator(mapDir))
{
// Ignore anything which isn't a .lin file
auto entryPath = entry.path();
if (entryPath.extension() == LIN_EXT
&& pointfileNameMatch(entryPath.stem().string(), mapStem.string()))
{
paths.insert(entryPath);
}
}
// Call functor on paths in order
for (const fs::path& p: paths)
func(p);
}
void Map::showPointFile(const fs::path& filePath)
{
_pointTrace->show(filePath);
}
bool Map::isPointTraceVisible() const
{
return _pointTrace->isVisible();
}
void Map::onSceneNodeErase(const scene::INodePtr& node)
{
// Detect when worldspawn is removed from the map
if (node == _worldSpawnNode)
{
_worldSpawnNode.reset();
}
}
void Map::setWorldspawn(const scene::INodePtr& node)
{
_worldSpawnNode = node;
}
Map::MapEventSignal Map::signal_mapEvent() const
{
return _mapEvent;
}
Map::EditMode Map::getEditMode()
{
return _editMode;
}
void Map::setEditMode(EditMode mode)
{
_editMode = mode;
if (_editMode == EditMode::Merge)
{
GlobalSelectionSystem().setSelectedAll(false);
GlobalSelectionSystem().setSelectionMode(selection::SelectionMode::MergeAction);
if (getRoot())
{
getRoot()->getRenderSystem()->setMergeModeEnabled(true);
}
}
else
{
GlobalSelectionSystem().setSelectionMode(selection::SelectionMode::Primitive);
if (getRoot())
{
getRoot()->getRenderSystem()->setMergeModeEnabled(false);
}
}
signal_editModeChanged().emit(_editMode);
SceneChangeNotify();
}
sigc::signal<void(IMap::EditMode)>& Map::signal_editModeChanged()
{
return _mapEditModeChangedSignal;
}
const scene::INodePtr& Map::getWorldspawn()
{
return _worldSpawnNode;
}
scene::IMapRootNodePtr Map::getRoot()
{
if (_resource)
{
// Try to cast the node onto a root node and return
return _resource->getRootNode();
}
return scene::IMapRootNodePtr();
}
MapFormatPtr Map::getFormat()
{
return GlobalMapFormatManager().getMapFormatForFilename(_mapName);
}
MapFormatPtr Map::getMapFormatForFilenameSafe(const std::string& filename)
{
auto candidate = GlobalMapFormatManager().getMapFormatForFilename(filename);
// Fall back to the format of the current map if the selection is empty (#5808)
return candidate ? candidate : getFormat();
}
// free all map elements, reinitialize the structures that depend on them
void Map::freeMap()
{
// Abort any ongoing merge
abortMergeOperation();
// Fire the map unloading event,
// This will de-select stuff, clear the pointfile, etc.
emitMapEvent(MapUnloading);
setWorldspawn(scene::INodePtr());
GlobalSceneGraph().setRoot(scene::IMapRootNodePtr());
emitMapEvent(MapUnloaded);
// Reset the resource pointer
_modifiedStatusListener.disconnect();
_resource.reset();
}
bool Map::isModified() const
{
return _modified;
}
void Map::setModified(bool modifiedFlag)
{
if (_modified != modifiedFlag)
{
_modified = modifiedFlag;
// when the map is modified, let the listeners now
signal_modifiedChanged().emit();
}
// Reset the map save timer
_mapSaveTimer.restart();
}
sigc::signal<void()>& Map::signal_modifiedChanged()
{
return _mapModifiedChangedSignal;
}
sigc::signal<void()>& Map::signal_postUndo()
{
return _mapPostUndoSignal;
}
sigc::signal<void()>& Map::signal_postRedo()
{
return _mapPostRedoSignal;
}
IUndoSystem& Map::getUndoSystem()
{
const auto& rootNode = _resource->getRootNode();
if (!rootNode)
{
throw std::runtime_error("No map resource loaded");
}
return rootNode->getUndoSystem();
}
// move the view to a certain position
void Map::focusViews(const Vector3& point, const Vector3& angles)
{
// Set the camera and the views to the given point
GlobalCameraManager().focusAllCameras(point, angles);
// ortho views might not be present in headless mode
if (module::GlobalModuleRegistry().moduleExists(MODULE_ORTHOVIEWMANAGER))
{
GlobalOrthoViewManager().setOrigin(point);
}
}
void Map::focusViewCmd(const cmd::ArgumentList& args)
{
if (args.size() != 2)
{
rWarning() << "Usage: FocusViews <origin:Vector3> <angles:Vector3>" << std::endl;
return;
}
focusViews(args[0].getVector3(), args[1].getVector3());
}
void Map::focusCameraOnSelectionCmd(const cmd::ArgumentList& args)
{
if (GlobalSelectionSystem().countSelected() == 0)
{
throw cmd::ExecutionNotPossible(_("Cannot focus, selection is empty"));
}
// Determine the bounds of the current selection
const auto& workZone = GlobalSelectionSystem().getWorkZone();
auto originAndAngles = scene::getOriginAndAnglesToLookAtBounds(workZone.bounds);
// Set the camera and the views to the given point
GlobalCameraManager().focusAllCameras(originAndAngles.first, originAndAngles.second);
}
scene::INodePtr Map::findWorldspawn()
{
scene::INodePtr worldspawn;
// Traverse the scenegraph and search for the worldspawn
GlobalSceneGraph().root()->foreachNode([&](const scene::INodePtr& node)
{
if (Node_isWorldspawn(node))
{
worldspawn = node;
return false; // done traversing
}
return true;
});
// Set the worldspawn, might be null if nothing was found
setWorldspawn(worldspawn);
return worldspawn;
}
scene::INodePtr Map::createWorldspawn()
{
scene::INodePtr worldspawn(GlobalEntityModule().createEntity(
GlobalEntityClassManager().findOrInsert("worldspawn", true)));
// We want the world spawn entity to go for the pole position
GlobalSceneGraph().root()->addChildNodeToFront(worldspawn);
return worldspawn;
}
const scene::INodePtr& Map::findOrInsertWorldspawn()
{
// If we don't know any worldspawn yet, and can't find one either,
// let's create one afresh
if (!_worldSpawnNode && findWorldspawn() == nullptr)
{
setWorldspawn(createWorldspawn());
}
return _worldSpawnNode;
}
void Map::load(const std::string& filename)
{
setMapName(filename);
loadMapResourceFromPath(_mapName);
}
bool Map::save(const MapFormatPtr& mapFormat)
{
if (_saveInProgress) return false; // safeguard
if (_resource->isReadOnly())
{
rError() << "This map is read-only and cannot be saved." << std::endl;
return false;
}
// Check if the map file has been modified in the meantime
if (_resource->fileOnDiskHasBeenModifiedSinceLastSave() &&
!radiant::FileOverwriteConfirmation::SendAndReceiveAnswer(
fmt::format(_("The file {0} has been modified since it was last saved,\nperhaps by another application. "
"Do you really want to overwrite the file?"), _mapName), _("File modification detected")))
{
return false;
}
_saveInProgress = true;
emitMapEvent(MapSaving);
util::ScopeTimer timer("map save");
bool success = false;
// Save the actual map resource
try
{
_resource->save(mapFormat);
// Clear the modified flag
setModified(false);
success = true;
}
catch (IMapResource::OperationException & ex)
{
radiant::NotificationMessage::SendError(ex.what());
}
emitMapEvent(MapSaved);
OperationMessage::Send(_("Map saved"));
_saveInProgress = false;
// Redraw the views, sometimes the backbuffer containing
// the previous frame will remain visible
SceneChangeNotify();
return success;
}
void Map::createNewMap()
{
setMapName(_(MAP_UNNAMED_STRING));
loadMapResourceFromPath(_mapName);
SceneChangeNotify();
setModified(false);
OperationMessage::Send(_("Empty Map created"));
focusViews(Vector3(0,0,30), Vector3(0,0,0));
}
IMapExporter::Ptr Map::createMapExporter(IMapWriter& writer,
const scene::IMapRootNodePtr& root, std::ostream& mapStream)
{
return std::make_shared<MapExporter>(writer, root, mapStream, 0);
}
bool Map::import(const std::string& filename)
{
bool success = false;
IMapResourcePtr resource = GlobalMapResourceManager().createFromPath(filename);
try
{
if (resource->load())
{
// load() returned TRUE, this means that the resource node
// is not the NULL node
const auto& otherRoot = resource->getRootNode();
// Adjust all new names to fit into the existing map namespace
algorithm::prepareNamesForImport(getRoot(), otherRoot);
algorithm::importMap(otherRoot);
success = true;
}
SceneChangeNotify();
}
catch (const IMapResource::OperationException& ex)
{
radiant::NotificationMessage::SendError(ex.what());
}
return success;
}
void Map::saveDirect(const std::string& filename, const MapFormatPtr& mapFormat)
{
if (_saveInProgress) return; // safeguard
_saveInProgress = true;
MapFormatPtr format = mapFormat;
if (!mapFormat)
{
format = getMapFormatForFilenameSafe(filename);
}
try
{
MapResource::saveFile(*format, GlobalSceneGraph().root(), scene::traverse, filename);
}
catch (const IMapResource::OperationException& ex)
{
radiant::NotificationMessage::SendError(ex.what());
}
_saveInProgress = false;
}
void Map::saveSelected(const std::string& filename, const MapFormatPtr& mapFormat)
{
if (_saveInProgress) return; // safeguard
_saveInProgress = true;
MapFormatPtr format = mapFormat;
if (!format)
{
format = getMapFormatForFilenameSafe(filename);
}
try
{
MapResource::saveFile(
*format,
GlobalSceneGraph().root(),
scene::traverseSelected, // TraversalFunc
filename
);
}
catch (const IMapResource::OperationException& ex)
{
radiant::NotificationMessage::SendError(ex.what());
}
_saveInProgress = false;
}
std::string Map::getSaveConfirmationText() const
{
std::string primaryText = fmt::format(_("Save changes to map \"{0}\"\nbefore closing?"), _mapName);
// Display "x seconds" or "x minutes"
int seconds = static_cast<int>(_mapSaveTimer.getSecondsPassed());
std::string timeString;
if (seconds > 120)
{
timeString = fmt::format(_("{0:d} minutes"), (seconds / 60));
}
else
{
timeString = fmt::format(_("{0:d} seconds"), seconds);
}
std::string secondaryText = fmt::format(
_("If you don't save, changes from the last {0}\nwill be lost."), timeString);
std::string confirmText = fmt::format("{0}\n\n{1}", primaryText, secondaryText);
return confirmText;
}
bool Map::askForSave(const std::string& title)
{
if (!isModified())
{
// Map is not modified, return positive
return true;
}
// Ask the user
auto answer = radiant::FileSaveConfirmation::SendAndReceiveAnswer(getSaveConfirmationText(), title);
if (answer == radiant::FileSaveConfirmation::Action::Cancel)
{
return false;
}
if (answer == radiant::FileSaveConfirmation::Action::SaveChanges)
{
// The user wants to save the map
if (isUnnamed())
{
// Map still unnamed, try to save the map with a new name
// and take the return value from the other routine.
return saveAs();
}
else
{
// Map is named, save it
save();
}
}
// Default behaviour: allow the action
return true;
}
bool Map::saveAs()
{
if (_saveInProgress) return false; // safeguard
auto fileInfo = MapFileManager::getMapFileSelection(false,
_("Save Map"), filetype::TYPE_MAP, getMapName());
if (fileInfo.fullPath.empty())
{
// Invalid filename entered, return false
return false;
}
// Remember the old resource, we might need to revert
auto oldResource = _resource;
// Create a new resource pointing to the given path...
_resource = GlobalMapResourceManager().createFromPath(fileInfo.fullPath);
// ...and import the existing root node into that resource
_resource->setRootNode(oldResource->getRootNode());
// Try to save the resource, this might fail
if (!save(fileInfo.mapFormat))
{
// Failure, revert the change
_resource = oldResource;
return false;
}
connectToRootNode();
// Resource save was successful, notify about this name change
rename(fileInfo.fullPath);
// add an MRU entry on success
GlobalMRU().insert(fileInfo.fullPath);
return true;
}
void Map::saveCopyAs()
{
// Let's see if we can remember a map name from a previous save
if (_lastCopyMapName.empty())
{
_lastCopyMapName = getMapName();
}
auto fileInfo = MapFileManager::getMapFileSelection(false,
_("Save Copy As..."), filetype::TYPE_MAP, _lastCopyMapName);
if (!fileInfo.fullPath.empty())
{
saveCopyAs(fileInfo.fullPath, fileInfo.mapFormat);
}
}
void Map::saveCopyAs(const std::string& absolutePath, const MapFormatPtr& mapFormat)
{
if (absolutePath.empty())
{
rWarning() << "Map::saveCopyAs: path must not be empty" << std::endl;
return;
}
// Remember the last name
_lastCopyMapName = absolutePath;
// Return the result of the actual save method
saveDirect(absolutePath, mapFormat);
}
void Map::loadPrefabAt(const cmd::ArgumentList& args)
{
if (args.size() < 2 || args.size() > 4)
{
rWarning() << "Usage: " << LOAD_PREFAB_AT_CMD <<
" <prefabPath:String> <targetCoords:Vector3> [insertAsGroup:0|1] [recalculatePrefabOrigin:0|1]" << std::endl;
return;
}
auto prefabPath = args[0].getString();
auto targetCoords = args[1].getVector3();
auto insertAsGroup = args.size() > 2 ? args[2].getBoolean() : false;
auto recalculatePrefabOrigin = args.size() > 3 ? args[3].getBoolean() : true;
if (!prefabPath.empty())
{
UndoableCommand undo("loadPrefabAt");
// Deselect everything
GlobalSelectionSystem().setSelectedAll(false);
// Now import the prefab (imported items get selected)
import(prefabPath);
// Get the selection bounds, snap its origin to the grid
scene::PrefabBoundsAccumulator accumulator;
GlobalSelectionSystem().foreachSelected(accumulator);
if (recalculatePrefabOrigin)
{
auto prefabCenter = accumulator.getBounds().getOrigin().getSnapped(GlobalGrid().getGridSize());
// Switch texture lock on
bool prevTexLockState = GlobalBrush().textureLockEnabled();
GlobalBrush().setTextureLock(true);
// Translate the selection to the given point
selection::algorithm::translateSelected(targetCoords - prefabCenter);
// Revert to previous state
GlobalBrush().setTextureLock(prevTexLockState);
}
// Check whether we should group the prefab parts
if (insertAsGroup && GlobalSelectionSystem().countSelected() > 1)
{
try
{
selection::groupSelected();
}
catch (cmd::ExecutionNotPossible& ex)
{
// Ignore grouping errors on prefab insert, just log the message
rError() << "Error grouping the prefab: " << ex.what() << std::endl;
}
}
}
}
void Map::saveMapCopyAs(const cmd::ArgumentList& args)
{
if (args.size() == 0 || args[0].getString().empty())
{
// Use the overload without arguments, it will ask for a file name
saveCopyAs();
}
else
{
// Pass the first argument we got
saveCopyAs(args[0].getString());
}
}
void Map::saveAutomaticMapBackup(const cmd::ArgumentList& args)
{
// Use the saveDirect routine to not change with the _lastCopyMapName member
saveDirect(args[0].getString());
}