// 阶段 B2:text 批处理 shader
// 同 rect 模式:uniform(header) + storage(instance 数组)
// 所有 text 共享同一张 atlas + sampler → 1 bind group → 1 draw call 画 N text glyphs
//
// **前提**:同 layer 内所有 text 必须用同一个 atlas(text renderer 当前就是
// per-layer 共享 atlas,所以天然满足)。
struct TextBatchUniform {
// 屏幕逻辑尺寸 + instance 数量
screen_size: vec2<f32>, // 0..8
count: u32, // 8..12
// 阶段 B2 fix:用 f32 不用 vec2,避免 WGSL 16-align 把它推到 offset 16
// (这样 struct 整体 = 16 bytes,跟 Rust #[repr(C)] layout 一致)
_pad: f32, // 12..16
};
// struct size = 16 bytes (WGSL 16-align)
struct TextInstance {
// rect = (x, y, w, h) 屏幕坐标
rect: vec4<f32>,
// color = (r, g, b, a)
color: vec4<f32>,
// uv = (u0, v0, u1, v1) 归一化纹理坐标
uv: vec4<f32>,
// 纹理采样模式:x = 0.0 → Mask(alpha 取纹理 R 通道,glyph/SVG tint);
// x = 1.0 → Color(straight RGBA 全彩纹理,SVG 全彩 / PNG 图片);
// x = 2.0 → Alpha(alpha 取纹理 A 通道,纹理 mask 命令)
mode: vec4<f32>,
};
@group(0) @binding(0) var<uniform> batch: TextBatchUniform;
@group(0) @binding(1) var<storage, read> instances: array<TextInstance>;
@group(0) @binding(2) var atlas: texture_2d<f32>;
@group(0) @binding(3) var atlas_sampler: sampler;
struct VsOut {
@builtin(position) clip_pos: vec4<f32>,
@location(0) uv: vec2<f32>,
// 阶段 B2 fix:fragment 没有 instance_index → 用 varying 传 color
@location(1) color: vec4<f32>,
// 纹理采样模式(instance.mode.x)
@location(2) tex_mode: f32,
};
@vertex
fn vs_main(
@builtin(vertex_index) vid: u32,
@builtin(instance_index) iid: u32,
) -> VsOut {
// 6 顶点 quad
var positions = array(
vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0),
vec2(0.0, 1.0), vec2(1.0, 0.0), vec2(1.0, 1.0),
);
var uvs = array(
vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0),
vec2(0.0, 1.0), vec2(1.0, 0.0), vec2(1.0, 1.0),
);
let p = positions[vid];
let corner_uv = uvs[vid];
let inst = instances[iid];
// 屏幕坐标 → 裁剪坐标: x ∈ [0, screen_w] → [-1, 1]
let world = vec2(
inst.rect.x + p.x * inst.rect.z,
inst.rect.y + p.y * inst.rect.w,
);
let clip = (world / batch.screen_size) * 2.0 - vec2(1.0, 1.0);
// 翻转 Y(WGPU 屏幕坐标 Y 向下,裁剪坐标 Y 向上)
let ndc = vec4(clip.x, -clip.y, 0.0, 1.0);
var out: VsOut;
out.clip_pos = ndc;
// 线性插值 UV
out.uv = inst.uv.xy + corner_uv * (inst.uv.zw - inst.uv.xy);
out.color = inst.color;
out.tex_mode = inst.mode.x;
return out;
}
@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
let tex = textureSample(atlas, atlas_sampler, in.uv);
if (in.tex_mode > 1.5) {
// Alpha mask(P2-1.3):destination-in 混合下只用 alpha
return vec4(in.color.rgb, in.color.a * tex.a);
}
// Color 模式:直通 RGBA 全彩纹理(SVG 全彩 / PNG),color 乘进纹理色
if (in.tex_mode > 0.5) {
return vec4(tex.rgb * in.color.rgb, tex.a * in.color.a);
}
// Mask 模式(默认):采样 R 通道作为 alpha(glyph atlas R8 / SVG coverage)
return vec4(in.color.rgb, in.color.a * tex.r);
}