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
//! # Viewport Editing Overlay for 2D games.
//!
//! Use this module to implement simple 2D editing for 2D games.
//!
//! To use add the egui and Yoleck plugins to the Bevy app, as well as the plugin of this module:
//!
//! ```no_run
//! # use bevy::prelude::*;
//! # use bevy_yoleck::bevy_egui::EguiPlugin;
//! # use bevy_yoleck::prelude::*;
//! # use bevy_yoleck::vpeol::prelude::*;
//! # let mut app = App::new();
//! app.add_plugins((EguiPlugin,
//!                 YoleckPluginForEditor,
//! // Use `Vpeol2dPluginForGame` instead when setting up for game.
//!                 Vpeol2dPluginForEditor));
//! ```
//!
//! Add the following components to the camera entity:
//! * [`VpeolCameraState`] in order to select and drag entities.
//! * [`Vpeol2dCameraControl`] in order to pan and zoom the camera with the mouse. This one can be
//!   skipped if there are other means to control the camera inside the editor, or if no camera
//!   control inside the editor is desired.
//!
//! ```no_run
//! # use bevy::prelude::*;
//! # use bevy_yoleck::vpeol::VpeolCameraState;
//! # use bevy_yoleck::vpeol::prelude::*;
//! # let commands: Commands = panic!();
//! commands
//!     .spawn(Camera2dBundle::default())
//!     .insert(VpeolCameraState::default())
//!     .insert(Vpeol2dCameraControl::default());
//! ```
//!
//! Entity selection by clicking on it is supported by just adding the plugin. To implement
//! dragging, there are two options:
//!
//! 1. Add  the [`Vpeol2dPosition`] Yoleck component and use it as the source of position (there
//!    are also [`Vpeol2dRotatation`] and [`Vpeol2dScale`], but they don't currently get editing
//!    support from vpeol_2d)
//!     ```no_run
//!     # use bevy::prelude::*;
//!     # use bevy_yoleck::prelude::*;
//!     # use bevy_yoleck::vpeol::prelude::*;
//!     # use serde::{Deserialize, Serialize};
//!     # #[derive(Clone, PartialEq, Serialize, Deserialize, Component, Default, YoleckComponent)]
//!     # struct Example;
//!     # let mut app = App::new();
//!     app.add_yoleck_entity_type({
//!         YoleckEntityType::new("Example")
//!             .with::<Vpeol2dPosition>() // vpeol_2d dragging
//!             .with::<Example>() // entity's specific data and systems
//!     });
//!     ```
//! 2. Use data passing. vpeol_2d will pass a `Vec3` to the entity being dragged:
//!     ```no_run
//!     # use bevy::prelude::*;
//!     # use bevy_yoleck::prelude::*;
//!     # use serde::{Deserialize, Serialize};
//!     # #[derive(Clone, PartialEq, Serialize, Deserialize, Component, Default, YoleckComponent)]
//!     # struct Example {
//!     #     position: Vec2,
//!     # }
//!     # let mut app = App::new();
//!     fn edit_example(mut edit: YoleckEdit<(Entity, &mut Example)>, passed_data: Res<YoleckPassedData>) {
//!         let Ok((entity, mut example)) = edit.get_single_mut() else { return };
//!         if let Some(pos) = passed_data.get::<Vec3>(entity) {
//!             example.position = pos.truncate();
//!         }
//!     }
//!
//!     fn populate_example(mut populate: YoleckPopulate<&Example>) {
//!         populate.populate(|_ctx, mut cmd, example| {
//!             cmd.insert(SpriteBundle {
//!                 transform: Transform::from_translation(example.position.extend(0.0)),
//!                 // Actual sprite components
//!                 ..Default::default()
//!             });
//!         });
//!     }
//!     ```

use crate::bevy_egui::{egui, EguiContexts};
use crate::exclusive_systems::{
    YoleckEntityCreationExclusiveSystems, YoleckExclusiveSystemDirective,
};
use crate::vpeol::{
    handle_clickable_children_system, ray_intersection_with_mesh, VpeolBasePlugin,
    VpeolCameraState, VpeolDragPlane, VpeolRepositionLevel, VpeolRootResolver, VpeolSystemSet,
    WindowGetter,
};
use bevy::input::mouse::MouseWheel;
use bevy::math::DVec2;
use bevy::prelude::*;
use bevy::render::camera::RenderTarget;
use bevy::render::view::VisibleEntities;
use bevy::sprite::{Anchor, Mesh2dHandle, WithMesh2d, WithSprite};
use bevy::text::TextLayoutInfo;
use bevy::utils::HashMap;
use serde::{Deserialize, Serialize};

