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
//! Custom shader renderer for post-processing effects
//!
//! Supports Ghostty/Shadertoy-style GLSL shaders with the following uniforms:
//! - `iTime`: Time in seconds (animated or fixed at 0.0)
//! - `iResolution`: Viewport resolution (width, height, 1.0)
//! - `iChannel0-3`: User texture channels (Shadertoy compatible)
//! - `iChannel4`: Terminal content texture
//! - `iTimeKeyPress`: Time when last key was pressed (same timebase as iTime)
//!
//! Ghostty-compatible cursor uniforms (v1.2.0+):
//! - `iCurrentCursor`: Current cursor position (xy) and size (zw) in pixels
//! - `iPreviousCursor`: Previous cursor position and size
//! - `iCurrentCursorColor`: Current cursor RGBA color (with opacity baked in)
//! - `iPreviousCursorColor`: Previous cursor RGBA color
//! - `iTimeCursorChange`: Time when cursor last moved (same timebase as iTime)
use anyhow::{Context, Result};
use par_term_emu_core_rust::cursor::CursorStyle;
use std::collections::BTreeMap;
use std::path::Path;
use std::time::Instant;
use wgpu::util::DeviceExt;
use wgpu::*;
mod builtin_textures;
mod cubemap;
mod cursor;
mod hot_reload;
pub mod pipeline;
mod state;
pub mod textures;
pub mod transpiler;
pub mod types;
mod uniforms;
use cubemap::CubemapTexture;
use pipeline::{
BindGroupInputs, create_bind_group, create_bind_group_layout, create_render_pipeline,
};
use textures::{ChannelTexture, load_channel_textures};
use transpiler::transpile_glsl_to_wgsl;
fn debug_shader_wgsl_filename(shader_name: &str) -> String {
format!("/tmp/par_term_{shader_name}_shader.wgsl")
}
fn write_debug_shader_wgsl(shader_name: &str, wgsl_source: &str) {
let debug_filename = debug_shader_wgsl_filename(shader_name);
if let Err(e) = std::fs::write(&debug_filename, wgsl_source) {
log::warn!("Failed to write debug shader: {}", e);
} else {
log::info!("Wrote debug shader to {}", debug_filename);
}
}
fn animation_start_after_enabled_update(
currently_enabled: bool,
enabled: bool,
current_start: Instant,
now: Instant,
) -> Instant {
if enabled && !currently_enabled {
now
} else {
current_start
}
}
/// Custom shader renderer that applies post-processing effects
pub struct CustomShaderRenderer {
/// The render pipeline for the custom shader
pub(crate) pipeline: RenderPipeline,
/// Bind group for shader uniforms and textures
pub(crate) bind_group: BindGroup,
/// Uniform buffer for shader parameters
pub(crate) uniform_buffer: Buffer,
/// Uniform buffer for custom shader control values
pub(crate) custom_uniform_buffer: Buffer,
/// Intermediate texture to render terminal content into
pub(crate) intermediate_texture: Texture,
/// View of the intermediate texture
pub(crate) intermediate_texture_view: TextureView,
/// Start time for animation
pub(crate) start_time: Instant,
/// Whether animation is enabled
pub(crate) animation_enabled: bool,
/// Animation speed multiplier
pub(crate) animation_speed: f32,
/// Current texture dimensions
pub(crate) texture_width: u32,
pub(crate) texture_height: u32,
/// Surface format for compatibility
pub(crate) surface_format: TextureFormat,
/// Bind group layout for recreating bind groups on resize
pub(crate) bind_group_layout: BindGroupLayout,
/// Sampler for the intermediate texture
pub(crate) sampler: Sampler,
/// Display scale factor for DPI scaling (e.g., 2.0 on Retina)
pub(crate) scale_factor: f32,
/// Window opacity for transparency
pub(crate) window_opacity: f32,
/// When true, text is always rendered at full opacity (overrides text_opacity)
pub(crate) keep_text_opaque: bool,
/// Full content mode - shader receives and can manipulate full terminal content
pub(crate) full_content_mode: bool,
/// Brightness multiplier for shader output (0.05-1.0)
pub(crate) brightness: f32,
/// Whether to dim shader output under terminal content.
pub(crate) auto_dim_under_text: bool,
/// Strength of dimming under terminal content.
pub(crate) auto_dim_strength: f32,
/// Frame counter for iFrame uniform
pub(crate) frame_count: u32,
/// Last frame time for calculating time delta
pub(crate) last_frame_time: Instant,
/// Current mouse position in pixels (xy)
pub(crate) mouse_position: [f32; 2],
/// Last click position in pixels (zw)
pub(crate) mouse_click_position: [f32; 2],
/// Whether mouse button is currently pressed (affects sign of zw)
pub(crate) mouse_button_down: bool,
/// Frame rate tracking: time accumulator for averaging
pub(crate) frame_time_accumulator: f32,
/// Frame rate tracking: frames in current second
pub(crate) frames_in_second: u32,
/// Current smoothed frame rate
pub(crate) current_frame_rate: f32,
// ============ Cursor tracking (Ghostty-compatible) ============
/// Current cursor position in cell coordinates (col, row)
pub(crate) current_cursor_pos: (usize, usize),
/// Previous cursor position in cell coordinates
pub(crate) previous_cursor_pos: (usize, usize),
/// Current cursor RGBA color
pub(crate) current_cursor_color: [f32; 4],
/// Previous cursor RGBA color
pub(crate) previous_cursor_color: [f32; 4],
/// Current cursor opacity (0.0 = invisible, 1.0 = fully visible)
pub(crate) current_cursor_opacity: f32,
/// Previous cursor opacity
pub(crate) previous_cursor_opacity: f32,
/// Time when cursor position last changed (same timebase as iTime)
pub(crate) cursor_change_time: f32,
/// Current cursor style (for size calculation)
pub(crate) current_cursor_style: CursorStyle,
/// Previous cursor style
pub(crate) previous_cursor_style: CursorStyle,
/// Cell width in pixels (for cursor position calculation)
pub(crate) cursor_cell_width: f32,
/// Cell height in pixels (for cursor position calculation)
pub(crate) cursor_cell_height: f32,
/// Window padding in pixels (for cursor position calculation)
pub(crate) cursor_window_padding: f32,
/// Vertical content offset in pixels (e.g., tab bar height)
pub(crate) cursor_content_offset_y: f32,
/// Horizontal content offset in pixels (e.g., tab bar on left)
pub(crate) cursor_content_offset_x: f32,
// ============ Cursor shader configuration ============
/// User-configured cursor color for shader effects [R, G, B, A]
pub(crate) cursor_shader_color: [f32; 4],
/// Cursor trail duration in seconds
pub(crate) cursor_trail_duration: f32,
/// Cursor glow radius in pixels
pub(crate) cursor_glow_radius: f32,
/// Cursor glow intensity (0.0-1.0)
pub(crate) cursor_glow_intensity: f32,
// ============ Key press tracking ============
/// Time when a key was last pressed (same timebase as iTime)
pub(crate) key_press_time: f32,
// ============ Channel textures (iChannel0-3) ============
/// Texture channels 0-3 (placeholders or loaded textures, Shadertoy compatible)
pub(crate) channel_textures: [ChannelTexture; 4],
// ============ Cubemap texture (iCubemap) ============
/// Cubemap texture for environment mapping (placeholder or loaded)
pub(crate) cubemap: CubemapTexture,
// ============ Background image as iChannel0 ============
/// When true, use the background image texture as iChannel0 instead of the configured texture
pub(crate) use_background_as_channel0: bool,
/// Background texture to use as iChannel0 when use_background_as_channel0 is true
/// This is a reference texture (view + sampler + dimensions) from the cell renderer
pub(crate) background_channel_texture: Option<ChannelTexture>,
/// Blend mode hint exposed to shaders for background-as-iChannel0 composition.
pub(crate) background_channel0_blend_mode: par_term_config::ShaderBackgroundBlendMode,
// ============ Solid background color ============
/// Solid background color [R, G, B, A] for shader compositing.
/// When A > 0, the shader uses this color as background instead of shader output.
/// RGB values are NOT premultiplied.
pub(crate) background_color: [f32; 4],
// ============ Progress bar state ============
/// Progress bar data [state, percent, isActive, activeCount]
pub(crate) progress_data: [f32; 4],
// ============ Command state ============
/// Command state data [state, exitCode, eventTime, running]
pub(crate) command_data: [f32; 4],
// ============ Focused pane bounds ============
/// Focused pane bounds [x, y, width, height] in bottom-left-origin pixels.
pub(crate) focused_pane: [f32; 4],
// ============ Scrollback context ============
/// Scrollback context [offset, visibleLines, scrollbackLines, normalizedDepth]
pub(crate) scroll_data: [f32; 4],
// ============ Content inset for panels ============
/// Right content inset in pixels (e.g., AI Inspector panel).
/// The shader renders to a viewport offset by this amount from the left.
pub(crate) content_inset_right: f32,
// ============ Custom shader controls ============
/// Custom controls parsed from `// control ...` shader comments.
pub(crate) custom_controls: Vec<par_term_config::ShaderControl>,
/// Current custom uniform values keyed by control name.
pub(crate) custom_uniform_values: BTreeMap<String, par_term_config::ShaderUniformValue>,
}
/// Parameters for creating a new [`CustomShaderRenderer`].
pub struct CustomShaderRendererConfig<'a> {
pub surface_format: TextureFormat,
pub shader_path: &'a Path,
pub width: u32,
pub height: u32,
pub animation_enabled: bool,
pub animation_speed: f32,
pub window_opacity: f32,
pub full_content_mode: bool,
pub channel_paths: &'a [Option<std::path::PathBuf>; 4],
pub cubemap_path: Option<&'a Path>,
pub custom_uniforms: &'a BTreeMap<String, par_term_config::ShaderUniformValue>,
pub background_channel0_blend_mode: par_term_config::ShaderBackgroundBlendMode,
}
impl CustomShaderRenderer {
/// Create a new custom shader renderer from a GLSL shader file.
pub fn new(
device: &Device,
queue: &Queue,
config: CustomShaderRendererConfig<'_>,
) -> Result<Self> {
let CustomShaderRendererConfig {
surface_format,
shader_path,
width,
height,
animation_enabled,
animation_speed,
window_opacity,
full_content_mode,
channel_paths,
cubemap_path,
custom_uniforms,
background_channel0_blend_mode,
} = config;
// Load the GLSL shader
let glsl_source = std::fs::read_to_string(shader_path)
.with_context(|| format!("Failed to read shader file: {}", shader_path.display()))?;
let control_parse = par_term_config::parse_shader_controls(&glsl_source);
for warning in &control_parse.warnings {
log::warn!(
"Shader control warning line {}: {}",
warning.line,
warning.message
);
}
let custom_controls = control_parse.controls;
let custom_uniform_values = custom_uniforms.clone();
// Transpile GLSL to WGSL
let wgsl_source = transpile_glsl_to_wgsl(&glsl_source, shader_path)?;
log::info!(
"Loaded custom shader from {} ({} bytes GLSL -> {} bytes WGSL)",
shader_path.display(),
glsl_source.len(),
wgsl_source.len()
);
log::debug!("Generated WGSL:\n{}", wgsl_source);
// DEBUG: Write generated WGSL to file for inspection
let shader_name = shader_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
write_debug_shader_wgsl(shader_name, &wgsl_source);
// Pre-validate WGSL
let module = naga::front::wgsl::parse_str(&wgsl_source)
.context("Custom shader WGSL parse failed")?;
let _info = naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::empty(),
)
.validate(&module)
.context("Custom shader WGSL validation failed")?;
let shader_module = device.create_shader_module(ShaderModuleDescriptor {
label: Some("Custom Shader Module"),
source: ShaderSource::Wgsl(wgsl_source.clone().into()),
});
// Create intermediate texture for terminal content
let (intermediate_texture, intermediate_texture_view) =
Self::create_intermediate_texture(device, surface_format, width, height);
// Create sampler for the intermediate texture (terminal content)
// Use Nearest filtering to keep text crisp and pixel-perfect
let sampler = device.create_sampler(&SamplerDescriptor {
label: Some("Custom Shader Sampler"),
address_mode_u: AddressMode::ClampToEdge,
address_mode_v: AddressMode::ClampToEdge,
address_mode_w: AddressMode::ClampToEdge,
mag_filter: FilterMode::Nearest,
min_filter: FilterMode::Nearest,
mipmap_filter: FilterMode::Nearest,
..Default::default()
});
// Load channel textures (iChannel0-3)
let channel_textures = load_channel_textures(device, queue, channel_paths);
// Load cubemap texture (iCubemap)
let cubemap = match cubemap_path {
Some(path) => match CubemapTexture::from_prefix(device, queue, path) {
Ok(cm) => cm,
Err(e) => {
log::error!("Failed to load cubemap '{}': {}", path.display(), e);
CubemapTexture::placeholder(device, queue)
}
},
None => CubemapTexture::placeholder(device, queue),
};
// Create uniform buffers
let uniform_buffer = Self::create_uniform_buffer(device);
let custom_uniform_data =
crate::custom_shader_renderer::types::CustomShaderControlUniforms::from_controls(
&custom_controls,
&custom_uniform_values,
);
let custom_uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Custom Shader Control Uniform Buffer"),
contents: bytemuck::cast_slice(&[custom_uniform_data]),
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
});
// Create bind group layout and bind group
let bind_group_layout = create_bind_group_layout(device);
let bind_group = create_bind_group(
device,
BindGroupInputs {
layout: &bind_group_layout,
uniform_buffer: &uniform_buffer,
intermediate_texture_view: &intermediate_texture_view,
custom_uniform_buffer: &custom_uniform_buffer,
sampler: &sampler,
channel_textures: &channel_textures,
cubemap: &cubemap,
},
);
// Create render pipeline
let pipeline = create_render_pipeline(
device,
&shader_module,
&bind_group_layout,
surface_format,
Some("Custom Shader Pipeline"),
);
let now = Instant::now();
Ok(Self {
pipeline,
bind_group,
uniform_buffer,
custom_uniform_buffer,
intermediate_texture,
intermediate_texture_view,
start_time: now,
animation_enabled,
animation_speed,
texture_width: width,
texture_height: height,
surface_format,
bind_group_layout,
sampler,
window_opacity,
keep_text_opaque: false,
scale_factor: 1.0,
full_content_mode,
brightness: 1.0,
auto_dim_under_text: false,
auto_dim_strength: 0.35,
frame_count: 0,
last_frame_time: now,
mouse_position: [0.0, 0.0],
mouse_click_position: [0.0, 0.0],
mouse_button_down: false,
frame_time_accumulator: 0.0,
frames_in_second: 0,
current_frame_rate: 60.0,
current_cursor_pos: (0, 0),
previous_cursor_pos: (0, 0),
current_cursor_color: [1.0, 1.0, 1.0, 1.0],
previous_cursor_color: [1.0, 1.0, 1.0, 1.0],
current_cursor_opacity: 1.0,
previous_cursor_opacity: 1.0,
cursor_change_time: 0.0,
current_cursor_style: CursorStyle::SteadyBlock,
previous_cursor_style: CursorStyle::SteadyBlock,
cursor_cell_width: 10.0,
cursor_cell_height: 20.0,
cursor_window_padding: 0.0,
cursor_content_offset_y: 0.0,
cursor_content_offset_x: 0.0,
cursor_shader_color: [1.0, 1.0, 1.0, 1.0],
cursor_trail_duration: 0.5,
cursor_glow_radius: 80.0,
cursor_glow_intensity: 0.3,
key_press_time: 0.0,
channel_textures,
cubemap,
use_background_as_channel0: false,
background_channel_texture: None,
background_channel0_blend_mode,
background_color: [0.0, 0.0, 0.0, 0.0], // No solid background by default
progress_data: [0.0, 0.0, 0.0, 0.0],
command_data: [0.0, 0.0, 0.0, 0.0],
focused_pane: [0.0, 0.0, width as f32, height as f32],
scroll_data: [0.0, 0.0, 0.0, 0.0],
content_inset_right: 0.0,
custom_controls,
custom_uniform_values,
})
}
/// Get a view of the intermediate texture for rendering terminal content into
pub fn intermediate_texture_view(&self) -> &TextureView {
&self.intermediate_texture_view
}
/// Render the custom shader effect to the output texture
///
/// # Arguments
/// * `device` - The GPU device
/// * `queue` - The command queue
/// * `output_view` - The texture view to render to
/// * `apply_opacity` - Whether to apply window opacity. Set to `false` when rendering
/// to an intermediate texture that will be processed by another shader (to avoid
/// double-applying opacity).
pub fn render(
&mut self,
device: &Device,
queue: &Queue,
output_view: &TextureView,
apply_opacity: bool,
) -> Result<()> {
self.render_with_clear_color(
device,
queue,
output_view,
apply_opacity,
Color::TRANSPARENT,
)
}
/// Render the custom shader with a specified clear color.
/// Use this for solid background colors where the clear color provides the background.
pub fn render_with_clear_color(
&mut self,
device: &Device,
queue: &Queue,
output_view: &TextureView,
apply_opacity: bool,
clear_color: Color,
) -> Result<()> {
let now = Instant::now();
// Calculate time value
let time = if self.animation_enabled {
self.start_time.elapsed().as_secs_f32() * self.animation_speed.max(0.0)
} else {
0.0
};
// Calculate time delta
let time_delta = now.duration_since(self.last_frame_time).as_secs_f32();
self.last_frame_time = now;
// Update frame rate calculation
self.frame_time_accumulator += time_delta;
self.frames_in_second += 1;
if self.frame_time_accumulator >= 1.0 {
self.current_frame_rate = self.frames_in_second as f32 / self.frame_time_accumulator;
self.frame_time_accumulator = 0.0;
self.frames_in_second = 0;
}
self.frame_count = self.frame_count.wrapping_add(1);
// Calculate uniforms
let uniforms = self.build_uniforms(time, time_delta, apply_opacity);
queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms]));
let custom_uniforms =
crate::custom_shader_renderer::types::CustomShaderControlUniforms::from_controls(
&self.custom_controls,
&self.custom_uniform_values,
);
queue.write_buffer(
&self.custom_uniform_buffer,
0,
bytemuck::cast_slice(&[custom_uniforms]),
);
// Create command encoder and render
let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor {
label: Some("Custom Shader Encoder"),
});
{
let mut render_pass = encoder.begin_render_pass(&RenderPassDescriptor {
label: Some("Custom Shader Render Pass"),
color_attachments: &[Some(RenderPassColorAttachment {
view: output_view,
resolve_target: None,
ops: Operations {
load: LoadOp::Clear(clear_color),
store: StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
// Note: We intentionally do NOT set a viewport here to exclude the panel area.
// The viewport approach doesn't work because fragCoord in WGSL is relative to
// the render target, not the viewport, causing UV coordinate mismatches.
// The opaque panel (PANEL_BG with alpha 255) covers any shader output under it.
render_pass.set_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &self.bind_group, &[]);
render_pass.draw(0..4, 0..1);
}
queue.submit(std::iter::once(encoder.finish()));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn enabling_animation_when_already_enabled_preserves_start_time() {
let start_time = Instant::now() - Duration::from_secs(5);
let now = Instant::now();
assert_eq!(
animation_start_after_enabled_update(true, true, start_time, now),
start_time
);
}
#[test]
fn enabling_animation_from_disabled_starts_at_now() {
let start_time = Instant::now() - Duration::from_secs(5);
let now = Instant::now();
assert_eq!(
animation_start_after_enabled_update(false, true, start_time, now),
now
);
}
#[test]
fn debug_shader_wgsl_filename_matches_new_renderer_output_path() {
assert_eq!(
debug_shader_wgsl_filename("matrix"),
"/tmp/par_term_matrix_shader.wgsl"
);
}
#[test]
fn write_debug_shader_wgsl_refreshes_existing_output() {
let shader_name = format!("par_term_test_{}", std::process::id());
let path = debug_shader_wgsl_filename(&shader_name);
let _ = std::fs::remove_file(&path);
write_debug_shader_wgsl(&shader_name, "first");
write_debug_shader_wgsl(&shader_name, "second");
assert_eq!(
std::fs::read_to_string(&path).expect("read debug wgsl"),
"second"
);
std::fs::remove_file(&path).expect("remove debug wgsl");
}
}