-
Notifications
You must be signed in to change notification settings - Fork 0
/
Volume_SdfTexture_InstancedMesh_Testing_Sample3Din2D.html
1331 lines (1041 loc) · 41.4 KB
/
Volume_SdfTexture_InstancedMesh_Testing_Sample3Din2D.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<title>Volume SDF Surface Track _ Final</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<style>
body {
margin: 0;
overflow: hidden;
}
.note {
position: fixed;
color: white;
}
</style>
<body>
<div class="note">
</div>
<script id="frag_Pos_GPGPU" type="x-shader/x-fragment">
uniform float time;
uniform float delta;
uniform float u_holdGPGPU;
uniform bool start;
uniform sampler3D texture3DSDF;
uniform sampler2D u_sdfTexture;
uniform float u_sdfScale;
uniform vec3 u_sdfOffset;
uniform float u_sdfVoxelSize;
uniform vec4 u_sdfSliceInfo;
uniform float u_sdfOutBoundForce;
uniform float u_sdfInBoundForce;
uniform float u_sdfThreshold;
vec2 computeSliceOffsetOrigin(float slice, float slicesPerRow, vec2 sliceSize) {
return sliceSize * vec2(mod(slice, slicesPerRow),
floor(slice / slicesPerRow));
}
vec4 sampleAs3DTextureOrigin(
sampler2D tex, vec3 texCoord, float size, float numRows, float slicesPerRow) {
float slice = texCoord.z * size;
float sliceZ = floor(slice); // slice we need
float zOffset = fract(slice); // dist between slices
vec2 sliceSize = vec2(1.0 / slicesPerRow, // u space of 1 slice
1.0 / numRows); // v space of 1 slice
vec2 slice0Offset = computeSliceOffsetOrigin(sliceZ, slicesPerRow, sliceSize);
vec2 slice1Offset = computeSliceOffsetOrigin(sliceZ + 1.0, slicesPerRow, sliceSize);
vec2 slicePixelSize = sliceSize / size; // space of 1 pixel
vec2 sliceInnerSize = slicePixelSize * (size - 1.0); // space of size pixels
vec2 uv = slicePixelSize * 0.5 + texCoord.xy * sliceInnerSize;
//uv = vec2(uv.x,1.-uv.y);
vec4 slice0Color = texture2D(tex, slice0Offset + uv);
vec4 slice1Color = texture2D(tex, slice1Offset + uv);
return mix(slice0Color, slice1Color, zOffset);
//return slice0Color;
}
void main() {
vec2 uv = gl_FragCoord.xy / resolution.xy;
vec4 tmpPos = texture2D( texturePosition, uv );
vec3 posSelf = tmpPos.xyz;
vec3 velSelf = texture2D( textureVelocity, uv ).xyz;
posSelf += velSelf * .5;
gl_FragColor = vec4( posSelf.xyz,1. );
}
</script>
<script id="frag_Vel_GPGPU" type="x-shader/x-fragment">
uniform float time;
uniform float delta;
uniform sampler2D u_sdfTexture;
uniform sampler3D texture3DSDF;
uniform float u_holdGPGPU;
uniform float u_sdfScale;
uniform vec3 u_sdfOffset;
uniform float u_sdfVoxelSize;
uniform vec4 u_sdfSliceInfo;
uniform float u_sdfOutBoundForce;
uniform float u_sdfInBoundForce;
uniform float u_sdfThreshold;
float random (in vec2 _st) {
return fract(sin(dot(_st.xy,
vec2(12.9898,78.233)))*
43758.5453123);
}
vec2 computeSliceOffsetOrigin(float slice, float slicesPerRow, vec2 sliceSize) {
return sliceSize * vec2(mod(slice, slicesPerRow),
floor(slice / slicesPerRow));
}
vec4 sampleAs3DTextureOrigin(
sampler2D tex, vec3 texCoord, float size, float numRows, float slicesPerRow) {
float slice = texCoord.z * size;
float sliceZ = floor(slice); // slice we need
float zOffset = fract(slice); // dist between slices
vec2 sliceSize = vec2(1.0 / slicesPerRow, // u space of 1 slice
1.0 / numRows); // v space of 1 slice
vec2 slice0Offset = computeSliceOffsetOrigin(sliceZ, slicesPerRow, sliceSize);
vec2 slice1Offset = computeSliceOffsetOrigin(sliceZ + 1.0, slicesPerRow, sliceSize);
vec2 slicePixelSize = sliceSize / size; // space of 1 pixel
vec2 sliceInnerSize = slicePixelSize * (size - 1.0); // space of size pixels
vec2 uv = slicePixelSize * 0.5 + texCoord.xy * sliceInnerSize;
//uv = vec2(uv.x,1.-uv.y);
vec4 slice0Color = texture2D(tex, slice0Offset + uv);
vec4 slice1Color = texture2D(tex, slice1Offset + uv);
return mix(slice0Color, slice1Color, zOffset);
//return slice0Color;
}
void main() {
vec2 uv = gl_FragCoord.xy / resolution.xy;
vec3 posSelf = texture2D( texturePosition, uv ).xyz;
vec3 velSelf = texture2D( textureVelocity, uv ).xyz;
posSelf += velSelf;
vec4 sdf3d = texture(texture3DSDF, posSelf + .5);
vec4 sdf3dFormat = sdf3d * 2. - 1.;
if(sdf3dFormat.w < 1.2) {
vec3 dis = normalize(sdf3dFormat.xyz + posSelf) * (-sdf3dFormat.w * u_holdGPGPU);
velSelf += dis * .5 ;
vec4 distanceInfo = sampleAs3DTextureOrigin(u_sdfTexture, posSelf, 128.,8.,16.);
vec4 distanceInfoFormat = distanceInfo * 2. - 1.;
vec3 disAA = normalize(distanceInfo.xyz + posSelf) * (-sdf3dFormat.w * u_holdGPGPU);
// velSelf += disAA * .5 ;
}else{
}
gl_FragColor = vec4( velSelf,1.);
}
</script>
<script type="importmap">
{
"imports": {
"three": "./three.module.js",
"three/addons/": "./jsm/"
}
}
</script>
<script type="module">
import Stats from 'three/addons/stats.module.js';
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/OrbitControls.js';
import { OBJLoader } from 'three/addons/OBJLoader.js';
import { ImprovedNoise } from 'three/addons/ImprovedNoise.js';
import { GPUComputationRenderer } from 'three/addons/GPUComputationRenderer.js';
import { GUI } from 'three/addons/lil-gui.module.min.js';
let renderer, scene, camera, stats;
let mesh, texturedd, dataTexture3D, dataTexture3DSample, materialCube, textureData3dOut
let meshLayer, matPoint, matInstanced
let delta, time, lastTime
let gpuCompute
let widthTexture = 128
let velocityVariable, positionVariable, extraVariable
let positionUniforms, velocityUniforms, extraUniforms
let monitorPos, monitorVel, monitorTrack1
const textureSDF = new THREE.TextureLoader().load('/models/eisbar/sdf.png')
const textureSDFCus = new THREE.TextureLoader().load('/models/eisbar/sdfcus.png')
let textureSDFData, texture2DView, matmat
//CheckSampleas3d
let matCheckSampleas3d
initRenderer()
initMain();
function initComputeRenderer(data3d) {
function fillPosTexture(texture) {
const arrT = texture.image.data;
for (let k = 0, kl = arrT.length; k < kl; k += 4) {
const x = Math.random() * 2 - 1;
const y = Math.random() * 2 - 1;
const z = Math.random() * 2 - 1;
let vp = new THREE.Vector3(x, y, z)
vp.multiplyScalar(.5)
arrT[k + 0] = vp.x
arrT[k + 1] = vp.y
arrT[k + 2] = vp.z
arrT[k + 3] = 1
}
console.log(arrT)
}
function fillVelTexture(texture) {
const arrT = texture.image.data;
for (let k = 0, kl = arrT.length; k < kl; k += 4) {
const x = Math.random() * 2 - 1;
const y = Math.random() * 2 - 1;
const z = Math.random() * 2 - 1;
let vv = new THREE.Vector3(x, y, z)
vv.multiplyScalar(.005)
arrT[k + 0] = vv.x
arrT[k + 1] = vv.y
arrT[k + 2] = vv.z
arrT[k + 3] = 1
}
}
gpuCompute = new GPUComputationRenderer(widthTexture, widthTexture, renderer);
const dtPosition = gpuCompute.createTexture();
const dtVelocity = gpuCompute.createTexture();
const dtExtra = gpuCompute.createTexture();
fillPosTexture(dtPosition);
fillVelTexture(dtVelocity);
velocityVariable = gpuCompute.addVariable('textureVelocity', document.getElementById('frag_Vel_GPGPU').textContent, dtVelocity);
positionVariable = gpuCompute.addVariable('texturePosition', document.getElementById('frag_Pos_GPGPU').textContent, dtPosition);
velocityVariable.wrapS = THREE.RepeatWrapping;
velocityVariable.wrapT = THREE.RepeatWrapping;
positionVariable.wrapS = THREE.RepeatWrapping;
positionVariable.wrapT = THREE.RepeatWrapping;
gpuCompute.setVariableDependencies(velocityVariable, [positionVariable, velocityVariable]);
gpuCompute.setVariableDependencies(positionVariable, [positionVariable, velocityVariable]);
positionUniforms = positionVariable.material.uniforms;
velocityUniforms = velocityVariable.material.uniforms;
positionUniforms['time'] = { value: 0.0 };
positionUniforms['delta'] = { value: 0.0 };
velocityUniforms['time'] = { value: 0.0 };
velocityUniforms['delta'] = { value: 0.0 };
positionUniforms['start'] = { value: false };
positionUniforms['u_holdGPGPU'] = { value: 0.5 };
function initDatasdfCOCO(dataOriFromImg) {
const width = 128*16;
const height = 128*8;
const size = width * height;
const data = new Float32Array(width * height * 4)
for ( let i = 0; i < size; i ++ ) {
const stride = i * 4;
data[ stride ] = dataOriFromImg[ stride ] / 255;
data[ stride + 1 ] = dataOriFromImg[ stride +1] / 255;
data[ stride + 2 ] = dataOriFromImg[ stride +2] / 255;
data[ stride + 3 ] = dataOriFromImg[ stride +3] / 255;
}
// used the buffer to create a DataTexture
const texture = new THREE.DataTexture( data, width, height,THREE.RGBAFormat,THREE.FloatType );
texture.needsUpdate = true;
return texture
}
const ddddd = initDatasdfCOCO(textureSDFData)
positionUniforms['u_sdfTexture'] = { value: ddddd };
velocityUniforms['u_sdfTexture'] = { value: textureSDF };
velocityUniforms['u_sdfOffset'] = { value: new THREE.Vector3(0.5000, 0.5000, 0.5000) };
velocityUniforms['u_sdfScale'] = { value: 1 };
velocityUniforms['u_sdfVoxelSize'] = { value: 128 };
velocityUniforms['u_sdfSliceInfo'] = { value: new THREE.Vector4(128, 16, 0.0625, 0.1250) };
velocityUniforms['u_sdfThreshold'] = { value: .05 };
velocityUniforms['u_sdfOutBoundForce'] = { value: .1 };
velocityUniforms['u_sdfInBoundForce'] = { value: .01 };
positionUniforms['u_sdfOffset'] = { value: new THREE.Vector3(0.5000, 0.5000, 0.5000) };
positionUniforms['u_sdfScale'] = { value: 1 };
positionUniforms['u_sdfVoxelSize'] = { value: 128 };
positionUniforms['u_sdfSliceInfo'] = { value: new THREE.Vector4(128, 16, 0.0625, 0.1250) };
positionUniforms['u_sdfThreshold'] = { value: .05 };
positionUniforms['u_sdfOutBoundForce'] = { value: .1 };
positionUniforms['u_sdfInBoundForce'] = { value: .01 };
positionUniforms['texture3DSDF'] = { value: data3d };
velocityUniforms['texture3DSDF'] = { value: data3d };
velocityUniforms['u_holdGPGPU'] = { value: 0.5 };
console.log(positionUniforms['texture3DSDF'])
const error = gpuCompute.init();
if (error !== null) {
console.error(error);
}
}
function initRenderer() {
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animate);
document.body.appendChild(renderer.domElement);
}
function initMain() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0x525453)
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.001, 10000);
camera.position.set(0, 0, 2);
new OrbitControls(camera, renderer.domElement);
const axesHelper = new THREE.AxesHelper(5);
//scene.add(axesHelper);
const light = new THREE.AmbientLight(0x404040); // soft white light
scene.add(light);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.5);
scene.add(directionalLight);
stats = new Stats();
document.body.appendChild(stats.dom);
initTexture()
// initVolume()
initGui()
window.addEventListener('resize', onWindowResize);
}
function initMonitor(d3) {
monitorPos = new THREE.Mesh(
new THREE.PlaneGeometry(1 *1, 1 *1),
new THREE.ShaderMaterial({
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec2 vUv;
uniform sampler3D tex;
uniform float u_slice;
void main() {
vec4 mapcolor = texture(tex, vec3(vUv,u_slice));
gl_FragColor = mapcolor*2.-1.;
}
`,
uniforms: {
tex: { value: d3 },
u_slice:{value:0}
},
transparent: true,
side: 2
})
)
monitorPos.position.x = -2.5
monitorPos.position.y = -0.5
monitorVel = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
new THREE.ShaderMaterial({
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec2 vUv;
uniform sampler2D tex;
void main() {
vec4 mapcolor = texture2D(tex, vUv);
gl_FragColor = mapcolor;
gl_FragColor = vec4(mapcolor.xy,0.,1.);
}
`,
uniforms: {
tex: { value: null }
},
transparent: true,
side: 2
})
)
monitorPos.position.x = -1
monitorVel.position.x = -1
monitorVel.position.y = .5
monitorTrack1 = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
new THREE.ShaderMaterial({
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec2 vUv;
uniform float u_slice;
uniform float u_sdfScale;
uniform vec3 u_sdfOffset;
uniform float u_sdfVoxelSize;
uniform vec4 u_sdfSliceInfo;
uniform float u_sdfOutBoundForce;
uniform float u_sdfInBoundForce;
uniform float u_sdfThreshold;
uniform sampler2D tex;
uniform sampler3D tex3d;
vec2 computeSliceOffsetOrigin(float slice, float slicesPerRow, vec2 sliceSize) {
return sliceSize * vec2(mod(slice, slicesPerRow),
floor(slice / slicesPerRow));
}
vec4 sampleAs3DTextureOrigin(
sampler2D tex, vec3 texCoord, float size, float numRows, float slicesPerRow) {
float slice = texCoord.z * size;
float sliceZ = floor(slice); // slice we need
float zOffset = fract(slice); // dist between slices
vec2 sliceSize = vec2(1.0 / slicesPerRow, // u space of 1 slice
1.0 / numRows); // v space of 1 slice
vec2 slice0Offset = computeSliceOffsetOrigin(sliceZ, slicesPerRow, sliceSize);
vec2 slice1Offset = computeSliceOffsetOrigin(sliceZ + 1.0, slicesPerRow, sliceSize);
vec2 slicePixelSize = sliceSize / size; // space of 1 pixel
vec2 sliceInnerSize = slicePixelSize * (size - 1.0); // space of size pixels
vec2 uv = slicePixelSize * 0.5 + texCoord.xy * sliceInnerSize;
//uv = vec2(uv.x,1.-uv.y);
vec4 slice0Color = texture2D(tex, slice0Offset + uv);
vec4 slice1Color = texture2D(tex, slice1Offset + uv);
return mix(slice0Color, slice1Color, zOffset);
return slice0Color;
}
void main() {
vec3 pos = vec3(vUv - .5,u_slice);
vec3 voxelTextureCoordOri = pos / u_sdfScale + u_sdfOffset ;
vec3 voxelTextureCoord = clamp(voxelTextureCoordOri, vec3(0.5 / u_sdfVoxelSize), vec3(1.0 - 0.5 / u_sdfVoxelSize));
vec4 distanceInfo = sampleAs3DTextureOrigin(tex, vec3(voxelTextureCoord.xy,min(0.995,u_slice)) , 128.,8.,16.);
vec4 distanceInfoFormat = distanceInfo * 2. - 1.;
vec3 disSDF = normalize(distanceInfoFormat.xyz + pos) * (- distanceInfoFormat.w * .5);
gl_FragColor = distanceInfoFormat;
vec4 sdf3d = texture(tex3d, vec3(voxelTextureCoord.xy,min(0.995,u_slice)) );
vec4 sdf3dFormat = sdf3d * 2. - 1.;
gl_FragColor = sdf3dFormat;
}
`,
uniforms: {
u_slice : { value: 0 },
tex: { value: textureSDFCus },
tex3d: { value: d3 },
u_sdfOffset : { value: new THREE.Vector3(0.5000, 0.5000, 0.5000) },
u_sdfScale : { value: 1 },
u_sdfVoxelSize : { value: 128 },
u_sdfSliceInfo : { value: new THREE.Vector4(128, 16, 0.0625, 0.1250) },
u_sdfThreshold : { value: .05 },
u_sdfOutBoundForce : { value: .1 },
u_sdfInBoundForce : { value: .01 }
},
transparent: true,
side: 2
})
)
monitorTrack1.position.x = 1
monitorTrack1.position.y = -1
scene.add(monitorPos,monitorVel,monitorTrack1)
}
function initInstancedMesh(data3d) {
const count = 2000; // Số lượng instance
const scale = 3.;
const geometry = new THREE.BoxGeometry(0.005 * scale, 0.005 * scale, 0.005 * scale);
// Tạo mảng lưu trữ vị trí các điểm
const positions = new Float32Array(count * 3);
const uvs = new Float32Array(count * 2); // Mảng UVs
const materialChunk = new THREE.MeshPhongMaterial({
color: 0xc5461b,
//emissive:0x3a2b82,
specular : 0x2c2a2a,
shininess: 100,
transparent:true
});
materialChunk.onBeforeCompile = (shader) => {
shader.uniforms.texturesdf = { value: textureSDF };
shader.uniforms.posGpu = { value: null };
shader.uniforms.velGpu = { value: null };
shader.uniforms.tSize = { value: new THREE.Vector2(widthTexture, widthTexture) };
shader.uniforms.u_sdfOffset={value :new THREE.Vector3(0.5000, 0.5000, 0.5000) },
shader.uniforms.u_sdfScale={value : 1},
shader.uniforms.u_sdfVoxelSize={value : 128},
shader.uniforms.u_sdfSliceInfo={value : new THREE.Vector4(128, 16, 8/128, 16/128)},
shader.uniforms.u_sdfThreshold={value : .05},
shader.uniforms.u_sdfOutBoundForce={value : .1},
shader.uniforms.u_sdfInBoundForce={value : .01},
shader.uniforms.u_slice={value : 0.},
// Sửa đổi vertex shader
shader.vertexShader = `
attribute vec3 offset;
varying vec2 vUv;
varying vec4 vPos;
uniform vec2 tSize;
uniform sampler2D posGpu;
uniform sampler2D velGpu;
uniform sampler2D texturesdf;
uniform float u_sdfScale;
uniform vec3 u_sdfOffset;
uniform float u_sdfVoxelSize;
uniform vec4 u_sdfSliceInfo;
uniform float u_sdfOutBoundForce;
uniform float u_sdfInBoundForce;
uniform float u_sdfThreshold;
uniform float u_slice;
${shader.vertexShader}
`.replace(
`#include <fog_vertex>`,
`#include <fog_vertex>
vec3 pos = position * min(.8,abs(offset.x));
float id = float(gl_InstanceID);
vec2 uvT = vec2(
mod(id, tSize.x) / tSize.x, // Tính chỉ số cột
floor(id / tSize.x) / tSize.y // Tính chỉ số hàng
);
vec4 posOfGpu = texture2D(posGpu, uvT);
pos += posOfGpu.xyz;
vPos = posOfGpu;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos * 5., 1.0);
vUv = uv;
`,
shader.fragmentShader = `
varying vec2 vUv;
varying vec4 vPos;
${shader.fragmentShader}
`.replace(
`#include <dithering_fragment>`,
`#include <dithering_fragment>
gl_FragColor = vec4(vec3(vPos) + outgoingLight, 1.);
`
),
console.log(shader.fragmentShader )
);
matInstanced = shader;
};
const offsets = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
offsets[i * 3 + 0] = Math.random()+.1; // X
offsets[i * 3 + 1] = Math.random(); // Y
offsets[i * 3 + 2] = Math.random()+.1; // Z
}
geometry.setAttribute('offset', new THREE.InstancedBufferAttribute(offsets, 3));
const cInstancedMesh = new THREE.InstancedMesh(geometry, materialChunk, count);
const colors = [];
for (let i = 0; i < count; i++) {
// Tạo ma trận transform cho mỗi instance
const matrix = new THREE.Matrix4();
// Tạo vị trí ngẫu nhiên trong phạm vi từ -50 đến 50
const position = new THREE.Vector3(
(Math.random() - 0.5) * 2,
(Math.random() - 0.5) * 2,
(Math.random() - 0.5) * 2
);
// Tạo tỷ lệ ngẫu nhiên từ 0.5 đến 1.5
const scale = new THREE.Vector3(
Math.random() + 0.5,
Math.random() + 0.5,
Math.random() + 0.5
);
// Tạo rotation ngẫu nhiên
const rotation = new THREE.Euler(
Math.random() * 2 * Math.PI,
Math.random() * 2 * Math.PI,
Math.random() * 2 * Math.PI
);
// Áp dụng transform vào ma trận
matrix.makeRotationFromEuler(rotation);
matrix.setPosition(position);
matrix.scale(scale);
// Gán ma trận cho instance thứ i
cInstancedMesh.setMatrixAt(i, matrix);
// Tạo màu ngẫu nhiên cho mỗi instance
const color = new THREE.Color(Math.random(), Math.random(), Math.random());
colors.push(color.r, color.g, color.b);
}
//scene.add(cInstancedMesh);
}
function initPoint(data3d) {
const count_p_size = 40;
const cubeSize = 1;
// Sử dụng BufferGeometry để tạo các điểm
const geometry = new THREE.BufferGeometry();
// Số lượng điểm (thay vì count_p_size ^ 3)
const numPoints = widthTexture * widthTexture;
// Tạo mảng lưu trữ vị trí các điểm
const positions = new Float32Array(numPoints * 3);
const uvs = new Float32Array(numPoints * 2); // Mảng UVs
// Tạo vị trí điểm ngẫu nhiên
let index = 0;
for (let i = 0; i < numPoints; i++) {
// Tạo các vị trí ngẫu nhiên trong phạm vi [-cubeSize/2, cubeSize/2]
const posX = Math.random() * cubeSize - cubeSize / 2;
const posY = Math.random() * cubeSize - cubeSize / 2;
const posZ = Math.random() * cubeSize - cubeSize / 2;
// Lưu vị trí điểm vào mảng
positions[index * 3] = posX;
positions[index * 3 + 1] = posY;
positions[index * 3 + 2] = posZ;
// Tạo UVs ngẫu nhiên hoặc theo một quy tắc nào đó
uvs[index * 2] = Math.random(); // u
uvs[index * 2 + 1] = Math.random(); // v
index++;
}
// Thêm vị trí vào geometry
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));
// Hoặc sử dụng ShaderMaterial như mã của bạn nếu bạn muốn tiếp tục xử lý bằng shader
matPoint = new THREE.ShaderMaterial({
vertexShader: `
varying vec2 vUv;
attribute vec3 offset;
uniform sampler3D dataTexture3D;
uniform sampler2D posGpu;
uniform float u_hold;
uniform vec2 tSize;
uniform float dt;
uniform float time;
varying vec2 vExtra;
varying vec4 vSdf;
void main() {
float id = float(gl_InstanceID);
vec2 uvT = vec2(
mod(id, tSize.x) / tSize.x, // Tính chỉ số cột
floor(id / tSize.x) / tSize.y // Tính chỉ số hàng
);
vec3 pos = position;
vec3 pos2 = position;
vec3 posOfGpu = texture2D(posGpu, uv).xyz;
// vec4 sdf3d = texture(dataTexture3D, pos + .5);
// vec4 sdf3dFormat = sdf3d * 2. - 1.;
// if(sdf3dFormat.w < .5) {
// pos -= normalize(sdf3dFormat.xyz + pos) * (sdf3dFormat.w * u_hold);
// }else{
// //pos = vec3(.5);
// }
vSdf = vec4(posOfGpu,1.);
gl_Position = projectionMatrix * modelViewMatrix * vec4(posOfGpu , 1.0);
gl_PointSize = 2.5;
vUv = uv;
}
`,
fragmentShader: `
varying vec2 vUv;
varying vec2 vExtra;
varying vec4 vSdf;
void main() {
gl_FragColor = vec4(vSdf.xyz, 1.-vSdf.w);
gl_FragColor = vec4(vec3(.4,.6,1.), step(.5,vSdf.w));
gl_FragColor = vec4(vec3(.4,.6,1.),1.);
gl_FragColor = vec4(1.-vSdf.xyz * 1.4, 1.);
}
`,
uniforms: {
texure3D: data3d,
dt: { value: 0 },
time: { value: 0 },
posGpu: { value: null },
tSize: { value: new THREE.Vector2(widthTexture, widthTexture) },
u_hold: { value: .5 }
},
transparent: true,
blending: THREE.NormalBlending
});
// Tạo Points (thay vì InstancedMesh)
const points = new THREE.Points(geometry, matPoint);
// Thêm các điểm vào scene
scene.add(points);
}
function checksample3das2d(data3d){
const scalePlane = 1
const ratio = 8/16
const sizeSlice = 128
const countLayerW = 16
const countLayerH = 8
const plane = new THREE.PlaneGeometry(scalePlane,scalePlane)
let textureFormat = textureSDFCus
textureFormat.flipY = false
matCheckSampleas3d = new THREE.ShaderMaterial({
transparent:true,
uniforms:{
texture2d: {value:textureFormat},
u_sdfOffset:{value :new THREE.Vector3(0.5000, 0.5000, 0.5000) },
u_sdfScale:{value : 1},
u_sdfVoxelSize:{value : 128},
u_sdfSliceInfo:{value : new THREE.Vector4(128, 16, 8/128, 16/128)},
u_sdfThreshold:{value : .05},
u_sdfOutBoundForce:{value : .1},
u_sdfInBoundForce:{value : .01},
//gui
u_slice:{value:0.}
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader : `
varying vec2 vUv;
// VER LUSION
vec2 computeSliceOffset(float slice, vec4 sliceInfo) {
return sliceInfo.zw * vec2(mod(slice, sliceInfo.y), floor(slice * sliceInfo.z));
}
vec4 sampleAs3DTexture(sampler2D tex, vec3 texCoord, vec4 sliceInfo) {
float slice = texCoord.z * sliceInfo.x;
float sliceZ = floor(slice);
vec2 slice0Offset = computeSliceOffset(sliceZ, sliceInfo);
vec2 slice1Offset = computeSliceOffset(sliceZ + 1.0, sliceInfo);
vec2 slicePixelSize = sliceInfo.zw / sliceInfo.x;
vec2 uv = slicePixelSize * 0.5 + texCoord.xy * (sliceInfo.zw - slicePixelSize);
vec4 slice0Color = texture2D(tex, slice0Offset + uv);
vec4 slice1Color = texture2D(tex, slice1Offset + uv);
//return mix(slice0Color, slice1Color, fract(slice));
return slice0Color;
}
uniform sampler2D texture2d;
uniform float u_sdfScale;
uniform vec3 u_sdfOffset;
uniform float u_sdfVoxelSize;
uniform vec4 u_sdfSliceInfo;
uniform float u_sdfOutBoundForce;
uniform float u_sdfInBoundForce;
uniform float u_sdfThreshold;
//gui
uniform float u_slice;
// VER OGIRIN
vec2 computeSliceOffsetOrigin(float slice, float slicesPerRow, vec2 sliceSize) {
return sliceSize * vec2(mod(slice, slicesPerRow),
floor(slice / slicesPerRow));
}
vec4 sampleAs3DTextureOrigin(
sampler2D tex, vec3 texCoord, float size, float numRows, float slicesPerRow) {
float slice = texCoord.z * size;
float sliceZ = floor(slice); // slice we need
float zOffset = fract(slice); // dist between slices
vec2 sliceSize = vec2(1.0 / slicesPerRow, // u space of 1 slice
1.0 / numRows); // v space of 1 slice
vec2 slice0Offset = computeSliceOffsetOrigin(sliceZ, slicesPerRow, sliceSize);
vec2 slice1Offset = computeSliceOffsetOrigin(sliceZ + 1.0, slicesPerRow, sliceSize);
vec2 slicePixelSize = sliceSize / size; // space of 1 pixel
vec2 sliceInnerSize = slicePixelSize * (size - 1.0); // space of size pixels
vec2 uv = slicePixelSize * 0.5 + texCoord.xy * sliceInnerSize;
//uv = vec2(uv.x,1.-uv.y);
vec4 slice0Color = texture2D(tex, slice0Offset + uv);
vec4 slice1Color = texture2D(tex, slice1Offset + uv);
//return mix(slice0Color, slice1Color, zOffset);
return slice0Color;
}
void main() {
vec3 posCheck = vec3(vec2(vUv.x,vUv.y) - .5,u_slice) ;
vec3 voxelTextureCoordOri = posCheck / u_sdfScale + u_sdfOffset;
vec3 voxelTextureCoord = clamp(voxelTextureCoordOri, vec3(0.5 / u_sdfVoxelSize), vec3(1.0 - 0.5 / u_sdfVoxelSize));
vec4 distanceInfo = sampleAs3DTexture(texture2d, voxelTextureCoord, u_sdfSliceInfo) * 2.0 - 1.0;
//check img
vec4 sampler2d = texture2D(texture2d,vec2(vUv.x/2.,vUv.y/8.));
gl_FragColor = vec4(.5,.5,.5,sampler2d.a);
// check slice base posCheck
gl_FragColor = distanceInfo;
//check coord
vec2 slice0OffsetCHeck = computeSliceOffset(50., u_sdfSliceInfo);
//gl_FragColor = vec4(vec3(slice0OffsetCHeck.x),1.);
// check orgigin sampler3d
vec4 finalSlice = sampleAs3DTextureOrigin(texture2d,vec3(vec2(vUv.x,vUv.y),min(0.995,u_slice)) ,128.,8.,16.)*2.-1.;
gl_FragColor = vec4(finalSlice.xyz,finalSlice.w);
}
`
})
scene.add(new THREE.Mesh(plane,matCheckSampleas3d))
}
function initTexture() {
const img = new Image();
img.src = '/models/eisbar/sdfcus.png';
img.onload = () => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
// Set canvas dimensions to match the image
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0);
// Get image data
const imageData = context.getImageData(0, 0, img.width, img.height);
textureSDFData = imageData.data;
const width3D = 128;
const height3D = 128;
const depth3D = 128; // Tổng số ô (16 * 8 = 128)
// Giả sử bạn đã có dữ liệu hình ảnh dạng RGBA (với 4 kênh màu)
const imageWidth = 16 * width3D; // Chiều rộng của hình ảnh lớn
const imageHeight = 8 * height3D; // Chiều cao của hình ảnh lớn
const textureData3dOut = new Float32Array(4 * width3D * height3D * depth3D);
extractTexture3D(textureSDFData)
// imageData chứa dữ liệu RGBA của hình ảnh lớn (16*8 ô)
function extractTexture3D(imageData) {
for (let slice = 0; slice < depth3D; slice++) {
// Tính toán vị trí của ô thứ `slice` trong hình ảnh lớn
const tileX = slice % 16; // Chỉ số ô trên trục X
const tileY = Math.floor(slice / 16); // Chỉ số ô trên trục Y
// Tọa độ pixel bắt đầu của ô trong hình ảnh lớn
const startX = tileX * width3D;
const startY = tileY * height3D;
// Duyệt qua từng pixel trong ô
for (let y = 0; y < height3D; y++) {
for (let x = 0; x < width3D; x++) {
// Chỉ số pixel trong hình ảnh lớn
const imageIndex = ((startY + y) * imageWidth + (startX + x)) * 4;
// Chỉ số pixel tương ứng trong texture 3D
const index3D = ((slice * height3D + y) * width3D + x) * 4;
// Sao chép dữ liệu từ hình ảnh lớn vào texture3D
// Case này origin
textureData3dOut[index3D] = (imageData[imageIndex] / 255)
textureData3dOut[index3D + 1] = (imageData[imageIndex + 1] / 255)
textureData3dOut[index3D + 2] = (imageData[imageIndex + 2] / 255)
textureData3dOut[index3D + 3] = (imageData[imageIndex + 3] / 255)
// Nên xử lý cho raymarching đỡ phức tạp
// textureData3dOut[index3D] = 1. - imageData[imageIndex] / 255;
// textureData3dOut[index3D + 1] = 1. - imageData[imageIndex + 1] / 255;
// textureData3dOut[index3D + 2] = 1. - imageData[imageIndex + 2] / 255;
// textureData3dOut[index3D + 3] = 1. - imageData[imageIndex + 3] / 255 < .5 ? 0.01 : 1.;
}
}
}
}
console.log(textureData3dOut)
// Cấu hình, đối với trường hợp này sữ dụng RBGA , vì track bằng alpha
dataTexture3D = new THREE.Data3DTexture(textureData3dOut, width3D, height3D, depth3D);
dataTexture3D.format = THREE.RGBAFormat;
dataTexture3D.type = THREE.FloatType;
dataTexture3D.minFilter = THREE.LinearFilter;
dataTexture3D.magFilter = THREE.LinearFilter;
dataTexture3D.unpackAlignment = 1;
dataTexture3D.needsUpdate = true;
//initModel()
checkTextureData(textureData3dOut)
initMonitor(dataTexture3D)
//initPoint(dataTexture3D)
initComputeRenderer(dataTexture3D)
initInstancedMesh(dataTexture3D)
checksample3das2d(dataTexture3D)
};