par-term-render 0.7.2

GPU-accelerated rendering engine for par-term terminal emulator
Documentation
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
//! GPU pipeline creation for cell renderer.
//!
//! This module contains functions for creating wgpu render pipelines
//! for backgrounds, text, background images, and visual bell.

use wgpu::*;

use super::types::{BackgroundInstance, TextInstance, Vertex};

/// Preferred glyph atlas texture size (width and height in pixels).
/// This value is validated against device limits at initialization.
const PREFERRED_ATLAS_SIZE: u32 = 2048;

/// Size in bytes of the visual bell uniform buffer.
/// Must be large enough to hold the bell uniforms struct, rounded up to
/// the wgpu minimum uniform buffer offset alignment (256 bytes).
const VISUAL_BELL_UNIFORM_BUFFER_SIZE: u64 = 64;

/// Size in bytes of the background image uniform buffer.
/// Contains a 4×4 transform matrix (16 × f32 = 64 bytes).
const BG_IMAGE_UNIFORM_BUFFER_SIZE: u64 = 64;

/// Custom blend state that blends RGB normally but replaces alpha.
/// This prevents alpha accumulation across multiple layers, ensuring
/// the final alpha equals window_opacity for proper window transparency.
const ALPHA_BLEND_RGB_REPLACE_ALPHA: BlendState = BlendState {
    color: BlendComponent {
        src_factor: BlendFactor::SrcAlpha,
        dst_factor: BlendFactor::OneMinusSrcAlpha,
        operation: BlendOperation::Add,
    },
    alpha: BlendComponent {
        // Replace alpha instead of accumulating: src * 1 + dst * 0 = src
        src_factor: BlendFactor::One,
        dst_factor: BlendFactor::Zero,
        operation: BlendOperation::Add,
    },
};

/// Text blend state: standard SrcAlpha blending for RGB, additive for alpha.
///
/// Anti-aliased text glyphs have fractional coverage alpha. Standard ALPHA_BLENDING
/// applies `SrcAlpha/OneMinusSrcAlpha` to the alpha channel too, which *reduces*
/// destination alpha (e.g., dst_a=1.0, glyph_a=0.5 → result_a=0.75). On macOS with
/// `CompositeAlphaMode::PreMultiplied`, this makes text edges translucent through to
/// the desktop.
///
/// Additive alpha (`One/One`, clamped to [0,1]) solves both use cases:
/// - **Direct-to-surface** (dst_a=1.0): `glyph_a + 1.0 ≥ 1.0 → clamped to 1.0` — opaque
/// - **Intermediate texture** (dst_a=0.0): `glyph_a + 0.0 = glyph_a` — custom shaders
///   can detect content via `step(0.01, terminalColor.a)`
const TEXT_BLEND: BlendState = BlendState {
    color: BlendComponent {
        src_factor: BlendFactor::SrcAlpha,
        dst_factor: BlendFactor::OneMinusSrcAlpha,
        operation: BlendOperation::Add,
    },
    alpha: BlendComponent {
        // Additive: src * 1 + dst * 1, clamped to [0,1] by hardware
        src_factor: BlendFactor::One,
        dst_factor: BlendFactor::One,
        operation: BlendOperation::Add,
    },
};

/// Create the background pipeline for cell backgrounds
pub fn create_bg_pipeline(device: &Device, surface_format: TextureFormat) -> RenderPipeline {
    let bg_shader = device.create_shader_module(include_wgsl!("../shaders/cell_bg.wgsl"));

    let bg_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
        label: Some("bg pipeline layout"),
        bind_group_layouts: &[],
        immediate_size: 0,
    });

    device.create_render_pipeline(&RenderPipelineDescriptor {
        label: Some("bg pipeline"),
        layout: Some(&bg_pipeline_layout),
        vertex: VertexState {
            module: &bg_shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: &[
                VertexBufferLayout {
                    array_stride: std::mem::size_of::<Vertex>() as BufferAddress,
                    step_mode: VertexStepMode::Vertex,
                    attributes: &vertex_attr_array![0 => Float32x2, 1 => Float32x2],
                },
                VertexBufferLayout {
                    array_stride: std::mem::size_of::<BackgroundInstance>() as BufferAddress,
                    step_mode: VertexStepMode::Instance,
                    attributes: &vertex_attr_array![2 => Float32x2, 3 => Float32x2, 4 => Float32x4],
                },
            ],
        },
        fragment: Some(FragmentState {
            module: &bg_shader,
            entry_point: Some("fs_main"),
            compilation_options: Default::default(),
            targets: &[Some(ColorTargetState {
                format: surface_format,
                // Use custom blend that replaces alpha to prevent accumulation
                // This ensures window_opacity is preserved across layers
                blend: Some(ALPHA_BLEND_RGB_REPLACE_ALPHA),
                write_mask: ColorWrites::ALL,
            })],
        }),
        primitive: PrimitiveState {
            topology: PrimitiveTopology::TriangleStrip,
            ..Default::default()
        },
        depth_stencil: None,
        multisample: MultisampleState::default(),
        cache: None,
        multiview_mask: None,
    })
}

