-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathShip.cpp
More file actions
4196 lines (3534 loc) · 163 KB
/
Ship.cpp
File metadata and controls
4196 lines (3534 loc) · 163 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 "Ship.h"
#include "clipper/clipper.h" // Used to get front and lateral areas by clipping everything below the waterline
#ifdef _DEBUG
#pragma comment(lib, "clipper/Debug/clipper.lib")
#else
#pragma comment(lib, "clipper/Release/clipper.lib")
#endif
using namespace Clipper2Lib;
extern uint32_t g_FramesInFlight;
extern sChrono Chronos[10];
extern float g_TWS_Kt;
extern float g_TWS_Deg;
extern vec2 g_Wind;
extern SoundManager * g_SoundMgr;
extern bool g_bPause;
extern Camera g_Camera;
extern bool g_bShowShipForcesWindows;
extern unique_ptr<VulkanTexture> g_TexWake0;
extern unique_ptr<VulkanTexture> g_TexWake1;
extern unique_ptr<VulkanTexture> g_TexWake2;
extern int g_WakeSize;
extern bool g_bShipShadow;
bool bTexWakeByVAO = true;
VulkanTexture TexContourShip;
int TexContourShipW;
int TexContourShipH;
Ship::Ship(shared_ptr<VulkanDevice>& vulkanDevice, VkRenderPass renderPassScene, VkExtent2D extent, VkRenderPass renderPassReflection, VkRenderPass randerPassShadow, uint32_t shadowWidth, uint32_t shadowHeight,
VkRenderPass randerPassBridgeMask, VkRenderPass randerPassWake, sShip& ship, Ocean* ocean, Camera& camera)
{
mVulkanDevice = vulkanDevice;
chrono.start();
this->ship = ship;
// Read the mvVertices and the faces
igl::readOBJ(ship.PathnameHull.c_str(), mV, mF);
stringstream ssHull;
// Vertices
mvVertices.resize(mV.rows());
mvVerticesInitial.resize(mV.rows());
for (int i = 0; i < mV.rows(); i++)
mvVerticesInitial[i] = vec3(mV(i, 0), mV(i, 1), mV(i, 2));
mvVertSubmerged.resize(mV.rows());
mvVertWaterHeight.resize(mV.rows());
mWorld = mat4(1.0f);
TransformVertices();
SetOcean(ocean);
InitModels(vulkanDevice, renderPassScene, extent, renderPassReflection, randerPassShadow, shadowWidth, shadowHeight, randerPassBridgeMask);
// Get data
InitDimensions();
UpdateWorldMatrix(); // Necessary for several calculations to come
mvTris.resize(mF.rows());
InitTriangles(); // Create the list of the triangles
InitCentroid(); // Compute the centre of the volume
InitSurfaces(); // Certain surfaces
InitInertia(); // Compute volume & all moments of inertia (Ixx, Iyy, Izz, Ixy, Ixz, Iyz)
// Info to display with interface
ssHull << "Length : " << std::fixed << std::setprecision(2) << mLength << " m" << endl;
ssHull << "Width : " << std::fixed << std::setprecision(2) << mWidth << " m" << endl;
ssHull << "Draft : " << std::fixed << std::setprecision(2) << mDraft << " m" << endl;
ssHull << "Mass : " << std::setprecision(0) << int(ship.Mass_t) << " t" << endl;
ssHull << "Power : " << std::setprecision(0) << int(ship.PowerkW) << " kW" << endl;
ssHull << "Max speed : " << std::fixed << std::setprecision(2) << ship.SpeedMaxKt << " kt" << endl;
ssHull << "Test speed : " << std::fixed << std::setprecision(2) << ship.SpeedEcoKt << " kt" << endl;
InfoModel = ssHull.str();
InitWaterVertices(); // Create the list of water vertices in the reference patch
InitHullMesh(vulkanDevice, renderPassScene, extent); // Create the VAO of the colored hull
InitPressureMesh(vulkanDevice, renderPassScene, extent);
InitContours(vulkanDevice, renderPassScene, extent);
InitWakeMesh(vulkanDevice, renderPassScene, extent, randerPassWake);
InitSounds(camera);
// Particles
mSmoke = make_unique<Smoke>(mVulkanDevice, renderPassScene, extent);
mSpray = make_unique<Spray>(mVulkanDevice, renderPassScene, extent);
if (ship.bFlag)
{
float spacing = ship.DimXFlag / 15.0f;
mFlag = make_unique<Flag>(vulkanDevice, renderPassScene, extent, 15, 10, spacing, ship.PathnameFlag.c_str());
}
mLight = make_unique<Light>(mVulkanDevice, renderPassScene, extent);
ResetVelocities();
bMotion = false;
bSound = true;
mArchimede.Name = "Archimede";
mGravity.Name = "Gravity";
mHeaveDrag.Name = "Heave Drag";
mThrust1.Name = "Thrust1";
mThrust2.Name = "Thrust2";
mPropDrag1.Name = "Prop Drag 1";
mPropDrag2.Name = "Prop Drag 2";
mViscousDrag.Name = "Viscous Drag";
mWavesDrag.Name = "Waves Drag";
mBowThrust.Name = "Bow Thrust";
mSternThrust.Name = "Stern Thrust";
mRudderLift.Name = "Rudder Lift";
mRudderDrag.Name = "Rudder Drag";
mAirDrag.Name = "Air Drag";
mWindTorque.Name = "Wind Rotation";
mWindDrift.Name = "Wind Drift";
mCentrifugalTorque.Name = "Centrifugal";
ComputeEquilibriumDraft();
ComputeMaxSpeed();
}
Ship::~Ship()
{
mModelFull.reset();
mPropeller1.reset();
mPropeller2.reset();
mRudder1.reset();
mRudder2.reset();
mRadar1.reset();
mRadar2.reset();
mHullMesh.reset();
mContourMesh1.reset();
mContourMesh2.reset();
mWakeMesh.reset();
mPressureMesh.reset();
mSoundThrust1.reset();
mSoundThrust2.reset();
mSoundBowThruster.reset();
mSoundSternThruster.reset();
mSmoke.reset();
mSpray.reset();
mFlag.reset();
}
void Ship::SetOcean(Ocean* ocean)
{
mOcean = ocean;
pDisplacement = ocean->GetPixelsDisplacement();
};
void Ship::InitModels(shared_ptr<VulkanDevice>& vulkanDevice, VkRenderPass renderPassScene, VkExtent2D extent, VkRenderPass renderPassReflection, VkRenderPass randerPassShadow, uint32_t shadowWidth, uint32_t shadowHeight, VkRenderPass randerPassBridgeMask)
{
// Load models
mModelFull = make_unique<Model>(vulkanDevice);
mModelFull->LoadModel(ship.PathnameFull.c_str());
stringstream ssFull;
ssFull << "Full: " << mModelFull->NbVertices << " vert. & " << mModelFull->NbFaces << " faces" << endl;
ssFull << "Hull: " << mV.rows() << " vert. & " << mF.rows() << " faces" << endl;
Info3D = ssFull.str();
mModelFull->CreateMsPipeline(renderPassScene, extent);
mModelFull->CreateReflectionPipeline(renderPassReflection, extent);
mModelFull->CreateShadowPipeline(randerPassShadow, { shadowWidth, shadowHeight });
mModelFull->CreateCxPipeline(renderPassScene, extent);
mModelFull->CreateBboxPipeline(renderPassScene, extent);
mModelFull->CreateBridgeMaskPipeline(randerPassBridgeMask, extent);
mModelFull->CreateWireframeMsPipeline(renderPassScene, extent);
mModelFull->CreateWireframeColorPipeline(renderPassScene, extent);
if (ship.PathnamePropeller1.length())
{
mPropeller1 = make_unique<Model>(vulkanDevice);
mPropeller1->LoadModel(ship.PathnamePropeller1.c_str());
mPropeller1->CreateMsPipeline(renderPassScene, extent);
mPropeller1->CreateWireframeMsPipeline(renderPassScene, extent);
}
if (ship.PathnamePropeller2.length())
{
mPropeller2 = make_unique<Model>(vulkanDevice);
mPropeller2->LoadModel(ship.PathnamePropeller2.c_str());
mPropeller2->CreateMsPipeline(renderPassScene, extent);
mPropeller2->CreateWireframeMsPipeline(renderPassScene, extent);
}
if (ship.PathnameRudder.length())
{
mRudder1 = make_unique<Model>(vulkanDevice);
mRudder1->LoadModel(ship.PathnameRudder.c_str());
mRudder1->CreateMsPipeline(renderPassScene, extent);
mRudder1->CreateWireframeMsPipeline(renderPassScene, extent);
if (ship.nRudder == 2)
{
mRudder2 = make_unique<Model>(vulkanDevice);
mRudder2->LoadModel(ship.PathnameRudder.c_str());
mRudder2->CreateMsPipeline(renderPassScene, extent);
mRudder2->CreateWireframeMsPipeline(renderPassScene, extent);
}
}
if (ship.PathnameRadar1.length())
{
mRadar1 = make_unique<Model>(vulkanDevice);
mRadar1->LoadModel(ship.PathnameRadar1.c_str());
mRadar1->CreateMsPipeline(renderPassScene, extent);
mRadar1->CreateWireframeMsPipeline(renderPassScene, extent);
}
if (ship.nRadar > 1 && ship.PathnameRadar2.length())
{
mRadar2 = make_unique<Model>(vulkanDevice);
mRadar2->LoadModel(ship.PathnameRadar2.c_str());
mRadar2->CreateMsPipeline(renderPassScene, extent);
mRadar2->CreateWireframeMsPipeline(renderPassScene, extent);
}
mAxis = make_unique<Model>(vulkanDevice);
mAxis->LoadModel("Resources/Interface/Axis.glb");
mAxis->CreateMsPipeline(renderPassScene, extent);
mAxis->bVisible = true;
}
void Ship::InitDimensions()
{
mBbox = mModelFull->GetBoundingBox();
mMass = ship.Mass_t * 1000.0f; // t -> kg for all physical calculations
mPowerW = ship.PowerkW * 1000.0f * 0.5f; // kW -> W for all physical calculations, 90% sur l'arbre et 55% d'efficacité de l'hélice, soit 0.5 au total
if (ship.nPropeller == 2) mPowerW *= 0.5f;
mLength = fabs(mBbox.max.x - mBbox.min.x); // Overall length
mLength3 = mLength * mLength * mLength; // Length3
mWidth = fabs(mBbox.max.z - mBbox.min.z); // Overall width
mHeight = fabs(mBbox.max.y - mBbox.min.y); // Overall height
if (mLength < mWidth) std::swap(mLength, mWidth);
mDraft = -mBbox.min.y; // Below the water level
mAirDraft = mBbox.max.y; // Above the water level
mBow = vec3(mBbox.max.x, 0.0f, 0.0f); // Distance to the centre
mStern = vec3(mBbox.min.x, 0.0f, 0.0f); // Distance to the centre
mWakePivot = vec3(mBbox.min.x + 0.5f * mWidth, 0.0f, 0.0f);
mRudderArea = (mLength * mDraft * 0.01f) * (1.0f + 0.25f * (mWidth / mDraft) * (mWidth / mDraft)); // DNV2 formula for the area of the rudder in m²
mBowThrustMax = ship.BowThrusterPowerW * ship.BowThrusterPerf;
mSternThrustMax = ship.SternThrusterPowerW * ship.SternThrusterPerf;
}
void Ship::InitTriangles()
{
sTriangle tri;
for (int i = 0; i < mF.rows(); ++i)
{
tri.I[0] = mF(i, 0);
tri.I[1] = mF(i, 1);
tri.I[2] = mF(i, 2);
vec3 u = mvVertices[tri.I[1]] - mvVertices[tri.I[0]];
vec3 v = mvVertices[tri.I[2]] - mvVertices[tri.I[0]];
vec3 a = glm::cross(v, u);
tri.Area = 0.5 * sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
tri.NormalInitial = glm::normalize(a);
tri.Color = vec3(0.5f, 0.5f, 0.5f);
mvTris[i] = tri;
}
}
void Ship::InitCentroid()
{
mCentroid = vec3(0.0f);
for (const auto& tri : mvTris)
mCentroid += mvVertices[tri.I[0]] + mvVertices[tri.I[1]] + mvVertices[tri.I[2]];
if (mvTris.size())
mCentroid /= (mvTris.size() * 3.0f);
#ifdef PROPERTIES
cout << "Centroid : ( " << mCentroid.x << ", " << mCentroid.y << ", " << mCentroid.z << " )" << endl;
#endif
}
bool IsPolygonClockwise(const Clipper2Lib::Path64& polygon)
{
int64_t sum = 0;
int n = (int)polygon.size();
for (int i = 0; i < n; ++i)
{
int j = (i + 1) % n;
sum += (polygon[j].x - polygon[i].x) * (polygon[j].y + polygon[i].y);
}
return sum > 0; // true if clockwise
}
void Ship::InitSurfaces()
{
// Area
mAreaXZ = mLength * mWidth;
// Cube root of the area in the XZ plane
mAreaXZ_RacCub = cbrtf(mAreaXZ);
// Wet area
mAreaWettedMax = 0.0f;
for (auto& tri : mvTris) mAreaWettedMax += tri.Area;
// Area of the propeller
mAreaPropeller = M_PI * 0.25f * ship.PropDiameter * ship.PropDiameter;
#ifdef PROPERTIES
cout << "Surface XZ : " << mAreaXZ << " m2" << endl;
cout << "Surface : " << mAreaWettedMax << " m2" << endl;
#endif
if (ship.AreaFront != 0.0f && ship.AreaLat != 0.0f)
return;
vector<Mesh>& vMeshes = mModelFull->GetMesh();
const double scale = 1e4;
const double scale2 = scale * scale;
Clipper2Lib::Paths64 projectedFront; // projection on (Y, Z) plane — front silhouette
Clipper2Lib::Paths64 projectedLat; // projection on (X, Y) plane — lateral silhouette
for (const auto& mesh : vMeshes)
{
for (size_t i = 0; i < mesh.vIndices.size(); i += 3)
{
const sVertex& v0 = mesh.vVertices[mesh.vIndices[i]];
const sVertex& v1 = mesh.vVertices[mesh.vIndices[i + 1]];
const sVertex& v2 = mesh.vVertices[mesh.vIndices[i + 2]];
// Front silhouette: project onto (Y=height, Z=width) plane
Clipper2Lib::Path64 triFront;
triFront.push_back({ (int64_t)(v0.pos.y * scale), (int64_t)(v0.pos.z * scale) });
triFront.push_back({ (int64_t)(v1.pos.y * scale), (int64_t)(v1.pos.z * scale) });
triFront.push_back({ (int64_t)(v2.pos.y * scale), (int64_t)(v2.pos.z * scale) });
if (IsPolygonClockwise(triFront)) std::reverse(triFront.begin(), triFront.end());
projectedFront.push_back(triFront);
// Lateral silhouette: project onto (X=length, Y=height) plane
Clipper2Lib::Path64 triLat;
triLat.push_back({ (int64_t)(v0.pos.x * scale), (int64_t)(v0.pos.y * scale) });
triLat.push_back({ (int64_t)(v1.pos.x * scale), (int64_t)(v1.pos.y * scale) });
triLat.push_back({ (int64_t)(v2.pos.x * scale), (int64_t)(v2.pos.y * scale) });
if (IsPolygonClockwise(triLat)) std::reverse(triLat.begin(), triLat.end());
projectedLat.push_back(triLat);
}
}
// ── Clip polygon : keep only the part above waterline (y >= 0) ────────────
const int64_t INF = std::numeric_limits<int64_t>::max() / 2;
const int64_t waterlineScaled = (int64_t)(ship.PositionY * scale); // waterline at y=0 in model space
Clipper2Lib::Path64 clipAboveWaterline;
clipAboveWaterline.push_back({ -INF, waterlineScaled });
clipAboveWaterline.push_back({ INF, waterlineScaled });
clipAboveWaterline.push_back({ INF, INF });
clipAboveWaterline.push_back({ -INF, INF });
// ── Helper lambda : union of triangles → clip above waterline → area + centroid ──
auto computeSilhouette = [&]( Clipper2Lib::Paths64& projected, float& outArea, vec2& outCenter)
{
outArea = 0.0f;
outCenter = vec2(0.0f);
// Step 1 : union all projected triangles → true 2D silhouette (no double-counting)
Clipper2Lib::Paths64 united;
Clipper2Lib::Clipper64 unionClipper;
unionClipper.AddSubject(projected);
unionClipper.Execute(Clipper2Lib::ClipType::Union, Clipper2Lib::FillRule::NonZero, united);
// Step 2 : intersect with above-waterline clip polygon
Clipper2Lib::Clipper64 clipper;
clipper.AddSubject(united);
clipper.AddClip(Clipper2Lib::Paths64{ clipAboveWaterline });
Clipper2Lib::Paths64 solution;
clipper.Execute(Clipper2Lib::ClipType::Intersection, Clipper2Lib::FillRule::Positive, solution);
// Step 3 : accumulate area and centroid over solution polygons
double totalArea = 0.0;
double cx = 0.0, cy = 0.0;
for (const auto& poly : solution)
{
double polyArea = Clipper2Lib::Area(poly) / scale2;
if (polyArea < 1e-12) continue;
// Polygon centroid via shoelace formula
double pcx = 0.0, pcy = 0.0;
int n = (int)poly.size();
for (int k = 0; k < n; ++k)
{
int l = (k + 1) % n;
double xk = (double)poly[k].x / scale;
double yk = (double)poly[k].y / scale;
double xl = (double)poly[l].x / scale;
double yl = (double)poly[l].y / scale;
double f = (xk * yl - xl * yk);
pcx += (xk + xl) * f;
pcy += (yk + yl) * f;
}
pcx /= (6.0 * polyArea);
pcy /= (6.0 * polyArea);
cx += pcx * polyArea;
cy += pcy * polyArea;
totalArea += polyArea;
}
if (totalArea > 0.0)
{
outArea = (float)totalArea;
outCenter.x = (float)(cx / totalArea);
outCenter.y = (float)(cy / totalArea);
}
};
// ── Front silhouette (projection on Y,Z) → AreaFront, AreaFrontCenter ────
vec2 frontCenter2D;
float frontArea = 0.0f;
computeSilhouette(projectedFront, frontArea, frontCenter2D);
ship.AreaFront = frontArea;
ship.AreaFrontCenter.y = frontCenter2D.x; // Y=height
ship.AreaFrontCenter.z = frontCenter2D.y; // Z=width
// ── Lateral silhouette (projection on X,Y) → AreaLat, AreaLatCenter ──────
vec2 latCenter2D;
float latArea = 0.0f;
computeSilhouette(projectedLat, latArea, latCenter2D);
ship.AreaLat = latArea;
ship.AreaLatCenter.x = latCenter2D.x; // X=length
ship.AreaLatCenter.y = latCenter2D.y; // Y=height
cout << "AreaFront : " << ship.AreaFront << " m2 center=";
PrintGlmVec3(ship.AreaFrontCenter);
cout << "AreaLat : " << ship.AreaLat << " m2 center=";
PrintGlmVec3(ship.AreaLatCenter);
cout << endl;
}
void Ship::InitInertia()
{
// Empirical radii of gyration (fraction of L or B), ITTC, Clarke 1983, Brix 1993
float kyy = 0.25f; // yaw : 0.22-0.28 × L
float kxx = 0.35f; // roll : 0.30-0.40 × B
float kzz = 0.25f; // pitch : 0.22-0.28 × L
switch (ship.Class)
{
case eClass::FastBoat: kyy = 0.26f; kxx = 0.38f; kzz = 0.26f; break;
case eClass::Corvette: kyy = 0.25f; kxx = 0.36f; kzz = 0.25f; break;
case eClass::Frigate: kyy = 0.25f; kxx = 0.35f; kzz = 0.25f; break;
case eClass::Fishing: kyy = 0.27f; kxx = 0.40f; kzz = 0.27f; break;
case eClass::Submarine: kyy = 0.24f; kxx = 0.32f; kzz = 0.24f; break;
case eClass::Ferry: kyy = 0.26f; kxx = 0.38f; kzz = 0.26f; break;
case eClass::Tugboat: kyy = 0.27f; kxx = 0.42f; kzz = 0.27f; break;
case eClass::Cargo: kyy = 0.25f; kxx = 0.35f; kzz = 0.25f; break;
case eClass::Supertanker: kyy = 0.24f; kxx = 0.33f; kzz = 0.24f; break;
}
mIyy = mMass * (kyy * mLength) * (kyy * mLength); // Yaw (autour Y, longueur X)
mIzz = mMass * (kzz * mLength) * (kzz * mLength); // Pitch (autour Z, longueur X)
mIxx = mMass * (kxx * mWidth) * (kxx * mWidth); // Roll (autour X, largeur Z)
mVolume = mMass / mWATER_DENSITY;
#ifdef PROPERTIES
// Displaying results
cout << "Volume : " << mVolume << " m3" << endl;
cout << "============================" << endl;
cout << "Moments d'inertie volumiques" << endl;
cout << "Volume total : " << mVolume << " m3" << endl;
cout << "Ixx = " << mIxx << " kg/m2" << endl;
cout << "Iyy = " << mIyy << " kg/m2" << endl;
cout << "Izz = " << mIzz << " kg/m2" << endl;
cout << endl;
#endif
}
void Ship::InitWaterVertices()
{
// Positions
for (int z = 0; z <= mOcean->MESH_SIZE; ++z)
{
vector<vec3> vPos;
for (int x = 0; x <= mOcean->MESH_SIZE; ++x)
{
int index = z * mOcean->MESH_SIZE_1 + x;
vec3 v;
v.x = (x - mOcean->MESH_SIZE / 2.0f) * mOcean->PATCH_SIZE / mOcean->MESH_SIZE;
v.y = 0.0f;
v.z = (z - mOcean->MESH_SIZE / 2.0f) * mOcean->PATCH_SIZE / mOcean->MESH_SIZE;
vPos.push_back(v);
}
mvWaterPos.push_back(vPos);
}
}
void Ship::InitHullMesh(shared_ptr<VulkanDevice>& vulkanDevice, VkRenderPass renderPassScene, VkExtent2D extent)
{
// Converting mvVertices, Normals and Colors
mvVertexColored = vector<float>(mvTris.size() * 3 * 6);
int index = 0;
for (const auto& tri : mvTris)
{
for (int j = 0; j < 3; ++j)
{
// Position
mvVertexColored[index++] = mvVertices[tri.I[j]].x; // x
mvVertexColored[index++] = mvVertices[tri.I[j]].y; // y
mvVertexColored[index++] = mvVertices[tri.I[j]].z; // z
// Color
mvVertexColored[index++] = tri.Color.r; // r
mvVertexColored[index++] = tri.Color.g; // g
mvVertexColored[index++] = tri.Color.b; // b
}
}
// Generation of mvIndices
vector<unsigned int> indices(mF.rows() * 3);
for (unsigned int i = 0; i < indices.size(); ++i)
indices[i] = i;
mHullMesh = make_unique<HullMesh>(vulkanDevice, mvVertexColored, indices);
mHullMesh->CreatePipeline(renderPassScene, extent);
}
void Ship::InitPressureMesh(shared_ptr<VulkanDevice>& vulkanDevice, VkRenderPass renderPassScene, VkExtent2D extent)
{
float coeff = 0.001f * (200000.0f / mMass) * (6000.0f / mF.rows());
vector<vec3> linePoints;
vec3 start = vec3(0.0f);
vec3 end = vec3(1.0f);
for (auto& tri : mvTris)
{
linePoints.push_back(start);
linePoints.push_back(end);
}
mPressureMesh = make_unique<LineMesh>(mVulkanDevice, linePoints);
mPressureMesh->CreatePipeline(renderPassScene, extent, VK_PRIMITIVE_TOPOLOGY_LINE_LIST);
mPressureMesh->UpdateVertices(linePoints);
}
void Ship::InitContours(shared_ptr<VulkanDevice>& vulkanDevice, VkRenderPass renderPassScene, VkExtent2D extent)
{
// Create 2 contours, the first for the spray, the second for the foam, which is a bit more expanded
// Contour
vector<vec3> contour = ComputeContour(); // Intersect the mesh with the ocean (Y = 0)
if (contour.size() == 0)
return;
// Sort the points
contour = ArrangeContour(contour);
mContourMesh1 = make_unique<LineMesh>(vulkanDevice, contour);
mContourMesh1->CreatePipeline(renderPassScene, extent);
// Put a small offset to the contour to create the spray, otherwise it would be exactly on the waterline and cause z-fighting
vector<vec3> contourSpray = OffsetContour(contour, 0.1f);
InitSpray(contourSpray);
// Close the contour by adding the first point at the end, otherwise the offset contour would be open and not form a closed loop
contour.push_back(contour.front());
// Expand the contour with a constant offset
contour = OffsetContour(contour, 0.5f);
// Create the second for visual debugging, but also to create the texture of the foam inside the expanded contour
mContourMesh2 = make_unique<LineMesh>(vulkanDevice, contour);
mContourMesh2->CreatePipeline(renderPassScene, extent);
CreateTextureOfContour(vulkanDevice, contour); // Create the texture formed with foam inside the exapnded contour
}
void Ship::InitWakeMesh(shared_ptr<VulkanDevice>& vulkanDevice, VkRenderPass renderPassScene, VkExtent2D extent, VkRenderPass randerPassWake)
{
mWakeMesh = make_unique<WakeMesh>(vulkanDevice, vWakeVertices);
mWakeMesh->CreatePipeline(renderPassScene, extent);
mWakeMesh->CreatePipelineTexture(randerPassWake, VkExtent2D(g_WakeSize, g_WakeSize));
mWakeMesh->CreateBlurPipelines();
}
void Ship::InitSounds(Camera& camera)
{
// Sounds
g_SoundMgr->setListenerPosition(camera.GetPosition());
g_SoundMgr->setListenerOrientation(camera.GetAt(), camera.GetUp());
// Power 1
mSoundThrust1 = make_unique<Sound>(ship.ThrustSound);
mSoundThrust1->setVolume(0.25f);
mSoundThrust1->setPosition(ship.Position + ship.PosPropeller1);
mSoundThrust1->setLooping(true);
mSoundThrust1->adjustDistances();
// Power 2
mSoundThrust2 = make_unique<Sound>(ship.ThrustSound);
mSoundThrust2->setVolume(0.25f);
mSoundThrust2->setPosition(ship.Position + ship.PosPropeller2);
mSoundThrust2->setLooping(true);
mSoundThrust2->adjustDistances();
if (bSound)
{
mSoundThrust1->play();
mSoundThrust2->play();
}
// Bow thruster
if (ship.HasBowThruster)
{
mSoundBowThruster = make_unique<Sound>(ship.BowThrusterSound);
mSoundBowThruster->setVolume(0.25f);
mSoundBowThruster->setPosition(ship.Position + ship.PosBowThruster);
mSoundBowThruster->setLooping(true);
mSoundBowThruster->adjustDistances();
}
// Stern thruster
if (ship.HasSternThruster)
{
mSoundSternThruster = make_unique<Sound>(ship.SternThrusterSound);
mSoundSternThruster->setVolume(0.25f);
mSoundSternThruster->setPosition(ship.Position + ship.PosSternThruster);
mSoundSternThruster->setLooping(true);
mSoundSternThruster->adjustDistances();
}
}
void FilterClosePoints(vector<sSprayPt>& pts)
{
if (pts.size() < 2)
return;
float totalDist = glm::length(pts.front().p - pts.back().p);
float threshold = totalDist / pts.size();
// New filtered list
vector<sSprayPt> filtered;
filtered.reserve(pts.size());
filtered.push_back(pts[0]); // Always keep the first point
vec3 lastPos = pts[0].p;
for (size_t i = 1; i < pts.size(); ++i)
{
float dist = glm::length(pts[i].p - lastPos);
if (dist >= threshold)
{
filtered.push_back(pts[i]);
lastPos = pts[i].p;
}
// Otherwise ignore the point that is too close
}
pts = std::move(filtered);
}
void Ship::InitSpray(vector<vec3>& contour)
{
if (contour.size() == 0)
return;
float maxForward = contour[0].x;
int frontIndex = 0;
for (int i = 1; i < (int)contour.size(); i++)
{
if (contour[i].x > maxForward)
{
maxForward = contour[i].x;
frontIndex = i;
}
}
vec3 frontPoint = contour[frontIndex];
mLeft.clear();
mRight.clear();
float dist = mLength * ship.SprayLength;
for (size_t i = 0; i < contour.size(); ++i)
{
vec3 p = contour[i];
float d = glm::length(p - frontPoint);
if (d <= dist)
{
// Find the point before and the point after on the contour
int idxPrev = (i == 0) ? (int)contour.size() - 1 : (int)i - 1;
int idxNext = (i == contour.size() - 1) ? 0 : (int)i + 1;
vec3 prev = contour[idxPrev];
vec3 next = contour[idxNext];
// Tangent vector (direction of the contour at point p)
vec3 tangent = glm::normalize(next - prev);
// For the x/z plane: take the outside
vec3 toPrev = prev - p;
vec3 toNext = next - p;
// Lateral vector in the plane (here (toNext - toPrev))
vec3 lateral = toNext - toPrev;
// Normal: perpendicular to tangent, oriented outward
vec3 n = glm::normalize(glm::cross(tangent, vec3(0, 1, 0)));
// We want n.z to have the same sign as p.z
if ((p.z < 0.0f && n.z < 0.0f) || (p.z > 0.0f && n.z > 0.0f))
{
// n already on the right side
}
else
n = -n;
sSprayPt pt;
pt.p = p;
pt.n = n;
if (p.z < 0.0f)
mLeft.push_back(pt);
else if (p.z > 0.0f)
mRight.push_back(pt);
}
}
// Comparator to sort in ascending order of distance on the X axis from frontPoint
auto compareNearToFarX = [frontPoint](const sSprayPt& a, const sSprayPt& b) {
float distA = frontPoint.x - a.p.x; // the "distance" in x from frontPoint
float distB = frontPoint.x - b.p.x;
return distA < distB;
};
std::sort(mLeft.begin(), mLeft.end(), compareNearToFarX);
std::sort(mRight.begin(), mRight.end(), compareNearToFarX);
FilterClosePoints(mLeft);
FilterClosePoints(mRight);
// Ajout de points extrapolés en avant (axe +X)
auto addForwardPoints = [this](vector<sSprayPt>& pts, int numExtra)
{
if (pts.size() < 2) return;
const sSprayPt& p0 = pts[0];
const sSprayPt& p1 = pts[1];
// Pas uniquement en X, ignorant l'écart transversal
float step = ship.Length / 200.0f;
// Direction purement axiale vers l'avant
vec3 dir = vec3(1.0f, 0.0f, 0.0f);
vector<sSprayPt> extra;
for (int i = 1; i <= numExtra; ++i)
{
sSprayPt pt;
// Z et Y restent ceux de p0 : le point reste sur le bord latéral de la proue
pt.p = vec3(p0.p.x + dir.x * step * (float)i, p0.p.y, p0.p.z);
pt.n = p0.n;
extra.push_back(pt);
}
std::reverse(extra.begin(), extra.end());
pts.insert(pts.begin(), extra.begin(), extra.end());
};
const int NUM_EXTRA_POINTS = 2;
addForwardPoints(mLeft, NUM_EXTRA_POINTS);
addForwardPoints(mRight, NUM_EXTRA_POINTS);
if (mLeft.size() > 1 && mRight.size() > 1)
{
mRandomOffsetRange = 0.0f;
for (size_t i = 0; i < mLeft.size() - 1; ++i)
mRandomOffsetRange += glm::length(mLeft[i + 1].p - mLeft[i].p);
for (size_t i = 0; i < mRight.size() - 1; ++i)
mRandomOffsetRange += glm::length(mRight[i + 1].p - mRight[i].p);
mRandomOffsetRange /= (mLeft.size() - 1 + mRight.size() - 1);
mRandomOffsetRange *= 0.1f;
}
}
vector<vec3> Ship::ComputeContour()
{
vector<vec3> contour;
contour.reserve(64);
for (const sTriangle& tri : mvTris)
{
const vec3& v0 = mvVertices[tri.I[0]];
const vec3& v1 = mvVertices[tri.I[1]];
const vec3& v2 = mvVertices[tri.I[2]];
float y0 = v0.y, y1 = v1.y, y2 = v2.y;
int sign0 = (y0 > 1e-6f) ? 1 : ((y0 < -1e-6f) ? -1 : 0);
int sign1 = (y1 > 1e-6f) ? 1 : ((y1 < -1e-6f) ? -1 : 0);
int sign2 = (y2 > 1e-6f) ? 1 : ((y2 < -1e-6f) ? -1 : 0);
if ((sign0 == 1 && sign1 == 1 && sign2 == 1) || (sign0 == -1 && sign1 == -1 && sign2 == -1)) continue;
// Points exactly on the plan (strict tolerance)
if (abs(y0) < 1e-6f) contour.push_back(v0);
if (abs(y1) < 1e-6f) contour.push_back(v1);
if (abs(y2) < 1e-6f) contour.push_back(v2);
// Edge 0-1: avoid division by zero
if (sign0 * sign1 < 0 && abs(y1 - y0) > 1e-6f)
{
float t = glm::clamp(-y0 / (y1 - y0), 0.0f, 1.0f);
contour.push_back(glm::mix(v0, v1, t));
}
// Edge 1-2
if (sign1 * sign2 < 0 && abs(y2 - y1) > 1e-6f)
{
float t = glm::clamp(-y1 / (y2 - y1), 0.0f, 1.0f);
contour.push_back(glm::mix(v1, v2, t));
}
// Edge 2-0
if (sign2 * sign0 < 0 && abs(y0 - y2) > 1e-6f)
{
float t = glm::clamp(-y2 / (y0 - y2), 0.0f, 1.0f);
contour.push_back(glm::mix(v2, v0, t));
}
}
// Sorting
std::sort(contour.begin(), contour.end(), [](const vec3& a, const vec3& b) {
return a.x < b.x || (a.x == b.x && a.z < b.z);
});
// Remove duplicates
vector<vec3> uniqueContour;
uniqueContour.reserve(contour.size());
for (size_t i = 0; i < contour.size(); ++i)
if (i == 0 || abs(contour[i].x - contour[i - 1].x) > 1e-4f || abs(contour[i].z - contour[i - 1].z) > 1e-4f)
uniqueContour.push_back(contour[i]);
return uniqueContour;
}
vector<vec3> Ship::ArrangeByCoordinates(const vector<vec3>& contourUnordered)
{
vector<vec3> left;
vector<vec3> right;
for (const vec3& p : contourUnordered)
{
if (p.z <= 0.0f) left.push_back(p);
else if (p.z > 0.0f) right.push_back(p);
}
auto compareNearToFarX = [](const vec3& a, const vec3& b) {
if (abs(a.x - b.x) < 1e-4f)
return a.z > b.z; // sort by z if x difference is very small
return a.x < b.x;
};
sort(left.begin(), left.end(), compareNearToFarX);
sort(right.begin(), right.end(), compareNearToFarX);
vector<vec3> ordered;
ordered.reserve(left.size() + right.size());
ordered.insert(ordered.end(), left.begin(), left.end());
ordered.insert(ordered.end(), right.rbegin(), right.rend()); // right in reverse order
return ordered;
}
vector<vec3> Ship::ArrangeByPolarAngle(const vector<vec3>& contourUnordered)
{
if (contourUnordered.empty()) return {};
// 1. Calculate the centroid (in the xz plane)
float cx = 0.f, cz = 0.f;
for (const vec3& p : contourUnordered) { cx += p.x; cz += p.z; }
cx /= contourUnordered.size();
cz /= contourUnordered.size();
// 2. Sort by polar angle around the centroid
vector<vec3> ordered = contourUnordered;
std::sort(ordered.begin(), ordered.end(), [cx, cz](const vec3& a, const vec3& b) {
float angleA = std::atan2(a.z - cz, a.x - cx);
float angleB = std::atan2(b.z - cz, b.x - cx);
return angleA < angleB;
});
// 3. Close the polygon
ordered.push_back(ordered.front());
return ordered;
}
vector<vec3> Ship::ArrangeContour(const vector<vec3>& contourUnordered)
{
if (ship.ContourType == 1)
return ArrangeByCoordinates(contourUnordered);
else
return ArrangeByPolarAngle(contourUnordered);
}
vector<vector<vec2>> offsetContourWithClipper(const vector<vec2>& contour, float offset, JoinType joinType = JoinType::Round, EndType endType = EndType::Polygon)
{
const double scaleClipper = 1e6; // scale factor to maintain accuracy of clipper (calculations on int64)
// Convert contour to Clipper int64
Path64 path;
path.reserve(contour.size());
for (const auto& pt : contour)
path.emplace_back(static_cast<int64_t>(pt.x * scaleClipper), static_cast<int64_t>(pt.y * scaleClipper));
// ClipperOffset manages multiple paths, we create a vector of paths
Paths64 paths;
paths.push_back(path);
// Offset in integer units, we convert the float offset to int64_t
int64_t intOffset = static_cast<int64_t>(offset * scaleClipper);
ClipperOffset offsetter;
offsetter.AddPaths(paths, joinType, endType);
Paths64 solution;
offsetter.Execute(intOffset, solution);
// Convert each solution polygon to glm::vec2 (float)
vector<vector<vec2>> result;
result.reserve(solution.size());
for (const Path64& p : solution)
{
vector<vec2> res;
result.reserve(p.size());
for (const auto& pt : p)
res.emplace_back(static_cast<float>(pt.x) / static_cast<float>(scaleClipper), static_cast<float>(pt.y) / static_cast<float>(scaleClipper));
result.push_back(res);
}
return result;
}
vector<vec3> Ship::OffsetContour(const vector<vec3>& contour, float offset)
{
// Convert contour in 3D to contour 2D
vector<vec2> contour2d;
for (const auto& v : contour)
contour2d.push_back(vec2(v.x, v.z));
// Execute the offset with clipper library
auto newContour = offsetContourWithClipper(contour2d, offset);
// Convert the result to 3D
vector<vec3> result;
size_t totalSize = 0;
for (const auto& contour : newContour)
totalSize += contour.size();
result.reserve(totalSize);
for (const auto& contour : newContour)
for (const vec2& p : contour)
result.emplace_back(p.x, 0.f, p.y); // Level of the water
return result;
}
bool isPointInPolygon(const vec2& pt, const vector<vec2>& contour2D)
{
// Tests if a point (x, z) is inside a polygon (ray algorithm)
bool inside = false;
size_t n = contour2D.size();
for (size_t i = 0, j = n - 1; i < n; j = i++)
{
const vec2& vi = contour2D[i];
const vec2& vj = contour2D[j];
if (((vi.y > pt.y) != (vj.y > pt.y)) && (pt.x < (vj.x - vi.x) * (pt.y - vi.y) / (vj.y - vi.y + 1e-8f) + vi.x))
inside = !inside;
}
return inside;
}
float minDistanceToContour(const vec2& pt, const vector<vec2>& contour2D)
{
// Minimum distance between a point and a polyline (to draw the outline in white)
float minDist = numeric_limits<float>::max();
size_t n = contour2D.size();
for (size_t i = 0; i < n; ++i)
{
const vec2& a = contour2D[i];
const vec2& b = contour2D[(i + 1) % n];
vec2 ab = b - a;
vec2 ap = pt - a;
float t = glm::clamp(glm::dot(ap, ab) / glm::dot(ab, ab), 0.0f, 1.0f);
vec2 proj = a + t * ab;
float dist = glm::distance(pt, proj);
if (dist < minDist) minDist = dist;
}
return minDist;
}
void Ship::CreateTextureOfContour(shared_ptr<VulkanDevice>& vulkanDevice, const vector<vec3>& contour)
{
const int SCALE = 4;
float metersW = std::ceil((mLength + 5.0f) / 10.0f) * 10.0f;
float metersH = std::ceil((mWidth + 5.0f) / 10.0f) * 10.0f;
TexContourShipW = (int)metersW * SCALE;
TexContourShipH = (int)metersH * SCALE;
float halfW = TexContourShipW / 2.0f;
float halfH = TexContourShipH / 2.0f;
vector<vec2> contourHi;
for (const auto& v : contour)
contourHi.emplace_back(v.x * SCALE + halfW, v.z * SCALE + halfH);
float edgeWidth = 1.0f * SCALE;
vector<float> mask(TexContourShipW * TexContourShipH);
for (int j = 0; j < TexContourShipH; ++j)
{
for (int i = 0; i < TexContourShipW; ++i)
{
vec2 pt(i + 0.5f, j + 0.5f);
bool inside = isPointInPolygon(pt, contourHi);
float dist = minDistanceToContour(pt, contourHi);