ratty 0.4.1

A GPU-rendered terminal emulator that supports inline 3D graphics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
//! Runtime Bevy systems for terminal presentation.
//!
//! These systems are scheduled from [`crate::plugin::TerminalPlugin`] in a mostly linear flow:
//!
//! - [`pump_pty_output`]
//! - [`crate::keyboard::handle_keyboard_input`]
//! - [`crate::mouse::handle_mouse_input`]
//! - [`handle_window_resize`]
//! - [`crate::scene::apply_terminal_presentation`]
//! - [`apply_inline_objects`]
//! - [`redraw_soft_terminal`]
//! - [`sync_inline_objects`]
//! - [`sync_rgp_objects`]
//! - [`apply_instance_brightness`]
//! - [`animate_terminal_plane_warp`]
//! - [`sync_asset_to_terminal_cursor`]
//!
//! The redraw path updates the terminal texture and presentation state first, then the inline
//! object systems rebuild or reposition scene entities that depend on the terminal grid.

use std::collections::HashMap;
use std::sync::mpsc::TryRecvError;

use crate::config::{AppConfig, CURSOR_DEPTH};
use crate::inline::{
    InlineObject, TerminalInlineObjectPlane, TerminalInlineObjectSprite, TerminalInlineObjects,
    TerminalRgpObject,
};
use crate::model::CursorModel;
use crate::model::spawn_cursor_model;
use crate::mouse::TerminalSelection;
use crate::rendering::{sync_plane_texture, sync_terminal_debug_image};
use crate::runtime::TerminalRuntime;
use crate::scene::{
    MobiusTransition, ModelLoadState, TerminalPlane, TerminalPlaneBack, TerminalPlaneMeshes,
    TerminalPlaneView, TerminalPlaneWarp, TerminalPresentation, TerminalPresentationMode,
    TerminalSprite, TerminalViewport,
};
use crate::terminal::{TerminalRedrawState, TerminalSurface, TerminalWidget};
use bevy::app::AppExit;
use bevy::ecs::message::{MessageReader, MessageWriter};
use bevy::ecs::system::SystemParam;
use bevy::gltf::GltfAssetLabel;
use bevy::image::ImageSampler;
use bevy::mesh::{Indices, VertexAttributeValues};
use bevy::prelude::*;
use bevy::render::render_resource::PrimitiveTopology;
use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
use bevy::window::{PrimaryWindow, WindowResized};

struct InlineLayout {
    columns: u32,
    rows: u32,
    center_x: f32,
    center_y: f32,
    local_x: f32,
    local_y: f32,
    local_width: f32,
    local_height: f32,
    pixel_width: f32,
    pixel_height: f32,
}

struct KittyRenderContext<'a> {
    mode: TerminalPresentationMode,
    warp_amount: f32,
    elapsed_secs: f32,
    materials: &'a mut Assets<StandardMaterial>,
    images: &'a mut Assets<Image>,
    meshes: &'a mut Assets<Mesh>,
    plane_children: &'a mut Vec<Entity>,
}

struct CursorPoseContext<'a, 'w, 's> {
    runtime: &'a TerminalRuntime,
    terminal: &'a TerminalSurface,
    viewport: &'a TerminalViewport,
    mode: TerminalPresentationMode,
    plane_warp_amount: f32,
    mobius_progress: f32,
    elapsed_secs: f32,
    plane_query: &'a Query<'w, 's, &'static Transform, (With<TerminalPlane>, Without<CursorModel>)>,
}

/// Marker for objects that already had instance brightness applied.
#[derive(Component)]
pub struct BrightnessAdjusted;

type PlaneTransformQuery<'w, 's> =
    Query<'w, 's, &'static Transform, (With<TerminalPlane>, Without<TerminalRgpObject>)>;
type CursorTransformQuery<'w, 's> = Query<
    'w,
    's,
    (&'static mut Transform, &'static mut Visibility),
    (With<CursorModel>, Without<TerminalPlane>),
>;
type PlaneBackResizeQuery<'w, 's> = Query<
    'w,
    's,
    &'static mut Transform,
    (
        With<TerminalPlaneBack>,
        Without<TerminalPlane>,
        Without<TerminalSprite>,
    ),
>;

/// Pumps PTY output into the terminal parser.
///
/// This runs early in the update schedule, before [`redraw_soft_terminal`]. It drains PTY output
/// from [`TerminalRuntime`], feeds it through [`TerminalInlineObjects::consume_pty_output`] and
/// requests a redraw through [`TerminalRedrawState`] when terminal state changed.
///
/// It also updates scroll-coupled inline anchors before the redraw and sync passes rebuild the
/// scene.
pub fn pump_pty_output(
    mut runtime: NonSendMut<TerminalRuntime>,
    mut inline_objects: ResMut<TerminalInlineObjects>,
    mut app_exit: MessageWriter<AppExit>,
    mut redraw: ResMut<TerminalRedrawState>,
) {
    let screen_rows = |screen: &vt100::Screen| {
        let (_, cols) = screen.size();
        screen.rows(0, cols).collect::<Vec<_>>()
    };

    let mut processed_output = false;
    loop {
        match runtime.rx.try_recv() {
            Ok(chunk) => {
                let track_scroll = inline_objects.has_scroll_tracked_anchors();
                let prev_rows: Option<Vec<String>> = if track_scroll {
                    let (_, cols) = runtime.parser.screen().size();
                    Some(runtime.parser.screen().rows(0, cols).collect::<Vec<_>>())
                } else {
                    None
                };
                let mut replies = inline_objects.consume_pty_output(&chunk, &mut runtime.parser);
                replies.extend(runtime.parser.callbacks_mut().take_replies());
                for reply in replies {
                    runtime.write_input(&reply);
                }
                if let Some(prev_rows) = prev_rows {
                    let next_rows = screen_rows(runtime.parser.screen());
                    let scrolled = infer_upward_scroll(&prev_rows, &next_rows);
                    inline_objects.apply_scroll(scrolled);
                }
                inline_objects.refresh_placeholder_anchors(runtime.parser.screen());
                processed_output = true;
            }
            Err(TryRecvError::Empty) => break,
            Err(TryRecvError::Disconnected) => {
                if !runtime.pty_disconnected {
                    runtime.pty_disconnected = true;
                    app_exit.write(AppExit::Success);
                }
                break;
            }
        }
    }

    if processed_output {
        redraw.request();
    }
}