/// Create the text bind group layout
pub fn create_text_bind_group_layout(device: &Device) -> BindGroupLayout {
    device.create_bind_group_layout(&BindGroupLayoutDescriptor {
        label: Some("text bind group layout"),
        entries: &[
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                ty: BindingType::Texture {
                    sample_type: TextureSampleType::Float { filterable: true },
                    view_dimension: TextureViewDimension::D2,
                    multisampled: false,
                },
                count: None,
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                ty: BindingType::Sampler(SamplerBindingType::Filtering),
                count: None,
            },
        ],
    })
}

/// Create the text bind group
pub fn create_text_bind_group(
    device: &Device,
    layout: &BindGroupLayout,
    atlas_view: &TextureView,
    atlas_sampler: &Sampler,
) -> BindGroup {
    device.create_bind_group(&BindGroupDescriptor {
        label: Some("text bind group"),
        layout,
        entries: &[
            BindGroupEntry {
                binding: 0,
                resource: BindingResource::TextureView(atlas_view),
            },
            BindGroupEntry {
                binding: 1,
                resource: BindingResource::Sampler(atlas_sampler),
            },
        ],
    })
}

/// Create the text pipeline for glyph rendering
pub fn create_text_pipeline(
    device: &Device,
    surface_format: TextureFormat,
    text_bind_group_layout: &BindGroupLayout,
) -> RenderPipeline {
    let text_shader = device.create_shader_module(include_wgsl!("../shaders/cell_text.wgsl"));

    let text_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
        label: Some("text pipeline layout"),
        bind_group_layouts: &[Some(text_bind_group_layout)],
        immediate_size: 0,
    });

    device.create_render_pipeline(&RenderPipelineDescriptor {
        label: Some("text pipeline"),
        layout: Some(&text_pipeline_layout),
        vertex: VertexState {
            module: &text_shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: &[
                VertexBufferLayout {
                    array_stride: std::mem::size_of::<Vertex>() as BufferAddress,
                    step_mode: VertexStepMode::Vertex,
                    attributes: &vertex_attr_array![0 => Float32x2, 1 => Float32x2],
                },
                VertexBufferLayout {
                    array_stride: std::mem::size_of::<TextInstance>() as BufferAddress,
                    step_mode: VertexStepMode::Instance,
                    attributes: &vertex_attr_array![
                        2 => Float32x2,
                        3 => Float32x2,
                        4 => Float32x2,
                        5 => Float32x2,
                        6 => Float32x4,
                        7 => Uint32
                    ],
                },
            ],
        },
        fragment: Some(FragmentState {
            module: &text_shader,
            entry_point: Some("fs_main"),
            compilation_options: Default::default(),
            targets: &[Some(ColorTargetState {
                format: surface_format,
                // Use TEXT_BLEND: standard SrcAlpha for RGB, additive for alpha.
                // This prevents anti-aliased text from reducing destination alpha
                // (which causes window translucency on macOS) while preserving
                // alpha writes needed for custom shader content detection.
                blend: Some(TEXT_BLEND),
                write_mask: ColorWrites::ALL,
            })],
        }),
        primitive: PrimitiveState {
            topology: PrimitiveTopology::TriangleStrip,
            ..Default::default()
        },
        depth_stencil: None,
        multisample: MultisampleState::default(),
        cache: None,
        multiview_mask: None,
    })
}

