-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgraphics_vk_shaderraster.cpp
More file actions
1344 lines (1283 loc) · 55.8 KB
/
Copy pathgraphics_vk_shaderraster.cpp
File metadata and controls
1344 lines (1283 loc) · 55.8 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
#include "subsystems/graphics/graphics_vk_internal.h"
#include "subsystems/graphics/graphics_vk_spirv.h"
#include "drivers/video/framebuffer.h"
#include "util/soft_float.h"
/*
* DuetOS — SPIR-V shader-based rasterizer hook.
*
* Bridge between the command-buffer replay and the
* `graphics_vk_spirv` interpreter. When `BindPipeline` records a
* pipeline whose VS + FS modules both have a parseable Program,
* `ShaderRasterizeDraw` runs the interpreter for each vertex
* (producing gl_Position) and each pixel (producing the fragment
* colour). Returns true on success so the caller skips the
* fixed-function fallback.
*
* What this v1 hook supports:
* - Graphics pipeline with one vertex shader + one fragment
* shader, both parsed into a Program by the v1 SPIR-V parser.
* - Vertex shader's Input layout: Location 0 carrying the
* position attribute (vec2 / vec3 — the first 2 components
* consumed; vec3.z fed to gl_Position via the shader's own
* mapping if the shader writes one). Subsequent Locations
* carry attribute data the shader picks up via OpLoad.
* - Vertex shader's Output layout: a Block (gl_PerVertex)
* whose member 0 is BuiltIn Position (vec4) — i.e. the
* standard glslang output — OR a bare vec4 Output decorated
* BuiltIn Position. Output is read from byte offset 0 of the
* Output variable backing.
* - Fragment shader's Output layout: a single Location 0 vec4
* RGBA written via OpStore. The components are clamped to
* [0, 1] and packed BGRA8 for the framebuffer.
*
* Shape NOT supported (falls back to fixed-function):
* - Vertex strides other than the canonical layout
* `{vec2/vec3 pos; padding}` aligned to 8 bytes — UNLESS the
* caller attaches an explicit VkSetVertexInputDuet
* description, in which case multi-binding lookups + the
* declared (binding, offset, format) tuple drive each fetch.
* - Topologies other than TriangleList (the fixed-function
* path handles Strip / Fan / Lines / Points).
* - Anything that needs OpKill-as-write — discards are honoured
* by skipping the pixel; the pixel-painted counter advances
* only on actual writes.
*
* The hook is a true opt-in: the existing fixed-function path is
* unchanged and remains the default for any pipeline that
* doesn't satisfy the criteria above. Visible behaviour for the
* gfxdemo + boot self-test is identical until a caller actually
* binds a parseable SPIR-V pipeline.
*/
namespace duetos::subsystems::graphics::internal
{
using ::duetos::core::Sf32;
using ::duetos::core::Sf32FromBits;
using ::duetos::core::Sf32ToBits;
namespace
{
// IEEE 754 bit patterns for 0.0 and 1.0 to clamp without
// pulling in float math at the call site.
constexpr u32 kBit0 = 0u;
constexpr u32 kBit1 = 0x3F800000u;
// Clamp an Sf32 to [0, 1] and convert to a u8 in [0, 255]. NaN
// snaps to 0; +inf to 255.
u8 ToUnorm8(Sf32 x)
{
if (::duetos::core::Sf32IsNaN(x))
return 0;
Sf32 clamped = ::duetos::core::Sf32Clamp(x, Sf32FromBits(kBit0), Sf32FromBits(kBit1));
// Multiply by 255 then truncate.
const Sf32 scaled = ::duetos::core::Sf32Mul(clamped, ::duetos::core::Sf32FromI32(255));
const i32 v = ::duetos::core::Sf32ToI32(scaled);
if (v < 0)
return 0;
if (v > 255)
return 255;
return static_cast<u8>(v);
}
u32 PackArgb(Sf32 r, Sf32 g, Sf32 b, Sf32 a)
{
const u8 R = ToUnorm8(r);
const u8 G = ToUnorm8(g);
const u8 B = ToUnorm8(b);
const u8 A = ToUnorm8(a);
return (static_cast<u32>(A) << 24) | (static_cast<u32>(R) << 16) | (static_cast<u32>(G) << 8) | static_cast<u32>(B);
}
// Per-varying snapshot taken once per vertex after the VS runs.
// `data[]` holds the Sf32 bit pattern for each scalar component of
// the VS Output at this Location, packed in natural order. The
// fragment-side interpolation pass reads the same Location off
// each of the 3 vertices' snapshots and writes the interpolated
// value into the matching FS Input.
constexpr u32 kMaxVaryingComponents = 16; // up to vec4 + a few extras
constexpr u32 kMaxVaryings = 8;
struct VaryingSnapshot
{
u32 location;
u32 component_count;
u32 data[kMaxVaryingComponents];
};
// Run a vertex shader for one vertex. Reads the vertex's
// per-attribute data from `vertex_buffer + vertex_index * stride`
// according to the shader's Input Locations, then executes the
// "main" entry point. Writes the gl_Position output components
// into `pos_out[0..3]` (vec4). If `varying_out` is non-null,
// also snapshots every Location-decorated Output the VS wrote
// (up to `varying_cap` entries) so the rasterizer can interpolate
// them per-pixel. When `pipe` carries an explicit vertex-input
// description (via VkSetVertexInputDuet), each Input is fetched
// at the (binding, offset) declared by the caller; otherwise the
// canonical 16-byte-per-Location fallback layout applies.
// Returns false if the shader can't be run.
bool RunVertexShader(spirv::Program* vs, const u8* vb, u64 vb_size, u64 stride, u32 vertex_index, u32* pos_out,
VaryingSnapshot* varying_out, u32 varying_cap, u32* varying_n_out, const PipelineRecord* pipe_rec,
const RasterState& st_ref_for_attrs)
{
if (vs == nullptr || vb == nullptr || pos_out == nullptr)
return false;
const u64 base = static_cast<u64>(vertex_index) * stride;
if (base + stride > vb_size)
return false;
spirv::ResetIO(vs);
if (pipe_rec != nullptr && pipe_rec->vertex_attribute_count > 0)
{
// Explicit description path: walk the attribute table and
// fetch each entry from its declared (binding, offset).
// Now honours multi-binding: each attribute can reference
// a different VkBuffer via its `binding` field; the
// per-binding slots in RasterState provide the buffer
// pointers.
(void)vb;
(void)vb_size;
for (u32 i = 0; i < pipe_rec->vertex_attribute_count; ++i)
{
const VkVertexAttributeDuet& a = pipe_rec->vertex_attributes[i];
u32 b_stride = static_cast<u32>(stride);
for (u32 b = 0; b < pipe_rec->vertex_binding_count; ++b)
{
if (pipe_rec->vertex_bindings[b].binding == a.binding)
{
b_stride = pipe_rec->vertex_bindings[b].stride_bytes;
break;
}
}
// Resolve the per-binding vertex buffer. Falls back to
// the legacy single-buffer path when the binding slot
// is unbound — that keeps single-binding callers
// working unchanged.
VkBuffer vb_handle = 0;
u64 vb_off = 0;
if (a.binding < RasterState::kMaxVbBindings)
{
vb_handle = st_ref_for_attrs.vb_per_binding[a.binding];
vb_off = st_ref_for_attrs.vb_offset_per_binding[a.binding];
}
if (vb_handle == 0)
{
vb_handle = st_ref_for_attrs.vertex_buffer;
vb_off = st_ref_for_attrs.vertex_offset;
}
if (vb_handle == 0 || !HandleInRange(vb_handle, kBufferBase))
continue;
const u32 bslot = SlotOf(vb_handle, kBufferBase);
if (!PoolIsLive(g_buffer_pool, bslot))
continue;
const BufferRecord& brec = g_buffer_data[bslot];
if (brec.backing == nullptr)
continue;
const u8* buf_base = static_cast<const u8*>(brec.backing) + brec.backing_offset + vb_off;
const u64 buf_size = (brec.size > vb_off) ? brec.size - vb_off : 0u;
const u64 vbase = static_cast<u64>(vertex_index) * b_stride;
const u64 off = vbase + a.offset_bytes;
if (off + a.byte_size > buf_size)
continue;
(void)spirv::WriteInputLocation(vs, a.location, buf_base + off, a.byte_size);
}
}
else
{
// Fallback canonical layout: Location N at offset N * 16.
for (u32 loc = 0; loc < 4; ++loc)
{
const u64 off = base + static_cast<u64>(loc) * 16u;
if (off + 16u > vb_size)
break;
(void)spirv::WriteInputLocation(vs, loc, vb + off, 16u);
}
}
// BuiltIn VertexIndex.
(void)spirv::WriteInputBuiltin(vs, spirv::builtins::kVertexIndex, &vertex_index, sizeof(vertex_index));
if (!spirv::ExecuteEntryPoint(vs, "main"))
return false;
if (!spirv::ReadOutputBuiltin(vs, spirv::builtins::kPosition, pos_out, 16u))
{
// Fallback: read Location 0 in case the shader writes
// position to a non-BuiltIn Output.
if (!spirv::ReadOutputLocation(vs, 0, pos_out, 16u))
return false;
}
if (varying_out != nullptr && varying_n_out != nullptr)
{
spirv::LocationVar locs[kMaxVaryings]{};
const u32 n = spirv::EnumerateLocationVars(vs, spirv::StorageClass::Output, locs, kMaxVaryings);
const u32 nb = (n < varying_cap) ? n : varying_cap;
for (u32 i = 0; i < nb; ++i)
{
varying_out[i].location = locs[i].location;
varying_out[i].component_count =
(locs[i].component_count < kMaxVaryingComponents) ? locs[i].component_count : kMaxVaryingComponents;
const u32 byte_size = varying_out[i].component_count * 4u;
(void)spirv::ReadOutputLocation(vs, locs[i].location, varying_out[i].data, byte_size);
}
*varying_n_out = nb;
}
return true;
}
// Run a fragment shader for one pixel. Sets gl_FragCoord then
// executes the entry point; reads the Location 0 vec4 colour and
// returns the packed BGRA8 word in `argb_out`. If `varyings` is
// non-null, writes the interpolated values to each matching FS
// Input Location before executing.
bool RunFragmentShader(spirv::Program* fs, const u32 pixel_xy[2], const VaryingSnapshot* varyings, u32 varying_n,
u32* argb_out)
{
if (fs == nullptr || argb_out == nullptr)
return false;
spirv::ResetIO(fs);
// gl_FragCoord is a vec4 (x, y, z, 1/w). v1 supplies (px, py,
// 0, 1) so a shader that derives anything from gl_FragCoord
// sees the right pixel-space coordinate. Z and 1/w are zero
// because the v1 raster doesn't yet plumb perspective-correct
// interpolation.
Sf32 fc[4] = {::duetos::core::Sf32FromU32(pixel_xy[0]), ::duetos::core::Sf32FromU32(pixel_xy[1]),
::duetos::core::Sf32Zero(), ::duetos::core::Sf32One()};
u32 fc_bits[4] = {Sf32ToBits(fc[0]), Sf32ToBits(fc[1]), Sf32ToBits(fc[2]), Sf32ToBits(fc[3])};
(void)spirv::WriteInputBuiltin(fs, spirv::builtins::kFragCoord, fc_bits, sizeof(fc_bits));
// Plumb interpolated varyings. The rasterizer already
// packed `varyings[i].data[]` with the linearly-interpolated
// Sf32 components for the FS Input at `varyings[i].location`.
for (u32 i = 0; i < varying_n; ++i)
{
const u32 bytes = varyings[i].component_count * 4u;
(void)spirv::WriteInputLocation(fs, varyings[i].location, varyings[i].data, bytes);
}
if (!spirv::ExecuteEntryPoint(fs, "main"))
return false;
// OpKill terminates the FS without producing a colour — the
// caller's per-pixel loop must skip the pixel paint. Return
// success-with-discard so RunFragmentShader's contract (true
// iff the shader executed) stays clean; the discard bit
// travels back through ExecuteEntryPointWasKilled() instead
// of an extra out-param.
if (spirv::ExecuteEntryPointWasKilled())
{
*argb_out = 0u;
return true;
}
u32 color_bits[4] = {0, 0, 0, Sf32ToBits(::duetos::core::Sf32One())};
if (!spirv::ReadOutputLocation(fs, 0, color_bits, sizeof(color_bits)))
return false;
*argb_out = PackArgb(Sf32FromBits(color_bits[0]), Sf32FromBits(color_bits[1]), Sf32FromBits(color_bits[2]),
Sf32FromBits(color_bits[3]));
return true;
}
// Sf32 helper: a*w0 + b*w1 + c*w2 where w0+w1+w2 = 1. Used by
// the per-pixel varying interpolation. No clamping — varyings
// can legitimately be negative or > 1.
Sf32 BaryLerp(Sf32 a, Sf32 b, Sf32 c, Sf32 w0, Sf32 w1, Sf32 w2)
{
const Sf32 t0 = ::duetos::core::Sf32Mul(a, w0);
const Sf32 t1 = ::duetos::core::Sf32Mul(b, w1);
const Sf32 t2 = ::duetos::core::Sf32Mul(c, w2);
return ::duetos::core::Sf32Add(::duetos::core::Sf32Add(t0, t1), t2);
}
// Convert a vec4 clip-space position into pixel coordinates by
// applying the standard NDC -> viewport mapping. Returns false if
// the position is degenerate (w == 0) or behind the eye. v1 uses
// the full framebuffer as the viewport — no glViewport / scissor
// shrinking yet on this path.
bool ClipToPixel(const u32 pos_bits[4], u32 fb_w, u32 fb_h, i32* px_out, i32* py_out)
{
const Sf32 x = Sf32FromBits(pos_bits[0]);
const Sf32 y = Sf32FromBits(pos_bits[1]);
const Sf32 w = Sf32FromBits(pos_bits[3]);
if (::duetos::core::Sf32IsZero(w) || ::duetos::core::Sf32IsNaN(w))
return false;
// NDC = clip / w.
const Sf32 ndc_x = ::duetos::core::Sf32Div(x, w);
const Sf32 ndc_y = ::duetos::core::Sf32Div(y, w);
// Viewport: px = (ndc_x + 1) * fb_w / 2; py = (1 - ndc_y) * fb_h / 2
// (Vulkan y-down NDC has the same sign as the framebuffer's row
// axis, so we don't flip; left as +1 to match GL convention which
// most reference shaders assume — a future slice can plumb the
// Vulkan y-flip via the viewport state when callers care).
const Sf32 half = ::duetos::core::Sf32FromBits(0x3F000000u); // 0.5
const Sf32 vx = ::duetos::core::Sf32Mul(::duetos::core::Sf32Add(ndc_x, ::duetos::core::Sf32One()),
::duetos::core::Sf32Mul(::duetos::core::Sf32FromU32(fb_w), half));
const Sf32 vy = ::duetos::core::Sf32Mul(::duetos::core::Sf32Sub(::duetos::core::Sf32One(), ndc_y),
::duetos::core::Sf32Mul(::duetos::core::Sf32FromU32(fb_h), half));
*px_out = ::duetos::core::Sf32ToI32(vx);
*py_out = ::duetos::core::Sf32ToI32(vy);
return true;
}
// Paint one triangle by walking its bounding box and invoking
// the fragment shader at every interior pixel. Reuses the
// integer edge-function test from `graphics_vk_raster.cpp` —
// inlined here so the shader path doesn't depend on the v0
// raster's internal helpers (which take a different signature).
//
// `varyings_per_vertex` is an array of length `3 * varying_n`:
// vertex 0's varyings at [0..varying_n), vertex 1's at
// [varying_n..2*varying_n), vertex 2's at [2*varying_n..3*varying_n).
// Each entry's `data[]` holds the Sf32 components for that VS
// Output at that vertex. The per-pixel loop interpolates them
// linearly via barycentric weights and hands the result to the
// fragment shader as Input Location N.
void PaintTriangle(i32 ax, i32 ay, i32 bx, i32 by, i32 cx, i32 cy, spirv::Program* fs, u32 fb_w, u32 fb_h,
const VaryingSnapshot* varyings_per_vertex, u32 varying_n, const u32* inv_w_per_vertex_bits,
const u32* z_per_vertex_bits)
{
// Bounding box clipped to framebuffer extent.
i32 minx = ax;
if (bx < minx)
minx = bx;
if (cx < minx)
minx = cx;
i32 maxx = ax;
if (bx > maxx)
maxx = bx;
if (cx > maxx)
maxx = cx;
i32 miny = ay;
if (by < miny)
miny = by;
if (cy < miny)
miny = cy;
i32 maxy = ay;
if (by > maxy)
maxy = by;
if (cy > maxy)
maxy = cy;
if (minx < 0)
minx = 0;
if (miny < 0)
miny = 0;
if (maxx >= static_cast<i32>(fb_w))
maxx = static_cast<i32>(fb_w) - 1;
if (maxy >= static_cast<i32>(fb_h))
maxy = static_cast<i32>(fb_h) - 1;
if (maxx < minx || maxy < miny)
return;
auto edge = [](i32 x0, i32 y0, i32 x1, i32 y1, i32 px, i32 py) -> i64
{ return static_cast<i64>(x1 - x0) * (py - y0) - static_cast<i64>(y1 - y0) * (px - x0); };
const i64 area2 = edge(ax, ay, bx, by, cx, cy);
if (area2 == 0)
return;
const bool ccw = area2 > 0;
// Hard cap: with a CPU fragment shader the per-pixel cost is
// ~1000x a memcpy, so a 1080p fullscreen triangle would take
// many seconds. Cap the painted area so a runaway draw doesn't
// brick the boot; the cap is generous enough for hello-world
// shaders (256x256 ≈ 64k pixel invocations) but stops a
// pathological caller painting the desktop.
constexpr u64 kMaxPaintedPixels = 65536;
u64 painted = 0;
u32 pixel_xy[2];
u32 argb = 0;
// Precompute the inverse of |area2| as Sf32 so the per-pixel
// barycentric-weight normalisation is a single multiply
// instead of a per-pixel Sf32Div (which is the slowest soft-
// float op). For a degenerate area we'd have returned above.
const u64 abs_area = (area2 < 0) ? static_cast<u64>(-area2) : static_cast<u64>(area2);
const Sf32 inv_area =
::duetos::core::Sf32Div(::duetos::core::Sf32One(), ::duetos::core::Sf32FromU32(static_cast<u32>(abs_area)));
// Per-pixel scratch for the interpolated varyings the FS reads.
VaryingSnapshot interp[kMaxVaryings]{};
for (u32 i = 0; i < varying_n; ++i)
{
interp[i].location = varyings_per_vertex[i].location;
interp[i].component_count = varyings_per_vertex[i].component_count;
}
// Perspective-correct interpolation precompute. When
// `inv_w_per_vertex_bits` is non-null, the rasterizer
// divides each varying by its vertex's w at vertex-fetch time
// (here, just once before the per-pixel loop), interpolates
// those `v/w` values linearly, interpolates `1/w` linearly,
// then per-pixel multiplies `v/w` by the interpolated w to
// recover the correct attribute. Without inv_w, the path
// falls back to affine (linear-in-screen-space) interpolation.
const bool persp = (inv_w_per_vertex_bits != nullptr);
// Depth-test precompute. When `z_per_vertex_bits` is non-null
// and the shared software depth surface allocates cleanly,
// each fragment computes its barycentric-interpolated Z (in
// NDC space, [-1, 1]) and tests it against the surface
// before invoking the FS. v3 uses LessOrEqual + writes; a
// future slice can plumb the per-pipeline compare op.
DepthSurface* dsurf = (z_per_vertex_bits != nullptr) ? DepthSurfaceGetOrAlloc() : nullptr;
const bool depth_test = (dsurf != nullptr);
Sf32 z0{0}, z1{0}, z2{0};
if (depth_test)
{
z0 = Sf32FromBits(z_per_vertex_bits[0]);
z1 = Sf32FromBits(z_per_vertex_bits[1]);
z2 = Sf32FromBits(z_per_vertex_bits[2]);
}
Sf32 inv_w0{0}, inv_w1{0}, inv_w2{0};
VaryingSnapshot vdivw[3 * kMaxVaryings]{};
if (persp)
{
inv_w0 = Sf32FromBits(inv_w_per_vertex_bits[0]);
inv_w1 = Sf32FromBits(inv_w_per_vertex_bits[1]);
inv_w2 = Sf32FromBits(inv_w_per_vertex_bits[2]);
const Sf32 invw_per_vert[3] = {inv_w0, inv_w1, inv_w2};
for (u32 v = 0; v < 3; ++v)
{
for (u32 vi = 0; vi < varying_n; ++vi)
{
vdivw[v * varying_n + vi].location = varyings_per_vertex[v * varying_n + vi].location;
vdivw[v * varying_n + vi].component_count = varyings_per_vertex[v * varying_n + vi].component_count;
for (u32 cc = 0;
cc < varyings_per_vertex[v * varying_n + vi].component_count && cc < kMaxVaryingComponents; ++cc)
{
vdivw[v * varying_n + vi].data[cc] = Sf32ToBits(::duetos::core::Sf32Mul(
Sf32FromBits(varyings_per_vertex[v * varying_n + vi].data[cc]), invw_per_vert[v]));
}
}
}
}
for (i32 py = miny; py <= maxy; ++py)
{
for (i32 px = minx; px <= maxx; ++px)
{
const i64 w0 = edge(bx, by, cx, cy, px, py);
const i64 w1 = edge(cx, cy, ax, ay, px, py);
const i64 w2 = edge(ax, ay, bx, by, px, py);
const bool inside_ccw = (w0 >= 0 && w1 >= 0 && w2 >= 0);
const bool inside_cw = (w0 <= 0 && w1 <= 0 && w2 <= 0);
if (ccw ? !inside_ccw : !inside_cw)
continue;
pixel_xy[0] = static_cast<u32>(px);
pixel_xy[1] = static_cast<u32>(py);
// Depth test (when enabled): compute the interpolated
// Z, map from NDC [-1, 1] to depth surface [0, 0xFFFF],
// compare against the stored value, write on pass.
if (depth_test)
{
const u64 aw0 = (w0 < 0) ? static_cast<u64>(-w0) : static_cast<u64>(w0);
const u64 aw1 = (w1 < 0) ? static_cast<u64>(-w1) : static_cast<u64>(w1);
const u64 aw2 = (w2 < 0) ? static_cast<u64>(-w2) : static_cast<u64>(w2);
// Use a scaled-int barycentric without the Sf32 cost:
// sum(|w|) == |area2|.
if (abs_area == 0)
continue;
// Z in NDC: linearly interpolate without perspective
// (Vulkan/GL depth is interpolated linearly in screen
// space — perspective-correct Z lands when the
// pipeline carries a real depth-range descriptor).
const Sf32 inv_a = inv_area;
const Sf32 bw0z = ::duetos::core::Sf32Mul(::duetos::core::Sf32FromU32(static_cast<u32>(aw0)), inv_a);
const Sf32 bw1z = ::duetos::core::Sf32Mul(::duetos::core::Sf32FromU32(static_cast<u32>(aw1)), inv_a);
const Sf32 bw2z = ::duetos::core::Sf32Mul(::duetos::core::Sf32FromU32(static_cast<u32>(aw2)), inv_a);
const Sf32 z_pix = BaryLerp(z0, z1, z2, bw0z, bw1z, bw2z);
// Map NDC [-1, 1] -> [0, 0xFFFF]. clamp first.
Sf32 z_clamped =
::duetos::core::Sf32Clamp(z_pix, ::duetos::core::Sf32NegOne(), ::duetos::core::Sf32One());
const Sf32 half = ::duetos::core::Sf32FromBits(0x3F000000u); // 0.5
const Sf32 mapped =
::duetos::core::Sf32Mul(::duetos::core::Sf32Add(z_clamped, ::duetos::core::Sf32One()),
::duetos::core::Sf32Mul(::duetos::core::Sf32FromU32(0xFFFFu), half));
const i32 z_int = ::duetos::core::Sf32ToI32(mapped);
u16 z_new = (z_int < 0) ? 0u : (z_int > 0xFFFF ? 0xFFFFu : static_cast<u16>(z_int));
const u64 zi = static_cast<u64>(py) * dsurf->w + px;
if (zi >= static_cast<u64>(dsurf->w) * dsurf->h)
continue;
if (z_new > dsurf->data[zi])
continue; // LessOrEqual fails
dsurf->data[zi] = z_new;
}
// Normalise barycentric weights. The unsigned edge
// magnitudes opposite each vertex sum to |area2|; dividing
// gives weights in [0, 1] that interpolate v0->v1->v2.
// For a CW triangle the sign flips but the magnitudes are
// still correct; |w_i| / |area2| is the right weight either
// way.
const u64 aw0 = (w0 < 0) ? static_cast<u64>(-w0) : static_cast<u64>(w0);
const u64 aw1 = (w1 < 0) ? static_cast<u64>(-w1) : static_cast<u64>(w1);
const u64 aw2 = (w2 < 0) ? static_cast<u64>(-w2) : static_cast<u64>(w2);
const Sf32 bw0 = ::duetos::core::Sf32Mul(::duetos::core::Sf32FromU32(static_cast<u32>(aw0)), inv_area);
const Sf32 bw1 = ::duetos::core::Sf32Mul(::duetos::core::Sf32FromU32(static_cast<u32>(aw1)), inv_area);
const Sf32 bw2 = ::duetos::core::Sf32Mul(::duetos::core::Sf32FromU32(static_cast<u32>(aw2)), inv_area);
// Perspective-correct path: interpolate v/w by bary
// weights, also interpolate 1/w, then per-pixel divide
// to recover v. Mathematically equivalent to the
// textbook formula, packaged for a single Sf32Div per
// pixel (which is the slow op).
if (persp)
{
const Sf32 invw_pix = BaryLerp(inv_w0, inv_w1, inv_w2, bw0, bw1, bw2);
// Avoid divide-by-zero pixel: skip the per-pixel
// perspective restore when interpolated 1/w
// collapses to zero (occurs only on degenerate
// homogeneous projections that wouldn't be visible
// anyway).
const Sf32 w_pix = ::duetos::core::Sf32IsZero(invw_pix)
? ::duetos::core::Sf32One()
: ::duetos::core::Sf32Div(::duetos::core::Sf32One(), invw_pix);
for (u32 vi = 0; vi < varying_n; ++vi)
{
const VaryingSnapshot& a_ss = vdivw[0 * varying_n + vi];
const VaryingSnapshot& b_ss = vdivw[1 * varying_n + vi];
const VaryingSnapshot& c_ss = vdivw[2 * varying_n + vi];
for (u32 cc = 0; cc < interp[vi].component_count && cc < kMaxVaryingComponents; ++cc)
{
const Sf32 lerped_over_w = BaryLerp(Sf32FromBits(a_ss.data[cc]), Sf32FromBits(b_ss.data[cc]),
Sf32FromBits(c_ss.data[cc]), bw0, bw1, bw2);
interp[vi].data[cc] = Sf32ToBits(::duetos::core::Sf32Mul(lerped_over_w, w_pix));
}
}
}
else
{
for (u32 vi = 0; vi < varying_n; ++vi)
{
const VaryingSnapshot& a_ss = varyings_per_vertex[0 * varying_n + vi];
const VaryingSnapshot& b_ss = varyings_per_vertex[1 * varying_n + vi];
const VaryingSnapshot& c_ss = varyings_per_vertex[2 * varying_n + vi];
for (u32 cc = 0; cc < interp[vi].component_count && cc < kMaxVaryingComponents; ++cc)
{
const Sf32 lerped = BaryLerp(Sf32FromBits(a_ss.data[cc]), Sf32FromBits(b_ss.data[cc]),
Sf32FromBits(c_ss.data[cc]), bw0, bw1, bw2);
interp[vi].data[cc] = Sf32ToBits(lerped);
}
}
}
if (!RunFragmentShader(fs, pixel_xy, interp, varying_n, &argb))
continue;
// OpKill in the FS leaves ExecuteEntryPointWasKilled()
// set — skip the pixel paint entirely. `painted`
// tracks only the pixels that actually reached the
// framebuffer.
if (spirv::ExecuteEntryPointWasKilled())
continue;
drivers::video::FramebufferPutPixel(static_cast<u32>(px), static_cast<u32>(py), argb);
++painted;
if (painted >= kMaxPaintedPixels)
{
drivers::video::FramebufferAddDamage(static_cast<u32>(minx), static_cast<u32>(miny),
static_cast<u32>(maxx - minx + 1),
static_cast<u32>(maxy - miny + 1));
return;
}
}
}
drivers::video::FramebufferAddDamage(static_cast<u32>(minx), static_cast<u32>(miny),
static_cast<u32>(maxx - minx + 1), static_cast<u32>(maxy - miny + 1));
}
// Same as the v0 rasterizer's helper — pick the scanout-backed
// image's extent if the bound RT is scanout, otherwise fall back
// to the framebuffer Query().
bool ResolveExtent(const RasterState& st, u32* w, u32* h)
{
if (st.fb_w > 0 && st.fb_h > 0)
{
*w = st.fb_w;
*h = st.fb_h;
return true;
}
return false;
}
bool ResolveVertexBuffer(const RasterState& st, const u8** base, u64* size)
{
if (st.vertex_buffer == 0 || !HandleInRange(st.vertex_buffer, kBufferBase))
return false;
const u32 slot = SlotOf(st.vertex_buffer, kBufferBase);
if (!PoolIsLive(g_buffer_pool, slot))
return false;
const BufferRecord& vb = g_buffer_data[slot];
if (vb.backing == nullptr)
return false;
if (st.vertex_offset >= vb.size)
return false;
const auto* p = static_cast<const u8*>(vb.backing) + vb.backing_offset + st.vertex_offset;
*base = p;
*size = vb.size - st.vertex_offset;
return true;
}
} // namespace
// --------------------------------------------------------------
// Public surface used by the executor + the cmd-buffer replay.
// --------------------------------------------------------------
bool QueryImageSize(u64 resource_handle, u32* out_w, u32* out_h, u32* out_d)
{
if (resource_handle == 0)
return false;
VkImage img = 0;
if (HandleInRange(resource_handle, kImageViewBase))
{
const u32 slot = SlotOf(resource_handle, kImageViewBase);
if (!PoolIsLive(g_imageview_pool, slot))
return false;
img = g_imageview_data[slot].image;
}
else if (HandleInRange(resource_handle, kImageBase))
{
img = resource_handle;
}
else
{
return false;
}
if (!HandleInRange(img, kImageBase))
return false;
const u32 islot = SlotOf(img, kImageBase);
if (!PoolIsLive(g_image_pool, islot))
return false;
const ImageRecord& rec = g_image_data[islot];
if (out_w)
*out_w = rec.extent.width;
if (out_h)
*out_h = rec.extent.height;
if (out_d)
*out_d = rec.extent.depth;
return true;
}
// Resolve a descriptor handle (VkImage or VkImageView) to the
// underlying ImageRecord, returning nullptr on any lookup failure.
// Both SampleImageRgba8 (filtered sampling) and FetchTexelBgra8 /
// WriteTexelBgra8 (unfiltered storage-image access) share this.
namespace
{
const ImageRecord* ResolveImageRecord(u64 resource_handle)
{
if (resource_handle == 0)
return nullptr;
VkImage img = 0;
if (HandleInRange(resource_handle, kImageViewBase))
{
const u32 slot = SlotOf(resource_handle, kImageViewBase);
if (!PoolIsLive(g_imageview_pool, slot))
return nullptr;
img = g_imageview_data[slot].image;
}
else if (HandleInRange(resource_handle, kImageBase))
{
img = resource_handle;
}
else
{
return nullptr;
}
if (!HandleInRange(img, kImageBase))
return nullptr;
const u32 islot = SlotOf(img, kImageBase);
if (!PoolIsLive(g_image_pool, islot))
return nullptr;
return &g_image_data[islot];
}
ImageRecord* ResolveImageRecordMut(u64 resource_handle)
{
// const_cast is fine: ResolveImageRecord only inspects pool
// bookkeeping. The caller takes responsibility for not racing
// against another mutator under the storage-image write lock.
return const_cast<ImageRecord*>(ResolveImageRecord(resource_handle));
}
} // namespace
u32 BytesPerTexelForFormat(u32 format)
{
switch (format)
{
case 0:
case 1:
return 4u; // BGRA8 / RGBA8
case 2:
return 1u; // R8
case 3:
return 2u; // R8G8
case 4:
return 2u; // R16
case 5:
return 16u; // R32G32B32A32_SFLOAT
default:
return 4u; // unknown — caller's bounds check still applies
}
}
namespace
{
// Sf32 helpers shared with the format unpack/pack table.
::duetos::core::Sf32 U8ToSf32Unorm(u8 v)
{
// v / 255.0
return ::duetos::core::Sf32Div(::duetos::core::Sf32FromU32(v), ::duetos::core::Sf32FromU32(255u));
}
::duetos::core::Sf32 U16ToSf32Unorm(u16 v)
{
// v / 65535.0
return ::duetos::core::Sf32Div(::duetos::core::Sf32FromU32(v), ::duetos::core::Sf32FromU32(65535u));
}
u8 Sf32ToU8Unorm(u32 sf_bits)
{
using ::duetos::core::Sf32;
using ::duetos::core::Sf32Clamp;
using ::duetos::core::Sf32FromU32;
using ::duetos::core::Sf32IsNaN;
using ::duetos::core::Sf32Mul;
using ::duetos::core::Sf32One;
using ::duetos::core::Sf32ToI32;
using ::duetos::core::Sf32Zero;
Sf32 s{sf_bits};
if (Sf32IsNaN(s))
return 0;
const i32 v = Sf32ToI32(Sf32Mul(Sf32Clamp(s, Sf32Zero(), Sf32One()), Sf32FromU32(255u)));
if (v < 0)
return 0;
if (v > 255)
return 255;
return static_cast<u8>(v);
}
u16 Sf32ToU16Unorm(u32 sf_bits)
{
using ::duetos::core::Sf32;
using ::duetos::core::Sf32Clamp;
using ::duetos::core::Sf32FromU32;
using ::duetos::core::Sf32IsNaN;
using ::duetos::core::Sf32Mul;
using ::duetos::core::Sf32One;
using ::duetos::core::Sf32ToI32;
using ::duetos::core::Sf32Zero;
Sf32 s{sf_bits};
if (Sf32IsNaN(s))
return 0;
const i32 v = Sf32ToI32(Sf32Mul(Sf32Clamp(s, Sf32Zero(), Sf32One()), Sf32FromU32(65535u)));
if (v < 0)
return 0;
if (v > 65535)
return 65535;
return static_cast<u16>(v);
}
u32 LeU32FromBytes(const u8* p)
{
return static_cast<u32>(p[0]) | (static_cast<u32>(p[1]) << 8) | (static_cast<u32>(p[2]) << 16) |
(static_cast<u32>(p[3]) << 24);
}
void PutU32Le(u8* p, u32 v)
{
p[0] = static_cast<u8>(v & 0xFFu);
p[1] = static_cast<u8>((v >> 8) & 0xFFu);
p[2] = static_cast<u8>((v >> 16) & 0xFFu);
p[3] = static_cast<u8>((v >> 24) & 0xFFu);
}
} // namespace
void FetchTexel(u64 resource_handle, u32 x, u32 y, u32 out[4])
{
using ::duetos::core::Sf32One;
using ::duetos::core::Sf32ToBits;
using ::duetos::core::Sf32Zero;
// Default to (0, 0, 0, 1) per spec for sampler-less OOB reads.
out[0] = Sf32ToBits(Sf32Zero());
out[1] = Sf32ToBits(Sf32Zero());
out[2] = Sf32ToBits(Sf32Zero());
out[3] = Sf32ToBits(Sf32One());
const ImageRecord* rec = ResolveImageRecord(resource_handle);
if (rec == nullptr || rec->backing == nullptr || rec->extent.width == 0 || rec->extent.height == 0)
return;
if (x >= rec->extent.width || y >= rec->extent.height)
return;
const u32 bpt = BytesPerTexelForFormat(rec->format);
const u64 off = (static_cast<u64>(y) * rec->extent.width + x) * bpt;
const u8* p = static_cast<const u8*>(rec->backing) + off;
switch (rec->format)
{
case 0:
case 1:
// Backing byte order is [R, G, B, A] regardless of the
// Vulkan enum name (the on-disk layout matches what
// SampleImageRgba8 expects).
out[0] = Sf32ToBits(U8ToSf32Unorm(p[0]));
out[1] = Sf32ToBits(U8ToSf32Unorm(p[1]));
out[2] = Sf32ToBits(U8ToSf32Unorm(p[2]));
out[3] = Sf32ToBits(U8ToSf32Unorm(p[3]));
break;
case 2:
out[0] = Sf32ToBits(U8ToSf32Unorm(p[0]));
break;
case 3:
out[0] = Sf32ToBits(U8ToSf32Unorm(p[0]));
out[1] = Sf32ToBits(U8ToSf32Unorm(p[1]));
break;
case 4:
{
const u16 r = static_cast<u16>(p[0]) | (static_cast<u16>(p[1]) << 8);
out[0] = Sf32ToBits(U16ToSf32Unorm(r));
break;
}
case 5:
// Raw f32 round-trip — backing carries the Sf32 bit
// pattern in little-endian order; the executor's Sf32
// helpers operate on the same u32 bit pattern.
out[0] = LeU32FromBytes(p + 0);
out[1] = LeU32FromBytes(p + 4);
out[2] = LeU32FromBytes(p + 8);
out[3] = LeU32FromBytes(p + 12);
break;
default:
break;
}
}
void WriteTexel(u64 resource_handle, u32 x, u32 y, const u32 in[4])
{
ImageRecord* rec = ResolveImageRecordMut(resource_handle);
if (rec == nullptr || rec->backing == nullptr || rec->extent.width == 0 || rec->extent.height == 0)
return;
if (x >= rec->extent.width || y >= rec->extent.height)
return;
const u32 bpt = BytesPerTexelForFormat(rec->format);
const u64 off = (static_cast<u64>(y) * rec->extent.width + x) * bpt;
u8* p = static_cast<u8*>(rec->backing) + off;
switch (rec->format)
{
case 0:
case 1:
p[0] = Sf32ToU8Unorm(in[0]);
p[1] = Sf32ToU8Unorm(in[1]);
p[2] = Sf32ToU8Unorm(in[2]);
p[3] = Sf32ToU8Unorm(in[3]);
break;
case 2:
p[0] = Sf32ToU8Unorm(in[0]);
break;
case 3:
p[0] = Sf32ToU8Unorm(in[0]);
p[1] = Sf32ToU8Unorm(in[1]);
break;
case 4:
{
const u16 r = Sf32ToU16Unorm(in[0]);
p[0] = static_cast<u8>(r & 0xFFu);
p[1] = static_cast<u8>((r >> 8) & 0xFFu);
break;
}
case 5:
PutU32Le(p + 0, in[0]);
PutU32Le(p + 4, in[1]);
PutU32Le(p + 8, in[2]);
PutU32Le(p + 12, in[3]);
break;
default:
break;
}
}
u32 FetchTexelBgra8(u64 resource_handle, u32 x, u32 y)
{
const ImageRecord* rec = ResolveImageRecord(resource_handle);
if (rec == nullptr || rec->backing == nullptr || rec->extent.width == 0 || rec->extent.height == 0)
return 0x00000000u;
if (x >= rec->extent.width || y >= rec->extent.height)
return 0x00000000u;
const u64 off = (static_cast<u64>(y) * rec->extent.width + x) * 4u;
const u8* p = static_cast<const u8*>(rec->backing) + off;
// Match `SampleImageRgba8`'s convention: backing byte order is
// [R, G, B, A]; returned packed word is 0xAARRGGBB. The
// function is named "Bgra8" because the Vulkan format enum it
// serves is `VK_FORMAT_B8G8R8A8_UNORM`; the on-disk byte order
// is DuetOS's internal-RGBA8 layout regardless.
return (static_cast<u32>(p[3]) << 24) | (static_cast<u32>(p[0]) << 16) | (static_cast<u32>(p[1]) << 8) |
static_cast<u32>(p[2]);
}
void WriteTexelBgra8(u64 resource_handle, u32 x, u32 y, u32 argb)
{
ImageRecord* rec = ResolveImageRecordMut(resource_handle);
if (rec == nullptr || rec->backing == nullptr || rec->extent.width == 0 || rec->extent.height == 0)
return;
if (x >= rec->extent.width || y >= rec->extent.height)
return;
const u64 off = (static_cast<u64>(y) * rec->extent.width + x) * 4u;
u8* p = static_cast<u8*>(rec->backing) + off;
// Inverse of FetchTexelBgra8: argb=0xAARRGGBB packs into
// backing bytes [R, G, B, A].
p[0] = static_cast<u8>((argb >> 16) & 0xFFu); // R
p[1] = static_cast<u8>((argb >> 8) & 0xFFu); // G
p[2] = static_cast<u8>(argb & 0xFFu); // B
p[3] = static_cast<u8>((argb >> 24) & 0xFFu); // A
}
u32 SampleImageRgba8(u64 resource_handle, u32 u_bits, u32 v_bits, SamplerAddressMode mode_u, SamplerAddressMode mode_v,
u8 filter)
{
if (resource_handle == 0)
return 0xFF000000u;
// The handle could be either a VkImage or a VkImageView.
// ImageView -> Image first; Image is what carries the backing.
VkImage img = 0;
if (HandleInRange(resource_handle, kImageViewBase))
{
const u32 slot = SlotOf(resource_handle, kImageViewBase);
if (!PoolIsLive(g_imageview_pool, slot))
return 0xFF000000u;
img = g_imageview_data[slot].image;
}
else if (HandleInRange(resource_handle, kImageBase))
{
img = resource_handle;
}
else
{
return 0xFF000000u;
}
if (!HandleInRange(img, kImageBase))
return 0xFF000000u;
const u32 islot = SlotOf(img, kImageBase);
if (!PoolIsLive(g_image_pool, islot))
return 0xFF000000u;
const ImageRecord& rec = g_image_data[islot];
if (rec.backing == nullptr || rec.extent.width == 0 || rec.extent.height == 0)
return 0xFF000000u;
using ::duetos::core::Sf32;
using ::duetos::core::Sf32Clamp;
using ::duetos::core::Sf32FromU32;
using ::duetos::core::Sf32Mul;
using ::duetos::core::Sf32One;
using ::duetos::core::Sf32Sub;
using ::duetos::core::Sf32ToI32;
using ::duetos::core::Sf32Zero;
// ClampToBorder is checked per-axis: only the axes whose
// mode is ClampToBorder return the border colour when their
// UV component falls outside [0, 1]. A mixed sampler such as
// (REPEAT_U, BORDER_V) correctly produces tiled-X /
// border-stamped-Y output instead of border-everywhere. v0's
// border colour is always transparent black (0x00000000); the
// spec's per-sampler borderColor variants (opaque black,
// opaque white, ints, custom) land when VkSamplerCreateInfo
// grows the field.
{
const Sf32 zero = Sf32Zero();
const Sf32 one = Sf32One();
const Sf32 uval{u_bits};
const Sf32 vval{v_bits};
const bool u_out = ::duetos::core::Sf32LessThan(uval, zero) || ::duetos::core::Sf32GreaterThan(uval, one);
const bool v_out = ::duetos::core::Sf32LessThan(vval, zero) || ::duetos::core::Sf32GreaterThan(vval, one);
if ((mode_u == SamplerAddressMode::ClampToBorder && u_out) ||
(mode_v == SamplerAddressMode::ClampToBorder && v_out))
return 0x00000000u;
}
// Apply each axis's addressing mode independently to fold raw
// UV into [0, 1]. The two folds operate on different scalars
// and don't share state — the lambda just routes through the
// per-axis mode.
auto fold = [](u32 bits, SamplerAddressMode mode) -> Sf32
{
Sf32 v{bits};
switch (mode)
{
case SamplerAddressMode::Repeat:
// fract(uv) wraps mod 1.0.
return ::duetos::core::Sf32Fract(v);
case SamplerAddressMode::MirroredRepeat:
{
// |fract(uv * 0.5) - 0.5| * 2 — produces a 0..1..0 sawtooth.
const Sf32 half = Sf32{0x3F000000u};
const Sf32 two = ::duetos::core::Sf32FromU32(2u);
const Sf32 f = ::duetos::core::Sf32Fract(::duetos::core::Sf32Mul(v, half));
return ::duetos::core::Sf32Mul(::duetos::core::Sf32Abs(::duetos::core::Sf32Sub(f, half)), two);
}