fn infer_upward_scroll(prev_rows: &[String], next_rows: &[String]) -> u16 {
    let max_shift = prev_rows.len().min(next_rows.len());
    for shift in (1..max_shift).rev() {
        if prev_rows
            .iter()
            .skip(shift)
            .zip(next_rows.iter())
            .all(|(prev, next)| prev == next)
        {
            return shift as u16;
        }
    }
    0
}

#[derive(SystemParam)]
pub(crate) struct ResizeParams<'w, 's> {
    primary_window: Query<'w, 's, Entity, With<PrimaryWindow>>,
    runtime: NonSendMut<'w, TerminalRuntime>,
    terminal: NonSendMut<'w, TerminalSurface>,
    redraw: ResMut<'w, TerminalRedrawState>,
    viewport: ResMut<'w, TerminalViewport>,
    sprite_query: Query<'w, 's, &'static mut Sprite, With<TerminalSprite>>,
    plane_query:
        Query<'w, 's, &'static mut Transform, (With<TerminalPlane>, Without<TerminalSprite>)>,
    plane_back_query: PlaneBackResizeQuery<'w, 's>,
    images: ResMut<'w, Assets<Image>>,
}

/// Handles primary window resize events.
///
/// This updates both the PTY grid and the rendered scene dimensions. It resizes
/// [`TerminalRuntime`], [`TerminalSurface`], [`TerminalViewport`], the 2D terminal sprite and the
/// front and back terminal plane transforms.
///
/// The updated terminal image is uploaded immediately so later systems in the same frame see the
/// new geometry.
pub(crate) fn handle_window_resize(
    mut resize_events: MessageReader<WindowResized>,
    mut params: ResizeParams,
) {
    let ResizeParams {
        primary_window,
        runtime,
        terminal,
        redraw,
        viewport,
        sprite_query,
        plane_query,
        plane_back_query,
        images,
    } = &mut params;
    let Ok(primary_window) = primary_window.single() else {
        return;
    };

    let mut latest_size = None;
    for event in resize_events.read() {
        if event.window == primary_window {
            latest_size = Some(Vec2::new(event.width, event.height));
        }
    }

    let Some(window_size) = latest_size else {
        return;
    };

    let viewport_size = Vec2::new(window_size.x.max(1.0), window_size.y.max(1.0));
    viewport.size = viewport_size;
    viewport.center = Vec2::ZERO;

    let char_dims = terminal.char_dimensions().max(UVec2::ONE);
    let cols = ((viewport_size.x / char_dims.x as f32).floor() as u16).max(1);
    let rows = ((viewport_size.y / char_dims.y as f32).floor() as u16).max(1);

    runtime.resize(cols, rows);
    terminal.resize(cols, rows);
    let _ = terminal.sync_image(images, 0.0);
    redraw.request();

    for mut sprite in sprite_query.iter_mut() {
        sprite.custom_size = Some(viewport_size);
    }

    for mut transform in plane_query.iter_mut() {
        transform.scale = viewport_size.extend(1.0);
    }

    for mut transform in plane_back_query.iter_mut() {
        transform.scale = viewport_size.extend(1.0);
    }
}

/// Applies inline object visibility for the current presentation mode.
///
/// This runs after [`crate::scene::apply_terminal_presentation`] and only flips scene visibility.
/// [`TerminalInlineObjectSprite`] entities are shown in [`TerminalPresentationMode::Flat2d`], while
/// [`TerminalInlineObjectPlane`] entities are shown in the 3D presentation modes.
pub fn apply_inline_objects(
    presentation: Res<TerminalPresentation>,
    mut sprite_query: Query<&mut Visibility, With<TerminalInlineObjectSprite>>,
    mut plane_query: Query<
        &mut Visibility,
        (
            With<TerminalInlineObjectPlane>,
            Without<TerminalInlineObjectSprite>,
        ),
    >,
) {
    let sprite_visibility = match presentation.mode {
        TerminalPresentationMode::Flat2d => Visibility::Visible,
        TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d => {
            Visibility::Hidden
        }
    };
    let plane_visibility = match presentation.mode {
        TerminalPresentationMode::Flat2d => Visibility::Hidden,
        TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d => {
            Visibility::Visible
        }
    };

    for mut visibility in &mut sprite_query {
        *visibility = sprite_visibility;
    }
    for mut visibility in &mut plane_query {
        *visibility = plane_visibility;
    }
}

/// Redraw system parameters.
#[derive(SystemParam)]
pub(crate) struct RedrawParams<'w, 's> {
    app_config: Res<'w, AppConfig>,
    runtime: NonSend<'w, TerminalRuntime>,
    terminal: NonSendMut<'w, TerminalSurface>,
    selection: Res<'w, TerminalSelection>,
    presentation: Res<'w, TerminalPresentation>,
    time: Res<'w, Time>,
    redraw: ResMut<'w, TerminalRedrawState>,
    images: ResMut<'w, Assets<Image>>,
    model_load_state: ResMut<'w, ModelLoadState>,
    commands: Commands<'w, 's>,
    meshes: ResMut<'w, Assets<Mesh>>,
    materials: ResMut<'w, Assets<StandardMaterial>>,
    plane_materials: Query<'w, 's, &'static MeshMaterial3d<StandardMaterial>, With<TerminalPlane>>,
    plane_back_materials:
        Query<'w, 's, &'static MeshMaterial3d<StandardMaterial>, With<TerminalPlaneBack>>,
    asset_server: Res<'w, AssetServer>,
}