/// Create the background image bind group layout
pub fn create_bg_image_bind_group_layout(device: &Device) -> BindGroupLayout {
    device.create_bind_group_layout(&BindGroupLayoutDescriptor {
        label: Some("bg image bind group layout"),
        entries: &[
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                ty: BindingType::Texture {
                    sample_type: TextureSampleType::Float { filterable: true },
                    view_dimension: TextureViewDimension::D2,
                    multisampled: false,
                },
                count: None,
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                ty: BindingType::Sampler(SamplerBindingType::Filtering),
                count: None,
            },
            BindGroupLayoutEntry {
                binding: 2,
                visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
                ty: BindingType::Buffer {
                    ty: BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
        ],
    })
}

/// Create the background image pipeline
pub fn create_bg_image_pipeline(
    device: &Device,
    surface_format: TextureFormat,
    bg_image_bind_group_layout: &BindGroupLayout,
) -> RenderPipeline {
    let bg_image_shader =
        device.create_shader_module(include_wgsl!("../shaders/background_image.wgsl"));

    let bg_image_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
        label: Some("bg image pipeline layout"),
        bind_group_layouts: &[Some(bg_image_bind_group_layout)],
        immediate_size: 0,
    });

    device.create_render_pipeline(&RenderPipelineDescriptor {
        label: Some("bg image pipeline"),
        layout: Some(&bg_image_pipeline_layout),
        vertex: VertexState {
            module: &bg_image_shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: &[VertexBufferLayout {
                array_stride: std::mem::size_of::<Vertex>() as BufferAddress,
                step_mode: VertexStepMode::Vertex,
                attributes: &vertex_attr_array![0 => Float32x2, 1 => Float32x2],
            }],
        },
        fragment: Some(FragmentState {
            module: &bg_image_shader,
            entry_point: Some("fs_main"),
            compilation_options: Default::default(),
            targets: &[Some(ColorTargetState {
                format: surface_format,
                // Use premultiplied alpha blending since shader outputs premultiplied colors
                blend: Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                write_mask: ColorWrites::ALL,
            })],
        }),
        primitive: PrimitiveState {
            topology: PrimitiveTopology::TriangleStrip,
            ..Default::default()
        },
        depth_stencil: None,
        multisample: MultisampleState::default(),
        cache: None,
        multiview_mask: None,
    })
}

/// Create the visual bell pipeline using dedicated fullscreen shader.
///
/// This pipeline renders a simple fullscreen quad overlay for the visual bell
/// flash effect. Unlike cell backgrounds, it doesn't need vertex/instance buffers
/// since the quad is generated procedurally from vertex_index.
pub fn create_visual_bell_pipeline(
    device: &Device,
    surface_format: TextureFormat,
) -> (RenderPipeline, BindGroup, BindGroupLayout, Buffer) {
    let visual_bell_shader =
        device.create_shader_module(include_wgsl!("../shaders/visual_bell.wgsl"));

    let visual_bell_bind_group_layout =
        device.create_bind_group_layout(&BindGroupLayoutDescriptor {
            label: Some("visual bell bind group layout"),
            entries: &[BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
                ty: BindingType::Buffer {
                    ty: BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        });

    let visual_bell_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
        label: Some("visual bell pipeline layout"),
        bind_group_layouts: &[Some(&visual_bell_bind_group_layout)],
        immediate_size: 0,
    });

    let visual_bell_pipeline = device.create_render_pipeline(&RenderPipelineDescriptor {
        label: Some("visual bell pipeline"),
        layout: Some(&visual_bell_pipeline_layout),
        vertex: VertexState {
            module: &visual_bell_shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: &[], // No vertex buffers - procedural quad from vertex_index
        },
        fragment: Some(FragmentState {
            module: &visual_bell_shader,
            entry_point: Some("fs_main"),
            compilation_options: Default::default(),
            targets: &[Some(ColorTargetState {
                format: surface_format,
                // Use premultiplied alpha blending for visual bell overlay
                blend: Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                write_mask: ColorWrites::ALL,
            })],
        }),
        primitive: PrimitiveState {
            topology: PrimitiveTopology::TriangleStrip,
            ..Default::default()
        },
        depth_stencil: None,
        multisample: MultisampleState::default(),
        cache: None,
        multiview_mask: None,
    });

    let visual_bell_uniform_buffer = device.create_buffer(&BufferDescriptor {
        label: Some("visual bell uniform buffer"),
        size: VISUAL_BELL_UNIFORM_BUFFER_SIZE,
        usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });

    let visual_bell_bind_group = device.create_bind_group(&BindGroupDescriptor {
        label: Some("visual bell bind group"),
        layout: &visual_bell_bind_group_layout,
        entries: &[BindGroupEntry {
            binding: 0,
            resource: visual_bell_uniform_buffer.as_entire_binding(),
        }],
    });

    (
        visual_bell_pipeline,
        visual_bell_bind_group,
        visual_bell_bind_group_layout,
        visual_bell_uniform_buffer,
    )
}