use crate::{prelude::*, YoleckSchedule};

/// Add the systems required for loading levels that use vpeol_2d components
pub struct Vpeol2dPluginForGame;

impl Plugin for Vpeol2dPluginForGame {
    fn build(&self, app: &mut App) {
        app.add_systems(
            YoleckSchedule::OverrideCommonComponents,
            vpeol_2d_populate_transform,
        );
        #[cfg(feature = "bevy_reflect")]
        register_reflect_types(app);
    }
}

#[cfg(feature = "bevy_reflect")]
fn register_reflect_types(app: &mut App) {
    app.register_type::<Vpeol2dPosition>();
    app.register_type::<Vpeol2dRotatation>();
    app.register_type::<Vpeol2dScale>();
    app.register_type::<Vpeol2dCameraControl>();
}

/// Add the systems required for 2D editing.
///
/// * 2D camera control (for cameras with [`Vpeol2dCameraControl`])
/// * Entity selection.
/// * Entity dragging.
/// * Connecting nested entities.
pub struct Vpeol2dPluginForEditor;

impl Plugin for Vpeol2dPluginForEditor {
    fn build(&self, app: &mut App) {
        app.add_plugins(VpeolBasePlugin);
        app.add_plugins(Vpeol2dPluginForGame);
        app.insert_resource(VpeolDragPlane::XY);

        app.add_systems(
            Update,
            (
                update_camera_status_for_sprites,
                update_camera_status_for_2d_meshes,
                update_camera_status_for_text_2d,
            )
                .in_set(VpeolSystemSet::UpdateCameraState),
        );
        app.add_systems(
            PostUpdate, // to prevent camera shaking (only seen it in 3D, but still)
            (camera_2d_pan, camera_2d_zoom).run_if(in_state(YoleckEditorState::EditorActive)),
        );
        app.add_systems(
            Update,
            (
                apply_deferred,
                handle_clickable_children_system::<
                    Or<(
                        (With<Sprite>, With<Handle<Image>>),
                        (With<TextLayoutInfo>, With<Anchor>),
                    )>,
                    (),
                >,
                apply_deferred,
            )
                .chain()
                .run_if(in_state(YoleckEditorState::EditorActive)),
        );
        app.add_yoleck_edit_system(vpeol_2d_edit_position);
        app.world_mut()
            .resource_mut::<YoleckEntityCreationExclusiveSystems>()
            .on_entity_creation(|queue| queue.push_back(vpeol_2d_init_position));
    }
}

struct CursorInWorldPos {
    cursor_in_world_pos: Vec2,
}

impl CursorInWorldPos {
    fn from_camera_state(camera_state: &VpeolCameraState) -> Option<Self> {
        Some(Self {
            cursor_in_world_pos: camera_state.cursor_ray?.origin.truncate(),
        })
    }

    fn cursor_in_entity_space(&self, transform: &GlobalTransform) -> Vec2 {
        transform
            .compute_matrix()
            .inverse()
            .project_point3(self.cursor_in_world_pos.extend(0.0))
            .truncate()
    }

    fn check_square(
        &self,
        entity_transform: &GlobalTransform,
        anchor: &Anchor,
        size: Vec2,
    ) -> bool {
        let cursor = self.cursor_in_entity_space(entity_transform);
        let anchor = anchor.as_vec();
        let mut min_corner = Vec2::new(-0.5, -0.5) - anchor;
        let mut max_corner = Vec2::new(0.5, 0.5) - anchor;
        for corner in [&mut min_corner, &mut max_corner] {
            corner.x *= size.x;
            corner.y *= size.y;
        }
        min_corner.x <= cursor.x
            && cursor.x <= max_corner.x
            && min_corner.y <= cursor.y
            && cursor.y <= max_corner.y
    }
}

