]> git.lizzy.rs Git - dragonfireclient.git/blob - src/test.cpp
ecbf653f978bc281bc4fd6ec9abe74bd2590ddaa
[dragonfireclient.git] / src / test.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "common_irrlicht.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 "utility.h"
29 #include "serialization.h"
30 #include "voxel.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 "utility_string.h"
39 #include "voxelalgorithms.h"
40 #include "inventory.h"
41
42 /*
43         Asserts that the exception occurs
44 */
45 #define EXCEPTION_CHECK(EType, code)\
46 {\
47         bool exception_thrown = false;\
48         try{ code; }\
49         catch(EType &e) { exception_thrown = true; }\
50         assert(exception_thrown);\
51 }
52
53 /*
54         A few item and node definitions for those tests that need them
55 */
56
57 #define CONTENT_STONE 0
58 #define CONTENT_GRASS 0x800
59 #define CONTENT_TORCH 100
60
61 void define_some_nodes(IWritableItemDefManager *idef, IWritableNodeDefManager *ndef)
62 {
63         content_t i;
64         ItemDefinition itemdef;
65         ContentFeatures f;
66
67         /*
68                 Stone
69         */
70         i = CONTENT_STONE;
71         itemdef = ItemDefinition();
72         itemdef.type = ITEM_NODE;
73         itemdef.name = "default:stone";
74         itemdef.description = "Stone";
75         itemdef.groups["cracky"] = 3;
76         itemdef.inventory_image = "[inventorycube"
77                 "{default_stone.png"
78                 "{default_stone.png"
79                 "{default_stone.png";
80         f = ContentFeatures();
81         f.name = itemdef.name;
82         for(int i = 0; i < 6; i++)
83                 f.tname_tiles[i] = "default_stone.png";
84         f.is_ground_content = true;
85         idef->registerItem(itemdef);
86         ndef->set(i, f);
87
88         /*
89                 Grass
90         */
91         i = CONTENT_GRASS;
92         itemdef = ItemDefinition();
93         itemdef.type = ITEM_NODE;
94         itemdef.name = "default:dirt_with_grass";
95         itemdef.description = "Dirt with grass";
96         itemdef.groups["crumbly"] = 3;
97         itemdef.inventory_image = "[inventorycube"
98                 "{default_grass.png"
99                 "{default_dirt.png&default_grass_side.png"
100                 "{default_dirt.png&default_grass_side.png";
101         f = ContentFeatures();
102         f.name = itemdef.name;
103         f.tname_tiles[0] = "default_grass.png";
104         f.tname_tiles[1] = "default_dirt.png";
105         for(int i = 2; i < 6; i++)
106                 f.tname_tiles[i] = "default_dirt.png^default_grass_side.png";
107         f.is_ground_content = true;
108         idef->registerItem(itemdef);
109         ndef->set(i, f);
110
111         /*
112                 Torch (minimal definition for lighting tests)
113         */
114         i = CONTENT_TORCH;
115         itemdef = ItemDefinition();
116         itemdef.type = ITEM_NODE;
117         itemdef.name = "default:torch";
118         f = ContentFeatures();
119         f.name = itemdef.name;
120         f.param_type = CPT_LIGHT;
121         f.light_propagates = true;
122         f.sunlight_propagates = true;
123         f.light_source = LIGHT_MAX-1;
124         idef->registerItem(itemdef);
125         ndef->set(i, f);
126 }
127
128 struct TestUtilities
129 {
130         void Run()
131         {
132                 /*infostream<<"wrapDegrees(100.0) = "<<wrapDegrees(100.0)<<std::endl;
133                 infostream<<"wrapDegrees(720.5) = "<<wrapDegrees(720.5)<<std::endl;
134                 infostream<<"wrapDegrees(-0.5) = "<<wrapDegrees(-0.5)<<std::endl;*/
135                 assert(fabs(wrapDegrees(100.0) - 100.0) < 0.001);
136                 assert(fabs(wrapDegrees(720.5) - 0.5) < 0.001);
137                 assert(fabs(wrapDegrees(-0.5) - (-0.5)) < 0.001);
138                 assert(fabs(wrapDegrees(-365.5) - (-5.5)) < 0.001);
139                 assert(lowercase("Foo bAR") == "foo bar");
140                 assert(is_yes("YeS") == true);
141                 assert(is_yes("") == false);
142                 assert(is_yes("FAlse") == false);
143                 const char *ends[] = {"abc", "c", "bc", NULL};
144                 assert(removeStringEnd("abc", ends) == "");
145                 assert(removeStringEnd("bc", ends) == "b");
146                 assert(removeStringEnd("12c", ends) == "12");
147                 assert(removeStringEnd("foo", ends) == "");
148         }
149 };
150
151 struct TestSettings
152 {
153         void Run()
154         {
155                 Settings s;
156                 // Test reading of settings
157                 s.parseConfigLine("leet = 1337");
158                 s.parseConfigLine("leetleet = 13371337");
159                 s.parseConfigLine("leetleet_neg = -13371337");
160                 s.parseConfigLine("floaty_thing = 1.1");
161                 s.parseConfigLine("stringy_thing = asd /( ¤%&(/\" BLÖÄRP");
162                 s.parseConfigLine("coord = (1, 2, 4.5)");
163                 assert(s.getS32("leet") == 1337);
164                 assert(s.getS16("leetleet") == 32767);
165                 assert(s.getS16("leetleet_neg") == -32768);
166                 // Not sure if 1.1 is an exact value as a float, but doesn't matter
167                 assert(fabs(s.getFloat("floaty_thing") - 1.1) < 0.001);
168                 assert(s.get("stringy_thing") == "asd /( ¤%&(/\" BLÖÄRP");
169                 assert(fabs(s.getV3F("coord").X - 1.0) < 0.001);
170                 assert(fabs(s.getV3F("coord").Y - 2.0) < 0.001);
171                 assert(fabs(s.getV3F("coord").Z - 4.5) < 0.001);
172                 // Test the setting of settings too
173                 s.setFloat("floaty_thing_2", 1.2);
174                 s.setV3F("coord2", v3f(1, 2, 3.3));
175                 assert(s.get("floaty_thing_2").substr(0,3) == "1.2");
176                 assert(fabs(s.getFloat("floaty_thing_2") - 1.2) < 0.001);
177                 assert(fabs(s.getV3F("coord2").X - 1.0) < 0.001);
178                 assert(fabs(s.getV3F("coord2").Y - 2.0) < 0.001);
179                 assert(fabs(s.getV3F("coord2").Z - 3.3) < 0.001);
180         }
181 };
182
183 struct TestSerialization
184 {
185         // To be used like this:
186         //   mkstr("Some\0string\0with\0embedded\0nuls")
187         // since std::string("...") doesn't work as expected in that case.
188         template<size_t N> std::string mkstr(const char (&s)[N])
189         {
190                 return std::string(s, N - 1);
191         }
192
193         void Run()
194         {
195                 // Tests some serialization primitives
196
197                 assert(serializeString("") == mkstr("\0\0"));
198                 assert(serializeWideString(L"") == mkstr("\0\0"));
199                 assert(serializeLongString("") == mkstr("\0\0\0\0"));
200                 assert(serializeJsonString("") == "\"\"");
201                 
202                 std::string teststring = "Hello world!";
203                 assert(serializeString(teststring) ==
204                         mkstr("\0\14Hello world!"));
205                 assert(serializeWideString(narrow_to_wide(teststring)) ==
206                         mkstr("\0\14\0H\0e\0l\0l\0o\0 \0w\0o\0r\0l\0d\0!"));
207                 assert(serializeLongString(teststring) ==
208                         mkstr("\0\0\0\14Hello world!"));
209                 assert(serializeJsonString(teststring) ==
210                         "\"Hello world!\"");
211
212                 std::string teststring2;
213                 std::wstring teststring2_w;
214                 std::string teststring2_w_encoded;
215                 {
216                         std::ostringstream tmp_os;
217                         std::wostringstream tmp_os_w;
218                         std::ostringstream tmp_os_w_encoded;
219                         for(int i = 0; i < 256; i++)
220                         {
221                                 tmp_os<<(char)i;
222                                 tmp_os_w<<(wchar_t)i;
223                                 tmp_os_w_encoded<<(char)0<<(char)i;
224                         }
225                         teststring2 = tmp_os.str();
226                         teststring2_w = tmp_os_w.str();
227                         teststring2_w_encoded = tmp_os_w_encoded.str();
228                 }
229                 assert(serializeString(teststring2) ==
230                         mkstr("\1\0") + teststring2);
231                 assert(serializeWideString(teststring2_w) ==
232                         mkstr("\1\0") + teststring2_w_encoded);
233                 assert(serializeLongString(teststring2) ==
234                         mkstr("\0\0\1\0") + teststring2);
235                 // MSVC fails when directly using "\\\\"
236                 std::string backslash = "\\";
237                 assert(serializeJsonString(teststring2) ==
238                         mkstr("\"") +
239                         "\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007" +
240                         "\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f" +
241                         "\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017" +
242                         "\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f" +
243                         " !\\\"" + teststring2.substr(0x23, 0x2f-0x23) +
244                         "\\/" + teststring2.substr(0x30, 0x5c-0x30) +
245                         backslash + backslash + teststring2.substr(0x5d, 0x7f-0x5d) + "\\u007f" +
246                         "\\u0080\\u0081\\u0082\\u0083\\u0084\\u0085\\u0086\\u0087" +
247                         "\\u0088\\u0089\\u008a\\u008b\\u008c\\u008d\\u008e\\u008f" +
248                         "\\u0090\\u0091\\u0092\\u0093\\u0094\\u0095\\u0096\\u0097" +
249                         "\\u0098\\u0099\\u009a\\u009b\\u009c\\u009d\\u009e\\u009f" +
250                         "\\u00a0\\u00a1\\u00a2\\u00a3\\u00a4\\u00a5\\u00a6\\u00a7" +
251                         "\\u00a8\\u00a9\\u00aa\\u00ab\\u00ac\\u00ad\\u00ae\\u00af" +
252                         "\\u00b0\\u00b1\\u00b2\\u00b3\\u00b4\\u00b5\\u00b6\\u00b7" +
253                         "\\u00b8\\u00b9\\u00ba\\u00bb\\u00bc\\u00bd\\u00be\\u00bf" +
254                         "\\u00c0\\u00c1\\u00c2\\u00c3\\u00c4\\u00c5\\u00c6\\u00c7" +
255                         "\\u00c8\\u00c9\\u00ca\\u00cb\\u00cc\\u00cd\\u00ce\\u00cf" +
256                         "\\u00d0\\u00d1\\u00d2\\u00d3\\u00d4\\u00d5\\u00d6\\u00d7" +
257                         "\\u00d8\\u00d9\\u00da\\u00db\\u00dc\\u00dd\\u00de\\u00df" +
258                         "\\u00e0\\u00e1\\u00e2\\u00e3\\u00e4\\u00e5\\u00e6\\u00e7" +
259                         "\\u00e8\\u00e9\\u00ea\\u00eb\\u00ec\\u00ed\\u00ee\\u00ef" +
260                         "\\u00f0\\u00f1\\u00f2\\u00f3\\u00f4\\u00f5\\u00f6\\u00f7" +
261                         "\\u00f8\\u00f9\\u00fa\\u00fb\\u00fc\\u00fd\\u00fe\\u00ff" +
262                         "\"");
263
264                 {
265                         std::istringstream is(serializeString(teststring2), std::ios::binary);
266                         assert(deSerializeString(is) == teststring2);
267                         assert(!is.eof());
268                         is.get();
269                         assert(is.eof());
270                 }
271                 {
272                         std::istringstream is(serializeWideString(teststring2_w), std::ios::binary);
273                         assert(deSerializeWideString(is) == teststring2_w);
274                         assert(!is.eof());
275                         is.get();
276                         assert(is.eof());
277                 }
278                 {
279                         std::istringstream is(serializeLongString(teststring2), std::ios::binary);
280                         assert(deSerializeLongString(is) == teststring2);
281                         assert(!is.eof());
282                         is.get();
283                         assert(is.eof());
284                 }
285                 {
286                         std::istringstream is(serializeJsonString(teststring2), std::ios::binary);
287                         //dstream<<serializeJsonString(deSerializeJsonString(is));
288                         assert(deSerializeJsonString(is) == teststring2);
289                         assert(!is.eof());
290                         is.get();
291                         assert(is.eof());
292                 }
293         }
294 };
295
296 struct TestCompress
297 {
298         void Run()
299         {
300                 { // ver 0
301
302                 SharedBuffer<u8> fromdata(4);
303                 fromdata[0]=1;
304                 fromdata[1]=5;
305                 fromdata[2]=5;
306                 fromdata[3]=1;
307                 
308                 std::ostringstream os(std::ios_base::binary);
309                 compress(fromdata, os, 0);
310
311                 std::string str_out = os.str();
312                 
313                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
314                 infostream<<"TestCompress: 1,5,5,1 -> ";
315                 for(u32 i=0; i<str_out.size(); i++)
316                 {
317                         infostream<<(u32)str_out[i]<<",";
318                 }
319                 infostream<<std::endl;
320
321                 assert(str_out.size() == 10);
322
323                 assert(str_out[0] == 0);
324                 assert(str_out[1] == 0);
325                 assert(str_out[2] == 0);
326                 assert(str_out[3] == 4);
327                 assert(str_out[4] == 0);
328                 assert(str_out[5] == 1);
329                 assert(str_out[6] == 1);
330                 assert(str_out[7] == 5);
331                 assert(str_out[8] == 0);
332                 assert(str_out[9] == 1);
333
334                 std::istringstream is(str_out, std::ios_base::binary);
335                 std::ostringstream os2(std::ios_base::binary);
336
337                 decompress(is, os2, 0);
338                 std::string str_out2 = os2.str();
339
340                 infostream<<"decompress: ";
341                 for(u32 i=0; i<str_out2.size(); i++)
342                 {
343                         infostream<<(u32)str_out2[i]<<",";
344                 }
345                 infostream<<std::endl;
346
347                 assert(str_out2.size() == fromdata.getSize());
348
349                 for(u32 i=0; i<str_out2.size(); i++)
350                 {
351                         assert(str_out2[i] == fromdata[i]);
352                 }
353
354                 }
355
356                 { // ver HIGHEST
357
358                 SharedBuffer<u8> fromdata(4);
359                 fromdata[0]=1;
360                 fromdata[1]=5;
361                 fromdata[2]=5;
362                 fromdata[3]=1;
363                 
364                 std::ostringstream os(std::ios_base::binary);
365                 compress(fromdata, os, SER_FMT_VER_HIGHEST);
366
367                 std::string str_out = os.str();
368                 
369                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
370                 infostream<<"TestCompress: 1,5,5,1 -> ";
371                 for(u32 i=0; i<str_out.size(); i++)
372                 {
373                         infostream<<(u32)str_out[i]<<",";
374                 }
375                 infostream<<std::endl;
376
377                 /*assert(str_out.size() == 10);
378
379                 assert(str_out[0] == 0);
380                 assert(str_out[1] == 0);
381                 assert(str_out[2] == 0);
382                 assert(str_out[3] == 4);
383                 assert(str_out[4] == 0);
384                 assert(str_out[5] == 1);
385                 assert(str_out[6] == 1);
386                 assert(str_out[7] == 5);
387                 assert(str_out[8] == 0);
388                 assert(str_out[9] == 1);*/
389
390                 std::istringstream is(str_out, std::ios_base::binary);
391                 std::ostringstream os2(std::ios_base::binary);
392
393                 decompress(is, os2, SER_FMT_VER_HIGHEST);
394                 std::string str_out2 = os2.str();
395
396                 infostream<<"decompress: ";
397                 for(u32 i=0; i<str_out2.size(); i++)
398                 {
399                         infostream<<(u32)str_out2[i]<<",";
400                 }
401                 infostream<<std::endl;
402
403                 assert(str_out2.size() == fromdata.getSize());
404
405                 for(u32 i=0; i<str_out2.size(); i++)
406                 {
407                         assert(str_out2[i] == fromdata[i]);
408                 }
409
410                 }
411         }
412 };
413
414 struct TestMapNode
415 {
416         void Run(INodeDefManager *nodedef)
417         {
418                 MapNode n;
419
420                 // Default values
421                 assert(n.getContent() == CONTENT_AIR);
422                 assert(n.getLight(LIGHTBANK_DAY, nodedef) == 0);
423                 assert(n.getLight(LIGHTBANK_NIGHT, nodedef) == 0);
424                 
425                 // Transparency
426                 n.setContent(CONTENT_AIR);
427                 assert(nodedef->get(n).light_propagates == true);
428                 n.setContent(LEGN(nodedef, "CONTENT_STONE"));
429                 assert(nodedef->get(n).light_propagates == false);
430         }
431 };
432
433 struct TestVoxelManipulator
434 {
435         void Run(INodeDefManager *nodedef)
436         {
437                 /*
438                         VoxelArea
439                 */
440
441                 VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1));
442                 assert(a.index(0,0,0) == 1*3*3 + 1*3 + 1);
443                 assert(a.index(-1,-1,-1) == 0);
444                 
445                 VoxelArea c(v3s16(-2,-2,-2), v3s16(2,2,2));
446                 // An area that is 1 bigger in x+ and z-
447                 VoxelArea d(v3s16(-2,-2,-3), v3s16(3,2,2));
448                 
449                 core::list<VoxelArea> aa;
450                 d.diff(c, aa);
451                 
452                 // Correct results
453                 core::array<VoxelArea> results;
454                 results.push_back(VoxelArea(v3s16(-2,-2,-3),v3s16(3,2,-3)));
455                 results.push_back(VoxelArea(v3s16(3,-2,-2),v3s16(3,2,2)));
456
457                 assert(aa.size() == results.size());
458                 
459                 infostream<<"Result of diff:"<<std::endl;
460                 for(core::list<VoxelArea>::Iterator
461                                 i = aa.begin(); i != aa.end(); i++)
462                 {
463                         i->print(infostream);
464                         infostream<<std::endl;
465                         
466                         s32 j = results.linear_search(*i);
467                         assert(j != -1);
468                         results.erase(j, 1);
469                 }
470
471
472                 /*
473                         VoxelManipulator
474                 */
475                 
476                 VoxelManipulator v;
477
478                 v.print(infostream, nodedef);
479
480                 infostream<<"*** Setting (-1,0,-1)=2 ***"<<std::endl;
481                 
482                 v.setNodeNoRef(v3s16(-1,0,-1), MapNode(CONTENT_GRASS));
483
484                 v.print(infostream, nodedef);
485
486                 assert(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
487
488                 infostream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl;
489
490                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1)));
491
492                 v.print(infostream, nodedef);
493
494                 infostream<<"*** Adding area ***"<<std::endl;
495
496                 v.addArea(a);
497                 
498                 v.print(infostream, nodedef);
499
500                 assert(v.getNode(v3s16(-1,0,-1)).getContent() == CONTENT_GRASS);
501                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1)));
502         }
503 };
504
505 struct TestVoxelAlgorithms
506 {
507         void Run(INodeDefManager *ndef)
508         {
509                 /*
510                         voxalgo::propagateSunlight
511                 */
512                 {
513                         VoxelManipulator v;
514                         for(u16 z=0; z<3; z++)
515                         for(u16 y=0; y<3; y++)
516                         for(u16 x=0; x<3; x++)
517                         {
518                                 v3s16 p(x,y,z);
519                                 v.setNodeNoRef(p, MapNode(CONTENT_AIR));
520                         }
521                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
522                         {
523                                 core::map<v3s16, bool> light_sources;
524                                 voxalgo::setLight(v, a, 0, ndef);
525                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
526                                                 v, a, true, light_sources, ndef);
527                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
528                                 assert(res.bottom_sunlight_valid == true);
529                                 assert(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
530                                                 == LIGHT_SUN);
531                         }
532                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
533                         {
534                                 core::map<v3s16, bool> light_sources;
535                                 voxalgo::setLight(v, a, 0, ndef);
536                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
537                                                 v, a, true, light_sources, ndef);
538                                 assert(res.bottom_sunlight_valid == true);
539                                 assert(v.getNode(v3s16(1,1,1)).getLight(LIGHTBANK_DAY, ndef)
540                                                 == LIGHT_SUN);
541                         }
542                         {
543                                 core::map<v3s16, bool> light_sources;
544                                 voxalgo::setLight(v, a, 0, ndef);
545                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
546                                                 v, a, false, light_sources, ndef);
547                                 assert(res.bottom_sunlight_valid == true);
548                                 assert(v.getNode(v3s16(2,0,2)).getLight(LIGHTBANK_DAY, ndef)
549                                                 == 0);
550                         }
551                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_STONE));
552                         {
553                                 core::map<v3s16, bool> light_sources;
554                                 voxalgo::setLight(v, a, 0, ndef);
555                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
556                                                 v, a, true, light_sources, ndef);
557                                 assert(res.bottom_sunlight_valid == true);
558                                 assert(v.getNode(v3s16(1,1,2)).getLight(LIGHTBANK_DAY, ndef)
559                                                 == 0);
560                         }
561                         {
562                                 core::map<v3s16, bool> light_sources;
563                                 voxalgo::setLight(v, a, 0, ndef);
564                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
565                                                 v, a, false, light_sources, ndef);
566                                 assert(res.bottom_sunlight_valid == true);
567                                 assert(v.getNode(v3s16(1,0,2)).getLight(LIGHTBANK_DAY, ndef)
568                                                 == 0);
569                         }
570                         {
571                                 MapNode n(CONTENT_AIR);
572                                 n.setLight(LIGHTBANK_DAY, 10, ndef);
573                                 v.setNodeNoRef(v3s16(1,-1,2), n);
574                         }
575                         {
576                                 core::map<v3s16, bool> light_sources;
577                                 voxalgo::setLight(v, a, 0, ndef);
578                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
579                                                 v, a, true, light_sources, ndef);
580                                 assert(res.bottom_sunlight_valid == true);
581                         }
582                         {
583                                 core::map<v3s16, bool> light_sources;
584                                 voxalgo::setLight(v, a, 0, ndef);
585                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
586                                                 v, a, false, light_sources, ndef);
587                                 assert(res.bottom_sunlight_valid == true);
588                         }
589                         {
590                                 MapNode n(CONTENT_AIR);
591                                 n.setLight(LIGHTBANK_DAY, LIGHT_SUN, ndef);
592                                 v.setNodeNoRef(v3s16(1,-1,2), n);
593                         }
594                         {
595                                 core::map<v3s16, bool> light_sources;
596                                 voxalgo::setLight(v, a, 0, ndef);
597                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
598                                                 v, a, true, light_sources, ndef);
599                                 assert(res.bottom_sunlight_valid == false);
600                         }
601                         {
602                                 core::map<v3s16, bool> light_sources;
603                                 voxalgo::setLight(v, a, 0, ndef);
604                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
605                                                 v, a, false, light_sources, ndef);
606                                 assert(res.bottom_sunlight_valid == false);
607                         }
608                         v.setNodeNoRef(v3s16(1,3,2), MapNode(CONTENT_IGNORE));
609                         {
610                                 core::map<v3s16, bool> light_sources;
611                                 voxalgo::setLight(v, a, 0, ndef);
612                                 voxalgo::SunlightPropagateResult res = voxalgo::propagateSunlight(
613                                                 v, a, true, light_sources, ndef);
614                                 assert(res.bottom_sunlight_valid == true);
615                         }
616                 }
617                 /*
618                         voxalgo::clearLightAndCollectSources
619                 */
620                 {
621                         VoxelManipulator v;
622                         for(u16 z=0; z<3; z++)
623                         for(u16 y=0; y<3; y++)
624                         for(u16 x=0; x<3; x++)
625                         {
626                                 v3s16 p(x,y,z);
627                                 v.setNode(p, MapNode(CONTENT_AIR));
628                         }
629                         VoxelArea a(v3s16(0,0,0), v3s16(2,2,2));
630                         v.setNodeNoRef(v3s16(0,0,0), MapNode(CONTENT_STONE));
631                         v.setNodeNoRef(v3s16(1,1,1), MapNode(CONTENT_TORCH));
632                         {
633                                 MapNode n(CONTENT_AIR);
634                                 n.setLight(LIGHTBANK_DAY, 1, ndef);
635                                 v.setNode(v3s16(1,1,2), n);
636                         }
637                         {
638                                 core::map<v3s16, bool> light_sources;
639                                 core::map<v3s16, u8> unlight_from;
640                                 voxalgo::clearLightAndCollectSources(v, a, LIGHTBANK_DAY,
641                                                 ndef, light_sources, unlight_from);
642                                 //v.print(dstream, ndef, VOXELPRINT_LIGHT_DAY);
643                                 assert(v.getNode(v3s16(0,1,1)).getLight(LIGHTBANK_DAY, ndef)
644                                                 == 0);
645                                 assert(light_sources.find(v3s16(1,1,1)) != NULL);
646                                 assert(light_sources.size() == 1);
647                                 assert(unlight_from.find(v3s16(1,1,2)) != NULL);
648                                 assert(unlight_from.size() == 1);
649                         }
650                 }
651         }
652 };
653
654 struct TestInventory
655 {
656         void Run(IItemDefManager *idef)
657         {
658                 std::string serialized_inventory =
659                 "List 0 32\n"
660                 "Empty\n"
661                 "Empty\n"
662                 "Empty\n"
663                 "Empty\n"
664                 "Empty\n"
665                 "Empty\n"
666                 "Empty\n"
667                 "Empty\n"
668                 "Empty\n"
669                 "Item default:cobble 61\n"
670                 "Empty\n"
671                 "Empty\n"
672                 "Empty\n"
673                 "Empty\n"
674                 "Empty\n"
675                 "Empty\n"
676                 "Item default:dirt 71\n"
677                 "Empty\n"
678                 "Empty\n"
679                 "Empty\n"
680                 "Empty\n"
681                 "Empty\n"
682                 "Empty\n"
683                 "Empty\n"
684                 "Item default:dirt 99\n"
685                 "Item default:cobble 38\n"
686                 "Empty\n"
687                 "Empty\n"
688                 "Empty\n"
689                 "Empty\n"
690                 "Empty\n"
691                 "Empty\n"
692                 "EndInventoryList\n"
693                 "EndInventory\n";
694                 
695                 std::string serialized_inventory_2 =
696                 "List main 32\n"
697                 "Empty\n"
698                 "Empty\n"
699                 "Empty\n"
700                 "Empty\n"
701                 "Empty\n"
702                 "Empty\n"
703                 "Empty\n"
704                 "Empty\n"
705                 "Empty\n"
706                 "Item default:cobble 61\n"
707                 "Empty\n"
708                 "Empty\n"
709                 "Empty\n"
710                 "Empty\n"
711                 "Empty\n"
712                 "Empty\n"
713                 "Item default:dirt 71\n"
714                 "Empty\n"
715                 "Empty\n"
716                 "Empty\n"
717                 "Empty\n"
718                 "Empty\n"
719                 "Empty\n"
720                 "Empty\n"
721                 "Item default:dirt 99\n"
722                 "Item default:cobble 38\n"
723                 "Empty\n"
724                 "Empty\n"
725                 "Empty\n"
726                 "Empty\n"
727                 "Empty\n"
728                 "Empty\n"
729                 "EndInventoryList\n"
730                 "EndInventory\n";
731                 
732                 Inventory inv(idef);
733                 std::istringstream is(serialized_inventory, std::ios::binary);
734                 inv.deSerialize(is);
735                 assert(inv.getList("0"));
736                 assert(!inv.getList("main"));
737                 inv.getList("0")->setName("main");
738                 assert(!inv.getList("0"));
739                 assert(inv.getList("main"));
740                 std::ostringstream inv_os(std::ios::binary);
741                 inv.serialize(inv_os);
742                 assert(inv_os.str() == serialized_inventory_2);
743         }
744 };
745
746 /*
747         NOTE: These tests became non-working then NodeContainer was removed.
748               These should be redone, utilizing some kind of a virtual
749                   interface for Map (IMap would be fine).
750 */
751 #if 0
752 struct TestMapBlock
753 {
754         class TC : public NodeContainer
755         {
756         public:
757
758                 MapNode node;
759                 bool position_valid;
760                 core::list<v3s16> validity_exceptions;
761
762                 TC()
763                 {
764                         position_valid = true;
765                 }
766
767                 virtual bool isValidPosition(v3s16 p)
768                 {
769                         //return position_valid ^ (p==position_valid_exception);
770                         bool exception = false;
771                         for(core::list<v3s16>::Iterator i=validity_exceptions.begin();
772                                         i != validity_exceptions.end(); i++)
773                         {
774                                 if(p == *i)
775                                 {
776                                         exception = true;
777                                         break;
778                                 }
779                         }
780                         return exception ? !position_valid : position_valid;
781                 }
782
783                 virtual MapNode getNode(v3s16 p)
784                 {
785                         if(isValidPosition(p) == false)
786                                 throw InvalidPositionException();
787                         return node;
788                 }
789
790                 virtual void setNode(v3s16 p, MapNode & n)
791                 {
792                         if(isValidPosition(p) == false)
793                                 throw InvalidPositionException();
794                 };
795
796                 virtual u16 nodeContainerId() const
797                 {
798                         return 666;
799                 }
800         };
801
802         void Run()
803         {
804                 TC parent;
805                 
806                 MapBlock b(&parent, v3s16(1,1,1));
807                 v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
808
809                 assert(b.getPosRelative() == relpos);
810
811                 assert(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
812                 assert(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
813                 assert(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
814                 assert(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
815                 assert(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
816                 assert(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
817                 
818                 assert(b.isValidPosition(v3s16(0,0,0)) == true);
819                 assert(b.isValidPosition(v3s16(-1,0,0)) == false);
820                 assert(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
821                 assert(b.isValidPosition(v3s16(-124,142,2341)) == false);
822                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
823                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);
824
825                 /*
826                         TODO: this method should probably be removed
827                         if the block size isn't going to be set variable
828                 */
829                 /*assert(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
830                                 MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
831                 
832                 // Changed flag should be initially set
833                 assert(b.getModified() == MOD_STATE_WRITE_NEEDED);
834                 b.resetModified();
835                 assert(b.getModified() == MOD_STATE_CLEAN);
836
837                 // All nodes should have been set to
838                 // .d=CONTENT_IGNORE and .getLight() = 0
839                 for(u16 z=0; z<MAP_BLOCKSIZE; z++)
840                 for(u16 y=0; y<MAP_BLOCKSIZE; y++)
841                 for(u16 x=0; x<MAP_BLOCKSIZE; x++)
842                 {
843                         //assert(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR);
844                         assert(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE);
845                         assert(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0);
846                         assert(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0);
847                 }
848                 
849                 {
850                         MapNode n(CONTENT_AIR);
851                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
852                         for(u16 y=0; y<MAP_BLOCKSIZE; y++)
853                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
854                         {
855                                 b.setNode(v3s16(x,y,z), n);
856                         }
857                 }
858                         
859                 /*
860                         Parent fetch functions
861                 */
862                 parent.position_valid = false;
863                 parent.node.setContent(5);
864
865                 MapNode n;
866                 
867                 // Positions in the block should still be valid
868                 assert(b.isValidPositionParent(v3s16(0,0,0)) == true);
869                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
870                 n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
871                 assert(n.getContent() == CONTENT_AIR);
872
873                 // ...but outside the block they should be invalid
874                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
875                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == false);
876                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
877                 
878                 {
879                         bool exception_thrown = false;
880                         try{
881                                 // This should throw an exception
882                                 MapNode n = b.getNodeParent(v3s16(0,0,-1));
883                         }
884                         catch(InvalidPositionException &e)
885                         {
886                                 exception_thrown = true;
887                         }
888                         assert(exception_thrown);
889                 }
890
891                 parent.position_valid = true;
892                 // Now the positions outside should be valid
893                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
894                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == true);
895                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
896                 n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
897                 assert(n.getContent() == 5);
898
899                 /*
900                         Set a node
901                 */
902                 v3s16 p(1,2,0);
903                 n.setContent(4);
904                 b.setNode(p, n);
905                 assert(b.getNode(p).getContent() == 4);
906                 //TODO: Update to new system
907                 /*assert(b.getNodeTile(p) == 4);
908                 assert(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/
909                 
910                 /*
911                         propagateSunlight()
912                 */
913                 // Set lighting of all nodes to 0
914                 for(u16 z=0; z<MAP_BLOCKSIZE; z++){
915                         for(u16 y=0; y<MAP_BLOCKSIZE; y++){
916                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
917                                         MapNode n = b.getNode(v3s16(x,y,z));
918                                         n.setLight(LIGHTBANK_DAY, 0);
919                                         n.setLight(LIGHTBANK_NIGHT, 0);
920                                         b.setNode(v3s16(x,y,z), n);
921                                 }
922                         }
923                 }
924                 {
925                         /*
926                                 Check how the block handles being a lonely sky block
927                         */
928                         parent.position_valid = true;
929                         b.setIsUnderground(false);
930                         parent.node.setContent(CONTENT_AIR);
931                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN);
932                         parent.node.setLight(LIGHTBANK_NIGHT, 0);
933                         core::map<v3s16, bool> light_sources;
934                         // The bottom block is invalid, because we have a shadowing node
935                         assert(b.propagateSunlight(light_sources) == false);
936                         assert(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
937                         assert(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
938                         assert(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0);
939                         assert(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0);
940                         assert(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0);
941                         assert(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
942                         assert(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN);
943                         assert(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0);
944                         assert(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0);
945                         // According to MapBlock::getFaceLight,
946                         // The face on the z+ side should have double-diminished light
947                         //assert(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
948                         // The face on the z+ side should have diminished light
949                         assert(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX));
950                 }
951                 /*
952                         Check how the block handles being in between blocks with some non-sunlight
953                         while being underground
954                 */
955                 {
956                         // Make neighbours to exist and set some non-sunlight to them
957                         parent.position_valid = true;
958                         b.setIsUnderground(true);
959                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
960                         core::map<v3s16, bool> light_sources;
961                         // The block below should be valid because there shouldn't be
962                         // sunlight in there either
963                         assert(b.propagateSunlight(light_sources, true) == true);
964                         // Should not touch nodes that are not affected (that is, all of them)
965                         //assert(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
966                         // Should set light of non-sunlighted blocks to 0.
967                         assert(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0);
968                 }
969                 /*
970                         Set up a situation where:
971                         - There is only air in this block
972                         - There is a valid non-sunlighted block at the bottom, and
973                         - Invalid blocks elsewhere.
974                         - the block is not underground.
975
976                         This should result in bottom block invalidity
977                 */
978                 {
979                         b.setIsUnderground(false);
980                         // Clear block
981                         for(u16 z=0; z<MAP_BLOCKSIZE; z++){
982                                 for(u16 y=0; y<MAP_BLOCKSIZE; y++){
983                                         for(u16 x=0; x<MAP_BLOCKSIZE; x++){
984                                                 MapNode n;
985                                                 n.setContent(CONTENT_AIR);
986                                                 n.setLight(LIGHTBANK_DAY, 0);
987                                                 b.setNode(v3s16(x,y,z), n);
988                                         }
989                                 }
990                         }
991                         // Make neighbours invalid
992                         parent.position_valid = false;
993                         // Add exceptions to the top of the bottom block
994                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
995                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
996                         {
997                                 parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
998                         }
999                         // Lighting value for the valid nodes
1000                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
1001                         core::map<v3s16, bool> light_sources;
1002                         // Bottom block is not valid
1003                         assert(b.propagateSunlight(light_sources) == false);
1004                 }
1005         }
1006 };
1007
1008 struct TestMapSector
1009 {
1010         class TC : public NodeContainer
1011         {
1012         public:
1013
1014                 MapNode node;
1015                 bool position_valid;
1016
1017                 TC()
1018                 {
1019                         position_valid = true;
1020                 }
1021
1022                 virtual bool isValidPosition(v3s16 p)
1023                 {
1024                         return position_valid;
1025                 }
1026
1027                 virtual MapNode getNode(v3s16 p)
1028                 {
1029                         if(position_valid == false)
1030                                 throw InvalidPositionException();
1031                         return node;
1032                 }
1033
1034                 virtual void setNode(v3s16 p, MapNode & n)
1035                 {
1036                         if(position_valid == false)
1037                                 throw InvalidPositionException();
1038                 };
1039                 
1040                 virtual u16 nodeContainerId() const
1041                 {
1042                         return 666;
1043                 }
1044         };
1045         
1046         void Run()
1047         {
1048                 TC parent;
1049                 parent.position_valid = false;
1050                 
1051                 // Create one with no heightmaps
1052                 ServerMapSector sector(&parent, v2s16(1,1));
1053                 
1054                 assert(sector.getBlockNoCreateNoEx(0) == 0);
1055                 assert(sector.getBlockNoCreateNoEx(1) == 0);
1056
1057                 MapBlock * bref = sector.createBlankBlock(-2);
1058                 
1059                 assert(sector.getBlockNoCreateNoEx(0) == 0);
1060                 assert(sector.getBlockNoCreateNoEx(-2) == bref);
1061                 
1062                 //TODO: Check for AlreadyExistsException
1063
1064                 /*bool exception_thrown = false;
1065                 try{
1066                         sector.getBlock(0);
1067                 }
1068                 catch(InvalidPositionException &e){
1069                         exception_thrown = true;
1070                 }
1071                 assert(exception_thrown);*/
1072
1073         }
1074 };
1075 #endif
1076
1077 struct TestSocket
1078 {
1079         void Run()
1080         {
1081                 const int port = 30003;
1082                 UDPSocket socket;
1083                 socket.Bind(port);
1084
1085                 const char sendbuffer[] = "hello world!";
1086                 socket.Send(Address(127,0,0,1,port), sendbuffer, sizeof(sendbuffer));
1087
1088                 sleep_ms(50);
1089
1090                 char rcvbuffer[256];
1091                 memset(rcvbuffer, 0, sizeof(rcvbuffer));
1092                 Address sender;
1093                 for(;;)
1094                 {
1095                         int bytes_read = socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer));
1096                         if(bytes_read < 0)
1097                                 break;
1098                 }
1099                 //FIXME: This fails on some systems
1100                 assert(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0);
1101                 assert(sender.getAddress() == Address(127,0,0,1, 0).getAddress());
1102         }
1103 };
1104
1105 struct TestConnection
1106 {
1107         void TestHelpers()
1108         {
1109                 /*
1110                         Test helper functions
1111                 */
1112
1113                 // Some constants for testing
1114                 u32 proto_id = 0x12345678;
1115                 u16 peer_id = 123;
1116                 u8 channel = 2;
1117                 SharedBuffer<u8> data1(1);
1118                 data1[0] = 100;
1119                 Address a(127,0,0,1, 10);
1120                 u16 seqnum = 34352;
1121
1122                 con::BufferedPacket p1 = con::makePacket(a, data1,
1123                                 proto_id, peer_id, channel);
1124                 /*
1125                         We should now have a packet with this data:
1126                         Header:
1127                                 [0] u32 protocol_id
1128                                 [4] u16 sender_peer_id
1129                                 [6] u8 channel
1130                         Data:
1131                                 [7] u8 data1[0]
1132                 */
1133                 assert(readU32(&p1.data[0]) == proto_id);
1134                 assert(readU16(&p1.data[4]) == peer_id);
1135                 assert(readU8(&p1.data[6]) == channel);
1136                 assert(readU8(&p1.data[7]) == data1[0]);
1137                 
1138                 //infostream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl;
1139
1140                 SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum);
1141
1142                 /*infostream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()="
1143                                 <<data1.getSize()<<std::endl;
1144                 infostream<<"readU8(&p2[3])="<<readU8(&p2[3])
1145                                 <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl;
1146                 infostream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/
1147
1148                 assert(p2.getSize() == 3 + data1.getSize());
1149                 assert(readU8(&p2[0]) == TYPE_RELIABLE);
1150                 assert(readU16(&p2[1]) == seqnum);
1151                 assert(readU8(&p2[3]) == data1[0]);
1152         }
1153
1154         struct Handler : public con::PeerHandler
1155         {
1156                 Handler(const char *a_name)
1157                 {
1158                         count = 0;
1159                         last_id = 0;
1160                         name = a_name;
1161                 }
1162                 void peerAdded(con::Peer *peer)
1163                 {
1164                         infostream<<"Handler("<<name<<")::peerAdded(): "
1165                                         "id="<<peer->id<<std::endl;
1166                         last_id = peer->id;
1167                         count++;
1168                 }
1169                 void deletingPeer(con::Peer *peer, bool timeout)
1170                 {
1171                         infostream<<"Handler("<<name<<")::deletingPeer(): "
1172                                         "id="<<peer->id
1173                                         <<", timeout="<<timeout<<std::endl;
1174                         last_id = peer->id;
1175                         count--;
1176                 }
1177
1178                 s32 count;
1179                 u16 last_id;
1180                 const char *name;
1181         };
1182
1183         void Run()
1184         {
1185                 DSTACK("TestConnection::Run");
1186
1187                 TestHelpers();
1188
1189                 /*
1190                         Test some real connections
1191
1192                         NOTE: This mostly tests the legacy interface.
1193                 */
1194
1195                 u32 proto_id = 0xad26846a;
1196
1197                 Handler hand_server("server");
1198                 Handler hand_client("client");
1199                 
1200                 infostream<<"** Creating server Connection"<<std::endl;
1201                 con::Connection server(proto_id, 512, 5.0, &hand_server);
1202                 server.Serve(30001);
1203                 
1204                 infostream<<"** Creating client Connection"<<std::endl;
1205                 con::Connection client(proto_id, 512, 5.0, &hand_client);
1206
1207                 assert(hand_server.count == 0);
1208                 assert(hand_client.count == 0);
1209                 
1210                 sleep_ms(50);
1211                 
1212                 Address server_address(127,0,0,1, 30001);
1213                 infostream<<"** running client.Connect()"<<std::endl;
1214                 client.Connect(server_address);
1215
1216                 sleep_ms(50);
1217                 
1218                 // Client should not have added client yet
1219                 assert(hand_client.count == 0);
1220                 
1221                 try
1222                 {
1223                         u16 peer_id;
1224                         SharedBuffer<u8> data;
1225                         infostream<<"** running client.Receive()"<<std::endl;
1226                         u32 size = client.Receive(peer_id, data);
1227                         infostream<<"** Client received: peer_id="<<peer_id
1228                                         <<", size="<<size
1229                                         <<std::endl;
1230                 }
1231                 catch(con::NoIncomingDataException &e)
1232                 {
1233                 }
1234
1235                 // Client should have added server now
1236                 assert(hand_client.count == 1);
1237                 assert(hand_client.last_id == 1);
1238                 // Server should not have added client yet
1239                 assert(hand_server.count == 0);
1240                 
1241                 sleep_ms(50);
1242
1243                 try
1244                 {
1245                         u16 peer_id;
1246                         SharedBuffer<u8> data;
1247                         infostream<<"** running server.Receive()"<<std::endl;
1248                         u32 size = server.Receive(peer_id, data);
1249                         infostream<<"** Server received: peer_id="<<peer_id
1250                                         <<", size="<<size
1251                                         <<std::endl;
1252                 }
1253                 catch(con::NoIncomingDataException &e)
1254                 {
1255                         // No actual data received, but the client has
1256                         // probably been connected
1257                 }
1258                 
1259                 // Client should be the same
1260                 assert(hand_client.count == 1);
1261                 assert(hand_client.last_id == 1);
1262                 // Server should have the client
1263                 assert(hand_server.count == 1);
1264                 assert(hand_server.last_id == 2);
1265                 
1266                 //sleep_ms(50);
1267
1268                 while(client.Connected() == false)
1269                 {
1270                         try
1271                         {
1272                                 u16 peer_id;
1273                                 SharedBuffer<u8> data;
1274                                 infostream<<"** running client.Receive()"<<std::endl;
1275                                 u32 size = client.Receive(peer_id, data);
1276                                 infostream<<"** Client received: peer_id="<<peer_id
1277                                                 <<", size="<<size
1278                                                 <<std::endl;
1279                         }
1280                         catch(con::NoIncomingDataException &e)
1281                         {
1282                         }
1283                         sleep_ms(50);
1284                 }
1285
1286                 sleep_ms(50);
1287                 
1288                 try
1289                 {
1290                         u16 peer_id;
1291                         SharedBuffer<u8> data;
1292                         infostream<<"** running server.Receive()"<<std::endl;
1293                         u32 size = server.Receive(peer_id, data);
1294                         infostream<<"** Server received: peer_id="<<peer_id
1295                                         <<", size="<<size
1296                                         <<std::endl;
1297                 }
1298                 catch(con::NoIncomingDataException &e)
1299                 {
1300                 }
1301 #if 1
1302                 /*
1303                         Simple send-receive test
1304                 */
1305                 {
1306                         /*u8 data[] = "Hello World!";
1307                         u32 datasize = sizeof(data);*/
1308                         SharedBuffer<u8> data = SharedBufferFromString("Hello World!");
1309
1310                         infostream<<"** running client.Send()"<<std::endl;
1311                         client.Send(PEER_ID_SERVER, 0, data, true);
1312
1313                         sleep_ms(50);
1314
1315                         u16 peer_id;
1316                         SharedBuffer<u8> recvdata;
1317                         infostream<<"** running server.Receive()"<<std::endl;
1318                         u32 size = server.Receive(peer_id, recvdata);
1319                         infostream<<"** Server received: peer_id="<<peer_id
1320                                         <<", size="<<size
1321                                         <<", data="<<*data
1322                                         <<std::endl;
1323                         assert(memcmp(*data, *recvdata, data.getSize()) == 0);
1324                 }
1325 #endif
1326                 u16 peer_id_client = 2;
1327 #if 0
1328                 /*
1329                         Send consequent packets in different order
1330                         Not compatible with new Connection, thus commented out.
1331                 */
1332                 {
1333                         //u8 data1[] = "hello1";
1334                         //u8 data2[] = "hello2";
1335                         SharedBuffer<u8> data1 = SharedBufferFromString("hello1");
1336                         SharedBuffer<u8> data2 = SharedBufferFromString("Hello2");
1337
1338                         Address client_address =
1339                                         server.GetPeerAddress(peer_id_client);
1340                         
1341                         infostream<<"*** Sending packets in wrong order (2,1,2)"
1342                                         <<std::endl;
1343                         
1344                         u8 chn = 0;
1345                         con::Channel *ch = &server.getPeer(peer_id_client)->channels[chn];
1346                         u16 sn = ch->next_outgoing_seqnum;
1347                         ch->next_outgoing_seqnum = sn+1;
1348                         server.Send(peer_id_client, chn, data2, true);
1349                         ch->next_outgoing_seqnum = sn;
1350                         server.Send(peer_id_client, chn, data1, true);
1351                         ch->next_outgoing_seqnum = sn+1;
1352                         server.Send(peer_id_client, chn, data2, true);
1353
1354                         sleep_ms(50);
1355
1356                         infostream<<"*** Receiving the packets"<<std::endl;
1357
1358                         u16 peer_id;
1359                         SharedBuffer<u8> recvdata;
1360                         u32 size;
1361
1362                         infostream<<"** running client.Receive()"<<std::endl;
1363                         peer_id = 132;
1364                         size = client.Receive(peer_id, recvdata);
1365                         infostream<<"** Client received: peer_id="<<peer_id
1366                                         <<", size="<<size
1367                                         <<", data="<<*recvdata
1368                                         <<std::endl;
1369                         assert(size == data1.getSize());
1370                         assert(memcmp(*data1, *recvdata, data1.getSize()) == 0);
1371                         assert(peer_id == PEER_ID_SERVER);
1372                         
1373                         infostream<<"** running client.Receive()"<<std::endl;
1374                         peer_id = 132;
1375                         size = client.Receive(peer_id, recvdata);
1376                         infostream<<"** Client received: peer_id="<<peer_id
1377                                         <<", size="<<size
1378                                         <<", data="<<*recvdata
1379                                         <<std::endl;
1380                         assert(size == data2.getSize());
1381                         assert(memcmp(*data2, *recvdata, data2.getSize()) == 0);
1382                         assert(peer_id == PEER_ID_SERVER);
1383                         
1384                         bool got_exception = false;
1385                         try
1386                         {
1387                                 infostream<<"** running client.Receive()"<<std::endl;
1388                                 peer_id = 132;
1389                                 size = client.Receive(peer_id, recvdata);
1390                                 infostream<<"** Client received: peer_id="<<peer_id
1391                                                 <<", size="<<size
1392                                                 <<", data="<<*recvdata
1393                                                 <<std::endl;
1394                         }
1395                         catch(con::NoIncomingDataException &e)
1396                         {
1397                                 infostream<<"** No incoming data for client"<<std::endl;
1398                                 got_exception = true;
1399                         }
1400                         assert(got_exception);
1401                 }
1402 #endif
1403 #if 0
1404                 /*
1405                         Send large amounts of packets (infinite test)
1406                         Commented out because of infinity.
1407                 */
1408                 {
1409                         infostream<<"Sending large amounts of packets (infinite test)"<<std::endl;
1410                         int sendcount = 0;
1411                         for(;;){
1412                                 int datasize = myrand_range(0,5)==0?myrand_range(100,10000):myrand_range(0,100);
1413                                 infostream<<"datasize="<<datasize<<std::endl;
1414                                 SharedBuffer<u8> data1(datasize);
1415                                 for(u16 i=0; i<datasize; i++)
1416                                         data1[i] = i/4;
1417                                 
1418                                 int sendtimes = myrand_range(1,10);
1419                                 for(int i=0; i<sendtimes; i++){
1420                                         server.Send(peer_id_client, 0, data1, true);
1421                                         sendcount++;
1422                                 }
1423                                 infostream<<"sendcount="<<sendcount<<std::endl;
1424                                 
1425                                 //int receivetimes = myrand_range(1,20);
1426                                 int receivetimes = 20;
1427                                 for(int i=0; i<receivetimes; i++){
1428                                         SharedBuffer<u8> recvdata;
1429                                         u16 peer_id = 132;
1430                                         u16 size = 0;
1431                                         bool received = false;
1432                                         try{
1433                                                 size = client.Receive(peer_id, recvdata);
1434                                                 received = true;
1435                                         }catch(con::NoIncomingDataException &e){
1436                                         }
1437                                 }
1438                         }
1439                 }
1440 #endif
1441                 /*
1442                         Send a large packet
1443                 */
1444                 {
1445                         const int datasize = 30000;
1446                         SharedBuffer<u8> data1(datasize);
1447                         for(u16 i=0; i<datasize; i++){
1448                                 data1[i] = i/4;
1449                         }
1450
1451                         infostream<<"Sending data (size="<<datasize<<"):";
1452                         for(int i=0; i<datasize && i<20; i++){
1453                                 if(i%2==0) infostream<<" ";
1454                                 char buf[10];
1455                                 snprintf(buf, 10, "%.2X", ((int)((const char*)*data1)[i])&0xff);
1456                                 infostream<<buf;
1457                         }
1458                         if(datasize>20)
1459                                 infostream<<"...";
1460                         infostream<<std::endl;
1461                         
1462                         server.Send(peer_id_client, 0, data1, true);
1463
1464                         //sleep_ms(3000);
1465                         
1466                         SharedBuffer<u8> recvdata;
1467                         infostream<<"** running client.Receive()"<<std::endl;
1468                         u16 peer_id = 132;
1469                         u16 size = 0;
1470                         bool received = false;
1471                         u32 timems0 = porting::getTimeMs();
1472                         for(;;){
1473                                 if(porting::getTimeMs() - timems0 > 5000 || received)
1474                                         break;
1475                                 try{
1476                                         size = client.Receive(peer_id, recvdata);
1477                                         received = true;
1478                                 }catch(con::NoIncomingDataException &e){
1479                                 }
1480                                 sleep_ms(10);
1481                         }
1482                         assert(received);
1483                         infostream<<"** Client received: peer_id="<<peer_id
1484                                         <<", size="<<size
1485                                         <<std::endl;
1486
1487                         infostream<<"Received data (size="<<size<<"): ";
1488                         for(int i=0; i<size && i<20; i++){
1489                                 if(i%2==0) infostream<<" ";
1490                                 char buf[10];
1491                                 snprintf(buf, 10, "%.2X", ((int)(recvdata[i]))&0xff);
1492                                 infostream<<buf;
1493                         }
1494                         if(size>20)
1495                                 infostream<<"...";
1496                         infostream<<std::endl;
1497
1498                         assert(memcmp(*data1, *recvdata, data1.getSize()) == 0);
1499                         assert(peer_id == PEER_ID_SERVER);
1500                 }
1501                 
1502                 // Check peer handlers
1503                 assert(hand_client.count == 1);
1504                 assert(hand_client.last_id == 1);
1505                 assert(hand_server.count == 1);
1506                 assert(hand_server.last_id == 2);
1507                 
1508                 //assert(0);
1509         }
1510 };
1511
1512 #define TEST(X)\
1513 {\
1514         X x;\
1515         infostream<<"Running " #X <<std::endl;\
1516         x.Run();\
1517 }
1518
1519 #define TESTPARAMS(X, ...)\
1520 {\
1521         X x;\
1522         infostream<<"Running " #X <<std::endl;\
1523         x.Run(__VA_ARGS__);\
1524 }
1525
1526 void run_tests()
1527 {
1528         DSTACK(__FUNCTION_NAME);
1529         
1530         // Create item and node definitions
1531         IWritableItemDefManager *idef = createItemDefManager();
1532         IWritableNodeDefManager *ndef = createNodeDefManager();
1533         define_some_nodes(idef, ndef);
1534
1535         infostream<<"run_tests() started"<<std::endl;
1536         TEST(TestUtilities);
1537         TEST(TestSettings);
1538         TEST(TestCompress);
1539         TEST(TestSerialization);
1540         TESTPARAMS(TestMapNode, ndef);
1541         TESTPARAMS(TestVoxelManipulator, ndef);
1542         TESTPARAMS(TestVoxelAlgorithms, ndef);
1543         TESTPARAMS(TestInventory, idef);
1544         //TEST(TestMapBlock);
1545         //TEST(TestMapSector);
1546         if(INTERNET_SIMULATOR == false){
1547                 TEST(TestSocket);
1548                 dout_con<<"=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
1549                 TEST(TestConnection);
1550                 dout_con<<"=== END RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
1551         }
1552         infostream<<"run_tests() passed"<<std::endl;
1553 }
1554