/// Create the glyph atlas texture and sampler.
///
/// Returns (texture, texture_view, sampler, actual_atlas_size).
/// The actual atlas size may be smaller than PREFERRED_ATLAS_SIZE if the
/// device has a lower max_texture_dimension_2d limit.
pub fn create_atlas(device: &Device) -> (Texture, TextureView, Sampler, u32) {
    let max_texture_size = device.limits().max_texture_dimension_2d;
    let atlas_size = PREFERRED_ATLAS_SIZE.min(max_texture_size);
    if atlas_size < PREFERRED_ATLAS_SIZE {
        log::warn!(
            "GPU texture size limit ({}) is smaller than preferred atlas size ({})",
            max_texture_size,
            PREFERRED_ATLAS_SIZE
        );
    }
    let atlas_texture = device.create_texture(&TextureDescriptor {
        label: Some("atlas texture"),
        size: Extent3d {
            width: atlas_size,
            height: atlas_size,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: TextureDimension::D2,
        format: TextureFormat::Rgba8Unorm,
        usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
        view_formats: &[],
    });
    let atlas_view = atlas_texture.create_view(&TextureViewDescriptor::default());
    let atlas_sampler = device.create_sampler(&SamplerDescriptor {
        address_mode_u: AddressMode::ClampToEdge,
        address_mode_v: AddressMode::ClampToEdge,
        mag_filter: FilterMode::Linear,
        min_filter: FilterMode::Linear,
        ..Default::default()
    });

    (atlas_texture, atlas_view, atlas_sampler, atlas_size)
}

/// Create the vertex buffer with unit quad vertices
pub fn create_vertex_buffer(device: &Device) -> Buffer {
    use wgpu::util::DeviceExt;

    let vertices = [
        Vertex {
            position: [0.0, 0.0],
            tex_coords: [0.0, 0.0],
        },
        Vertex {
            position: [1.0, 0.0],
            tex_coords: [1.0, 0.0],
        },
        Vertex {
            position: [0.0, 1.0],
            tex_coords: [0.0, 1.0],
        },
        Vertex {
            position: [1.0, 1.0],
            tex_coords: [1.0, 1.0],
        },
    ];

    device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("vertex buffer"),
        contents: bytemuck::cast_slice(&vertices),
        usage: BufferUsages::VERTEX,
    })
}

/// Create instance buffers for backgrounds and text
pub fn create_instance_buffers(
    device: &Device,
    max_bg_instances: usize,
    max_text_instances: usize,
) -> (Buffer, Buffer) {
    let bg_instance_buffer = device.create_buffer(&BufferDescriptor {
        label: Some("bg instance buffer"),
        size: (max_bg_instances * std::mem::size_of::<BackgroundInstance>()) as u64,
        usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });
    let text_instance_buffer = device.create_buffer(&BufferDescriptor {
        label: Some("text instance buffer"),
        size: (max_text_instances * std::mem::size_of::<TextInstance>()) as u64,
        usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });

    (bg_instance_buffer, text_instance_buffer)
}

/// Create the opaque-alpha pipeline that forces alpha=1.0 on the entire surface.
///
/// This is a permanent safeguard for macOS `CompositeAlphaMode::PreMultiplied`:
/// a single full-screen triangle writes ONLY the alpha channel (no blending,
/// `ColorWrites::ALPHA`), guaranteeing an opaque surface when window_opacity == 1.0.
/// The pass is skipped when the user wants actual window transparency.
pub fn create_opaque_alpha_pipeline(
    device: &Device,
    surface_format: TextureFormat,
) -> RenderPipeline {
    let shader = device.create_shader_module(include_wgsl!("../shaders/opaque_alpha.wgsl"));

    let layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
        label: Some("opaque alpha pipeline layout"),
        bind_group_layouts: &[],
        immediate_size: 0,
    });

    device.create_render_pipeline(&RenderPipelineDescriptor {
        label: Some("opaque alpha pipeline"),
        layout: Some(&layout),
        vertex: VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: &[],
        },
        fragment: Some(FragmentState {
            module: &shader,
            entry_point: Some("fs_main"),
            compilation_options: Default::default(),
            targets: &[Some(ColorTargetState {
                format: surface_format,
                blend: None,                    // No blending — direct write
                write_mask: ColorWrites::ALPHA, // ONLY write alpha channel
            })],
        }),
        primitive: PrimitiveState {
            topology: PrimitiveTopology::TriangleList,
            ..Default::default()
        },
        depth_stencil: None,
        multisample: MultisampleState::default(),
        cache: None,
        multiview_mask: None,
    })
}

/// Create the background image uniform buffer
pub fn create_bg_image_uniform_buffer(device: &Device) -> Buffer {
    device.create_buffer(&BufferDescriptor {
        label: Some("bg image uniform buffer"),
        size: BG_IMAGE_UNIFORM_BUFFER_SIZE,
        usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
        mapped_at_creation: false,
    })
}