#[allow(clippy::type_complexity)]
fn update_camera_status_for_sprites(
    mut cameras_query: Query<(&mut VpeolCameraState, &VisibleEntities)>,
    entities_query: Query<(
        Entity,
        &GlobalTransform,
        &Sprite,
        &Handle<Image>,
        Option<&TextureAtlas>,
    )>,
    image_assets: Res<Assets<Image>>,
    texture_atlas_layout_assets: Res<Assets<TextureAtlasLayout>>,
    root_resolver: VpeolRootResolver,
) {
    for (mut camera_state, visible_entities) in cameras_query.iter_mut() {
        let Some(cursor) = CursorInWorldPos::from_camera_state(&camera_state) else {
            continue;
        };

        for (entity, entity_transform, sprite, texture, texture_atlas) in
            entities_query.iter_many(visible_entities.iter::<WithSprite>())
        // entities_query.iter()
        {
            let size = if let Some(custom_size) = sprite.custom_size {
                custom_size
            } else if let Some(texture_atlas) = texture_atlas {
                let Some(texture_atlas_layout) =
                    texture_atlas_layout_assets.get(&texture_atlas.layout)
                else {
                    continue;
                };
                texture_atlas_layout.textures[texture_atlas.index]
                    .size()
                    .as_vec2()
            } else if let Some(texture) = image_assets.get(texture) {
                texture.size().as_vec2()
            } else {
                continue;
            };
            if cursor.check_square(entity_transform, &sprite.anchor, size) {
                let z_depth = entity_transform.translation().z;
                let Some(root_entity) = root_resolver.resolve_root(entity) else {
                    continue;
                };
                camera_state.consider(root_entity, z_depth, || {
                    cursor.cursor_in_world_pos.extend(z_depth)
                });
            }
        }
    }
}

fn update_camera_status_for_2d_meshes(
    mut cameras_query: Query<(&mut VpeolCameraState, &VisibleEntities)>,
    entities_query: Query<(Entity, &GlobalTransform, &Mesh2dHandle)>,
    mesh_assets: Res<Assets<Mesh>>,
    root_resolver: VpeolRootResolver,
) {
    for (mut camera_state, visible_entities) in cameras_query.iter_mut() {
        let Some(cursor_ray) = camera_state.cursor_ray else {
            continue;
        };
        for (entity, global_transform, mesh) in
            entities_query.iter_many(visible_entities.iter::<WithMesh2d>())
        {
            let Some(mesh) = mesh_assets.get(&mesh.0) else {
                continue;
            };

            let inverse_transform = global_transform.compute_matrix().inverse();

            let ray_in_object_coords = Ray3d {
                origin: inverse_transform.transform_point3(cursor_ray.origin),
                direction: inverse_transform
                    .transform_vector3(*cursor_ray.direction)
                    .try_into()
                    .unwrap(),
            };

            let Some(distance) = ray_intersection_with_mesh(ray_in_object_coords, mesh) else {
                continue;
            };

            let Some(root_entity) = root_resolver.resolve_root(entity) else {
                continue;
            };
            camera_state.consider(root_entity, -distance, || cursor_ray.get_point(distance));
        }
    }
}

fn update_camera_status_for_text_2d(
    mut cameras_query: Query<(&mut VpeolCameraState, &VisibleEntities)>,
    entities_query: Query<(Entity, &GlobalTransform, &TextLayoutInfo, &Anchor)>,
    root_resolver: VpeolRootResolver,
) {
    for (mut camera_state, visible_entities) in cameras_query.iter_mut() {
        let Some(cursor) = CursorInWorldPos::from_camera_state(&camera_state) else {
            continue;
        };

        for (entity, entity_transform, text_layout_info, anchor) in
            // Weird that it is not `WithText`...
            entities_query.iter_many(visible_entities.iter::<WithSprite>())
        {
            if cursor.check_square(entity_transform, anchor, text_layout_info.logical_size) {
                let z_depth = entity_transform.translation().z;
                let Some(root_entity) = root_resolver.resolve_root(entity) else {
                    continue;
                };
                camera_state.consider(root_entity, z_depth, || {
                    cursor.cursor_in_world_pos.extend(z_depth)
                });
            }
        }
    }
}

