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