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