/
MapSavingLoading.cpp
1178 lines (877 loc) · 41.1 KB
/
MapSavingLoading.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 "RadiantTest.h"
#include <fstream>
#include "iundo.h"
#include "imap.h"
#include "imapformat.h"
#include "ifilesystem.h"
#include "iradiant.h"
#include "iselectiongroup.h"
#include "ilightnode.h"
#include "icommandsystem.h"
#include "messages/FileSelectionRequest.h"
#include "messages/FileOverwriteConfirmation.h"
#include "messages/MapFileOperation.h"
#include "algorithm/Scene.h"
#include "algorithm/XmlUtils.h"
#include "algorithm/Primitives.h"
#include "os/file.h"
#include <sigc++/connection.h>
using namespace std::chrono_literals;
namespace test
{
namespace
{
class FileSelectionHelper
{
private:
std::size_t _msgSubscription;
std::string _path;
map::MapFormatPtr _format;
public:
FileSelectionHelper(const std::string& path, const map::MapFormatPtr& format) :
_path(path),
_format(format)
{
// Subscribe to the event asking for the target path
_msgSubscription = GlobalRadiantCore().getMessageBus().addListener(
radiant::IMessage::Type::FileSelectionRequest,
radiant::TypeListener<radiant::FileSelectionRequest>(
[this](radiant::FileSelectionRequest& msg)
{
msg.setHandled(true);
msg.setResult(radiant::FileSelectionRequest::Result
{
_path,
_format->getMapFormatName()
});
}));
}
~FileSelectionHelper()
{
GlobalRadiantCore().getMessageBus().removeListener(_msgSubscription);
}
};
class FileOverwriteHelper
{
private:
std::size_t _msgSubscription;
bool _shouldOverwrite;
bool _messageReceived;
public:
FileOverwriteHelper(bool shouldOverwrite) :
_shouldOverwrite(shouldOverwrite),
_messageReceived(false)
{
// Subscribe to the event asking for the target path
_msgSubscription = GlobalRadiantCore().getMessageBus().addListener(
radiant::IMessage::Type::FileOverwriteConfirmation,
radiant::TypeListener<radiant::FileOverwriteConfirmation>(
[this](radiant::FileOverwriteConfirmation& msg)
{
_messageReceived = true;
msg.confirmOverwrite(_shouldOverwrite);
msg.setHandled(true);
}));
}
bool messageReceived() const
{
return _messageReceived;
}
~FileOverwriteHelper()
{
GlobalRadiantCore().getMessageBus().removeListener(_msgSubscription);
}
};
}
class MapFileTestBase :
public RadiantTest
{
private:
std::list<fs::path> _pathsToCleanupAfterTest;
protected:
virtual void TearDown() override
{
for (const auto& path : _pathsToCleanupAfterTest)
{
fs::remove(path);
}
RadiantTest::TearDown();
}
// Creates a copy of the given map (including the .darkradiant file) in the temp data path
// The copy will be removed in the TearDown() method
fs::path createMapCopyInTempDataPath(const std::string& mapToCopy, const std::string& newFilename)
{
fs::path targetPath = _context.getTemporaryDataPath();
targetPath /= newFilename;
return createMapCopy(mapToCopy, targetPath);
}
// Creates a copy of the given map (including the .darkradiant file) in the mod-relative maps path
// The copy will be removed in the TearDown() method
fs::path createMapCopyInModMapsPath(const std::string& mapToCopy, const std::string& newFilename)
{
fs::path targetPath = _context.getTestProjectPath();
targetPath /= "maps/";
targetPath /= newFilename;
return createMapCopy(mapToCopy, targetPath);
}
private:
fs::path createMapCopy(const std::string& mapToCopy, const fs::path& targetPath)
{
fs::path mapPath = _context.getTestProjectPath();
mapPath /= "maps/";
mapPath /= mapToCopy;
fs::path targetInfoFilePath = fs::path(targetPath).replace_extension("darkradiant");
_pathsToCleanupAfterTest.push_back(targetPath);
_pathsToCleanupAfterTest.push_back(targetInfoFilePath);
// Copy both .map and .darkradiant file
fs::remove(targetPath);
fs::remove(targetInfoFilePath);
fs::copy(mapPath, targetPath);
fs::copy(fs::path(mapPath).replace_extension("darkradiant"), targetInfoFilePath);
return targetPath;
}
};
using MapLoadingTest = MapFileTestBase;
using MapSavingTest = MapFileTestBase;
TEST_F(MapLoadingTest, openMapWithEmptyStringAsksForPath)
{
bool eventFired = false;
// Subscribe to the event we expect to be fired
auto msgSubscription = GlobalRadiantCore().getMessageBus().addListener(
radiant::IMessage::Type::FileSelectionRequest,
radiant::TypeListener<radiant::FileSelectionRequest>(
[&](radiant::FileSelectionRequest& msg)
{
eventFired = true;
}));
// Calling OpenMap with no arguments will send a message to the UI
GlobalCommandSystem().executeCommand("OpenMap");
EXPECT_TRUE(eventFired) << "OpenMap didn't ask for a map file as expected";
GlobalRadiantCore().getMessageBus().removeListener(msgSubscription);
}
// Checks the main map info (brushes, entities, spawnargs), no layers or grouping
void checkAltarSceneGeometry()
{
auto root = GlobalMapModule().getRoot();
auto worldspawn = GlobalMapModule().findOrInsertWorldspawn();
// Check a specific spawnarg on worldspawn
EXPECT_EQ(Node_getEntity(worldspawn)->getKeyValue("_color"), "0.286 0.408 0.259");
// Check if all entities are present
auto knownEntities = { "func_static_153", "func_static_154", "func_static_156",
"func_static_155", "func_static_63", "func_static_66", "func_static_70",
"func_static_164", "func_static_165", "light_torchflame_13", "religious_symbol_1" };
for (auto entity : knownEntities)
{
EXPECT_TRUE(algorithm::getEntityByName(root, entity));
}
// Check number of patches
auto isPatchDef3 = [](const scene::INodePtr& node) { return Node_isPatch(node) && Node_getIPatch(node)->subdivisionsFixed(); };
auto isPatchDef2 = [](const scene::INodePtr& node) { return Node_isPatch(node) && !Node_getIPatch(node)->subdivisionsFixed(); };
EXPECT_EQ(algorithm::getChildCount(worldspawn, isPatchDef3), 110); // 110 patchDef3
EXPECT_EQ(algorithm::getChildCount(worldspawn, isPatchDef2), 16); // 16 patchDef2
// Check number of brushes
auto isBrush = [](const scene::INodePtr& node) { return Node_isBrush(node); };
EXPECT_EQ(algorithm::getChildCount(root, isBrush), 37); // 37 brushes in total
EXPECT_EQ(algorithm::getChildCount(worldspawn, isBrush), 21); // 21 worldspawn brushes
EXPECT_EQ(algorithm::getChildCount(algorithm::getEntityByName(root, "func_static_66"), isBrush), 4); // 4 child brushes
EXPECT_EQ(algorithm::getChildCount(algorithm::getEntityByName(root, "func_static_70"), isBrush), 4); // 4 child brushes
EXPECT_EQ(algorithm::getChildCount(algorithm::getEntityByName(root, "func_static_164"), isBrush), 4); // 4 child brushes
EXPECT_EQ(algorithm::getChildCount(algorithm::getEntityByName(root, "func_static_165"), isBrush), 4); // 4 child brushes
// Check the lights
auto isLight = [](const scene::INodePtr& node) { return Node_getLightNode(node) != nullptr; };
EXPECT_EQ(algorithm::getChildCount(root, isLight), 1); // 1 light
// Check a specific model
auto religiousSymbol = Node_getEntity(algorithm::getEntityByName(root, "religious_symbol_1"));
EXPECT_EQ(religiousSymbol->getKeyValue("classname"), "altar_moveable_loot_religious_symbol");
EXPECT_EQ(religiousSymbol->getKeyValue("origin"), "-0.0448253 12.0322 -177");
}
// Check entire map including geometry, entities, layers, groups
void checkAltarScene()
{
checkAltarSceneGeometry();
auto root = GlobalMapModule().getRoot();
// Check layers
EXPECT_TRUE(root->getLayerManager().getLayerID("Default") != -1);
EXPECT_TRUE(root->getLayerManager().getLayerID("Windows") != -1);
EXPECT_TRUE(root->getLayerManager().getLayerID("Lights") != -1);
EXPECT_TRUE(root->getLayerManager().getLayerID("Ceiling") != -1);
// Check map property
EXPECT_EQ(root->getProperty("LastShaderClipboardMaterial"), "textures/tiles01");
// Check selection group profile
std::size_t numGroups = 0;
std::multiset<std::size_t> groupCounts;
root->getSelectionGroupManager().foreachSelectionGroup([&](const selection::ISelectionGroup& group)
{
++numGroups;
groupCounts.insert(group.size());
});
EXPECT_EQ(numGroups, 4);
EXPECT_EQ(groupCounts.count(2), 1); // 1 group with 2 members
EXPECT_EQ(groupCounts.count(3), 2); // 2 groups with 3 members
EXPECT_EQ(groupCounts.count(12), 1); // 1 group with 12 members
}
TEST_F(MapLoadingTest, openMapFromAbsolutePath)
{
// Generate an absolute path to a map in a temporary folder
auto temporaryMap = createMapCopyInTempDataPath("altar.map", "temp_altar.map");
GlobalCommandSystem().executeCommand("OpenMap", temporaryMap.string());
// Check if the scene contains what we expect
checkAltarScene();
EXPECT_EQ(GlobalMapModule().getMapName(), temporaryMap.string());
}
TEST_F(MapLoadingTest, openMapFromModRelativePath)
{
std::string modRelativePath = "maps/altar.map";
// The map is located in maps/altar.map folder, check that it physically exists
fs::path mapPath = _context.getTestProjectPath();
mapPath /= modRelativePath;
EXPECT_TRUE(os::fileOrDirExists(mapPath));
GlobalCommandSystem().executeCommand("OpenMap", modRelativePath);
// Check if the scene contains what we expect
checkAltarScene();
// Right now, even when opening from the mod folder, the map name is showing the absolute path
//EXPECT_EQ(GlobalMapModule().getMapName(), "maps/" + mapName);
}
TEST_F(MapLoadingTest, openMapFromMapsFolder)
{
std::string mapName = "altar.map";
// The map is located in maps/altar.map folder, check that it physically exists
fs::path mapPath = _context.getTestProjectPath();
mapPath /= "maps";
mapPath /= mapName;
EXPECT_TRUE(os::fileOrDirExists(mapPath));
GlobalCommandSystem().executeCommand("OpenMap", mapName);
// Check if the scene contains what we expect
checkAltarScene();
// Right now, even when opening from the mod folder, the map name is showing the absolute path
//EXPECT_EQ(GlobalMapModule().getMapName(), "maps/" + mapName);
}
TEST_F(MapLoadingTest, openMapFromModPak)
{
std::string modRelativePath = "maps/altar_in_pk4.map";
// The map is located in maps/ folder within the altar.pk4, check that it doesn't physically exist
fs::path mapPath = _context.getTestProjectPath();
mapPath /= modRelativePath;
EXPECT_FALSE(os::fileOrDirExists(mapPath));
GlobalCommandSystem().executeCommand("OpenMap", modRelativePath);
// Check if the scene contains what we expect
checkAltarScene();
EXPECT_EQ(GlobalMapModule().getMapName(), modRelativePath);
}
TEST_F(MapLoadingTest, openMapFromArchive)
{
auto pakPath = fs::path(_context.getTestResourcePath()) / "map_loading_test.pk4";
std::string archiveRelativePath = "maps/altar_packed.map";
GlobalCommandSystem().executeCommand("OpenMapFromArchive", pakPath.string(), archiveRelativePath);
// Check if the scene contains what we expect
checkAltarScene();
}
TEST_F(MapLoadingTest, openMapFromArchiveWithoutInfoFile)
{
auto pakPath = fs::path(_context.getTestResourcePath()) / "map_loading_test.pk4";
std::string archiveRelativePath = "maps/altar_packed_without_dr_file.map";
GlobalCommandSystem().executeCommand("OpenMapFromArchive", pakPath.string(), archiveRelativePath);
// Check if the scene contains what we expect, just the geometry since the map
// is lacking its .darkradiant file
checkAltarSceneGeometry();
}
TEST_F(MapLoadingTest, openNonExistentMap)
{
std::string mapName = "idontexist.map";
GlobalCommandSystem().executeCommand("OpenMap", mapName);
// No worldspawn in this map, it should be empty
EXPECT_FALSE(algorithm::getEntityByName(GlobalMapModule().getRoot(), "world"));
EXPECT_EQ(GlobalMapModule().getMapName(), "unnamed.map");
}
TEST_F(MapLoadingTest, openWithInvalidPath)
{
// Pass a directory name to it
GlobalCommandSystem().executeCommand("OpenMap", _context.getTemporaryDataPath());
// No worldspawn in this map, it should be empty
EXPECT_FALSE(algorithm::getEntityByName(GlobalMapModule().getRoot(), "world"));
EXPECT_EQ(GlobalMapModule().getMapName(), "unnamed.map");
}
TEST_F(MapLoadingTest, openWithInvalidPathInsideMod)
{
// Pass a directory name to it
GlobalCommandSystem().executeCommand("OpenMap", _context.getTestProjectPath());
// No worldspawn in this map, it should be empty
EXPECT_FALSE(algorithm::getEntityByName(GlobalMapModule().getRoot(), "world"));
EXPECT_EQ(GlobalMapModule().getMapName(), "unnamed.map");
}
TEST_F(MapLoadingTest, openMapWithoutInfoFile)
{
auto tempPath = createMapCopyInTempDataPath("altar.map", "altar_openMapWithoutInfoFile.map");
fs::remove(fs::path(tempPath).replace_extension("darkradiant"));
EXPECT_FALSE(os::fileOrDirExists(fs::path(tempPath).replace_extension("darkradiant")));
GlobalCommandSystem().executeCommand("OpenMap", tempPath.string());
checkAltarSceneGeometry();
EXPECT_EQ(GlobalMapModule().getMapName(), tempPath.string());
}
TEST_F(MapLoadingTest, loadingCanBeCancelled)
{
std::string mapName = "altar.map";
std::string otherMap = "altar_loadingCanBeCancelled.map";
auto tempPath = createMapCopyInTempDataPath(mapName, otherMap);
// Load a valid map first
GlobalCommandSystem().executeCommand("OpenMap", mapName);
checkAltarScene();
bool cancelIssued = false;
// Subscribe to the map file operation progress event to cancel loading
// Subscribe to the event we expect to be fired
auto msgSubscription = GlobalRadiantCore().getMessageBus().addListener(
radiant::IMessage::Type::MapFileOperation,
radiant::TypeListener<map::FileOperation>(
[&](map::FileOperation& msg)
{
if (msg.getOperationType() == map::FileOperation::Type::Import &&
msg.getMessageType() == map::FileOperation::Started)
{
// set the flag before, since cancelOperation will be throwing an exception
cancelIssued = true;
msg.cancelOperation();
}
}));
// Now load the other map and cancel the operation
GlobalCommandSystem().executeCommand("OpenMap", tempPath.string());
// Operation should have been actively cancelled
EXPECT_TRUE(cancelIssued);
// Map should be empty
EXPECT_FALSE(algorithm::getEntityByName(GlobalMapModule().getRoot(), "world"));
EXPECT_EQ(GlobalMapModule().getMapName(), "unnamed.map");
GlobalRadiantCore().getMessageBus().removeListener(msgSubscription);
}
TEST_F(MapSavingTest, saveMapWithoutModification)
{
auto tempPath = createMapCopyInTempDataPath("altar.map", "altar_saveMapWithoutModification.map");
GlobalCommandSystem().executeCommand("OpenMap", tempPath.string());
checkAltarScene();
bool mapSavedFired = false;
sigc::connection conn = GlobalMapModule().signal_mapEvent().connect([&](IMap::MapEvent ev)
{
mapSavedFired |= ev == IMap::MapEvent::MapSaved;
});
EXPECT_FALSE(GlobalMapModule().isModified());
GlobalCommandSystem().executeCommand("SaveMap");
// SaveMap should trigger even though the map is not modified
EXPECT_TRUE(mapSavedFired);
conn.disconnect();
}
TEST_F(MapSavingTest, saveMapClearsModifiedFlag)
{
auto tempPath = createMapCopyInTempDataPath("altar.map", "altar_modified_flag_test.map");
GlobalCommandSystem().executeCommand("OpenMap", tempPath.string());
checkAltarScene();
EXPECT_FALSE(GlobalMapModule().isModified());
// Modify the worldspawn key values (in an Undoable transaction)
algorithm::setWorldspawnKeyValue("dummykey", "dummyvalue");
// This should mark the map as modified
EXPECT_TRUE(GlobalMapModule().isModified());
GlobalCommandSystem().executeCommand("SaveMap");
// Modified flag should be cleared now
EXPECT_FALSE(GlobalMapModule().isModified());
}
TEST_F(MapSavingTest, saveMapDoesntChangeMap)
{
// Create a copy of the map file in the mod-relative maps/ folder
fs::path mapPath = _context.getTestProjectPath();
mapPath /= "maps/altar.map";
// The map is located in maps/altar.map folder, check that it physically exists
std::string modRelativePath = "maps/altar_saveMapDoesntChangeMap.map";
fs::path copiedMap = _context.getTestProjectPath();
copiedMap /= modRelativePath;
fs::remove(copiedMap);
fs::remove(fs::path(copiedMap).replace_extension("darkradiant"));
fs::remove(copiedMap);
fs::copy(mapPath, copiedMap);
fs::copy(fs::path(mapPath).replace_extension("darkradiant"), fs::path(copiedMap).replace_extension("darkradiant"));
auto originalModificationDate = fs::last_write_time(copiedMap);
GlobalCommandSystem().executeCommand("OpenMap", modRelativePath);
checkAltarScene();
GlobalCommandSystem().executeCommand("SaveMap");
// Check that the file got modified
EXPECT_NE(fs::last_write_time(copiedMap), originalModificationDate);
// Load it again and check the scene
GlobalCommandSystem().executeCommand("OpenMap", modRelativePath);
checkAltarScene();
fs::remove(copiedMap);
fs::remove(fs::path(copiedMap).replace_extension("bak"));
fs::remove(fs::path(copiedMap).replace_extension("darkradiant"));
fs::remove(fs::path(copiedMap).replace_extension("darkradiant").string() + ".bak");
}
TEST_F(MapSavingTest, saveMapCreatesInfoFile)
{
// Ensure a worldspawn entity, this is enough
auto worldspawn = GlobalMapModule().findOrInsertWorldspawn();
// Respond to the file selection request when saving
fs::path tempPath = _context.getTemporaryDataPath();
tempPath /= "just_a_worldspawn.map";
auto infoFilePath = fs::path(tempPath).replace_extension("darkradiant");
auto format = GlobalMapFormatManager().getMapFormatForFilename(tempPath.string());
FileSelectionHelper responder(tempPath.string(), format);
EXPECT_FALSE(os::fileOrDirExists(tempPath));
EXPECT_FALSE(os::fileOrDirExists(infoFilePath));
// Save the map
GlobalCommandSystem().executeCommand("SaveMap");
EXPECT_TRUE(os::fileOrDirExists(tempPath));
EXPECT_TRUE(os::fileOrDirExists(infoFilePath));
}
namespace
{
// Shared algorithm to create a 6-brush map with layers
void doCheckSaveMapPreservesLayerInfo(const std::string& savePath, const map::MapFormatPtr& format)
{
auto worldspawn = GlobalMapModule().findOrInsertWorldspawn();
auto brush1 = algorithm::createCubicBrush(worldspawn, Vector3(400, 400, 400), "shader1");
auto brush2 = algorithm::createCubicBrush(worldspawn, Vector3(500, 100, 200), "shader2");
auto brush3 = algorithm::createCubicBrush(worldspawn, Vector3(300, 100, 200), "shader3");
auto brush4 = algorithm::createCubicBrush(worldspawn, Vector3(300, 100, 700), "shader4");
auto brush5 = algorithm::createCubicBrush(worldspawn, Vector3(300, 600, 700), "shader5");
auto brush6 = algorithm::createCubicBrush(worldspawn, Vector3(300, 900, 700), "shader6");
int layerId1 = GlobalMapModule().getRoot()->getLayerManager().createLayer("Layer1");
int layerId2 = GlobalMapModule().getRoot()->getLayerManager().createLayer("Layer2");
int layerId3 = GlobalMapModule().getRoot()->getLayerManager().createLayer("Layer3");
int layerId4 = GlobalMapModule().getRoot()->getLayerManager().createLayer("Layer4");
// Assign worldspawn to layers
worldspawn->assignToLayers(scene::LayerList{ 0, layerId1, layerId2, layerId3, layerId4 });
// Assign brushes to layers
brush1->assignToLayers(scene::LayerList{ 0, layerId1 });
brush2->assignToLayers(scene::LayerList{ layerId1, layerId2 });
brush3->assignToLayers(scene::LayerList{ layerId3, layerId2 });
brush4->assignToLayers(scene::LayerList{ 0, layerId4 });
brush5->assignToLayers(scene::LayerList{ 0, layerId4 });
brush6->assignToLayers(scene::LayerList{ layerId2, layerId4 });
// Clear any referenes to the old scene
worldspawn = brush1 = brush2 = brush3 = brush4 = brush5 = brush6 = scene::INodePtr();
// Respond to the file selection request when saving
FileSelectionHelper responder(savePath, format);
// Save the map
GlobalCommandSystem().executeCommand("SaveMap");
// Clear the map, load from that file
GlobalCommandSystem().executeCommand("OpenMap", savePath);
// Refresh the node references from the new map
worldspawn = GlobalMapModule().findOrInsertWorldspawn();
brush1 = algorithm::findFirstBrushWithMaterial(worldspawn, "shader1");
brush2 = algorithm::findFirstBrushWithMaterial(worldspawn, "shader2");
brush3 = algorithm::findFirstBrushWithMaterial(worldspawn, "shader3");
brush4 = algorithm::findFirstBrushWithMaterial(worldspawn, "shader4");
brush5 = algorithm::findFirstBrushWithMaterial(worldspawn, "shader5");
brush6 = algorithm::findFirstBrushWithMaterial(worldspawn, "shader6");
// Check the layers
EXPECT_EQ(worldspawn->getLayers(), scene::LayerList({ 0, layerId1, layerId2, layerId3, layerId4 }));
EXPECT_EQ(brush1->getLayers(), scene::LayerList({ 0, layerId1 }));
EXPECT_EQ(brush2->getLayers(), scene::LayerList({ layerId1, layerId2 }));
EXPECT_EQ(brush3->getLayers(), scene::LayerList({ layerId3, layerId2 }));
EXPECT_EQ(brush4->getLayers(), scene::LayerList({ 0, layerId4 }));
EXPECT_EQ(brush5->getLayers(), scene::LayerList({ 0, layerId4 }));
EXPECT_EQ(brush6->getLayers(), scene::LayerList({ layerId2, layerId4 }));
}
}
TEST_F(MapSavingTest, saveMapPreservesLayerInfo)
{
fs::path tempPath = _context.getTemporaryDataPath();
tempPath /= "six_brushes_with_layers.map";
auto format = GlobalMapFormatManager().getMapFormatForFilename(tempPath.string());
doCheckSaveMapPreservesLayerInfo(tempPath.string(), format);
}
TEST_F(MapSavingTest, saveMapxPreservesLayerInfo)
{
fs::path tempPath = _context.getTemporaryDataPath();
tempPath /= "six_brushes_with_layers.mapx";
auto format = GlobalMapFormatManager().getMapFormatForFilename(tempPath.string());
doCheckSaveMapPreservesLayerInfo(tempPath.string(), format);
}
TEST_F(MapSavingTest, saveAs)
{
std::string modRelativePath = "maps/altar.map";
// The map is located in maps/altar.map folder, check that it physically exists
fs::path mapPath = _context.getTestProjectPath();
mapPath /= modRelativePath;
EXPECT_TRUE(os::fileOrDirExists(mapPath));
GlobalCommandSystem().executeCommand("OpenMap", modRelativePath);
checkAltarScene();
// Select the format based on the extension
auto format = GlobalMapFormatManager().getMapFormatForFilename(modRelativePath);
fs::path tempPath = _context.getTemporaryDataPath();
tempPath /= "altar_copy.map";
EXPECT_FALSE(os::fileOrDirExists(tempPath));
// Respond to the event asking for the target path
FileSelectionHelper responder(tempPath.string(), format);
GlobalCommandSystem().executeCommand("SaveMapAs");
// Check that the file got created
EXPECT_TRUE(os::fileOrDirExists(tempPath));
// The map path should have been changed
EXPECT_EQ(GlobalMapModule().getMapName(), tempPath.string());
// Load it again and check the scene
GlobalCommandSystem().executeCommand("OpenMap", tempPath.string());
checkAltarScene();
}
TEST_F(MapSavingTest, saveAsWithFormatWillContinueUsingThatFormat)
{
std::string modRelativePath = "maps/altar.map";
GlobalCommandSystem().executeCommand("OpenMap", modRelativePath);
checkAltarScene();
// Select the format based on the mapx extension
fs::path tempPath = _context.getTemporaryDataPath();
tempPath /= "altar_copy.mapx";
auto format = GlobalMapFormatManager().getMapFormatForFilename(tempPath.string());
EXPECT_EQ(format->getMapFormatName(), map::PORTABLE_MAP_FORMAT_NAME);
FileSelectionHelper responder(tempPath.string(), format);
EXPECT_FALSE(os::fileOrDirExists(tempPath));
GlobalCommandSystem().executeCommand("SaveMapAs");
// Check that the file got created
EXPECT_TRUE(os::fileOrDirExists(tempPath));
algorithm::assertFileIsMapxFile(tempPath.string());
// The map path should have been changed
EXPECT_EQ(GlobalMapModule().getMapName(), tempPath.string());
// Modify something in the map and save again
algorithm::setWorldspawnKeyValue("dummykey222", "dummyvalue");
GlobalCommandSystem().executeCommand("SaveMap");
// Check that file, it should still be using the portable format
algorithm::assertFileIsMapxFile(tempPath.string());
}
TEST_F(MapSavingTest, saveCopyAs)
{
std::string modRelativePath = "maps/altar.map";
GlobalCommandSystem().executeCommand("OpenMap", modRelativePath);
checkAltarScene();
EXPECT_EQ(GlobalMapModule().getMapName(), modRelativePath);
// Select the format based on the extension
auto format = GlobalMapFormatManager().getMapFormatForFilename(modRelativePath);
fs::path tempPath = _context.getTemporaryDataPath();
tempPath /= "altar_copy.map";
FileSelectionHelper responder(tempPath.string(), format);
EXPECT_FALSE(os::fileOrDirExists(tempPath));
GlobalCommandSystem().executeCommand("SaveMapCopyAs");
// Check that the file got created
EXPECT_TRUE(os::fileOrDirExists(tempPath));
// The map path should NOT have been changed
EXPECT_EQ(GlobalMapModule().getMapName(), modRelativePath);
// Load the copy and verify the scene
GlobalCommandSystem().executeCommand("OpenMap", tempPath.string());
checkAltarScene();
}
TEST_F(MapSavingTest, saveCopyAsMapx)
{
std::string modRelativePath = "maps/altar.map";
GlobalCommandSystem().executeCommand("OpenMap", modRelativePath);
checkAltarScene();
EXPECT_EQ(GlobalMapModule().getMapName(), modRelativePath);
// Select the format based on the mapx extension
fs::path tempPath = _context.getTemporaryDataPath();
tempPath /= "altar_copy.mapx";
auto format = GlobalMapFormatManager().getMapFormatForFilename(tempPath.string());
EXPECT_EQ(format->getMapFormatName(), map::PORTABLE_MAP_FORMAT_NAME);
FileSelectionHelper responder(tempPath.string(), format);
EXPECT_FALSE(os::fileOrDirExists(tempPath));
GlobalCommandSystem().executeCommand("SaveMapCopyAs");
// Check that the file got created
EXPECT_TRUE(os::fileOrDirExists(tempPath));
// Check the output file
algorithm::assertFileIsMapxFile(tempPath.string());
// The map path should NOT have been changed
EXPECT_EQ(GlobalMapModule().getMapName(), modRelativePath);
// Load the portable format map and verify the scene
GlobalCommandSystem().executeCommand("OpenMap", tempPath.string());
checkAltarScene();
EXPECT_EQ(GlobalMapModule().getMapName(), tempPath);
}
// Check that the overwriting an existing map file will create a backup set
TEST_F(MapSavingTest, saveMapCreatesBackup)
{
auto mapPath = createMapCopyInTempDataPath("altar.map", "altar_saveMapCreatesBackup.map");
auto originalSize = fs::file_size(mapPath);
auto originalModDate = fs::last_write_time(mapPath);
GlobalCommandSystem().executeCommand("OpenMap", mapPath.string());
checkAltarScene();
fs::path mapBackupPath = mapPath.replace_extension("bak");
fs::path infoFileBackupPath = mapPath.replace_extension("darkradiant").string() + ".bak";
EXPECT_FALSE(os::fileOrDirExists(mapBackupPath));
EXPECT_FALSE(os::fileOrDirExists(infoFileBackupPath));
GlobalCommandSystem().executeCommand("SaveMap");
// Check that the target file got modified
EXPECT_NE(fs::last_write_time(mapPath), originalModDate);
// Check that the backup files exist now
EXPECT_TRUE(os::fileOrDirExists(mapBackupPath));
EXPECT_TRUE(os::fileOrDirExists(infoFileBackupPath));
// The backup should have the write time of the original map
EXPECT_EQ(fs::last_write_time(mapBackupPath), originalModDate);
// Remove the backup at the end of this test
fs::remove(mapBackupPath);
fs::remove(infoFileBackupPath);
}
TEST_F(MapSavingTest, saveMapxCreatesBackup)
{
std::string modRelativePath = "maps/altar.map";
GlobalCommandSystem().executeCommand("OpenMap", modRelativePath);
checkAltarScene();
// Select the format based on the mapx extension
auto mapxPath = fs::path(_context.getTemporaryDataPath()) / "altar_saveMapxCreatesBackup.mapx";
auto format = GlobalMapFormatManager().getMapFormatForFilename(mapxPath.string());
EXPECT_EQ(format->getMapFormatName(), map::PORTABLE_MAP_FORMAT_NAME);
FileSelectionHelper responder(mapxPath.string(), format);
GlobalCommandSystem().executeCommand("SaveMapAs");
// Mapx file should be there, the backup should be missing
EXPECT_TRUE(os::fileOrDirExists(mapxPath));
EXPECT_FALSE(os::fileOrDirExists(fs::path(mapxPath).replace_extension("bak")));
// Now we have a .mapx file lying around, overwrite it to create a backup
GlobalCommandSystem().executeCommand("SaveMap");
// Mapx backup should be there now
EXPECT_TRUE(os::fileOrDirExists(fs::path(mapxPath).replace_extension("bak")));
fs::remove(mapxPath);
fs::remove(fs::path(mapxPath).replace_extension("bak"));
}
TEST_F(MapSavingTest, saveMapReplacesOldBackup)
{
auto mapPath = createMapCopyInTempDataPath("altar.map", "altar_saveMapReplacesOldBackup.map");
// Create two fake backup files
fs::path mapBackupPath = fs::path(mapPath).replace_extension("bak");
std::ofstream fakeBackup(mapBackupPath.string());
fakeBackup << "123=map";
fakeBackup.flush();
fakeBackup.close();
// Fake the mod time too, it needs to be different from the time
// the above stream closes the file (otherwise the test might fail if it's fast enough)
auto fakeTime = fs::last_write_time(mapBackupPath);
fs::last_write_time(mapBackupPath, fakeTime + 1h);
auto originalBackupSize = fs::file_size(mapBackupPath);
auto originalBackupModTime = fs::last_write_time(mapBackupPath);
fs::path infoFileBackupPath = fs::path(mapPath).replace_extension("darkradiant").string() + ".bak";
std::ofstream fakeInfoBackup(infoFileBackupPath.string());
fakeInfoBackup << "123=info";
fakeInfoBackup.flush();
fakeInfoBackup.close();
fakeTime = fs::last_write_time(infoFileBackupPath);
fs::last_write_time(infoFileBackupPath, fakeTime + 1h);
auto originalInfoBackupSize = fs::file_size(infoFileBackupPath);
auto originalInfoBackupModTime = fs::last_write_time(infoFileBackupPath);
// Open the map, verify the scene
GlobalCommandSystem().executeCommand("OpenMap", mapPath.string());
checkAltarScene();
// Overwrite the map, this should replace the backups
GlobalCommandSystem().executeCommand("SaveMap");
// Check that the backup files got modified
EXPECT_NE(fs::last_write_time(mapBackupPath), originalBackupModTime);
EXPECT_NE(fs::last_write_time(infoFileBackupPath), originalInfoBackupModTime);
EXPECT_NE(fs::file_size(mapBackupPath), originalBackupSize);
EXPECT_NE(fs::file_size(infoFileBackupPath), originalInfoBackupSize);
}
TEST_F(MapSavingTest, saveMapOpenedInModRelativePath)
{
std::string mapFileName = "altar_saveMapOpenedWithModRelativePath.map";
auto tempPath = createMapCopyInModMapsPath("altar.map", mapFileName);
GlobalCommandSystem().executeCommand("OpenMap", "maps/" + mapFileName);
checkAltarScene();
auto originalModDate = fs::last_write_time(tempPath);
GlobalCommandSystem().executeCommand("SaveMap");
// File should have been modified
EXPECT_NE(fs::last_write_time(tempPath), originalModDate);
// Remove the backups
fs::remove(tempPath.replace_extension("bak"));
fs::remove(tempPath.replace_extension("darkradiant").string() + ".bak");
}
TEST_F(MapSavingTest, saveMapOpenedInAbsolutePath)
{
std::string mapFileName = "altar_saveMapOpenedWithAbsolutePath.map";
auto tempPath = createMapCopyInTempDataPath("altar.map", mapFileName);
GlobalCommandSystem().executeCommand("OpenMap", tempPath.string());
checkAltarScene();
auto originalModDate = fs::last_write_time(tempPath);
GlobalCommandSystem().executeCommand("SaveMap");
// File should have been modified
EXPECT_NE(fs::last_write_time(tempPath), originalModDate);
// Remove the backups
fs::remove(tempPath.replace_extension("bak"));
fs::remove(tempPath.replace_extension("darkradiant").string() + ".bak");
}
TEST_F(MapSavingTest, saveArchivedMapWillAskForFilename)
{
// A map that has been loaded from an archive file is not writeable
// the map saving algorithm should detect this and ask for a new file location
auto pakPath = fs::path(_context.getTestResourcePath()) / "map_loading_test.pk4";
std::string archiveRelativePath = "maps/altar_packed.map";
GlobalCommandSystem().executeCommand("OpenMapFromArchive", pakPath.string(), archiveRelativePath);
checkAltarScene();
bool eventFired = false;
fs::path outputPath = _context.getTemporaryDataPath();
outputPath /= "altar_packed_copy.map";
auto format = GlobalMapFormatManager().getMapFormatForFilename(outputPath.string());
// Subscribe to the event asking for the target path
auto msgSubscription = GlobalRadiantCore().getMessageBus().addListener(
radiant::IMessage::Type::FileSelectionRequest,
radiant::TypeListener<radiant::FileSelectionRequest>(
[&](radiant::FileSelectionRequest& msg)
{
eventFired = true;
msg.setHandled(true);
msg.setResult(radiant::FileSelectionRequest::Result
{
outputPath.string(),
format->getMapFormatName()
});
}));
// This should ask the user for a file location, i.e. fire the above event
GlobalCommandSystem().executeCommand("SaveMap");
EXPECT_TRUE(eventFired) << "Radiant didn't ask for a new filename when saving an archived map";
eventFired = false;
// Save again, this should no longer ask for a location
GlobalCommandSystem().executeCommand("SaveMap");
EXPECT_FALSE(eventFired);
GlobalRadiantCore().getMessageBus().removeListener(msgSubscription);
}
TEST_F(MapSavingTest, savingUnnamedMapDoesntWarnAboutOverwrite)
{
EXPECT_TRUE(GlobalMapModule().isUnnamed());
fs::path outputPath = _context.getTemporaryDataPath();
outputPath /= "whatevername.mapx";
auto format = GlobalMapFormatManager().getMapFormatForFilename(outputPath.string());
EXPECT_FALSE(os::fileOrDirExists(outputPath));
// Save to a temporary path
FileSelectionHelper saveHelper(outputPath.string(), format);
FileOverwriteHelper overwriteHelper(false); // don't overwrite
// This should ask the user for a file location, i.e. fire the above event
// but shouldn't warn about for overwriting (file doesn't exist)
GlobalCommandSystem().executeCommand("SaveMap");
// File should have been created without overwrite event
EXPECT_TRUE(os::fileOrDirExists(outputPath));
EXPECT_FALSE(overwriteHelper.messageReceived());
}
TEST_F(MapSavingTest, savingUnnamedMapDoesntWarnAboutOverwriteWhenFileExists)
{
EXPECT_TRUE(GlobalMapModule().isUnnamed());
fs::path outputPath = _context.getTemporaryDataPath();
outputPath /= "whatevername.mapx";
auto format = GlobalMapFormatManager().getMapFormatForFilename(outputPath.string());
std::ofstream stream(outputPath);
stream << "Test";
stream.flush();
stream.close();