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