/// Redraws the terminal surface.
///
/// This runs after [`pump_pty_output`] and [`crate::mouse::handle_mouse_input`]. It redraws the
/// Ratatui buffer into [`TerminalSurface`], uploads the rendered image, refreshes the debug back
/// texture and synchronizes the front and back plane materials to the latest terminal images.
///
/// On the first successful upload it defers cursor-model spawning to the next frame. After that,
/// it ensures the cursor model exists so [`sync_asset_to_terminal_cursor`] can position it.
pub(crate) fn redraw_soft_terminal(mut params: RedrawParams) {
    let RedrawParams {
        app_config,
        runtime,
        terminal,
        selection,
        presentation,
        time,
        redraw,
        images,
        model_load_state,
        commands,
        meshes,
        materials,
        plane_materials,
        plane_back_materials,
        asset_server,
    } = &mut params;
    let needs_redraw = redraw.take();
    let force_live_redraw = matches!(
        presentation.mode,
        TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
    ) && !app_config.cursor.model.visible;
    if !needs_redraw && !force_live_redraw && model_load_state.loaded {
        return;
    }

    let screen = runtime.parser.screen();
    let _ = terminal.tui.draw(|frame| {
        frame.render_widget(
            TerminalWidget {
                screen,
                selection,
                theme: &app_config.theme,
                font_style: app_config.font.style,
            },
            frame.area(),
        );

        if !app_config.cursor.model.visible && !screen.hide_cursor() {
            let (cursor_row, cursor_col) = screen.cursor_position();
            frame.set_cursor_position((cursor_col, cursor_row));
        }
    });

    let _ = terminal.sync_image(images, time.elapsed_secs());
    if matches!(
        presentation.mode,
        TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
    ) {
        sync_terminal_debug_image(terminal, images, screen);
    }

    sync_plane_texture(terminal.image_handle.as_ref(), plane_materials, materials);
    if matches!(
        presentation.mode,
        TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
    ) {
        sync_plane_texture(
            terminal.back_image_handle.as_ref(),
            plane_back_materials,
            materials,
        );
    }

    if !model_load_state.first_frame_uploaded {
        model_load_state.first_frame_uploaded = true;
        redraw.request();
        return;
    }

    if !model_load_state.loaded {
        if app_config.cursor.model.visible {
            spawn_cursor_model(commands, meshes, materials, asset_server, app_config);
        }
        model_load_state.loaded = true;
    }
}

