-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathwebglripper.js
More file actions
1462 lines (1202 loc) · 43.3 KB
/
Copy pathwebglripper.js
File metadata and controls
1462 lines (1202 loc) · 43.3 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
const OBJUtils = {
DrawModes: {
"POINTS": 0,
"LINES": 1,
"LINE_STRIP": 2,
"LINE_LOOP": 3,
"TRIANGLES": 4,
"TRIANGLE_STRIP": 5,
"TRIANGE_FAN": 6
},
/* Used to store a texture for use in OBJModel */
OBJTexture: class {
constructor(filename, url, type = "map_Kd") {
this._URL = url;
this._FILENAME = filename;
this._TYPE = type;
}
getTexString() {
return `${this._TYPE} ${this._FILENAME}.png`;
}
},
OBJColor: class {
r = 0;
g = 0;
b = 0;
constructor(r, g, b, a) {
this.r = r;
this.g = g;
this.b = b;
}
toString() {
return `${this.r} ${this.g} ${this.b}`;
}
},
/* Used to store color info about the primitive */
OBJColTexture: class {
constructor(filename, color) {
this._COLOR = color;
this._FILENAME = filename;
}
getTexString() {
return `Kd ${this._COLOR.toString()}`;
}
},
/* Used to store indices and how to draw them */
OBJPrimitive: class {
constructor(mode, indices) {
this._MODE = mode;
this._INDICES = indices;
}
},
/* OBJ Creation */
OBJModel: class {
// Primitives = [] // Array of OBJPrimitive's
// Vertices = [] // Array of Vertices
// Normals = [] // Array of Normals
// UVs = [] // Array of UVs
// Textures = [] // Array of OBJTexture or OBJColTexture for the obj
constructor(_Primitives, _Vertices, _Normals, _UVs, _Textures, _Name) {
this.vertex = _Vertices;
this.normal = _Normals;
this.uv = _UVs;
this.primitives = _Primitives;
this.textures = _Textures;
this.name = _Name || `rip${Math.random()}`;
}
transform(matrix) {
LogToParent("Transforming vertices: ", this.vertex.length/3);
for (let vI = 0; vI < this.vertex.length; vI += 3) {
let v = [this.vertex[vI + 0], this.vertex[vI + 1], this.vertex[vI + 2]];
let transformed = multiplyMatrixAndPoint(matrix, v);
this.vertex[vI + 0] = transformed[0];
this.vertex[vI + 1] = transformed[1];
this.vertex[vI + 2] = transformed[2];
}
}
BuildOBJ() {
let obj = '';
obj += `mtllib ${this.name}.mtl\n`; // Set model library to use
obj += `o ${this.name}\n`; // Define model name
for (let vI = 0; vI < this.vertex.length; vI += 3) {
obj += 'v ';
for (let vJ = 0; vJ < 3; ++vJ)
obj += this.vertex[vI + vJ] + ' ';
obj += '\n';
} // Write all vertex positions into the obj file
for (let nI = 0; nI < this.normal.length; nI += 3) {
obj += 'vn ';
for (let nJ = 0; nJ < 3; ++nJ)
obj += this.normal[nI + nJ] + ' ';
obj += '\n';
} // Write all normal positions into the obj file
for (let uI = 0; uI < this.uv.length; uI += 2) {
obj += 'vt ';
for (let uJ = 0; uJ < 2; ++uJ)
obj += this.uv[uI + uJ] + ' ';
obj += '\n';
} // Write all Texture Coords into the obj file
obj += `usemtl ${this.name}\n`; // Specify to start using the mtl lib for the indices below
obj += 's on \n'; // Enable Smooth Shading
let hasNormals = this.normal.length != 0;
let hasUVs = this.uv.length != 0;
let primitive = this.primitives;
switch (primitive._MODE) {
case OBJUtils.DrawModes["TRIANGLES"]:
case OBJUtils.DrawModes["TRIANGLE_STRIP"]:
let isStrip = (primitive._MODE == OBJUtils.DrawModes["TRIANGLE_STRIP"]);
for (let j = 0; j + 2 < primitive._INDICES.length; !isStrip ? j += 3 : j++) {
obj += 'f ';
let order = [0, 1, 2];
if (isStrip && (j % 2 == 1)) {
order = [0, 2, 1];
}
for (let k = 0; k < 3; ++k) {
let faceNumber = primitive._INDICES[j + order[k]] + 1;
obj += faceNumber;
if (hasNormals || hasUVs) {
obj += '/';
if (hasUVs)
obj += faceNumber;
if (hasNormals)
obj += `/${faceNumber}`;
}
obj += ' ';
}
obj += '\n';
}
break;
} // Write indices into obj file
return obj;
}
BuildMTL() {
let mtl = '';
mtl += `newmtl ${this.name}\n`;
this.textures.forEach(function (texture) {
mtl += `${texture.getTexString()}\n`;
});
return mtl;
}
}
} // OBJ File Namespace
class Downloader {
static async DownloadImage(filename, url) {
const a = document.createElement("a");
a.href = await this.toDataURL(url);
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
static async DownloadBlob(filename, blob) {
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
static DownloadString(filename, str) {
var textblob = new Blob([str], { type: 'text/plain' });
var link = document.createElement('a');
link.download = filename;
link.innerHTML = 'Download File';
link.href = window.URL.createObjectURL(textblob);
link.onclick = function (e) { document.body.removeChild(e.target); };
link.style.display = 'none';
document.body.appendChild(link);
link.click();
}
static toDataURL(url) {
return fetch(url).then((response) => {
return response.blob();
}).then(blob => {
return URL.createObjectURL(blob);
});
}
} // Downloader Class
let _window = window;
// Create config object
_window.WEBGLRipperSettings = {
// Settings
hasLoadedSettings: false,
CaptureSceneKeyCode: 45, // Insert Key
CaptureTexturesKeyCode: 45, // Insert Key
defaultTexWidth: 4096,
defaultTexHeight: 4096, // As we can't always retrieve the width and height of a texture, we must have a default size in that case.
shouldUnFlipTex: true, // If we should unflip the textures
doModelViewMatrix: false,
isDebug: true, // Debug Printing
isDoShaderCalc: false, // Force the shader to do calculations, useful for grabbing specific frames of vertex animations.
shouldDownloadZip: false, // Download all the model assets into a zip file.
minimumClears: 1, // Minimum amount of clears
};
let LogToParent = function () {
if (!_window.WEBGLRipperSettings.isDebug)
return;
_window.console.log('[WebGLRipper]', ...arguments);
};
// https://stackoverflow.com/questions/5629684/how-can-i-check-if-an-element-exists-in-the-visible-dom
let doesElementExist = function(element) {
return typeof(element) != 'undefined' && element != null;
};
let loadWebGLRipperSettings = function() {
if(!doesElementExist(document.getElementById("webgl_ripper_settings"))) {
LogToParent("Settings failed to load!");
return;
}
if(_window.WEBGLRipperSettings.hasLoadedSettings) {
LogToParent("Settings already loaded!");
return;
}
let hiddenSettings = document.getElementById("webgl_ripper_settings");
let settings = JSON.parse(hiddenSettings.textContent);
LogToParent("Loaded Settings: ", settings);
_window.WEBGLRipperSettings.defaultTexWidth = parseInt(settings.default_texture_res.split("x")[0]) || 4096;
_window.WEBGLRipperSettings.defaultTexHeight = parseInt(settings.default_texture_res.split("x")[1]) || 4096;
_window.WEBGLRipperSettings.isDoShaderCalc = settings.do_shader_calc;
_window.WEBGLRipperSettings.isDebug = settings.is_debug_mode;
_window.WEBGLRipperSettings.shouldUnFlipTex = settings.unflip_textures;
_window.WEBGLRipperSettings.doModelViewMatrix = settings.do_model_view_matrix;
_window.WEBGLRipperSettings.shouldDownloadZip = settings.should_download_zip;
_window.WEBGLRipperSettings.minimumClears = parseInt(settings.minimum_clears);
_window.WEBGLRipperSettings.hasLoadedSettings = true;
};
_window.RIPPERS = [];
_window.MODELS = [];
document.addEventListener('keydown', function (event) {
if (event.keyCode == _window.WEBGLRipperSettings.CaptureSceneKeyCode && !event.shiftKey) {
LogToParent("Starting capturing...");
for(let i = 0; i < _window.RIPPERS.length; i++) {
LogToParent("Started capture on: ", _window.RIPPERS[ i ]);
_window.RIPPERS[ i ]._StartCapturing = true;
}
}
});
function resizeArrayBuffer(originalBuffer, newByteSize) {
if(originalBuffer.byteLength > newByteSize){
throw new Error("Can't resize to a smaller array");
}
if(originalBuffer.detached)
return; // TODO: Fix
const resizedBuffer = new ArrayBuffer(newByteSize);
const originalView = new Uint8Array(originalBuffer);
const resizedView = new Uint8Array(resizedBuffer);
resizedView.set(originalView);
return resizedBuffer;
}
// https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Matrix_math_for_the_web
function multiplyMatrixAndPoint(matrix, point) {
let c0r0 = matrix[0], c1r0 = matrix[1], c2r0 = matrix[2], c3r0 = matrix[3];
let c0r1 = matrix[4], c1r1 = matrix[5], c2r1 = matrix[6], c3r1 = matrix[7];
let c0r2 = matrix[8], c1r2 = matrix[9], c2r2 = matrix[10], c3r2 = matrix[11];
let c0r3 = matrix[12], c1r3 = matrix[13], c2r3 = matrix[14], c3r3 = matrix[15];
let x = point[0];
let y = point[1];
let z = point[2];
let w = 1;
let resultX = x * c0r0 + y * c0r1 + z * c0r2 + w * c0r3;
let resultY = x * c1r0 + y * c1r1 + z * c1r2 + w * c1r3;
let resultZ = x * c2r0 + y * c2r1 + z * c2r2 + w * c2r3;
return [resultX, resultY, resultZ];
}
class WebGLRipperWrapper {
_StartCapturing = false;
_IsEnabled = true;
_IsWebGL2 = false;
_GLViewport = { x: 0, y: 0, width: 0, height: 0 };
_GLContext = null;
_GLState = new Map();
_GLBuffers = new Map();
_GLActiveTextureIndex = 0;
_GLCurrentBoundTexture = null;
_GLTextures = new Map();
_GLAllTextures = [];
_GLCurrentUVS = [];
_GLCurrentUVIndex = -1;
_GLCurrentNormals = [];
_GLCurrentNormalIndex = -1;
_GLCurrentVertices = [];
_GLCurrentVertexIndex = -1;
_GLCurrentAttribIndex = 0;
_GLCurrentAttrib = [];
_GLCurrentAttribEnabled = [];
_ClearCount = 0;
_CurrentModels = [];
_TextureCache = new Map();
_isCapturing = false;
_needsToReset = false;
_AttribTypeEnum = {
VERTEX: 0,
NORMAL: 1,
UVS: 2
};
constructor(gl) {
this._GLContext = gl;
}
HelperFunc_GetDataURIFromWebGLTexture(gl, webglTexture, texWidth, texHeight, flip = true) {
let fb = gl.createFramebuffer();
// make this the current frame buffer
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
// attach the texture to the framebuffer.
gl.framebufferTexture2D(
gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D, webglTexture, 0);
// check if you can read from this type of texture.
let canRead = (gl.checkFramebufferStatus(gl.FRAMEBUFFER) == gl.FRAMEBUFFER_COMPLETE);
if (!canRead) {
// Unbind the framebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return null;
}
var pixels = new Uint8Array(texWidth * texHeight * 4);
// read the pixels
gl.readPixels(0, 0, texWidth, texHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
// Unbind the framebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
if (flip) {
// Now do pixel manipulation to make it right side up -- https://stackoverflow.com/questions/41969562/how-can-i-flip-the-result-of-webglrenderingcontext-readpixels
var halfHeight = texHeight / 2 | 0; // the | 0 keeps the result an int
var bytesPerRow = texWidth * 4;
// make a temp buffer to hold one row
var temp = new Uint8Array(texWidth * 4);
for (var y = 0; y < halfHeight; ++y) {
var topOffset = y * bytesPerRow;
var bottomOffset = (texHeight - y - 1) * bytesPerRow;
// make copy of a row on the top half
temp.set(pixels.subarray(topOffset, topOffset + bytesPerRow));
// copy a row from the bottom half to the top
pixels.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow);
// copy the copy of the top half row to the bottom half
pixels.set(temp, bottomOffset);
}
}
let canvas = document.createElement("canvas");
canvas.width = texWidth;
canvas.height = texHeight;
let ctx = canvas.getContext('2d');
let arr = new Uint8ClampedArray(pixels);
let imgData = new ImageData(arr, texWidth, texHeight);
ctx.putImageData(imgData, 0, 0);
return canvas.toDataURL("image/png");
}
HelperFunc_GetAttribValueType(attrib) {
let vertexNames = [
'position',
'vertex',
'avertexposition',
's_attribute_0',
'avertex',
'vertex_position', // Playcanvas.js
'aposition', // Playcanvas.js
'vposition', // imvu.com
'vertexposition', // Raylib
'a_pos' // nick.com
];
let normalNames = [
'avertexnormal',
'normal',
's_attribute_1',
'vertex_normal', // Playcanvas.js
'vnormal', // imvu.com
'vertexnormal', // Raylib
];
let uvNames = [
'uv',
'texcoord',
'texcoords',
'texcoord0',
'atexturecoord',
'vertex_texcoord0', // Playcanvas.js
'vtexcoord', // imvu.com
'vertextexcoord', // Raylib
'a_uv', // nick.com
];
let attribName = attrib.name.toLowerCase();
if (vertexNames.includes(attribName))
return this._AttribTypeEnum.VERTEX;
if (normalNames.includes(attribName))
return this._AttribTypeEnum.NORMAL;
if (uvNames.includes(attribName))
return this._AttribTypeEnum.UVS;
return -1;
}
HelperFunc_IsPossibleTextureUniform(texname) {
const textureMap = new Map();
// Diffuse / Ambient
textureMap.set('map' , 'map_Kd');
textureMap.set('usampler' , 'map_Kd');
textureMap.set('texture' , 'map_Kd');
textureMap.set('bonesampler' , 'map_Kd');
textureMap.set('bonetexture' , 'map_Kd');
textureMap.set('albedosampler' , 'map_Kd');
textureMap.set('source' , 'map_Kd');
textureMap.set('u_texture' , 'map_Kd');
textureMap.set('texture_envatlas', 'map_Kd');
// classic.minecraft.net
textureMap.set("diffusesampler", 'map_Kd');
textureMap.set("ambientsampler", 'map_Kd');
for (let t = 0; t < 32; t++)
textureMap.set(`texture${t}`,'map_Kd');
// Normals
textureMap.set('normalmap', 'norm'); /* PBR rendering */
// Roughness
textureMap.set('roughnessmap', 'map_Pr'); // three.js
if(!textureMap.has(texname.toLowerCase())) {
LogToParent("Not a known texture type: ", texname);
return null;
}
return textureMap.get(texname.toLowerCase());
}
HelperFunc_GetCurrentProgram(self, gl) {
return gl.getParameter(gl.CURRENT_PROGRAM);
}
/* Used for debugging */
HelperFunc_DownloadTextureAtLoc(self, gl, loc) {
/* See if a texture is bound to that slot */
let tex = self._GLTextures.get(loc);
if (tex == undefined || !tex) {
LogToParent("No Texture found in slot: ", loc);
return;
}
let texWidth = tex.width || _window.WEBGLRipperSettings.defaultTexWidth;
let texHeight = tex.height || _window.WEBGLRipperSettings.defaultTexHeight;
let uri = self.HelperFunc_GetDataURIFromWebGLTexture(gl, tex, texWidth, texHeight, _window.WEBGLRipperSettings.shouldUnFlipTex);
if (uri == null) {
LogToParent("Recieved null texture!");
return;
}
let objTexture = new OBJUtils.OBJTexture("tex_" + self._CurrentModels.length, uri);
Downloader.DownloadImage(objTexture._FILENAME, objTexture._URL);
LogToParent("Recieved texture, Sampler Location: ", loc, ", WebGL Texture Object: ", tex);
}
HelperFunc_GetModelMatrix(self, gl) {
let uniformData = self.readUniformData(gl);
LogToParent("Current Uniform Data: ", uniformData);
let _CurrentProgram = self.HelperFunc_GetCurrentProgram(self, gl);
let modelMatrix = null;
let modelMatrixs = [
"modelviewmatrix", // three.js
"modelmatrix",
"world",
"matrix_model"
];
uniformData.forEach(uniform => {
if (modelMatrixs.includes(uniform.name.toLowerCase())) {
var loc = gl.getUniformLocation(_CurrentProgram, uniform.name);
if(!loc) {
return;
}
modelMatrix = gl.getUniform(_CurrentProgram, loc);
LogToParent("Recieved modelMatrix: ", modelMatrix);
}
});
return modelMatrix;
}
HelperFunc_GetAllTextures(self, gl) {
let textures = [];
let uniformData = self.readUniformData(gl);
LogToParent("Current Uniform Data: ", uniformData);
let _CurrentProgram = self.HelperFunc_GetCurrentProgram(self, gl);
uniformData.forEach(uniform => {
if (uniform.type != gl.SAMPLER_2D)
return;
let texType = self.HelperFunc_IsPossibleTextureUniform(uniform.name);
if (texType === null)
return;
/* Get the sampler location of the texture */
var loc = gl.getUniformLocation(_CurrentProgram, uniform.name);
/* Read the location of the webgl texture slot from the sampler */
let samplerLocation = gl.getUniform(_CurrentProgram, loc);
/* Make sure it's a texture slot */
if (samplerLocation < 0 || samplerLocation > 31) {
LogToParent("Sampler location out of bounds: ", samplerLocation);
return;
}
/* See if a texture is bound to that slot */
let tex = self._GLTextures.get(samplerLocation);
if (tex == undefined || !tex) {
LogToParent("No Texture found in slot: ", samplerLocation);
return;
}
if (self._TextureCache.get(tex)) {
textures.push(self._TextureCache.get(tex));
LogToParent("Texture already in cache");
return;
}
let texWidth = tex.width || _window.WEBGLRipperSettings.defaultTexWidth;
let texHeight = tex.height || _window.WEBGLRipperSettings.defaultTexHeight;
let uri = self.HelperFunc_GetDataURIFromWebGLTexture(gl, tex, texWidth, texHeight, _window.WEBGLRipperSettings.shouldUnFlipTex);
if (uri == null) {
LogToParent("Recieved null texture!");
return;
}
// Will not work on http servers :(
let texName = crypto.randomUUID();
let objTexture = new OBJUtils.OBJTexture(texName, uri, texType);
self._TextureCache.set(tex, objTexture);
textures.push(objTexture);
LogToParent("Recieved texture, Sampler Location: ", samplerLocation, ", WebGL Texture Object: ", tex, ", With texture type: ", texType);
});
return textures;
}
HelperFunc_SizeOfType(self, gl, glType) {
switch (glType) {
case gl.BYTE:
case gl.UNSIGNED_BYTE:
return 1;
case gl.SHORT:
case gl.UNSIGNED_SHORT:
return 2;
default:
case gl.FLOAT:
return 4;
}
return 1;
}
HelperFunc_UpdateAllAttributes(self, gl) { // Got help from: https://github.com/benvanik/WebGL-Inspector/blob/c5f961dba261cbd94d9b3ff3ddbaf8b7d3bf5ef9/core/ui/shared/BufferPreview.js#L191
let attribData = self.readAttribData(gl);
attribData.forEach(function (attr) {
if (!self._GLCurrentAttribEnabled[attr.loc])
return;
let attribType = self.HelperFunc_GetAttribValueType(attr);
if(attribType < 0) {
LogToParent("Unknown Attrib Type: ", attr);
return;
}
let _bufferData = self.getBufferDataFromBuffer(self, gl.getVertexAttrib(attr.loc, gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING));
if (!_bufferData || _bufferData.byteLength <= 0)
return;
let bufferData = [];
// TODO: Improve the actual capture :/
// Fix: https://github.com/Rilshrink/WebGLRipper/issues/30
//let vAttribData = self._GLCurrentAttrib[attr.loc];
let vAttribData = {
size: gl.getVertexAttrib(attr.loc, gl.VERTEX_ATTRIB_ARRAY_SIZE),
type: gl.getVertexAttrib(attr.loc, gl.VERTEX_ATTRIB_ARRAY_TYPE),
stride: gl.getVertexAttrib(attr.loc, gl.VERTEX_ATTRIB_ARRAY_STRIDE),
offset: gl.getVertexAttribOffset(attr.loc, gl.VERTEX_ATTRIB_ARRAY_POINTER),
normalized: gl.getVertexAttrib(attr.loc, gl.VERTEX_ATTRIB_ARRAY_NORMALIZED),
};
if(vAttribData == null) {
LogToParent("Missing attrib data at location: ", attr.loc);
return;
}
LogToParent("Got vAttribData: ", vAttribData, "Along with attr: ", attr);
const SizeArrayMap = {
[gl.BYTE]: 1 * vAttribData.size,
[gl.UNSIGNED_BYTE]: 1 * vAttribData.size,
[gl.SHORT]: 2 * vAttribData.size,
[gl.UNSIGNED_SHORT]: 2 * vAttribData.size,
[gl.FLOAT]: 4 * vAttribData.size
};
let byteAdvance = SizeArrayMap[vAttribData.type];
let typeSize = byteAdvance / vAttribData.size;
let fStride = vAttribData.stride ? vAttribData.stride : byteAdvance;
const TypedArrayMap = {
[gl.BYTE]: Int8Array,
[gl.UNSIGNED_BYTE]: Uint8Array,
[gl.SHORT]: Int16Array,
[gl.UNSIGNED_SHORT]: Uint16Array,
[gl.FLOAT]: Float32Array
};
const TypedArrayConstructor = TypedArrayMap[vAttribData.type];
// Fix other bug
if(_bufferData instanceof ArrayBuffer) {
_bufferData = new TypedArrayConstructor(_bufferData, vAttribData.offset);
} else {
_bufferData = new TypedArrayConstructor(_bufferData.buffer, vAttribData.offset);
}
let byteOffset = vAttribData.offset;
while (byteOffset <= _bufferData.byteLength) {
var readView = new TypedArrayConstructor(_bufferData.buffer.slice(byteOffset, byteOffset + fStride));
for (let i = 0; i < vAttribData.size; i++) {
bufferData.push(readView[i]);
}
byteOffset += fStride;
}
if (!bufferData) {
LogToParent("Couldn't get bufferData: ", attr);
return;
}
bufferData = new TypedArrayConstructor(bufferData);
LogToParent("Final Stride is: ", fStride, ", Buffer byte length: ", _bufferData.byteLength, "Original Buffer Data: ", _bufferData, "Got New Buffer Data: ", bufferData);
switch (attribType) {
case self._AttribTypeEnum.VERTEX:
self._GLCurrentVertices = bufferData;
self._GLCurrentVertexIndex = attr.loc;
break;
case self._AttribTypeEnum.NORMAL:
self._GLCurrentNormals = bufferData;
self._GLCurrentNormalIndex = attr.loc;
break;
case self._AttribTypeEnum.UVS:
self._GLCurrentUVS = bufferData;
self._GLCurrentUVIndex = attr.loc;
break;
default:
LogToParent("Unknown Attrib Type: ", attr);
break;
}
});
}
HelperFunc_PerformRIP(self, gl) {
LogToParent(`Downloading ${self._CurrentModels.length}`);
let models = self._CurrentModels.slice(); // Create a copy
// Download each model
if(_window.WEBGLRipperSettings.shouldDownloadZip && JSZip) {
const zip = new JSZip();
models.forEach(async function (obj) {
zip.file(`${obj.name}.obj`, obj.BuildOBJ());
if (obj.textures.length <= 0)
return;
zip.file(`${obj.name}.mtl`, obj.BuildMTL());
});
let textures = [];
let texcache = [];
models.forEach(function (obj) {
obj.textures.forEach(function (texture) {
if (!texture._URL)
return;
if (texcache[texture._URL])
return;
textures.push(texture);
texcache[texture._URL] = true;
});
});
textures.forEach(async function (texture) {
zip.file(`${texture._FILENAME}.png`, texture._URL.replace("data:image/png;base64,", ""), {base64: true});
});
zip.generateAsync({type:"blob"}).then(function(content) {
let dateString = new Date().toISOString();
Downloader.DownloadBlob(`${dateString}-rip.zip`, content);
});
} else {
function pause(msec) {
return new Promise((resolve) => {
setTimeout(resolve, msec || 1000);
});
}
async function downloadModel(obj) {
await Downloader.DownloadString(`${obj.name}.obj`, obj.BuildOBJ());
if (obj.textures.length > 0) {
await Downloader.DownloadString(`${obj.name}.mtl`, obj.BuildMTL());
}
}
async function downloadTexture(texture) {
await Downloader.DownloadImage(texture._FILENAME, texture._URL);
}
async function downloadAll(elements, isModel = true) {
var count = 0;
for (const e of elements) {
if (isModel) {
await downloadModel(e);
} else {
await downloadTexture(e);
}
await pause(500); // Pause to not overload the browser in case of big scenes
}
}
downloadAll(models).catch((error) => {
console.error("An error occurred while downloading models:", error);
});
// Download each texture
let textures = [];
let texcache = [];
models.forEach(function (obj) {
obj.textures.forEach(function (texture) {
if (!texture._URL) return;
if (texcache[texture._URL]) return;
textures.push(texture);
texcache[texture._URL] = true;
});
});
downloadAll(textures, false).catch((error) => {
console.error("An error occurred while downloading textures:", error);
});
}
// Reset vars
self._isCapturing = false;
self._needsToReset = true;
self._CurrentModels = [];
}
HelperFunc_Flush(self, gl) {
self._GLCurrentUVS = [];
self._GLCurrentNormals = [];
self._GLCurrentVertices = [];
}
HelperFunc_ResetAll(self, gl) {
self._TextureCache = new Map();
self._ClearCount = 0;
}
hooked_viewport(self, gl, args, oFunc) { // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/viewport
let _x = args[0];
let _y = args[1];
let _width = args[2];
let _height = args[3];
self._GLViewport = { x: _x, y: _y, width: _width, height: _height };
}
hooked_activeTexture(self, gl, args, oFunc) {
self._GLActiveTextureIndex = args[0] - gl.TEXTURE0;
}
hooked_texImage2D(self, gl, args, oFunc) { // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texImage2D
let target = args[0];
if (target != gl.TEXTURE_2D)
return;
self._GLAllTextures.forEach(glTex => {
if(glTex == self._GLCurrentBoundTexture)
glTex.is2DTexture = true;
});
// Attempt to get width and height of texture
let pixels = null;
switch (args.length) {
case 9:
pixels = args[8];
break;
case 6:
pixels = args[5];
break;
}
if (pixels == null)
return;
let _ArrayBufferView = (new Uint16Array()).constructor.prototype.__proto__.constructor;
if ((pixels instanceof _ArrayBufferView))
return;
if (pixels instanceof ImageData ||
pixels instanceof HTMLImageElement ||
pixels instanceof HTMLCanvasElement ||
pixels instanceof HTMLVideoElement ||
pixels instanceof ImageBitmap) {
self._GLCurrentBoundTexture.width = pixels.width;
self._GLCurrentBoundTexture.height = pixels.height;
}
}
hooked_shaderSource(self, gl, args, oFunc) { // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/shaderSource
let shader = args[0];
let source = args[1];
if (!shader || !source)
return;
//LogToParent("Got shader source: ", source);
}
hooked_linkProgram(self, gl, args, oFunc) {
let program = args[0];
if (!_window.WEBGLRipperSettings.isDoShaderCalc) {
return;
}
gl.transformFeedbackVaryings(program, ["gl_Position"], gl.SEPARATE_ATTRIBS);
LogToParent("[ShaderCalc] Added Transform Feedback for gl_Position");
}
hooked_bindTexture(self, gl, args, oFunc) { // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindTexture
let target = args[0];
let texture = args[1];
if (target != gl.TEXTURE_2D)
return;
if (texture == null)
return;
self._GLTextures.set(self._GLActiveTextureIndex, texture);
self._GLCurrentBoundTexture = texture;
}
hooked_drawArrays(self, gl, args, oFunc) { // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawArrays
if (!self._isCapturing)
return;
LogToParent("Captured 'drawArrays' call: ", args);
let drawMode = args[0];
let indFirst = args[1];
let indCount = args[2];
switch (drawMode) {
case OBJUtils.DrawModes.TRIANGLES:
case OBJUtils.DrawModes.TRIANGLE_STRIP:
break;
default:
LogToParent("Unsupported draw mode: ", drawMode);
return;
}
self.HelperFunc_UpdateAllAttributes(self, gl);
if (self._GLCurrentVertices.length <= 0) {
LogToParent("Got no vertices in drawArrays call");
return;
}
if(_window.WEBGLRipperSettings.isDoShaderCalc) {
/* Setup Area */
}
let textures = self.HelperFunc_GetAllTextures(self, gl);
let indices = [];
// Go through each position, see if it exists or not and add an indice to it!
let indice = 0;
for (let i = 0; i < self._GLCurrentVertices.length; i += 3) {
indices.push(indice++);
}
LogToParent("Using indices, size: ", indices.length, ", to cut out from ", indFirst, " to ", indFirst, " + ", indCount);
indices = indices.slice(indFirst, indFirst + indCount);
LogToParent("New indices size: ", indices.length);
let objPrimitives = new OBJUtils.OBJPrimitive(drawMode, indices);
let objID = self._CurrentModels.length;
let builtOBJ = new OBJUtils.OBJModel(objPrimitives, self._GLCurrentVertices, self._GLCurrentNormals, self._GLCurrentUVS, textures, `RIP${objID}`);
if(_window.WEBGLRipperSettings.doModelViewMatrix) {
let modelMatrix = self.HelperFunc_GetModelMatrix(self, gl);
if (modelMatrix){
builtOBJ.transform(modelMatrix);
}
}
self._CurrentModels.push(builtOBJ);
LogToParent("Finished Building OBJ: ", builtOBJ);
// Cleanup
self.HelperFunc_Flush(self, gl);
if(_window.WEBGLRipperSettings.isDoShaderCalc)
return true;
}
hooked_drawElements(self, gl, args, oFunc) { // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/drawElements
if (!self._isCapturing)
return;
LogToParent("Captured 'drawElements' call: ", args);
let drawMode = args[0];
let indCount = args[1];
let indType = args[2];
let indOffset = args[3];
switch (drawMode) {
case OBJUtils.DrawModes.TRIANGLES:
case OBJUtils.DrawModes.TRIANGLE_STRIP:
break;
default:
LogToParent("Unsupported draw mode: ", drawMode);
return;
}
let oIndices = self.getBufferedIndices(self);
if (!oIndices || oIndices == undefined) {