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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
use std::{cmp::min, fmt::Debug};
use beamterm_data::{CellSize, FontAtlasData, FontStyle, Glyph, GlyphEffect, TerminalSize};
use compact_str::CompactString;
use glow::HasContext;
use crate::{
CursorPosition,
error::Error,
gl::{
CellIterator, CellQuery, Drawable, GlState, RenderContext, ShaderProgram,
atlas::{self, FontAtlas, GlyphSlot},
buffer_upload_array,
dirty_regions::DirtyRegions,
selection::SelectionTracker,
ubo::UniformBufferObject,
},
mat4::Mat4,
};
/// A high-performance terminal grid renderer using instanced rendering.
///
/// `TerminalGrid` renders a grid of terminal cells using GL instanced drawing.
/// Each cell can display a character from a font atlas with customizable foreground
/// and background colors. The renderer uses a 2D texture array to efficiently
/// store glyph data and supports real-time updates of cell content.
#[derive(Debug)]
#[must_use = "call `delete(gl)` before dropping to avoid GPU resource leaks"]
pub struct TerminalGrid {
/// GPU resources (shader, buffers, UBOs) - recreated on context loss
gpu: GpuResources,
/// Terminal cell instance data
cells: Vec<CellDynamic>,
/// Terminal size in cells
terminal_size: TerminalSize,
/// Size of the canvas in pixels (physical)
canvas_size_px: (i32, i32),
/// Current device pixel ratio
pixel_ratio: f32,
/// Font atlas for rendering text.
atlas: FontAtlas,
/// Fallback glyph for missing symbols.
fallback_glyph: u16,
/// Selection tracker for managing cell selections.
selection: SelectionTracker,
/// Indicates whether there are cells pending flush to the GPU.
dirty_regions: DirtyRegions,
/// Background cell opacity (0.0 = fully transparent, 1.0 = fully opaque).
bg_alpha: f32,
}
/// GPU resources that need to be recreated after a context loss.
///
/// This struct encapsulates all GL-dependent resources: shader program,
/// vertex buffers, uniform buffer objects, and uniform locations. These
/// resources become invalid after a context loss and must be recreated
/// with a fresh GL context.
#[derive(Debug)]
struct GpuResources {
/// Shader program for rendering the terminal cells.
shader: ShaderProgram,
/// Buffers for the terminal grid (VAO, VBO, instance buffers)
buffers: TerminalBuffers,
/// Shared state for the vertex shader
ubo_vertex: UniformBufferObject,
/// Shared state for the fragment shader
ubo_fragment: UniformBufferObject,
/// Uniform location for the texture sampler.
sampler_loc: glow::UniformLocation,
}
impl GpuResources {
const FRAGMENT_GLSL: &'static str = include_str!("../shaders/cell.frag");
const VERTEX_GLSL: &'static str = include_str!("../shaders/cell.vert");
fn delete(&self, gl: &glow::Context) {
self.shader.delete(gl);
self.buffers.delete(gl);
self.ubo_vertex.delete(gl);
self.ubo_fragment.delete(gl);
}
/// Creates all GPU resources for the terminal grid.
///
/// This method creates and initializes:
/// - Vertex Array Object (VAO)
/// - Vertex and index buffers
/// - Instance buffers for cell positions and data
/// - Shader program
/// - Uniform Buffer Objects (UBOs)
fn new(
gl: &glow::Context,
cell_pos: &[CellStatic],
cell_data: &[CellDynamic],
cell_size: CellSize,
glsl_version: crate::GlslVersion,
) -> Result<Self, Error> {
// Create and setup the Vertex Array Object
let vao =
unsafe { gl.create_vertex_array() }.map_err(Error::vertex_array_creation_failed)?;
unsafe { gl.bind_vertex_array(Some(vao)) };
// Create all buffers
let buffers = setup_buffers(gl, vao, cell_pos, cell_data, cell_size)?;
// Unbind VAO to prevent accidental modification
unsafe { gl.bind_vertex_array(None) };
// Setup shader and uniform data with version-injected sources
let vertex_source = format!("{}{}", glsl_version.vertex_preamble(), Self::VERTEX_GLSL);
let fragment_source = format!(
"{}{}",
glsl_version.fragment_preamble(),
Self::FRAGMENT_GLSL
);
let shader = ShaderProgram::create(gl, &vertex_source, &fragment_source)?;
shader.use_program(gl);
let ubo_vertex = UniformBufferObject::new(gl, CellVertexUbo::BINDING_POINT)?;
ubo_vertex.bind_to_shader(gl, &shader, "VertUbo")?;
let ubo_fragment = UniformBufferObject::new(gl, CellFragmentUbo::BINDING_POINT)?;
ubo_fragment.bind_to_shader(gl, &shader, "FragUbo")?;
let sampler_loc = unsafe { gl.get_uniform_location(shader.program, "u_sampler") }
.ok_or(Error::uniform_location_failed("u_sampler"))?;
Ok(Self {
shader,
buffers,
ubo_vertex,
ubo_fragment,
sampler_loc,
})
}
}
#[derive(Debug)]
struct TerminalBuffers {
vao: glow::VertexArray,
vertices: glow::Buffer,
instance_pos: glow::Buffer,
instance_cell: glow::Buffer,
indices: glow::Buffer,
}
impl TerminalBuffers {
fn delete(&self, gl: &glow::Context) {
unsafe {
gl.delete_vertex_array(self.vao);
gl.delete_buffer(self.vertices);
gl.delete_buffer(self.instance_pos);
gl.delete_buffer(self.instance_cell);
gl.delete_buffer(self.indices);
}
}
/// Binds the VAO and instance cell buffer for sub-range uploads.
/// Must be paired with [`unbind_instance_buffer`](Self::unbind_instance_buffer).
fn bind_instance_buffer(&self, gl: &glow::Context) {
unsafe {
gl.bind_vertex_array(Some(self.vao));
gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.instance_cell));
}
}
/// Unbinds the VAO after sub-range uploads.
fn unbind_instance_buffer(&self, gl: &glow::Context) {
#![allow(clippy::unused_self)] // consistent API with bind_instance_buffer
unsafe { gl.bind_vertex_array(None) };
}
/// Uploads the full instance cell buffer via buffer orphaning.
///
/// The VAO and buffer must already be bound via
/// [`bind_instance_buffer`](Self::bind_instance_buffer).
#[allow(clippy::unused_self)] // consistent API with bind/unbind
fn upload_instance_data<T: Copy>(&self, gl: &glow::Context, cell_data: &[T]) {
unsafe { buffer_upload_array(gl, glow::ARRAY_BUFFER, cell_data, glow::DYNAMIC_DRAW) };
}
/// Uploads a sub-range of the instance cell buffer using `buffer_sub_data`.
///
/// The VAO and buffer must already be bound via
/// [`bind_instance_buffer`](Self::bind_instance_buffer).
#[allow(clippy::unused_self)] // consistent API with bind/unbind
fn upload_instance_data_range<T: Copy>(
&self,
gl: &glow::Context,
cell_data: &[T],
byte_offset: usize,
) {
unsafe {
let bytes =
std::slice::from_raw_parts(cell_data.as_ptr() as *const u8, size_of_val(cell_data));
gl.buffer_sub_data_u8_slice(glow::ARRAY_BUFFER, byte_offset as i32, bytes);
}
}
/// Updates the vertex buffer with new cell dimensions.
fn update_vertex_buffer(&self, gl: &glow::Context, cell_size: CellSize) {
let (w, h) = (cell_size.width as f32, cell_size.height as f32);
#[rustfmt::skip]
let vertices: [f32; 16] = [
//x y u v
w, 0.0, 1.0, 0.0, // top-right
0.0, h, 0.0, 1.0, // bottom-left
w, h, 1.0, 1.0, // bottom-right
0.0, 0.0, 0.0, 0.0 // top-left
];
unsafe {
gl.bind_vertex_array(Some(self.vao));
gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.vertices));
let bytes = std::slice::from_raw_parts(
vertices.as_ptr() as *const u8,
vertices.len() * size_of::<f32>(),
);
gl.buffer_sub_data_u8_slice(glow::ARRAY_BUFFER, 0, bytes);
gl.bind_vertex_array(None);
}
}
}
impl TerminalGrid {
/// Creates a new terminal grid with the given atlas and screen dimensions.
///
/// # Errors
/// Returns an error if shader compilation, buffer creation, or other
/// GPU resource allocation fails.
pub fn new(
gl: &glow::Context,
mut atlas: FontAtlas,
screen_size: (i32, i32),
pixel_ratio: f32,
glsl_version: &crate::GlslVersion,
) -> Result<Self, Error> {
let cell_scale = atlas.cell_scale_for_dpr(pixel_ratio);
let cell_size = atlas.cell_size().scale(cell_scale);
let cols = screen_size.0 / cell_size.width;
let rows = screen_size.1 / cell_size.height;
let space_glyph = atlas.space_glyph_id();
let cell_data = create_terminal_cell_data(cols, rows, space_glyph);
let cell_pos = CellStatic::create_grid(cols, rows);
let grid = Self {
gpu: GpuResources::new(gl, &cell_pos, &cell_data, cell_size, *glsl_version)?,
terminal_size: TerminalSize::new(cols as u16, rows as u16),
canvas_size_px: screen_size,
pixel_ratio,
cells: cell_data,
atlas,
fallback_glyph: space_glyph,
selection: SelectionTracker::new(),
dirty_regions: DirtyRegions::new((cols * rows) as usize),
bg_alpha: 1.0,
};
grid.upload_ubo_data(gl);
Ok(grid)
}
/// Deletes all GPU resources owned by this terminal grid.
///
/// This must be called before dropping the `TerminalGrid` to avoid GPU
/// resource leaks on native OpenGL targets. On WASM, WebGL context teardown
/// handles cleanup automatically, but explicit deletion is still recommended.
pub fn delete(self, gl: &glow::Context) {
self.gpu.delete(gl);
self.atlas.delete(gl);
}
/// Returns the effective cell size for layout (base cell size * cell scale).
fn effective_cell_size(&self) -> CellSize {
let cell_scale = self.atlas.cell_scale_for_dpr(self.pixel_ratio);
self.atlas.cell_size().scale(cell_scale)
}
/// Sets the fallback glyph for missing characters.
pub fn set_fallback_glyph(&mut self, fallback: &str) {
self.fallback_glyph = self
.atlas
.resolve_glyph_slot(fallback, FontStyle::Normal as u16)
.map_or(' ' as u16, |slot| slot.slot_id());
}
/// Replaces the current font atlas with a new one, translating all existing
/// glyph IDs to the new atlas.
///
/// This method handles the transition between atlases by:
/// 1. Looking up the symbol for each existing glyph ID in the old atlas
/// 2. Resolving the corresponding glyph slot in the new atlas
/// 3. Updating double-width glyphs (emoji, wide chars) across both cells
/// 4. Resizing the grid if cell dimensions changed
pub fn replace_atlas(&mut self, gl: &glow::Context, mut atlas: FontAtlas) {
let glyph_mask = atlas::GLYPH_SLOT_MASK as u16;
let style_mask = !glyph_mask;
// compute space glyph before mutable borrows
let space_glyph = atlas.space_glyph_id();
// update fallback glyph to new atlas, before translating existing cells
self.fallback_glyph = self
.atlas
.get_symbol(self.fallback_glyph & glyph_mask)
.and_then(|symbol| {
let style_bits = self.fallback_glyph & style_mask;
atlas.resolve_glyph_slot(symbol.as_str(), style_bits)
})
.map_or(space_glyph, |slot| slot.slot_id());
// translate existing glyph ids to new atlas
let mut skip_next = false;
for idx in 0..self.cells.len() {
if skip_next {
skip_next = false;
continue;
}
let old_glyph_id = self.cells[idx].glyph_id();
let style_bits = old_glyph_id & style_mask;
let slot = self
.atlas
.get_symbol(old_glyph_id & glyph_mask)
.and_then(|symbol| atlas.resolve_glyph_slot(symbol.as_str(), style_bits));
match slot {
Some(GlyphSlot::Normal(id)) => {
self.cells[idx].set_glyph_id(id);
},
Some(GlyphSlot::Wide(id)) | Some(GlyphSlot::Emoji(id)) => {
self.cells[idx].set_glyph_id(id);
// update right-half in next cell if within bounds
if let Some(next_cell) = self.cells.get_mut(idx + 1) {
next_cell.set_glyph_id(id + 1);
skip_next = true;
}
},
None => {
self.cells[idx].set_glyph_id(self.fallback_glyph);
},
}
}
// clear any active selection, just to keep it simple
self.selection.clear();
// replace atlas and resize grid accordingly
let old_atlas = std::mem::replace(&mut self.atlas, atlas);
old_atlas.delete(gl);
self.dirty_regions.mark_all();
// update vertex buffer with new cell dimensions
self.gpu
.buffers
.update_vertex_buffer(gl, self.effective_cell_size());
let _ = self.resize(gl, self.canvas_size_px, self.pixel_ratio);
}
/// Returns the [`FontAtlas`] used by this terminal grid.
#[must_use]
pub fn atlas(&self) -> &FontAtlas {
&self.atlas
}
/// Returns a mutable reference to the font atlas.
pub fn atlas_mut(&mut self) -> &mut FontAtlas {
&mut self.atlas
}
/// Sets the background opacity for terminal cells.
///
/// When less than 1.0, cell backgrounds become semi-transparent, allowing
/// content rendered behind the terminal grid to show through. Text remains
/// fully opaque regardless of this setting.
///
/// The change takes effect on the next call to [`resize`](Self::resize) or
/// when the UBO data is next uploaded.
pub fn set_bg_alpha(&mut self, gl: &glow::Context, alpha: f32) {
self.bg_alpha = alpha.clamp(0.0, 1.0);
self.upload_ubo_data(gl);
}
/// Returns the canvas size in pixels.
#[must_use]
pub fn canvas_size(&self) -> (i32, i32) {
self.canvas_size_px
}
/// Returns the effective cell dimensions in pixels (base size * cell scale).
#[must_use]
pub fn cell_size(&self) -> CellSize {
self.effective_cell_size()
}
/// Returns the cell dimensions in CSS pixels (effective size / device pixel ratio).
///
/// Use this for converting browser mouse coordinates (which are in CSS pixels)
/// to terminal grid coordinates.
#[must_use]
pub fn css_cell_size(&self) -> (f32, f32) {
let cs = self.effective_cell_size();
if self.pixel_ratio <= 0.0 {
return (cs.width as f32, cs.height as f32);
}
(
cs.width as f32 / self.pixel_ratio,
cs.height as f32 / self.pixel_ratio,
)
}
/// Returns the size of the terminal grid in cells.
#[must_use]
pub fn terminal_size(&self) -> TerminalSize {
self.terminal_size
}
/// Renders the terminal grid in a single call.
///
/// This is a convenience method that constructs a [`RenderContext`] and
/// executes the full [`Drawable`] lifecycle (`prepare` → `draw` → `cleanup`).
/// For advanced use cases such as compositing with other GL content, use the
/// [`Drawable`] trait methods directly.
///
/// # Errors
/// Returns an error if shader uniform lookup fails during `prepare`.
pub fn render(&self, gl: &glow::Context, state: &mut GlState) -> Result<(), crate::Error> {
let mut ctx = RenderContext { gl, state };
self.prepare(&mut ctx)?;
self.draw(&mut ctx);
self.cleanup(&mut ctx);
Ok(())
}
/// Returns a mutable reference to the cell data at the specified cell coordinates.
pub fn cell_data_mut(&mut self, x: u16, y: u16) -> Option<&mut CellDynamic> {
let cols = self.terminal_size.cols;
let idx = y as usize * cols as usize + x as usize;
self.dirty_regions.mark(idx);
self.cells.get_mut(idx)
}
/// Returns the active selection state of the terminal grid.
#[must_use]
pub fn selection_tracker(&self) -> SelectionTracker {
self.selection.clone()
}
/// Returns the symbols in the specified block range as a `CompactString`.
pub(super) fn get_symbols(&self, selection: CellIterator) -> CompactString {
let mut text = CompactString::new("");
for (idx, require_newline_after) in selection {
let cell_symbol = self.get_cell_symbol(idx);
if cell_symbol.is_some() {
text.push_str(&cell_symbol.unwrap_or_default());
}
if require_newline_after {
text.push('\n'); // add newline after each row
}
}
text
}
/// Returns the ASCII character at the given position, if it's an ASCII char.
///
/// Returns `None` for non-ASCII characters or out-of-bounds positions.
/// This is an optimized path for URL detection that avoids string allocation.
pub(crate) fn get_ascii_char_at(&self, cursor: CursorPosition) -> Option<char> {
let idx = cursor.row as usize * self.terminal_size.cols as usize + cursor.col as usize;
if idx < self.cells.len() {
let glyph_id = self.cells[idx].glyph_id();
self.atlas.get_ascii_char(glyph_id)
} else {
None
}
}
/// Internal method — not covered by semver guarantees.
#[doc(hidden)]
#[must_use]
pub fn hash_cells(&self, selection: CellQuery) -> u64 {
use std::hash::{Hash, Hasher};
use rustc_hash::FxHasher;
let mut hasher = FxHasher::default();
for (idx, _) in self.cell_iter(selection) {
self.cells[idx].hash(&mut hasher);
}
hasher.finish()
}
fn get_cell_symbol(&self, idx: usize) -> Option<CompactString> {
if idx < self.cells.len() {
let glyph_id = self.cells[idx].glyph_id();
let cell_symbol = self.atlas.get_symbol(glyph_id);
if cell_symbol.is_some() {
return cell_symbol;
}
}
self.fallback_symbol()
}
/// Uploads uniform buffer data for screen and cell dimensions.
fn upload_ubo_data(&self, gl: &glow::Context) {
let vertex_ubo = CellVertexUbo::new(self.canvas_size_px, self.effective_cell_size());
self.gpu.ubo_vertex.upload_data(gl, &vertex_ubo);
let fragment_ubo = CellFragmentUbo::new(&self.atlas, self.bg_alpha);
self.gpu
.ubo_fragment
.upload_data(gl, &fragment_ubo);
}
/// Returns the total number of cells in the terminal grid.
#[must_use]
pub fn cell_count(&self) -> usize {
self.cells.len()
}
/// Updates the content of terminal cells with new data.
///
/// # Errors
/// This method is infallible in the current implementation but returns
/// `Result` for API consistency with other update methods.
pub fn update_cells<'a>(
&mut self,
cells: impl Iterator<Item = CellData<'a>>,
) -> Result<(), Error> {
let fallback_glyph = GlyphSlot::Normal(self.fallback_glyph);
// split borrows: atlas needs &mut, cells needs &mut, dirty_regions needs &mut
let atlas = &mut self.atlas;
let cell_buf = &mut self.cells;
// handle double-width emoji that span two cells
let mut pending_cell: Option<CellDynamic> = None;
cell_buf
.iter_mut()
.zip(cells)
.for_each(|(cell, data)| {
let glyph = atlas
.resolve_glyph_slot(data.symbol, data.style_bits)
.unwrap_or(fallback_glyph);
*cell = if let Some(second_cell) = pending_cell.take() {
second_cell
} else {
match glyph {
GlyphSlot::Normal(id) => CellDynamic::new(id, data.fg, data.bg),
GlyphSlot::Wide(id) | GlyphSlot::Emoji(id) => {
// storing a double-width glyph, reserve next cell with right-half id
pending_cell = Some(CellDynamic::new(id + 1, data.fg, data.bg));
CellDynamic::new(id, data.fg, data.bg)
},
}
}
});
self.dirty_regions.mark_all();
Ok(())
}
/// Updates cells at specific grid coordinates.
///
/// # Errors
/// This method is infallible in the current implementation but returns
/// `Result` for API consistency with other update methods.
pub fn update_cells_by_position<'a>(
&mut self,
cells: impl Iterator<Item = (u16, u16, CellData<'a>)>,
) -> Result<(), Error> {
let cols = self.terminal_size.cols as usize;
let cells_by_index = cells.map(|(x, y, data)| (y as usize * cols + x as usize, data));
self.update_cells_by_index(cells_by_index)
}
/// Updates cells at specific flat indices.
///
/// # Errors
/// This method is infallible in the current implementation but returns
/// `Result` for API consistency with other update methods.
pub fn update_cells_by_index<'a>(
&mut self,
cells: impl Iterator<Item = (usize, CellData<'a>)>,
) -> Result<(), Error> {
let fallback_glyph = GlyphSlot::Normal(self.fallback_glyph);
let atlas = &mut self.atlas;
let cell_buf = &mut self.cells;
let dirty_regions = &mut self.dirty_regions;
let cell_count = cell_buf.len();
// ratatui and beamterm can disagree on which emoji
// are double-width (beamterm assumes double-width for all emoji),
// so for ratatui and similar clients we need to skip the next cell
// if we just wrote a double-width emoji in the current cell.
let mut skip_idx = None;
cells
.filter(|(idx, _)| *idx < cell_count)
.for_each(|(idx, cell)| {
if skip_idx.take() == Some(idx) {
// skip this cell, already handled as part of previous double-width emoji
return;
}
let glyph = atlas
.resolve_glyph_slot(cell.symbol, cell.style_bits)
.unwrap_or(fallback_glyph);
match glyph {
GlyphSlot::Normal(id) => {
cell_buf[idx] = CellDynamic::new(id, cell.fg, cell.bg);
dirty_regions.mark(idx);
},
GlyphSlot::Wide(id) | GlyphSlot::Emoji(id) => {
// render left half in current cell
cell_buf[idx] = CellDynamic::new(id, cell.fg, cell.bg);
dirty_regions.mark(idx);
// render right half in next cell, if within bounds
if let Some(c) = cell_buf.get_mut(idx + 1) {
*c = CellDynamic::new(id + 1, cell.fg, cell.bg);
dirty_regions.mark(idx + 1);
skip_idx = Some(idx + 1);
}
},
}
});
Ok(())
}
/// Updates a single cell at the given grid coordinates.
///
/// # Errors
/// This method is infallible in the current implementation but returns
/// `Result` for API consistency with batch update methods.
pub fn update_cell(&mut self, x: u16, y: u16, cell_data: CellData) -> Result<(), Error> {
let cols = self.terminal_size.cols;
let idx = y as usize * cols as usize + x as usize;
self.update_cell_by_index(idx, cell_data)
}
/// Updates a single cell at the given flat index.
///
/// # Errors
/// This method is infallible in the current implementation but returns
/// `Result` for API consistency with batch update methods.
pub fn update_cell_by_index(&mut self, idx: usize, cell_data: CellData) -> Result<(), Error> {
self.update_cells_by_index(std::iter::once((idx, cell_data)))
}
/// Flushes pending cell updates to the GPU.
///
/// This also flushes any pending glyph data in the atlas texture
/// (e.g., newly rasterized glyphs in a dynamic atlas).
///
/// # Errors
/// Returns an error if the atlas texture flush fails (e.g., glyph
/// rasterization or texture upload failure in a dynamic atlas).
pub fn flush_cells(&mut self, gl: &glow::Context) -> Result<(), Error> {
// flush any pending atlas glyph uploads before uploading cell data
self.atlas.bind(gl);
self.atlas.flush(gl)?;
if self.dirty_regions.is_clean() {
return Ok(()); // no pending updates to flush
}
// if there is an active selected region with a content hash,
// check if the underlying content has changed; if so, clear the selection
self.clear_stale_selection();
// If there's an active selection, flip the colors of the selected cells.
// This ensures that the selected cells are rendered with inverted colors
// during the GPU upload process.
self.flip_selected_cell_colors();
self.gpu.buffers.bind_instance_buffer(gl);
if self.dirty_regions.is_all_active_dirty() {
// all active chunks dirty — single full upload via buffer orphaning
self.gpu
.buffers
.upload_instance_data(gl, &self.cells);
self.dirty_regions.clear();
} else {
// merge adjacent dirty chunks into contiguous uploads
for (start, end) in self.dirty_regions.drain() {
self.gpu.buffers.upload_instance_data_range(
gl,
&self.cells[start..end],
start * CellDynamic::SIZE,
);
}
}
self.gpu.buffers.unbind_instance_buffer(gl);
// Restore the original colors of the selected cells after the upload.
// This ensures that the internal state of the cells remains consistent.
self.flip_selected_cell_colors();
Ok(())
}
fn flip_selected_cell_colors(&mut self) {
if let Some(iter) = self.selected_cells_iter() {
iter.for_each(|(idx, _)| {
self.cells[idx].flip_colors();
self.dirty_regions.mark(idx);
});
}
}
fn selected_cells_iter(&self) -> Option<CellIterator> {
self.selection
.get_query()
.map(|query| self.cell_iter(query))
}
/// Resizes the terminal grid to fit the new canvas dimensions.
///
/// # Errors
/// Returns an error if GPU buffer recreation or atlas pixel ratio
/// update fails.
pub fn resize(
&mut self,
gl: &glow::Context,
canvas_size: (i32, i32),
pixel_ratio: f32,
) -> Result<(), Error> {
self.canvas_size_px = canvas_size;
self.pixel_ratio = pixel_ratio;
let cell_size = self.effective_cell_size();
// Update vertex buffer with new cell dimensions
self.gpu
.buffers
.update_vertex_buffer(gl, cell_size);
// Update the UBO with new screen size
self.upload_ubo_data(gl);
let cols = (canvas_size.0 / cell_size.width).max(1);
let rows = (canvas_size.1 / cell_size.height).max(1);
if self.terminal_size == TerminalSize::new(cols as u16, rows as u16) {
return Ok(()); // no change in terminal size
}
// update buffers; bind VAO to ensure correct state
unsafe {
gl.bind_vertex_array(Some(self.gpu.buffers.vao));
// delete old cell instance buffers
gl.delete_buffer(self.gpu.buffers.instance_cell);
gl.delete_buffer(self.gpu.buffers.instance_pos);
}
// resize cell data vector
let current_size = (
self.terminal_size.cols as i32,
self.terminal_size.rows as i32,
);
let cell_data = self.resize_cell_grid(current_size, (cols, rows));
self.cells = cell_data;
let cell_pos = CellStatic::create_grid(cols, rows);
// re-create buffers with new data
self.gpu.buffers.instance_cell = create_dynamic_instance_buffer(gl, &self.cells)?;
self.gpu.buffers.instance_pos = create_static_instance_buffer(gl, &cell_pos)?;
// unbind VAO
unsafe { gl.bind_vertex_array(None) };
self.terminal_size = TerminalSize::new(cols as u16, rows as u16);
self.dirty_regions = DirtyRegions::new(self.cells.len());
Ok(())
}
/// Recreates all GPU resources after a context loss.
///
/// Note: After a context loss, old GL resources are already invalid,
/// so we skip explicit deletion and just create fresh resources.
///
/// # Errors
/// Returns an error if shader compilation, buffer creation, or other
/// GPU resource allocation fails.
pub fn recreate_resources(
&mut self,
gl: &glow::Context,
glsl_version: &crate::GlslVersion,
) -> Result<(), Error> {
let cell_size = self.effective_cell_size();
let (cols, rows) = (
self.terminal_size.cols as i32,
self.terminal_size.rows as i32,
);
let cell_pos = CellStatic::create_grid(cols, rows);
// Recreate all GPU resources (old ones are invalid after context loss)
self.gpu = GpuResources::new(gl, &cell_pos, &self.cells, cell_size, *glsl_version)?;
// Upload UBO data
self.upload_ubo_data(gl);
// Mark cells as needing flush to upload to new buffers
self.dirty_regions.mark_all();
Ok(())
}
/// Recreates the font atlas texture after a context loss.
///
/// # Errors
/// Returns an error if GPU texture creation fails.
pub fn recreate_atlas_texture(&mut self, gl: &glow::Context) -> Result<(), Error> {
self.atlas.recreate_texture(gl)
}
/// Returns the base glyph identifier for a given symbol.
pub fn base_glyph_id(&mut self, symbol: &str) -> Option<u16> {
self.atlas.get_base_glyph_id(symbol)
}
fn fallback_symbol(&self) -> Option<CompactString> {
self.atlas.get_symbol(self.fallback_glyph)
}
fn clear_stale_selection(&self) {
if let Some(query) = self.selection_tracker().get_query()
&& let Some(hash) = query.content_hash
&& hash != self.hash_cells(query)
{
self.selection.clear();
}
}
fn resize_cell_grid(&mut self, old_size: (i32, i32), new_size: (i32, i32)) -> Vec<CellDynamic> {
let empty_cell = CellDynamic::new(self.atlas.space_glyph_id(), 0xFFFFFF, 0x000000);
let new_len = new_size.0 * new_size.1;
let mut new_cells = Vec::with_capacity(new_len as usize);
for _ in 0..new_len {
new_cells.push(empty_cell);
}
let cells = &self.cells;
for y in 0..min(old_size.1, new_size.1) {
for x in 0..min(old_size.0, new_size.0) {
let new_idx = (y * new_size.0 + x) as usize;
let old_idx = (y * old_size.0 + x) as usize;
new_cells[new_idx] = cells[old_idx];
}
}
new_cells
}
}
fn setup_buffers(
gl: &glow::Context,
vao: glow::VertexArray,
cell_pos: &[CellStatic],
cell_data: &[CellDynamic],
cell_size: CellSize,
) -> Result<TerminalBuffers, Error> {
let (w, h) = (cell_size.width as f32, cell_size.height as f32);
#[rustfmt::skip]
let vertices = [
//x y u v
w, 0.0, 1.0, 0.0, // top-right
0.0, h, 0.0, 1.0, // bottom-left
w, h, 1.0, 1.0, // bottom-right
0.0, 0.0, 0.0, 0.0 // top-left
];
let indices = [0, 1, 2, 0, 3, 1];
Ok(TerminalBuffers {
vao,
vertices: create_buffer_f32(gl, glow::ARRAY_BUFFER, &vertices, glow::STATIC_DRAW)?,
instance_pos: create_static_instance_buffer(gl, cell_pos)?,
instance_cell: create_dynamic_instance_buffer(gl, cell_data)?,
indices: create_buffer_u8(gl, glow::ELEMENT_ARRAY_BUFFER, &indices, glow::STATIC_DRAW)?,
})
}
fn create_buffer_u8(
gl: &glow::Context,
target: u32,
data: &[u8],
usage: u32,
) -> Result<glow::Buffer, Error> {
let buffer =
unsafe { gl.create_buffer() }.map_err(|e| Error::buffer_creation_failed("vbo-u8", e))?;
unsafe {
gl.bind_buffer(target, Some(buffer));
gl.buffer_data_u8_slice(target, data, usage);
}
Ok(buffer)
}
fn create_buffer_f32(
gl: &glow::Context,
target: u32,
data: &[f32],
usage: u32,
) -> Result<glow::Buffer, Error> {
let buffer =
unsafe { gl.create_buffer() }.map_err(|e| Error::buffer_creation_failed("vbo-f32", e))?;
unsafe {
gl.bind_buffer(target, Some(buffer));
let bytes =
std::slice::from_raw_parts(data.as_ptr() as *const u8, std::mem::size_of_val(data));
gl.buffer_data_u8_slice(target, bytes, usage);
}
// vertex attributes
const STRIDE: i32 = (2 + 2) * 4; // 4 floats per vertex
enable_vertex_attrib(gl, attrib::POS, 2, glow::FLOAT, 0, STRIDE);
enable_vertex_attrib(gl, attrib::UV, 2, glow::FLOAT, 8, STRIDE);
Ok(buffer)
}
fn create_static_instance_buffer(
gl: &glow::Context,
instance_data: &[CellStatic],
) -> Result<glow::Buffer, Error> {
let buffer = unsafe { gl.create_buffer() }
.map_err(|e| Error::buffer_creation_failed("static-instance-buffer", e))?;
unsafe {
gl.bind_buffer(glow::ARRAY_BUFFER, Some(buffer));
buffer_upload_array(gl, glow::ARRAY_BUFFER, instance_data, glow::STATIC_DRAW);
}
let stride = size_of::<CellStatic>() as i32;
enable_vertex_attrib_array(gl, attrib::GRID_XY, 2, glow::UNSIGNED_SHORT, 0, stride);
Ok(buffer)
}
fn create_dynamic_instance_buffer(
gl: &glow::Context,
instance_data: &[CellDynamic],
) -> Result<glow::Buffer, Error> {
let buffer = unsafe { gl.create_buffer() }
.map_err(|e| Error::buffer_creation_failed("dynamic-instance-buffer", e))?;
unsafe {
gl.bind_buffer(glow::ARRAY_BUFFER, Some(buffer));
buffer_upload_array(gl, glow::ARRAY_BUFFER, instance_data, glow::DYNAMIC_DRAW);
}
let stride = size_of::<CellDynamic>() as i32;
// setup instance attributes (while VAO is bound)
enable_vertex_attrib_array(
gl,
attrib::PACKED_DEPTH_FG_BG,
2,
glow::UNSIGNED_INT,
0,
stride,
);
Ok(buffer)
}
fn enable_vertex_attrib_array(
gl: &glow::Context,
index: u32,
size: i32,
type_: u32,
offset: i32,
stride: i32,
) {
enable_vertex_attrib(gl, index, size, type_, offset, stride);
unsafe { gl.vertex_attrib_divisor(index, 1) };
}
fn enable_vertex_attrib(
gl: &glow::Context,
index: u32,
size: i32,
type_: u32,
offset: i32,
stride: i32,
) {
unsafe {
gl.enable_vertex_attrib_array(index);
if type_ == glow::FLOAT {
gl.vertex_attrib_pointer_f32(index, size, type_, false, stride, offset);
} else {
gl.vertex_attrib_pointer_i32(index, size, type_, stride, offset);
}
}
}
impl Drawable for TerminalGrid {
fn prepare(&self, context: &mut RenderContext) -> Result<(), crate::Error> {
let gl = context.gl;
self.gpu.shader.use_program(gl);
unsafe { gl.bind_vertex_array(Some(self.gpu.buffers.vao)) };
context.state.active_texture(gl, glow::TEXTURE0);
self.atlas.bind(gl);
self.gpu.ubo_vertex.bind(context.gl);
self.gpu.ubo_fragment.bind(context.gl);
unsafe { gl.uniform_1_i32(Some(&self.gpu.sampler_loc), 0) };
Ok(())
}
fn draw(&self, context: &mut RenderContext) {
let gl = context.gl;
let cell_count = self.cells.len() as i32;
unsafe {
gl.draw_elements_instanced(glow::TRIANGLES, 6, glow::UNSIGNED_BYTE, 0, cell_count);
}
}
fn cleanup(&self, context: &mut RenderContext) {
let gl = context.gl;
unsafe {
gl.bind_vertex_array(None);
gl.bind_texture(glow::TEXTURE_2D_ARRAY, None);
gl.use_program(None);
}
self.gpu.ubo_vertex.unbind(gl);
self.gpu.ubo_fragment.unbind(gl);
}
}
/// Data for a single terminal cell including character and colors.
///
/// `CellData` represents the visual content of one terminal cell, including
/// the character to display and its foreground and background colors.
/// Colors are specified as RGB values packed into 32-bit integers.
///
/// # Color Format
/// Colors use the format 0xRRGGBB where:
/// - RR: Red component
/// - GG: Green component
/// - BB: Blue component
#[derive(Debug, Copy, Clone)]
pub struct CellData<'a> {
symbol: &'a str,
style_bits: u16,
fg: u32,
bg: u32,
}
impl<'a> CellData<'a> {
/// Creates new cell data with the specified character and colors.
#[must_use]
pub fn new(symbol: &'a str, style: FontStyle, effect: GlyphEffect, fg: u32, bg: u32) -> Self {
let style_bits = style.style_mask() | effect as u16;
// emoji and glyph base mask should not intersect with style bits
debug_assert!(
0x81FF & style_bits == 0,
"Invalid style bits: {style_bits:#04x}"
);
Self::new_with_style_bits(symbol, style_bits, fg, bg)
}
/// Creates new cell data with pre-encoded style bits.
#[must_use]
pub const fn new_with_style_bits(symbol: &'a str, style_bits: u16, fg: u32, bg: u32) -> Self {
Self { symbol, style_bits, fg, bg }
}
}
/// Static instance data for terminal cell positioning.
#[derive(Clone, Copy)]
#[repr(C, align(4))]
struct CellStatic {
/// Grid position as (x, y) coordinates in cell units.
pub grid_xy: [u16; 2],
}
/// Dynamic instance data for terminal cell appearance.
///
/// `CellDynamic` contains the frequently-changing visual data for each terminal
/// cell, including the character glyph and colors.
///
/// # Memory Layout
/// The 8-byte data array is packed as follows:
/// - Bytes 0-1: Glyph depth/layer index (u16, little-endian)
/// - Bytes 2-4: Foreground color RGB (3 bytes)
/// - Bytes 5-7: Background color RGB (3 bytes)
#[derive(Debug, Clone, Copy, Hash)]
#[repr(C, align(4))]
pub struct CellDynamic {
/// Packed cell data:
///
/// # Byte Layout
/// - `data[0]`: Lower 8 bits of glyph depth/layer index
/// - `data[1]`: Upper 8 bits of glyph depth/layer index
/// - `data[2]`: Foreground red component (0-255)
/// - `data[3]`: Foreground green component (0-255)
/// - `data[4]`: Foreground blue component (0-255)
/// - `data[5]`: Background red component (0-255)
/// - `data[6]`: Background green component (0-255)
/// - `data[7]`: Background blue component (0-255)
data: [u8; 8], // 2b layer, fg:rgb, bg:rgb
}
impl CellStatic {
fn create_grid(cols: i32, rows: i32) -> Vec<Self> {
debug_assert!(cols > 0 && cols < u16::MAX as i32, "cols: {cols}");
debug_assert!(rows > 0 && rows < u16::MAX as i32, "rows: {rows}");
(0..rows)
.flat_map(|row| (0..cols).map(move |col| (col, row)))
.map(|(col, row)| Self { grid_xy: [col as u16, row as u16] })
.collect()
}
}
impl CellDynamic {
const SIZE: usize = size_of::<Self>();
const GLYPH_STYLE_MASK: u16 =
Glyph::BOLD_FLAG | Glyph::ITALIC_FLAG | Glyph::UNDERLINE_FLAG | Glyph::STRIKETHROUGH_FLAG;
/// Creates a new packed cell from a glyph ID and foreground/background colors.
#[inline]
#[must_use]
pub fn new(glyph_id: u16, fg: u32, bg: u32) -> Self {
let mut data = [0; 8];
// pack glyph ID into the first two bytes
let glyph_id = glyph_id.to_le_bytes();
data[0] = glyph_id[0];
data[1] = glyph_id[1];
let fg = fg.to_le_bytes();
data[2] = fg[2]; // R
data[3] = fg[1]; // G
data[4] = fg[0]; // B
let bg = bg.to_le_bytes();
data[5] = bg[2]; // R
data[6] = bg[1]; // G
data[7] = bg[0]; // B
Self { data }
}
/// Overwrites the current cell style bits with the provided style bits.
pub fn style(&mut self, style_bits: u16) {
let glyph_id = (self.glyph_id() & !Self::GLYPH_STYLE_MASK) | style_bits;
self.data[..2].copy_from_slice(&glyph_id.to_le_bytes());
}
/// Swaps foreground and background colors.
pub fn flip_colors(&mut self) {
// swap foreground and background colors
let fg = [self.data[2], self.data[3], self.data[4]];
self.data[2] = self.data[5]; // R
self.data[3] = self.data[6]; // G
self.data[4] = self.data[7]; // B
self.data[5] = fg[0]; // R
self.data[6] = fg[1]; // G
self.data[7] = fg[2]; // B
}
/// Sets the foreground color of the cell.
pub fn fg_color(&mut self, fg: u32) {
let fg = fg.to_le_bytes();
self.data[2] = fg[2]; // R
self.data[3] = fg[1]; // G
self.data[4] = fg[0]; // B
}
/// Sets the background color of the cell.
pub fn bg_color(&mut self, bg: u32) {
let bg = bg.to_le_bytes();
self.data[5] = bg[2]; // R
self.data[6] = bg[1]; // G
self.data[7] = bg[0]; // B
}
/// Returns foreground color as a packed RGB value.
#[must_use]
pub fn get_fg_color(&self) -> u32 {
// unpack foreground color from data
((self.data[2] as u32) << 16) | ((self.data[3] as u32) << 8) | (self.data[4] as u32)
}
/// Returns background color as a packed RGB value.
#[must_use]
pub fn get_bg_color(&self) -> u32 {
// unpack background color from data
((self.data[5] as u32) << 16) | ((self.data[6] as u32) << 8) | (self.data[7] as u32)
}
/// Returns the style bits for this cell, excluding id and emoji bits.
#[must_use]
pub fn get_style(&self) -> u16 {
self.glyph_id() & Self::GLYPH_STYLE_MASK
}
#[inline]
fn glyph_id(self) -> u16 {
u16::from_le_bytes([self.data[0], self.data[1]])
}
fn set_glyph_id(&mut self, glyph_id: u16) {
let bytes = glyph_id.to_le_bytes();
self.data[0] = bytes[0];
self.data[1] = bytes[1];
}
}
#[derive(Clone, Copy)]
#[repr(C, align(16))] // std140 layout requires proper alignment
struct CellVertexUbo {
pub projection: [f32; 16], // mat4
pub cell_size: [f32; 2], // vec2 - screen cell size
pub _padding: [f32; 2],
}
#[derive(Clone, Copy)]
#[repr(C, align(16))] // std140 layout requires proper alignment
struct CellFragmentUbo {
pub padding_frac: [f32; 2], // padding as a fraction of cell size
pub underline_pos: f32, // underline position (0.0 = top, 1.0 = bottom)
pub underline_thickness: f32, // underline thickness as fraction of cell height
pub strikethrough_pos: f32, // strikethrough position (0.0 = top, 1.0 = bottom)
pub strikethrough_thickness: f32, // strikethrough thickness as fraction of cell height
pub emoji_bit: u32, // static atlas: 12, dynamic atlas: 15
pub bg_alpha: f32, // background cell opacity (0.0 = transparent, 1.0 = opaque)
}
impl CellVertexUbo {
pub const BINDING_POINT: u32 = 0;
fn new(canvas_size: (i32, i32), cell_size: CellSize) -> Self {
let projection =
Mat4::orthographic_from_size(canvas_size.0 as f32, canvas_size.1 as f32).data;
Self {
projection,
cell_size: [cell_size.width as f32, cell_size.height as f32],
_padding: [0.0; 2], // padding to ensure proper alignment
}
}
}
impl CellFragmentUbo {
pub const BINDING_POINT: u32 = 1;
fn new(atlas: &FontAtlas, bg_alpha: f32) -> Self {
// Use texture cell size for padding calculation (physical pixels in texture)
let tcs = atlas.texture_cell_size();
let underline = atlas.underline();
let strikethrough = atlas.strikethrough();
Self {
padding_frac: [
FontAtlasData::PADDING as f32 / tcs.width as f32,
FontAtlasData::PADDING as f32 / tcs.height as f32,
],
underline_pos: underline.position(),
underline_thickness: underline.thickness(),
strikethrough_pos: strikethrough.position(),
strikethrough_thickness: strikethrough.thickness(),
emoji_bit: atlas.emoji_bit(),
bg_alpha,
}
}
}
fn create_terminal_cell_data(cols: i32, rows: i32, fill_glyph: u16) -> Vec<CellDynamic> {
(0..cols * rows)
.map(|_i| CellDynamic::new(fill_glyph, 0x00ff_ffff, 0x0000_0000))
.collect()
}
mod attrib {
pub const POS: u32 = 0;
pub const UV: u32 = 1;
pub const GRID_XY: u32 = 2;
pub const PACKED_DEPTH_FG_BG: u32 = 3;
}