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