Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add native picking support for tiles #572

Open
zacryol opened this issue Nov 29, 2024 · 1 comment
Open

Add native picking support for tiles #572

zacryol opened this issue Nov 29, 2024 · 1 comment

Comments

@zacryol
Copy link

zacryol commented Nov 29, 2024

With the release of bevy 0.15, picking has been added to the engine: https://bevyengine.org/news/bevy-0-15/#entity-picking-selection

bevy_ecs_tilemap should implement a backend for this functionality, allowing the selection of individual tiles.

I've previously written a crate that adds integration via bevy_mod_picking (https://github.com/zacryol/bevy_picking_tilemap, works with up to bevy 0.14 currently) that can be used as a starting point.

@rparrett rparrett mentioned this issue Dec 5, 2024
7 tasks
@dpogorzelski
Copy link

dpogorzelski commented Dec 5, 2024

A 5 minute hack seems to make it work again with 0.15 but i'm probably missing stuff, mostly no idea of what i'm doing :)

use bevy::{
    app::{Plugin, PreUpdate},
    ecs::{entity::Entity, event::EventWriter, query::With, system::Query},
    math::{Vec2, Vec4},
    prelude::{App, Vec4Swizzles},
    render::{
        camera::{Camera, OrthographicProjection},
        view::ViewVisibility,
    },
    transform::components::GlobalTransform,
    window::PrimaryWindow,
};
use bevy::{
    picking::{
        backend::{HitData, PointerHits},
        pointer::{PointerId, PointerLocation},
        PickSet,
    },
    prelude::IntoSystemConfigs,
};
use bevy_ecs_tilemap::{
    map::{TilemapGridSize, TilemapSize, TilemapType},
    tiles::{TilePos, TileStorage, TileVisible},
};

pub use bevy_ecs_tilemap;

/// `bevy_ecs_tilemap` backend for `bevy_mod_picking`
///
/// The plugins provided by those two crates must be added separately.
pub struct TilemapBackend;

impl Plugin for TilemapBackend {
    fn build(&self, app: &mut App) {
        app.add_systems(PreUpdate, tile_picking.in_set(PickSet::Backend));
    }
}

fn tile_picking(
    pointers: Query<(&PointerId, &PointerLocation)>,
    cameras: Query<(Entity, &Camera, &GlobalTransform, &OrthographicProjection)>,
    primary_window: Query<Entity, With<PrimaryWindow>>,
    tilemap_q: Query<(
        &TilemapSize,
        &TilemapGridSize,
        &TilemapType,
        &TileStorage,
        &GlobalTransform,
        &ViewVisibility,
    )>,
    tile_q: Query<&TileVisible>,
    mut output: EventWriter<PointerHits>,
) {
    for (p_id, p_loc) in pointers
        .iter()
        .filter_map(|(p_id, p_loc)| p_loc.location().map(|l| (p_id, l)))
    {
        // let mut blocked = false;
        let Some((cam_entity, camera, cam_transform, cam_ortho)) = cameras
            .iter()
            .filter(|(_, camera, _, _)| camera.is_active)
            .find(|(_, camera, _, _)| {
                camera
                    .target
                    .normalize(Some(match primary_window.get_single() {
                        Ok(w) => w,
                        Err(_) => return false,
                    }))
                    .unwrap()
                    == p_loc.target
            })
        else {
            continue;
        };

        let Ok(cursor_pos_world) = camera.viewport_to_world_2d(cam_transform, p_loc.position)
        else {
            continue;
        };

        let picks = tilemap_q
            .iter()
            .filter(|(.., vis)| vis.get())
            .filter_map(|(t_s, tgs, tty, t_store, gt, ..)| {
                // if blocked {
                //     return None;
                // }
                let in_map_pos: Vec2 = {
                    let pos = Vec4::from((cursor_pos_world, 0., 1.));
                    let in_map_pos = gt.compute_matrix().inverse() * pos;
                    in_map_pos.xy()
                };
                let picked: Entity = TilePos::from_world_pos(&in_map_pos, t_s, tgs, tty)
                    .and_then(|tile_pos| t_store.get(&tile_pos))?;
                let vis = tile_q.get(picked).ok()?;
                if !vis.0 {
                    return None;
                }
                // blocked = pck.is_some_and(|p| p.should_block_lower);
                let depth = -cam_ortho.near - gt.translation().z;
                Some((picked, HitData::new(cam_entity, depth, None, None)))
            })
            .collect();
        // f32 required by PointerHits
        #[allow(clippy::cast_precision_loss)]
        let order = camera.order as f32;
        output.send(PointerHits::new(*p_id, picks, order));
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants