-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSuper3DX.java
More file actions
3025 lines (2689 loc) · 134 KB
/
Copy pathSuper3DX.java
File metadata and controls
3025 lines (2689 loc) · 134 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
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import java.util.concurrent.*;
import java.io.*;
import java.nio.file.*;
public class Super3DX {
public final int width;
public final int height;
private final int[] framebuffer;
private final float[] zBuffer;
private final BufferedImage image;
private final Matrix4x4 viewMatrix = new Matrix4x4();
private final Matrix4x4 projMatrix = new Matrix4x4();
private final Matrix4x4 viewProjMatrix = new Matrix4x4();
private final Matrix4x4 mvpMatrix = new Matrix4x4();
private float nearClip = 0.1f;
private float farClip = 1000.0f;
private float fov = 60.0f;
private boolean backfaceCulling = true;
private final java.util.List<Light> lights = new ArrayList<>();
private float specularIntensity = 0.6f;
private float shininess = 32.0f;
private Vec3 cameraPos = new Vec3();
// === THREADING & TILE-BASED ===
private final ForkJoinPool threadPool;
private TileRegion[] tileRegions;
private java.util.List<TriangleBatch>[] tileBatches;
private boolean useTileBased = false;
private int tileSize = 32;
private int numThreads;
// === PROFILING ===
public int statsDrawCalls, statsTriangles, statsPixels;
public long statsRasterTime, statsFrameTime;
private ShadowMap shadowMap;
private final Matrix4x4 lightViewMatrix = new Matrix4x4();
private final Matrix4x4 lightProjMatrix = new Matrix4x4();
private final Matrix4x4 lightVP = new Matrix4x4();
private final Matrix4x4 lightMVP = new Matrix4x4();
private float shadowBias = 0.005f;
private float shadowIntensity = 0.35f;
private final Vertex shadowV0 = new Vertex();
private final Vertex shadowV1 = new Vertex();
private final Vertex shadowV2 = new Vertex();
private final Vertex[] clippedVerts = new Vertex[10];
public enum BlendMode { NONE, ALPHA, ADDITIVE }
public enum CullMode { NONE, FRONT, BACK }
public enum RenderMode { SOLID, WIREFRAME, SOLID_WIREFRAME }
private BlendMode blendMode = BlendMode.NONE;
private CullMode cullMode = CullMode.BACK;
private RenderMode renderMode = RenderMode.SOLID;
private boolean gammaCorrection = false;
private boolean fogEnabled = false;
private Color fogColor = new Color(128, 128, 128);
private float fogNear = 5.0f;
private float fogFar = 15.0f;
public Super3DX(int width, int height) {
this.width = width;
this.height = height;
this.framebuffer = new int[width * height];
this.zBuffer = new float[width * height];
this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
this.numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() - 1);
this.threadPool = new ForkJoinPool(numThreads);
initTiles(32);
setPerspective(fov, (float)width / height, nearClip, farClip);
resetDefaultLights();
}
public void resetDefaultLights() {
lights.clear();
lights.add(Light.ambient(0.3f, 0.3f, 0.3f, 0.3f));
lights.add(Light.directional(new Vec3(0.5f, -1.0f, 0.3f).normalize(), 1f, 1f, 1f, 0.7f));
}
public void enableTileBased(boolean enable, int tileSize) {
this.useTileBased = enable && numThreads > 1;
if (this.tileSize != tileSize) { this.tileSize = tileSize; initTiles(tileSize); }
}
@SuppressWarnings("unchecked")
private void initTiles(int ts) {
this.tileSize = ts;
int tx = (width + ts - 1) / ts, ty = (height + ts - 1) / ts;
tileRegions = new TileRegion[tx * ty];
tileBatches = new java.util.List[tx * ty];
for (int y = 0; y < ty; y++) for (int x = 0; x < tx; x++) {
int idx = y * tx + x;
tileRegions[idx] = new TileRegion(x * ts, y * ts, Math.min(ts, width - x * ts), Math.min(ts, height - y * ts));
tileBatches[idx] = new ArrayList<>();
}
}
public void setCamera(Vec3 position, Vec3 target, Vec3 up) {
cameraPos = position;
viewMatrix.lookAt(position, target, up);
updateViewProj();
}
public void setPerspective(float fovDeg, float aspect, float near, float far) {
this.fov = fovDeg;
this.nearClip = near;
this.farClip = far;
projMatrix.perspective(fovDeg, aspect, near, far);
updateViewProj();
}
private void updateViewProj() {
viewProjMatrix.mul(projMatrix, viewMatrix);
}
public void clear(int color) {
Arrays.fill(framebuffer, color);
Arrays.fill(zBuffer, Float.MAX_VALUE);
}
public void clear(Color color) {
clear(color.getRGB());
}
public void applyFXAA() {
int[] src = framebuffer.clone();
for (int y = 1; y < height - 1; y++) {
for (int x = 1; x < width - 1; x++) {
int idx = y * width + x;
int c = src[idx];
int l = src[y * width + x - 1];
int rp = src[y * width + x + 1];
int u = src[(y - 1) * width + x];
int d = src[(y + 1) * width + x];
float lumaC = ((c>>16&0xFF)*0.299f + (c>>8&0xFF)*0.587f + (c&0xFF)*0.114f);
float lumaL = ((l>>16&0xFF)*0.299f + (l>>8&0xFF)*0.587f + (l&0xFF)*0.114f);
float lumaR = ((rp>>16&0xFF)*0.299f + (rp>>8&0xFF)*0.587f + (rp&0xFF)*0.114f);
float lumaU = ((u>>16&0xFF)*0.299f + (u>>8&0xFF)*0.587f + (u&0xFF)*0.114f);
float lumaD = ((d>>16&0xFF)*0.299f + (d>>8&0xFF)*0.587f + (d&0xFF)*0.114f);
float contrast = Math.max(Math.abs(lumaL - lumaC), Math.abs(lumaR - lumaC));
contrast = Math.max(contrast, Math.max(Math.abs(lumaU - lumaC), Math.abs(lumaD - lumaC)));
if (contrast > 0.1f) {
int rr = ((c>>16&0xFF)+(l>>16&0xFF)+(rp>>16&0xFF)+(u>>16&0xFF)+(d>>16&0xFF))/5;
int g = ((c>> 8&0xFF)+(l>> 8&0xFF)+(rp>> 8&0xFF)+(u>> 8&0xFF)+(d>> 8&0xFF))/5;
int b = ((c &0xFF)+(l &0xFF)+(rp &0xFF)+(u &0xFF)+(d &0xFF))/5;
framebuffer[idx] = (rr << 16) | (g << 8) | b;
}
}
}
}
public void setBlendMode(BlendMode mode) {
this.blendMode = mode;
}
public void setCullMode(CullMode mode) {
this.cullMode = mode;
this.backfaceCulling = mode != CullMode.NONE;
}
public void setRenderMode(RenderMode mode) {
this.renderMode = mode;
}
public void setGammaCorrection(boolean enable) {
this.gammaCorrection = enable;
}
public void renderInstanced(Mesh mesh, Matrix4x4[] transforms, Texture texture) {
for (Matrix4x4 m : transforms) {
renderMesh(mesh, m, texture);
}
}
public void renderBillboard(Texture texture, Vec3 position, float size) {
Vec3 forward = new Vec3(0, 0, -1);
Vec3 right = cameraPos.sub(position).cross(new Vec3(0, 1, 0));
float rl = right.length();
if (rl < 1e-6f) right = new Vec3(1, 0, 0); else right = right.scale(1f / rl);
Vec3 up = new Vec3(0, 1, 0);
float h = size / 2;
Vec3[] corners = {
position.add(right.scale(-h)).add(up.scale(-h)),
position.add(right.scale( h)).add(up.scale(-h)),
position.add(right.scale( h)).add(up.scale( h)),
position.add(right.scale(-h)).add(up.scale( h))
};
Vertex[] verts = new Vertex[4];
float[][] uv = {{0,0},{1,0},{1,1},{0,1}};
Vec3 n = forward;
for (int i = 0; i < 4; i++) {
verts[i] = new Vertex(corners[i], n, Color.WHITE, uv[i][0], uv[i][1]);
}
int[] idx = {0,1,2,0,2,3};
Mesh quad = new Mesh(verts, idx);
renderMesh(quad, new Matrix4x4(), texture);
}
public void renderParticles(ParticleEmitter emitter, Texture texture) {
for (Particle p : emitter.particles) {
renderBillboard(texture, p.position, p.size);
}
}
public void applyBloom(float threshold, int passes) {
int[] src = framebuffer.clone();
int[] bright = new int[width * height];
for (int i = 0; i < src.length; i++) {
int r = (src[i] >> 16) & 0xFF, g = (src[i] >> 8) & 0xFF, b = src[i] & 0xFF;
float luma = 0.2126f * r + 0.7152f * g + 0.0722f * b;
if (luma > threshold * 255) {
bright[i] = src[i];
}
}
int[] blurred = bright.clone();
for (int p = 0; p < passes; p++) {
int[] tmp = blurred.clone();
for (int y = 1; y < height - 1; y++) {
for (int x = 1; x < width - 1; x++) {
int idx = y * width + x;
int rr = 0, gg = 0, bb = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
int c = tmp[(y + dy) * width + (x + dx)];
rr += (c >> 16) & 0xFF; gg += (c >> 8) & 0xFF; bb += c & 0xFF;
}
}
blurred[idx] = (rr / 9 << 16) | (gg / 9 << 8) | (bb / 9);
}
}
}
for (int i = 0; i < src.length; i++) {
int sr = (src[i] >> 16) & 0xFF, sg = (src[i] >> 8) & 0xFF, sb = src[i] & 0xFF;
int br = (blurred[i] >> 16) & 0xFF, bg = (blurred[i] >> 8) & 0xFF, bb = blurred[i] & 0xFF;
framebuffer[i] = (Math.min(255, sr + br) << 16) | (Math.min(255, sg + bg) << 8) | Math.min(255, sb + bb);
}
}
public void setFog(Color color, float near, float far) {
this.fogColor = color;
this.fogNear = near;
this.fogFar = far;
this.fogEnabled = true;
}
public void disableFog() {
this.fogEnabled = false;
}
public void setSpecular(float intensity, float shininess) {
this.specularIntensity = intensity;
this.shininess = shininess;
}
public void applySkinning(Mesh mesh, Skeleton skeleton, AnimationClip clip, float time) {
mesh.saveBindPose();
Matrix4x4[] boneMats = new Matrix4x4[skeleton.numBones];
for (int i = 0; i < skeleton.numBones; i++) boneMats[i] = new Matrix4x4();
clip.sample(time, boneMats);
Matrix4x4[] finalMats = new Matrix4x4[skeleton.numBones];
Matrix4x4[] normalMats = new Matrix4x4[skeleton.numBones];
for (int i = 0; i < skeleton.numBones; i++) {
finalMats[i] = new Matrix4x4();
finalMats[i].mul(boneMats[i], skeleton.inverseBindPose[i]);
normalMats[i] = inverseTranspose3x3(finalMats[i]);
}
for (int vi = 0; vi < mesh.vertices.length; vi++) {
Vertex v = mesh.vertices[vi];
float px = mesh.bindPositions[vi].x, py = mesh.bindPositions[vi].y, pz = mesh.bindPositions[vi].z, pw = mesh.bindPositions[vi].w;
float nx = mesh.bindNormals[vi].x, ny = mesh.bindNormals[vi].y, nz = mesh.bindNormals[vi].z;
v.position.x = 0; v.position.y = 0; v.position.z = 0; v.position.w = 0;
v.normal.x = 0; v.normal.y = 0; v.normal.z = 0;
for (int j = 0; j < 4; j++) {
int bi = v.boneIndices[j];
float bw = v.boneWeights[j];
if (bi < 0 || bi >= skeleton.numBones || bw == 0) continue;
Matrix4x4 m = finalMats[bi];
v.position.x += (m.m00 * px + m.m01 * py + m.m02 * pz + m.m03 * pw) * bw;
v.position.y += (m.m10 * px + m.m11 * py + m.m12 * pz + m.m13 * pw) * bw;
v.position.z += (m.m20 * px + m.m21 * py + m.m22 * pz + m.m23 * pw) * bw;
v.position.w += (m.m30 * px + m.m31 * py + m.m32 * pz + m.m33 * pw) * bw;
Matrix4x4 nm = normalMats[bi];
v.normal.x += (nm.m00 * nx + nm.m01 * ny + nm.m02 * nz) * bw;
v.normal.y += (nm.m10 * nx + nm.m11 * ny + nm.m12 * nz) * bw;
v.normal.z += (nm.m20 * nx + nm.m21 * ny + nm.m22 * nz) * bw;
}
}
}
public void renderAnimatedMesh(Mesh mesh, Matrix4x4 worldMatrix, Skeleton skeleton, AnimationClip clip, float time, Texture texture) {
applySkinning(mesh, skeleton, clip, time);
renderMesh(mesh, worldMatrix, texture, null);
}
public void renderMesh(Mesh mesh, Matrix4x4 worldMatrix) {
renderMesh(mesh, worldMatrix, null, null);
}
public void renderMesh(Mesh mesh, Matrix4x4 worldMatrix, Texture texture) {
renderMesh(mesh, worldMatrix, texture, null);
}
public void renderMesh(Mesh mesh, Matrix4x4 worldMatrix, Texture texture, Texture normalMap) {
mvpMatrix.mul(viewProjMatrix, worldMatrix);
for (int i = 0; i < mesh.numTriangles; i++) {
int i0 = mesh.indices[i * 3];
int i1 = mesh.indices[i * 3 + 1];
int i2 = mesh.indices[i * 3 + 2];
Vertex v0 = mesh.vertices[i0];
Vertex v1 = mesh.vertices[i1];
Vertex v2 = mesh.vertices[i2];
Vertex tv0 = transformVertex(v0, mvpMatrix, worldMatrix);
Vertex tv1 = transformVertex(v1, mvpMatrix, worldMatrix);
Vertex tv2 = transformVertex(v2, mvpMatrix, worldMatrix);
// Backface culling in world space
if (backfaceCulling) {
Vec3 normal = calculateNormal(tv0.position, tv1.position, tv2.position);
if ((cullMode == CullMode.BACK && normal.z > 0) || (cullMode == CullMode.FRONT && normal.z < 0)) continue;
}
// Compute light-space positions for shadow mapping
boolean doShadow = shadowMap != null;
if (doShadow) {
lightMVP.mul(lightVP, worldMatrix);
Vec4 lp0 = mulVec4(v0.position, lightMVP);
Vec4 lp1 = mulVec4(v1.position, lightMVP);
Vec4 lp2 = mulVec4(v2.position, lightMVP);
tv0.lpX = lp0.x; tv0.lpY = lp0.y; tv0.lpZ = lp0.z; tv0.lpW = lp0.w;
tv1.lpX = lp1.x; tv1.lpY = lp1.y; tv1.lpZ = lp1.z; tv1.lpW = lp1.w;
tv2.lpX = lp2.x; tv2.lpY = lp2.y; tv2.lpZ = lp2.z; tv2.lpW = lp2.w;
}
// Compute world-space positions for specular lighting
{
Vec4 w0 = mulVec4(v0.position, worldMatrix);
Vec4 w1 = mulVec4(v1.position, worldMatrix);
Vec4 w2 = mulVec4(v2.position, worldMatrix);
float wDiv0 = 1f / Math.max(w0.w, 1e-10f);
float wDiv1 = 1f / Math.max(w1.w, 1e-10f);
float wDiv2 = 1f / Math.max(w2.w, 1e-10f);
tv0.wx = w0.x * wDiv0; tv0.wy = w0.y * wDiv0; tv0.wz = w0.z * wDiv0;
tv1.wx = w1.x * wDiv1; tv1.wy = w1.y * wDiv1; tv1.wz = w1.z * wDiv1;
tv2.wx = w2.x * wDiv2; tv2.wy = w2.y * wDiv2; tv2.wz = w2.z * wDiv2;
tv0.nnx = tv0.normal.x; tv0.nny = tv0.normal.y; tv0.nnz = tv0.normal.z;
tv1.nnx = tv1.normal.x; tv1.nny = tv1.normal.y; tv1.nnz = tv1.normal.z;
tv2.nnx = tv2.normal.x; tv2.nny = tv2.normal.y; tv2.nnz = tv2.normal.z;
}
// Clip against near plane
Vertex[] clipped = clipTriangle(tv0, tv1, tv2);
int numVerts = clipped.length;
if (numVerts < 3) continue;
// Per-vertex multi-light accumulation (before perspective divide)
float[] lrgb = new float[3];
for (int j = 0; j < numVerts; j++) {
Vertex v = clipped[j];
Vec3 normal = v.normal.clone();
Vec3 viewDir = new Vec3(cameraPos.x - v.wx, cameraPos.y - v.wy, cameraPos.z - v.wz).normalize();
accumulateLight(new Vec3(v.wx, v.wy, v.wz), normal, viewDir, lrgb);
float r = Math.min(1, lrgb[0]);
float g = Math.min(1, lrgb[1]);
float b = Math.min(1, lrgb[2]);
v.color = new Color(Math.min(255, (int)(v.color.getRed() * r)),
Math.min(255, (int)(v.color.getGreen() * g)),
Math.min(255, (int)(v.color.getBlue() * b)));
}
// Perspective division and screen mapping
for (int j = 0; j < numVerts; j++) {
Vertex v = clipped[j];
float invW = 1.0f / Math.max(v.position.w, 1e-10f);
v.position.x *= invW;
v.position.y *= invW;
v.position.z *= invW;
v.position.w = 1.0f;
v.screenX = (int)((v.position.x * 0.5f + 0.5f) * width);
v.screenY = (int)((-v.position.y * 0.5f + 0.5f) * height);
v.depth = v.position.z;
// Store inverse W for perspective correct interpolation
v.invW = invW;
if (texture != null) {
v.u = v.u * invW;
v.v = v.v * invW;
}
if (doShadow) {
v.lpX = v.lpX * invW;
v.lpY = v.lpY * invW;
v.lpZ = v.lpZ * invW;
v.lpW = v.lpW * invW;
}
v.wx = v.wx * invW;
v.wy = v.wy * invW;
v.wz = v.wz * invW;
v.nnx = v.nnx * invW;
v.nny = v.nny * invW;
v.nnz = v.nnz * invW;
}
// Rasterize triangles
if (renderMode != RenderMode.WIREFRAME) {
if (useTileBased && threadPool != null) {
// Collect into tile batches for parallel processing
for (int j = 1; j < numVerts - 1; j++) {
int triIdx = statsTriangles++;
for (int ti = 0; ti < tileRegions.length; ti++) {
Vertex a = clipped[0], b = clipped[j], c = clipped[j + 1];
int minX = Math.max(tileRegions[ti].x, Math.max(0, Math.min(a.screenX, Math.min(b.screenX, c.screenX))));
int maxX = Math.min(tileRegions[ti].x + tileRegions[ti].w - 1, Math.min(width - 1, Math.max(a.screenX, Math.max(b.screenX, c.screenX))));
int minY = Math.max(tileRegions[ti].y, Math.max(0, Math.min(a.screenY, Math.min(b.screenY, c.screenY))));
int maxY = Math.min(tileRegions[ti].y + tileRegions[ti].h - 1, Math.min(height - 1, Math.max(a.screenY, Math.max(b.screenY, c.screenY))));
if (minX <= maxX && minY <= maxY) {
// Rasterize directly to this tile region
if (texture != null) rasterizeTexturedTriangleClipped(a, b, c, texture, normalMap, minX, maxX, minY, maxY);
else rasterizeTriangleClipped(a, b, c, minX, maxX, minY, maxY);
}
}
}
} else {
for (int j = 1; j < numVerts - 1; j++) {
Vertex a = clipped[0], b = clipped[j], c = clipped[j + 1];
if (texture != null) rasterizeTexturedTriangle(a, b, c, texture, normalMap);
else rasterizeTriangle(a, b, c);
}
}
}
// Wireframe overlay
if (renderMode != RenderMode.SOLID && clipped.length >= 3) {
Color wfColor = renderMode == RenderMode.WIREFRAME ? Color.WHITE : Color.YELLOW;
for (int j = 1; j < numVerts - 1; j++) {
drawLine(clipped[0].screenX, clipped[0].screenY, clipped[j].screenX, clipped[j].screenY, wfColor);
drawLine(clipped[j].screenX, clipped[j].screenY, clipped[j+1].screenX, clipped[j+1].screenY, wfColor);
}
drawLine(clipped[numVerts-1].screenX, clipped[numVerts-1].screenY, clipped[0].screenX, clipped[0].screenY, wfColor);
}
}
}
private void accumulateLight(Vec3 pos, Vec3 normal, Vec3 viewDir, float[] outRgb) {
outRgb[0] = outRgb[1] = outRgb[2] = 0;
for (Light l : lights) {
switch (l.type) {
case AMBIENT:
outRgb[0] += l.r * l.intensity;
outRgb[1] += l.g * l.intensity;
outRgb[2] += l.b * l.intensity;
break;
case DIRECTIONAL: {
float NdotL = Math.max(0, normal.dot(l.direction));
if (NdotL <= 0) break;
Vec3 halfDir = l.direction.add(viewDir).normalize();
float NdotH = Math.max(0, normal.dot(halfDir));
float spec = (float)Math.pow(NdotH, shininess);
float factor = l.intensity * NdotL;
outRgb[0] += l.r * factor;
outRgb[1] += l.g * factor;
outRgb[2] += l.b * factor;
if (spec > 0) {
float sf = specularIntensity * spec;
outRgb[0] += sf;
outRgb[1] += sf;
outRgb[2] += sf;
}
break;
}
case POINT: {
Vec3 toLight = l.position.sub(pos);
float dist = toLight.length();
if (dist > l.range) break;
Vec3 ldir = toLight.scale(1f / Math.max(dist, 1e-10f));
float NdotL = Math.max(0, normal.dot(ldir));
if (NdotL <= 0) break;
float atten = 1f / (l.constantAtten + l.linearAtten * dist + l.quadraticAtten * dist * dist);
Vec3 halfDir = ldir.add(viewDir).normalize();
float NdotH = Math.max(0, normal.dot(halfDir));
float spec = (float)Math.pow(NdotH, shininess);
float factor = l.intensity * NdotL * atten;
outRgb[0] += l.r * factor;
outRgb[1] += l.g * factor;
outRgb[2] += l.b * factor;
if (spec > 0) {
float sf = specularIntensity * spec * atten;
outRgb[0] += sf;
outRgb[1] += sf;
outRgb[2] += sf;
}
break;
}
case SPOT: {
Vec3 toLight = l.position.sub(pos);
float dist = toLight.length();
if (dist > l.range) break;
Vec3 ldir = toLight.scale(1f / Math.max(dist, 1e-10f));
float NdotL = Math.max(0, normal.dot(ldir));
if (NdotL <= 0) break;
float cosOuter = (float)Math.cos(l.spotOuterAngle * Math.PI / 180);
float cosInner = (float)Math.cos(l.spotInnerAngle * Math.PI / 180);
float cosAngle = -ldir.dot(l.direction);
float spotFactor;
if (cosAngle <= cosOuter) {
spotFactor = 0;
} else if (cosAngle >= cosInner) {
spotFactor = 1;
} else {
spotFactor = (cosAngle - cosOuter) / (cosInner - cosOuter);
}
if (spotFactor <= 0) break;
float atten = 1f / (l.constantAtten + l.linearAtten * dist + l.quadraticAtten * dist * dist);
Vec3 halfDir = ldir.add(viewDir).normalize();
float NdotH = Math.max(0, normal.dot(halfDir));
float spec = (float)Math.pow(NdotH, shininess);
float factor = l.intensity * NdotL * atten * spotFactor;
outRgb[0] += l.r * factor;
outRgb[1] += l.g * factor;
outRgb[2] += l.b * factor;
if (spec > 0) {
float sf = specularIntensity * spec * atten * spotFactor;
outRgb[0] += sf;
outRgb[1] += sf;
outRgb[2] += sf;
}
break;
}
}
}
}
private Color scaleColor(Color color, float factor) {
int r = Math.min(255, Math.max(0, (int)(color.getRed() * factor)));
int g = Math.min(255, Math.max(0, (int)(color.getGreen() * factor)));
int b = Math.min(255, Math.max(0, (int)(color.getBlue() * factor)));
return new Color(r, g, b);
}
private Vertex transformVertex(Vertex v, Matrix4x4 mat, Matrix4x4 world) {
Vertex result = new Vertex();
result.position.x = mat.m00 * v.position.x + mat.m01 * v.position.y + mat.m02 * v.position.z + mat.m03 * v.position.w;
result.position.y = mat.m10 * v.position.x + mat.m11 * v.position.y + mat.m12 * v.position.z + mat.m13 * v.position.w;
result.position.z = mat.m20 * v.position.x + mat.m21 * v.position.y + mat.m22 * v.position.z + mat.m23 * v.position.w;
result.position.w = mat.m30 * v.position.x + mat.m31 * v.position.y + mat.m32 * v.position.z + mat.m33 * v.position.w;
// Transform normal by world matrix (upper-left 3x3)
result.normal.x = world.m00 * v.normal.x + world.m01 * v.normal.y + world.m02 * v.normal.z;
result.normal.y = world.m10 * v.normal.x + world.m11 * v.normal.y + world.m12 * v.normal.z;
result.normal.z = world.m20 * v.normal.x + world.m21 * v.normal.y + world.m22 * v.normal.z;
result.normal.normalize();
result.color = v.color;
result.u = v.u;
result.v = v.v;
result.invW = v.invW;
result.lpX = v.lpX;
result.lpY = v.lpY;
result.lpZ = v.lpZ;
result.lpW = v.lpW;
result.wx = v.wx;
result.wy = v.wy;
result.wz = v.wz;
result.nnx = v.nnx;
result.nny = v.nny;
result.nnz = v.nnz;
return result;
}
private Vec3 calculateNormal(Vec4 a, Vec4 b, Vec4 c) {
float aw = a.w == 0 ? 1 : a.w, bw = b.w == 0 ? 1 : b.w, cw = c.w == 0 ? 1 : c.w;
Vec3 ab = new Vec3(b.x / bw - a.x / aw, b.y / bw - a.y / aw, b.z / bw - a.z / aw);
Vec3 ac = new Vec3(c.x / cw - a.x / aw, c.y / cw - a.y / aw, c.z / cw - a.z / aw);
Vec3 normal = ab.cross(ac);
normal.normalize();
return normal;
}
private Vec3 calculateNormal(Vec3 a, Vec3 b, Vec3 c) {
Vec3 ab = new Vec3(b.x - a.x, b.y - a.y, b.z - a.z);
Vec3 ac = new Vec3(c.x - a.x, c.y - a.y, c.z - a.z);
Vec3 normal = ab.cross(ac);
normal.normalize();
return normal;
}
private Vec3 applyMatrix3(Vec4 v, Matrix4x4 m) {
return new Vec3(
m.m00 * v.x + m.m01 * v.y + m.m02 * v.z,
m.m10 * v.x + m.m11 * v.y + m.m12 * v.z,
m.m20 * v.x + m.m21 * v.y + m.m22 * v.z
);
}
private Matrix4x4 inverseTranspose3x3(Matrix4x4 m) {
float a = m.m00, b = m.m01, c = m.m02;
float d = m.m10, e = m.m11, f = m.m12;
float g = m.m20, h = m.m21, i = m.m22;
float det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
if (det == 0) return m;
float invDet = 1f / det;
Matrix4x4 r = new Matrix4x4();
r.m00 = (e * i - f * h) * invDet;
r.m01 = (c * h - b * i) * invDet;
r.m02 = (b * f - c * e) * invDet;
r.m10 = (f * g - d * i) * invDet;
r.m11 = (a * i - c * g) * invDet;
r.m12 = (c * d - a * f) * invDet;
r.m20 = (d * h - e * g) * invDet;
r.m21 = (b * g - a * h) * invDet;
r.m22 = (a * e - b * d) * invDet;
return r;
}
private Vec4 mulVec4(Vec4 v, Matrix4x4 m) {
Vec4 r = new Vec4();
r.x = m.m00 * v.x + m.m01 * v.y + m.m02 * v.z + m.m03 * v.w;
r.y = m.m10 * v.x + m.m11 * v.y + m.m12 * v.z + m.m13 * v.w;
r.z = m.m20 * v.x + m.m21 * v.y + m.m22 * v.z + m.m23 * v.w;
r.w = m.m30 * v.x + m.m31 * v.y + m.m32 * v.z + m.m33 * v.w;
return r;
}
private Vertex[] clipTriangle(Vertex v0, Vertex v1, Vertex v2) {
float[][] planes = {
{ 1, 0, 0, 1}, {-1, 0, 0, 1},
{ 0, 1, 0, 1}, { 0, -1, 0, 1},
{ 0, 0, 1, 1}, { 0, 0, -1, 1}
};
java.util.List<Vertex> input = new java.util.ArrayList<>();
input.add(v0); input.add(v1); input.add(v2);
for (int p = 0; p < 6; p++) {
float px = planes[p][0], py = planes[p][1], pz = planes[p][2], pw = planes[p][3];
java.util.List<Vertex> output = new java.util.ArrayList<>();
int n = input.size();
if (n == 0) break;
for (int i = 0; i < n; i++) {
Vertex a = input.get(i);
Vertex b = input.get((i + 1) % n);
float dA = a.position.x * px + a.position.y * py + a.position.z * pz + a.position.w * pw;
float dB = b.position.x * px + b.position.y * py + b.position.z * pz + b.position.w * pw;
boolean insideA = dA >= 0;
boolean insideB = dB >= 0;
if (insideA) output.add(a);
if (insideA != insideB) {
float t = dA / (dA - dB);
output.add(interpolateVertex(a, b, t));
}
}
input = output;
}
return input.toArray(new Vertex[0]);
}
private Vertex interpolateVertex(Vertex a, Vertex b, float t) {
Vertex result = new Vertex();
result.position.x = a.position.x + (b.position.x - a.position.x) * t;
result.position.y = a.position.y + (b.position.y - a.position.y) * t;
result.position.z = a.position.z + (b.position.z - a.position.z) * t;
result.position.w = a.position.w + (b.position.w - a.position.w) * t;
result.normal.x = a.normal.x + (b.normal.x - a.normal.x) * t;
result.normal.y = a.normal.y + (b.normal.y - a.normal.y) * t;
result.normal.z = a.normal.z + (b.normal.z - a.normal.z) * t;
result.normal.normalize();
result.color = lerpColor(a.color, b.color, t);
result.u = a.u + (b.u - a.u) * t;
result.v = a.v + (b.v - a.v) * t;
result.invW = a.invW + (b.invW - a.invW) * t;
result.lpX = a.lpX + (b.lpX - a.lpX) * t;
result.lpY = a.lpY + (b.lpY - a.lpY) * t;
result.lpZ = a.lpZ + (b.lpZ - a.lpZ) * t;
result.lpW = a.lpW + (b.lpW - a.lpW) * t;
result.wx = a.wx + (b.wx - a.wx) * t;
result.wy = a.wy + (b.wy - a.wy) * t;
result.wz = a.wz + (b.wz - a.wz) * t;
result.nnx = a.nnx + (b.nnx - a.nnx) * t;
result.nny = a.nny + (b.nny - a.nny) * t;
result.nnz = a.nnz + (b.nnz - a.nnz) * t;
return result;
}
private void rasterizeTriangle(Vertex v0, Vertex v1, Vertex v2) {
Vertex[] verts = {v0, v1, v2};
sortByY(verts);
// Degenerate triangle check
if (verts[0].screenY == verts[2].screenY) return;
int yStart = Math.max(0, verts[0].screenY);
int yEnd = Math.min(height - 1, verts[2].screenY);
for (int y = yStart; y <= yEnd; y++) {
// Calculate scanline endpoints
float t1 = (y - verts[0].screenY) / (float)(verts[2].screenY - verts[0].screenY);
float t2;
int rightA, rightB;
int x1 = lerp(verts[0].screenX, verts[2].screenX, t1);
int x2;
if (y < verts[1].screenY) {
float tTop = verts[1].screenY - verts[0].screenY;
t2 = tTop != 0 ? (y - verts[0].screenY) / tTop : 0;
x2 = lerp(verts[0].screenX, verts[1].screenX, t2);
rightA = 0; rightB = 1;
} else {
float denom = verts[2].screenY - verts[1].screenY;
t2 = denom != 0 ? (y - verts[1].screenY) / denom : 0;
x2 = lerp(verts[1].screenX, verts[2].screenX, t2);
rightA = 1; rightB = 2;
}
// Interpolate Z and color at endpoints (before potential swap)
float z1 = lerp(verts[0].depth, verts[2].depth, t1);
float z2 = lerp(verts[rightA].depth, verts[rightB].depth, t2);
float lx1 = lerp(verts[0].lpX, verts[2].lpX, t1);
float lx2 = lerp(verts[rightA].lpX, verts[rightB].lpX, t2);
float ly1 = lerp(verts[0].lpY, verts[2].lpY, t1);
float ly2 = lerp(verts[rightA].lpY, verts[rightB].lpY, t2);
float lz1 = lerp(verts[0].lpZ, verts[2].lpZ, t1);
float lz2 = lerp(verts[rightA].lpZ, verts[rightB].lpZ, t2);
float lw1 = lerp(verts[0].lpW, verts[2].lpW, t1);
float lw2 = lerp(verts[rightA].lpW, verts[rightB].lpW, t2);
float iw1 = lerp(verts[0].invW, verts[2].invW, t1);
float iw2 = lerp(verts[rightA].invW, verts[rightB].invW, t2);
Color c1 = lerpColor(verts[0].color, verts[2].color, t1);
Color c2 = lerpColor(verts[rightA].color, verts[rightB].color, t2);
if (x1 > x2) {
int tmp = x1; x1 = x2; x2 = tmp;
float tf; tf = z1; z1 = z2; z2 = tf;
tf = lx1; lx1 = lx2; lx2 = tf;
tf = ly1; ly1 = ly2; ly2 = tf;
tf = lz1; lz1 = lz2; lz2 = tf;
tf = lw1; lw1 = lw2; lw2 = tf;
tf = iw1; iw1 = iw2; iw2 = tf;
Color tc = c1; c1 = c2; c2 = tc;
}
x1 = Math.max(0, x1);
x2 = Math.min(width - 1, x2);
if (x1 > x2) continue;
boolean doShadow = shadowMap != null;
for (int x = x1; x <= x2; x++) {
float t = (x - x1) / (float)(x2 - x1 + 1);
float depth = lerp(z1, z2, t);
int index = y * width + x;
if (depth < zBuffer[index]) {
zBuffer[index] = depth;
Color color = lerpColor(c1, c2, t);
if (doShadow) {
float iw = lerp(iw1, iw2, t);
float lpx = lerp(lx1, lx2, t) / iw;
float lpy = lerp(ly1, ly2, t) / iw;
float lpz = lerp(lz1, lz2, t) / iw;
float lpw = lerp(lw1, lw2, t) / iw;
if (lpw > 0) {
float smU = (lpx / lpw) * 0.5f + 0.5f;
float smV = (-lpy / lpw) * 0.5f + 0.5f;
float smD = (lpz / lpw) * 0.5f + 0.5f;
if (smU >= 0 && smU < 1 && smV >= 0 && smV < 1) {
int smX = (int)(smU * shadowMap.size);
int smY = (int)(smV * shadowMap.size);
int sm = 0, total = 0;
int r = 1;
for (int dy = -r; dy <= r; dy++) {
for (int dx = -r; dx <= r; dx++) {
int sx = smX + dx, sy = smY + dy;
if (sx >= 0 && sx < shadowMap.size && sy >= 0 && sy < shadowMap.size) {
total++;
if (smD <= shadowMap.depthBuffer[sy * shadowMap.size + sx] + shadowBias)
sm++;
}
}
}
float shadow = (float)sm / total;
color = scaleColor(color, 1.0f - shadowIntensity * (1.0f - shadow));
}
}
}
writeFragment(index, color, depth);
}
}
}
}
private void rasterizeTexturedTriangle(Vertex vert0, Vertex vert1, Vertex vert2, Texture texture, Texture normalMap) {
// Pre-compute tangent frame for normal mapping (world-space positions)
boolean hasNormalMap = normalMap != null;
Vec3 tangent = new Vec3(), bitangent = new Vec3();
if (hasNormalMap) {
float invW0 = Math.abs(vert0.invW) > 1e-10f ? vert0.invW : 1f;
float invW1 = Math.abs(vert1.invW) > 1e-10f ? vert1.invW : 1f;
float invW2 = Math.abs(vert2.invW) > 1e-10f ? vert2.invW : 1f;
float p0x = vert0.wx / invW0, p0y = vert0.wy / invW0, p0z = vert0.wz / invW0;
float p1x = vert1.wx / invW1, p1y = vert1.wy / invW1, p1z = vert1.wz / invW1;
float p2x = vert2.wx / invW2, p2y = vert2.wy / invW2, p2z = vert2.wz / invW2;
Vec3 edge1 = new Vec3(p1x - p0x, p1y - p0y, p1z - p0z);
Vec3 edge2 = new Vec3(p2x - p0x, p2y - p0y, p2z - p0z);
float du1 = vert1.u - vert0.u, dv1 = vert1.v - vert0.v;
float du2 = vert2.u - vert0.u, dv2 = vert2.v - vert0.v;
float det = du1 * dv2 - du2 * dv1;
if (Math.abs(det) > 1e-6f) {
float f = 1f / det;
tangent.x = (edge1.x * dv2 - edge2.x * dv1) * f;
tangent.y = (edge1.y * dv2 - edge2.y * dv1) * f;
tangent.z = (edge1.z * dv2 - edge2.z * dv1) * f;
tangent.normalize();
bitangent.x = (edge2.x * du1 - edge1.x * du2) * f;
bitangent.y = (edge2.y * du1 - edge1.y * du2) * f;
bitangent.z = (edge2.z * du1 - edge1.z * du2) * f;
bitangent.normalize();
} else {
hasNormalMap = false;
}
}
Vertex[] verts = {vert0, vert1, vert2};
sortByY(verts);
// Degenerate triangle check
if (verts[0].screenY == verts[2].screenY) return;
int yStart = Math.max(0, verts[0].screenY);
int yEnd = Math.min(height - 1, verts[2].screenY);
for (int y = yStart; y <= yEnd; y++) {
// Calculate scanline endpoints
float t1 = (y - verts[0].screenY) / (float)(verts[2].screenY - verts[0].screenY);
float t2;
int rightA, rightB;
int x1 = lerp(verts[0].screenX, verts[2].screenX, t1);
int x2;
if (y < verts[1].screenY) {
float tTop = verts[1].screenY - verts[0].screenY;
t2 = tTop != 0 ? (y - verts[0].screenY) / tTop : 0;
x2 = lerp(verts[0].screenX, verts[1].screenX, t2);
rightA = 0; rightB = 1;
} else {
float denom = verts[2].screenY - verts[1].screenY;
t2 = denom != 0 ? (y - verts[1].screenY) / denom : 0;
x2 = lerp(verts[1].screenX, verts[2].screenX, t2);
rightA = 1; rightB = 2;
}
// Interpolate attributes at endpoints (before potential swap)
float z1 = lerp(verts[0].depth, verts[2].depth, t1);
float z2 = lerp(verts[rightA].depth, verts[rightB].depth, t2);
float u1 = lerp(verts[0].u, verts[2].u, t1);
float u2 = lerp(verts[rightA].u, verts[rightB].u, t2);
float v1 = lerp(verts[0].v, verts[2].v, t1);
float v2 = lerp(verts[rightA].v, verts[rightB].v, t2);
float iw1 = lerp(verts[0].invW, verts[2].invW, t1);
float iw2 = lerp(verts[rightA].invW, verts[rightB].invW, t2);
float lx1 = lerp(verts[0].lpX, verts[2].lpX, t1);
float lx2 = lerp(verts[rightA].lpX, verts[rightB].lpX, t2);
float ly1 = lerp(verts[0].lpY, verts[2].lpY, t1);
float ly2 = lerp(verts[rightA].lpY, verts[rightB].lpY, t2);
float lz1 = lerp(verts[0].lpZ, verts[2].lpZ, t1);
float lz2 = lerp(verts[rightA].lpZ, verts[rightB].lpZ, t2);
float lw1 = lerp(verts[0].lpW, verts[2].lpW, t1);
float lw2 = lerp(verts[rightA].lpW, verts[rightB].lpW, t2);
float nnx1 = lerp(verts[0].nnx, verts[2].nnx, t1);
float nnx2 = lerp(verts[rightA].nnx, verts[rightB].nnx, t2);
float nny1 = lerp(verts[0].nny, verts[2].nny, t1);
float nny2 = lerp(verts[rightA].nny, verts[rightB].nny, t2);
float nnz1 = lerp(verts[0].nnz, verts[2].nnz, t1);
float nnz2 = lerp(verts[rightA].nnz, verts[rightB].nnz, t2);
float wx1 = lerp(verts[0].wx, verts[2].wx, t1);
float wx2 = lerp(verts[rightA].wx, verts[rightB].wx, t2);
float wy1 = lerp(verts[0].wy, verts[2].wy, t1);
float wy2 = lerp(verts[rightA].wy, verts[rightB].wy, t2);
float wz1 = lerp(verts[0].wz, verts[2].wz, t1);
float wz2 = lerp(verts[rightA].wz, verts[rightB].wz, t2);
Color c1 = lerpColor(verts[0].color, verts[2].color, t1);
Color c2 = lerpColor(verts[rightA].color, verts[rightB].color, t2);
if (x1 > x2) {
int tmp = x1; x1 = x2; x2 = tmp;
float tf; tf = z1; z1 = z2; z2 = tf;
tf = u1; u1 = u2; u2 = tf;
tf = v1; v1 = v2; v2 = tf;
tf = iw1; iw1 = iw2; iw2 = tf;
tf = lx1; lx1 = lx2; lx2 = tf;
tf = ly1; ly1 = ly2; ly2 = tf;
tf = lz1; lz1 = lz2; lz2 = tf;
tf = lw1; lw1 = lw2; lw2 = tf;
tf = nnx1; nnx1 = nnx2; nnx2 = tf;
tf = nny1; nny1 = nny2; nny2 = tf;
tf = nnz1; nnz1 = nnz2; nnz2 = tf;
tf = wx1; wx1 = wx2; wx2 = tf;
tf = wy1; wy1 = wy2; wy2 = tf;
tf = wz1; wz1 = wz2; wz2 = tf;
Color tc = c1; c1 = c2; c2 = tc;
}
x1 = Math.max(0, x1);
x2 = Math.min(width - 1, x2);
if (x1 > x2) continue;
boolean doShadow = shadowMap != null;
for (int x = x1; x <= x2; x++) {
float t = (x - x1) / (float)(x2 - x1 + 1);
float depth = lerp(z1, z2, t);
int index = y * width + x;
if (depth < zBuffer[index]) {
zBuffer[index] = depth;
// Perspective correct texture mapping
float iw = lerp(iw1, iw2, t);
float u = lerp(u1, u2, t) / iw;
float v = lerp(v1, v2, t) / iw;
// Wrap texture coordinates
u = ((u % 1.0f) + 1.0f) % 1.0f;
v = ((v % 1.0f) + 1.0f) % 1.0f;
// Mipmap LOD selection
float lod = 0;
if (texture.mipmaps != null) {
float du = Math.abs(lerp(u1, u2, t + 0.01f) / iw - u) * texture.width;
float dv = Math.abs(lerp(v1, v2, t + 0.01f) / iw - v) * texture.height;
lod = (float)(Math.log(Math.max(du, dv)) / Math.log(2));
}
int texColor = texture.sample(u, v, lod);
Color color = lerpColor(c1, c2, t);
color = modulateColor(color, new Color(texColor));
// Per-pixel normal mapping and lighting
if (hasNormalMap) {
int nmX = (int)(u * normalMap.width);
int nmY = (int)(v * normalMap.height);
nmX = Math.min(normalMap.width - 1, Math.max(0, nmX));
nmY = Math.min(normalMap.height - 1, Math.max(0, nmY));
int nmColor = normalMap.pixels[nmY * normalMap.width + nmX];
float nx = ((nmColor >> 16) & 0xFF) / 127.5f - 1f;
float ny = ((nmColor >> 8) & 0xFF) / 127.5f - 1f;
float nz = (nmColor & 0xFF) / 127.5f - 1f;
float nnx = lerp(nnx1, nnx2, t) / iw;
float nny = lerp(nny1, nny2, t) / iw;
float nnz = lerp(nnz1, nnz2, t) / iw;
float invN = 1f / (float)Math.sqrt(nnx * nnx + nny * nny + nnz * nnz);
float wnx = nnx * invN, wny = nny * invN, wnz = nnz * invN;
// TBN transform
float ddx = nx * tangent.x + ny * bitangent.x + nz * wnx;
float ddy = nx * tangent.y + ny * bitangent.y + nz * wny;
float ddz = nx * tangent.z + ny * bitangent.z + nz * wnz;
float invD = 1f / (float)Math.sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
ddx *= invD; ddy *= invD; ddz *= invD;
// Per-pixel multi-light accumulation
float wpx = lerp(wx1, wx2, t) / iw;
float wpy = lerp(wy1, wy2, t) / iw;
float wpz = lerp(wz1, wz2, t) / iw;
Vec3 pn = new Vec3(ddx, ddy, ddz);
Vec3 pv = new Vec3(cameraPos.x - wpx, cameraPos.y - wpy, cameraPos.z - wpz).normalize();
float[] lr = new float[3];
accumulateLight(new Vec3(wpx, wpy, wpz), pn, pv, lr);
float lr2 = Math.min(1, lr[0]);
float lg = Math.min(1, lr[1]);
float lb = Math.min(1, lr[2]);
int pr = (int)(color.getRed() * lr2);
int pg = (int)(color.getGreen() * lg);
int pb = (int)(color.getBlue() * lb);
color = new Color(Math.min(255, pr), Math.min(255, pg), Math.min(255, pb));
}