-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOcean.cpp
More file actions
1794 lines (1478 loc) · 64.5 KB
/
Ocean.cpp
File metadata and controls
1794 lines (1478 loc) · 64.5 KB
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SimShip by Edouard Halbert
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License
http://creativecommons.org/licenses/by-nc-nd/4.0/ */
#include "Ocean.h"
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
#include <algorithm>
#include <numeric>
#include <random>
// For spectrum study
bool bStats = true;
static float Min = FLT_MAX;
static float Max = FLT_MIN;
static float Sum = 0.0f;
static int nSum = 0;
void MinMax(float length)
{
if (length < Min)
Min = length;
if (length > Max)
Max = length;
Sum += length;
nSum++;
}
void getKMinMax()
{
cout << "= V E C T O R K =============================" << endl;
cout << "Min = " << Min << endl;
cout << "Max = " << Max << endl;
cout << "Avg = " << Sum / nSum << endl;
cout << "n = " << nSum << endl;
}
extern GLuint TexContourShip; // Texture of the contour of the ship
extern int TexContourShipW, TexContourShipH; // Size of the contour of the ship
extern GLuint TexReflectionColor;
extern bool g_bShipWake;
extern GLuint TexWakeBuffer; // Buffer of wake
extern int TexWakeBufferSize;
extern GLuint TexWakeVao; // Texture of wake made by a projection of vao
extern int TexWakeVaoSize;
extern bool bTexWakeByVAO;
extern GLuint TexShadowMap;
extern mat4 LightViewProjection;
extern bool g_bShipShadow;
int SPECTRUM = 0;
struct InstanceData
{
mat4 modelMatrix;
float seed;
};
Ocean::Ocean(vec2 wind, Sky* sky)
{
mSky = sky;
GetWind(wind);
EvaluatePersistence(PersistenceSec);
Init();
}
Ocean::~Ocean()
{
if (mTexInitialSpectrum)
glDeleteTextures(1, &mTexInitialSpectrum);
if (mTexFrequencies)
glDeleteTextures(1, &mTexFrequencies);
if (mTexUpdatedSpectra[0] && mTexUpdatedSpectra[1])
glDeleteTextures(2, &mTexUpdatedSpectra[0]);
if (mTexTempData)
glDeleteTextures(1, &mTexTempData);
if (mTexDisplacements)
glDeleteTextures(1, &mTexDisplacements);
if (mTexGradients)
glDeleteTextures(1, &mTexGradients);
if (mTexFoamAcc1)
glDeleteTextures(1, &mTexFoamAcc1);
if (mTexFoamAcc2)
glDeleteTextures(1, &mTexFoamAcc2);
if (mTexFoamBuffer)
glDeleteTextures(1, &mTexFoamBuffer);
if (mTexFoamBuffer)
glDeleteTextures(1, &TexWakeBuffer);
if (mVbo)
glDeleteBuffers(1, &mVbo);
if (mVao)
glDeleteVertexArrays(1, &mVao);
if (mIbo)
glDeleteBuffers(1, &mIbo);
for (GLuint vao : mvVAOs)
if (vao)
glDeleteVertexArrays(1, &vao);
}
// Init
void Ocean::Init()
{
// Sort the ocean colors by their hue
//int color = 0;
//for (auto& c : vOceanColors)
//{
// float h, s, l;
// RGBtoHSL(c, h, s, l);
// cout << color++ << " : " << h << endl;
//}
GLint maxanisotropy = 5;
//glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxanisotropy);
maxanisotropy = std::max(maxanisotropy, 2);
// Generate initial spectrum and frequencies
glGenTextures(1, &mTexInitialSpectrum);
glGenTextures(1, &mTexFrequencies);
glBindTexture(GL_TEXTURE_2D, mTexInitialSpectrum);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RG32F, FFT_SIZE_1, FFT_SIZE_1);
glBindTexture(GL_TEXTURE_2D, mTexFrequencies);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, FFT_SIZE_1, FFT_SIZE_1);
// Fill in the 2 textures with data
InitFrequencies();
// Create other spectrum textures
glGenTextures(2, mTexUpdatedSpectra);
glBindTexture(GL_TEXTURE_2D, mTexUpdatedSpectra[0]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RG32F, FFT_SIZE, FFT_SIZE);
glBindTexture(GL_TEXTURE_2D, mTexUpdatedSpectra[1]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RG32F, FFT_SIZE, FFT_SIZE);
glGenTextures(1, &mTexTempData);
glBindTexture(GL_TEXTURE_2D, mTexTempData);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RG32F, FFT_SIZE, FFT_SIZE);
// Create displacement map
glGenTextures(1, &mTexDisplacements);
glBindTexture(GL_TEXTURE_2D, mTexDisplacements);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA32F, FFT_SIZE, FFT_SIZE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// For displacement pixels
mPixelsDisplacement = make_unique<float[]>(FFT_SIZE * FFT_SIZE * 4);
// Create gradient & folding map
glGenTextures(1, &mTexGradients);
glBindTexture(GL_TEXTURE_2D, mTexGradients);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA16F, FFT_SIZE, FFT_SIZE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Create accumulation buffer for the foam
glGenTextures(1, &mTexFoamAcc1);
glBindTexture(GL_TEXTURE_2D, mTexFoamAcc1);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, FFT_SIZE, FFT_SIZE);
glGenTextures(1, &mTexFoamAcc2);
glBindTexture(GL_TEXTURE_2D, mTexFoamAcc2);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, FFT_SIZE, FFT_SIZE);
// Create environment map
mTexEnvironment = make_unique<Texture>();
mTexEnvironment->CreateFromDDSFile("Resources/Ocean/ocean_env.dds");
maxanisotropy = 8;
// Create the texture of the foam
mTexFoamDesign = make_unique<Texture>();
mTexFoamDesign->CreateFromFile("Resources/Ocean/foam.png");
glBindTexture(GL_TEXTURE_2D, mTexFoamDesign->id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxanisotropy);
mTexFoamBubbles = make_unique<Texture>();
mTexFoamBubbles->CreateFromFile("Resources/Ocean/foam_bubbles.png");
glBindTexture(GL_TEXTURE_2D, mTexFoamBubbles->id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxanisotropy);
// Create the texture of the wake
mTexFoam = make_unique<Texture>();
mTexFoam->CreateFromFile("Resources/Ocean/seamless-seawater-with-foam-1.jpg");
glBindTexture(GL_TEXTURE_2D, mTexFoam->id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxanisotropy);
mTexWaterDuDv = make_unique<Texture>();
mTexWaterDuDv->CreateFromFile("Resources/Ocean/waterDUDV.png");
glBindTexture(GL_TEXTURE_2D, mTexWaterDuDv->id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxanisotropy);
mTexKelvinArray = InitTexture2DArray();
glBindTextureUnit(0, mTexKelvinArray);
glBindTexture(GL_TEXTURE_2D, 0);
CreateMesh();
CreateLODMeshes();
GetPatchVertices();
// Load shaders
auto highestSetBit = [](uint32_t x) -> uint32_t {
uint32_t ret = 0;
while (x >>= 1)
++ret;
return ret;
};
char defines[256];
uint32_t log2OfPow2 = highestSetBit(FFT_SIZE);
sprintf_s(defines, "#define FFT_SIZE %d\n#define GRID_SIZE %d\n#define LOG2_N_SIZE %d\n#define PATCH_SIZE_X2_N %.4f\n",
FFT_SIZE,
MESH_SIZE,
log2OfPow2,
(float)PATCH_SIZE * 2.0f / (float)FFT_SIZE);
mShaderSpectrum = make_unique<Shader>();
mShaderSpectrum->addDefines(defines);
mShaderSpectrum->Load("", "", "", "Resources/Ocean/updatespectrum.comp");
mShaderSpectrum->use();
mShaderSpectrum->setInt("tilde_h0", 0);
mShaderSpectrum->setInt("frequencies", 1);
mShaderSpectrum->setInt("tilde_h", 2);
mShaderSpectrum->setInt("tilde_D", 3);
mShaderFft = make_unique<Shader>();
mShaderFft->addDefines(defines);
mShaderFft->Load("", "", "", "Resources/Ocean/fourier_fft.comp");
mShaderFft->use();
mShaderFft->setInt("readbuff", 0);
mShaderFft->setInt("writebuff", 1);
mShaderDisplacements = make_unique<Shader>();
mShaderDisplacements->addDefines(defines);
mShaderDisplacements->Load("", "", "", "Resources/Ocean/createdisplacement.comp");
mShaderDisplacements->use();
mShaderDisplacements->setInt("heightmap", 0);
mShaderDisplacements->setInt("choppyfield", 1);
mShaderDisplacements->setInt("displacement", 2);
mShaderGradients = make_unique<Shader>();
mShaderGradients->addDefines(defines);
mShaderGradients->Load("", "", "", "Resources/Ocean/creategradients.comp");
mShaderGradients->use();
mShaderGradients->setInt("displacement", 0);
mShaderGradients->setInt("gradients", 1);
mShaderGradients->setInt("accfoam1", 2);
mShaderGradients->setInt("accfoam2", 3);
mShaderOcean = make_unique<Shader>();
mShaderOcean->addDefines(defines);
mShaderOcean->Load("Resources/Ocean/ocean.vert", "Resources/Ocean/ocean.frag");
mShaderOcean->use();
mShaderOcean->setInt("displacement", 0); // dx, dy, dz
mShaderOcean->setInt("envmap", 1); // cubemap texture
mShaderOcean->setInt("gradients", 2); // jacobians for the foam
mShaderOcean->setInt("foamBuffer", 3); // buffer accumulation of the foam which progressively disappear
mShaderOcean->setInt("foamTexture", 4); // texture of the foam
mShaderOcean->setInt("foamBubbles", 5); // texture to add bubbles
mShaderOcean->setInt("foamTexture", 6); // texture of the foam
mShaderOceanWake = make_unique<Shader>();
mShaderOceanWake->addDefines(defines);
mShaderOceanWake->Load("Resources/Ocean/ocean_wake.vert", "Resources/Ocean/ocean_wake.frag");
mShaderOceanWake->use();
mShaderOceanWake->setInt("displacement", 0); // dx, dy, dz
mShaderOceanWake->setInt("kelvinArray", 1);
mShaderOceanWake->setInt("envmap", 2); // cubemap texture
mShaderOceanWake->setInt("gradients", 3); // jacobians for the foam
mShaderOceanWake->setInt("foamBuffer", 4); // buffer accumulation of the foam which progressively disappear
mShaderOceanWake->setInt("foamDesign", 5); // texture of the foam
mShaderOceanWake->setInt("foamBubbles", 6); // texture to add bubbles
mShaderOceanWake->setInt("foamTexture", 7); // texture of the foam
mShaderOceanWake->setInt("contourShip", 8); // texture of foam around the ship
mShaderOceanWake->setInt("reflectionTexture", 9);// reflection texture
mShaderOceanWake->setInt("waterDUDV", 10); // texture to add vibrations of the water for the reflection
mShaderOceanWake->setInt("wakeBuffer", 11); // wake of the ship
mShaderOceanWake->setInt("shadowMap", 12); // shadow of the ship
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxanisotropy / 2);
OceanColor = color_255_to_1(vOceanColors[iOceanColor]);
}
void Ocean::InitFrequencies()
{
Lambda = EvaluateLambda(Wind);
mt19937 gen(static_cast<unsigned int>(std::time(0)));
normal_distribution<> gaussian(0.0, 1.0);
complex<float>* h0data = new complex<float>[(FFT_SIZE_1) * (FFT_SIZE_1)];
vec2 k;
float sqrt_S;
//vector<float> vS(FFT_SIZE_1 * FFT_SIZE_1);
float* wdata = new float[(FFT_SIZE_1) * (FFT_SIZE_1)];
{
for (int m = 0; m <= FFT_SIZE; ++m)
{
for (int n = 0; n <= FFT_SIZE; ++n)
{
// n & m are bound from -FFT_SIZE/2 to FFT_SIZE/2
k.x = 2.0 * M_PI * (n - FFT_SIZE / 2) / LengthWave;
k.y = 2.0 * M_PI * (m - FFT_SIZE / 2) / LengthWave;
switch (SPECTRUM)
{
case 0: sqrt_S = sqrtf(Phillips(k)); break;
case 1: sqrt_S = sqrtf(JONSWAP(k)); break;
case 2: sqrt_S = sqrtf(PiersonMoskowitz(k)); break;
case 3: sqrt_S = sqrtf(DonelanBanner(k)); break;
case 4: sqrt_S = sqrtf(Elfouhaily(k)); break;
case 5: sqrt_S = sqrtf(Elfouhaily2(k)); break;
case 6: sqrt_S = sqrtf(TexelMarsenArsloe(k)); break;
case 7: sqrt_S = sqrtf(TexelMarsenArsloe2(k)); break;
}
sqrt_S *= Amplitude;
//vS.push_back(sqrt_S);
int index = m * (FFT_SIZE_1) + n;
h0data[index].real(gaussian(gen) * sqrt_S);
h0data[index].imag(gaussian(gen) * sqrt_S);
// Dispersion relation \omega^2(k) = gk
wdata[index] = sqrtf(mGravity * glm::length(k));
}
}
}
//getKMinMax();
//GetSpectrumStats(vS);
glBindTexture(GL_TEXTURE_2D, mTexFrequencies);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, FFT_SIZE_1, FFT_SIZE_1, GL_RED, GL_FLOAT, wdata);
glBindTexture(GL_TEXTURE_2D, mTexInitialSpectrum);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, FFT_SIZE_1, FFT_SIZE_1, GL_RG, GL_FLOAT, h0data);
delete[] wdata;
delete[] h0data;
}
GLuint Ocean::InitTexture2DArray()
{
const int texCount = 100;
const int width = 1024;
const int height = 1024;
stbi_set_flip_vertically_on_load(true);
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D_ARRAY, textureID);
// Allouer espace pour la texture 2D array
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_R8, width, height, texCount);
for (int i = 0; i < texCount; i++)
{
string filename;
if (i < 9)
filename = "Resources/Kelvin/Kelvin-1024_Fr-00" + std::to_string(i + 1) + ".png";
else if (i < 99)
filename = "Resources/Kelvin/Kelvin-1024_Fr-0" + std::to_string(i + 1) + ".png";
else
filename = "Resources/Kelvin/Kelvin-1024_Fr-" + std::to_string(i + 1) + ".png";
int w, h, nrChannels;
unsigned char* data = stbi_load(filename.c_str(), &w, &h, &nrChannels, 1); // Charger en un canal (GL_RED)
if (!data) {
std::cerr << "Error loadind texture " << filename << std::endl;
continue;
}
if (w != width || h != height) {
std::cerr << "Incorrect size in " << filename << std::endl;
stbi_image_free(data);
continue;
}
// Copier les données dans la couche i de la 2D texture array
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, width, height, 1, GL_RED, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
// Paramètres de filtrage / wrapping
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
stbi_set_flip_vertically_on_load(false);
return textureID;
}
void Ocean::GetWind(vec2 wind)
{
Wind = wind;
Lambda = EvaluateLambda(Wind);
};
void Ocean::CreateMesh()
{
// Create mesh of PATCH_SIZE meters (MESH_SIZE cells x MESH_SIZE cells)
GridVertex* vdata = new GridVertex[MESH_SIZE_1 * MESH_SIZE_1];
for (int z = 0; z <= MESH_SIZE; ++z)
{
for (int x = 0; x <= MESH_SIZE; ++x)
{
int index = z * MESH_SIZE_1 + x;
vdata[index].position.x = (x - MESH_SIZE / 2.0f) * PATCH_SIZE / MESH_SIZE;
vdata[index].position.y = 0.0f;
vdata[index].position.z = (z - MESH_SIZE / 2.0f) * PATCH_SIZE / MESH_SIZE;
vdata[index].texCoord.x = (float)x / (float)MESH_SIZE;
vdata[index].texCoord.y = (float)z / (float)MESH_SIZE;
}
}
unsigned int* idata = new unsigned int[MESH_SIZE_1 * MESH_SIZE_1 * 6];
int index;
mIndicesCount = 0;
for (int z = 0; z < MESH_SIZE; ++z)
{
for (int x = 0; x < MESH_SIZE; ++x)
{
index = z * MESH_SIZE_1 + x;
// two triangles
idata[mIndicesCount++] = index;
idata[mIndicesCount++] = index + MESH_SIZE_1;
idata[mIndicesCount++] = index + MESH_SIZE_1 + 1;
idata[mIndicesCount++] = index;
idata[mIndicesCount++] = index + MESH_SIZE_1 + 1;
idata[mIndicesCount++] = index + 1;
}
}
// Générer et lier le mVAO
glGenVertexArrays(1, &mVao);
glBindVertexArray(mVao);
// Générer et lier le VBO
glGenBuffers(1, &mVbo);
glBindBuffer(GL_ARRAY_BUFFER, mVbo);
// Allouer l'espace pour le buffer, mais sans y mettre de données pour l'instant
glBufferData(GL_ARRAY_BUFFER, MESH_SIZE_1 * MESH_SIZE_1 * sizeof(GridVertex), vdata, GL_STATIC_DRAW);
// Activez les attributs
glEnableVertexAttribArray(0); // position
glEnableVertexAttribArray(1); // texCoord
// Configurez les pointeurs d'attributs
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GridVertex), 0); // position
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GridVertex), (void*)offsetof(GridVertex, texCoord)); // texCoord
// Générer et lier l'IBO
glGenBuffers(1, &mIbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mIndicesCount * sizeof(unsigned int), idata, GL_STATIC_DRAW);
glBindVertexArray(0);
}
void Ocean::CreateLODMesh(int meshSize, vector<GridVertex>& vertices, vector<unsigned int>& indices)
{
int meshSize1 = meshSize + 1;
vertices.resize(meshSize1 * meshSize1);
// Création des mvVertices
for (int z = 0; z <= meshSize; ++z)
{
for (int x = 0; x <= meshSize; ++x)
{
int index = z * meshSize1 + x;
vertices[index].position.x = (x - meshSize / 2.0f) * PATCH_SIZE / meshSize;
vertices[index].position.y = 0.0f;
vertices[index].position.z = (z - meshSize / 2.0f) * PATCH_SIZE / meshSize;
vertices[index].texCoord.x = (float)x / (float)meshSize;
vertices[index].texCoord.y = (float)z / (float)meshSize;
}
}
// Création des mvIndices
indices.clear();
for (int z = 0; z < meshSize; ++z)
{
for (int x = 0; x < meshSize; ++x)
{
int index = z * meshSize1 + x;
indices.push_back(index);
indices.push_back(index + meshSize1);
indices.push_back(index + meshSize1 + 1);
indices.push_back(index);
indices.push_back(index + meshSize1 + 1);
indices.push_back(index + 1);
}
}
}
void Ocean::CreateLODMeshes()
{
// Create multiple LOD patches
for (int meshSize : mvMeshSizes)
{
vector<GridVertex> vertices;
vector<unsigned int> indices;
CreateLODMesh(meshSize, vertices, indices);
GLuint vao, vbo, ibo;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GridVertex), vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0); // layout (location = 0) in vec3 aPosition;
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GridVertex), (void*)0);
glEnableVertexAttribArray(1); // layout (location = 1) in vec2 aTexCoords;
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GridVertex), (void*)offsetof(GridVertex, texCoord));
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), indices.data(), GL_STATIC_DRAW);
mvVAOs.push_back(vao);
mvIndicesCounts.push_back(indices.size());
glBindVertexArray(0);
// Libération des buffers (optionnel, car le mVAO les référence toujours)
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ibo);
}
}
void Ocean::GetPatchVertices()
{
// Positions
for (int z = 0; z <= MESH_SIZE; ++z)
{
vector<vec3> vPos;
for (int x = 0; x <= MESH_SIZE; ++x)
{
int index = z * MESH_SIZE_1 + x;
vec3 v;
v.x = (x - MESH_SIZE / 2.0f) * PATCH_SIZE / MESH_SIZE;
v.y = 0.0f;
v.z = (z - MESH_SIZE / 2.0f) * PATCH_SIZE / MESH_SIZE;
vPos.push_back(v);
}
mvPatchVertices.push_back(vPos);
}
}
float Ocean::EvaluateLambda(vec2 wind)
{
float lambdaLow = -0.6f;
float lambdaHigh = -0.9f;
// in Knots
float windLow = 12.0f;
float windHigh = 28.0f;
return glm::mix(lambdaLow, lambdaHigh, (glm::length(wind) * 1.852f - windLow) / (windHigh - windLow)); // [ -1f @ 12 kn, -2.f @ 60 kn ]
}
void Ocean::EvaluatePersistence(float seconds)
{
PersistenceSec = seconds;
PersistenceFactor = -std::log(0.01f) / PersistenceSec;
}
// Spectra
float Ocean::Phillips(vec2 k)
{
/*
* For FFT + 1 = 513 => there are 269169 calls to this function (513 x 513).
* Due to 2 possibilities to exit before the result, there are only 131854 calls which succeed.
* Wind force is divided by 2 (more realistic)
*/
float k_length = glm::length(k);
if (k_length < 0.000001f)
return 0.0f;
// k^2 & k^4
float k_length2 = k_length * k_length;
float k_length4 = k_length2 * k_length2;
float k_dot_w = glm::dot(glm::normalize(k), glm::normalize(Wind * 0.7f));
// If wave is moving against wind direction
if (k_dot_w < 0.0f)
return 0.0f;
// Directional distribution (added to Phillips spectrum)
k_dot_w = pow(cos(1.0f * acos(k_dot_w)), 3);
float k_dot_w2 = k_dot_w * k_dot_w; // The higher the exponent in (k_dot_w)exp will be set (2 in this case), the more the waves will be aligned with the wind direction
float L = glm::length2(Wind * 0.7f) / mGravity; // Largest possible wave for wind speed V. L = V^2 / g
float L2 = L * L;
// Suppress waves smaller than 1 / 1000
float damping = 0.0001f;
float l2 = L2 * damping * damping;
float S = exp(-1.0f / (k_length2 * L2)) / k_length4 * k_dot_w2 * exp(-k_length2 * l2);
return S * 0.0000375f; // Acceptable factor to have the Amplitude around 1.0f
}
float Ocean::JONSWAP(vec2 k)
{
// Le spectre JONSWAP est plus complexe et prend en compte plus de paramètres que le spectre de Phillips. Il produit généralement des vagues plus prononcées et plus réalistes, en particulier pour les mers en développement.
k *= 6.0f;
if (k.x == 0.0f && k.y == 0.0f)
return 0.0f;
float k_length = glm::length(k);
//MinMax(k_length);
float w_length = glm::length(Wind);
float fetch = 1000.0f; // Longueur du fetch en mètres (à ajuster selon vos besoins)
float g = mGravity;
// Paramètres JONSWAP
float alpha = 0.076f * pow(w_length * w_length / (fetch * g), -0.22f);
float omega_p = 22.0f * pow(g * g / (w_length * fetch), 1.0f / 3.0f); // Fréquence de pic
float gamma = 3.3f; // Facteur de pic (typiquement entre 1 et 7)
float sigma = (k_length <= omega_p) ? 0.07f : 0.09f;
// Calcul du spectre
float omega = sqrt(g * k_length);
float r = exp(-(omega - omega_p) * (omega - omega_p) / (2.0f * sigma * sigma * omega_p * omega_p));
float S_pm = (alpha * g * g / pow(omega, 5)) * exp(-1.25f * pow(omega_p / omega, 4));
float S_j = S_pm * pow(gamma, r);
// Directionnalité
float k_dot_w = glm::dot(glm::normalize(k), glm::normalize(Wind));
float D = pow(cos(0.5f * acos(k_dot_w)), 2); // Distribution directionnelle
float S = S_j * D / (k_length * k_length * k_length * k_length);
return S * 1.0f;
}
float Ocean::JONSWAP2(vec2 k)
{
float k_length = glm::length(k * 0.001f);
if (k_length < 0.000001f)
return 0.0f;
float omega = sqrt(mGravity * k_length);
float omega_p = 0.855f * mGravity / glm::length(Wind); // Fréquence de pic
float alpha = 0.0081f; // Constante de Phillips
float gamma = 3.3f; // Facteur de pic
float sigma = (omega <= omega_p) ? 0.07f : 0.09f;
float r = exp(-(omega - omega_p) * (omega - omega_p) / (2.0f * sigma * sigma * omega_p * omega_p));
float S = (alpha * mGravity * mGravity / (omega * omega * omega * omega * omega)) * exp(-1.25f * pow(omega_p / omega, 4)) * pow(gamma, r);
// Distribution directionnelle
float theta = atan2(k.y, k.x);
float cos_theta = cos(theta - atan2(Wind.y, Wind.x));
float D = pow(cos_theta, 2); // Distribution cosinus carré
return S * D * 0.0375f * Amplitude; // Facteur d'échelle pour ajuster l'amplitude
}
float Ocean::PiersonMoskowitz(vec2 k)
{
// Ce spectre est souvent utilisé pour modéliser des mers complètement développées. Il est plus simple que le spectre JONSWAP et ne prend pas en compte le fetch limité.
k *= 5.5f;
if (k.x == 0.0f && k.y == 0.0f)
return 0.0f;
float k_length = glm::length(k);
float g = mGravity;
float w_length = glm::length(Wind);
// Paramètres du spectre Pierson-Moskowitz
float alpha = 0.0081f; // Constante de Phillips qui contrôle l'amplitude globale du spectre.
float omega_p = g / w_length; // Fréquence de pic
// Calcul du spectre
float omega = sqrt(g * k_length);
float S_pm = (alpha * g * g / pow(omega, 5)) * exp(-5.0f / 4.0f * pow(omega_p / omega, 4));
// Directionnalité
float k_dot_w = glm::dot(glm::normalize(k), glm::normalize(Wind));
float D = pow(cos(0.5f * acos(k_dot_w)), 2); // Distribution directionnelle
float S = S_pm * D / (k_length * k_length * k_length * k_length);
return S * 1.0f;
}
float Ocean::DonelanBanner(vec2 k)
{
// Ce spectre est une amélioration du spectre JONSWAP, particulièrement adapté pour les vents forts et les vagues courtes.
k *= 3.0f;
if (k.x == 0.0f && k.y == 0.0f)
return 0.0f;
float k_length = glm::length(k);
float g = mGravity;
float w_length = glm::length(Wind);
// Paramètres du spectre Donelan-Banner
float alpha = 0.006f * sqrt(w_length / g);
float omega_p = 0.877f * g / w_length;
float gamma = 1.7f;
float sigma = 0.08f * (1.0f + 4.0f / pow(omega_p * w_length / g, 3));
// Calcul du spectre
float omega = sqrt(g * k_length);
float r = exp(-pow(omega - omega_p, 2) / (2.0f * sigma * sigma * omega_p * omega_p));
float S_db = alpha * g * g / pow(omega, 4) * exp(-pow(omega_p / omega, 4)) * pow(gamma, r);
// Directionnalité
float k_dot_w = glm::dot(glm::normalize(k), glm::normalize(Wind));
float theta = acos(k_dot_w);
float beta = 2.61f * pow(omega / omega_p, 0.65f);
float sech = 1.0f / cosh(beta * theta);
float D = pow(sech, 2);
float S = S_db * D / (k_length * k_length * k_length * k_length);
return S * 0.1f;
}
float Ocean::Elfouhaily(vec2 k)
{
const float KM = 370.0;
const float CM = 0.23;
vec2 wave_vector = k;
wave_vector *= 80.f;
float k_length = length(wave_vector);
float U10 = length(Wind);
float Omega = 0.84f;
float kp = mGravity * (Omega / U10) * (Omega / U10);
float c = sqrt(mGravity * k_length * (1.f + ((k_length * k_length) / (KM * KM)))) / k_length;
float cp = sqrt(mGravity * kp * (1.f + ((kp * kp) / (KM * KM)))) / kp;
float Lpm = exp(-1.25 * (kp / k_length) * (kp / k_length));
float gamma = 1.7;
float sigma = 0.08 * (1.0 + 4.0 * pow(Omega, -3.0));
float Gamma = exp(-(sqrt(k_length / kp) - 1.0) * (sqrtf(k_length / kp) - 1.0) / 2.0 * (sigma * sigma));
float Jp = pow(gamma, Gamma);
float Fp = Lpm * Jp * exp(-Omega / sqrt(10.0) * (sqrt(k_length / kp) - 1.0));
float alphap = 0.006 * sqrt(Omega);
float Bl = 0.5 * alphap * cp / c * Fp;
float z0 = 0.000037 * U10 * U10 / mGravity * pow(U10 / cp, 0.9);
float uStar = 0.41 * U10 / log(10.0 / z0);
float alpham = 0.01 * ((uStar < CM) ? (1.0 + log(uStar / CM)) : (1.0 + 3.0 * log(uStar / CM)));
float Fm = exp(-0.25 * (k_length / KM - 1.0) * (k_length / KM - 1.0));
float Bh = 0.5 * alpham * CM / c * Fm * Lpm;
float a0 = log(2.0) / 4.0;
float am = 0.13 * uStar / CM;
float Delta = tanh(a0 + 4.0 * pow(c / cp, 2.5) + am * pow(CM / c, 2.5));
float cosPhi = glm::dot(glm::normalize(Wind), glm::normalize(wave_vector));
float S = (1.0 / (2.0 * M_PI)) * pow(k_length, -4.0) * (Bl + Bh) * (1.0 + Delta * (2.0 * cosPhi * cosPhi - 1.0));
float dk = 2.0 * M_PI / MESH_SIZE;
float h = sqrt(S / 2.0) * dk;
if (wave_vector.x == 0.0 && wave_vector.y == 0.0) h = 0.f;
return h;
}
float Ocean::Elfouhaily2(vec2 k)
{
float Hs = 2.0f;
float U10 = glm::length(Wind);
float fetch = 100.0f;
float g = 9.81f; // Accélération due à la gravité
float kp = (g / U10) * std::pow(fetch, -0.33f); // Nombre d'onde pic
float alpha = 0.0074f; // Coefficient de Phillips
float k_length = glm::length(k);
if (k_length == 0.0f)
return 0.0f;
// Spectre d'Elfouhaily
float S = alpha * Hs * Hs * std::pow(kp, 2) * std::pow(k_length, -3) * std::exp(-5.0f / 4.0f * std::pow(k_length / kp, -2)) * std::exp(-0.5f * std::pow(k_length / kp - 1, 2));
return S * 0.01f;
}
float Ocean::TexelMarsenArsloe(vec2 k)
{
// Ce spectre de Texel-MARSEN-ARSLOE (TMA) est une modification du spectre JONSWAP pour les eaux peu profondes
k *= 6.f;
float windSpeed = glm::length(Wind); // Vitesse du vent en m/s
float fetchLength = 100000.0f; // 100 km
float peakFrequency = 0.1f; // 0.1 Hz
float depth = 10.0f;
if (k.x == 0.0f && k.y == 0.0f)
return 0.0f;
float k_length = glm::length(k);
float g = mGravity;
float omega = sqrt(g * k_length * tanh(k_length * depth));
float omega_p = 2.0f * M_PI * peakFrequency;
// Paramètres JONSWAP
float alpha = 0.076f * pow(windSpeed * windSpeed / (fetchLength * g), 0.22f);
float gamma = 3.3f;
float sigma = (omega <= omega_p) ? 0.07f : 0.09f;
// Calcul du spectre JONSWAP
float r = exp(-pow(omega - omega_p, 2) / (2 * sigma * sigma * omega_p * omega_p));
float S_j = alpha * g * g / pow(omega, 5) * exp(-5.0f / 4.0f * pow(omega_p / omega, 4)) * pow(gamma, r);
// Facteur de profondeur limitée
float k_h = k_length * depth;
float phi = 0.5f + 0.5f * tanh(2.0f * k_h);
// Directionnalité
float k_dot_w = glm::dot(glm::normalize(k), glm::normalize(Wind));
float D = pow(cos(0.5f * acos(k_dot_w)), 2);
float S = S_j * phi * D / (k_length * k_length * k_length * k_length);
return S * 1.0f;
}
float Ocean::TexelMarsenArsloe2(vec2 k)
{
float omega = glm::length(k);
if (omega == 0.0f)
return 0.0f;
float Hs = 2.0f; // Hauteur significative
float Tp = 10.0f; // Période de pic
float g = 9.81f; // Accélération due à la gravité
float omega_p = 2 * M_PI / Tp; // Fréquence de pic
float alpha = 0.0081f; // Coefficient empirique
// Spectre de Texel Marsen Arsloe
float S = (alpha * Hs * Hs) / std::pow(omega, 5) * std::exp(-1.25f * std::pow(omega_p / omega, 4)) * std::exp(-0.5f * std::pow((omega - omega_p) / (0.07f * omega_p), 2));
return S * 0.01f;
}
// Update
void Ocean::Update(float t)
{
// Update spectra
mShaderSpectrum->use(); // Ocean/updatespectrum.comp
mShaderSpectrum->setFloat("time", t); // t * 0.6 might be a adhoc parameter to slow down the speed of the waves
glBindImageTexture(0, mTexInitialSpectrum, 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32F); // tilde_h0
glBindImageTexture(1, mTexFrequencies, 0, GL_TRUE, 0, GL_READ_ONLY, GL_R32F); // frequencies
glBindImageTexture(2, mTexUpdatedSpectra[0], 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_RG32F); // tilde_h
glBindImageTexture(3, mTexUpdatedSpectra[1], 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_RG32F); // tilde_D
glDispatchCompute(FFT_SIZE / 16, FFT_SIZE / 16, 1);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
// Transform spectra to spatial/time domain
FourierTransform(mTexUpdatedSpectra[0]); // readbuff
FourierTransform(mTexUpdatedSpectra[1]); // writebuff
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
// Calculate displacement map
mShaderDisplacements->use(); // Ocean/createdisplacement.comp
glBindImageTexture(0, mTexUpdatedSpectra[0], 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32F); // heightmap
glBindImageTexture(1, mTexUpdatedSpectra[1], 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32F); // choppyfield
glBindImageTexture(2, mTexDisplacements, 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_RGBA32F); // displacement
mShaderDisplacements->setFloat("lambda", Lambda);
glDispatchCompute(FFT_SIZE / 16, FFT_SIZE / 16, 1);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
// Calculate normal & folding map
swap(mTexFoamAcc1, mTexFoamAcc2);
mTexFoamBuffer = mTexFoamAcc1;
mShaderGradients->use(); // Ocean/creategradients.comp
glBindImageTexture(0, mTexDisplacements, 0, GL_TRUE, 0, GL_READ_ONLY, GL_RGBA32F); // displacements
glBindImageTexture(1, mTexGradients, 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_RGBA16F); // gradients
glBindImageTexture(2, mTexFoamAcc1, 0, GL_TRUE, 0, GL_READ_ONLY, GL_R32F); // accumulation of foam (alternate read/write)
glBindImageTexture(3, mTexFoamAcc2, 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_R32F); // accumulation of foam (alternate read/write)
static float tOld = t;
mShaderGradients->setFloat("t", t - tOld);
mShaderGradients->setFloat("persistenceFactor", PersistenceFactor);
tOld = t;
glDispatchCompute(FFT_SIZE / 16, FFT_SIZE / 16, 1);
glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT | GL_TEXTURE_FETCH_BARRIER_BIT);
// Get data of displacement (x, y, z)
glBindTexture(GL_TEXTURE_2D, mTexDisplacements);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, mPixelsDisplacement.get());
glBindTexture(GL_TEXTURE_2D, 0);
}
void Ocean::FourierTransform(GLuint spectrum)
{
// horizontal pass
glBindImageTexture(0, spectrum, 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32F);
glBindImageTexture(1, mTexTempData, 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_RG32F);
mShaderFft->use();
glDispatchCompute(FFT_SIZE, 1, 1);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
// vertical pass
glBindImageTexture(0, mTexTempData, 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32F);
glBindImageTexture(1, spectrum, 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_RG32F);
mShaderFft->use();
glDispatchCompute(FFT_SIZE, 1, 1);
}
bool Ocean::GetVerticeXZ(vec2 pos, vec3& output)
{
int x = (static_cast<int>(pos.x * MESH_SIZE / PATCH_SIZE) + MESH_SIZE / 2) % MESH_SIZE;
if (x < 0) x += MESH_SIZE;
int z = (static_cast<int>(pos.y * MESH_SIZE / PATCH_SIZE) + MESH_SIZE / 2) % MESH_SIZE;
if (z < 0) z += MESH_SIZE;
int xFft = (x - MESH_SIZE / 2) * FFT_SIZE / MESH_SIZE + FFT_SIZE / 2;
int yFft = (z - MESH_SIZE / 2) * FFT_SIZE / MESH_SIZE + FFT_SIZE / 2;
int index = 4 * (yFft * FFT_SIZE + xFft);
// Outside the map
if (index < 0 || index >= FFT_SIZE * FFT_SIZE * 4)
return false;
output = { pos.x + mPixelsDisplacement[index + 0], mPixelsDisplacement[index + 1] , pos.y + mPixelsDisplacement[index + 2] };
return true;
}
bool Ocean::GetVerticeXYZ(vec3 pos, vec3& output)
{
int x = (static_cast<int>(pos.x * MESH_SIZE / PATCH_SIZE) + MESH_SIZE / 2) % MESH_SIZE;
if (x < 0) x += MESH_SIZE;
int z = (static_cast<int>(pos.z * MESH_SIZE / PATCH_SIZE) + MESH_SIZE / 2) % MESH_SIZE;
if (z < 0) z += MESH_SIZE;
int xFft = (x - MESH_SIZE / 2) * FFT_SIZE / MESH_SIZE + FFT_SIZE / 2;
int yFft = (z - MESH_SIZE / 2) * FFT_SIZE / MESH_SIZE + FFT_SIZE / 2;
int index = 4 * (yFft * FFT_SIZE + xFft);
// Outside the map
if (index < 0 || index >= FFT_SIZE * FFT_SIZE * 4)
return false;
output = { pos.x + mPixelsDisplacement[index + 0], mPixelsDisplacement[index + 1] , pos.z + mPixelsDisplacement[index + 2] };
return true;
}
// Analysis
void Ocean::GetAllJacobians()
{
glBindTexture(GL_TEXTURE_2D, mTexGradients);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, mPixelsDisplacement.get());
float Max = FLT_MIN;
float Min = FLT_MAX;
float J;
for (int i = 0; i < FFT_SIZE * FFT_SIZE; i += 4)
{
J = mPixelsDisplacement[i + 3];
if (J < Min)
Min = J;
if (J > Max)