-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVTS2X3D-AI-003.html
827 lines (699 loc) · 30 KB
/
VTS2X3D-AI-003.html
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
<strong></strong><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VST to X3D Converter</title>
<style>
body {
font-family: system-ui, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.upload-area {
border: 2px dashed #ccc;
border-radius: 4px;
padding: 2rem;
text-align: center;
margin: 1rem 0;
background: #fafafa;
cursor: pointer;
}
.upload-area.dragover {
border-color: #4299e1;
background: #ebf8ff;
}
.button {
background: #4299e1;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
}
.button:hover {
background: #3182ce;
}
.button:disabled {
background: #a0aec0;
cursor: not-allowed;
}
#status {
margin-top: 1rem;
padding: 1rem;
border-radius: 4px;
}
.error {
background: #fff5f5;
color: #c53030;
border: 1px solid #feb2b2;
}
.success {
background: #f0fff4;
color: #2f855a;
border: 1px solid #9ae6b4;
}
</style>
</head>
<body>
<div class="container">
<h1>VST to X3D Converter</h1>
<p>Upload a .vst file to convert it to X3D format.</p>
<div id="dropArea" class="upload-area">
<p>Drag and drop a .vst file here or click to select</p>
<input type="file" id="fileInput" accept=".vst" style="display: none">
</div>
<input type="text" id = "txtProductId" name="txtProductId" value = "2n292378085vilb128f0006l0m1" style="width:250px;">
<button id="convertBtn" class="button" >Convert to X3D</button>
<div id="status" style="display: none;"></div>
</div>
<script>
//
// JPG images https://pds-imaging.jpl.nasa.gov/data/mer/spirit/mer2no_0xxx/browse/sol1869/edr/
// IMG images https://pds-imaging.jpl.nasa.gov/data/mer/spirit/mer2no_0xxx/data/sol1869/edr/
// VST files: https://pds-imaging.jpl.nasa.gov/data/mer/spirit/mer2mw_0xxx/data/navcam/site0137/
// JPG images https://planetarydata.jpl.nasa.gov/img/data/mer2-m-navcam-5-disparity-ops-v1.0/mer2no_0xxx/browse/sol1869/rdr/
// IMG images https://planetarydata.jpl.nasa.gov/img/data/mer2-m-navcam-5-disparity-ops-v1.0/mer2no_0xxx/data/sol1869/rdr/
https://planetarydata.jpl.nasa.gov/w10n/mer2-m-navcam-5-disparity-ops-v1.0/mer2no_0xxx/data/sol1869/rdr/
// VST files https://planetarydata.jpl.nasa.gov/img/data/mer2-m-hazcam-5-mesh-ops-v1.0/mer2mw_0xxx/
// VST files https://planetarydata.jpl.nasa.gov/img/data/mer/spirit/mer2mw_0xxx/
// VST files https://planetarydata.jpl.nasa.gov/w10n/mer2-m-hazcam-5-wedge-ops-v1.0/mer2mw_0xxx/
// cassini/cassini_orbiter/coiss_2015/data/1503245366_1503271060/N1503245366_1.IMG
// mer/mer2ho_0xxx/data/sol1869/rdr/
/*
Root folders nomenclature:
mer2mw_0xxx 3d Meshes and wedges
mer2no_0xxx Navigation Camera (EDR & RDR) images (JPG and IMG)
mer2om_0xxx Mosaic images
mer2po_0xxx Panoromic Camera (EDR & RDR) images (JPG and IMG)
mer2pc_0xxx Panoromic Camera Science Products (EDRs) images (JPG and IMG)
3d nomenclature:
points = vertices
triangle corner vertices = facets
Wedge = NASA stereo pair?
*/
BASE_IMG_URL = "https://planetarydata.jpl.nasa.gov/w10n/mer2-m-navcam-5-disparity-ops-v1.0/mer2no_0xxx/";
IMG_RAW_FOLDER = "data/";
IMG_JPG_FOLDER = "browse/";
PRODUCT_FOLDER = "sol1869/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;
base_texture_folder = BASE_IMG_URL + IMG_JPG_FOLDER + PRODUCT_FOLDER;
proxyURL = "https://win98.altervista.org/space/exploration/myp.php?pass=miapass&mode=native&url=";
const graphicalProducts = [
"RAD",
"RAL",
"RSD",
"RSL",
"EFF",
"ESF",
"EDN",
"ILF",
"ILL",
"FFL",
"MRD",
"MRL",
"RFD",
"RFL",
"IOF",
"IOL",
"IFF",
"IFL",
"IFS",
"CCD",
"CCL",
"CFD",
"CFL"
];
// 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() {
console.log("HEADER");
// Parse header
const header = new VSTHeader(this.dataView, this.offset);
console.log("HEADER",header);
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');
}
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++) {
// Leggi 2048 byte direttamente da DataView come array di byte
const textureBytes = new Uint8Array(this.dataView.buffer, this.offset, 2048);
// Converti i byte in stringa per poter ottenere il nome della texture
const textureRef = String.fromCharCode.apply(null, textureBytes);
// Ottieni il nome del file di texture e applica le modifiche necessarie
let textureName = textureRef.substring(10, 37) + '.img.jpg';
console.log("HEADER - textureName:", textureName);
///// Found a suitable product, i.e. a real image:
let textureUrlLeft = textureName.substring(0, 11);
let textureUrlRight = textureName.substring(14);
let siteNumberCoded = textureName.substr(14,2); // example: b1 = site 137, coded as "site037" in folder name
let siteNumberString = siteCodeToString(siteNumberCoded);
console.log("siteNumberString=", siteNumberString);
let solNumber = await getSolNumberFromLabel(textureRef.substring(10, 37), siteNumberString);
console.log(siteNumberString, solNumber);
let textureBASE64 = "error";
for (let productIndex = 0; (( productIndex < graphicalProducts.length) && (textureBASE64 === "error")); productIndex++) {
let textureUrlProduct = graphicalProducts[productIndex];
console.log("Looking for product ", textureUrlProduct, " in folder ", base_texture_folder);
let textureUrl = base_texture_folder + textureUrlLeft + textureUrlProduct + textureUrlRight;
textureUrl = textureUrl.toLowerCase();
textureBASE64 = await urlToBase64(textureUrl);
if (textureBASE64 !== "error") {
console.log("FOUND!");
}
};
if (textureBASE64 === "error") {
console.log("Could not found texture in folder " + base_texture_folder);
}
// Aggiungi textureName all'array textureFiles
this.textureFiles.push(textureBASE64);
// Aggiorna l'offset per la prossima texture
this.offset += 2048;
}
// Skip coordinate system
this.offset += 4096;
// Read vertices
console.log("HEADER - vertices: ",header.vertexNum);
for (let i = 0; i < header.vertexNum; i++) {
const vertex = new Vertex(this.dataView, this.offset, needsReverse);
this.vertices.push(vertex);
this.offset += 20; // Size of Vertex
}
// Process LODs
console.log("HEADER - LODs: ",header.lodNum);
const lods = [];
for (let i = 0; i < header.lodNum; i++) {
const lod = this.parseLOD(needsReverse);
lods.push(lod);
}
return {
header,
bbox,
textureFiles: this.textureFiles,
vertices: this.vertices,
lods
};
}
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;
}
}
function generateX3D(vstData, whichLod) {
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}`;
let 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) => {
if (lodIndex >= whichLod) {
x3d += `\n <Shape 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="';
const points = [];
patch.arrays.forEach(array => {
array.forEach(vertexIndex => {
points.push(formatPoint(vertices[vertexIndex]));
});
});
x3d += points.join(', ');
x3d += '"/>\n </PointSet>';
} else {
finalUrl = /*proxyURL + encodeURIComponent(*/vstData.textureFiles[patch.header.texture]/*)*/;
// Handle textured triangles
x3d += `\n <Appearance>
<ImageTexture url="` + finalUrl+ `"/>
</Appearance>
<IndexedTriangleStripSet 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(' ');
// Add coordinates
x3d += `">\n <Coordinate point="`;
const points = [];
for (let i = 0; i <= lod.header.vertMax; i++) {
points.push(formatPoint(vertices[i]));
}
x3d += points.join(', ');
x3d += '"/>';
// Add texture coordinates
x3d += `\n <TextureCoordinate point="`;
const texCoords = [];
for (let i = 0; i <= lod.header.vertMax; i++) {
texCoords.push(formatTexCoord(vertices[i]));
}
x3d += texCoords.join(', ');
x3d += '"/>\n </IndexedTriangleStripSet>';
}
});
x3d += '\n </Shape>';
}
});
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;
// 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 file = e.dataTransfer.files[0];
handleFile(file);
});
// Funzione per gestire il file selezionato
function handleFile(file) {
if (!file) return;
if (!file.name.toLowerCase().endsWith('.vst')) {
showStatus('Per favore seleziona un file .vst', 'error');
return;
}
selectedFile = file;
convertBtn.disabled = false;
showStatus(`File selezionato: ${file.name}`, 'success');
alert("OK, local file selected.");
txtProductId.value = file.name.replace(".vst","").replace(".VST","");
}
convertBtn.addEventListener('click', async () => {
product_name_no_ext = document.getElementById("txtProductId").value; // 2n292377885vilb126f0006l0m1 = small vst for testing, sol 1870
base_VST_filename = BASE_VST_URL + VST_CAMERA_FOLDER + VST_FOLDER_SITE_NAME + product_name_no_ext.toLowerCase();
let txtVSTurl = base_VST_filename + ".vst"; // DEBUG
let arrayBuffer;
// try {
if (selectedFile) {
console.log("Converting selected file:", selectedFile);
// Se il file � selezionato dall'utente
arrayBuffer = await selectedFile.arrayBuffer();
} else if (txtVSTurl) {
console.log("Downloading file from url and converting:",txtVSTurl);
// Se esiste un URL in txtVSTurl, scarica il file usando il proxy
const proxyURL = "http://win98.altervista.org/space/exploration/myp.php?pass=miapass&mode=native&url=";
response = await fetch(proxyURL + encodeURIComponent(txtVSTurl));
if (!response.ok) throw new Error("Errore nel download del file da URL.");
arrayBuffer = await response.arrayBuffer();
} else {
showStatus("Nessun file selezionato o URL fornito.", "error");
return;
}
console.log("Starting VST parsing...");
// Parsing e generazione del contenuto X3D
const parser = new VSTParser(arrayBuffer);
const vstData = await parser.parse();
console.log("vstData=",vstData);
console.log("textures=",vstData.textureFiles);
// Invert Z coordinate (in MER system the positive vertical axis points to ground):
const invertedVertices = vstData.vertices.map(item => ({
...item,
z: -item.z
}));
vstData.vertices = invertedVertices;
const x3dContent = generateX3D(vstData, 1); // DEBUG last lod = higher res
// Crea e scarica il file X3D
const blob = new Blob([x3dContent], { type: 'model/x3d+xml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
console.log("Saving to ", product_name_no_ext + '.x3d');
a.download = selectedFile ? selectedFile.name.replace('.vst', '.x3d') : product_name_no_ext + '.x3d';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showStatus('Conversione completata con successo!', 'success');
//} catch (error) {
// showStatus(`Errore durante la conversione: ${error.message}`, 'error');
// }
});
// Funzione per mostrare lo status
function showStatus(message, type) {
status.textContent = message;
status.style.display = 'block';
status.className = type;
}
async function urlToBase64(imageUrl) {
finalUrl = proxyURL + encodeURIComponent(imageUrl);
try {
// Scarica l'immagine come blob
const response = await fetch(finalUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
// Verifica che il MIME type sia JPEG
if (blob.type !== 'image/jpeg') {
return ("error");
}
// Determina il tipo MIME corretto
const mimeType = blob.type;//'image/jpeg';
// Converti il blob in base64
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64String = reader.result;
const base64Data = base64String.split(',')[1];
resolve(`data:${mimeType};base64,${base64Data}`);
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (error) {
throw new Error(`Errore durante la conversione dell'immagine: ${error.message}`);
}
}
function siteCodeToString(code) {
console.log("Decoding site couple ", code);
if (code.length !== 2) {
throw new Error("Il codice deve essere una stringa di due caratteri.");
}
const firstChar = code[0];
const secondChar = code[1];
// Caso 1: numerico puro ("00" - "99")
if (!isNaN(firstChar) && !isNaN(secondChar)) {
return parseInt(code, 10);
}
// Caso 2: alfanumerico ("A0" - "ZZ")
const alphabetOffset = 'A'.charCodeAt(0); // Offset per calcolare il valore delle lettere
const firstValue = firstChar.charCodeAt(0) - alphabetOffset;
let secondValue;
if (isNaN(secondChar)) {
// Se il secondo carattere è una lettera
secondValue = secondChar.charCodeAt(0) - alphabetOffset + 10;
} else {
// Se il secondo carattere è un numero
secondValue = parseInt(secondChar, 10);
}
// Formula per calcolare l'intervallo corretto (da 100 in poi)
return 100 + firstValue * 36 + secondValue;
}
async function getSolNumberFromLabel(textureName, siteNumberString) {
let fileName = txtProductId.value + ".lbl"
VSTurl = BASE_VST_URL + VST_CAMERA_FOLDER + "site0" + siteNumberString + "/" + fileName ; // DEBUG: valid only up to site 0138, for Spirit!!
console.log("getSolNumberFromLabel - looking for label: ", VSTurl);
finalUrl = proxyURL + encodeURIComponent(VSTurl);
try {
// Scarica file come blob
const response = await fetch(finalUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
// Verifica che il MIME type sia JPEG
// if (blob.type !== 'image/jpeg') {
// return ("error");
// }
console.log("MIME:",blob.type);
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
VSTlabel = reader.result;
console.log(VSTlabel);
solNumber = extractSol(VSTlabel);
resolve(solNumber);
};
reader.onerror = reject;
reader.readAsText(blob);
});
} catch (error) {
throw new Error(`Errore durante la conversione dell'immagine: ${error.message}`);
}
}
function extractSol(labelContent) {
const match = labelContent.match(/PLANET_DAY_NUMBER\s*=\s*(\d+)/);
if (match) {
return parseInt(match[1], 10);
} else {
throw new Error("PLANET_DAY_NUMBER non trovato nel contenuto fornito.");
}
}
</script>
</body>
</html>