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