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