/// Pan and zoom a camera entity with the mouse while inisde the editor.
#[derive(Component)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy::reflect::Reflect))]
pub struct Vpeol2dCameraControl {
    /// How much to zoom when receiving scroll event in `MouseScrollUnit::Line` units.
    pub zoom_per_scroll_line: f32,
    /// How much to zoom when receiving scroll event in `MouseScrollUnit::Pixel` units.
    pub zoom_per_scroll_pixel: f32,
}

impl Default for Vpeol2dCameraControl {
    fn default() -> Self {
        Self {
            zoom_per_scroll_line: 0.2,
            zoom_per_scroll_pixel: 0.001,
        }
    }
}

fn camera_2d_pan(
    mut egui_context: EguiContexts,
    mouse_buttons: Res<ButtonInput<MouseButton>>,
    mut cameras_query: Query<
        (Entity, &mut Transform, &VpeolCameraState),
        With<Vpeol2dCameraControl>,
    >,
    mut last_cursor_world_pos_by_camera: Local<HashMap<Entity, Vec2>>,
) {
    enum MouseButtonOp {
        JustPressed,
        BeingPressed,
    }

    let mouse_button_op = if mouse_buttons.just_pressed(MouseButton::Right) {
        if egui_context.ctx_mut().is_pointer_over_area() {
            return;
        }
        MouseButtonOp::JustPressed
    } else if mouse_buttons.pressed(MouseButton::Right) {
        MouseButtonOp::BeingPressed
    } else {
        last_cursor_world_pos_by_camera.clear();
        return;
    };

    for (camera_entity, mut camera_transform, camera_state) in cameras_query.iter_mut() {
        let Some(cursor_ray) = camera_state.cursor_ray else {
            continue;
        };
        let world_pos = cursor_ray.origin.truncate();

        match mouse_button_op {
            MouseButtonOp::JustPressed => {
                last_cursor_world_pos_by_camera.insert(camera_entity, world_pos);
            }
            MouseButtonOp::BeingPressed => {
                if let Some(prev_pos) = last_cursor_world_pos_by_camera.get_mut(&camera_entity) {
                    let movement = *prev_pos - world_pos;
                    camera_transform.translation += movement.extend(0.0);
                }
            }
        }
    }
}

fn camera_2d_zoom(
    mut egui_context: EguiContexts,
    window_getter: WindowGetter,
    mut cameras_query: Query<(
        &mut Transform,
        &VpeolCameraState,
        &Camera,
        &Vpeol2dCameraControl,
    )>,
    mut wheel_events_reader: EventReader<MouseWheel>,
) {
    if egui_context.ctx_mut().is_pointer_over_area() {
        return;
    }

    for (mut camera_transform, camera_state, camera, camera_control) in cameras_query.iter_mut() {
        let Some(cursor_ray) = camera_state.cursor_ray else {
            continue;
        };
        let world_pos = cursor_ray.origin.truncate();

        let zoom_amount: f32 = wheel_events_reader
            .read()
            .map(|wheel_event| match wheel_event.unit {
                bevy::input::mouse::MouseScrollUnit::Line => {
                    wheel_event.y * camera_control.zoom_per_scroll_line
                }
                bevy::input::mouse::MouseScrollUnit::Pixel => {
                    wheel_event.y * camera_control.zoom_per_scroll_pixel
                }
            })
            .sum();

        if zoom_amount == 0.0 {
            continue;
        }

        let scale_by = (-zoom_amount).exp();

        let window = if let RenderTarget::Window(window_ref) = camera.target {
            window_getter.get_window(window_ref).unwrap()
        } else {
            continue;
        };
        camera_transform.scale.x *= scale_by;
        camera_transform.scale.y *= scale_by;
        let Some(cursor_in_screen_pos) = window.cursor_position() else {
            continue;
        };
        let Some(new_cursor_ray) =
            camera.viewport_to_world(&((*camera_transform.as_ref()).into()), cursor_in_screen_pos)
        else {
            continue;
        };
        let new_world_pos = new_cursor_ray.origin.truncate();
        camera_transform.translation += (world_pos - new_world_pos).extend(0.0);
    }
}

