aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/world/TerrainDecoder.cs
blob: 0f1b733784f245c19285b5e1c5d7ad95a9d1d5ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
/*
* Copyright (c) OpenSim project, http://sim.opensecondlife.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in the
*       documentation and/or other materials provided with the distribution.
*     * Neither the name of the <organization> nor the
*       names of its contributors may be used to endorse or promote products
*       derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY <copyright holder> ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* 
*/

using System;
using System.Collections.Generic;
//using libsecondlife;
using libsecondlife.Packets;

namespace OpenSim
{
	/// <summary>
	/// Description of TerrainDecoder.
	/// </summary>
	public class TerrainDecode
	{
		
        public enum LayerType : byte
        {
            Land = 0x4C,
            Water = 0x57,
            Wind = 0x37,
            Cloud = 0x38
        }

        public struct GroupHeader
        {
            public int Stride;
            public int PatchSize;
            public LayerType Type;
        }

        public struct PatchHeader
        {
            public float DCOffset;
            public int Range;
            public int QuantWBits;
            public int PatchIDs;
            public uint WordBits;
        }

        public class Patch
        {
            public float[] Heightmap;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="simulator"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="data"></param>
       // public delegate void LandPatchCallback(Simulator simulator, int x, int y, int width, float[] data);


        /// <summary>
        /// 
        /// </summary>
        //public event LandPatchCallback OnLandPatch;

		private Random RandomClass = new Random();
		
        private const byte END_OF_PATCHES = 97;
        private const int PATCHES_PER_EDGE = 16;
        private const float OO_SQRT2 = 0.7071067811865475244008443621049f;

        //private SecondLife Client;
        private Dictionary<ulong, Patch[]> SimPatches = new Dictionary<ulong, Patch[]>();
        private float[] DequantizeTable16 = new float[16 * 16];
        private float[] DequantizeTable32 = new float[32 * 32];
        private float[] ICosineTable16 = new float[16 * 16];
        private float[] ICosineTable32 = new float[32 * 32];
        private int[] DeCopyMatrix16 = new int[16 * 16];
        private int[] DeCopyMatrix32 = new int[32 * 32];


        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        public TerrainDecode()
        {
         
            // Initialize the decompression tables
            BuildDequantizeTable16();
            BuildDequantizeTable32();
            SetupICosines16();
            SetupICosines32();
            BuildDecopyMatrix16();
            BuildDecopyMatrix32();

       }

        
        private void BuildDequantizeTable16()
        {
            for (int j = 0; j < 16; j++)
            {
                for (int i = 0; i < 16; i++)
                {
                    DequantizeTable16[j * 16 + i] = 1.0f + 2.0f * (float)(i + j);
                }
            }
        }

        private void BuildDequantizeTable32()
        {
            for (int j = 0; j < 32; j++)
            {
                for (int i = 0; i < 32; i++)
                {
                    DequantizeTable32[j * 32 + i] = 1.0f + 2.0f * (float)(i + j);
                }
            }
        }

        private void SetupICosines16()
        {
            const float hposz = (float)Math.PI * 0.5f / 16.0f;

            for (int u = 0; u < 16; u++)
            {
                for (int n = 0; n < 16; n++)
                {
                    ICosineTable16[u * 16 + n] = (float)Math.Cos((2.0f * (float)n + 1.0f) * (float)u * hposz);
                }
            }
        }

        private void SetupICosines32()
        {
            const float hposz = (float)Math.PI * 0.5f / 32.0f;

            for (int u = 0; u < 32; u++)
            {
                for (int n = 0; n < 32; n++)
                {
                    ICosineTable32[u * 32 + n] = (float)Math.Cos((2.0f * (float)n + 1.0f) * (float)u * hposz);
                }
            }
        }

        private void BuildDecopyMatrix16()
        {
            bool diag = false;
            bool right = true;
            int i = 0;
            int j = 0;
            int count = 0;

            while (i < 16 && j < 16)
            {
                DeCopyMatrix16[j * 16 + i] = count++;

                if (!diag)
                {
                    if (right)
                    {
                        if (i < 16 - 1) i++;
                        else j++;

                        right = false;
                        diag = true;
                    }
                    else
                    {
                        if (j < 16 - 1) j++;
                        else i++;

                        right = true;
                        diag = true;
                    }
                }
                else
                {
                    if (right)
                    {
                        i++;
                        j--;
                        if (i == 16 - 1 || j == 0) diag = false;
                    }
                    else
                    {
                        i--;
                        j++;
                        if (j == 16 - 1 || i == 0) diag = false;
                    }
                }
            }
        }

