-
Notifications
You must be signed in to change notification settings - Fork 1
/
VST2X3D-AI.js
1780 lines (1449 loc) · 69.3 KB
/
VST2X3D-AI.js
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
/*
* 010:
* Accepts lading of local img, lbl, vst; download if not available
*/
/* 0.7.0
* Added list of links to raw textures, jpg textures, textures folders
*/
/* 0.6.0 update:
* Implemented extraction of texture from .IMG loaded together with VST locally;
* known bug: kaitai struct does not support yet this file format:
* FORMAT='HALF' <<<<<<<<<<<
* TYPE='IMAGE'
* BUFSIZ=512
* DIM=3 <<<<<<<<<
* EOL=0
* RECSIZE=512
* ORG='BSQ'
* NL=256
* NS=256
* NB=1 <<<<<<<<<<<<
* N1=256
* N2=256
*/
BASE_IMG_URL = "";
//BASE_IMG_URL_NAVCAM = "https://planetarydata.jpl.nasa.gov/w10n/mer2-m-navcam-5-disparity-ops-v1.0/mer2no_0xxx/";
BASE_IMG_URL_NAVCAM = "https://planetarydata.jpl.nasa.gov/img/data/mer/spirit/mer2no_0xxx/";
BASE_IMG_URL_PANCAM = "https://planetarydata.jpl.nasa.gov/img/data/mer/spirit/mer2po_0xxx/";
BASE_IMG_URL_HAZCAM = "https://planetarydata.jpl.nasa.gov/img/data/mer/spirit/mer2po_0xxx/";
IMG_RAW_FOLDER = "data/";
IMG_JPG_FOLDER = "browse/";
SOL_FOLDER = "sol#SOLNUMBER#/rdr/"; // sol must be determined from VST // DEBUG!! (Sol number is in .lbl of .vst file)
BASE_VST_URL = "https://planetarydata.jpl.nasa.gov/img/data/mer/spirit/mer2mw_0xxx/";
VST_CAMERA_FOLDER = "data/navcam/"; // (navcam --> mer2no_0xxx for images) // DEBUG: add other cameras!
VST_FOLDER_SITE_NAME = "site0137/"; // DEBUG! Site number is in filename (137=B1)
product_name_no_ext = "2n292378085vilb128f0006l0m1"; // 2n292377885vilb126f0006l0m1 = small vst for testing, sol 1870 // DEBUG
// 2n292377885vilb126f0006l0m1
// 2n292378085vilb128f0006l0m1
base_VST_filename = BASE_VST_URL + VST_CAMERA_FOLDER + VST_FOLDER_SITE_NAME + product_name_no_ext;
let angles = 0;
let solNumber = 0;
let x3d = null;
wireframeEnabled = false;
let rawIMGfileContents = null;
let extractedVicarData = "";
proxyURL = "https://win98.altervista.org/space/exploration/myp.php?pass=miapass&mode=native&url=";
x3dShapes = [];
rotatedShapes = [];
const graphicalProducts = [
"RAD",
"RAL",
"RSL",
"EFF",
"ESF",
"EDN",
"ILF",
"ILL",
"FFL",
"MRD",
"MRL",
"RFD",
"RFL",
"IOF",
"IOL",
"IFF",
"IFL",
"IFS",
"CCD",
"CCL",
"CFD",
"CFL",
"ITH",
"THN"
];
// Strutture dati VST
class VSTHeader {
constructor(dataView, offset = 0) {
this.label = dataView.getInt32(offset, true);
this.byteOrder = dataView.getInt32(offset + 4, true);
this.versionMajor = dataView.getInt32(offset + 8, true);
this.versionMinor = dataView.getInt32(offset + 12, true);
this.implementation = dataView.getInt32(offset + 16, true);
this.res1 = dataView.getInt32(offset + 20, true);
this.res2 = dataView.getInt32(offset + 24, true);
this.textureNum = dataView.getInt32(offset + 28, true);
this.vertexNum = dataView.getInt32(offset + 32, true);
this.lodNum = dataView.getInt32(offset + 36, true);
// Gestione byte order
if (this.byteOrder === 0x00010203) {
this.reverseValues();
}
}
reverseValues() {
this.versionMajor = this.reverseInt32(this.versionMajor);
this.versionMinor = this.reverseInt32(this.versionMinor);
this.textureNum = this.reverseInt32(this.textureNum);
this.vertexNum = this.reverseInt32(this.vertexNum);
this.lodNum = this.reverseInt32(this.lodNum);
}
reverseInt32(value) {
return ((value & 0xFF) << 24) |
((value & 0xFF00) << 8) |
((value & 0xFF0000) >>> 8) |
((value & 0xFF000000) >>> 24);
}
}
class BoundingBox {
constructor(dataView, offset = 0, needsReverse = false) {
this.xMin = dataView.getFloat32(offset, true);
this.yMin = dataView.getFloat32(offset + 4, true);
this.zMin = dataView.getFloat32(offset + 8, true);
this.xMax = dataView.getFloat32(offset + 12, true);
this.yMax = dataView.getFloat32(offset + 16, true);
this.zMax = dataView.getFloat32(offset + 20, true);
if (needsReverse) {
this.reverseValues();
}
}
reverseValues() {
[this.xMin, this.yMin, this.zMin, this.xMax, this.yMax, this.zMax] =
[this.xMin, this.yMin, this.zMin, this.xMax, this.yMax, this.zMax].map(this.reverseFloat32);
}
reverseFloat32(value) {
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
view.setFloat32(0, value, true);
return view.getFloat32(0, false);
}
}
class Vertex {
constructor(dataView, offset = 0, needsReverse = false) {
this.tx = dataView.getFloat32(offset, true);
this.ty = dataView.getFloat32(offset + 4, true);
this.x = dataView.getFloat32(offset + 8, true);
this.y = dataView.getFloat32(offset + 12, true);
this.z = dataView.getFloat32(offset + 16, true);
if (needsReverse) {
this.reverseValues();
}
}
reverseValues() {
[this.tx, this.ty, this.x, this.y, this.z] =
[this.tx, this.ty, this.x, this.y, this.z].map(this.reverseFloat32);
}
reverseFloat32(value) {
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
view.setFloat32(0, value, true);
return view.getFloat32(0, false);
}
}
class LODHeader {
constructor(dataView, offset = 0, needsReverse = false) {
this.size = dataView.getInt32(offset, true);
this.res1 = dataView.getInt32(offset + 4, true);
this.res2 = dataView.getInt32(offset + 8, true);
this.vertexNum = dataView.getInt32(offset + 12, true);
this.distThreshold = dataView.getFloat32(offset + 16, true);
this.patchNum = dataView.getInt32(offset + 20, true);
this.vertMax = dataView.getInt32(offset + 24, true);
if (needsReverse) {
this.reverseValues();
}
}
reverseValues() {
this.patchNum = this.reverseInt32(this.patchNum);
this.vertexNum = this.reverseInt32(this.vertexNum);
this.vertMax = this.reverseInt32(this.vertMax);
this.distThreshold = this.reverseFloat32(this.distThreshold);
}
reverseInt32(value) {
return ((value & 0xFF) << 24) |
((value & 0xFF00) << 8) |
((value & 0xFF0000) >>> 8) |
((value & 0xFF000000) >>> 24);
}
reverseFloat32(value) {
const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);
view.setFloat32(0, value, true);
return view.getFloat32(0, false);
}
}
class PatchHeader {
constructor(dataView, offset = 0, needsReverse = false) {
this.res1 = dataView.getInt32(offset, true);
this.res2 = dataView.getInt32(offset + 4, true);
this.pointCloud = dataView.getInt32(offset + 8, true);
this.texture = dataView.getInt32(offset + 12, true);
this.arrayNum = dataView.getInt32(offset + 16, true);
this.totalVertexNum = dataView.getInt32(offset + 20, true);
if (needsReverse) {
this.reverseValues();
}
}
reverseValues() {
this.pointCloud = this.reverseInt32(this.pointCloud);
this.arrayNum = this.reverseInt32(this.arrayNum);
this.texture = this.reverseInt32(this.texture);
this.totalVertexNum = this.reverseInt32(this.totalVertexNum);
}
reverseInt32(value) {
return ((value & 0xFF) << 24) |
((value & 0xFF00) << 8) |
((value & 0xFF0000) >>> 8) |
((value & 0xFF000000) >>> 24);
}
}
class VSTParser {
constructor(arrayBuffer) {
this.dataView = new DataView(arrayBuffer);
this.offset = 0;
this.textureFiles = [];
this.vertices = [];
}
async parse(imgFiles, lblFiles) { //////// <<<<<<<<<<<<<<<<<<<<<------------------------ VST PARSER
console.log("VST parsing - IMG:", imgFiles, ", LBL:",lblFiles);
const fileProgressBar = document.getElementById('fileProgressBar');
fileProgressBar.value = 0; // Resetta la barra di progresso
const totalSteps = 8; // Numero totale di passi significativi (puoi aggiungerne altri)
let currentStep = 0;
const advanceProgress = async (stepMessage) => {
currentStep++;
fileProgressBar.value = Math.round((currentStep / totalSteps) * 100);
await new Promise(resolve => setTimeout(resolve, 0)); // Permetti aggiornamenti in tempo reale
};
try {
// Parse header
const header = new VSTHeader(this.dataView, this.offset);
this.offset += 40; // Size of VSTHeader
// Validate VST format
if (header.label !== 0x00545356) throw new Error('Invalid VST file format');
if (header.implementation !== 0x0052454D) throw new Error('Implementation MER expected');
await advanceProgress("HEADER2 - Header parsed");
const needsReverse = header.byteOrder === 0x00010203;
////////////////// Parse bounding box
const bbox = new BoundingBox(this.dataView, this.offset, needsReverse);
this.offset += 24; // Size of BoundingBox
////////////// Parse texture references
for (let i = 0; i < header.textureNum; i++) {
let imgFileFound = false;
let imgContents = "";
let labelContents = "";
let textureBASE64 = "error";
angles = null;
let VSTlabel = "";
const textureBytes = new Uint8Array(this.dataView.buffer, this.offset, 2048);
const textureRef = String.fromCharCode.apply(null, textureBytes);
console.log("PARSE REF=",textureRef.split("\x00")[1] + "/" + textureRef.split("\x00")[2]);
let textureName = textureRef.substring(10, 37) + '.img.jpg';
textureName = textureName.substring(0, 23) + "l" + textureName.substring(24); // Force left camera for texture
textureName = textureName.substring(0, 26) + "1" + textureName.substring(27); // Force version 1 for IMG product
console.log("PARSE textureName=",textureName);
const secondChar = textureName.charAt(1).toLowerCase();
if (secondChar === 'n') {
BASE_IMG_URL = BASE_IMG_URL_NAVCAM
} else if (secondChar === 'p') {
BASE_IMG_URL = BASE_IMG_URL_PANCAM
} else if ((secondChar === 'r') || (secondChar === 'f') ) {
BASE_IMG_URL = BASE_IMG_URL_HAZCAM
} else {
throw new Error("Carattere non riconosciuto '" + secondChar + "' per determinare la cartella della fotocamera."); // Gestione errore
}
let textureUrlLeft = textureName.substring(0, 11);
let textureUrlRight = textureName.substring(14);
let currentVSTProductID = (textureName.substring(0, 11) + "vil" + textureName.substring(14, 27)).toLowerCase(); // 2n294774058vilb1cup0783l0m1
let currentRAWIMGProductID = textureRef.substring(10, 37);
let siteNumberCoded = textureName.substr(14, 2);
let siteNumberString = "site0" + siteCodeToString(siteNumberCoded);
if (lblFiles.length === 0) {
// Local file not available, download; .LBL file is located in .VST folder, which depends on site number, which is coded into .VST filename:
VSTlabel = await downloadLBL(currentVSTProductID + ".lbl", siteNumberString);
saveRawContents(VSTlabel, currentVSTProductID + ".lbl");
} else {
console.log("Retrieving sol from local .LBL file associated to local .VST file...");
for (const file of lblFiles) {
const fileName = file.name.toUpperCase();
let suggestedFilename = currentVSTProductID.toUpperCase() + ".LBL";
console.log(" Testing file: " , fileName);
console.log(" Required : " , suggestedFilename);
if (fileName.substring(0,23) === suggestedFilename.substring(0,23)) { // disregard version and left/rigth match
console.log(" File match, getting sol...");
VSTlabel = await loadLocalLabel(file);
//console.log(" retrived sol:", solNumber);
break; // Exit loop once file is found
} else {
console.log(" No match, skipping.");
}
}
} // End processing local .IMG label
solNumber = extractSol(VSTlabel);
console.log("SOLNUMBER=",solNumber);
let base_texture_folder = BASE_IMG_URL + IMG_JPG_FOLDER + SOL_FOLDER;
let base_texture_folderNew = base_texture_folder.replace("#SOLNUMBER#",solNumber);
let base_raw_texture_folder = base_texture_folder.replace("#SOLNUMBER#",solNumber).replace("browse","data");
console.log("PARSE - Folder for texture:",base_texture_folderNew);
spnProcessed.innerHTML += `Texture: ` +
` <a href="` + base_raw_texture_folder + currentRAWIMGProductID.toLowerCase() + `.img">raw</a>`+
`, <a href="` + base_texture_folderNew + currentRAWIMGProductID.toLowerCase() + `.img.jpg">jpg</a>`+
`, <a href="` + base_texture_folderNew + `">folder</a><br>`;
console.log("currentRAWIMGProductID=",currentRAWIMGProductID);
console.log("Number of local files available:", imgFiles.length);
let currentRAWIMGfileName = currentRAWIMGProductID + ".IMG";
for (let productIndex = 0; ((productIndex < graphicalProducts.length) && (textureBASE64 === "error") && (imgFileFound === false)); productIndex++) {
let textureVariant = graphicalProducts[productIndex];
console.log("productIndex=",productIndex, ", product variant: ", textureVariant);
let textureUrl = base_texture_folderNew + textureUrlLeft + textureVariant + textureUrlRight;
//textureUrl = textureUrl;
let suggestedFilename = (textureUrlLeft + textureVariant + textureUrlRight).toUpperCase().replace(".JPG","");
if ( labelContents === "") {
console.log("label not loaded yet, looking locally, then online...")
if (imgFiles.length === 0) { // no local IMG file available, download:
console.log("no local IMG file '" + suggestedFilename + " 'available for Alt/Az, download...")
let rawContents = await downloadIMG(currentRAWIMGProductID, siteNumberString, solNumber);
console.log("rawContents=",rawContents);
labelContents = new TextDecoder().decode(rawContents);
console.log("labelContents=",labelContents.length);
textureBASE64 = await getTextureFromIMG(rawContents);
console.log(" Length of RETRIEVED texture:",textureBASE64.length)
saveRawContents(rawContents, currentRAWIMGfileName);
} else {
console.log(" DEBUG: labelContents to be taken from local file ", suggestedFilename)
// labelContents to be taken from local file /// dEBUG
console.log(" Searching for possible textures...");
for (const file of imgFiles) {
const fileName = file.name.toUpperCase();
console.log(" Current file: " , fileName , " vs IMG filename taken from VST:" , currentRAWIMGfileName);
if (fileName.toLowerCase().substring(0,23) === currentRAWIMGfileName.toLowerCase().substring(0,23)) { // disregard version and left/rigth match
console.log(" File match, getting texture...");
const imgData = await getDataFromLocalIMG(file);
textureBASE64 = imgData.textureBASE64;
solNumber = imgData.solNumber;
labelContents = imgData.fileContentsString;
console.log(" Length of LOCAL texture:", textureBASE64.length);
imgFileFound = true;
break; // Exit loop once file is found
} else {
console.log(" No match, skipping.");
}
}
}
console.log("IMG loaded, reading angles...");
angles = extractVicarData2(labelContents);
console.log(" angles for " + suggestedFilename + " = ", angles);
}
console.log("Texture length:", textureBASE64.length);
} // for sui graphicalProducts
///////////////// end texture retrieval /////////
if (textureBASE64 !== "error") {
//
} else {
console.log(" **** ERROR, no texture");
}
this.textureFiles.push(textureBASE64 || null);
this.offset += 2048;
} // for (textures ref)
await advanceProgress("HEADER2 - Textures loaded");
//////////// COORDINATES ////////
// in the VST file the coordinate system binary data is 12 64 bit floats (total 96 bytes used)
// which are simply the C, A, H, V vectors of the camera model in the order
// Cx, Cy, Cz, Ax, Ay, Az, Hx, Hy, Hz, Vx, Vy, Vz.
/*
- C is a 3D vector that gives the location of the Center of projection of the left navcam camera as
it was positioned by the pan/tilt mast relative to rover frame when that image was acquired.
- A is a 3D vector that gives the Axis of that camera which is the direction in which it was pointed.
- The other two are the Horizontal and Vertical 3D vectors in the plane of the image sensor.
There is some nuance because the CAHV camera model doesn’t actually require A, H, and V to be orthonormal.
However, you can construct an orhonormal basis from them, see this code to do that:
https://github.com/NASA-AMMOS/VICAR/blob/8264ad382401a93224cbecb810796a0c0262d36b/vos/p2/sub/cahvor/cmod_cahv.c#L795
*/
/*
CAHV Camera Model
The CAHV camera model is equivalent to the standard
linear photogrammetric model for a pinhole camera. It
is useful for very small field of view cameras and as a
building block for more complex camera models. The
CAHV model consists of four 3-vectors: C, A, H, and
V. Vector C gives the location of the pinhole. Vector
A gives the camera axis, defined as the normal to the
image plane. Vector H encodes the horizontal axis of
the image plane (H’), the coordinate (Hc) of the image
column at the optical centre of the image plane, and the
horizontal focal length (Hs) of the camera, in pixels.
Vector V encodes corresponding information (V’, Vc,
Vs) in the vertical direction. The angle (theta) between
horizontal and vertical vectors H’ and V’ is about 90°.
Non-orthogonal H’ and V’ generally represent an
attempt to compensate for distortion that CAHV
vectors cannot directly model. Image dimensions are
supplied along with the CAHV model.
"CAMERA RESPONSE SIMULATION FOR PLANETARY EXPLORATION"
https://robotics.jpl.nasa.gov/media/documents/rmadison3.pdf
*/
const coords = (() => {
const float64Array = [];
const float64View = new Float64Array(1);
const uint8View = new Uint8Array(float64View.buffer);
for (let i = 0; i < 96; i += 8) { // 8 byte per ogni float64
// Copia 8 byte alla volta nel buffer temporaneo
for (let j = 0; j < 8; j++) {
uint8View[j] = this.dataView.getUint8(this.offset + i + j);
}
// Aggiungi il float64 risultante all'array
float64Array.push(float64View[0]);
}
const Cx = float64Array[0];
const Cy = float64Array[1];
const Cz = float64Array[2];
const Ax = float64Array[3];
const Ay = float64Array[4];
const Az = float64Array[5];
const Hx = float64Array[6];
const Hy = float64Array[7];
const Hz = float64Array[8];
const Vx = float64Array[9];
const Vy = float64Array[10];
const Vz = float64Array[11];
const up = [0, 1, 0];
// Calcola il vettore direzione
const Dx = Ax - Cx;
const Dy = Ay - Cy;
const Dz = Az - Cz;
// Calcola la lunghezza del vettore
const magnitude = Math.sqrt(Dx * Dx + Dy * Dy + Dz * Dz);
// Normalizza il vettore direzione
const normDx = Dx / magnitude;
const normDy = Dy / magnitude;
const normDz = Dz / magnitude;
// Calcola gli angoli Yaw e Pitch
const yaw = Math.atan2(normDz, normDx); // Psi
const pitch = Math.asin(-normDy); // Theta
// Vettore Up di riferimento
const Ux = up[0], Uy = up[1], Uz = up[2];
// Calcola il vettore Right tramite il prodotto vettoriale D x U
const Rx = normDy * Uz - normDz * Uy;
const Ry = normDz * Ux - normDx * Uz;
const Rz = normDx * Uy - normDy * Ux;
// Normalizza il vettore Right
const magnitudeR = Math.sqrt(Rx * Rx + Ry * Ry + Rz * Rz);
const normRx = Rx / magnitudeR;
const normRy = Ry / magnitudeR;
const normRz = Rz / magnitudeR;
// Calcola il Roll
const roll = Math.atan2(normRy * Uz - normRz * Uy, normDx * Ux + normDy * Uy + normDz * Uz); // Phi
return {
Cx, Cy, Cz,
Ax, Ay, Az,
Hx, Hy, Hz,
Vx, Vy, Vz,
yawRad: yaw,
pitchRad: pitch,
rollRad: roll,
yawDeg: yaw * 180 / Math.PI,
pitchDeg: pitch * 180 / Math.PI,
rollDeg: roll * 180 / Math.PI,
description: "C = camera location, A = camera pointing vector w.r.t. C frame"
}
})();
this.offset += 4096;
await advanceProgress("HEADER2 - Textures references loaded");
/////////// Read vertices
for (let i = 0; i < header.vertexNum; i++) {
const vertex = new Vertex(this.dataView, this.offset, needsReverse);
this.vertices.push(vertex);
this.offset += 20;
}
await advanceProgress("HEADER2 - Vertex loaded");
//////////// Process LODs
const lods = [];
for (let i = 0; i < header.lodNum; i++) {
const lod = this.parseLOD(needsReverse);
lods.push(lod);
await advanceProgress("HEADER2 - LOD processed");
}
fileProgressBar.value = 100; // Parsing completato
return {
header,
bbox,
textureFiles: this.textureFiles,
vertices: this.vertices,
lods,
coordinateSystem : coords
};
} catch (error) { // parse header
console.error("Errore durante il parsing:", error);
fileProgressBar.value = 0; // Reset in caso di errore
throw error;
}
} // parse VST header
parseLOD(needsReverse) {
const lodHeader = new LODHeader(this.dataView, this.offset, needsReverse);
this.offset += 28; // Size of LODHeader
// Skip texture bounding boxes
this.offset += 24 * this.textureFiles.length;
const patches = [];
for (let i = 0; i < lodHeader.patchNum; i++) {
const patch = this.parsePatch(needsReverse);
patches.push(patch);
}
return {
header: lodHeader,
patches
};
}
parsePatch(needsReverse) {
const patchHeader = new PatchHeader(this.dataView, this.offset, needsReverse);
this.offset += 24; // Size of PatchHeader
const arrays = [];
let pos1 = this.offset;
let pos2 = pos1 + patchHeader.arrayNum * 4;
for (let i = 0; i < patchHeader.arrayNum; i++) {
// Save current position
const currentPos = this.offset;
// Read array length
this.offset = pos1;
let arrayLen = this.dataView.getInt32(this.offset, true);
if (needsReverse) {
arrayLen = ((arrayLen & 0xFF) << 24) |
((arrayLen & 0xFF00) << 8) |
((arrayLen & 0xFF0000) >>> 8) |
((arrayLen & 0xFF000000) >>> 24);
}
pos1 += 4;
// Read vertex indices
this.offset = pos2;
const indices = [];
for (let j = 0; j < arrayLen; j++) {
let index = this.dataView.getInt32(this.offset, true);
if (needsReverse) {
index = ((index & 0xFF) << 24) |
((index & 0xFF00) << 8) |
((index & 0xFF0000) >>> 8) |
((index & 0xFF000000) >>> 24);
}
indices.push(index);
this.offset += 4;
}
pos2 = this.offset;
arrays.push(indices);
}
return {
header: patchHeader,
arrays
};
}
readString(length) {
const bytes = new Uint8Array(this.dataView.buffer, this.offset, length);
let str = '';
for (let i = 0; i < length && bytes[i] !== 0; i++) {
str += String.fromCharCode(bytes[i]);
}
this.offset += length;
return str;
}
} /// class VST parser
function generateOBJ_AI(vstData, startLod, endLod) { /// debug
const vertices = vstData.vertices;
const lods = vstData.lods;
let obj = "";
// Write vertex data
for (let vertex of vertices) {
obj += `v ${vertex.x} ${-vertex.z} ${vertex.y}\n`;
}
// Write texture coordinate data
for (let vertex of vertices) {
obj += `vt ${vertex.tx} ${1 - vertex.ty}\n`;
}
obj += "# Faces\n";
// Write face data for each LOD from startLod to endLod
//for (let lodIndex = startLod; lodIndex <= endLod; lodIndex++) {
lodIndex=1; // debug
const lod = lods[lodIndex]; // debug
for (let patch of lod.patches) {
if (patch.header.pointCloud === 0) {
const textureFile = vstData.textureFiles?.[patch.header.texture];
if (textureFile) {
obj += `# Material: ${textureFile}\n`;
obj += `usemtl mtl_${patch.header.texture}\n`;
obj += `mtllib ${textureFile.replace('.png', '.mtl')}\n`;
}
obj += `g shape_lod${lodIndex}\n`; // Aggiungo il numero del LOD al nome del gruppo
for (let array of patch.arrays) {
obj += "f ";
for (let index of array) {
obj += `${index+1}/${index+1} `;
}
obj += "\n";
}
}
}
//}
return obj;
}
function generateX3D(vstData, startLod, endLod) {
const bbox = vstData.bbox;
const vertices = vstData.vertices;
const lods = vstData.lods;
// Helper to format coordinates for X3D
const formatPoint = (vertex) => `${vertex.x} ${-vertex.z} ${vertex.y}`;
const formatTexCoord = (vertex) => `${vertex.tx} ${1 - vertex.ty}`;
x3d = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN" "http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D profile="CADInterchange">
<head>
<meta name="generator" content="vst2x3d"/>
</head>
<Scene>
<NavigationInfo type='"WALK" "ANY"'/>
<Viewpoint description="Start" position="0.0 0.0 0.0" orientation="1 0 0 3.14"/>`;
// Calculate bounding box center and size
const bboxCenter = {
x: (bbox.xMax + bbox.xMin) / 2,
y: -(bbox.zMax + bbox.zMin) / 2,
z: (bbox.yMax + bbox.yMin) / 2
};
const bboxSize = {
x: (bbox.xMax - bbox.xMin) / 2,
y: (bbox.zMax - bbox.zMin) / 2,
z: (bbox.yMax - bbox.yMin) / 2
};
lods.forEach((lod, lodIndex) => {
currentShape = "";
wireframe = "";
if (( startLod <= lodIndex) && (lodIndex <= endLod)) {
//console.log("Inserting LOD n. ", lodIndex, ", V=", lod.header.vertexNum, ", T=", lod.patches[0].header.arrayNum);
x3d += `\n <Shape id = "PROD_${product_name_no_ext}_LOD_${lodIndex}" bboxCenter="${bboxCenter.x} ${bboxCenter.y} ${bboxCenter.z}" bboxSize="${bboxSize.x} ${bboxSize.y} ${bboxSize.z}">`;
currentShape += `\n <Shape id = "PROD_${product_name_no_ext}_LOD_${lodIndex}" bboxCenter="${bboxCenter.x} ${bboxCenter.y} ${bboxCenter.z}" bboxSize="${bboxSize.x} ${bboxSize.y} ${bboxSize.z}">`;
lod.patches.forEach(patch => {
if (patch.header.pointCloud === 1) {
// Handle point cloud
x3d += '\n <PointSet>\n <Coordinate point="';
currentShape += '\n <PointSet>\n <Coordinate point="';
const points = [];
patch.arrays.forEach(array => {
array.forEach(vertexIndex => {
points.push(formatPoint(vertices[vertexIndex]));
});
});
x3d += points.join(', ');
currentShape += points.join(', ');
x3d += '"/>\n </PointSet>';
currentShape += '"/>\n </PointSet>';
} else {
// Handle trianglestrip
textureOk = false;
if (vstData.textureFiles && vstData.textureFiles[patch.header.texture]) {
finalUrl = vstData.textureFiles[patch.header.texture];
textureOk = true;
} else {
textureOk = false; // redundant, just to add the closing "else"
console.log("Creating x3d file without the missing texture.");
}
// Handle textured triangles
x3d += `\n <Appearance>
<Material backAmbientIntensity='1.0'
backDiffuseColor='1 1 1'
diffuseColor='1 1 1'
transparency='0'/>`;
currentShape += `\n <Appearance>
<Material backAmbientIntensity='1.0'
backDiffuseColor='1 1 1'
diffuseColor='1 1 1'
transparency='0'/>`;
wireframe += `\n <Appearance>
<Material emissiveColor = "1 1 0"/>`;
if (textureOk) {
x3d += `\n <ImageTexture url="` + finalUrl+ `"\n />
<TextureProperties boundaryModeS='REPEAT'
boundaryModeT='REPEAT'
magnificationFilter='NICEST'
minificationFilter='NICEST'\n />`;
currentShape += `\n <ImageTexture url="` + finalUrl+ `"\n />
<TextureProperties boundaryModeS='REPEAT'
boundaryModeT='REPEAT'
magnificationFilter='NICEST'
minificationFilter='NICEST'\n />`;
}
x3d += `\n </Appearance>
<IndexedTriangleStripSet solid='false'
ccw='true'
index="`;
currentShape += `\n </Appearance>
<IndexedTriangleStripSet solid='false'
ccw='true'
index="`;
wireframe += `\n </Appearance>
<IndexedLineSet solid='false'
ccw='true'
index="`;
// Add indices with strip separators
const indices = [];
patch.arrays.forEach((array, arrayIndex) => {
if (arrayIndex > 0) indices.push(-1);
indices.push(...array);
});
x3d += indices.join(' ');
currentShape += indices.join(' ');
wireframe += indices.join(' ');
// Add coordinates
x3d += `">\n <Coordinate point="`;
currentShape += `">\n <Coordinate point="`;
wireframe += `">\n <Coordinate point="`;
const points = [];
for (let i = 0; i <= lod.header.vertMax; i++) {
points.push(formatPoint(vertices[i]));
}
x3d += points.join(', ');
currentShape += points.join(', ');
wireframe += points.join(', ');
x3d += '"\n />';
currentShape += '"\n />';
wireframe += '"\n />';
if (textureOk) {
// Add texture coordinates
x3d += `\n <TextureCoordinate point="`;
currentShape += `\n <TextureCoordinate point="`;
wireframe += `\n <TextureCoordinate point="`;
const texCoords = [];
for (let i = 0; i <= lod.header.vertMax; i++) {
texCoords.push(formatTexCoord(vertices[i]));
}
x3d += texCoords.join(', ');
currentShape += texCoords.join(', ');
wireframe += texCoords.join(', ');
x3d += '"\n />';
currentShape += '"\n />';
wireframe += '"\n />';
}
x3d += '\n </IndexedTriangleStripSet>';
currentShape += '\n </IndexedTriangleStripSet>';
wireframe += '\n </IndexedLineSet>';
x3d += '\n </Shape>';
currentShape += '\n </Shape>';
if (wireframeEnabled) {
x3d += `\n <Shape id = "PROD_${product_name_no_ext}_LOD_${lodIndex}_wireframe" bboxCenter="${bboxCenter.x} ${bboxCenter.y} ${bboxCenter.z}" bboxSize="${bboxSize.x} ${bboxSize.y} ${bboxSize.z}">`;
currentShape += `\n <Shape id = "PROD_${product_name_no_ext}_LOD_${lodIndex}_wireframe" bboxCenter="${bboxCenter.x} ${bboxCenter.y} ${bboxCenter.z}" bboxSize="${bboxSize.x} ${bboxSize.y} ${bboxSize.z}">`;
x3d += wireframe;
}
} // patch cycle, trianglestrip type
}); // patch cycle
if (wireframeEnabled) {
x3d += '\n </Shape>';
currentShape += '\n </Shape>';
}
x3dShapes.push(currentShape);
currentShape="";
} // selected lod
}); // lod cycle
x3d += '\n </Scene>\n</X3D>';
return x3d;
}
const dropArea = document.getElementById('dropArea');
const fileInput = document.getElementById('fileInput');
//const convertBtn = document.getElementById('convertBtn');
const status = document.getElementById('status');
let selectedFile = null;
/*
// moved to main
// Handler per il click sull'area di drop
dropArea.addEventListener('click', () => {
fileInput.click();
});
// Handler per il cambio del file input
fileInput.addEventListener('change', (e) => {
handleFile(e.target.files[0]);
});
// Handlers per il drag and drop
dropArea.addEventListener('dragover', (e) => {
e.preventDefault();
dropArea.classList.add('dragover');
});
dropArea.addEventListener('dragleave', () => {
dropArea.classList.remove('dragover');
});
dropArea.addEventListener('drop', (e) => {
e.preventDefault();
dropArea.classList.remove('dragover');
const files = Array.from(e.dataTransfer.files);
handleFiles(files);
});
*/
// Funzione per gestire i file selezionati
async function handleFiles(files, prodIdControl) {
if (!files || files.length === 0) return;
// Filtra solo i file .vst
const vstFiles = files.filter(file => file.name.toLowerCase().endsWith('.vst'));
const imgFiles = files.filter(file => file.name.toLowerCase().endsWith('.img'));
const lblFiles = files.filter(file => file.name.toLowerCase().endsWith('.lbl'));
if (vstFiles.length === 0) {
showStatus('Per favore seleziona almeno un file .vst', 'error');
return;
}
if (vstFiles.length !== files.length) {
showStatus(`Trovati ${vstFiles.length} file .vst su ${files.length} file selezionati`, 'warning');
}
selectedFiles = vstFiles;
//convertBtn.disabled = false;
// Mostra la lista dei file selezionati
const fileList = vstFiles.map(file => file.name).join(', ');
console.log("fileList:", fileList);
showStatus(`File selezionati: ${fileList}`, 'success');
// Ottieni la barra di progresso e resetta il valore
const progressBar = document.getElementById('progressBar');
progressBar.value = 0;
progressBar.max = vstFiles.length;
// Processa i file in sequenza
for (let i = 0; i < vstFiles.length; i++) {
try {
console.log("Calling processor",imgFiles);;
await processFile(vstFiles[i], i, prodIdControl, imgFiles, lblFiles); // <<<<<<<<<<<<<<<<<<------------------- main process
progressBar.value = i + 1; // Aggiorna la barra di progresso
showStatus(`Completato il file ${i + 1} di ${vstFiles.length}: ${vstFiles[i].name}`, 'success');
document.getElementById("spnLoaded").innerHTML += vstFiles[i].name+ "<br>";
} catch (error) {
showStatus(`Errore nel processare il file ${vstFiles[i].name}: ${error.message}`, 'error');
// break; // Decommentare per fermarsi al primo errore
}
}
// Mostra il completamento al termine
showStatus('Elaborazione completata!', 'success');
}
async function processFile(file, index, prodIdControl, imgFiles, lblFiles) {
console.log("Avvia la conversione per "+ file.name, imgFiles,lblFiles);
prodIdControl.value = file.name.split(".")[0];
await startConversion(file, index, prodIdControl, imgFiles, lblFiles); // <<<<<<<<<<<<<<<<<<------------------- conversion process
console.log("Fatto.");
}
async function startConversion (selectedFile, index, prodIdControl, imgFiles, lblFiles) { // <<<<<<<<<<<<<<<<<<------------------- conversion function
console.log("Conversion started",prodIdControl);
showStatus("Conversion started", 'success');
product_name_no_ext = prodIdControl.value;