Skip to main content

par_term_render/cell_renderer/pane_render/
mod.rs

1// ARC-005 completed: file reduced from ~1004 lines to ~791 lines (target: <800).
2//
3// Extracted submodules:
4//   powerline.rs        — Powerline fringe-extension logic (pure fn, no self access).
5//                         `extend_powerline_fringes()` adjusts bg-quad x0/x1 to eliminate
6//                         anti-aliased dark fringes at separator boundaries.
7//   block_char_render.rs — Geometric rendering of block/box-drawing characters via the text
8//                          pipeline. `render_block_char_geometrically()` returns Some(new_idx)
9//                          when rendered; caller continues the per-cell loop.
10//
11// Note: The glyph font-fallback loop was extracted to `CellRenderer::resolve_glyph_with_fallback()`
12// in `atlas.rs` (ARC-004 / QA-003). The RLE bg-instance merge inner loop remains inlined
13// as it mutates self.bg_instances in place with no clean free-function boundary.
14//
15// IMPORTANT invariants to preserve (see MEMORY.md and CLAUDE.md):
16//   • 3-phase draw ordering: bg instances → text instances → cursor overlays
17//   • `fill_default_bg_cells` controls default-bg skip in bg-image mode
18//   • `skip_solid_background` must NOT be used to gate default-bg rendering
19//
20// Tracking: Issues ARC-005 and ARC-009 in AUDIT.md.
21
22use super::block_chars;
23use super::instance_buffers::{
24    STIPPLE_OFF_PX, STIPPLE_ON_PX, UNDERLINE_HEIGHT_RATIO, compute_cursor_text_color,
25};
26use super::{BackgroundInstance, Cell, CellRenderer, PaneViewport, TextInstance};
27use anyhow::Result;
28use par_term_config::{SeparatorMark, color_u8x4_rgb_to_f32, color_u8x4_rgb_to_f32_a};
29mod block_char_render;
30mod cursor_overlays;
31mod powerline;
32mod separators;
33
34use block_char_render::BlockCharRenderParams;
35
36use cursor_overlays::CursorOverlayParams;
37
38/// Atlas texture size in pixels. Must match the value used at atlas creation time.
39/// See `PREFERRED_ATLAS_SIZE` in `pipeline.rs` and `atlas_size` on `CellRendererAtlas`.
40pub(crate) const ATLAS_SIZE: f32 = 2048.0;
41
42/// Parameters for rendering a single pane to a surface texture view.
43pub struct PaneRenderViewParams<'a> {
44    pub viewport: &'a PaneViewport,
45    pub cells: &'a [Cell],
46    pub cols: usize,
47    pub rows: usize,
48    pub cursor_pos: Option<(usize, usize)>,
49    pub cursor_opacity: f32,
50    pub show_scrollbar: bool,
51    pub clear_first: bool,
52    pub skip_background_image: bool,
53    /// When true, emit background quads for default-bg cells (fills gaps in background-image mode).
54    /// Set to false in custom shader mode so the shader output shows through.
55    pub fill_default_bg_cells: bool,
56    pub separator_marks: &'a [SeparatorMark],
57    pub pane_background: Option<&'a par_term_config::PaneBackground>,
58}
59
60/// Parameters for building GPU instance buffers for a pane.
61pub(super) struct PaneInstanceBuildParams<'a> {
62    pub viewport: &'a PaneViewport,
63    pub cells: &'a [Cell],
64    pub cols: usize,
65    pub rows: usize,
66    pub cursor_pos: Option<(usize, usize)>,
67    pub cursor_opacity: f32,
68    pub skip_solid_background: bool,
69    pub fill_default_bg_cells: bool,
70    pub separator_marks: &'a [SeparatorMark],
71}
72
73impl CellRenderer {
74    /// Render a single pane's content within a viewport to an existing surface texture
75    ///
76    /// This method renders cells to a specific region of the render target,
77    /// using a GPU scissor rect to clip to the pane bounds.
78    ///
79    /// # Arguments
80    /// * `surface_view` - The texture view to render to
81    /// * `viewport` - The pane's viewport (position, size, focus state, opacity)
82    /// * `cells` - The cells to render (should match viewport grid size)
83    /// * `cols` - Number of columns in the cell grid
84    /// * `rows` - Number of rows in the cell grid
85    /// * `cursor_pos` - Cursor position (col, row) within this pane, or None if no cursor
86    /// * `cursor_opacity` - Cursor opacity (0.0 = hidden, 1.0 = fully visible)
87    /// * `show_scrollbar` - Whether to render the scrollbar for this pane
88    /// * `clear_first` - If true, clears the viewport region before rendering
89    /// * `skip_background_image` - If true, skip rendering the background image. Use this
90    ///   when the background image has already been rendered full-screen (for split panes).
91    pub fn render_pane_to_view(
92        &mut self,
93        surface_view: &wgpu::TextureView,
94        p: PaneRenderViewParams<'_>,
95    ) -> Result<()> {
96        let PaneRenderViewParams {
97            viewport,
98            cells,
99            cols,
100            rows,
101            cursor_pos,
102            cursor_opacity,
103            show_scrollbar,
104            clear_first,
105            skip_background_image,
106            fill_default_bg_cells,
107            separator_marks,
108            pane_background,
109        } = p;
110        // Build instance buffers for this pane's cells.
111        // Returns cursor_overlay_start: the bg_instance index where cursor overlays begin.
112        // Used for 3-phase rendering (bgs → text → cursor overlays).
113        let cursor_overlay_start = self.build_pane_instance_buffers(PaneInstanceBuildParams {
114            viewport,
115            cells,
116            cols,
117            rows,
118            cursor_pos,
119            cursor_opacity,
120            skip_solid_background: skip_background_image,
121            fill_default_bg_cells,
122            separator_marks,
123        })?;
124
125        // Pre-update per-pane background uniform buffer and bind group if needed (must happen
126        // before the render pass). Buffers are allocated once and reused across frames.
127        // Per-pane backgrounds are explicit user overrides and always prepared, even when a
128        // custom shader or global background would normally be skipped.
129        let has_pane_bg = if let Some(pane_bg) = pane_background
130            && let Some(ref path) = pane_bg.image_path
131            && self.bg_state.pane_bg_cache.contains_key(path.as_str())
132        {
133            self.prepare_pane_bg_bind_group(
134                path.as_str(),
135                super::background::PaneBgBindGroupParams {
136                    pane_x: viewport.x,
137                    pane_y: viewport.y,
138                    pane_width: viewport.width,
139                    pane_height: viewport.height,
140                    mode: pane_bg.mode,
141                    opacity: pane_bg.opacity,
142                    darken: pane_bg.darken,
143                },
144            );
145            true
146        } else {
147            false
148        };
149
150        // Retrieve cached path for use in the render pass (must be done before borrow in pass).
151        let pane_bg_path: Option<String> = if has_pane_bg {
152            pane_background
153                .and_then(|pb| pb.image_path.as_ref())
154                .map(|p| p.to_string())
155        } else {
156            None
157        };
158
159        let mut encoder = self
160            .device
161            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
162                label: Some("pane render encoder"),
163            });
164
165        // Determine load operation and clear color
166        let load_op = if clear_first {
167            let clear_color = if self.bg_state.bg_is_solid_color {
168                wgpu::Color {
169                    r: self.bg_state.solid_bg_color[0] as f64
170                        * self.window_opacity as f64
171                        * viewport.opacity as f64,
172                    g: self.bg_state.solid_bg_color[1] as f64
173                        * self.window_opacity as f64
174                        * viewport.opacity as f64,
175                    b: self.bg_state.solid_bg_color[2] as f64
176                        * self.window_opacity as f64
177                        * viewport.opacity as f64,
178                    a: self.window_opacity as f64 * viewport.opacity as f64,
179                }
180            } else {
181                wgpu::Color {
182                    r: self.background_color[0] as f64
183                        * self.window_opacity as f64
184                        * viewport.opacity as f64,
185                    g: self.background_color[1] as f64
186                        * self.window_opacity as f64
187                        * viewport.opacity as f64,
188                    b: self.background_color[2] as f64
189                        * self.window_opacity as f64
190                        * viewport.opacity as f64,
191                    a: self.window_opacity as f64 * viewport.opacity as f64,
192                }
193            };
194            wgpu::LoadOp::Clear(clear_color)
195        } else {
196            wgpu::LoadOp::Load
197        };
198
199        {
200            let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
201                label: Some("pane render pass"),
202                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
203                    view: surface_view,
204                    resolve_target: None,
205                    ops: wgpu::Operations {
206                        load: load_op,
207                        store: wgpu::StoreOp::Store,
208                    },
209                    depth_slice: None,
210                })],
211                depth_stencil_attachment: None,
212                timestamp_writes: None,
213                occlusion_query_set: None,
214            });
215
216            // Set scissor rect to clip rendering to pane bounds
217            let (sx, sy, sw, sh) = viewport.to_scissor_rect();
218            render_pass.set_scissor_rect(sx, sy, sw, sh);
219
220            // Render per-pane background image within scissor rect.
221            // Per-pane backgrounds are explicit user overrides and always render,
222            // even when a custom shader or global background is active.
223            if let Some(ref path) = pane_bg_path
224                && let Some(cached) = self.bg_state.pane_bg_uniform_cache.get(path.as_str())
225            {
226                render_pass.set_pipeline(&self.pipelines.bg_image_pipeline);
227                render_pass.set_bind_group(0, &cached.bind_group, &[]);
228                render_pass.set_vertex_buffer(0, self.buffers.vertex_buffer.slice(..));
229                render_pass.draw(0..4, 0..1);
230            }
231
232            self.emit_three_phase_draw_calls(
233                &mut render_pass,
234                cursor_overlay_start as u32,
235                self.buffers.actual_bg_instances as u32,
236            );
237
238            // Render scrollbar if requested (uses its own scissor rect internally)
239            if show_scrollbar {
240                // Reset scissor to full surface for scrollbar
241                render_pass.set_scissor_rect(0, 0, self.config.width, self.config.height);
242                self.scrollbar.render(&mut render_pass);
243            }
244        }
245
246        self.queue.submit(std::iter::once(encoder.finish()));
247        Ok(())
248    }
249
250    /// Build instance buffers for a pane's cells with viewport offset.
251    ///
252    /// Similar to `build_instance_buffers` but adjusts all positions to be relative to the
253    /// viewport origin. Also appends cursor overlay instances (beam bar and hollow borders)
254    /// after the cell background instances.
255    ///
256    /// Returns the index in `bg_instances` where cursor overlays begin (`cursor_overlay_start`).
257    /// The caller uses this for 3-phase rendering: cell bgs, text, then cursor overlays on top.
258    ///
259    /// `skip_solid_background`: if true, skip the solid background fill for the viewport
260    /// (use when a custom shader or background image was already rendered full-screen).
261    fn build_pane_instance_buffers(&mut self, p: PaneInstanceBuildParams<'_>) -> Result<usize> {
262        let PaneInstanceBuildParams {
263            viewport,
264            cells,
265            cols,
266            rows,
267            cursor_pos,
268            cursor_opacity,
269            skip_solid_background,
270            fill_default_bg_cells,
271            separator_marks,
272        } = p;
273        // Clear previous instance buffers
274        for instance in &mut self.bg_instances {
275            instance.size = [0.0, 0.0];
276            instance.color = [0.0, 0.0, 0.0, 0.0];
277        }
278
279        // Add a background rectangle covering the entire pane viewport (unless skipped)
280        // This ensures the pane has a proper background even when cells are skipped.
281        // Skip when a custom shader or background image was already rendered full-screen.
282        let bg_start_index = if !skip_solid_background && !self.bg_instances.is_empty() {
283            let bg_color = self.background_color;
284            let opacity = self.window_opacity * viewport.opacity;
285            let width_f = self.config.width as f32;
286            let height_f = self.config.height as f32;
287            self.bg_instances[0] = super::types::BackgroundInstance {
288                position: [
289                    viewport.x / width_f * 2.0 - 1.0,
290                    1.0 - (viewport.y / height_f * 2.0),
291                ],
292                size: [
293                    viewport.width / width_f * 2.0,
294                    viewport.height / height_f * 2.0,
295                ],
296                color: [
297                    bg_color[0] * opacity,
298                    bg_color[1] * opacity,
299                    bg_color[2] * opacity,
300                    opacity,
301                ],
302            };
303            1 // Start cell backgrounds at index 1
304        } else {
305            0 // Start cell backgrounds at index 0 (no viewport fill)
306        };
307
308        for instance in &mut self.text_instances {
309            instance.size = [0.0, 0.0];
310        }
311
312        // Start at bg_start_index (1 if viewport fill was added, 0 otherwise)
313        let mut bg_index = bg_start_index;
314        let mut text_index = 0;
315
316        // Content offset - positions are relative to content area (with padding applied)
317        let (content_x, content_y) = viewport.content_origin();
318        let opacity_multiplier = viewport.opacity;
319
320        for row in 0..rows {
321            let row_start = row * cols;
322            let row_end = (row + 1) * cols;
323            if row_start >= cells.len() {
324                break;
325            }
326            let row_cells = &cells[row_start..row_end.min(cells.len())];
327
328            // Background - use RLE to merge consecutive cells with same color
329            let mut col = 0;
330            while col < row_cells.len() {
331                let cell = &row_cells[col];
332                let bg_f = color_u8x4_rgb_to_f32(cell.bg_color);
333                let is_default_bg = (bg_f[0] - self.background_color[0]).abs() < 0.001
334                    && (bg_f[1] - self.background_color[1]).abs() < 0.001
335                    && (bg_f[2] - self.background_color[2]).abs() < 0.001;
336
337                // Check for cursor at this position (position check only, no opacity gate)
338                let cursor_at_cell = cursor_pos.is_some_and(|(cx, cy)| cx == col && cy == row)
339                    && !self.cursor.hidden_for_shader;
340                // Hollow cursor (unfocused + Hollow style) must show regardless of blink opacity
341                let render_hollow_here = cursor_at_cell
342                    && !self.is_focused
343                    && self.cursor.unfocused_style == par_term_config::UnfocusedCursorStyle::Hollow;
344                let has_cursor = (cursor_at_cell && cursor_opacity > 0.0) || render_hollow_here;
345
346                // Skip cells with half-block characters (▄/▀).
347                // These are rendered entirely through the text pipeline to avoid
348                // cross-pipeline coordinate seams that cause visible banding.
349                let is_half_block = {
350                    let mut chars = cell.grapheme.chars();
351                    matches!(chars.next(), Some('\u{2580}' | '\u{2584}')) && chars.next().is_none()
352                };
353
354                // Skip default-bg cells only when NOT in background-image/shader mode.
355                // When skip_solid_background is true (background image or custom shader active),
356                // no viewport fill is drawn, so default-bg cells between colored segments would
357                // show the background image through — causing visible gaps/lines in the tmux
358                // status bar. In that mode we render them with the theme background color instead.
359                // Skip default-bg cells unless fill_default_bg_cells is set (background-image mode).
360                // In normal mode: viewport fill quad covers them — no individual quad needed.
361                // In shader mode: shader output must show through — do not paint over it.
362                // In bg-image mode: fill_default_bg_cells=true — render with theme bg color to
363                // close gaps that would otherwise show the background image unexpectedly.
364                if is_half_block || (is_default_bg && !has_cursor && !fill_default_bg_cells) {
365                    col += 1;
366                    continue;
367                }
368
369                // Calculate background color with alpha and pane opacity
370                let bg_alpha =
371                    if self.transparency_affects_only_default_background && !is_default_bg {
372                        1.0
373                    } else {
374                        self.window_opacity
375                    };
376                let pane_alpha = bg_alpha * opacity_multiplier;
377                let mut bg_color = color_u8x4_rgb_to_f32_a(cell.bg_color, pane_alpha);
378
379                // TODO(QA-002/QA-008): extract into `render_cursor_cell()` helper.
380                // Signature would be:
381                //   fn render_cursor_cell(&mut self, col: usize, row: usize,
382                //       content_x: f32, content_y: f32, bg_color: [f32; 4],
383                //       cursor_opacity: f32, render_hollow_here: bool,
384                //       bg_index: &mut usize)
385                // Handle cursor at this position
386                if has_cursor {
387                    use par_term_emu_core_rust::cursor::CursorStyle;
388                    match self.cursor.style {
389                        CursorStyle::SteadyBlock | CursorStyle::BlinkingBlock => {
390                            if !render_hollow_here {
391                                // Solid block cursor: blend cursor color into background
392                                for (bg, &cursor) in
393                                    bg_color.iter_mut().take(3).zip(&self.cursor.color)
394                                {
395                                    *bg = *bg * (1.0 - cursor_opacity) + cursor * cursor_opacity;
396                                }
397                                bg_color[3] = bg_color[3].max(cursor_opacity * opacity_multiplier);
398                            }
399                            // If hollow: keep original background color (outline added as overlay)
400                        }
401                        _ => {}
402                    }
403
404                    // Cursor cell can't be merged
405                    // Snap to pixel boundaries to match text pipeline alignment
406                    let x0 = (content_x + col as f32 * self.grid.cell_width).round();
407                    let x1 = (content_x + (col + 1) as f32 * self.grid.cell_width).round();
408                    let y0 = (content_y + row as f32 * self.grid.cell_height).round();
409                    let y1 = (content_y + (row + 1) as f32 * self.grid.cell_height).round();
410
411                    if bg_index < self.buffers.max_bg_instances {
412                        self.bg_instances[bg_index] = BackgroundInstance {
413                            position: [
414                                x0 / self.config.width as f32 * 2.0 - 1.0,
415                                1.0 - (y0 / self.config.height as f32 * 2.0),
416                            ],
417                            size: [
418                                (x1 - x0) / self.config.width as f32 * 2.0,
419                                (y1 - y0) / self.config.height as f32 * 2.0,
420                            ],
421                            color: bg_color,
422                        };
423                        bg_index += 1;
424                    }
425                    col += 1;
426                    continue;
427                }
428
429                // RLE: Find run of consecutive cells with same background color
430                let start_col = col;
431                let run_color = cell.bg_color;
432                col += 1;
433                while col < row_cells.len() {
434                    let next_cell = &row_cells[col];
435                    let next_cursor_at_cell = cursor_pos
436                        .is_some_and(|(cx, cy)| cx == col && cy == row)
437                        && !self.cursor.hidden_for_shader;
438                    let next_hollow = next_cursor_at_cell
439                        && !self.is_focused
440                        && self.cursor.unfocused_style
441                            == par_term_config::UnfocusedCursorStyle::Hollow;
442                    let next_has_cursor =
443                        (next_cursor_at_cell && cursor_opacity > 0.0) || next_hollow;
444                    let next_is_half_block = {
445                        let mut chars = next_cell.grapheme.chars();
446                        matches!(chars.next(), Some('\u{2580}' | '\u{2584}'))
447                            && chars.next().is_none()
448                    };
449                    if next_cell.bg_color != run_color || next_has_cursor || next_is_half_block {
450                        break;
451                    }
452                    col += 1;
453                }
454                let run_length = col - start_col;
455
456                // Create single quad spanning entire run.
457                // Snap all edges to pixel boundaries to match the text pipeline and
458                // eliminate sub-pixel gaps between adjacent differently-colored cell runs.
459                let x0 = (content_x + start_col as f32 * self.grid.cell_width).round();
460                let x1 =
461                    (content_x + (start_col + run_length) as f32 * self.grid.cell_width).round();
462                let y0 = (content_y + row as f32 * self.grid.cell_height).round();
463                let y1 = (content_y + (row + 1) as f32 * self.grid.cell_height).round();
464
465                // Extend the colored bg quad 1 px under adjacent powerline separator glyphs
466                // to eliminate the dark fringe at their anti-aliased edges.
467                // See powerline.rs for full rationale.
468                let (x0, x1) =
469                    powerline::extend_powerline_fringes(powerline::PowerlineFringeParams {
470                        row_cells,
471                        start_col,
472                        col,
473                        x0,
474                        x1,
475                        skip_solid_background,
476                        is_default_bg,
477                        background_color: self.background_color,
478                    });
479
480                if bg_index < self.buffers.max_bg_instances {
481                    self.bg_instances[bg_index] = BackgroundInstance {
482                        position: [
483                            x0 / self.config.width as f32 * 2.0 - 1.0,
484                            1.0 - (y0 / self.config.height as f32 * 2.0),
485                        ],
486                        size: [
487                            (x1 - x0) / self.config.width as f32 * 2.0,
488                            (y1 - y0) / self.config.height as f32 * 2.0,
489                        ],
490                        color: bg_color,
491                    };
492                    bg_index += 1;
493                }
494            }
495
496            // Text rendering
497            let natural_line_height =
498                self.font.font_ascent + self.font.font_descent + self.font.font_leading;
499            let vertical_padding = (self.grid.cell_height - natural_line_height).max(0.0) / 2.0;
500            let baseline_y = content_y
501                + (row as f32 * self.grid.cell_height)
502                + vertical_padding
503                + self.font.font_ascent;
504
505            // Compute text alpha - force opaque if keep_text_opaque is enabled
506            let text_alpha = if self.keep_text_opaque {
507                opacity_multiplier // Only apply pane dimming, not window transparency
508            } else {
509                self.window_opacity * opacity_multiplier
510            };
511
512            // Check if this row has the cursor and it's a visible block cursor
513            // (for cursor text color override in split-pane rendering)
514            let cursor_is_block_on_this_row = {
515                use par_term_emu_core_rust::cursor::CursorStyle;
516                cursor_pos.is_some_and(|(_, cy)| cy == row)
517                    && cursor_opacity > 0.0
518                    && !self.cursor.hidden_for_shader
519                    && matches!(
520                        self.cursor.style,
521                        CursorStyle::SteadyBlock | CursorStyle::BlinkingBlock
522                    )
523                    && (self.is_focused
524                        || self.cursor.unfocused_style
525                            == par_term_config::UnfocusedCursorStyle::Same)
526            };
527
528            for (col_idx, cell) in row_cells.iter().enumerate() {
529                if cell.wide_char_spacer || cell.grapheme == " " {
530                    continue;
531                }
532
533                // Avoid Vec<char> allocation: use iterator-based char access.
534                let Some(ch) = cell.grapheme.chars().next() else {
535                    continue;
536                };
537                let second_char = cell.grapheme.chars().nth(1);
538                // grapheme_len is 1, 2, or "more than 2" — we stop counting at 3.
539                let grapheme_len = match second_char {
540                    None => 1usize,
541                    Some(_) => {
542                        if cell.grapheme.chars().nth(2).is_none() {
543                            2
544                        } else {
545                            3
546                        }
547                    }
548                };
549
550                // Determine text color - apply cursor_text_color (or auto-contrast) when the
551                // block cursor is on this cell, otherwise use the cell's foreground color.
552                let render_fg_color: [f32; 4] = if cursor_is_block_on_this_row
553                    && cursor_pos.is_some_and(|(cx, _)| cx == col_idx)
554                {
555                    compute_cursor_text_color(self.cursor.color, self.cursor.text_color, text_alpha)
556                } else {
557                    color_u8x4_rgb_to_f32_a(cell.fg_color, text_alpha)
558                };
559
560                // Classify character for block/box-drawing detection and glyph snapping.
561                let char_type = block_chars::classify_char(ch);
562
563                // Attempt geometric rendering for block/box-drawing characters.
564                // See block_char_render.rs for the full implementation.
565                let block_x0 = (content_x + col_idx as f32 * self.grid.cell_width).round();
566                let block_y0 = (content_y + row as f32 * self.grid.cell_height).round();
567                let block_y1 = (content_y + (row + 1) as f32 * self.grid.cell_height).round();
568                if let Some(new_idx) = self.render_block_char_geometrically(BlockCharRenderParams {
569                    cell,
570                    ch,
571                    grapheme_len,
572                    x0_pixel: block_x0,
573                    y0_pixel: block_y0,
574                    y1_pixel: block_y1,
575                    render_fg_color,
576                    text_alpha,
577                    text_index,
578                }) {
579                    text_index = new_idx;
580                    continue;
581                }
582
583                // Check if this character should be rendered as a monochrome symbol.
584                // Also handle symbol + VS16 (U+FE0F): strip VS16, render monochrome.
585                let (force_monochrome, base_char) = if grapheme_len == 1 {
586                    (super::atlas::should_render_as_symbol(ch), ch)
587                } else if grapheme_len == 2
588                    && second_char == Some('\u{FE0F}')
589                    && super::atlas::should_render_as_symbol(ch)
590                {
591                    // Symbol + VS16: strip VS16 and render base char as monochrome
592                    (true, ch)
593                } else {
594                    (false, ch)
595                };
596
597                // Resolve a renderable glyph via the shared font-fallback helper (ARC-004 / QA-003).
598                // This replaces the duplicated excluded_fonts/get_or_rasterize_glyph loop
599                // that previously existed in both pane_render/mod.rs and text_instance_builder.rs.
600                let resolved_info = self.resolve_glyph_with_fallback(
601                    base_char,
602                    &cell.grapheme,
603                    cell.bold,
604                    cell.italic,
605                    force_monochrome,
606                );
607
608                if let Some(info) = resolved_info {
609                    let char_w = if cell.wide_char {
610                        self.grid.cell_width * 2.0
611                    } else {
612                        self.grid.cell_width
613                    };
614                    let x0 = content_x + col_idx as f32 * self.grid.cell_width;
615                    let y0 = content_y + row as f32 * self.grid.cell_height;
616                    let x1 = x0 + char_w;
617                    let y1 = y0 + self.grid.cell_height;
618
619                    let cell_w = x1 - x0;
620                    let cell_h = y1 - y0;
621                    let scale_x = cell_w / char_w;
622                    let scale_y = cell_h / self.grid.cell_height;
623
624                    let baseline_offset =
625                        baseline_y - (content_y + row as f32 * self.grid.cell_height);
626                    let glyph_left = x0 + (info.bearing_x * scale_x).round();
627                    let baseline_in_cell = (baseline_offset * scale_y).round();
628                    let glyph_top = y0 + baseline_in_cell - info.bearing_y;
629
630                    let render_w = info.width as f32 * scale_x;
631                    let render_h = info.height as f32 * scale_y;
632
633                    let (final_left, final_top, final_w, final_h) =
634                        if grapheme_len == 1 && block_chars::should_snap_to_boundaries(char_type) {
635                            block_chars::snap_glyph_to_cell(block_chars::SnapGlyphParams {
636                                glyph_left,
637                                glyph_top,
638                                render_w,
639                                render_h,
640                                cell_x0: x0,
641                                cell_y0: y0,
642                                cell_x1: x1,
643                                cell_y1: y1,
644                                snap_threshold: 3.0,
645                                extension: 0.5,
646                            })
647                        } else {
648                            (glyph_left, glyph_top, render_w, render_h)
649                        };
650
651                    if text_index < self.buffers.max_text_instances {
652                        self.text_instances[text_index] = TextInstance {
653                            position: [
654                                final_left / self.config.width as f32 * 2.0 - 1.0,
655                                1.0 - (final_top / self.config.height as f32 * 2.0),
656                            ],
657                            size: [
658                                final_w / self.config.width as f32 * 2.0,
659                                final_h / self.config.height as f32 * 2.0,
660                            ],
661                            tex_offset: [info.x as f32 / ATLAS_SIZE, info.y as f32 / ATLAS_SIZE],
662                            tex_size: [
663                                info.width as f32 / ATLAS_SIZE,
664                                info.height as f32 / ATLAS_SIZE,
665                            ],
666                            color: render_fg_color,
667                            is_colored: if info.is_colored { 1 } else { 0 },
668                        };
669                        text_index += 1;
670                    }
671                }
672            }
673
674            // Underlines: emit a thin rectangle at the bottom of each underlined cell.
675            // Mirrors the logic in text_instance_builder.rs but uses pane-local coordinates.
676            {
677                let underline_thickness = (self.grid.cell_height * UNDERLINE_HEIGHT_RATIO)
678                    .max(1.0)
679                    .round();
680                let tex_offset = [
681                    self.atlas.solid_pixel_offset.0 as f32 / ATLAS_SIZE,
682                    self.atlas.solid_pixel_offset.1 as f32 / ATLAS_SIZE,
683                ];
684                let tex_size = [1.0 / ATLAS_SIZE, 1.0 / ATLAS_SIZE];
685                let y0 = content_y + (row + 1) as f32 * self.grid.cell_height - underline_thickness;
686                let ndc_y = 1.0 - (y0 / self.config.height as f32 * 2.0);
687                let ndc_h = underline_thickness / self.config.height as f32 * 2.0;
688                let is_stipple =
689                    self.link_underline_style == par_term_config::LinkUnderlineStyle::Stipple;
690                let stipple_period = STIPPLE_ON_PX + STIPPLE_OFF_PX;
691
692                for col_idx in 0..cols {
693                    if row_start + col_idx >= cells.len() {
694                        break;
695                    }
696                    let cell = &cells[row_start + col_idx];
697                    if !cell.underline {
698                        continue;
699                    }
700                    let fg = color_u8x4_rgb_to_f32_a(cell.fg_color, text_alpha);
701                    let cell_x0 = content_x + col_idx as f32 * self.grid.cell_width;
702
703                    if is_stipple {
704                        let mut px = 0.0;
705                        while px < self.grid.cell_width
706                            && text_index < self.buffers.max_text_instances
707                        {
708                            let seg_w = STIPPLE_ON_PX.min(self.grid.cell_width - px);
709                            let x = cell_x0 + px;
710                            self.text_instances[text_index] = TextInstance {
711                                position: [x / self.config.width as f32 * 2.0 - 1.0, ndc_y],
712                                size: [seg_w / self.config.width as f32 * 2.0, ndc_h],
713                                tex_offset,
714                                tex_size,
715                                color: fg,
716                                is_colored: 0,
717                            };
718                            text_index += 1;
719                            px += stipple_period;
720                        }
721                    } else if text_index < self.buffers.max_text_instances {
722                        self.text_instances[text_index] = TextInstance {
723                            position: [cell_x0 / self.config.width as f32 * 2.0 - 1.0, ndc_y],
724                            size: [self.grid.cell_width / self.config.width as f32 * 2.0, ndc_h],
725                            tex_offset,
726                            tex_size,
727                            color: fg,
728                            is_colored: 0,
729                        };
730                        text_index += 1;
731                    }
732                }
733            }
734        }
735
736        // Inject command separator line instances — see separators.rs
737        bg_index = self.emit_separator_instances(
738            separator_marks,
739            cols,
740            rows,
741            content_x,
742            content_y,
743            opacity_multiplier,
744            bg_index,
745        );
746
747        // --- Cursor overlays (beam/underline bar + hollow borders) ---
748        // These are rendered in Phase 3 (on top of text) via the 3-phase draw in render_pane_to_view.
749        // Record where cursor overlays start — everything after this index is an overlay.
750        let cursor_overlay_start = bg_index;
751
752        if let Some((cursor_col, cursor_row)) = cursor_pos {
753            let cursor_x0 = content_x + cursor_col as f32 * self.grid.cell_width;
754            let cursor_x1 = cursor_x0 + self.grid.cell_width;
755            let cursor_y0 = (content_y + cursor_row as f32 * self.grid.cell_height).round();
756            let cursor_y1 = (content_y + (cursor_row + 1) as f32 * self.grid.cell_height).round();
757
758            // Emit guide, shadow, beam/underline bar, hollow outline — see cursor_overlays.rs
759            bg_index = self.emit_cursor_overlays(
760                CursorOverlayParams {
761                    cursor_x0,
762                    cursor_x1,
763                    cursor_y0,
764                    cursor_y1,
765                    cols,
766                    content_x,
767                    cursor_opacity,
768                },
769                bg_index,
770            );
771        }
772
773        // Update actual instance counts for draw calls
774        self.buffers.actual_bg_instances = bg_index;
775        self.buffers.actual_text_instances = text_index;
776
777        // Upload only the used portion of instance buffers to GPU.
778        // Each pane typically uses a fraction of the full-window buffer, so uploading
779        // only [0..count] instead of the entire array significantly reduces per-pane
780        // staging bandwidth — critical when rendering many split panes per frame.
781        if bg_index > 0 {
782            self.queue.write_buffer(
783                &self.buffers.bg_instance_buffer,
784                0,
785                bytemuck::cast_slice(&self.bg_instances[..bg_index]),
786            );
787        }
788        if text_index > 0 {
789            self.queue.write_buffer(
790                &self.buffers.text_instance_buffer,
791                0,
792                bytemuck::cast_slice(&self.text_instances[..text_index]),
793            );
794        }
795
796        Ok(cursor_overlay_start)
797    }
798}