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