/// Synchronizes Kitty inline objects.
#[derive(SystemParam)]
pub(crate) struct SyncInlineParams<'w, 's> {
    commands: Commands<'w, 's>,
    inline_objects: ResMut<'w, TerminalInlineObjects>,
    terminal: NonSend<'w, TerminalSurface>,
    viewport: Res<'w, TerminalViewport>,
    presentation: Res<'w, TerminalPresentation>,
    plane_warp: Res<'w, TerminalPlaneWarp>,
    time: Res<'w, Time>,
    plane_query: Query<'w, 's, (Entity, &'static Transform), With<TerminalPlane>>,
    sprite_query: Query<'w, 's, Entity, With<TerminalInlineObjectSprite>>,
    plane_image_query: Query<'w, 's, Entity, With<TerminalInlineObjectPlane>>,
    rgp_query: Query<'w, 's, Entity, With<TerminalRgpObject>>,
    asset_server: Res<'w, AssetServer>,
    materials: ResMut<'w, Assets<StandardMaterial>>,
    images: ResMut<'w, Assets<Image>>,
    meshes: ResMut<'w, Assets<Mesh>>,
}

/// Synchronizes Kitty inline object entities.
///
/// This runs after [`redraw_soft_terminal`]. It rebuilds the scene entities for registered
/// [`InlineObject::KittyImage`] values and clears stale inline entities first so the scene matches
/// the latest terminal anchors exactly.
///
/// In 2D mode it spawns [`TerminalInlineObjectSprite`] entities. In 3D mode it also generates
/// plane-attached meshes under [`TerminalPlane`] so images follow the warped terminal surface.
pub(crate) fn sync_inline_objects(mut params: SyncInlineParams) {
    let SyncInlineParams {
        commands,
        inline_objects,
        terminal,
        viewport,
        presentation,
        plane_warp,
        time,
        plane_query,
        sprite_query,
        plane_image_query,
        rgp_query,
        asset_server,
        materials,
        images,
        meshes,
    } = &mut params;
    let force_warp_sync = matches!(
        presentation.mode,
        TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d
    ) && plane_warp.amount > 0.0
        && !inline_objects.anchors.is_empty();
    if !force_warp_sync && !inline_objects.needs_sync(viewport.size, terminal.cols, terminal.rows) {
        return;
    }

    for entity in sprite_query.iter() {
        commands.entity(entity).despawn();
    }
    for entity in plane_image_query.iter() {
        commands.entity(entity).despawn();
    }
    for entity in rgp_query.iter() {
        commands.entity(entity).despawn();
    }

    let Ok((plane_entity, _plane_transform)) = plane_query.single() else {
        return;
    };

    let cell_width = viewport.size.x / terminal.cols.max(1) as f32;
    let cell_height = viewport.size.y / terminal.rows.max(1) as f32;
    let elapsed_secs = time.elapsed_secs();
    let renderable_ids = inline_objects
        .anchors
        .iter()
        .filter_map(|(object_id, anchor)| {
            inline_objects.objects.get(object_id)?;
            let start = anchor.row as i32;
            let end = start + anchor.rows as i32;
            (start < terminal.rows as i32 && end > 0).then_some(*object_id)
        })
        .collect::<Vec<_>>();

    let mut plane_children = Vec::new();
    for object_id in renderable_ids {
        let Some(anchor) = inline_objects.anchors.get(&object_id) else {
            continue;
        };
        let layout = inline_layout(anchor, terminal, viewport, cell_width, cell_height);
        let style = anchor.style;
        let Some(object) = inline_objects.objects.get_mut(&object_id) else {
            continue;
        };
        match object {
            InlineObject::KittyImage(object) => {
                let mut ctx = KittyRenderContext {
                    mode: presentation.mode,
                    warp_amount: plane_warp.amount,
                    elapsed_secs,
                    materials,
                    images,
                    meshes,
                    plane_children: &mut plane_children,
                };
                sync_kitty_inline_image(commands, object, &layout, &mut ctx);
            }
            InlineObject::RgpObject(object) => {
                spawn_rgp_object(
                    commands,
                    object_id,
                    object,
                    style,
                    materials,
                    meshes,
                    asset_server,
                );
            }
        }
    }

    if !plane_children.is_empty() {
        commands.entity(plane_entity).add_children(&plane_children);
    }

    inline_objects.finish_sync(viewport.size, terminal.cols, terminal.rows);
}

fn inline_layout(
    anchor: &crate::inline::InlineAnchor,
    terminal: &TerminalSurface,
    viewport: &TerminalViewport,
    cell_width: f32,
    cell_height: f32,
) -> InlineLayout {
    let cols = terminal.cols.max(1) as f32;
    let rows = terminal.rows.max(1) as f32;
    let center_x = viewport.center.x - viewport.size.x * 0.5
        + (anchor.col as f32 + anchor.columns as f32 * 0.5) * cell_width;
    let center_y = viewport.center.y + viewport.size.y * 0.5
        - (anchor.row as f32 + anchor.rows as f32 * 0.5) * cell_height;

    InlineLayout {
        columns: anchor.columns,
        rows: anchor.rows,
        center_x,
        center_y,
        local_x: (anchor.col as f32 + anchor.columns as f32 * 0.5) / cols - 0.5,
        local_y: 0.5 - (anchor.row as f32 + anchor.rows as f32 * 0.5) / rows,
        local_width: anchor.columns as f32 / cols,
        local_height: anchor.rows as f32 / rows,
        pixel_width: anchor.columns as f32 * cell_width,
        pixel_height: anchor.rows as f32 * cell_height,
    }
}

fn sync_kitty_inline_image(
    commands: &mut Commands,
    object: &mut crate::inline::KittyInlineObject,
    layout: &InlineLayout,
    ctx: &mut KittyRenderContext<'_>,
) {
    let image_handle = if let Some(handle) = object.raster.handle.as_ref() {
        handle.clone()
    } else {
        let mut image = Image::new_fill(
            Extent3d {
                width: object.raster.width,
                height: object.raster.height,
                depth_or_array_layers: 1,
            },
            TextureDimension::D2,
            &[0, 0, 0, 0],
            TextureFormat::Rgba8UnormSrgb,
            bevy::asset::RenderAssetUsages::default(),
        );
        image.sampler = ImageSampler::nearest();
        image.data = Some(object.raster.rgba.clone());
        let handle = ctx.images.add(image);
        object.raster.handle = Some(handle.clone());
        handle
    };

    let mut sprite = Sprite::from_image(image_handle.clone());
    sprite.custom_size = Some(Vec2::new(layout.pixel_width, layout.pixel_height));
    commands.spawn((
        TerminalInlineObjectSprite,
        sprite,
        Transform::from_translation(Vec3::new(layout.center_x, layout.center_y, 5.0)),
        match ctx.mode {
            TerminalPresentationMode::Flat2d => Visibility::Visible,
            TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d => {
                Visibility::Hidden
            }
        },
    ));

    let x_segments = layout.columns.clamp(2, 24);
    let y_segments = layout.rows.clamp(2, 24);
    let vertex_count = ((x_segments + 1) * (y_segments + 1)) as usize;
    let mut positions = Vec::with_capacity(vertex_count);
    let mut normals = Vec::with_capacity(vertex_count);
    let mut uvs = Vec::with_capacity(vertex_count);
    let mut indices = Vec::with_capacity((x_segments * y_segments * 6) as usize);

    for y in 0..=y_segments {
        let v = y as f32 / y_segments as f32;
        let py = layout.local_y + (0.5 - v) * layout.local_height;
        for x in 0..=x_segments {
            let u = x as f32 / x_segments as f32;
            let px = layout.local_x + (u - 0.5) * layout.local_width;
            positions.push([
                px,
                py,
                plane_surface_z(px, py, ctx.warp_amount, ctx.elapsed_secs) + 1.5,
            ]);
            normals.push([0.0, 0.0, 1.0]);
            uvs.push([u, v]);
        }
    }

    for y in 0..y_segments {
        for x in 0..x_segments {
            let row = y * (x_segments + 1);
            let next_row = (y + 1) * (x_segments + 1);
            let i0 = row + x;
            let i1 = i0 + 1;
            let i2 = next_row + x;
            let i3 = i2 + 1;
            indices.extend_from_slice(&[i0, i2, i1, i1, i2, i3]);
        }
    }

    let mesh = ctx.meshes.add(
        Mesh::new(
            PrimitiveTopology::TriangleList,
            bevy::asset::RenderAssetUsages::default(),
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
        .with_inserted_indices(Indices::U32(indices)),
    );
    ctx.plane_children.push(
        commands
            .spawn((
                TerminalInlineObjectPlane,
                Mesh3d(mesh),
                MeshMaterial3d(ctx.materials.add(StandardMaterial {
                    base_color: Color::WHITE,
                    base_color_texture: Some(image_handle),
                    alpha_mode: AlphaMode::Blend,
                    unlit: true,
                    ..default()
                })),
                Transform::default(),
            ))
            .id(),
    );
}

fn spawn_rgp_object(
    commands: &mut Commands,
    object_id: u32,
    object: &mut crate::inline::RgpInlineObject,
    style: crate::inline::InlineStyle,
    materials: &mut Assets<StandardMaterial>,
    meshes: &mut Assets<Mesh>,
    asset_server: &AssetServer,
) {
    match object {
        crate::inline::RgpInlineObject::Obj {
            meshes: source_meshes,
            handles,
        } => {
            let depth_key = (style.depth.max(0.0) * 100.0).round() as u32;
            let mesh_handles = if let Some((existing_key, existing_handles)) = handles.as_ref() {
                if *existing_key == depth_key {
                    existing_handles.clone()
                } else {
                    let mesh_handles = source_meshes
                        .iter()
                        .cloned()
                        .map(|mesh| meshes.add(extrude_mesh(mesh, style.depth)))
                        .collect::<Vec<_>>();
                    *handles = Some((depth_key, mesh_handles.clone()));
                    mesh_handles
                }
            } else {
                let mesh_handles = source_meshes
                    .iter()
                    .cloned()
                    .map(|mesh| meshes.add(extrude_mesh(mesh, style.depth)))
                    .collect::<Vec<_>>();
                *handles = Some((depth_key, mesh_handles.clone()));
                mesh_handles
            };
            let use_lighting = true;
            let [r, g, b] = match style.color {
                Some([r, g, b]) => [r, g, b],
                None => [255, 255, 255],
            };
            let material = materials.add(StandardMaterial {
                base_color: Color::srgb_u8(r, g, b),
                emissive: if use_lighting {
                    LinearRgba::rgb(0.02, 0.02, 0.02)
                } else {
                    LinearRgba::rgb(0.0, 0.0, 0.0)
                },
                metallic: 0.0,
                perceptual_roughness: if use_lighting { 0.88 } else { 1.0 },
                reflectance: if use_lighting { 0.18 } else { 0.0 },
                cull_mode: None,
                unlit: !use_lighting,
                ..default()
            });
            let root = commands
                .spawn((
                    TerminalRgpObject { object_id },
                    Transform::default(),
                    Visibility::Visible,
                ))
                .id();
            let children = mesh_handles
                .into_iter()
                .map(|handle| {
                    commands
                        .spawn((
                            Mesh3d(handle),
                            MeshMaterial3d(material.clone()),
                            Transform::default(),
                        ))
                        .id()
                })
                .collect::<Vec<_>>();
            commands.entity(root).add_children(&children);
        }
        crate::inline::RgpInlineObject::Gltf { asset_path, handle } => {
            let handle = if let Some(handle) = handle.as_ref() {
                handle.clone()
            } else {
                let scene =
                    asset_server.load(GltfAssetLabel::Scene(0).from_asset(asset_path.clone()));
                *handle = Some(scene.clone());
                scene
            };
            commands.spawn((
                TerminalRgpObject { object_id },
                Transform::default(),
                Visibility::Visible,
                SceneRoot(handle),
            ));
        }
    }
}

/// Synchronizes RGP inline objects.
#[derive(SystemParam)]
pub(crate) struct RgpSyncParams<'w, 's> {
    app_config: Res<'w, AppConfig>,
    terminal: NonSend<'w, TerminalSurface>,
    viewport: Res<'w, TerminalViewport>,
    presentation: Res<'w, TerminalPresentation>,
    mobius_transition: Res<'w, MobiusTransition>,
    plane_warp: Res<'w, TerminalPlaneWarp>,
    time: Res<'w, Time>,
    plane_query: PlaneTransformQuery<'w, 's>,
    inline_objects: Res<'w, TerminalInlineObjects>,
    query: Query<
        'w,
        's,
        (
            &'static TerminalRgpObject,
            &'static mut Transform,
            &'static mut Visibility,
        ),
    >,
}

/// Synchronizes RGP object entities.
///
/// This runs after [`sync_inline_objects`]. It does not create registrations itself; instead, it
/// positions existing [`TerminalRgpObject`] roots from [`TerminalInlineObjects`] anchor data.
///
/// In [`TerminalPresentationMode::Flat2d`] objects are placed in screen space above the terminal
/// surface. In the 3D modes they are projected onto the active terminal surface using the current
/// [`TerminalPlane`] transform.
pub(crate) fn sync_rgp_objects(mut params: RgpSyncParams) {
    let RgpSyncParams {
        app_config,
        terminal,
        viewport,
        presentation,
        mobius_transition,
        plane_warp,
        time,
        plane_query,
        inline_objects,
        query,
    } = &mut params;
    let cell_width = viewport.size.x / terminal.cols.max(1) as f32;
    let cell_height = viewport.size.y / terminal.rows.max(1) as f32;
    let elapsed_secs = time.elapsed_secs();
    let mobius_progress = active_mobius_progress(presentation.mode, mobius_transition);

    for (object, mut transform, mut visibility) in query.iter_mut() {
        let Some(anchor) = inline_objects.anchors.get(&object.object_id) else {
            *visibility = Visibility::Hidden;
            continue;
        };
        let layout = inline_layout(anchor, terminal, viewport, cell_width, cell_height);
        let base_scale = layout.pixel_width.max(layout.pixel_height).max(1.0) * 0.9;
        let scale = base_scale * anchor.style.scale.max(0.001);
        let scale3 = Vec3::new(
            anchor.style.scale3.x.max(0.001),
            anchor.style.scale3.y.max(0.001),
            anchor.style.scale3.z.max(0.001),
        );
        let base_oblique = if anchor.style.depth > 0.0 {
            Quat::from_rotation_y(0.75) * Quat::from_rotation_x(0.35)
        } else {
            Quat::IDENTITY
        };
        let explicit_rotation = Quat::from_euler(
            EulerRot::XYZ,
            anchor.style.rotation.x.to_radians(),
            anchor.style.rotation.y.to_radians(),
            anchor.style.rotation.z.to_radians(),
        );
        let (spin, tilt, bob) = if anchor.style.animate {
            (
                elapsed_secs * app_config.cursor.animation.spin_speed,
                elapsed_secs * app_config.cursor.animation.spin_speed * 0.7,
                (elapsed_secs * app_config.cursor.animation.bob_speed).sin()
                    * cell_height
                    * app_config.cursor.animation.bob_amplitude,
            )
        } else {
            (0.0, 0.0, 0.0)
        };
        let animated_rotation = Quat::from_rotation_y(spin) * Quat::from_rotation_x(tilt);
        let object_rotation = base_oblique * explicit_rotation * animated_rotation;
        let object_scale = Vec3::splat(scale) * scale3;

        match presentation.mode {
            TerminalPresentationMode::Flat2d => {
                transform.translation = Vec3::new(
                    layout.center_x + anchor.style.offset.x,
                    layout.center_y + bob + anchor.style.offset.y,
                    CURSOR_DEPTH + anchor.style.depth * 4.0 + anchor.style.offset.z,
                );
                transform.rotation = object_rotation;
                transform.scale = object_scale;
                *visibility = Visibility::Visible;
            }
            TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d => {
                let Ok(plane_transform) = plane_query.single() else {
                    *visibility = Visibility::Hidden;
                    continue;
                };
                let local_position = plane_surface_point(
                    presentation.mode,
                    layout.local_x,
                    layout.local_y,
                    plane_warp.amount,
                    elapsed_secs,
                    8.0 + anchor.style.depth * 1.5,
                    mobius_progress,
                ) + anchor.style.offset;
                transform.translation = plane_transform.transform_point(local_position);
                transform.rotation = plane_transform.rotation * object_rotation;
                transform.scale = object_scale;
                *visibility = Visibility::Visible;
            }
        }
    }
}

/// Brightness application parameters.
#[derive(SystemParam)]
pub(crate) struct BrightnessParams<'w, 's> {
    app_config: Res<'w, AppConfig>,
    inline_objects: Res<'w, TerminalInlineObjects>,
    rgp_roots: Query<'w, 's, (Entity, &'static TerminalRgpObject)>,
    cursor_roots: Query<'w, 's, Entity, With<CursorModel>>,
    parent_query: Query<'w, 's, &'static ChildOf>,
    material_query: Query<
        'w,
        's,
        (
            Entity,
            &'static mut MeshMaterial3d<StandardMaterial>,
            &'static ChildOf,
        ),
        Without<BrightnessAdjusted>,
    >,
    materials: ResMut<'w, Assets<StandardMaterial>>,
    commands: Commands<'w, 's>,
}

/// Applies per-instance brightness to spawned materials.
///
/// This runs after [`sync_rgp_objects`] so newly spawned object descendants already exist. It walks
/// up each material-bearing entity through [`ChildOf`] relationships, finds either an
/// [`TerminalRgpObject`] root or a [`CursorModel`] root and clones the referenced material with
/// the effective brightness applied.
///
/// Adjusted entities receive [`BrightnessAdjusted`] so the same material branch is not processed
/// again every frame.
pub(crate) fn apply_instance_brightness(mut params: BrightnessParams) {
    let BrightnessParams {
        app_config,
        inline_objects,
        rgp_roots,
        cursor_roots,
        parent_query,
        material_query,
        materials,
        commands,
    } = &mut params;
    if material_query.is_empty() {
        return;
    }

    let rgp_brightness = rgp_roots
        .iter()
        .filter_map(|(entity, object)| {
            let brightness = inline_objects
                .anchors
                .get(&object.object_id)
                .map(|anchor| anchor.style.brightness)?;
            Some((entity, brightness))
        })
        .collect::<HashMap<_, _>>();
    let cursor_roots = cursor_roots.iter().collect::<Vec<_>>();

    for (entity, mut material_handle, parent) in material_query.iter_mut() {
        let mut current = parent.parent();
        let mut brightness = None;

        loop {
            if let Some(value) = rgp_brightness.get(&current) {
                brightness = Some(*value);
                break;
            }
            if cursor_roots.contains(&current) {
                brightness = Some(app_config.cursor.model.brightness);
                break;
            }
            let Ok(next) = parent_query.get(current) else {
                break;
            };
            current = next.parent();
        }

        let Some(brightness) = brightness else {
            continue;
        };

        let Some(source_material) = materials.get(&material_handle.0).cloned() else {
            continue;
        };
        let mut adjusted = source_material;
        let linear = adjusted.base_color.to_linear();
        adjusted.base_color = Color::linear_rgba(
            linear.red * brightness,
            linear.green * brightness,
            linear.blue * brightness,
            linear.alpha,
        );
        adjusted.emissive = LinearRgba::new(
            adjusted.emissive.red * brightness,
            adjusted.emissive.green * brightness,
            adjusted.emissive.blue * brightness,
            adjusted.emissive.alpha,
        );
        material_handle.0 = materials.add(adjusted);
        commands.entity(entity).insert(BrightnessAdjusted);
    }
}

fn extrude_mesh(mesh: Mesh, depth: f32) -> Mesh {
    if depth <= 0.0 {
        return mesh;
    }

    let Some(VertexAttributeValues::Float32x3(source_positions)) =
        mesh.attribute(Mesh::ATTRIBUTE_POSITION)
    else {
        return mesh;
    };
    // `depth` is meant to give thickness to flat artwork. Applying the same extrusion to meshes
    // that already have volume creates overlapping surfaces and unstable depth ordering.
    let mut min_z = f32::INFINITY;
    let mut max_z = f32::NEG_INFINITY;
    for &[_, _, z] in source_positions {
        min_z = min_z.min(z);
        max_z = max_z.max(z);
    }
    if (max_z - min_z).abs() > 1e-4 {
        return mesh;
    }
    let Some(indices) = mesh.indices() else {
        return mesh;
    };

    let indices = match indices {
        Indices::U16(values) => values.iter().map(|&value| value as u32).collect::<Vec<_>>(),
        Indices::U32(values) => values.clone(),
    };
    if indices.len() < 3 {
        return mesh;
    }

    let thickness = depth * 0.03;
    let half = thickness * 0.5;
    let source_len = source_positions.len() as u32;

    let mut positions = Vec::<[f32; 3]>::with_capacity(source_positions.len() * 2);
    let mut normals = Vec::<[f32; 3]>::with_capacity(source_positions.len() * 2);

    for &[x, y, z] in source_positions {
        positions.push([x, y, z + half]);
        normals.push([0.0, 0.0, 1.0]);
    }
    for &[x, y, z] in source_positions {
        positions.push([x, y, z - half]);
        normals.push([0.0, 0.0, -1.0]);
    }

    let mut out_indices = Vec::<u32>::with_capacity(indices.len() * 4);
    for triangle in indices.chunks_exact(3) {
        out_indices.extend_from_slice(triangle);
        out_indices.extend_from_slice(&[
            triangle[2] + source_len,
            triangle[1] + source_len,
            triangle[0] + source_len,
        ]);
    }

    let mut edge_counts = HashMap::<(u32, u32), u32>::new();
    for triangle in indices.chunks_exact(3) {
        for edge in [
            (triangle[0], triangle[1]),
            (triangle[1], triangle[2]),
            (triangle[2], triangle[0]),
        ] {
            let key = if edge.0 < edge.1 {
                edge
            } else {
                (edge.1, edge.0)
            };
            *edge_counts.entry(key).or_insert(0) += 1;
        }
    }

    for ((a, b), count) in edge_counts {
        if count != 1 {
            continue;
        }

        let front_a = source_positions[a as usize];
        let front_b = source_positions[b as usize];
        let edge = Vec3::new(
            front_b[0] - front_a[0],
            front_b[1] - front_a[1],
            front_b[2] - front_a[2],
        );
        let side_normal = Vec3::new(edge.y, -edge.x, 0.0).normalize_or_zero();

        let base = positions.len() as u32;
        positions.extend_from_slice(&[
            [front_a[0], front_a[1], front_a[2] + half],
            [front_b[0], front_b[1], front_b[2] + half],
            [front_b[0], front_b[1], front_b[2] - half],
            [front_a[0], front_a[1], front_a[2] - half],
        ]);
        for _ in 0..4 {
            normals.push([side_normal.x, side_normal.y, side_normal.z]);
        }
        out_indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
    }

    Mesh::new(PrimitiveTopology::TriangleList, Default::default())
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
        .with_inserted_indices(Indices::U32(out_indices))
}

/// Animates the terminal plane warp.
///
/// This updates the front and back meshes stored in [`TerminalPlaneMeshes`]. It is independent of
/// the redraw path and only mutates mesh vertex positions, so plane presentation can keep moving
/// even when the terminal contents are otherwise static.
pub fn animate_terminal_plane_warp(
    time: Res<Time>,
    presentation: Res<TerminalPresentation>,
    mobius_transition: Res<MobiusTransition>,
    warp: Res<TerminalPlaneWarp>,
    plane_meshes: Res<TerminalPlaneMeshes>,
    mut meshes: ResMut<Assets<Mesh>>,
) {
    if presentation.mode == TerminalPresentationMode::Flat2d {
        return;
    }

    let needs_update = match presentation.mode {
        TerminalPresentationMode::Flat2d => false,
        TerminalPresentationMode::Plane3d => {
            presentation.is_changed() || warp.is_changed() || warp.amount > 0.0
        }
        // Reapply the strip every frame so mode switches and time-based motion are visible.
        TerminalPresentationMode::Mobius3d => true,
    };
    if !needs_update {
        return;
    }

    let pulse = warp.amount * (0.96 + 0.04 * (time.elapsed_secs() * 2.2).sin());
    let mobius_progress = active_mobius_progress(presentation.mode, &mobius_transition);
    apply_plane_warp(
        meshes.get_mut(&plane_meshes.front),
        presentation.mode,
        pulse,
        time.elapsed_secs(),
        -1.0,
        mobius_progress,
    );
    apply_plane_warp(
        meshes.get_mut(&plane_meshes.back),
        presentation.mode,
        pulse,
        time.elapsed_secs(),
        1.0,
        mobius_progress,
    );
}

/// Advances the Mobius transition and restores normal 3D interaction when it completes.
pub fn animate_mobius_transition(
    time: Res<Time>,
    mut presentation: ResMut<TerminalPresentation>,
    mut mobius_transition: ResMut<MobiusTransition>,
    mut plane_view: ResMut<TerminalPlaneView>,
    mut redraw: ResMut<TerminalRedrawState>,
) {
    if presentation.mode != TerminalPresentationMode::Mobius3d {
        mobius_transition.stop();
        return;
    }

    if !mobius_transition.active {
        return;
    }

    mobius_transition.elapsed_secs += time.delta_secs();
    redraw.request();

    if mobius_transition.finished() {
        plane_view.zoom = mobius_transition.end_zoom.max(0.1);
        if mobius_transition.direction == crate::scene::MobiusTransitionDirection::Exiting {
            plane_view.yaw = mobius_transition.source_yaw;
            plane_view.pitch = mobius_transition.source_pitch;
            plane_view.camera_offset = mobius_transition.source_camera_offset;
            presentation.mode = mobius_transition.source_mode;
        }
        mobius_transition.stop();
        redraw.request();
    }
}

fn active_mobius_progress(
    mode: TerminalPresentationMode,
    mobius_transition: &MobiusTransition,
) -> f32 {
    if mode != TerminalPresentationMode::Mobius3d {
        return 0.0;
    }

    if mobius_transition.active {
        mobius_transition.morph_progress()
    } else {
        1.0
    }
}

fn apply_plane_warp(
    mesh: Option<&mut Mesh>,
    mode: TerminalPresentationMode,
    pulse: f32,
    elapsed_secs: f32,
    direction: f32,
    mobius_progress: f32,
) {
    let Some(mesh) = mesh else {
        return;
    };
    let Some(VertexAttributeValues::Float32x2(uvs)) = mesh.attribute(Mesh::ATTRIBUTE_UV_0) else {
        return;
    };
    let uvs = uvs.clone();
    let Some(VertexAttributeValues::Float32x3(positions)) =
        mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION)
    else {
        return;
    };

    for (position, uv) in positions.iter_mut().zip(uvs.iter()) {
        let x = uv[0] - 0.5;
        let y = 0.5 - uv[1];
        let point = plane_surface_point(mode, x, y, pulse, elapsed_secs, 0.0, mobius_progress);
        position[0] = point.x;
        position[1] = point.y;
        position[2] = match mode {
            TerminalPresentationMode::Plane3d => point.z * direction,
            TerminalPresentationMode::Flat2d | TerminalPresentationMode::Mobius3d => point.z,
        };
    }
}

/// Cursor synchronization parameters.
#[derive(SystemParam)]
pub(crate) struct CursorSyncParams<'w, 's> {
    app_config: Res<'w, AppConfig>,
    runtime: NonSend<'w, TerminalRuntime>,
    terminal: NonSend<'w, TerminalSurface>,
    viewport: Res<'w, TerminalViewport>,
    presentation: Res<'w, TerminalPresentation>,
    mobius_transition: Res<'w, MobiusTransition>,
    plane_warp: Res<'w, TerminalPlaneWarp>,
    time: Res<'w, Time>,
    plane_query: Query<'w, 's, &'static Transform, (With<TerminalPlane>, Without<CursorModel>)>,
    query: CursorTransformQuery<'w, 's>,
}

/// Synchronizes the 3D cursor model with the terminal cursor.
///
/// This runs after [`redraw_soft_terminal`], once the cursor model has been spawned and the latest
/// terminal cursor position is available from [`TerminalRuntime`]. It updates the [`CursorModel`]
/// transform and visibility for both 2D and 3D presentation modes.
///
/// In 3D mode the cursor model is positioned relative to the current [`TerminalPlane`] transform
/// and warp amount.
pub(crate) fn sync_asset_to_terminal_cursor(mut params: CursorSyncParams) {
    let CursorSyncParams {
        app_config,
        runtime,
        terminal,
        viewport,
        presentation,
        mobius_transition,
        plane_warp,
        time,
        plane_query,
        query,
    } = &mut params;
    if query.is_empty() {
        return;
    }

    let pose_ctx = CursorPoseContext {
        runtime,
        terminal,
        viewport,
        mode: presentation.mode,
        plane_warp_amount: plane_warp.amount,
        mobius_progress: active_mobius_progress(presentation.mode, mobius_transition),
        elapsed_secs: time.elapsed_secs(),
        plane_query,
    };
    let (translation, rotation, scale, cursor_visibility) = cursor_pose(app_config, &pose_ctx);
    for (mut transform, mut visibility) in query.iter_mut() {
        transform.translation = translation;
        transform.rotation = rotation;
        transform.scale = Vec3::splat(scale.max(0.001));
        *visibility = cursor_visibility;
    }
}

fn cursor_pose(
    app_config: &AppConfig,
    ctx: &CursorPoseContext<'_, '_, '_>,
) -> (Vec3, Quat, f32, Visibility) {
    let cols = ctx.terminal.cols.max(1) as f32;
    let rows = ctx.terminal.rows.max(1) as f32;
    let cell_width = ctx.viewport.size.x / cols;
    let cell_height = ctx.viewport.size.y / rows;
    let scale = cell_width.min(cell_height) * app_config.cursor.model.scale_factor;

    let screen = ctx.runtime.parser.screen();
    let (cursor_row, cursor_col) = screen.cursor_position();
    let cursor_col = cursor_col.min(ctx.terminal.cols.saturating_sub(1)) as f32;
    let cursor_row = cursor_row.min(ctx.terminal.rows.saturating_sub(1)) as f32;

    let cursor_x = cursor_col + 0.5 + app_config.cursor.model.x_offset;
    let local_x = ctx.viewport.center.x - ctx.viewport.size.x * 0.5 + cursor_x * cell_width;
    let local_y =
        ctx.viewport.center.y + ctx.viewport.size.y * 0.5 - (cursor_row + 0.5) * cell_height;
    let spin = ctx.elapsed_secs * app_config.cursor.animation.spin_speed;
    let bob = (ctx.elapsed_secs * app_config.cursor.animation.bob_speed).sin()
        * cell_height
        * app_config.cursor.animation.bob_amplitude;
    let plane_bob = if ctx.viewport.size.y > 0.0 {
        bob / ctx.viewport.size.y
    } else {
        0.0
    };

    let (translation, rotation, visibility) = match ctx.mode {
        TerminalPresentationMode::Flat2d => (
            Vec3::new(local_x, local_y + bob, CURSOR_DEPTH),
            Quat::from_rotation_y(spin) * Quat::from_rotation_x(-0.25),
            if !app_config.cursor.model.visible || screen.hide_cursor() {
                Visibility::Hidden
            } else {
                Visibility::Visible
            },
        ),
        TerminalPresentationMode::Plane3d | TerminalPresentationMode::Mobius3d => {
            let Ok(plane_transform) = ctx.plane_query.single() else {
                return (Vec3::ZERO, Quat::IDENTITY, scale, Visibility::Hidden);
            };
            let plane_local_x = cursor_x / cols - 0.5;
            let plane_local_y = 0.5 - (cursor_row + 0.5) / rows + plane_bob;
            let local_position = plane_surface_point(
                ctx.mode,
                plane_local_x,
                plane_local_y,
                ctx.plane_warp_amount,
                ctx.elapsed_secs,
                app_config.cursor.model.plane_offset,
                ctx.mobius_progress,
            );
            (
                plane_transform.transform_point(local_position),
                plane_transform.rotation
                    * (Quat::from_rotation_y(spin) * Quat::from_rotation_x(-0.25)),
                if app_config.cursor.model.visible {
                    Visibility::Visible
                } else {
                    Visibility::Hidden
                },
            )
        }
    };

    (translation, rotation, scale, visibility)
}

fn plane_surface_z(local_x: f32, local_y: f32, warp_amount: f32, elapsed_secs: f32) -> f32 {
    if warp_amount <= 0.0 {
        return 0.0;
    }

    let pulse = warp_amount * (0.96 + 0.04 * (elapsed_secs * 2.2).sin());
    let radius = (local_x * local_x + local_y * local_y).sqrt();
    let core = (-radius * 9.0).exp();
    let ring = (-(radius - 0.22).powi(2) * 18.0).exp();
    -(core * 360.0 + ring * 72.0) * pulse
}

fn plane_surface_point(
    mode: TerminalPresentationMode,
    local_x: f32,
    local_y: f32,
    warp_amount: f32,
    elapsed_secs: f32,
    depth_offset: f32,
    mobius_progress: f32,
) -> Vec3 {
    match mode {
        TerminalPresentationMode::Flat2d => Vec3::new(local_x, local_y, depth_offset),
        TerminalPresentationMode::Plane3d => Vec3::new(
            local_x,
            local_y,
            plane_surface_z(local_x, local_y, warp_amount, elapsed_secs) + depth_offset,
        ),
        TerminalPresentationMode::Mobius3d => {
            let source_point = Vec3::new(local_x, local_y, depth_offset);
            let target_point =
                mobius_surface_point(local_x, local_y, warp_amount, elapsed_secs, depth_offset);
            source_point.lerp(target_point, mobius_progress)
        }
    }
}

fn mobius_surface_point(
    local_x: f32,
    local_y: f32,
    warp_amount: f32,
    elapsed_secs: f32,
    depth_offset: f32,
) -> Vec3 {
    let twist = 1.0 + warp_amount * 0.06 * (elapsed_secs * 0.7).sin();
    let angle = (local_x + 0.5) * std::f32::consts::TAU;
    let radius = 0.24 + warp_amount * 0.015;
    let width = local_y * (0.42 + warp_amount * 0.04);
    let half_angle = angle * 0.5 * twist;
    let cos_half = half_angle.cos();
    let sin_half = half_angle.sin();
    let ring = radius + width * cos_half;

    Vec3::new(
        ring * angle.cos(),
        ring * angle.sin(),
        width * sin_half * 320.0 + depth_offset,
    )
}