Clarifying current gfx status and some graphic driver issues

未关闭
#440 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
22/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
活跃
技术栈
cpp

调研方向

The reported bug is in the face-culling winding logic of EdgeEquation and setup_triangle in sw/common/gfx_setup.h, with the call path through setup_k in sw/gfx/gfx_frontend_k.h. Start by reading how det's sign maps to front and back faces, and check it against the Vulkan front-face state the driver passes in. Done means vkcube's culling matches the requested VkFrontFace on the reporter's FPGA setup. The reporter's patch is a workaround, not a reviewed fix, so validate the change against the maintainers' expectations.

由索引模型根据 Issue 内容生成。

描述

Hello, absolute gorgeous work there, kudos, I decided to try actually running the gpu on an fpga board I have and had a ton of fun experience doing so, though not just plug and play experience ofc.

I am using surplus pci-e card variant of Microsoft catapult v3 board (https://github.com/tow3rs/catapult-v3-smartnic-re for details), so I had to tinker in a top level module of my own, but it seems to sort of work. First problem was me thinking that the default config fits and just enabled raster, tex and om, but quickly ran into fact that driver expects MMU, so after adding it I was able to run vkcube, which did not go well:

First frames Image

Quite a lot was going there, and first issue was again, me: default config has no rv A extension, shader compiler assumes rv32imaf, giving ignored last coord addition per line (sporadic line shifts).

After `A` rtl cfg fix Image

Then some seemingly real issues had to be fixed to get almost reference similar render:

Good render Image

AI disclosure / Warning: Lot of assistance during bringup, implementation of catapult v3 specific top and vibe coded fixes ahead. Issue's text is human written with some copy-paste from ai notes and patches

Patches provided are not PR-ready, just examples of my workarounds for context and likely locations of issues
Used commit was 90a6262

So one by one (examples with single fix reverted per issue)

1. Face culling is inverted for Vulkan

EdgeEquation in the shared setup frontend treated det < 0 as back-facing. In a y-down framebuffer det is the positive screen-space shoelace, and Vulkan's front-face area is -det/2, so under VK_FRONT_FACE_COUNTER_CLOCKWISE the convention is det < 0 = front. CULL_BACK and CULL_FRONT were exactly swapped, and so was the facing bit.

Thus resulting in inverted culling

Patch
diff --git a/sw/common/gfx_setup.h b/sw/common/gfx_setup.h
index 7b9d619d0..dca7e6cef 100644
--- a/sw/common/gfx_setup.h
+++ b/sw/common/gfx_setup.h
@@ -114,17 +114,26 @@ static inline vec4f ClipToScreen(const vec4f& in, float left, float right,
 
 // Edge functions (a,b,c) per edge in HDC; winding flipped so interior is
 // positive. Returns false for the degenerate (det==0) triangle, and — under a
-// face-cull mode (SETUP_CULL_*) — for the culled winding (BACK = negative
-// area, FRONT = positive). cull_mode defaults to two-sided (no cull).
+// face-cull mode (SETUP_CULL_*) — for the culled winding.
 //
-// out_back receives the winding the flip is about to erase (true = back-facing),
-// which is the only place gl_FrontFacing can come from: after the flip both
-// windings look identical to every downstream consumer. Optional — pass nullptr
-// when the caller only wants coverage.
+// det is the standard screen-space shoelace, but the screen is the Vulkan
+// framebuffer and its y axis points down: a positive det is a clockwise
+// winding as seen by the application. Vulkan's front-face area is
+// a = -1/2 * det, so VK_FRONT_FACE_COUNTER_CLOCKWISE makes det < 0 the front
+// face (and det > 0 the back); a clockwise front face swaps the two. front_cw
+// carries that VkFrontFace state, so SETUP_CULL_BACK/FRONT mean Vulkan's cull
+// back/front under the draw's own front-face convention.
+//
+// out_back receives true for a back-facing triangle under that convention,
+// recorded before the edges are flipped. This is the only place gl_FrontFacing
+// can come from: after the flip both windings look identical to every
+// downstream consumer. Optional — pass nullptr when the caller only wants
+// coverage.
 static inline bool EdgeEquation(vec3f edges[3], const vec4f& v0,
                                 const vec4f& v1, const vec4f& v2,
                                 uint32_t cull_mode = SETUP_CULL_NONE,
-                                bool* out_back = nullptr) {
+                                bool* out_back = nullptr,
+                                bool front_cw = false) {
   float a0 = (v1.y * v2.w) - (v2.y * v1.w);
   float a1 = (v2.y * v0.w) - (v0.y * v2.w);
   float a2 = (v0.y * v1.w) - (v1.y * v0.w);
@@ -140,14 +149,19 @@ static inline bool EdgeEquation(vec3f edges[3], const vec4f& v0,
   float det = c0 * v0.w + c1 * v1.w + c2 * v2.w;
   if (det == 0.0f)
     return false;                          // degenerate (zero area)
-  const bool back = (det < 0.0f);          // winding that needs a flip
+  // y-down framebuffer: det>0 is clockwise, hence the back face of a
+  // counter-clockwise front face and the front face of a clockwise one.
+  const bool back = front_cw ? (det < 0.0f) : (det > 0.0f);
   if ((cull_mode == SETUP_CULL_BACK  &&  back) ||
       (cull_mode == SETUP_CULL_FRONT && !back))
     return false;                          // face-culled
   if (out_back != nullptr) {
     *out_back = back;
   }
-  if (back) {
+  // Keep the interior positive for the rasterizer. The coefficients above are
+  // positive for det>0 and negative for det<0, so this flip is det<0 -- not
+  // the face-cull back sign, which moves with front_cw.
+  if (det < 0.0f) {
     for (int i = 0; i < 3; ++i) {
       edges[i].x *= -1.0f; edges[i].y *= -1.0f; edges[i].z *= -1.0f;
     }
@@ -194,13 +208,16 @@ static inline void EdgeToFixed(vec3e_t out[3], const vec3f in[3]) {
 // is culled (degenerate or empty bbox) — matching Binning()'s two `continue`s.
 // vp carries the app viewport transform; nullptr => the default full-framebuffer
 // y-down viewport (screen = ndc mapped onto [0,width] x [0,height], y-down).
+// front_cw is the draw's VkFrontFace convention (false = counter-clockwise) and
+// drives both the face cull and the recorded facing bit.
 static inline bool setup_triangle(const setup_vertex_t& v0,
                                   const setup_vertex_t& v1,
                                   const setup_vertex_t& v2,
                                   int width, int height, float near, float far,
                                   rast_prim_t& out_prim, setup_bbox_t& out_bbox,
                                   uint32_t cull_mode = SETUP_CULL_NONE,
-                                  const setup_viewport_t* vp = nullptr) {
+                                  const setup_viewport_t* vp = nullptr,
+                                  bool front_cw = false) {
   vec4f p0 = { v0.pos[0], v0.pos[1], v0.pos[2], v0.pos[3] };
   vec4f p1 = { v1.pos[0], v1.pos[1], v1.pos[2], v1.pos[3] };
   vec4f p2 = { v2.pos[0], v2.pos[1], v2.pos[2], v2.pos[3] };
@@ -232,7 +249,7 @@ static inline bool setup_triangle(const setup_vertex_t& v0,
     vec4f ph0 = ClipToHDC(p0, L, R, T, B, zn, zf, halfz);
     vec4f ph1 = ClipToHDC(p1, L, R, T, B, zn, zf, halfz);
     vec4f ph2 = ClipToHDC(p2, L, R, T, B, zn, zf, halfz);
-    if (!EdgeEquation(edges, ph0, ph1, ph2, cull_mode, &back))
+    if (!EdgeEquation(edges, ph0, ph1, ph2, cull_mode, &back, front_cw))
       return false;  // degenerate or face-culled
   }
   out_prim.facing = back ? 1u : 0u;
@@ -259,6 +276,32 @@ static inline bool setup_triangle(const setup_vertex_t& v0,
       return false;  // empty
   }
 
+  // Affine, screen-space edge equations. The homogeneous HDC coefficients keep w
+  // inside them, so each edge carries its own w_i*w_j factor; the raster and the
+  // fragment shader both evaluate the stored coefficients at plain pixel
+  // coordinates, and a per-edge scale factor makes F_i/sum(F) non-affine - it
+  // drifts as soon as the three w differ, which is what perspective-correct
+  // interpolation must not do. Screen-space coefficients are the affine set the
+  // two consumers assume. The winding (and hence the flip) is unchanged by the
+  // perspective divide because every w is positive.
+  {
+    const vec4f ps[3] = {ps0, ps1, ps2};
+    for (int k = 0; k < 3; ++k) {
+      const vec4f& ea = ps[(k + 1) % 3];
+      const vec4f& eb = ps[(k + 2) % 3];
+      edges[k].x = ea.y - eb.y;
+      edges[k].y = eb.x - ea.x;
+      edges[k].z = ea.x * eb.y - eb.x * ea.y;
+    }
+    float det2 = edges[0].x * ps0.x + edges[0].y * ps0.y + edges[0].z;
+    if (det2 < 0.0f) {
+      for (int k = 0; k < 3; ++k) {
+        edges[k].x = -edges[k].x;
+        edges[k].y = -edges[k].y;
+        edges[k].z = -edges[k].z;
+      }
+    }
+  }
   // Half-pixel sampling offset, then Q15.16 edges.
   edges[0].z += edges[0].x * 0.5f + edges[0].y * 0.5f;
   edges[1].z += edges[1].x * 0.5f + edges[1].y * 0.5f;
diff --git a/sw/gfx/gfx_frontend_k.h b/sw/gfx/gfx_frontend_k.h
index e2ee763c9..e527d176f 100644
--- a/sw/gfx/gfx_frontend_k.h
+++ b/sw/gfx/gfx_frontend_k.h
@@ -50,7 +50,7 @@ static inline void pipe_bin_range(const setup_bbox_t& p, int& bL, int& bR, int&
 // the entry (the merged 9-stage function otherwise overruns the uniform pass).
 static uint32_t __attribute__((noinline))
 pipe_clip_and_setup(const setup_vertex_t* v, int W, int H, uint32_t cull_mode,
-                    const setup_viewport_t* vp,
+                    bool front_cw, const setup_viewport_t* vp,
                     rast_prim_t* prim_out, setup_bbox_t* bbox_out) {
   clip_tri_t sub[SETUP_MAX_SUB];
   // The near plane the clip uses and the depth range setup maps onto have to
@@ -61,7 +61,7 @@ pipe_clip_and_setup(const setup_vertex_t* v, int W, int H, uint32_t cull_mode,
     rast_prim_t prim{};
     setup_bbox_t bb{};
     if (setup_triangle(sub[s].v[0], sub[s].v[1], sub[s].v[2], W, H,
-                       SETUP_NEAR, SETUP_FAR, prim, bb, cull_mode, vp)) {
+                       SETUP_NEAR, SETUP_FAR, prim, bb, cull_mode, vp, front_cw)) {
       prim_out[kept] = prim;
       bbox_out[kept] = bb;
       ++kept;
@@ -129,6 +129,10 @@ __kernel void setup_k(pipe_arg_t* __UNIFORM__ arg) {
   const uint32_t ntri = arg->num_tris;
   const int      W = (int)arg->width;
   const int      H = (int)arg->height;
+  // VkFrontFace state the driver captured with the rasterizer cso: the
+  // frontend's back/front classification (cull and the facing bit) depends on
+  // it because the framebuffer is y-down (see EdgeEquation).
+  const bool     front_cw = arg->front_cw != 0u;
   const uint32_t tid = threadIdx.x;
   const uint32_t T   = blockDim.x;
 
@@ -159,7 +163,8 @@ __kernel void setup_k(pipe_arg_t* __UNIFORM__ arg) {
     for (size_t t = gid; t < ntri; t += gstride) {
       rast_prim_t pr[SETUP_MAX_SUB];
       setup_bbox_t bb[SETUP_MAX_SUB];
-      keep[t] = pipe_clip_and_setup(&verts[3 * t], W, H, arg->cull_mode, vpp, pr, bb);
+      keep[t] = pipe_clip_and_setup(&verts[3 * t], W, H, arg->cull_mode,
+                                    front_cw, vpp, pr, bb);
     }
   } break;
 
@@ -186,7 +191,8 @@ __kernel void setup_k(pipe_arg_t* __UNIFORM__ arg) {
     for (size_t t = gid; t < ntri; t += gstride) {
       rast_prim_t pr[SETUP_MAX_SUB];
       setup_bbox_t bb[SETUP_MAX_SUB];
-      uint32_t kept = pipe_clip_and_setup(&verts[3 * t], W, H, arg->cull_mode, vpp, pr, bb);
+      uint32_t kept = pipe_clip_and_setup(&verts[3 * t], W, H, arg->cull_mode,
+                                          front_cw, vpp, pr, bb);
       // The provoking vertex is the source triangle's first, sampled HERE rather
       // than inside setup: clipping reorders and synthesises vertices, so after
       // it the original first vertex is no longer identifiable. Same reason
Failure example image Image
2. Winding direction is silently ignored

Gallium has folded VkFrontFace into front_ccw, not into cull_face, so there is no winding swap left to do here: PIPE_FACE_BACK maps straight to SETUP_CULL_BACK.

So CW winding seems to do the same thing as CCW

Patch
diff --git a/src/gallium/drivers/vortexpipe/kernels/gfx_frontend/Makefile b/src/gallium/drivers/vortexpipe/kernels/gfx_frontend/Makefile
index c8ba19d..da6cabe 100644
--- a/src/gallium/drivers/vortexpipe/kernels/gfx_frontend/Makefile
+++ b/src/gallium/drivers/vortexpipe/kernels/gfx_frontend/Makefile
@@ -88,7 +88,9 @@ all: $(OUTDIR)/gfx_frontend$(XLEN).vxbin
 
 # Kernel sources are owned by the Vortex SDK (sw/gfx + sw/common), not copied
 # here — this driver compiles them, the SDK is the single source of truth.
-GFX_HDRS := $(wildcard $(VORTEX_HOME)/sw/gfx/*.h) $(VORTEX_HOME)/sw/common/gfx_frontend_abi.h
+GFX_HDRS := $(wildcard $(VORTEX_HOME)/sw/gfx/*.h) \
+            $(VORTEX_HOME)/sw/common/gfx_frontend_abi.h \
+            $(VORTEX_HOME)/sw/common/gfx_setup.h
 
 $(OUTDIR)/gfx_frontend$(XLEN).elf: gfx_frontend_kernel.cpp $(GFX_HDRS) Makefile
 	$(CLANG) $(VX_CFLAGS) gfx_frontend_kernel.cpp $(VX_LDFLAGS) -o $@
diff --git a/src/gallium/drivers/vortexpipe/vp_context.c b/src/gallium/drivers/vortexpipe/vp_context.c
index 94a32e3..17a9acc 100644
--- a/src/gallium/drivers/vortexpipe/vp_context.c
+++ b/src/gallium/drivers/vortexpipe/vp_context.c
@@ -2871,24 +2871,21 @@ vp_set_scissor_states(struct pipe_context *pipe, unsigned start_slot,
 }
 
 /* Translate the bound Gallium rasterizer state to the device SETUP_CULL_*
- * face-cull mode. The device culls on the signed-area sign in screen
- * space, where a triangle's winding matches the Vulkan framebuffer area
- * sign: vortexpipe runs the VS output (clip-space gl_Position) through the
- * app's captured viewport transform (vp_set_viewport_states -> the device
- * setup's scale/bias), so the front-end det sign equals the Vulkan area sign
- * — including a y-flip, which the negative sy sign-flips correctly. det>0 is
- * the front (positive-area) winding, det<0 the back; front_ccw selects which
- * of the two Vulkan calls "front".
+ * face-cull mode. The front end applies the Vulkan framebuffer-area
+ * convention itself (y down, area = -1/2 * shoelace, see EdgeEquation) and
+ * receives the draw's VkFrontFace through pipe_arg_t::front_cw, so
+ * SETUP_CULL_BACK/FRONT already mean Vulkan's cull back/front under that
+ * convention. Gallium has folded VkFrontFace into front_ccw, not into
+ * cull_face, so there is no winding swap left to do here: PIPE_FACE_BACK
+ * maps straight to SETUP_CULL_BACK.
  * PIPE_FACE_FRONT_AND_BACK (cull everything) is handled by the caller. */
 static uint32_t
 vp_cull_mode(const struct vp_rast_cso *r)
 {
    if (!r || r->cull_face == PIPE_FACE_NONE)
       return SETUP_CULL_NONE;
-   bool cull_back = (r->cull_face == PIPE_FACE_BACK);
-   if (!r->front_ccw)
-      cull_back = !cull_back;   /* CW front face swaps the device winding sense */
-   return cull_back ? SETUP_CULL_BACK : SETUP_CULL_FRONT;
+   return (r->cull_face == PIPE_FACE_BACK) ? SETUP_CULL_BACK
+                                           : SETUP_CULL_FRONT;
 }
 
 /* A passthrough vertex shader: copies N input attributes straight to
@@ -3528,6 +3525,9 @@ vp_draw_vbo(struct pipe_context *pipe,
           * buffer stays at the render-pass clear) rather than emit a device
           * "cull all" mode the front end lacks. */
          uint32_t cull_mode = vp_cull_mode(vp->cur_rast);
+         /* VkFrontFace reaches the front end separately: it selects which
+          * screen-space winding is front for both the cull and gl_FrontFacing. */
+         const bool front_cw = vp->cur_rast && !vp->cur_rast->front_ccw;
          if (vp->cur_rast && vp->cur_rast->cull_face == PIPE_FACE_FRONT_AND_BACK) {
             vp_dbg("vortexpipe: draw_vbo -> cull FRONT_AND_BACK, nothing drawn");
             vp_unmap_vertex_input(pipe, vxfers, vin.num_bufs);
@@ -3796,8 +3796,8 @@ vp_draw_vbo(struct pipe_context *pipe,
                                      color_dev, depth_dev, w, h, &om,
                                      tex_used ? tex_dev : 0,
                                      tex_used ? &tex : NULL,
-                                     cull_mode, fs_sw_tex, fs_sw_om,
-                                     fs_sw_raster,
+                                     cull_mode, front_cw,
+                                     fs_sw_tex, fs_sw_om, fs_sw_raster,
                                      vp_sx, vp_tx, vp_sy, vp_ty,
                                      vp_min_z, vp_max_z,
                                      sc_used ? &sc_rect : NULL,
diff --git a/src/gallium/drivers/vortexpipe/vp_private.h b/src/gallium/drivers/vortexpipe/vp_private.h
index 4a5a907..881cdbe 100644
--- a/src/gallium/drivers/vortexpipe/vp_private.h
+++ b/src/gallium/drivers/vortexpipe/vp_private.h
@@ -325,9 +325,10 @@ struct vp_blend_cso {
 
 /* Captured rasterizer state: the face-cull inputs the device front end
  * needs. cull_face is the Gallium PIPE_FACE_* mask and front_ccw the
- * front-face winding; vp_draw_vbo turns the pair into the device
- * SETUP_CULL_* mode (see vp_cull_mode), and whether the bound scissor rect
- * applies at all — everything else in pipe_rasterizer_state stays with
+ * front-face winding; vp_draw_vbo turns cull_face into the device
+ * SETUP_CULL_* mode (see vp_cull_mode) and front_ccw into the front end's
+ * VkFrontFace input (pipe_arg_t::front_cw), and whether the bound scissor
+ * rect applies at all — everything else in pipe_rasterizer_state stays with
  * llvmpipe. */
 struct vp_rast_cso {
    unsigned cull_face;         /* PIPE_FACE_{NONE,FRONT,BACK,FRONT_AND_BACK} */
diff --git a/src/gallium/drivers/vortexpipe/vp_raster.cpp b/src/gallium/drivers/vortexpipe/vp_raster.cpp
index e8a47a0..2d750c6 100644
--- a/src/gallium/drivers/vortexpipe/vp_raster.cpp
+++ b/src/gallium/drivers/vortexpipe/vp_raster.cpp
@@ -369,7 +369,7 @@ vp_raster_draw(struct pipe_screen *screen, vx_device_h dev,
                uint32_t width, uint32_t height,
                const struct vp_om_params *om,
                uint64_t tex_dev, const struct vp_tex_params *tex,
-               uint32_t cull_mode,
+               uint32_t cull_mode, bool front_cw,
                bool sw_tex, bool sw_om, bool sw_raster,
                float vp_sx, float vp_tx, float vp_sy, float vp_ty,
                float vp_min_z, float vp_max_z,
@@ -557,6 +557,7 @@ vp_raster_draw(struct pipe_screen *screen, vx_device_h dev,
       arg.bin_cols   = bin_cols;
       arg.num_bins   = num_bins;
       arg.cull_mode  = cull_mode;                /* SETUP_CULL_* from the rasterizer state */
+      arg.front_cw   = front_cw ? 1u : 0u;       /* VkFrontFace for cull + gl_FrontFacing */
       arg.vp_sx = vp_sx; arg.vp_tx = vp_tx;      /* app viewport transform (screen = ndc*scale+bias) */
       arg.vp_sy = vp_sy; arg.vp_ty = vp_ty;      /* negative vp_sy = Vulkan y-flip */
       arg.vp_minz = vp_min_z; arg.vp_maxz = vp_max_z;
diff --git a/src/gallium/drivers/vortexpipe/vp_raster.h b/src/gallium/drivers/vortexpipe/vp_raster.h
index 03ef01a..9e10308 100644
--- a/src/gallium/drivers/vortexpipe/vp_raster.h
+++ b/src/gallium/drivers/vortexpipe/vp_raster.h
@@ -178,6 +178,9 @@ void vp_texstate_fill(gfx_sw_texstate_t *ts, uint64_t tex_dev,
  *                 untextured draw.
  *   cull_mode     device SETUP_CULL_* face-cull mode (0 = none / two-sided),
  *                 translated from the bound rasterizer state.
+ *   front_cw      VkFrontFace convention: false = counter-clockwise (default),
+ *                 true = clockwise. Selects the winding the cull and
+ *                 gl_FrontFacing are evaluated against.
  *   vp_sx/tx/sy/ty  viewport transform (screen = ndc*scale + bias) captured
  *                 from the app's VkViewport; a negative vp_sy is the Vulkan
  *                 y-flip. The caller only takes this path for a full-framebuffer
@@ -210,7 +213,7 @@ bool vp_raster_draw(struct pipe_screen *screen, vx_device_h dev,
                     uint32_t width, uint32_t height,
                     const struct vp_om_params *om,
                     uint64_t tex_dev, const struct vp_tex_params *tex,
-                    uint32_t cull_mode,
+                    uint32_t cull_mode, bool front_cw,
                     bool sw_tex, bool sw_om, bool sw_raster,
                     float vp_sx, float vp_tx, float vp_sy, float vp_ty,
                     float vp_min_z, float vp_max_z,
3. Stored edge equations are built in a space with a per-edge w factor

Barycentrics exact when 1/w is uniform, drifting in proportion to the perspective spread. Textures look "smeared" rather than wrong.

setup_triangle built the stored edge equations from ClipToHDC, which keeps w (HDC = w * screen), so every edge coefficient carried its own w_i * w_j. Both consumers - the raster RTL (VX_raster_edge) and the fragment shader (emit_bc) - evaluate the coefficients at plain pixel coordinates, so F_i / sum(F) stops being affine. The factors cancel only when all three w are equal.

Resulting in a twisted textures especially visible between triangles

In my case I have tried to rewrite it to rebuild from the screen-space vertices the bbox block already computes; the homogeneous pass still drives facing. This is just example of how I fixed it, you might get some better way.

Patch
diff --git a/sw/common/gfx_setup.h b/sw/common/gfx_setup.h
index dca7e6cef..a86f71406 100644
--- a/sw/common/gfx_setup.h
+++ b/sw/common/gfx_setup.h
@@ -76,27 +76,6 @@ static inline float fmax2(float a, float b) { return a > b ? a : b; }
 static inline int   imin2(int a, int b)     { return a < b ? a : b; }
 static inline int   imax2(int a, int b)     { return a > b ? a : b; }
 
-// Clip-space (x,y,z,w) -> homogeneous-device-coordinate; W preserved so edge
-// equations stay perspective-correct (graphics.cpp ClipToHDC).
-// Viewport bounds are float so a fractional / y-flipped (top>bottom) app
-// viewport transforms exactly; a full-framebuffer viewport passes integer
-// bounds unchanged.
-static inline vec4f ClipToHDC(const vec4f& in, float left, float right,
-                              float top, float bottom, float near, float far,
-                              bool halfz = false) {
-  float minX   = (left + right) * 0.5f;
-  float scaleX = (right - left) * 0.5f;
-  float minY   = (top + bottom) * 0.5f;
-  float scaleY = (bottom - top) * 0.5f;
-  // GL maps [-1,1] onto [near,far]; Vulkan's clip z is already 0-based.
-  float minZ   = halfz ? near : (near + far) * 0.5f;
-  float scaleZ = halfz ? (far - near) : (far - near) * 0.5f;
-  return { in.x * scaleX + in.w * minX,
-           in.y * scaleY + in.w * minY,
-           in.z * scaleZ + in.w * minZ,
-           in.w };
-}
-
 // Clip-space -> screen space (perspective divide then viewport).
 static inline vec4f ClipToScreen(const vec4f& in, float left, float right,
                                  float top, float bottom, float near, float far,
@@ -242,22 +221,28 @@ static inline bool setup_triangle(const setup_vertex_t& v0,
   const float zn = vp_has_z ? vp->minz : near;
   const float zf = vp_has_z ? vp->maxz : far;
 
-  // Edge equations in HDC.
+  // Screen-space vertices: the bbox needs them, and so do the edge equations.
+  vec4f ps0 = ClipToScreen(p0, L, R, T, B, zn, zf, halfz);
+  vec4f ps1 = ClipToScreen(p1, L, R, T, B, zn, zf, halfz);
+  vec4f ps2 = ClipToScreen(p2, L, R, T, B, zn, zf, halfz);
+
+  // Edge equations in screen space. Both consumers - the raster and the fragment
+  // shader - evaluate the stored coefficients at plain pixel coordinates, so the
+  // coefficients have to be affine. EdgeEquation uses w only inside its cross
+  // products, so feeding it w=1 gives exactly that, and keeps the winding,
+  // cull-mode and degenerate decisions in the one place they already lived.
   vec3f edges[3];
   bool back = false;
   {
-    vec4f ph0 = ClipToHDC(p0, L, R, T, B, zn, zf, halfz);
-    vec4f ph1 = ClipToHDC(p1, L, R, T, B, zn, zf, halfz);
-    vec4f ph2 = ClipToHDC(p2, L, R, T, B, zn, zf, halfz);
-    if (!EdgeEquation(edges, ph0, ph1, ph2, cull_mode, &back, front_cw))
+    const vec4f s0 = {ps0.x, ps0.y, 0.0f, 1.0f};
+    const vec4f s1 = {ps1.x, ps1.y, 0.0f, 1.0f};
+    const vec4f s2 = {ps2.x, ps2.y, 0.0f, 1.0f};
+    if (!EdgeEquation(edges, s0, s1, s2, cull_mode, &back, front_cw))
       return false;  // degenerate or face-culled
   }
   out_prim.facing = back ? 1u : 0u;
 
   // Screen-space bbox (clamped to render target).
-  vec4f ps0 = ClipToScreen(p0, L, R, T, B, zn, zf, halfz);
-  vec4f ps1 = ClipToScreen(p1, L, R, T, B, zn, zf, halfz);
-  vec4f ps2 = ClipToScreen(p2, L, R, T, B, zn, zf, halfz);
   {
     float left   = fmin2(ps0.x, fmin2(ps1.x, ps2.x));
     float right  = fmax2(ps0.x, fmax2(ps1.x, ps2.x));
@@ -276,32 +261,6 @@ static inline bool setup_triangle(const setup_vertex_t& v0,
       return false;  // empty
   }
 
-  // Affine, screen-space edge equations. The homogeneous HDC coefficients keep w
-  // inside them, so each edge carries its own w_i*w_j factor; the raster and the
-  // fragment shader both evaluate the stored coefficients at plain pixel
-  // coordinates, and a per-edge scale factor makes F_i/sum(F) non-affine - it
-  // drifts as soon as the three w differ, which is what perspective-correct
-  // interpolation must not do. Screen-space coefficients are the affine set the
-  // two consumers assume. The winding (and hence the flip) is unchanged by the
-  // perspective divide because every w is positive.
-  {
-    const vec4f ps[3] = {ps0, ps1, ps2};
-    for (int k = 0; k < 3; ++k) {
-      const vec4f& ea = ps[(k + 1) % 3];
-      const vec4f& eb = ps[(k + 2) % 3];
-      edges[k].x = ea.y - eb.y;
-      edges[k].y = eb.x - ea.x;
-      edges[k].z = ea.x * eb.y - eb.x * ea.y;
-    }
-    float det2 = edges[0].x * ps0.x + edges[0].y * ps0.y + edges[0].z;
-    if (det2 < 0.0f) {
-      for (int k = 0; k < 3; ++k) {
-        edges[k].x = -edges[k].x;
-        edges[k].y = -edges[k].y;
-        edges[k].z = -edges[k].z;
-      }
-    }
-  }
   // Half-pixel sampling offset, then Q15.16 edges.
   edges[0].z += edges[0].x * 0.5f + edges[0].y * 0.5f;
   edges[1].z += edges[1].x * 0.5f + edges[1].y * 0.5f;

Failure example image Image
4. The quad-derivative path read the wrong thread id

The most obvious effect, quads' screen-space derivatives are dispatched wrong due to seemingly wrong variable passed in shader compiler

Patch
diff --git a/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c b/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c
--- a/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c
+++ b/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c
@@ -4730,7 +4748,7 @@ emit_quad_deriv(struct vp_tr *t, LLVMValueRef value, unsigned dir)
    LLVMValueRef fs   = LLVMBuildBitCast(t->b, self, t->f32, "");
    LLVMValueRef fn_  = LLVMBuildBitCast(t->b, nb,   t->f32, "");
 
-   LLVMValueRef lane = emit_csr_read(t, VX_CSR_CTA_THREAD_ID_X, "lane");
+   LLVMValueRef lane = emit_csr_read(t, VX_CSR_THREAD_ID, "lane");
    LLVMValueRef far  = LLVMBuildICmp(t->b, LLVMIntNE,
       LLVMBuildAnd(t->b, lane, LLVMConstInt(t->i32, dir, false), ""),
       LLVMConstInt(t->i32, 0, false), "far");
Failure example image Image
5. Subtle unorm rounding issue

emit_to_byte() truncated where Vulkan rounds
Subtle lsb level shifts of colors diverging from llvm-pipe reference, easy to fix and non-critical

Patch
diff --git a/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c b/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c
--- a/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c
+++ b/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c
@@ -4842,6 +4864,7 @@ emit_to_byte(struct vp_tr *t, LLVMValueRef f)
       t->i32, "");
    LLVMValueRef v = LLVMBuildMul(t->b, q,
       LLVMConstInt(t->i32, 255, false), "");
+   v = LLVMBuildAdd(t->b, v, LLVMConstInt(t->i32, 8388608, false), "");
    v = LLVMBuildAShr(t->b, v, LLVMConstInt(t->i32, 24, false), "");
    return LLVMBuildAnd(t->b, v, LLVMConstInt(t->i32, 0xff, false), "");
 }
6. Complete shader failure on OM render target overflow

Under MESA_VORTEX_STRICT every draw became a no-op and the app rendered nothing; without strict mode everything silently fell back to the software path.

zink declares fragment outputs past the OM's four render targets (RT4 was seen with glxgears) even when nothing is bound there. The compiler treated rt >= GFX_OM_MAX_RT as a shader error, which left fsv NULL, which made hw_path false for the draw.

Aka, some programs declare many outputs, while not actually using them. Instead of failing I decided to allow them to overflow to scratchpad memory.

Patch
diff --git a/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c b/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c
--- a/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c
+++ b/src/gallium/drivers/vortexpipe/vp_nir_to_llvm.c
@@ -223,6 +223,9 @@ struct vp_tr {
     * FS output area; the wrapper packs slots 0..num_color-1 into a src_colors[]
     * array and calls gfx_om_fragment_mrt_sw when num_color > 1. */
    unsigned       fs_num_color;
+   /* Bound colour attachments; colour outputs at or beyond this index are
+    * discarded (routed to a scratch slot) as Vulkan requires. */
+   unsigned       fs_color_limit;
    unsigned       fs_out_words;  /* i32 words in the FS output area (incl. scratch) */
    int            fs_depth_off;  /* byte offset of gl_FragDepth's slot; -1 if unwritten */
    /* gl_FragCoord is declared as a shader input and so owns a slot in the input
@@ -4628,13 +4631,28 @@ fs_scan_io(struct vp_tr *t, struct nir_shader *nir)
          slot = GFX_OM_MAX_RT + scratch;      /* scratch area past the colours */
          scratch++;
       } else {
-         if ((unsigned)rt >= GFX_OM_MAX_RT) { /* bound the RT index */
-            mesa_loge("vortexpipe: FS colour output RT%d exceeds VX_OM_MAX_RT=%u",
-                      rt, GFX_OM_MAX_RT);
-            VP_FAIL(t); return;
+         if ((unsigned)rt >= GFX_OM_MAX_RT || (unsigned)rt >= t->fs_color_limit) {
+            /* beyond the bound colour attachments: Vulkan discards it */
+            /* Local patch for the Arria 10 bring-up. zink declares fragment outputs
+             * past the OM's four render targets (RT4 seen with glxgears) even when
+             * nothing is bound there. Failing the whole shader leaves fsv NULL, so
+             * hw_path is false and every draw falls back -- under MESA_VORTEX_STRICT
+             * that is a no-op and the app renders nothing. Give the unrepresentable
+             * output a scratch slot instead (exactly as depth/stencil already do):
+             * the OM cannot write RT>=%u in any case, and the remaining outputs stay
+             * usable, so the hardware path is taken. Warn once, not per shader. */
+            static bool rt_warned;
+            if (!rt_warned) {
+               rt_warned = true;
+               mesa_logw("vortexpipe: FS colour output RT%d beyond VX_OM_MAX_RT=%u routed to scratch (further such outputs not reported)",
+                         rt, GFX_OM_MAX_RT);
+            }
+            slot = GFX_OM_MAX_RT + scratch;
+            scratch++;
+         } else {
+            slot = (unsigned)rt;
+            if ((unsigned)rt + 1 > num_color) num_color = (unsigned)rt + 1;
          }
-         slot = (unsigned)rt;
-         if ((unsigned)rt + 1 > num_color) num_color = (unsigned)rt + 1;
       }
       t->vars[t->nvars].var     = var;
       t->vars[t->nvars].alloca  = NULL;
@@ -5775,6 +5798,9 @@ vp_nir_to_llvm(struct nir_shader *nir, char **out_ir,
    }
 
    struct vp_tr t = {0};
+   /* Bound colour attachments: colour outputs at or beyond this index are
+    * discarded (routed to scratch), as Vulkan requires. */
+   t.fs_color_limit = num_color ? num_color : GFX_OM_MAX_RT;
    t.ok    = true;
    t.is_vs = (nir->info.stage == MESA_SHADER_VERTEX);
    t.is_fs = (nir->info.stage == MESA_SHADER_FRAGMENT);

Now the questions:

What do you think about my mileage so far?
I am interested to know in what state the current gfx stack and rendering hw part of the project is.
As I understood the HW part is mostly working, but driver stack is still in prototype stage.
Which level of testing render and Vulkan/gl/etc paths are currently on (aka just synthetics for now; or it should already have been rendering right, and I did something wrong, getting such hurdles with minimal viable target (vkcube); or opposite: wip, untested, such problems to be expected, compute part is currently priority over gfx).
I am just clarifying where should I set my expectation with the current state of things, as I made first decision to trust repo, search errors in my additions; but that quickly fell apart and is more like: rtl is likely fine, first place to look at is driver, then shader compiler.

Also I have noticed that this is mostly a university project, so I hope I haven't completed somebody's lab/term assignment on accident :)

Nonetheless still really impressive stuff. I wish this project and its community to have wide recognition and an interesting future. I look forward to hearing back from you on opinion of my findings.

主要语言
Verilog
星标
2.4k
派生
563
平均合并
2 天 12 小时
30 天内合并 PR
33

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

vortexgpgpu/vortex 的其他 Issue

查看 vortexgpgpu/vortex 的全部 Issue

相似的 Issue

更多 Computer Graphics Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。