        private void BuildDecopyMatrix32()
        {
            bool diag = false;
            bool right = true;
            int i = 0;
            int j = 0;
            int count = 0;

            while (i < 32 && j < 32)
            {
                DeCopyMatrix32[j * 32 + i] = count++;

                if (!diag)
                {
                    if (right)
                    {
                        if (i < 32 - 1) i++;
                        else j++;

                        right = false;
                        diag = true;
                    }
                    else
                    {
                        if (j < 32 - 1) j++;
                        else i++;

                        right = true;
                        diag = true;
                    }
                }
                else
                {
                    if (right)
                    {
                        i++;
                        j--;
                        if (i == 32 - 1 || j == 0) diag = false;
                    }
                    else
                    {
                        i--;
                        j++;
                        if (j == 32 - 1 || i == 0) diag = false;
                    }
                }
            }
        }
        
        private void EncodePatchHeader(BitPacker bitpack, PatchHeader header)
        {
        	bitpack.PackBits(header.QuantWBits,8);
        	
        	if (header.QuantWBits == END_OF_PATCHES)
                return;
        	
        	bitpack.PackFloat(header.DCOffset);
        	bitpack.PackBits(header.Range,16);
        	bitpack.PackBits(header.PatchIDs,10);
        	
        }
		
        public  void DCTLine16(float[] In, float[] Out, int line)
        {
        	int N =16;
			int lineSize = line * 16;
        
        	for(int k = 0; k < N;k++)
        	{
        		float sum = 0.0f;
        		for(int n = 0; n < N; n++)
        		{
        			float num = (float)(Math.PI*k*(2.0f*n+1)/(2*N));
        			float cosine = (float)Math.Cos(num);
        			float product = In[lineSize +n] * cosine;
        			sum += product;
        		}

        		float alpha;
        		if(k == 0)
        		{
        			alpha = (float)(1.0f/Math.Sqrt(2));
        		}
        		else
        		{
        			alpha = 1;
        		}
        		Out[lineSize + k] =(float)( sum * alpha );
        		
        	}
        }
        public  void DCTColumn16(float[] In, float[] Out, int Column)
        {
        	int N =16;
        	int uSize;
        	
        	for(int k = 0; k < N; k++){
        		float sum = 0.0f;
        		for(int n = 0; n < N; n++)
        		{
        			uSize = n * 16;
        			float num = (float)(Math.PI*k*(2.0f*n+1)/(2*N));
        			float cosine = (float)Math.Cos(num);
        			float product = In[uSize + Column] * cosine;
        			sum += product;
        		}

        		float alpha;
        		if(k == 0)
        		{
        			alpha = (float)(1.0f/Math.Sqrt(2));
        		}
        		else
        		{
        			alpha = 1;
        		}
        		Out[16 * k  + Column] = (float)( sum * alpha * (2.0f /N));
        		
        	}
        }
        
        private void EncodePatch(int[] patches, BitPacker bitpack, int size)
        {
        	int lastnum =0; 
        	for(int n = 0; n < size * size; n++)
        	{
        		if(patches[n]!=0)
        		   lastnum=n;
        	}	 
        	for (int n = 0; n < lastnum+1; n++)
            {
        		if(patches[n] != 0)
        		{
        			bitpack.PackBits(1,1); //value or EOB
        			bitpack.PackBits(1,1); //value
        			if(patches[n] > 0)
        			{
        				
        				bitpack.PackBits(0,1); // positive
        				bitpack.PackBits(patches[n],13);
        				
        			}
        			else
        			{
        				bitpack.PackBits(1,1); // negative
        				
        				int temp = patches[n] * -1;
        				bitpack.PackBits(temp,13);
        				
        			}
        		}
        		else
        		{
        			bitpack.PackBits(0,1); // no value
        		}
        	}
        	
        	bitpack.PackBits(1,1); //value or EOB
        	bitpack.PackBits(0,1); // EOB
        }
      
