]> git.lizzy.rs Git - minetest.git/blob - src/test.cpp
Fix mapgen using unitialised height map values
[minetest.git] / src / test.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "test.h"
21 #include "irrlichttypes_extrabloated.h"
22 #include "debug.h"
23 #include "map.h"
24 #include "player.h"
25 #include "main.h"
26 #include "socket.h"
27 #include "network/connection.h"
28 #include "serialization.h"
29 #include "voxel.h"
30 #include "collision.h"
31 #include <sstream>
32 #include "porting.h"
33 #include "content_mapnode.h"
34 #include "nodedef.h"
35 #include "mapsector.h"
36 #include "settings.h"
37 #include "log.h"
38 #include "util/string.h"
39 #include "filesys.h"
40 #include "voxelalgorithms.h"
41 #include "inventory.h"
42 #include "util/numeric.h"
43 #include "util/serialize.h"
44 #include "noise.h" // PseudoRandom used for random data for compression
45 #include "network/networkprotocol.h" // LATEST_PROTOCOL_VERSION
46 #include <algorithm>
47
48 /*
49         Asserts that the exception occurs
50 */
51 #define EXCEPTION_CHECK(EType, code)\
52 {\
53         bool exception_thrown = false;\
54         try{ code; }\
55         catch(EType &e) { exception_thrown = true; }\
56         UASSERT(exception_thrown);\
57 }
58
59 #define UTEST(x, fmt, ...)\
60 {\
61         if(!(x)){\
62                 dstream << "Test (" #x ") failed: " fmt << std::endl; \
63                 test_failed = true;\
64         }\
65 }
66
67 #define UASSERT(x) UTEST(x, "UASSERT")
68
69 /*
70         A few item and node definitions for those tests that need them
71 */
72
73 static content_t CONTENT_STONE;
74 static content_t CONTENT_GRASS;
75 static content_t CONTENT_TORCH;
76
77 void define_some_nodes(IWritableItemDefManager *idef, IWritableNodeDefManager *ndef)
78 {
79         ItemDefinition itemdef;
80         ContentFeatures f;
81
82         /*
83                 Stone
84         */
85         itemdef = ItemDefinition();
86         itemdef.type = ITEM_NODE;
87         itemdef.name = "default:stone";
88         itemdef.description = "Stone";
89         itemdef.groups["cracky"] = 3;
90         itemdef.inventory_image = "[inventorycube"
91                 "{default_stone.png"
92                 "{default_stone.png"
93                 "{default_stone.png";
94         f = ContentFeatures();
95         f.name = itemdef.name;
96         for(int i = 0; i < 6; i++)
97                 f.tiledef[i].name = "default_stone.png";
98         f.is_ground_content = true;
99         idef->registerItem(itemdef);
100         CONTENT_STONE = ndef->set(f.name, f);
101
102         /*
103                 Grass
104         */
105         itemdef = ItemDefinition();
106         itemdef.type = ITEM_NODE;
107         itemdef.name = "default:dirt_with_grass";
108         itemdef.description = "Dirt with grass";
109         itemdef.groups["crumbly"] = 3;
110         itemdef.inventory_image = "[inventorycube"
111                 "{default_grass.png"
112                 "{default_dirt.png&default_grass_side.png"
113                 "{default_dirt.png&default_grass_side.png";
114         f = ContentFeatures();
115         f.name = itemdef.name;
116         f.tiledef[0].name = "default_grass.png";
117         f.tiledef[1].name = "default_dirt.png";
118         for(int i = 2; i < 6; i++)
119                 f.tiledef[i].name = "default_dirt.png^default_grass_side.png";
120         f.is_ground_content = true;
121         idef->registerItem(itemdef);
122         CONTENT_GRASS = ndef->set(f.name, f);
123
124         /*
125                 Torch (minimal definition for lighting tests)
126         */
127         itemdef = ItemDefinition();
128         itemdef.type = ITEM_NODE;
129         itemdef.name = "default:torch";
130         f = ContentFeatures();
131         f.name = itemdef.name;
132         f.param_type = CPT_LIGHT;
133         f.light_propagates = true;
134         f.sunlight_propagates = true;
135         f.light_source = LIGHT_MAX-1;
136         idef->registerItem(itemdef);
137         CONTENT_TORCH = ndef->set(f.name, f);
138 }
139
140 struct TestBase
141 {
142         bool test_failed;
143         TestBase():
144                 test_failed(false)
145         {}
146 };
147
148 struct TestUtilities: public TestBase
149 {
150         inline float ref_WrapDegrees180(float f)
151         {
152                 // This is a slower alternative to the wrapDegrees_180() function;
153                 // used as a reference for testing
154                 float value = fmodf(f + 180, 360);
155                 if (value < 0)
156                         value += 360;
157                 return value - 180;
158         }
159
160         inline float ref_WrapDegrees_0_360(float f)
161         {
162                 // This is a slower alternative to the wrapDegrees_0_360() function;
163                 // used as a reference for testing
164                 float value = fmodf(f, 360);
165                 if (value < 0)
166                         value += 360;
167                 return value < 0 ? value + 360 : value;
168         }
169
170
171         void Run()
172         {
173                 UASSERT(fabs(modulo360f(100.0) - 100.0) < 0.001);
174                 UASSERT(fabs(modulo360f(720.5) - 0.5) < 0.001);
175                 UASSERT(fabs(modulo360f(-0.5) - (-0.5)) < 0.001);
176                 UASSERT(fabs(modulo360f(-365.5) - (-5.5)) < 0.001);
177
178                 for (float f = -720; f <= -360; f += 0.25) {
179                         UASSERT(fabs(modulo360f(f) - modulo360f(f + 360)) < 0.001);
180                 }
181
182                 for (float f = -1440; f <= 1440; f += 0.25) {
183                         UASSERT(fabs(modulo360f(f) - fmodf(f, 360)) < 0.001);
184                         UASSERT(fabs(wrapDegrees_180(f) - ref_WrapDegrees180(f)) < 0.001);
185                         UASSERT(fabs(wrapDegrees_0_360(f) - ref_WrapDegrees_0_360(f)) < 0.001);
186                         UASSERT(wrapDegrees_0_360(fabs(wrapDegrees_180(f) - wrapDegrees_0_360(f))) < 0.001);
187                 }
188
189                 UASSERT(lowercase("Foo bAR") == "foo bar");
190                 UASSERT(trim("\n \t\r  Foo bAR  \r\n\t\t  ") == "Foo bAR");
191                 UASSERT(trim("\n \t\r    \r\n\t\t  ") == "");
192                 UASSERT(is_yes("YeS") == true);
193                 UASSERT(is_yes("") == false);
194                 UASSERT(is_yes("FAlse") == false);
195                 UASSERT(is_yes("-1") == true);
196                 UASSERT(is_yes("0") == false);
197                 UASSERT(is_yes("1") == true);
198                 UASSERT(is_yes("2") == true);
199                 const char *ends[] = {"abc", "c", "bc", "", NULL};
200                 UASSERT(removeStringEnd("abc", ends) == "");
201                 UASSERT(removeStringEnd("bc", ends) == "b");
202                 UASSERT(removeStringEnd("12c", ends) == "12");
203                 UASSERT(removeStringEnd("foo", ends) == "");
204                 UASSERT(urlencode("\"Aardvarks lurk, OK?\"")
205                                 == "%22Aardvarks%20lurk%2C%20OK%3F%22");
206                 UASSERT(urldecode("%22Aardvarks%20lurk%2C%20OK%3F%22")
207                                 == "\"Aardvarks lurk, OK?\"");
208                 UASSERT(padStringRight("hello", 8) == "hello   ");
209                 UASSERT(str_equal(narrow_to_wide("abc"), narrow_to_wide("abc")));
210                 UASSERT(str_equal(narrow_to_wide("ABC"), narrow_to_wide("abc"), true));
211                 UASSERT(trim("  a") == "a");
212                 UASSERT(trim("   a  ") == "a");
213                 UASSERT(trim("a   ") == "a");
214                 UASSERT(trim("") == "");
215                 UASSERT(mystoi("123", 0, 1000) == 123);
216                 UASSERT(mystoi("123", 0, 10) == 10);
217                 std::string test_str;
218                 test_str = "Hello there";
219                 str_replace(test_str, "there", "world");
220                 UASSERT(test_str == "Hello world");
221                 test_str = "ThisAisAaAtest";
222                 str_replace(test_str, 'A', ' ');
223                 UASSERT(test_str == "This is a test");
224                 UASSERT(string_allowed("hello", "abcdefghijklmno") == true);
225                 UASSERT(string_allowed("123", "abcdefghijklmno") == false);
226                 UASSERT(string_allowed_blacklist("hello", "123") == true);
227                 UASSERT(string_allowed_blacklist("hello123", "123") == false);
228                 UASSERT(wrap_rows("12345678",4) == "1234\n5678");
229                 UASSERT(is_number("123") == true);
230                 UASSERT(is_number("") == false);
231                 UASSERT(is_number("123a") == false);
232                 UASSERT(is_power_of_two(0) == false);
233                 UASSERT(is_power_of_two(1) == true);
234                 UASSERT(is_power_of_two(2) == true);
235                 UASSERT(is_power_of_two(3) == false);
236                 for (int exponent = 2; exponent <= 31; ++exponent) {
237                         UASSERT(is_power_of_two((1 << exponent) - 1) == false);
238                         UASSERT(is_power_of_two((1 << exponent)) == true);
239                         UASSERT(is_power_of_two((1 << exponent) + 1) == false);
240                 }
241                 UASSERT(is_power_of_two((u32)-1) == false);
242         }
243 };
244
245 struct TestPath: public TestBase
246 {
247         // adjusts a POSIX path to system-specific conventions
248         // -> changes '/' to DIR_DELIM
249         // -> absolute paths start with "C:\\" on windows
250         std::string p(std::string path)
251         {
252                 for(size_t i = 0; i < path.size(); ++i){
253                         if(path[i] == '/'){
254                                 path.replace(i, 1, DIR_DELIM);
255                                 i += std::string(DIR_DELIM).size() - 1; // generally a no-op
256                         }
257                 }
258
259                 #ifdef _WIN32
260                 if(path[0] == '\\')
261                         path = "C:" + path;
262                 #endif
263
264                 return path;
265         }
266
267         void Run()
268         {
269                 std::string path, result, removed;
270
271                 /*
272                         Test fs::IsDirDelimiter
273                 */
274                 UASSERT(fs::IsDirDelimiter('/') == true);
275                 UASSERT(fs::IsDirDelimiter('A') == false);
276                 UASSERT(fs::IsDirDelimiter(0) == false);
277                 #ifdef _WIN32
278                 UASSERT(fs::IsDirDelimiter('\\') == true);
279                 #else
280                 UASSERT(fs::IsDirDelimiter('\\') == false);
281                 #endif
282
283                 /*
284                         Test fs::PathStartsWith
285                 */
286                 {
287                         const int numpaths = 12;
288                         std::string paths[numpaths] = {
289                                 "",
290                                 p("/"),
291                                 p("/home/user/minetest"),
292                                 p("/home/user/minetest/bin"),
293                                 p("/home/user/.minetest"),
294                                 p("/tmp/dir/file"),
295                                 p("/tmp/file/"),
296                                 p("/tmP/file"),
297                                 p("/tmp"),
298                                 p("/tmp/dir"),
299                                 p("/home/user2/minetest/worlds"),
300                                 p("/home/user2/minetest/world"),
301                         };
302                         /*
303                                 expected fs::PathStartsWith results
304                                 0 = returns false
305                                 1 = returns true
306                                 2 = returns false on windows, true elsewhere
307                                 3 = returns true on windows, false elsewhere
308                                 4 = returns true if and only if
309                                     FILESYS_CASE_INSENSITIVE is true
310                         */
311                         int expected_results[numpaths][numpaths] = {
312                                 {1,2,0,0,0,0,0,0,0,0,0,0},
313                                 {1,1,0,0,0,0,0,0,0,0,0,0},
314                                 {1,1,1,0,0,0,0,0,0,0,0,0},
315                                 {1,1,1,1,0,0,0,0,0,0,0,0},
316                                 {1,1,0,0,1,0,0,0,0,0,0,0},
317                                 {1,1,0,0,0,1,0,0,1,1,0,0},
318                                 {1,1,0,0,0,0,1,4,1,0,0,0},
319                                 {1,1,0,0,0,0,4,1,4,0,0,0},
320                                 {1,1,0,0,0,0,0,0,1,0,0,0},
321                                 {1,1,0,0,0,0,0,0,1,1,0,0},
322                                 {1,1,0,0,0,0,0,0,0,0,1,0},
323                                 {1,1,0,0,0,0,0,0,0,0,0,1},
324                         };
325
326                         for (int i = 0; i < numpaths; i++)
327                         for (int j = 0; j < numpaths; j++){
328                                 /*verbosestream<<"testing fs::PathStartsWith(\""
329                                         <<paths[i]<<"\", \""
330                                         <<paths[j]<<"\")"<<std::endl;*/
331                                 bool starts = fs::PathStartsWith(paths[i], paths[j]);
332                                 int expected = expected_results[i][j];
333                                 if(expected == 0){
334                                         UASSERT(starts == false);
335                                 }
336                                 else if(expected == 1){
337                                         UASSERT(starts == true);
338                                 }
339                                 #ifdef _WIN32
340                                 else if(expected == 2){
341                                         UASSERT(starts == false);
342                                 }
343                                 else if(expected == 3){
344                                         UASSERT(starts == true);
345                                 }
346                                 #else
347                                 else if(expected == 2){
348                                         UASSERT(starts == true);
349                                 }
350                                 else if(expected == 3){
351                                         UASSERT(starts == false);
352                                 }
353                                 #endif
354                                 else if(expected == 4){
355                                         UASSERT(starts == (bool)FILESYS_CASE_INSENSITIVE);
356                                 }
357                         }
358                 }
359
360                 /*
361                         Test fs::RemoveLastPathComponent
362                 */
363                 UASSERT(fs::RemoveLastPathComponent("") == "");
364                 path = p("/home/user/minetest/bin/..//worlds/world1");
365                 result = fs::RemoveLastPathComponent(path, &removed, 0);
366                 UASSERT(result == path);
367                 UASSERT(removed == "");
368                 result = fs::RemoveLastPathComponent(path, &removed, 1);
369                 UASSERT(result == p("/home/user/minetest/bin/..//worlds"));
370                 UASSERT(removed == p("world1"));
371                 result = fs::RemoveLastPathComponent(path, &removed, 2);
372                 UASSERT(result == p("/home/user/minetest/bin/.."));
373                 UASSERT(removed == p("worlds/world1"));
374                 result = fs::RemoveLastPathComponent(path, &removed, 3);
375                 UASSERT(result == p("/home/user/minetest/bin"));
376                 UASSERT(removed == p("../worlds/world1"));
377                 result = fs::RemoveLastPathComponent(path, &removed, 4);
378                 UASSERT(result == p("/home/user/minetest"));
379                 UASSERT(removed == p("bin/../worlds/world1"));
380                 result = fs::RemoveLastPathComponent(path, &removed, 5);
381                 UASSERT(result == p("/home/user"));
382                 UASSERT(removed == p("minetest/bin/../worlds/world1"));
383                 result = fs::RemoveLastPathComponent(path, &removed, 6);
384                 UASSERT(result == p("/home"));
385                 UASSERT(removed == p("user/minetest/bin/../worlds/world1"));
386                 result = fs::RemoveLastPathComponent(path, &removed, 7);
387                 #ifdef _WIN32
388                 UASSERT(result == "C:");
389                 #else
390                 UASSERT(result == "");
391                 #endif
392                 UASSERT(removed == p("home/user/minetest/bin/../worlds/world1"));
393
394                 /*
395                         Now repeat the test with a trailing delimiter
396                 */
397                 path = p("/home/user/minetest/bin/..//worlds/world1/");
398                 result = fs::RemoveLastPathComponent(path, &removed, 0);
399                 UASSERT(result == path);
400                 UASSERT(removed == "");
401                 result = fs::RemoveLastPathComponent(path, &removed, 1);
402                 UASSERT(result == p("/home/user/minetest/bin/..//worlds"));
403                 UASSERT(removed == p("world1"));
404                 result = fs::RemoveLastPathComponent(path, &removed, 2);
405                 UASSERT(result == p("/home/user/minetest/bin/.."));
406                 UASSERT(removed == p("worlds/world1"));
407                 result = fs::RemoveLastPathComponent(path, &removed, 3);
408                 UASSERT(result == p("/home/user/minetest/bin"));
409                 UASSERT(removed == p("../worlds/world1"));
410                 result = fs::RemoveLastPathComponent(path, &removed, 4);
411                 UASSERT(result == p("/home/user/minetest"));
412                 UASSERT(removed == p("bin/../worlds/world1"));
413                 result = fs::RemoveLastPathComponent(path, &removed, 5);
414                 UASSERT(result == p("/home/user"));
415                 UASSERT(removed == p("minetest/bin/../worlds/world1"));
416                 result = fs::RemoveLastPathComponent(path, &removed, 6);
417                 UASSERT(result == p("/home"));
418                 UASSERT(removed == p("user/minetest/bin/../worlds/world1"));
419                 result = fs::RemoveLastPathComponent(path, &removed, 7);
420                 #ifdef _WIN32
421                 UASSERT(result == "C:");
422                 #else
423                 UASSERT(result == "");
424                 #endif
425                 UASSERT(removed == p("home/user/minetest/bin/../worlds/world1"));
426
427                 /*
428                         Test fs::RemoveRelativePathComponent
429                 */
430                 path = p("/home/user/minetest/bin");
431                 result = fs::RemoveRelativePathComponents(path);
432                 UASSERT(result == path);
433                 path = p("/home/user/minetest/bin/../worlds/world1");
434                 result = fs::RemoveRelativePathComponents(path);
435                 UASSERT(result == p("/home/user/minetest/worlds/world1"));
436                 path = p("/home/user/minetest/bin/../worlds/world1/");
437                 result = fs::RemoveRelativePathComponents(path);
438                 UASSERT(result == p("/home/user/minetest/worlds/world1"));
439                 path = p(".");
440                 result = fs::RemoveRelativePathComponents(path);
441                 UASSERT(result == "");
442                 path = p("./subdir/../..");
443                 result = fs::RemoveRelativePathComponents(path);
444                 UASSERT(result == "");
445                 path = p("/a/b/c/.././../d/../e/f/g/../h/i/j/../../../..");
446                 result = fs::RemoveRelativePathComponents(path);
447                 UASSERT(result == p("/a/e"));
448         }
449 };
450
451 #define TEST_CONFIG_TEXT_BEFORE               \
452         "leet = 1337\n"                           \
453         "leetleet = 13371337\n"                   \
454         "leetleet_neg = -13371337\n"              \
455         "floaty_thing = 1.1\n"                    \
456         "stringy_thing = asd /( Â¤%&(/\" BLÖÄRP\n" \
457         "coord = (1, 2, 4.5)\n"                   \
458         "      # this is just a comment\n"        \
459         "this is an invalid line\n"               \
460         "asdf = {\n"                              \
461         "       a   = 5\n"                            \
462         "       bb  = 2.5\n"                          \
463         "       ccc = \"\"\"\n"                       \
464         "testy\n"                                 \
465         "   testa   \n"                           \
466         "\"\"\"\n"                                \
467         "\n"                                      \
468         "}\n"                                     \
469         "blarg = \"\"\" \n"                       \
470         "some multiline text\n"                   \
471         "     with leading whitespace!\n"         \
472         "\"\"\"\n"                                \
473         "np_terrain = 5, 40, (250, 250, 250), 12341, 5, 0.7, 2.4\n" \
474         "zoop = true"
475
476 #define TEST_CONFIG_TEXT_AFTER                \
477         "leet = 1337\n"                           \
478         "leetleet = 13371337\n"                   \
479         "leetleet_neg = -13371337\n"              \
480         "floaty_thing = 1.1\n"                    \
481         "stringy_thing = asd /( Â¤%&(/\" BLÖÄRP\n" \
482         "coord = (1, 2, 4.5)\n"                   \
483         "      # this is just a comment\n"        \
484         "this is an invalid line\n"               \
485         "asdf = {\n"                              \
486         "       a   = 5\n"                            \
487         "       bb  = 2.5\n"                          \
488         "       ccc = \"\"\"\n"                       \
489         "testy\n"                                 \
490         "   testa   \n"                           \
491         "\"\"\"\n"                                \
492         "\n"                                      \
493         "}\n"                                     \
494         "blarg = \"\"\" \n"                       \
495         "some multiline text\n"                   \
496         "     with leading whitespace!\n"         \
497         "\"\"\"\n"                                \
498         "np_terrain = {\n"                        \
499         "       flags = defaults\n"                   \
500         "       lacunarity = 2.4\n"                   \
501         "       octaves = 6\n"                        \
502         "       offset = 3.5\n"                       \
503         "       persistence = 0.7\n"                  \
504         "       scale = 40\n"                         \
505         "       seed = 12341\n"                       \
506         "       spread = (250,250,250)\n"             \
507         "}\n"                                     \
508         "zoop = true\n"                           \
509         "coord2 = (1,2,3.3)\n"                    \
510         "floaty_thing_2 = 1.2\n"                  \
511         "groupy_thing = {\n"                      \
512         "       animals = cute\n"                     \
513         "       num_apples = 4\n"                     \
514         "       num_oranges = 53\n"                   \
515         "}\n"
516
517 struct TestSettings: public TestBase
518 {
519         void Run()
520         {
521                 try {
522                 Settings s;
523
524                 // Test reading of settings
525                 std::istringstream is(TEST_CONFIG_TEXT_BEFORE);
526                 s.parseConfigLines(is);
527
528                 UASSERT(s.getS32("leet") == 1337);
529                 UASSERT(s.getS16("leetleet") == 32767);
530                 UASSERT(s.getS16("leetleet_neg") == -32768);
531
532                 // Not sure if 1.1 is an exact value as a float, but doesn't matter
533                 UASSERT(fabs(s.getFloat("floaty_thing") - 1.1) < 0.001);
534                 UASSERT(s.get("stringy_thing") == "asd /( Â¤%&(/\" BLÖÄRP");
535                 UASSERT(fabs(s.getV3F("coord").X - 1.0) < 0.001);
536                 UASSERT(fabs(s.getV3F("coord").Y - 2.0) < 0.001);
537                 UASSERT(fabs(s.getV3F("coord").Z - 4.5) < 0.001);
538
539                 // Test the setting of settings too
540                 s.setFloat("floaty_thing_2", 1.2);
541                 s.setV3F("coord2", v3f(1, 2, 3.3));
542                 UASSERT(s.get("floaty_thing_2").substr(0,3) == "1.2");
543                 UASSERT(fabs(s.getFloat("floaty_thing_2") - 1.2) < 0.001);
544                 UASSERT(fabs(s.getV3F("coord2").X - 1.0) < 0.001);
545                 UASSERT(fabs(s.getV3F("coord2").Y - 2.0) < 0.001);
546                 UASSERT(fabs(s.getV3F("coord2").Z - 3.3) < 0.001);
547
548                 // Test settings groups
549                 Settings *group = s.getGroup("asdf");
550                 UASSERT(group != NULL);
551                 UASSERT(s.getGroupNoEx("zoop", group) == false);
552                 UASSERT(group->getS16("a") == 5);
553                 UASSERT(fabs(group->getFloat("bb") - 2.5) < 0.001);
554
555                 Settings *group3 = new Settings;
556                 group3->set("cat", "meow");
557                 group3->set("dog", "woof");
558
559                 Settings *group2 = new Settings;
560                 group2->setS16("num_apples", 4);
561                 group2->setS16("num_oranges", 53);
562                 group2->setGroup("animals", group3);
563                 group2->set("animals", "cute"); //destroys group 3
564                 s.setGroup("groupy_thing", group2);
565
566                 // Test set failure conditions
567                 UASSERT(s.set("Zoop = Poop\nsome_other_setting", "false") == false);
568                 UASSERT(s.set("sneaky", "\"\"\"\njabberwocky = false") == false);
569                 UASSERT(s.set("hehe", "asdfasdf\n\"\"\"\nsomething = false") == false);
570
571                 // Test multiline settings
572                 UASSERT(group->get("ccc") == "testy\n   testa   ");
573
574                 UASSERT(s.get("blarg") ==
575                         "some multiline text\n"
576                         "     with leading whitespace!");
577
578                 // Test NoiseParams
579                 UASSERT(s.getEntry("np_terrain").is_group == false);
580
581                 NoiseParams np;
582                 UASSERT(s.getNoiseParams("np_terrain", np) == true);
583                 UASSERT(fabs(np.offset - 5) < 0.001);
584                 UASSERT(fabs(np.scale - 40) < 0.001);
585                 UASSERT(fabs(np.spread.X - 250) < 0.001);
586                 UASSERT(fabs(np.spread.Y - 250) < 0.001);
587                 UASSERT(fabs(np.spread.Z - 250) < 0.001);
588                 UASSERT(np.seed == 12341);
589                 UASSERT(np.octaves == 5);
590                 UASSERT(fabs(np.persist - 0.7) < 0.001);
591
592                 np.offset  = 3.5;
593                 np.octaves = 6;
594                 s.setNoiseParams("np_terrain", np);
595
596                 UASSERT(s.getEntry("np_terrain").is_group == true);
597
598                 // Test writing
599                 std::ostringstream os(std::ios_base::binary);
600                 is.clear();
601                 is.seekg(0);
602
603                 UASSERT(s.updateConfigObject(is, os, "", 0) == true);
604                 //printf(">>>> expected config:\n%s\n", TEST_CONFIG_TEXT_AFTER);
605                 //printf(">>>> actual config:\n%s\n", os.str().c_str());
606                 UASSERT(os.str() == TEST_CONFIG_TEXT_AFTER);
607                 } catch (SettingNotFoundException &e) {
608                         UASSERT(!"Setting not found!");
609                 }
610         }
611 };
612
613 struct TestSerialization: public TestBase
614 {
615         // To be used like this:
616         //   mkstr("Some\0string\0with\0embedded\0nuls")
617         // since std::string("...") doesn't work as expected in that case.
618         template<size_t N> std::string mkstr(const char (&s)[N])
619         {
620                 return std::string(s, N - 1);
621         }
622
623         void Run()
624         {
625                 // Tests some serialization primitives
626
627                 UASSERT(serializeString("") == mkstr("\0\0"));
628                 UASSERT(serializeWideString(L"") == mkstr("\0\0"));
629                 UASSERT(serializeLongString("") == mkstr("\0\0\0\0"));
630                 UASSERT(serializeJsonString("") == "\"\"");
631
632                 std::string teststring = "Hello world!";
633                 UASSERT(serializeString(teststring) ==
634                         mkstr("\0\14Hello world!"));
635                 UASSERT(serializeWideString(narrow_to_wide(teststring)) ==
636                         mkstr("\0\14\0H\0e\0l\0l\0o\0 \0w\0o\0r\0l\0d\0!"));
637                 UASSERT(serializeLongString(teststring) ==
638                         mkstr("\0\0\0\14Hello world!"));
639                 UASSERT(serializeJsonString(teststring) ==
640                         "\"Hello world!\"");
641
642                 std::string teststring2;
643                 std::wstring teststring2_w;
644                 std::string teststring2_w_encoded;
645                 {
646                         std::ostringstream tmp_os;
647                         std::wostringstream tmp_os_w;
648                         std::ostringstream tmp_os_w_encoded;
649                         for(int i = 0; i < 256; i++)
650                         {
651                                 tmp_os<<(char)i;
652                                 tmp_os_w<<(wchar_t)i;
653                                 tmp_os_w_encoded<<(char)0<<(char)i;
654                         }
655                         teststring2 = tmp_os.str();
656                         teststring2_w = tmp_os_w.str();
657                         teststring2_w_encoded = tmp_os_w_encoded.str();
658                 }
659                 UASSERT(serializeString(teststring2) ==
660                         mkstr("\1\0") + teststring2);
661                 UASSERT(serializeWideString(teststring2_w) ==
662                         mkstr("\1\0") + teststring2_w_encoded);
663                 UASSERT(serializeLongString(teststring2) ==
664                         mkstr("\0\0\1\0") + teststring2);
665                 // MSVC fails when directly using "\\\\"
666                 std::string backslash = "\\";
667                 UASSERT(serializeJsonString(teststring2) ==
668                         mkstr("\"") +
669                         "\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007" +
670                         "\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f" +
671                         "\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017" +
672                         "\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f" +
673                         " !\\\"" + teststring2.substr(0x23, 0x2f-0x23) +
674                         "\\/" + teststring2.substr(0x30, 0x5c-0x30) +
675                         backslash + backslash + teststring2.substr(0x5d, 0x7f-0x5d) + "\\u007f" +
676                         "\\u0080\\u0081\\u0082\\u0083\\u0084\\u0085\\u0086\\u0087" +
677                         "\\u0088\\u0089\\u008a\\u008b\\u008c\\u008d\\u008e\\u008f" +
678                         "\\u0090\\u0091\\u0092\\u0093\\u0094\\u0095\\u0096\\u0097" +
679                         "\\u0098\\u0099\\u009a\\u009b\\u009c\\u009d\\u009e\\u009f" +
680                         "\\u00a0\\u00a1\\u00a2\\u00a3\\u00a4\\u00a5\\u00a6\\u00a7" +
681                         "\\u00a8\\u00a9\\u00aa\\u00ab\\u00ac\\u00ad\\u00ae\\u00af" +
682                         "\\u00b0\\u00b1\\u00b2\\u00b3\\u00b4\\u00b5\\u00b6\\u00b7" +
683                         "\\u00b8\\u00b9\\u00ba\\u00bb\\u00bc\\u00bd\\u00be\\u00bf" +
684                         "\\u00c0\\u00c1\\u00c2\\u00c3\\u00c4\\u00c5\\u00c6\\u00c7" +
685                         "\\u00c8\\u00c9\\u00ca\\u00cb\\u00cc\\u00cd\\u00ce\\u00cf" +
686                         "\\u00d0\\u00d1\\u00d2\\u00d3\\u00d4\\u00d5\\u00d6\\u00d7" +
687                         "\\u00d8\\u00d9\\u00da\\u00db\\u00dc\\u00dd\\u00de\\u00df" +
688                         "\\u00e0\\u00e1\\u00e2\\u00e3\\u00e4\\u00e5\\u00e6\\u00e7" +
689                         "\\u00e8\\u00e9\\u00ea\\u00eb\\u00ec\\u00ed\\u00ee\\u00ef" +
690                         "\\u00f0\\u00f1\\u00f2\\u00f3\\u00f4\\u00f5\\u00f6\\u00f7" +
691                         "\\u00f8\\u00f9\\u00fa\\u00fb\\u00fc\\u00fd\\u00fe\\u00ff" +
692                         "\"");
693
694                 {
695                         std::istringstream is(serializeString(teststring2), std::ios::binary);
696                         UASSERT(deSerializeString(is) == teststring2);
697                         UASSERT(!is.eof());
698                         is.get();
699                         UASSERT(is.eof());
700                 }
701                 {
702                         std::istringstream is(serializeWideString(teststring2_w), std::ios::binary);
703                         UASSERT(deSerializeWideString(is) == teststring2_w);
704                         UASSERT(!is.eof());
705                         is.get();
706                         UASSERT(is.eof());
707                 }
708                 {
709                         std::istringstream is(serializeLongString(teststring2), std::ios::binary);
710                         UASSERT(deSerializeLongString(is) == teststring2);
711                         UASSERT(!is.eof());
712                         is.get();
713                         UASSERT(is.eof());
714                 }
715                 {
716                         std::istringstream is(serializeJsonString(teststring2), std::ios::binary);
717                         //dstream<<serializeJsonString(deSerializeJsonString(is));
718                         UASSERT(deSerializeJsonString(is) == teststring2);
719                         UASSERT(!is.eof());
720                         is.get();
721                         UASSERT(is.eof());
722                 }
723         }
724 };
725
726 struct TestNodedefSerialization: public TestBase
727 {
728         void Run()
729         {
730                 ContentFeatures f;
731                 f.name = "default:stone";
732                 for(int i = 0; i < 6; i++)
733                         f.tiledef[i].name = "default_stone.png";
734                 f.is_ground_content = true;
735                 std::ostringstream os(std::ios::binary);
736                 f.serialize(os, LATEST_PROTOCOL_VERSION);
737                 verbosestream<<"Test ContentFeatures size: "<<os.str().size()<<std::endl;
738                 std::istringstream is(os.str(), std::ios::binary);
739                 ContentFeatures f2;
740                 f2.deSerialize(is);
741                 UASSERT(f.walkable == f2.walkable);
742                 UASSERT(f.node_box.type == f2.node_box.type);
743         }
744 };
745
746 struct TestCompress: public TestBase
747 {
748         void Run()
749         {
750                 { // ver 0
751
752                 SharedBuffer<u8> fromdata(4);
753                 fromdata[0]=1;
754                 fromdata[1]=5;
755                 fromdata[2]=5;
756                 fromdata[3]=1;
757
758                 std::ostringstream os(std::ios_base::binary);
759                 compress(fromdata, os, 0);
760
761                 std::string str_out = os.str();
762
763                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
764                 infostream<<"TestCompress: 1,5,5,1 -> ";
765                 for(u32 i=0; i<str_out.size(); i++)
766                 {
767                         infostream<<(u32)str_out[i]<<",";
768                 }
769                 infostream<<std::endl;
770
771                 UASSERT(str_out.size() == 10);
772
773                 UASSERT(str_out[0] == 0);
774                 UASSERT(str_out[1] == 0);
775                 UASSERT(str_out[2] == 0);
776                 UASSERT(str_out[3] == 4);
777                 UASSERT(str_out[4] == 0);
778                 UASSERT(str_out[5] == 1);
779                 UASSERT(str_out[6] == 1);
780                 UASSERT(str_out[7] == 5);
781                 UASSERT(str_out[8] == 0);
782                 UASSERT(str_out[9] == 1);
783
784                 std::istringstream is(str_out, std::ios_base::binary);
785                 std::ostringstream os2(std::ios_base::binary);
786
787                 decompress(is, os2, 0);
788                 std::string str_out2 = os2.str();
789
790                 infostream<<"decompress: ";
791                 for(u32 i=0; i<str_out2.size(); i++)
792                 {
793                         infostream<<(u32)str_out2[i]<<",";
794                 }
795                 infostream<<std::endl;
796
797                 UASSERT(str_out2.size() == fromdata.getSize());
798
799                 for(u32 i=0; i<str_out2.size(); i++)
800                 {
801                         UASSERT(str_out2[i] == fromdata[i]);
802                 }
803
804                 }
805
806                 { // ver HIGHEST
807
808                 SharedBuffer<u8> fromdata(4);
809                 fromdata[0]=1;
810                 fromdata[1]=5;
811                 fromdata[2]=5;
812                 fromdata[3]=1;
813
814                 std::ostringstream os(std::ios_base::binary);
815                 compress(fromdata, os, SER_FMT_VER_HIGHEST_READ);
816
817                 std::string str_out = os.str();
818
819                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
820                 infostream<<"TestCompress: 1,5,5,1 -> ";
821                 for(u32 i=0; i<str_out.size(); i++)
822                 {
823                         infostream<<(u32)str_out[i]<<",";
824                 }
825                 infostream<<std::endl;
826
827                 std::istringstream is(str_out, std::ios_base::binary);
828                 std::ostringstream os2(std::ios_base::binary);
829
830                 decompress(is, os2, SER_FMT_VER_HIGHEST_READ);
831                 std::string str_out2 = os2.str();
832
833                 infostream<<"decompress: ";
834                 for(u32 i=0; i<str_out2.size(); i++)
835                 {
836                         infostream<<(u32)str_out2[i]<<",";
837                 }
838                 infostream<<std::endl;
839
840                 UASSERT(str_out2.size() == fromdata.getSize());
841
842                 for(u32 i=0; i<str_out2.size(); i++)
843                 {
844                         UASSERT(str_out2[i] == fromdata[i]);
845                 }
846
847                 }
848
849                 // Test zlib wrapper with large amounts of data (larger than its
850                 // internal buffers)
851                 {
852                         infostream<<"Test: Testing zlib wrappers with a large amount "
853                                         <<"of pseudorandom data"<<std::endl;
854                         u32 size = 50000;
855                         infostream<<"Test: Input size of large compressZlib is "
856                                         <<size<<std::endl;
857                         std::string data_in;
858                         data_in.resize(size);
859                         PseudoRandom pseudorandom(9420);
860                         for(u32 i=0; i<size; i++)
861                                 data_in[i] = pseudorandom.range(0,255);
862                         std::ostringstream os_compressed(std::ios::binary);
863                         compressZlib(data_in, os_compressed);
864                         infostream<<"Test: Output size of large compressZlib is "
865                                         <<os_compressed.str().size()<<std::endl;
866                         std::istringstream is_compressed(os_compressed.str(), std::ios::binary);
867                         std::ostringstream os_decompressed(std::ios::binary);
868                         decompressZlib(is_compressed, os_decompressed);
869                         infostream<<"Test: Output size of large decompressZlib is "
870                                         <<os_decompressed.str().size()<<std::endl;
871                         std::string str_decompressed = os_decompressed.str();
872                         UTEST(str_decompressed.size() == data_in.size(), "Output size not"
873                                         " equal (output: %u, input: %u)",
874                                         (unsigned int)str_decompressed.size(), (unsigned int)data_in.size());
875                         for(u32 i=0; i<size && i<str_decompressed.size(); i++){
876                                 UTEST(str_decompressed[i] == data_in[i],
877                                                 "index out[%i]=%i differs from in[%i]=%i",
878                                                 i, str_decompressed[i], i, data_in[i]);
879                         }
880                 }
881         }
882 };
883
884 struct TestMapNode: public TestBase
885 {
886         void Run(INodeDefManager *nodedef)
887         {
888                 MapNode n(CONTENT_AIR);
889
890                 UASSERT(n.getContent() == CONTENT_AIR);
891                 UASSERT(n.getLight(LIGHTBANK_DAY, nodedef) == 0);
892                 UASSERT(n.getLight(LIGHTBANK_NIGHT, nodedef) == 0);
893
894                 // Transparency
895                 n.setContent(CONTENT_AIR);
896                 UASSERT(nodedef->get(n).light_propagates == true);
897                 n.setContent(LEGN(nodedef, "CONTENT_STONE"));
898                 UASSERT(nodedef->get(n).light_propagates == false);
899         }
900 };
901
902 struct TestVoxelManipulator: public TestBase
903 {
904         void Run(INodeDefManager *nodedef)
905         {
906                 /*
907                         VoxelArea
908                 */
909
910                 VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1));
911                 UASSERT(a.index(0,0,0) == 1*3*3 + 1*3 + 1);
912                 UASSERT(a.index(-1,-1,-1) == 0);
913
914                 VoxelArea c(v3s16(-2,-2,-2), v3s16(2,2,2));
915                 // An area that is 1 bigger in x+ and z-
916                 VoxelArea d(v3s16(-2,-2,-3), v3s16(3,2,2));
917
918                 std::list<VoxelArea> aa;
919                 d.diff(c, aa);
920
921                 // Correct results
922                 std::vector<VoxelArea> results;
923                 results.push_back(VoxelArea(v3s16(-2,-2,-3),v3s16(3,2,-3)));
924                 results.push_back(VoxelArea(v3s16(3,-2,-2),v3s16(3,2,2)));
925
926                 UASSERT(aa.size() == results.size());
927
928                 infostream<<"Result of diff:"<<std::endl;
929                 for(std::list<VoxelArea>::const_iterator
930                                 i = aa.begin(); i != aa.end(); ++i)
931                 {
932                         i->print(infostream);
933                         infostream<<std::endl;
934
935                         std::vector<VoxelArea>::iterator j = std::find(results.begin(), results.end(), *i);
936                         UASSERT(j != results.end());
937                         results.erase(j);
938                 }
939
940
941                 /*
942                         VoxelManipulator
943                 */
944
945                 VoxelManipulator v;
946
947                 v.print(infostream, nodedef);
948
949                 infostream<<"*** Setting (-1,0,-1)=2 ***"<<std::endl;
950
951                 v.setNodeNoRef(v3s16(-1,0,-1), MapNode(CONTENT_GRASS));
952
953                 v.print(infostream, nodedef);
954
955                 UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
956
957                 infostream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl;
958
959                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1)));
960
961                 v.print(infostream, nodedef);
962
963                 infostream<<"*** Adding area ***"<<std::endl;
964
965                 v.addArea(a);
966
967                 v.print(infostream, nodedef);
968
969                 UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
970                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1)));
971         }
972 };
973
974 struct TestVoxelAlgorithms: public TestBase
975 {
976         void Run(INodeDefManager *ndef)
977         {
978                 /*
979                         voxalgo::propagateSunlight
980                 */
981                 {
982                         VoxelManipulator v;
983                         for(u16 z=0; z<3; z++)
984                         for(u16 y=0; y<3; y++)
985                         for(u16 x=0; x<3; x++)
986                         {
987                                 v3s16 p(x,y,z);
988                                 v.setNodeNoRef(p, MapNode(CONTENT_AIR));
989                         }
990                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
991                         {
992                                 std::set<v3s16> light_sources;
993                                 voxalgo::setLight(v, a, 0, ndef);
994                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
995                                                 v, a, true, light_sources, ndef);
996                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
997                                 UASSERT(res.bottom_sunlight_valid == true);
998                                 UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
999                                                 == LIGHT_SUN);
1000                         }
1001                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
1002                         {
1003                                 std::set<v3s16> light_sources;
1004                                 voxalgo::setLight(v, a, 0, ndef);
1005                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1006                                                 v, a, true, light_sources, ndef);
1007                                 UASSERT(res.bottom_sunlight_valid == true);
1008                                 UASSERT(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
1009                                                 == LIGHT_SUN);
1010                         }
1011                         {
1012                                 std::set<v3s16> light_sources;
1013                                 voxalgo::setLight(v, a, 0, ndef);
1014                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1015                                                 v, a, false, light_sources, ndef);
1016                                 UASSERT(res.bottom_sunlight_valid == true);
1017                                 UASSERT(v.getNode(v3s16(2,0,2)).getLight(LIGHTBANK_DAY, ndef)
1018                                                 == 0);
1019                         }
1020                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_STONE));
1021                         {
1022                                 std::set<v3s16> light_sources;
1023                                 voxalgo::setLight(v, a, 0, ndef);
1024                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1025                                                 v, a, true, light_sources, ndef);
1026                                 UASSERT(res.bottom_sunlight_valid == true);
1027                                 UASSERT(v.getNode(v3s16(1,1,2)).getLight(LIGHTBANK_DAY, ndef)
1028                                                 == 0);
1029                         }
1030                         {
1031                                 std::set<v3s16> light_sources;
1032                                 voxalgo::setLight(v, a, 0, ndef);
1033                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1034                                                 v, a, false, light_sources, ndef);
1035                                 UASSERT(res.bottom_sunlight_valid == true);
1036                                 UASSERT(v.getNode(v3s16(1,0,2)).getLight(LIGHTBANK_DAY, ndef)
1037                                                 == 0);
1038                         }
1039                         {
1040                                 MapNode n(CONTENT_AIR);
1041                                 n.setLight(LIGHTBANK_DAY, 10, ndef);
1042                                 v.setNodeNoRef(v3s16(1,-1,2), n);
1043                         }
1044                         {
1045                                 std::set<v3s16> light_sources;
1046                                 voxalgo::setLight(v, a, 0, ndef);
1047                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1048                                                 v, a, true, light_sources, ndef);
1049                                 UASSERT(res.bottom_sunlight_valid == true);
1050                         }
1051                         {
1052                                 std::set<v3s16> light_sources;
1053                                 voxalgo::setLight(v, a, 0, ndef);
1054                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1055                                                 v, a, false, light_sources, ndef);
1056                                 UASSERT(res.bottom_sunlight_valid == true);
1057                         }
1058                         {
1059                                 MapNode n(CONTENT_AIR);
1060                                 n.setLight(LIGHTBANK_DAY, LIGHT_SUN, ndef);
1061                                 v.setNodeNoRef(v3s16(1,-1,2), n);
1062                         }
1063                         {
1064                                 std::set<v3s16> light_sources;
1065                                 voxalgo::setLight(v, a, 0, ndef);
1066                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1067                                                 v, a, true, light_sources, ndef);
1068                                 UASSERT(res.bottom_sunlight_valid == false);
1069                         }
1070                         {
1071                                 std::set<v3s16> light_sources;
1072                                 voxalgo::setLight(v, a, 0, ndef);
1073                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1074                                                 v, a, false, light_sources, ndef);
1075                                 UASSERT(res.bottom_sunlight_valid == false);
1076                         }
1077                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_IGNORE));
1078                         {
1079                                 std::set<v3s16> light_sources;
1080                                 voxalgo::setLight(v, a, 0, ndef);
1081                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
1082                                                 v, a, true, light_sources, ndef);
1083                                 UASSERT(res.bottom_sunlight_valid == true);
1084                         }
1085                 }
1086                 /*
1087                         voxalgo::clearLightAndCollectSources
1088                 */
1089                 {
1090                         VoxelManipulator v;
1091                         for(u16 z=0; z<3; z++)
1092                         for(u16 y=0; y<3; y++)
1093                         for(u16 x=0; x<3; x++)
1094                         {
1095                                 v3s16 p(x,y,z);
1096                                 v.setNode(p, MapNode(CONTENT_AIR));
1097                         }
1098                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
1099                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
1100                         v.setNodeNoRef(v3s16(1,1,1), MapNode(CONTENT_TORCH));
1101                         {
1102                                 MapNode n(CONTENT_AIR);
1103                                 n.setLight(LIGHTBANK_DAY, 1, ndef);
1104                                 v.setNode(v3s16(1,1,2), n);
1105                         }
1106                         {
1107                                 std::set<v3s16> light_sources;
1108                                 std::map<v3s16, u8> unlight_from;
1109                                 voxalgo::clearLightAndCollectSources(v, a, LIGHTBANK_DAY,
1110                                                 ndef, light_sources, unlight_from);
1111                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
1112                                 UASSERT(v.getNode(v3s16(0,1,1)).getLight(LIGHTBANK_DAY, ndef)
1113                                                 == 0);
1114                                 UASSERT(light_sources.find(v3s16(1,1,1)) != light_sources.end());
1115                                 UASSERT(light_sources.size() == 1);
1116                                 UASSERT(unlight_from.find(v3s16(1,1,2)) != unlight_from.end());
1117                                 UASSERT(unlight_from.size() == 1);
1118                         }
1119                 }
1120         }
1121 };
1122
1123 struct TestInventory: public TestBase
1124 {
1125         void Run(IItemDefManager *idef)
1126         {
1127                 std::string serialized_inventory =
1128                 "List 0 32\n"
1129                 "Width 3\n"
1130                 "Empty\n"
1131                 "Empty\n"
1132                 "Empty\n"
1133                 "Empty\n"
1134                 "Empty\n"
1135                 "Empty\n"
1136                 "Empty\n"
1137                 "Empty\n"
1138                 "Empty\n"
1139                 "Item default:cobble 61\n"
1140                 "Empty\n"
1141                 "Empty\n"
1142                 "Empty\n"
1143                 "Empty\n"
1144                 "Empty\n"
1145                 "Empty\n"
1146                 "Item default:dirt 71\n"
1147                 "Empty\n"
1148                 "Empty\n"
1149                 "Empty\n"
1150                 "Empty\n"
1151                 "Empty\n"
1152                 "Empty\n"
1153                 "Empty\n"
1154                 "Item default:dirt 99\n"
1155                 "Item default:cobble 38\n"
1156                 "Empty\n"
1157                 "Empty\n"
1158                 "Empty\n"
1159                 "Empty\n"
1160                 "Empty\n"
1161                 "Empty\n"
1162                 "EndInventoryList\n"
1163                 "EndInventory\n";
1164
1165                 std::string serialized_inventory_2 =
1166                 "List main 32\n"
1167                 "Width 5\n"
1168                 "Empty\n"
1169                 "Empty\n"
1170                 "Empty\n"
1171                 "Empty\n"
1172                 "Empty\n"
1173                 "Empty\n"
1174                 "Empty\n"
1175                 "Empty\n"
1176                 "Empty\n"
1177                 "Item default:cobble 61\n"
1178                 "Empty\n"
1179                 "Empty\n"
1180                 "Empty\n"
1181                 "Empty\n"
1182                 "Empty\n"
1183                 "Empty\n"
1184                 "Item default:dirt 71\n"
1185                 "Empty\n"
1186                 "Empty\n"
1187                 "Empty\n"
1188                 "Empty\n"
1189                 "Empty\n"
1190                 "Empty\n"
1191                 "Empty\n"
1192                 "Item default:dirt 99\n"
1193                 "Item default:cobble 38\n"
1194                 "Empty\n"
1195                 "Empty\n"
1196                 "Empty\n"
1197                 "Empty\n"
1198                 "Empty\n"
1199                 "Empty\n"
1200                 "EndInventoryList\n"
1201                 "EndInventory\n";
1202
1203                 Inventory inv(idef);
1204                 std::istringstream is(serialized_inventory, std::ios::binary);
1205                 inv.deSerialize(is);
1206                 UASSERT(inv.getList("0"));
1207                 UASSERT(!inv.getList("main"));
1208                 inv.getList("0")->setName("main");
1209                 UASSERT(!inv.getList("0"));
1210                 UASSERT(inv.getList("main"));
1211                 UASSERT(inv.getList("main")->getWidth() == 3);
1212                 inv.getList("main")->setWidth(5);
1213                 std::ostringstream inv_os(std::ios::binary);
1214                 inv.serialize(inv_os);
1215                 UASSERT(inv_os.str() == serialized_inventory_2);
1216         }
1217 };
1218
1219 /*
1220         NOTE: These tests became non-working then NodeContainer was removed.
1221               These should be redone, utilizing some kind of a virtual
1222                   interface for Map (IMap would be fine).
1223 */
1224 #if 0
1225 struct TestMapBlock: public TestBase
1226 {
1227         class TC : public NodeContainer
1228         {
1229         public:
1230
1231                 MapNode node;
1232                 bool position_valid;
1233                 core::list<v3s16> validity_exceptions;
1234
1235                 TC()
1236                 {
1237                         position_valid = true;
1238                 }
1239
1240                 virtual bool isValidPosition(v3s16 p)
1241                 {
1242                         //return position_valid ^ (p==position_valid_exception);
1243                         bool exception = false;
1244                         for(core::list<v3s16>::Iterator i=validity_exceptions.begin();
1245                                         i != validity_exceptions.end(); i++)
1246                         {
1247                                 if(p == *i)
1248                                 {
1249                                         exception = true;
1250                                         break;
1251                                 }
1252                         }
1253                         return exception ? !position_valid : position_valid;
1254                 }
1255
1256                 virtual MapNode getNode(v3s16 p)
1257                 {
1258                         if(isValidPosition(p) == false)
1259                                 throw InvalidPositionException();
1260                         return node;
1261                 }
1262
1263                 virtual void setNode(v3s16 p, MapNode & n)
1264                 {
1265                         if(isValidPosition(p) == false)
1266                                 throw InvalidPositionException();
1267                 };
1268
1269                 virtual u16 nodeContainerId() const
1270                 {
1271                         return 666;
1272                 }
1273         };
1274
1275         void Run()
1276         {
1277                 TC parent;
1278
1279                 MapBlock b(&parent, v3s16(1,1,1));
1280                 v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
1281
1282                 UASSERT(b.getPosRelative() == relpos);
1283
1284                 UASSERT(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
1285                 UASSERT(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
1286                 UASSERT(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
1287                 UASSERT(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
1288                 UASSERT(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
1289                 UASSERT(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
1290
1291                 UASSERT(b.isValidPosition(v3s16(0,0,0)) == true);
1292                 UASSERT(b.isValidPosition(v3s16(-1,0,0)) == false);
1293                 UASSERT(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
1294                 UASSERT(b.isValidPosition(v3s16(-124,142,2341)) == false);
1295                 UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
1296                 UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);
1297
1298                 /*
1299                         TODO: this method should probably be removed
1300                         if the block size isn't going to be set variable
1301                 */
1302                 /*UASSERT(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
1303                                 MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
1304
1305                 // Changed flag should be initially set
1306                 UASSERT(b.getModified() == MOD_STATE_WRITE_NEEDED);
1307                 b.resetModified();
1308                 UASSERT(b.getModified() == MOD_STATE_CLEAN);
1309
1310                 // All nodes should have been set to
1311                 // .d=CONTENT_IGNORE and .getLight() = 0
1312                 for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1313                 for(u16 y=0; y<MAP_BLOCKSIZE; y++)
1314                 for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1315                 {
1316                         //UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR);
1317                         UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE);
1318                         UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0);
1319                         UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0);
1320                 }
1321
1322                 {
1323                         MapNode n(CONTENT_AIR);
1324                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1325                         for(u16 y=0; y<MAP_BLOCKSIZE; y++)
1326                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1327                         {
1328                                 b.setNode(v3s16(x,y,z), n);
1329                         }
1330                 }
1331
1332                 /*
1333                         Parent fetch functions
1334                 */
1335                 parent.position_valid = false;
1336                 parent.node.setContent(5);
1337
1338                 MapNode n;
1339
1340                 // Positions in the block should still be valid
1341                 UASSERT(b.isValidPositionParent(v3s16(0,0,0)) == true);
1342                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
1343                 n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
1344                 UASSERT(n.getContent() == CONTENT_AIR);
1345
1346                 // ...but outside the block they should be invalid
1347                 UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
1348                 UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == false);
1349                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
1350
1351                 {
1352                         bool exception_thrown = false;
1353                         try{
1354                                 // This should throw an exception
1355                                 MapNode n = b.getNodeParent(v3s16(0,0,-1));
1356                         }
1357                         catch(InvalidPositionException &e)
1358                         {
1359                                 exception_thrown = true;
1360                         }
1361                         UASSERT(exception_thrown);
1362                 }
1363
1364                 parent.position_valid = true;
1365                 // Now the positions outside should be valid
1366                 UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
1367                 UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == true);
1368                 UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
1369                 n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
1370                 UASSERT(n.getContent() == 5);
1371
1372                 /*
1373                         Set a node
1374                 */
1375                 v3s16 p(1,2,0);
1376                 n.setContent(4);
1377                 b.setNode(p, n);
1378                 UASSERT(b.getNode(p).getContent() == 4);
1379                 //TODO: Update to new system
1380                 /*UASSERT(b.getNodeTile(p) == 4);
1381                 UASSERT(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/
1382
1383                 /*
1384                         propagateSunlight()
1385                 */
1386                 // Set lighting of all nodes to 0
1387                 for(u16 z=0; z<MAP_BLOCKSIZE; z++){
1388                         for(u16 y=0; y<MAP_BLOCKSIZE; y++){
1389                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
1390                                         MapNode n = b.getNode(v3s16(x,y,z));
1391                                         n.setLight(LIGHTBANK_DAY, 0);
1392                                         n.setLight(LIGHTBANK_NIGHT, 0);
1393                                         b.setNode(v3s16(x,y,z), n);
1394                                 }
1395                         }
1396                 }
1397                 {
1398                         /*
1399                                 Check how the block handles being a lonely sky block
1400                         */
1401                         parent.position_valid = true;
1402                         b.setIsUnderground(false);
1403                         parent.node.setContent(CONTENT_AIR);
1404                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN);
1405                         parent.node.setLight(LIGHTBANK_NIGHT, 0);
1406                         core::map<v3s16, bool> light_sources;
1407                         // The bottom block is invalid, because we have a shadowing node
1408                         UASSERT(b.propagateSunlight(light_sources) == false);
1409                         UASSERT(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1410                         UASSERT(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1411                         UASSERT(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0);
1412                         UASSERT(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0);
1413                         UASSERT(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0);
1414                         UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
1415                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN);
1416                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0);
1417                         UASSERT(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0);
1418                         // According to MapBlock::getFaceLight,
1419                         // The face on the z+ side should have double-diminished light
1420                         //UASSERT(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
1421                         // The face on the z+ side should have diminished light
1422                         UASSERT(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX));
1423                 }
1424                 /*
1425                         Check how the block handles being in between blocks with some non-sunlight
1426                         while being underground
1427                 */
1428                 {
1429                         // Make neighbours to exist and set some non-sunlight to them
1430                         parent.position_valid = true;
1431                         b.setIsUnderground(true);
1432                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1433                         core::map<v3s16, bool> light_sources;
1434                         // The block below should be valid because there shouldn't be
1435                         // sunlight in there either
1436                         UASSERT(b.propagateSunlight(light_sources, true) == true);
1437                         // Should not touch nodes that are not affected (that is, all of them)
1438                         //UASSERT(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
1439                         // Should set light of non-sunlighted blocks to 0.
1440                         UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0);
1441                 }
1442                 /*
1443                         Set up a situation where:
1444                         - There is only air in this block
1445                         - There is a valid non-sunlighted block at the bottom, and
1446                         - Invalid blocks elsewhere.
1447                         - the block is not underground.
1448
1449                         This should result in bottom block invalidity
1450                 */
1451                 {
1452                         b.setIsUnderground(false);
1453                         // Clear block
1454                         for(u16 z=0; z<MAP_BLOCKSIZE; z++){
1455                                 for(u16 y=0; y<MAP_BLOCKSIZE; y++){
1456                                         for(u16 x=0; x<MAP_BLOCKSIZE; x++){
1457                                                 MapNode n;
1458                                                 n.setContent(CONTENT_AIR);
1459                                                 n.setLight(LIGHTBANK_DAY, 0);
1460                                                 b.setNode(v3s16(x,y,z), n);
1461                                         }
1462                                 }
1463                         }
1464                         // Make neighbours invalid
1465                         parent.position_valid = false;
1466                         // Add exceptions to the top of the bottom block
1467                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
1468                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
1469                         {
1470                                 parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
1471                         }
1472                         // Lighting value for the valid nodes
1473                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1474                         core::map<v3s16, bool> light_sources;
1475                         // Bottom block is not valid
1476                         UASSERT(b.propagateSunlight(light_sources) == false);
1477                 }
1478         }
1479 };
1480
1481 struct TestMapSector: public TestBase
1482 {
1483         class TC : public NodeContainer
1484         {
1485         public:
1486
1487                 MapNode node;
1488                 bool position_valid;
1489
1490                 TC()
1491                 {
1492                         position_valid = true;
1493                 }
1494
1495                 virtual bool isValidPosition(v3s16 p)
1496                 {
1497                         return position_valid;
1498                 }
1499
1500                 virtual MapNode getNode(v3s16 p)
1501                 {
1502                         if(position_valid == false)
1503                                 throw InvalidPositionException();
1504                         return node;
1505                 }
1506
1507                 virtual void setNode(v3s16 p, MapNode & n)
1508                 {
1509                         if(position_valid == false)
1510                                 throw InvalidPositionException();
1511                 };
1512
1513                 virtual u16 nodeContainerId() const
1514                 {
1515                         return 666;
1516                 }
1517         };
1518
1519         void Run()
1520         {
1521                 TC parent;
1522                 parent.position_valid = false;
1523
1524                 // Create one with no heightmaps
1525                 ServerMapSector sector(&parent, v2s16(1,1));
1526
1527                 UASSERT(sector.getBlockNoCreateNoEx(0) == 0);
1528                 UASSERT(sector.getBlockNoCreateNoEx(1) == 0);
1529
1530                 MapBlock * bref = sector.createBlankBlock(-2);
1531
1532                 UASSERT(sector.getBlockNoCreateNoEx(0) == 0);
1533                 UASSERT(sector.getBlockNoCreateNoEx(-2) == bref);
1534
1535                 //TODO: Check for AlreadyExistsException
1536
1537                 /*bool exception_thrown = false;
1538                 try{
1539                         sector.getBlock(0);
1540                 }
1541                 catch(InvalidPositionException &e){
1542                         exception_thrown = true;
1543                 }
1544                 UASSERT(exception_thrown);*/
1545
1546         }
1547 };
1548 #endif
1549
1550 struct TestCollision: public TestBase
1551 {
1552         void Run()
1553         {
1554                 /*
1555                         axisAlignedCollision
1556                 */
1557
1558                 for(s16 bx = -3; bx <= 3; bx++)
1559                 for(s16 by = -3; by <= 3; by++)
1560                 for(s16 bz = -3; bz <= 3; bz++)
1561                 {
1562                         // X-
1563                         {
1564                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1565                                 aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1);
1566                                 v3f v(1, 0, 0);
1567                                 f32 dtime = 0;
1568                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1569                                 UASSERT(fabs(dtime - 1.000) < 0.001);
1570                         }
1571                         {
1572                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1573                                 aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1);
1574                                 v3f v(-1, 0, 0);
1575                                 f32 dtime = 0;
1576                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1577                         }
1578                         {
1579                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1580                                 aabb3f m(bx-2, by+1.5, bz, bx-1, by+2.5, bz-1);
1581                                 v3f v(1, 0, 0);
1582                                 f32 dtime;
1583                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1584                         }
1585                         {
1586                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1587                                 aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1);
1588                                 v3f v(0.5, 0.1, 0);
1589                                 f32 dtime;
1590                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1591                                 UASSERT(fabs(dtime - 3.000) < 0.001);
1592                         }
1593                         {
1594                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1595                                 aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1);
1596                                 v3f v(0.5, 0.1, 0);
1597                                 f32 dtime;
1598                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1599                                 UASSERT(fabs(dtime - 3.000) < 0.001);
1600                         }
1601
1602                         // X+
1603                         {
1604                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1605                                 aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1);
1606                                 v3f v(-1, 0, 0);
1607                                 f32 dtime;
1608                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1609                                 UASSERT(fabs(dtime - 1.000) < 0.001);
1610                         }
1611                         {
1612                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1613                                 aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1);
1614                                 v3f v(1, 0, 0);
1615                                 f32 dtime;
1616                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1617                         }
1618                         {
1619                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1620                                 aabb3f m(bx+2, by, bz+1.5, bx+3, by+1, bz+3.5);
1621                                 v3f v(-1, 0, 0);
1622                                 f32 dtime;
1623                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == -1);
1624                         }
1625                         {
1626                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1627                                 aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1);
1628                                 v3f v(-0.5, 0.2, 0);
1629                                 f32 dtime;
1630                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);  // Y, not X!
1631                                 UASSERT(fabs(dtime - 2.500) < 0.001);
1632                         }
1633                         {
1634                                 aabb3f s(bx, by, bz, bx+1, by+1, bz+1);
1635                                 aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1);
1636                                 v3f v(-0.5, 0.3, 0);
1637                                 f32 dtime;
1638                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1639                                 UASSERT(fabs(dtime - 2.000) < 0.001);
1640                         }
1641
1642                         // TODO: Y-, Y+, Z-, Z+
1643
1644                         // misc
1645                         {
1646                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1647                                 aabb3f m(bx+2.3, by+2.29, bz+2.29, bx+4.2, by+4.2, bz+4.2);
1648                                 v3f v(-1./3, -1./3, -1./3);
1649                                 f32 dtime;
1650                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1651                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1652                         }
1653                         {
1654                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1655                                 aabb3f m(bx+2.29, by+2.3, bz+2.29, bx+4.2, by+4.2, bz+4.2);
1656                                 v3f v(-1./3, -1./3, -1./3);
1657                                 f32 dtime;
1658                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);
1659                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1660                         }
1661                         {
1662                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1663                                 aabb3f m(bx+2.29, by+2.29, bz+2.3, bx+4.2, by+4.2, bz+4.2);
1664                                 v3f v(-1./3, -1./3, -1./3);
1665                                 f32 dtime;
1666                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2);
1667                                 UASSERT(fabs(dtime - 0.9) < 0.001);
1668                         }
1669                         {
1670                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1671                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.3, by-2.29, bz-2.29);
1672                                 v3f v(1./7, 1./7, 1./7);
1673                                 f32 dtime;
1674                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 0);
1675                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1676                         }
1677                         {
1678                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1679                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.3, bz-2.29);
1680                                 v3f v(1./7, 1./7, 1./7);
1681                                 f32 dtime;
1682                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 1);
1683                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1684                         }
1685                         {
1686                                 aabb3f s(bx, by, bz, bx+2, by+2, bz+2);
1687                                 aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.29, bz-2.3);
1688                                 v3f v(1./7, 1./7, 1./7);
1689                                 f32 dtime;
1690                                 UASSERT(axisAlignedCollision(s, m, v, 0, dtime) == 2);
1691                                 UASSERT(fabs(dtime - 16.1) < 0.001);
1692                         }
1693                 }
1694         }
1695 };
1696
1697 struct TestSocket: public TestBase
1698 {
1699         void Run()
1700         {
1701                 const int port = 30003;
1702                 Address address(0, 0, 0, 0, port);
1703                 Address bind_addr(0, 0, 0, 0, port);
1704                 Address address6((IPv6AddressBytes*) NULL, port);
1705
1706                 /*
1707                  * Try to use the bind_address for servers with no localhost address
1708                  * For example: FreeBSD jails
1709                  */
1710                 std::string bind_str = g_settings->get("bind_address");
1711                 try {
1712                         bind_addr.Resolve(bind_str.c_str());
1713
1714                         if (!bind_addr.isIPv6()) {
1715                                 address = bind_addr;
1716                         }
1717                 } catch (ResolveError &e) {
1718                 }
1719
1720                 // IPv6 socket test
1721                 if (g_settings->getBool("enable_ipv6")) {
1722                         UDPSocket socket6;
1723
1724                         if (!socket6.init(true, true)) {
1725                                 /* Note: Failing to create an IPv6 socket is not technically an
1726                                    error because the OS may not support IPv6 or it may
1727                                    have been disabled. IPv6 is not /required/ by
1728                                    minetest and therefore this should not cause the unit
1729                                    test to fail
1730                                 */
1731                                 dstream << "WARNING: IPv6 socket creation failed (unit test)"
1732                                         << std::endl;
1733                         } else {
1734                                 const char sendbuffer[] = "hello world!";
1735                                 IPv6AddressBytes bytes;
1736                                 bytes.bytes[15] = 1;
1737
1738                                 socket6.Bind(address6);
1739
1740                                 try {
1741                                         socket6.Send(Address(&bytes, port), sendbuffer, sizeof(sendbuffer));
1742
1743                                         sleep_ms(50);
1744
1745                                         char rcvbuffer[256] = { 0 };
1746                                         Address sender;
1747
1748                                         for(;;) {
1749                                                 if (socket6.Receive(sender, rcvbuffer, sizeof(rcvbuffer )) < 0)
1750                                                         break;
1751                                         }
1752                                         //FIXME: This fails on some systems
1753                                         UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer)) == 0);
1754                                         UASSERT(memcmp(sender.getAddress6().sin6_addr.s6_addr,
1755                                                         Address(&bytes, 0).getAddress6().sin6_addr.s6_addr, 16) == 0);
1756                                 }
1757                                 catch (SendFailedException &e) {
1758                                         errorstream << "IPv6 support enabled but not available!"
1759                                                     << std::endl;
1760                                 }
1761                         }
1762                 }
1763
1764                 // IPv4 socket test
1765                 {
1766                         UDPSocket socket(false);
1767                         socket.Bind(address);
1768
1769                         const char sendbuffer[] = "hello world!";
1770                         /*
1771                          * If there is a bind address, use it.
1772                          * It's useful in container environments
1773                          */
1774                         if (address != Address(0, 0, 0, 0, port)) {
1775                                 socket.Send(address, sendbuffer, sizeof(sendbuffer));
1776                         }
1777                         else
1778                                 socket.Send(Address(127, 0, 0 ,1, port), sendbuffer, sizeof(sendbuffer));
1779
1780                         sleep_ms(50);
1781
1782                         char rcvbuffer[256] = { 0 };
1783                         Address sender;
1784                         for(;;) {
1785                                 if (socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer)) < 0)
1786                                         break;
1787                         }
1788                         //FIXME: This fails on some systems
1789                         UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer)) == 0);
1790
1791                         if (address != Address(0, 0, 0, 0, port)) {
1792                                 UASSERT(sender.getAddress().sin_addr.s_addr ==
1793                                                 address.getAddress().sin_addr.s_addr);
1794                         }
1795                         else {
1796                                 UASSERT(sender.getAddress().sin_addr.s_addr ==
1797                                                 Address(127, 0, 0, 1, 0).getAddress().sin_addr.s_addr);
1798                         }
1799                 }
1800         }
1801 };
1802
1803 struct TestConnection: public TestBase
1804 {
1805         void TestHelpers()
1806         {
1807                 /*
1808                         Test helper functions
1809                 */
1810
1811                 // Some constants for testing
1812                 u32 proto_id = 0x12345678;
1813                 u16 peer_id = 123;
1814                 u8 channel = 2;
1815                 SharedBuffer<u8> data1(1);
1816                 data1[0] = 100;
1817                 Address a(127,0,0,1, 10);
1818                 const u16 seqnum = 34352;
1819
1820                 con::BufferedPacket p1 = con::makePacket(a, data1,
1821                                 proto_id, peer_id, channel);
1822                 /*
1823                         We should now have a packet with this data:
1824                         Header:
1825                                 [0] u32 protocol_id
1826                                 [4] u16 sender_peer_id
1827                                 [6] u8 channel
1828                         Data:
1829                                 [7] u8 data1[0]
1830                 */
1831                 UASSERT(readU32(&p1.data[0]) == proto_id);
1832                 UASSERT(readU16(&p1.data[4]) == peer_id);
1833                 UASSERT(readU8(&p1.data[6]) == channel);
1834                 UASSERT(readU8(&p1.data[7]) == data1[0]);
1835
1836                 //infostream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl;
1837
1838                 SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum);
1839
1840                 /*infostream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()="
1841                                 <<data1.getSize()<<std::endl;
1842                 infostream<<"readU8(&p2[3])="<<readU8(&p2[3])
1843                                 <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl;
1844                 infostream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/
1845
1846                 UASSERT(p2.getSize() == 3 + data1.getSize());
1847                 UASSERT(readU8(&p2[0]) == TYPE_RELIABLE);
1848                 UASSERT(readU16(&p2[1]) == seqnum);
1849                 UASSERT(readU8(&p2[3]) == data1[0]);
1850         }
1851
1852         struct Handler : public con::PeerHandler
1853         {
1854                 Handler(const char *a_name)
1855                 {
1856                         count = 0;
1857                         last_id = 0;
1858                         name = a_name;
1859                 }
1860                 void peerAdded(con::Peer *peer)
1861                 {
1862                         infostream<<"Handler("<<name<<")::peerAdded(): "
1863                                         "id="<<peer->id<<std::endl;
1864                         last_id = peer->id;
1865                         count++;
1866                 }
1867                 void deletingPeer(con::Peer *peer, bool timeout)
1868                 {
1869                         infostream<<"Handler("<<name<<")::deletingPeer(): "
1870                                         "id="<<peer->id
1871                                         <<", timeout="<<timeout<<std::endl;
1872                         last_id = peer->id;
1873                         count--;
1874                 }
1875
1876                 s32 count;
1877                 u16 last_id;
1878                 const char *name;
1879         };
1880
1881         void Run()
1882         {
1883                 DSTACK("TestConnection::Run");
1884
1885                 TestHelpers();
1886
1887                 /*
1888                         Test some real connections
1889
1890                         NOTE: This mostly tests the legacy interface.
1891                 */
1892
1893                 u32 proto_id = 0xad26846a;
1894
1895                 Handler hand_server("server");
1896                 Handler hand_client("client");
1897
1898                 Address address(0, 0, 0, 0, 30001);
1899                 Address bind_addr(0, 0, 0, 0, 30001);
1900                 /*
1901                  * Try to use the bind_address for servers with no localhost address
1902                  * For example: FreeBSD jails
1903                  */
1904                 std::string bind_str = g_settings->get("bind_address");
1905                 try {
1906                         bind_addr.Resolve(bind_str.c_str());
1907
1908                         if (!bind_addr.isIPv6()) {
1909                                 address = bind_addr;
1910                         }
1911                 } catch (ResolveError &e) {
1912                 }
1913
1914                 infostream<<"** Creating server Connection"<<std::endl;
1915                 con::Connection server(proto_id, 512, 5.0, false, &hand_server);
1916                 server.Serve(address);
1917
1918                 infostream<<"** Creating client Connection"<<std::endl;
1919                 con::Connection client(proto_id, 512, 5.0, false, &hand_client);
1920
1921                 UASSERT(hand_server.count == 0);
1922                 UASSERT(hand_client.count == 0);
1923
1924                 sleep_ms(50);
1925
1926                 Address server_address(127, 0, 0, 1, 30001);
1927                 if (address != Address(0, 0, 0, 0, 30001)) {
1928                         server_address = bind_addr;
1929                 }
1930
1931                 infostream<<"** running client.Connect()"<<std::endl;
1932                 client.Connect(server_address);
1933
1934                 sleep_ms(50);
1935
1936                 // Client should not have added client yet
1937                 UASSERT(hand_client.count == 0);
1938
1939                 try
1940                 {
1941                         u16 peer_id;
1942                         SharedBuffer<u8> data;
1943                         infostream<<"** running client.Receive()"<<std::endl;
1944                         u32 size = client.Receive(peer_id, data);
1945                         infostream<<"** Client received: peer_id="<<peer_id
1946                                         <<", size="<<size
1947                                         <<std::endl;
1948                 }
1949                 catch(con::NoIncomingDataException &e)
1950                 {
1951                 }
1952
1953                 // Client should have added server now
1954                 UASSERT(hand_client.count == 1);
1955                 UASSERT(hand_client.last_id == 1);
1956                 // Server should not have added client yet
1957                 UASSERT(hand_server.count == 0);
1958
1959                 sleep_ms(100);
1960
1961                 try
1962                 {
1963                         u16 peer_id;
1964                         SharedBuffer<u8> data;
1965                         infostream<<"** running server.Receive()"<<std::endl;
1966                         u32 size = server.Receive(peer_id, data);
1967                         infostream<<"** Server received: peer_id="<<peer_id
1968                                         <<", size="<<size
1969                                         <<std::endl;
1970                 }
1971                 catch(con::NoIncomingDataException &e)
1972                 {
1973                         // No actual data received, but the client has
1974                         // probably been connected
1975                 }
1976
1977                 // Client should be the same
1978                 UASSERT(hand_client.count == 1);
1979                 UASSERT(hand_client.last_id == 1);
1980                 // Server should have the client
1981                 UASSERT(hand_server.count == 1);
1982                 UASSERT(hand_server.last_id == 2);
1983
1984                 //sleep_ms(50);
1985
1986                 while(client.Connected() == false)
1987                 {
1988                         try
1989                         {
1990                                 u16 peer_id;
1991                                 SharedBuffer<u8> data;
1992                                 infostream<<"** running client.Receive()"<<std::endl;
1993                                 u32 size = client.Receive(peer_id, data);
1994                                 infostream<<"** Client received: peer_id="<<peer_id
1995                                                 <<", size="<<size
1996                                                 <<std::endl;
1997                         }
1998                         catch(con::NoIncomingDataException &e)
1999                         {
2000                         }
2001                         sleep_ms(50);
2002                 }
2003
2004                 sleep_ms(50);
2005
2006                 try
2007                 {
2008                         u16 peer_id;
2009                         SharedBuffer<u8> data;
2010                         infostream<<"** running server.Receive()"<<std::endl;
2011                         u32 size = server.Receive(peer_id, data);
2012                         infostream<<"** Server received: peer_id="<<peer_id
2013                                         <<", size="<<size
2014                                         <<std::endl;
2015                 }
2016                 catch(con::NoIncomingDataException &e)
2017                 {
2018                 }
2019
2020                 /*
2021                         Simple send-receive test
2022                 */
2023                 {
2024                         NetworkPacket* pkt = new NetworkPacket((u8*) "Hello World !", 14, 0);
2025
2026                         SharedBuffer<u8> sentdata = pkt->oldForgePacket();
2027
2028                         infostream<<"** running client.Send()"<<std::endl;
2029                         client.Send(PEER_ID_SERVER, 0, pkt, true);
2030
2031                         sleep_ms(50);
2032
2033                         u16 peer_id;
2034                         SharedBuffer<u8> recvdata;
2035                         infostream << "** running server.Receive()" << std::endl;
2036                         u32 size = server.Receive(peer_id, recvdata);
2037                         infostream << "** Server received: peer_id=" << peer_id
2038                                         << ", size=" << size
2039                                         << ", data=" << (const char*)pkt->getU8Ptr(0)
2040                                         << std::endl;
2041
2042                         UASSERT(memcmp(*sentdata, *recvdata, recvdata.getSize()) == 0);
2043
2044                         delete pkt;
2045                 }
2046
2047                 u16 peer_id_client = 2;
2048                 /*
2049                         Send a large packet
2050                 */
2051                 {
2052                         const int datasize = 30000;
2053                         NetworkPacket* pkt = new NetworkPacket(0, datasize);
2054                         for(u16 i=0; i<datasize; i++){
2055                                 *pkt << (u8) i/4;
2056                         }
2057
2058                         infostream<<"Sending data (size="<<datasize<<"):";
2059                         for(int i=0; i<datasize && i<20; i++){
2060                                 if(i%2==0) infostream<<" ";
2061                                 char buf[10];
2062                                 snprintf(buf, 10, "%.2X", ((int)((const char*)pkt->getU8Ptr(0))[i])&0xff);
2063                                 infostream<<buf;
2064                         }
2065                         if(datasize>20)
2066                                 infostream<<"...";
2067                         infostream<<std::endl;
2068
2069                         SharedBuffer<u8> sentdata = pkt->oldForgePacket();
2070
2071                         server.Send(peer_id_client, 0, pkt, true);
2072
2073                         //sleep_ms(3000);
2074
2075                         SharedBuffer<u8> recvdata;
2076                         infostream<<"** running client.Receive()"<<std::endl;
2077                         u16 peer_id = 132;
2078                         u16 size = 0;
2079                         bool received = false;
2080                         u32 timems0 = porting::getTimeMs();
2081                         for(;;){
2082                                 if(porting::getTimeMs() - timems0 > 5000 || received)
2083                                         break;
2084                                 try{
2085                                         size = client.Receive(peer_id, recvdata);
2086                                         received = true;
2087                                 }catch(con::NoIncomingDataException &e){
2088                                 }
2089                                 sleep_ms(10);
2090                         }
2091                         UASSERT(received);
2092                         infostream<<"** Client received: peer_id="<<peer_id
2093                                         <<", size="<<size
2094                                         <<std::endl;
2095
2096                         infostream<<"Received data (size="<<size<<"): ";
2097                         for(int i=0; i<size && i<20; i++){
2098                                 if(i%2==0) infostream<<" ";
2099                                 char buf[10];
2100                                 snprintf(buf, 10, "%.2X", ((int)(recvdata[i]))&0xff);
2101                                 infostream<<buf;
2102                         }
2103                         if(size>20)
2104                                 infostream<<"...";
2105                         infostream<<std::endl;
2106
2107                         UASSERT(memcmp(*sentdata, *recvdata, recvdata.getSize()) == 0);
2108                         UASSERT(peer_id == PEER_ID_SERVER);
2109
2110                         delete pkt;
2111                 }
2112
2113                 // Check peer handlers
2114                 UASSERT(hand_client.count == 1);
2115                 UASSERT(hand_client.last_id == 1);
2116                 UASSERT(hand_server.count == 1);
2117                 UASSERT(hand_server.last_id == 2);
2118
2119                 //assert(0);
2120         }
2121 };
2122
2123 #define TEST(X) do {\
2124         X x;\
2125         infostream<<"Running " #X <<std::endl;\
2126         x.Run();\
2127         tests_run++;\
2128         tests_failed += x.test_failed ? 1 : 0;\
2129 } while (0)
2130
2131 #define TESTPARAMS(X, ...) do {\
2132         X x;\
2133         infostream<<"Running " #X <<std::endl;\
2134         x.Run(__VA_ARGS__);\
2135         tests_run++;\
2136         tests_failed += x.test_failed ? 1 : 0;\
2137 } while (0)
2138
2139 void run_tests()
2140 {
2141         DSTACK(__FUNCTION_NAME);
2142
2143         int tests_run = 0;
2144         int tests_failed = 0;
2145
2146         // Create item and node definitions
2147         IWritableItemDefManager *idef = createItemDefManager();
2148         IWritableNodeDefManager *ndef = createNodeDefManager();
2149         define_some_nodes(idef, ndef);
2150
2151         log_set_lev_silence(LMT_ERROR, true);
2152
2153         infostream<<"run_tests() started"<<std::endl;
2154         TEST(TestUtilities);
2155         TEST(TestPath);
2156         TEST(TestSettings);
2157         TEST(TestCompress);
2158         TEST(TestSerialization);
2159         TEST(TestNodedefSerialization);
2160         TESTPARAMS(TestMapNode, ndef);
2161         TESTPARAMS(TestVoxelManipulator, ndef);
2162         TESTPARAMS(TestVoxelAlgorithms, ndef);
2163         TESTPARAMS(TestInventory, idef);
2164         //TEST(TestMapBlock);
2165         //TEST(TestMapSector);
2166         TEST(TestCollision);
2167         if(INTERNET_SIMULATOR == false){
2168                 TEST(TestSocket);
2169                 dout_con << "=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ===" << std::endl;
2170                 TEST(TestConnection);
2171                 dout_con << "=== END RUNNING UNIT TESTS FOR CONNECTION ===" << std::endl;
2172         }
2173
2174         log_set_lev_silence(LMT_ERROR, false);
2175
2176         delete idef;
2177         delete ndef;
2178
2179         if(tests_failed == 0) {
2180                 actionstream << "run_tests(): " << tests_failed << " / " << tests_run << " tests failed." << std::endl;
2181                 actionstream << "run_tests() passed." << std::endl;
2182                 return;
2183         } else {
2184                 errorstream << "run_tests(): " << tests_failed << " / " << tests_run << " tests failed." << std::endl;
2185                 errorstream << "run_tests() aborting." << std::endl;
2186                 abort();
2187         }
2188 }
2189