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