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