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