/// A position component that's edited and populated by vpeol_2d.
#[derive(Clone, PartialEq, Serialize, Deserialize, Component, Default, YoleckComponent)]
#[serde(transparent)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy::reflect::Reflect))]
pub struct Vpeol2dPosition(pub Vec2);

/// A rotation component that's populated (but not edited) by vpeol_2d.
///
/// The rotation is in radians around the Z axis.
#[derive(Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
#[serde(transparent)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy::reflect::Reflect))]
pub struct Vpeol2dRotatation(pub f32);

/// A scale component that's populated (but not edited) by vpeol_2d.
#[derive(Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
#[serde(transparent)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy::reflect::Reflect))]
pub struct Vpeol2dScale(pub Vec2);

impl Default for Vpeol2dScale {
    fn default() -> Self {
        Self(Vec2::ONE)
    }
}

fn vpeol_2d_edit_position(
    mut ui: ResMut<YoleckUi>,
    mut edit: YoleckEdit<(Entity, &mut Vpeol2dPosition)>,
    passed_data: Res<YoleckPassedData>,
) {
    if edit.is_empty() || edit.has_nonmatching() {
        return;
    }
    // Use double precision to prevent rounding errors when there are many entities.
    let mut average = DVec2::ZERO;
    let mut num_entities = 0;
    let mut transition = Vec2::ZERO;
    for (entity, position) in edit.iter_matching() {
        if let Some(pos) = passed_data.get::<Vec3>(entity) {
            transition = pos.truncate() - position.0;
        }
        average += position.0.as_dvec2();
        num_entities += 1;
    }
    average /= num_entities as f64;

    ui.horizontal(|ui| {
        let mut new_average = average;
        ui.add(egui::DragValue::new(&mut new_average.x).prefix("X:"));
        ui.add(egui::DragValue::new(&mut new_average.y).prefix("Y:"));
        transition += (new_average - average).as_vec2();
    });

    if transition.is_finite() && transition != Vec2::ZERO {
        for (_, mut position) in edit.iter_matching_mut() {
            position.0 += transition;
        }
    }
}

fn vpeol_2d_init_position(
    mut egui_context: EguiContexts,
    ui: Res<YoleckUi>,
    mut edit: YoleckEdit<&mut Vpeol2dPosition>,
    cameras_query: Query<&VpeolCameraState>,
    mouse_buttons: Res<ButtonInput<MouseButton>>,
) -> YoleckExclusiveSystemDirective {
    let Ok(mut position) = edit.get_single_mut() else {
        return YoleckExclusiveSystemDirective::Finished;
    };

    let Some(cursor_ray) = cameras_query
        .iter()
        .find_map(|camera_state| camera_state.cursor_ray)
    else {
        return YoleckExclusiveSystemDirective::Listening;
    };

    position.0 = cursor_ray.origin.truncate();

    if egui_context.ctx_mut().is_pointer_over_area() || ui.ctx().is_pointer_over_area() {
        return YoleckExclusiveSystemDirective::Listening;
    }

    if mouse_buttons.just_released(MouseButton::Left) {
        return YoleckExclusiveSystemDirective::Finished;
    }

    YoleckExclusiveSystemDirective::Listening
}

fn vpeol_2d_populate_transform(
    mut populate: YoleckPopulate<(
        &Vpeol2dPosition,
        Option<&Vpeol2dRotatation>,
        Option<&Vpeol2dScale>,
        &YoleckBelongsToLevel,
    )>,
    levels_query: Query<&VpeolRepositionLevel>,
) {
    populate.populate(
        |_ctx, mut cmd, (position, rotation, scale, belongs_to_level)| {
            let mut transform = Transform::from_translation(position.0.extend(0.0));
            if let Some(Vpeol2dRotatation(rotation)) = rotation {
                transform = transform.with_rotation(Quat::from_rotation_z(*rotation));
            }
            if let Some(Vpeol2dScale(scale)) = scale {
                transform = transform.with_scale(scale.extend(1.0));
            }

            if let Ok(VpeolRepositionLevel(level_transform)) =
                levels_query.get(belongs_to_level.level)
            {
                transform = *level_transform * transform;
            }

            cmd.insert(TransformBundle {
                local: transform,
                global: transform.into(),
            });
        },
    )
}