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