		public int[] CompressPatch(float[] patches)
        {
			int size = 16;
            float[] block = new float[size * size];
            int[] output = new int[size * size];
            int prequant = (139 >> 4) + 2;
            int quantize = 1 << prequant;
            float ooq = 1.0f / (float)quantize;
            float mult = ooq * (float)1;
            float addval = mult * (float)(1 << (prequant - 1)) + 20.4989f;
			
            if (size == 16) 
            {
                for (int n = 0; n < 16 * 16; n++)
                {
                	block[n] = (float)((patches[n] - addval)/ mult);
                }

                float[] ftemp = new float[32 * 32];

                for (int o = 0; o < 16; o++)
                    this.DCTColumn16(block, ftemp, o);
                for (int o = 0; o < 16; o++)
                    this.DCTLine16(ftemp, block, o);
            }
          
            for (int j = 0; j < block.Length; j++)
            {
                output[DeCopyMatrix16[j]] = (int)(block[j] / DequantizeTable16[j]);
            }
			
         	return output;
        }

		public Packet CreateLayerPacket(float[] heightmap, int minX, int maxX, int minY, int maxY)
        {
        	//int minX = 0, maxX = 2, minY = 0, maxY = 1; //these should be passed to this function
        	LayerDataPacket layer = new LayerDataPacket();
        	byte[] Encoded = new byte[2048];
        	layer.LayerID.Type = 76;
        	GroupHeader header = new GroupHeader();
        	header.Stride = 264;
        	header.PatchSize = 16;
        	header.Type = LayerType.Land;
        	BitPacker newpack = new BitPacker(Encoded,0);
        	newpack.PackBits(header.Stride,16);
        	newpack.PackBits(header.PatchSize,8);
        	newpack.PackBits((int)header.Type,8);
        	
        	
        	float[] height;
        	for(int y = minY; y< maxY; y++)
        	{
        		for(int x = minX ; x < maxX ; x++)
        		{
        			height = new float[256];
        			Array.Copy(heightmap, (4096 *y) +(x *256), height, 0, 256);
        			
        			this.CreatePatch(height, newpack, x, y);
        		}
        	}
        	
        	PatchHeader headers = new PatchHeader();
        	headers.QuantWBits = END_OF_PATCHES;
        	this.EncodePatchHeader(newpack, headers);
        	
        	int lastused=0;
        	for(int i = 0; i < 1024 ; i++)
        	{
        		if(Encoded[i] !=0)
        			lastused = i;
        	}
        	
        	byte[] data = new byte[lastused+1];
        	Array.Copy(Encoded, data, lastused+1);
        	layer.LayerData.Data =data;
        	
        	return(layer);
        }
        public void CreatePatch(float[] heightmap, BitPacker newpack, int x, int y)
        {
        	PatchHeader header = new PatchHeader();
        	header.DCOffset = 20.4989f;
        	header.QuantWBits = 139;
        	header.Range = 1;
        	header.PatchIDs = (y & 0x1F);
        	header.PatchIDs += x <<5 ;
        	
        	this.EncodePatchHeader(newpack, header);
        	
        	int[] newpatch = this.CompressPatch(heightmap);
            this.EncodePatch(newpatch, newpack, 16);
        	
        }
    }
	
	//***************************************************
	public class BitPacker
    {
        private const int MAX_BITS = 8;

        private byte[] Data;
        public int bytePos;
        public int bitPos;

        /// <summary>
        /// Default constructor, initialize the bit packer / bit unpacker
        /// with a byte array and starting position
        /// </summary>
        /// <param name="data">Byte array to pack bits in to or unpack from</param>
        /// <param name="pos">Starting position in the byte array</param>
        public BitPacker(byte[] data, int pos)
        {
            Data = data;
            bytePos = pos;
        }

        /// <summary>
        /// Pack a floating point value in to the data
        /// </summary>
        /// <param name="data">Floating point value to pack</param>
        public void PackFloat(float data)
        {
            byte[] input = BitConverter.GetBytes(data);
            PackBitArray(input, 32);
        }

        /// <summary>
        /// Pack part or all of an integer in to the data
        /// </summary>
        /// <param name="data">Integer containing the data to pack</param>
        /// <param name="totalCount">Number of bits of the integer to pack</param>
        public void PackBits(int data, int totalCount)
        {
            byte[] input = BitConverter.GetBytes(data);
            PackBitArray(input, totalCount);
        }

