utility.h: Change Buffer's interface to be more compatible with SharedBuffer's interf...
[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 "mapsector.h"
35 #include "settings.h"
36 #include "log.h"
37
38 /*
39         Asserts that the exception occurs
40 */
41 #define EXCEPTION_CHECK(EType, code)\
42 {\
43         bool exception_thrown = false;\
44         try{ code; }\
45         catch(EType &e) { exception_thrown = true; }\
46         assert(exception_thrown);\
47 }
48
49 struct TestUtilities
50 {
51         void Run()
52         {
53                 /*infostream<<"wrapDegrees(100.0) = "<<wrapDegrees(100.0)<<std::endl;
54                 infostream<<"wrapDegrees(720.5) = "<<wrapDegrees(720.5)<<std::endl;
55                 infostream<<"wrapDegrees(-0.5) = "<<wrapDegrees(-0.5)<<std::endl;*/
56                 assert(fabs(wrapDegrees(100.0) - 100.0) < 0.001);
57                 assert(fabs(wrapDegrees(720.5) - 0.5) < 0.001);
58                 assert(fabs(wrapDegrees(-0.5) - (-0.5)) < 0.001);
59                 assert(fabs(wrapDegrees(-365.5) - (-5.5)) < 0.001);
60                 assert(lowercase("Foo bAR") == "foo bar");
61                 assert(is_yes("YeS") == true);
62                 assert(is_yes("") == false);
63                 assert(is_yes("FAlse") == false);
64         }
65 };
66
67 struct TestSettings
68 {
69         void Run()
70         {
71                 Settings s;
72                 // Test reading of settings
73                 s.parseConfigLine("leet = 1337");
74                 s.parseConfigLine("leetleet = 13371337");
75                 s.parseConfigLine("leetleet_neg = -13371337");
76                 s.parseConfigLine("floaty_thing = 1.1");
77                 s.parseConfigLine("stringy_thing = asd /( ¤%&(/\" BLÖÄRP");
78                 s.parseConfigLine("coord = (1, 2, 4.5)");
79                 assert(s.getS32("leet") == 1337);
80                 assert(s.getS16("leetleet") == 32767);
81                 assert(s.getS16("leetleet_neg") == -32768);
82                 // Not sure if 1.1 is an exact value as a float, but doesn't matter
83                 assert(fabs(s.getFloat("floaty_thing") - 1.1) < 0.001);
84                 assert(s.get("stringy_thing") == "asd /( ¤%&(/\" BLÖÄRP");
85                 assert(fabs(s.getV3F("coord").X - 1.0) < 0.001);
86                 assert(fabs(s.getV3F("coord").Y - 2.0) < 0.001);
87                 assert(fabs(s.getV3F("coord").Z - 4.5) < 0.001);
88                 // Test the setting of settings too
89                 s.setFloat("floaty_thing_2", 1.2);
90                 s.setV3F("coord2", v3f(1, 2, 3.3));
91                 assert(s.get("floaty_thing_2").substr(0,3) == "1.2");
92                 assert(fabs(s.getFloat("floaty_thing_2") - 1.2) < 0.001);
93                 assert(fabs(s.getV3F("coord2").X - 1.0) < 0.001);
94                 assert(fabs(s.getV3F("coord2").Y - 2.0) < 0.001);
95                 assert(fabs(s.getV3F("coord2").Z - 3.3) < 0.001);
96         }
97 };
98                 
99 struct TestCompress
100 {
101         void Run()
102         {
103                 { // ver 0
104
105                 SharedBuffer<u8> fromdata(4);
106                 fromdata[0]=1;
107                 fromdata[1]=5;
108                 fromdata[2]=5;
109                 fromdata[3]=1;
110                 
111                 std::ostringstream os(std::ios_base::binary);
112                 compress(fromdata, os, 0);
113
114                 std::string str_out = os.str();
115                 
116                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
117                 infostream<<"TestCompress: 1,5,5,1 -> ";
118                 for(u32 i=0; i<str_out.size(); i++)
119                 {
120                         infostream<<(u32)str_out[i]<<",";
121                 }
122                 infostream<<std::endl;
123
124                 assert(str_out.size() == 10);
125
126                 assert(str_out[0] == 0);
127                 assert(str_out[1] == 0);
128                 assert(str_out[2] == 0);
129                 assert(str_out[3] == 4);
130                 assert(str_out[4] == 0);
131                 assert(str_out[5] == 1);
132                 assert(str_out[6] == 1);
133                 assert(str_out[7] == 5);
134                 assert(str_out[8] == 0);
135                 assert(str_out[9] == 1);
136
137                 std::istringstream is(str_out, std::ios_base::binary);
138                 std::ostringstream os2(std::ios_base::binary);
139
140                 decompress(is, os2, 0);
141                 std::string str_out2 = os2.str();
142
143                 infostream<<"decompress: ";
144                 for(u32 i=0; i<str_out2.size(); i++)
145                 {
146                         infostream<<(u32)str_out2[i]<<",";
147                 }
148                 infostream<<std::endl;
149
150                 assert(str_out2.size() == fromdata.getSize());
151
152                 for(u32 i=0; i<str_out2.size(); i++)
153                 {
154                         assert(str_out2[i] == fromdata[i]);
155                 }
156
157                 }
158
159                 { // ver HIGHEST
160
161                 SharedBuffer<u8> fromdata(4);
162                 fromdata[0]=1;
163                 fromdata[1]=5;
164                 fromdata[2]=5;
165                 fromdata[3]=1;
166                 
167                 std::ostringstream os(std::ios_base::binary);
168                 compress(fromdata, os, SER_FMT_VER_HIGHEST);
169
170                 std::string str_out = os.str();
171                 
172                 infostream<<"str_out.size()="<<str_out.size()<<std::endl;
173                 infostream<<"TestCompress: 1,5,5,1 -> ";
174                 for(u32 i=0; i<str_out.size(); i++)
175                 {
176                         infostream<<(u32)str_out[i]<<",";
177                 }
178                 infostream<<std::endl;
179
180                 /*assert(str_out.size() == 10);
181
182                 assert(str_out[0] == 0);
183                 assert(str_out[1] == 0);
184                 assert(str_out[2] == 0);
185                 assert(str_out[3] == 4);
186                 assert(str_out[4] == 0);
187                 assert(str_out[5] == 1);
188                 assert(str_out[6] == 1);
189                 assert(str_out[7] == 5);
190                 assert(str_out[8] == 0);
191                 assert(str_out[9] == 1);*/
192
193                 std::istringstream is(str_out, std::ios_base::binary);
194                 std::ostringstream os2(std::ios_base::binary);
195
196                 decompress(is, os2, SER_FMT_VER_HIGHEST);
197                 std::string str_out2 = os2.str();
198
199                 infostream<<"decompress: ";
200                 for(u32 i=0; i<str_out2.size(); i++)
201                 {
202                         infostream<<(u32)str_out2[i]<<",";
203                 }
204                 infostream<<std::endl;
205
206                 assert(str_out2.size() == fromdata.getSize());
207
208                 for(u32 i=0; i<str_out2.size(); i++)
209                 {
210                         assert(str_out2[i] == fromdata[i]);
211                 }
212
213                 }
214         }
215 };
216
217 struct TestMapNode
218 {
219         void Run()
220         {
221                 MapNode n;
222
223                 // Default values
224                 assert(n.getContent() == CONTENT_AIR);
225                 assert(n.getLight(LIGHTBANK_DAY) == 0);
226                 assert(n.getLight(LIGHTBANK_NIGHT) == 0);
227                 
228                 // Transparency
229                 n.setContent(CONTENT_AIR);
230                 assert(n.light_propagates() == true);
231                 n.setContent(CONTENT_STONE);
232                 assert(n.light_propagates() == false);
233         }
234 };
235
236 struct TestVoxelManipulator
237 {
238         void Run()
239         {
240                 /*
241                         VoxelArea
242                 */
243
244                 VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1));
245                 assert(a.index(0,0,0) == 1*3*3 + 1*3 + 1);
246                 assert(a.index(-1,-1,-1) == 0);
247                 
248                 VoxelArea c(v3s16(-2,-2,-2), v3s16(2,2,2));
249                 // An area that is 1 bigger in x+ and z-
250                 VoxelArea d(v3s16(-2,-2,-3), v3s16(3,2,2));
251                 
252                 core::list<VoxelArea> aa;
253                 d.diff(c, aa);
254                 
255                 // Correct results
256                 core::array<VoxelArea> results;
257                 results.push_back(VoxelArea(v3s16(-2,-2,-3),v3s16(3,2,-3)));
258                 results.push_back(VoxelArea(v3s16(3,-2,-2),v3s16(3,2,2)));
259
260                 assert(aa.size() == results.size());
261                 
262                 infostream<<"Result of diff:"<<std::endl;
263                 for(core::list<VoxelArea>::Iterator
264                                 i = aa.begin(); i != aa.end(); i++)
265                 {
266                         i->print(infostream);
267                         infostream<<std::endl;
268                         
269                         s32 j = results.linear_search(*i);
270                         assert(j != -1);
271                         results.erase(j, 1);
272                 }
273
274
275                 /*
276                         VoxelManipulator
277                 */
278                 
279                 VoxelManipulator v;
280
281                 v.print(infostream);
282
283                 infostream<<"*** Setting (-1,0,-1)=2 ***"<<std::endl;
284                 
285                 v.setNodeNoRef(v3s16(-1,0,-1), MapNode(2));
286
287                 v.print(infostream);
288
289                 assert(v.getNode(v3s16(-1,0,-1)).getContent() == 2);
290
291                 infostream<<"*** Reading from inexistent (0,0,-1) ***"<<std::endl;
292
293                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1)));
294
295                 v.print(infostream);
296
297                 infostream<<"*** Adding area ***"<<std::endl;
298
299                 v.addArea(a);
300                 
301                 v.print(infostream);
302
303                 assert(v.getNode(v3s16(-1,0,-1)).getContent() == 2);
304                 EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1)));
305
306 #if 0
307                 /*
308                         Water stuff
309                 */
310
311                 v.clear();
312
313                 const char *content =
314                         "#...######  "
315                         "#...##..##  "
316                         "#........ .."
317                         "############"
318
319                         "#...######  "
320                         "#...##..##  "
321                         "#........#  "
322                         "############"
323                 ;
324
325                 v3s16 size(12, 4, 2);
326                 VoxelArea area(v3s16(0,0,0), size-v3s16(1,1,1));
327                 
328                 const char *p = content;
329                 for(s16 z=0; z<size.Z; z++)
330                 for(s16 y=size.Y-1; y>=0; y--)
331                 for(s16 x=0; x<size.X; x++)
332                 {
333                         MapNode n;
334                         //n.pressure = size.Y - y;
335                         if(*p == '#')
336                                 n.setContent(CONTENT_STONE);
337                         else if(*p == '.')
338                                 n.setContent(CONTENT_WATER);
339                         else if(*p == ' ')
340                                 n.setContent(CONTENT_AIR);
341                         else
342                                 assert(0);
343                         v.setNode(v3s16(x,y,z), n);
344                         p++;
345                 }
346
347                 v.print(infostream, VOXELPRINT_WATERPRESSURE);
348                 
349                 core::map<v3s16, u8> active_nodes;
350                 v.updateAreaWaterPressure(area, active_nodes);
351
352                 v.print(infostream, VOXELPRINT_WATERPRESSURE);
353                 
354                 //s16 highest_y = -32768;
355                 /*
356                         NOTE: These are commented out because this behaviour is changed
357                               all the time
358                 */
359                 //assert(v.getWaterPressure(v3s16(7, 1, 1), highest_y, 0) == -1);
360                 //assert(highest_y == 3);
361                 /*assert(v.getWaterPressure(v3s16(7, 1, 1), highest_y, 0) == 3);
362                 //assert(highest_y == 3);*/
363                 
364                 active_nodes.clear();
365                 active_nodes[v3s16(9,1,0)] = 1;
366                 //v.flowWater(active_nodes, 0, true, 1000);
367                 v.flowWater(active_nodes, 0, false, 1000);
368                 
369                 infostream<<"Final result of flowWater:"<<std::endl;
370                 v.print(infostream, VOXELPRINT_WATERPRESSURE);
371 #endif
372                 
373                 //assert(0);
374         }
375 };
376
377 /*
378         NOTE: These tests became non-working then NodeContainer was removed.
379               These should be redone, utilizing some kind of a virtual
380                   interface for Map (IMap would be fine).
381 */
382 #if 0
383 struct TestMapBlock
384 {
385         class TC : public NodeContainer
386         {
387         public:
388
389                 MapNode node;
390                 bool position_valid;
391                 core::list<v3s16> validity_exceptions;
392
393                 TC()
394                 {
395                         position_valid = true;
396                 }
397
398                 virtual bool isValidPosition(v3s16 p)
399                 {
400                         //return position_valid ^ (p==position_valid_exception);
401                         bool exception = false;
402                         for(core::list<v3s16>::Iterator i=validity_exceptions.begin();
403                                         i != validity_exceptions.end(); i++)
404                         {
405                                 if(p == *i)
406                                 {
407                                         exception = true;
408                                         break;
409                                 }
410                         }
411                         return exception ? !position_valid : position_valid;
412                 }
413
414                 virtual MapNode getNode(v3s16 p)
415                 {
416                         if(isValidPosition(p) == false)
417                                 throw InvalidPositionException();
418                         return node;
419                 }
420
421                 virtual void setNode(v3s16 p, MapNode & n)
422                 {
423                         if(isValidPosition(p) == false)
424                                 throw InvalidPositionException();
425                 };
426
427                 virtual u16 nodeContainerId() const
428                 {
429                         return 666;
430                 }
431         };
432
433         void Run()
434         {
435                 TC parent;
436                 
437                 MapBlock b(&parent, v3s16(1,1,1));
438                 v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
439
440                 assert(b.getPosRelative() == relpos);
441
442                 assert(b.getBox().MinEdge.X == MAP_BLOCKSIZE);
443                 assert(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1);
444                 assert(b.getBox().MinEdge.Y == MAP_BLOCKSIZE);
445                 assert(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1);
446                 assert(b.getBox().MinEdge.Z == MAP_BLOCKSIZE);
447                 assert(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1);
448                 
449                 assert(b.isValidPosition(v3s16(0,0,0)) == true);
450                 assert(b.isValidPosition(v3s16(-1,0,0)) == false);
451                 assert(b.isValidPosition(v3s16(-1,-142,-2341)) == false);
452                 assert(b.isValidPosition(v3s16(-124,142,2341)) == false);
453                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
454                 assert(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false);
455
456                 /*
457                         TODO: this method should probably be removed
458                         if the block size isn't going to be set variable
459                 */
460                 /*assert(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE,
461                                 MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/
462                 
463                 // Changed flag should be initially set
464                 assert(b.getChangedFlag() == true);
465                 b.resetChangedFlag();
466                 assert(b.getChangedFlag() == false);
467
468                 // All nodes should have been set to
469                 // .d=CONTENT_IGNORE and .getLight() = 0
470                 for(u16 z=0; z<MAP_BLOCKSIZE; z++)
471                 for(u16 y=0; y<MAP_BLOCKSIZE; y++)
472                 for(u16 x=0; x<MAP_BLOCKSIZE; x++)
473                 {
474                         //assert(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR);
475                         assert(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE);
476                         assert(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0);
477                         assert(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0);
478                 }
479                 
480                 {
481                         MapNode n(CONTENT_AIR);
482                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
483                         for(u16 y=0; y<MAP_BLOCKSIZE; y++)
484                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
485                         {
486                                 b.setNode(v3s16(x,y,z), n);
487                         }
488                 }
489                         
490                 /*
491                         Parent fetch functions
492                 */
493                 parent.position_valid = false;
494                 parent.node.setContent(5);
495
496                 MapNode n;
497                 
498                 // Positions in the block should still be valid
499                 assert(b.isValidPositionParent(v3s16(0,0,0)) == true);
500                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true);
501                 n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0));
502                 assert(n.getContent() == CONTENT_AIR);
503
504                 // ...but outside the block they should be invalid
505                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == false);
506                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == false);
507                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false);
508                 
509                 {
510                         bool exception_thrown = false;
511                         try{
512                                 // This should throw an exception
513                                 MapNode n = b.getNodeParent(v3s16(0,0,-1));
514                         }
515                         catch(InvalidPositionException &e)
516                         {
517                                 exception_thrown = true;
518                         }
519                         assert(exception_thrown);
520                 }
521
522                 parent.position_valid = true;
523                 // Now the positions outside should be valid
524                 assert(b.isValidPositionParent(v3s16(-121,2341,0)) == true);
525                 assert(b.isValidPositionParent(v3s16(-1,0,0)) == true);
526                 assert(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true);
527                 n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE));
528                 assert(n.getContent() == 5);
529
530                 /*
531                         Set a node
532                 */
533                 v3s16 p(1,2,0);
534                 n.setContent(4);
535                 b.setNode(p, n);
536                 assert(b.getNode(p).getContent() == 4);
537                 //TODO: Update to new system
538                 /*assert(b.getNodeTile(p) == 4);
539                 assert(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/
540                 
541                 /*
542                         propagateSunlight()
543                 */
544                 // Set lighting of all nodes to 0
545                 for(u16 z=0; z<MAP_BLOCKSIZE; z++){
546                         for(u16 y=0; y<MAP_BLOCKSIZE; y++){
547                                 for(u16 x=0; x<MAP_BLOCKSIZE; x++){
548                                         MapNode n = b.getNode(v3s16(x,y,z));
549                                         n.setLight(LIGHTBANK_DAY, 0);
550                                         n.setLight(LIGHTBANK_NIGHT, 0);
551                                         b.setNode(v3s16(x,y,z), n);
552                                 }
553                         }
554                 }
555                 {
556                         /*
557                                 Check how the block handles being a lonely sky block
558                         */
559                         parent.position_valid = true;
560                         b.setIsUnderground(false);
561                         parent.node.setContent(CONTENT_AIR);
562                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN);
563                         parent.node.setLight(LIGHTBANK_NIGHT, 0);
564                         core::map<v3s16, bool> light_sources;
565                         // The bottom block is invalid, because we have a shadowing node
566                         assert(b.propagateSunlight(light_sources) == false);
567                         assert(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
568                         assert(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
569                         assert(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0);
570                         assert(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0);
571                         assert(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0);
572                         assert(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN);
573                         assert(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN);
574                         assert(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0);
575                         assert(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0);
576                         // According to MapBlock::getFaceLight,
577                         // The face on the z+ side should have double-diminished light
578                         //assert(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX)));
579                         // The face on the z+ side should have diminished light
580                         assert(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX));
581                 }
582                 /*
583                         Check how the block handles being in between blocks with some non-sunlight
584                         while being underground
585                 */
586                 {
587                         // Make neighbours to exist and set some non-sunlight to them
588                         parent.position_valid = true;
589                         b.setIsUnderground(true);
590                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
591                         core::map<v3s16, bool> light_sources;
592                         // The block below should be valid because there shouldn't be
593                         // sunlight in there either
594                         assert(b.propagateSunlight(light_sources, true) == true);
595                         // Should not touch nodes that are not affected (that is, all of them)
596                         //assert(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN);
597                         // Should set light of non-sunlighted blocks to 0.
598                         assert(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0);
599                 }
600                 /*
601                         Set up a situation where:
602                         - There is only air in this block
603                         - There is a valid non-sunlighted block at the bottom, and
604                         - Invalid blocks elsewhere.
605                         - the block is not underground.
606
607                         This should result in bottom block invalidity
608                 */
609                 {
610                         b.setIsUnderground(false);
611                         // Clear block
612                         for(u16 z=0; z<MAP_BLOCKSIZE; z++){
613                                 for(u16 y=0; y<MAP_BLOCKSIZE; y++){
614                                         for(u16 x=0; x<MAP_BLOCKSIZE; x++){
615                                                 MapNode n;
616                                                 n.setContent(CONTENT_AIR);
617                                                 n.setLight(LIGHTBANK_DAY, 0);
618                                                 b.setNode(v3s16(x,y,z), n);
619                                         }
620                                 }
621                         }
622                         // Make neighbours invalid
623                         parent.position_valid = false;
624                         // Add exceptions to the top of the bottom block
625                         for(u16 x=0; x<MAP_BLOCKSIZE; x++)
626                         for(u16 z=0; z<MAP_BLOCKSIZE; z++)
627                         {
628                                 parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z));
629                         }
630                         // Lighting value for the valid nodes
631                         parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2);
632                         core::map<v3s16, bool> light_sources;
633                         // Bottom block is not valid
634                         assert(b.propagateSunlight(light_sources) == false);
635                 }
636         }
637 };
638
639 struct TestMapSector
640 {
641         class TC : public NodeContainer
642         {
643         public:
644
645                 MapNode node;
646                 bool position_valid;
647
648                 TC()
649                 {
650                         position_valid = true;
651                 }
652
653                 virtual bool isValidPosition(v3s16 p)
654                 {
655                         return position_valid;
656                 }
657
658                 virtual MapNode getNode(v3s16 p)
659                 {
660                         if(position_valid == false)
661                                 throw InvalidPositionException();
662                         return node;
663                 }
664
665                 virtual void setNode(v3s16 p, MapNode & n)
666                 {
667                         if(position_valid == false)
668                                 throw InvalidPositionException();
669                 };
670                 
671                 virtual u16 nodeContainerId() const
672                 {
673                         return 666;
674                 }
675         };
676         
677         void Run()
678         {
679                 TC parent;
680                 parent.position_valid = false;
681                 
682                 // Create one with no heightmaps
683                 ServerMapSector sector(&parent, v2s16(1,1));
684                 
685                 assert(sector.getBlockNoCreateNoEx(0) == 0);
686                 assert(sector.getBlockNoCreateNoEx(1) == 0);
687
688                 MapBlock * bref = sector.createBlankBlock(-2);
689                 
690                 assert(sector.getBlockNoCreateNoEx(0) == 0);
691                 assert(sector.getBlockNoCreateNoEx(-2) == bref);
692                 
693                 //TODO: Check for AlreadyExistsException
694
695                 /*bool exception_thrown = false;
696                 try{
697                         sector.getBlock(0);
698                 }
699                 catch(InvalidPositionException &e){
700                         exception_thrown = true;
701                 }
702                 assert(exception_thrown);*/
703
704         }
705 };
706 #endif
707
708 struct TestSocket
709 {
710         void Run()
711         {
712                 const int port = 30003;
713                 UDPSocket socket;
714                 socket.Bind(port);
715
716                 const char sendbuffer[] = "hello world!";
717                 socket.Send(Address(127,0,0,1,port), sendbuffer, sizeof(sendbuffer));
718
719                 sleep_ms(50);
720
721                 char rcvbuffer[256];
722                 memset(rcvbuffer, 0, sizeof(rcvbuffer));
723                 Address sender;
724                 for(;;)
725                 {
726                         int bytes_read = socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer));
727                         if(bytes_read < 0)
728                                 break;
729                 }
730                 //FIXME: This fails on some systems
731                 assert(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0);
732                 assert(sender.getAddress() == Address(127,0,0,1, 0).getAddress());
733         }
734 };
735
736 struct TestConnection
737 {
738         void TestHelpers()
739         {
740                 /*
741                         Test helper functions
742                 */
743
744                 // Some constants for testing
745                 u32 proto_id = 0x12345678;
746                 u16 peer_id = 123;
747                 u8 channel = 2;
748                 SharedBuffer<u8> data1(1);
749                 data1[0] = 100;
750                 Address a(127,0,0,1, 10);
751                 u16 seqnum = 34352;
752
753                 con::BufferedPacket p1 = con::makePacket(a, data1,
754                                 proto_id, peer_id, channel);
755                 /*
756                         We should now have a packet with this data:
757                         Header:
758                                 [0] u32 protocol_id
759                                 [4] u16 sender_peer_id
760                                 [6] u8 channel
761                         Data:
762                                 [7] u8 data1[0]
763                 */
764                 assert(readU32(&p1.data[0]) == proto_id);
765                 assert(readU16(&p1.data[4]) == peer_id);
766                 assert(readU8(&p1.data[6]) == channel);
767                 assert(readU8(&p1.data[7]) == data1[0]);
768                 
769                 //infostream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl;
770
771                 SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum);
772
773                 /*infostream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()="
774                                 <<data1.getSize()<<std::endl;
775                 infostream<<"readU8(&p2[3])="<<readU8(&p2[3])
776                                 <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl;
777                 infostream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/
778
779                 assert(p2.getSize() == 3 + data1.getSize());
780                 assert(readU8(&p2[0]) == TYPE_RELIABLE);
781                 assert(readU16(&p2[1]) == seqnum);
782                 assert(readU8(&p2[3]) == data1[0]);
783         }
784
785         struct Handler : public con::PeerHandler
786         {
787                 Handler(const char *a_name)
788                 {
789                         count = 0;
790                         last_id = 0;
791                         name = a_name;
792                 }
793                 void peerAdded(con::Peer *peer)
794                 {
795                         infostream<<"Handler("<<name<<")::peerAdded(): "
796                                         "id="<<peer->id<<std::endl;
797                         last_id = peer->id;
798                         count++;
799                 }
800                 void deletingPeer(con::Peer *peer, bool timeout)
801                 {
802                         infostream<<"Handler("<<name<<")::deletingPeer(): "
803                                         "id="<<peer->id
804                                         <<", timeout="<<timeout<<std::endl;
805                         last_id = peer->id;
806                         count--;
807                 }
808
809                 s32 count;
810                 u16 last_id;
811                 const char *name;
812         };
813
814         void Run()
815         {
816                 DSTACK("TestConnection::Run");
817
818                 TestHelpers();
819
820                 /*
821                         Test some real connections
822
823                         NOTE: This mostly tests the legacy interface.
824                 */
825
826                 u32 proto_id = 0xad26846a;
827
828                 Handler hand_server("server");
829                 Handler hand_client("client");
830                 
831                 infostream<<"** Creating server Connection"<<std::endl;
832                 con::Connection server(proto_id, 512, 5.0, &hand_server);
833                 server.Serve(30001);
834                 
835                 infostream<<"** Creating client Connection"<<std::endl;
836                 con::Connection client(proto_id, 512, 5.0, &hand_client);
837
838                 assert(hand_server.count == 0);
839                 assert(hand_client.count == 0);
840                 
841                 sleep_ms(50);
842                 
843                 Address server_address(127,0,0,1, 30001);
844                 infostream<<"** running client.Connect()"<<std::endl;
845                 client.Connect(server_address);
846
847                 sleep_ms(50);
848                 
849                 // Client should not have added client yet
850                 assert(hand_client.count == 0);
851                 
852                 try
853                 {
854                         u16 peer_id;
855                         u8 data[100];
856                         infostream<<"** running client.Receive()"<<std::endl;
857                         u32 size = client.Receive(peer_id, data, 100);
858                         infostream<<"** Client received: peer_id="<<peer_id
859                                         <<", size="<<size
860                                         <<std::endl;
861                 }
862                 catch(con::NoIncomingDataException &e)
863                 {
864                 }
865
866                 // Client should have added server now
867                 assert(hand_client.count == 1);
868                 assert(hand_client.last_id == 1);
869                 // Server should not have added client yet
870                 assert(hand_server.count == 0);
871                 
872                 sleep_ms(50);
873
874                 try
875                 {
876                         u16 peer_id;
877                         u8 data[100];
878                         infostream<<"** running server.Receive()"<<std::endl;
879                         u32 size = server.Receive(peer_id, data, 100);
880                         infostream<<"** Server received: peer_id="<<peer_id
881                                         <<", size="<<size
882                                         <<std::endl;
883                 }
884                 catch(con::NoIncomingDataException &e)
885                 {
886                         // No actual data received, but the client has
887                         // probably been connected
888                 }
889                 
890                 // Client should be the same
891                 assert(hand_client.count == 1);
892                 assert(hand_client.last_id == 1);
893                 // Server should have the client
894                 assert(hand_server.count == 1);
895                 assert(hand_server.last_id == 2);
896                 
897                 //sleep_ms(50);
898
899                 while(client.Connected() == false)
900                 {
901                         try
902                         {
903                                 u16 peer_id;
904                                 u8 data[100];
905                                 infostream<<"** running client.Receive()"<<std::endl;
906                                 u32 size = client.Receive(peer_id, data, 100);
907                                 infostream<<"** Client received: peer_id="<<peer_id
908                                                 <<", size="<<size
909                                                 <<std::endl;
910                         }
911                         catch(con::NoIncomingDataException &e)
912                         {
913                         }
914                         sleep_ms(50);
915                 }
916
917                 sleep_ms(50);
918                 
919                 try
920                 {
921                         u16 peer_id;
922                         u8 data[100];
923                         infostream<<"** running server.Receive()"<<std::endl;
924                         u32 size = server.Receive(peer_id, data, 100);
925                         infostream<<"** Server received: peer_id="<<peer_id
926                                         <<", size="<<size
927                                         <<std::endl;
928                 }
929                 catch(con::NoIncomingDataException &e)
930                 {
931                 }
932 #if 1
933                 /*
934                         Simple send-receive test
935                 */
936                 {
937                         /*u8 data[] = "Hello World!";
938                         u32 datasize = sizeof(data);*/
939                         SharedBuffer<u8> data = SharedBufferFromString("Hello World!");
940
941                         infostream<<"** running client.Send()"<<std::endl;
942                         client.Send(PEER_ID_SERVER, 0, data, true);
943
944                         sleep_ms(50);
945
946                         u16 peer_id;
947                         u8 recvdata[100];
948                         infostream<<"** running server.Receive()"<<std::endl;
949                         u32 size = server.Receive(peer_id, recvdata, 100);
950                         infostream<<"** Server received: peer_id="<<peer_id
951                                         <<", size="<<size
952                                         <<", data="<<*data
953                                         <<std::endl;
954                         assert(memcmp(*data, recvdata, data.getSize()) == 0);
955                 }
956 #endif
957                 u16 peer_id_client = 2;
958 #if 0
959                 /*
960                         Send consequent packets in different order
961                         Not compatible with new Connection, thus commented out.
962                 */
963                 {
964                         //u8 data1[] = "hello1";
965                         //u8 data2[] = "hello2";
966                         SharedBuffer<u8> data1 = SharedBufferFromString("hello1");
967                         SharedBuffer<u8> data2 = SharedBufferFromString("Hello2");
968
969                         Address client_address =
970                                         server.GetPeerAddress(peer_id_client);
971                         
972                         infostream<<"*** Sending packets in wrong order (2,1,2)"
973                                         <<std::endl;
974                         
975                         u8 chn = 0;
976                         con::Channel *ch = &server.getPeer(peer_id_client)->channels[chn];
977                         u16 sn = ch->next_outgoing_seqnum;
978                         ch->next_outgoing_seqnum = sn+1;
979                         server.Send(peer_id_client, chn, data2, true);
980                         ch->next_outgoing_seqnum = sn;
981                         server.Send(peer_id_client, chn, data1, true);
982                         ch->next_outgoing_seqnum = sn+1;
983                         server.Send(peer_id_client, chn, data2, true);
984
985                         sleep_ms(50);
986
987                         infostream<<"*** Receiving the packets"<<std::endl;
988
989                         u16 peer_id;
990                         u8 recvdata[20];
991                         u32 size;
992
993                         infostream<<"** running client.Receive()"<<std::endl;
994                         peer_id = 132;
995                         size = client.Receive(peer_id, recvdata, 20);
996                         infostream<<"** Client received: peer_id="<<peer_id
997                                         <<", size="<<size
998                                         <<", data="<<recvdata
999                                         <<std::endl;
1000                         assert(size == data1.getSize());
1001                         assert(memcmp(*data1, recvdata, data1.getSize()) == 0);
1002                         assert(peer_id == PEER_ID_SERVER);
1003                         
1004                         infostream<<"** running client.Receive()"<<std::endl;
1005                         peer_id = 132;
1006                         size = client.Receive(peer_id, recvdata, 20);
1007                         infostream<<"** Client received: peer_id="<<peer_id
1008                                         <<", size="<<size
1009                                         <<", data="<<recvdata
1010                                         <<std::endl;
1011                         assert(size == data2.getSize());
1012                         assert(memcmp(*data2, recvdata, data2.getSize()) == 0);
1013                         assert(peer_id == PEER_ID_SERVER);
1014                         
1015                         bool got_exception = false;
1016                         try
1017                         {
1018                                 infostream<<"** running client.Receive()"<<std::endl;
1019                                 peer_id = 132;
1020                                 size = client.Receive(peer_id, recvdata, 20);
1021                                 infostream<<"** Client received: peer_id="<<peer_id
1022                                                 <<", size="<<size
1023                                                 <<", data="<<recvdata
1024                                                 <<std::endl;
1025                         }
1026                         catch(con::NoIncomingDataException &e)
1027                         {
1028                                 infostream<<"** No incoming data for client"<<std::endl;
1029                                 got_exception = true;
1030                         }
1031                         assert(got_exception);
1032                 }
1033 #endif
1034 #if 0
1035                 /*
1036                         Send large amounts of packets (infinite test)
1037                         Commented out because of infinity.
1038                 */
1039                 {
1040                         infostream<<"Sending large amounts of packets (infinite test)"<<std::endl;
1041                         int sendcount = 0;
1042                         for(;;){
1043                                 int datasize = myrand_range(0,5)==0?myrand_range(100,10000):myrand_range(0,100);
1044                                 infostream<<"datasize="<<datasize<<std::endl;
1045                                 SharedBuffer<u8> data1(datasize);
1046                                 for(u16 i=0; i<datasize; i++)
1047                                         data1[i] = i/4;
1048                                 
1049                                 int sendtimes = myrand_range(1,10);
1050                                 for(int i=0; i<sendtimes; i++){
1051                                         server.Send(peer_id_client, 0, data1, true);
1052                                         sendcount++;
1053                                 }
1054                                 infostream<<"sendcount="<<sendcount<<std::endl;
1055                                 
1056                                 //int receivetimes = myrand_range(1,20);
1057                                 int receivetimes = 20;
1058                                 for(int i=0; i<receivetimes; i++){
1059                                         u8 recvdata[100000];
1060                                         u16 peer_id = 132;
1061                                         u16 size = 0;
1062                                         bool received = false;
1063                                         try{
1064                                                 size = client.Receive(peer_id, recvdata, 100000);
1065                                                 received = true;
1066                                         }catch(con::NoIncomingDataException &e){
1067                                         }
1068                                 }
1069                         }
1070                 }
1071 #endif
1072                 /*
1073                         Send a large packet
1074                 */
1075                 {
1076                         const int datasize = 30000;
1077                         SharedBuffer<u8> data1(datasize);
1078                         for(u16 i=0; i<datasize; i++){
1079                                 data1[i] = i/4;
1080                         }
1081
1082                         infostream<<"Sending data (size="<<datasize<<"):";
1083                         for(int i=0; i<datasize && i<20; i++){
1084                                 if(i%2==0) DEBUGPRINT(" ");
1085                                 DEBUGPRINT("%.2X", ((int)((const char*)*data1)[i])&0xff);
1086                         }
1087                         if(datasize>20)
1088                                 infostream<<"...";
1089                         infostream<<std::endl;
1090                         
1091                         server.Send(peer_id_client, 0, data1, true);
1092
1093                         sleep_ms(3000);
1094                         
1095                         u8 recvdata[datasize + 1000];
1096                         infostream<<"** running client.Receive()"<<std::endl;
1097                         u16 peer_id = 132;
1098                         u16 size = 0;
1099                         bool received = false;
1100                         u32 timems0 = porting::getTimeMs();
1101                         for(;;){
1102                                 if(porting::getTimeMs() - timems0 > 5000)
1103                                         break;
1104                                 try{
1105                                         size = client.Receive(peer_id, recvdata, datasize + 1000);
1106                                         received = true;
1107                                 }catch(con::NoIncomingDataException &e){
1108                                 }
1109                                 sleep_ms(10);
1110                         }
1111                         assert(received);
1112                         infostream<<"** Client received: peer_id="<<peer_id
1113                                         <<", size="<<size
1114                                         <<std::endl;
1115
1116                         infostream<<"Received data (size="<<size<<"):";
1117                         for(int i=0; i<size && i<20; i++){
1118                                 if(i%2==0) DEBUGPRINT(" ");
1119                                 DEBUGPRINT("%.2X", ((int)((const char*)recvdata)[i])&0xff);
1120                         }
1121                         if(size>20)
1122                                 infostream<<"...";
1123                         infostream<<std::endl;
1124
1125                         assert(memcmp(*data1, recvdata, data1.getSize()) == 0);
1126                         assert(peer_id == PEER_ID_SERVER);
1127                 }
1128                 
1129                 // Check peer handlers
1130                 assert(hand_client.count == 1);
1131                 assert(hand_client.last_id == 1);
1132                 assert(hand_server.count == 1);
1133                 assert(hand_server.last_id == 2);
1134                 
1135                 //assert(0);
1136         }
1137 };
1138
1139 #define TEST(X)\
1140 {\
1141         X x;\
1142         infostream<<"Running " #X <<std::endl;\
1143         x.Run();\
1144 }
1145
1146 void run_tests()
1147 {
1148         DSTACK(__FUNCTION_NAME);
1149         infostream<<"run_tests() started"<<std::endl;
1150         TEST(TestUtilities);
1151         TEST(TestSettings);
1152         TEST(TestCompress);
1153         TEST(TestMapNode);
1154         TEST(TestVoxelManipulator);
1155         //TEST(TestMapBlock);
1156         //TEST(TestMapSector);
1157         if(INTERNET_SIMULATOR == false){
1158                 TEST(TestSocket);
1159                 dout_con<<"=== BEGIN RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
1160                 TEST(TestConnection);
1161                 dout_con<<"=== END RUNNING UNIT TESTS FOR CONNECTION ==="<<std::endl;
1162         }
1163         infostream<<"run_tests() passed"<<std::endl;
1164 }
1165