        /// <summary>
        /// Unpacking a floating point value from the data
        /// </summary>
        /// <returns>Unpacked floating point value</returns>
        public float UnpackFloat()
        {
            byte[] output = UnpackBitsArray(32);

            if (!BitConverter.IsLittleEndian) Array.Reverse(output);
            return BitConverter.ToSingle(output, 0);
        }

        /// <summary>
        /// Unpack a variable number of bits from the data in to integer format
        /// </summary>
        /// <param name="totalCount">Number of bits to unpack</param>
        /// <returns>An integer containing the unpacked bits</returns>
        /// <remarks>This function is only useful up to 32 bits</remarks>
        public int UnpackBits(int totalCount)
        {
            byte[] output = UnpackBitsArray(totalCount);

            if (!BitConverter.IsLittleEndian) Array.Reverse(output);
            return BitConverter.ToInt32(output, 0);
        }

        private void PackBitArray(byte[] data, int totalCount)
        {
            int count = 0;
            int curBytePos = 0;
            int curBitPos = 0;
			
            while (totalCount > 0)
            {
            	if (totalCount > (MAX_BITS ))
                {
                    count = MAX_BITS ;
                    totalCount -= MAX_BITS ;
                }
                else
                {
                    count = totalCount;
                    totalCount = 0;
                }

                while (count > 0)
                {
                    switch(count)
                    {
                    	case 1:
                    		 if ((data[curBytePos] & (0x01)) != 0)
                    		 {
                    		 	 Data[bytePos] |= (byte)(0x80 >> bitPos);
                    		 }
                    		 break;
                    	case 2:
                    		 if ((data[curBytePos] & (0x02)) != 0)
                    		 {
                    		 	 Data[bytePos] |= (byte)(0x80 >> bitPos);
                    		 }
                    		 break;
                    	case 3:
                    		 if ((data[curBytePos] & (0x04)) != 0)
                    		 {
                    		 	 Data[bytePos] |= (byte)(0x80 >> bitPos);
                    		 }
                    		 break;
                    	case 4:
                    		 if ((data[curBytePos] & (0x08)) != 0)
                    		 {
                    		 	 Data[bytePos] |= (byte)(0x80 >> bitPos);
                    		 }
                    		 break;
                    	case 5:
                    		 if ((data[curBytePos] & (0x10)) != 0)
                    		 {
                    		 	 Data[bytePos] |= (byte)(0x80 >> bitPos);
                    		 }
                    		 break;
                    	case 6:
                    		 if ((data[curBytePos] & (0x20)) != 0)
                    		 {
                    		 	 Data[bytePos] |= (byte)(0x80 >> bitPos);
                    		 }
                    		 break;
                    	case 7:
                    		 if ((data[curBytePos] & (0x40)) != 0)
                    		 {
                    		 	 Data[bytePos] |= (byte)(0x80 >> bitPos);
                    		 }
                    		 break;
                    	case 8:
                    		 if ((data[curBytePos] & (0x80)) != 0)
                    		 {
                    		 	 Data[bytePos] |= (byte)(0x80 >> bitPos);
                    		 }
                    		 break;
                    }
                   
                    bitPos++;
                    --count;
                    ++curBitPos;

                    if (bitPos >= MAX_BITS)
                    {
                        bitPos = 0;
                        ++bytePos;
                    }
                    if (curBitPos >= MAX_BITS)
                    {
                        curBitPos = 0;
                        ++curBytePos;
                    }
                }
            }
        }
       

        private byte[] UnpackBitsArray(int totalCount)
        {
            int count = 0;
            byte[] output = new byte[4];
            int curBytePos = 0;
            int curBitPos = 0;

            while (totalCount > 0)
            {
                if (totalCount > MAX_BITS)
                {
                    count = MAX_BITS;
                    totalCount -= MAX_BITS;
                }
                else
                {
                    count = totalCount;
                    totalCount = 0;
                }

                while (count > 0)
                {
                    // Shift the previous bits
                    output[curBytePos] <<= 1;

                    // Grab one bit
                    if ((Data[bytePos] & (0x80 >> bitPos++)) != 0)
                        ++output[curBytePos];

                    --count;
                    ++curBitPos;

                    if (bitPos >= MAX_BITS)
                    {
                        bitPos = 0;
                        ++bytePos;
                    }
                    if (curBitPos >= MAX_BITS)
                    {
                        curBitPos = 0;
                        ++curBytePos;
                    }
                }
            }

            return output;
        }
    }
}