- 
          
- 
                Notifications
    You must be signed in to change notification settings 
- Fork 4.2k
Add custom cursors #14284
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
          
     Merged
      
      
            alice-i-cecile
  merged 24 commits into
  bevyengine:main
from
eero-lehtinen:custom-cursors
  
      
      
   
  Aug 12, 2024 
      
    
  
     Merged
                    Add custom cursors #14284
Changes from all commits
      Commits
    
    
            Show all changes
          
          
            24 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      5b139fd
              
                Add custom cursors
              
              
                eero-lehtinen b2a3e95
              
                Remove double log
              
              
                eero-lehtinen d2ebb18
              
                Fix doctest
              
              
                eero-lehtinen 8f96339
              
                Fix web build
              
              
                eero-lehtinen c5caf68
              
                Fix docs
              
              
                eero-lehtinen 0ae2d72
              
                Move code to bevy_render to allow using Handle<Image> for cursors
              
              
                eero-lehtinen 5500d3c
              
                Fix example
              
              
                eero-lehtinen 906fb9b
              
                Move system cursors back to bevy_window
              
              
                eero-lehtinen 3267ae7
              
                Fix doc
              
              
                eero-lehtinen b7e66c0
              
                Remove useless dependency
              
              
                eero-lehtinen 80e5b1f
              
                Fix docs
              
              
                eero-lehtinen 882a9d1
              
                Fix wasm build
              
              
                eero-lehtinen 37416fa
              
                Fix wasm
              
              
                eero-lehtinen 1188d9c
              
                Fix rebase
              
              
                eero-lehtinen 6c76a0d
              
                Fix duplicate exported `CustomCursor` name
              
              
                eero-lehtinen a4e8c9e
              
                Remove custom cursors from prelude
              
              
                eero-lehtinen 95a0808
              
                Fix setting cursor to not yet loaded image
              
              
                eero-lehtinen 444aef6
              
                Fix possibly overlapping cache keys
              
              
                eero-lehtinen 4a30e84
              
                Always clear cursor queue to avoid setting it twice
              
              
                eero-lehtinen b1ae997
              
                Fix float pixel calculation
              
              
                eero-lehtinen 4d2aeb0
              
                Merge branch 'main' into custom-cursors
              
              
                eero-lehtinen b591ec6
              
                Fix example
              
              
                eero-lehtinen 67a507f
              
                Update cursors only when world update was run
              
              
                eero-lehtinen 410b074
              
                Typo fix
              
              
                alice-i-cecile File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| use bevy_asset::{AssetId, Assets, Handle}; | ||
| use bevy_ecs::{ | ||
| change_detection::DetectChanges, | ||
| component::Component, | ||
| entity::Entity, | ||
| query::With, | ||
| reflect::ReflectComponent, | ||
| system::{Commands, Local, Query, Res}, | ||
| world::Ref, | ||
| }; | ||
| use bevy_reflect::{std_traits::ReflectDefault, Reflect}; | ||
| use bevy_utils::{tracing::warn, HashSet}; | ||
| use bevy_window::{SystemCursorIcon, Window}; | ||
| use bevy_winit::{ | ||
| convert_system_cursor_icon, CursorSource, CustomCursorCache, CustomCursorCacheKey, | ||
| PendingCursor, | ||
| }; | ||
| use wgpu::TextureFormat; | ||
|  | ||
| use crate::prelude::Image; | ||
|  | ||
| /// Insert into a window entity to set the cursor for that window. | ||
| #[derive(Component, Debug, Clone, Reflect, PartialEq, Eq)] | ||
| #[reflect(Component, Debug, Default)] | ||
| pub enum CursorIcon { | ||
| /// Custom cursor image. | ||
| Custom(CustomCursor), | ||
| /// System provided cursor icon. | ||
| System(SystemCursorIcon), | ||
| } | ||
|  | ||
| impl Default for CursorIcon { | ||
| fn default() -> Self { | ||
| CursorIcon::System(Default::default()) | ||
| } | ||
| } | ||
|  | ||
| impl From<SystemCursorIcon> for CursorIcon { | ||
| fn from(icon: SystemCursorIcon) -> Self { | ||
| CursorIcon::System(icon) | ||
| } | ||
| } | ||
|  | ||
| impl From<CustomCursor> for CursorIcon { | ||
| fn from(cursor: CustomCursor) -> Self { | ||
| CursorIcon::Custom(cursor) | ||
| } | ||
| } | ||
|  | ||
| /// Custom cursor image data. | ||
| #[derive(Debug, Clone, Reflect, PartialEq, Eq, Hash)] | ||
| pub enum CustomCursor { | ||
| /// Image to use as a cursor. | ||
| Image { | ||
| /// The image must be in 8 bit int or 32 bit float rgba. PNG images | ||
| /// work well for this. | ||
| handle: Handle<Image>, | ||
| /// X and Y coordinates of the hotspot in pixels. The hotspot must be | ||
| /// within the image bounds. | ||
| hotspot: (u16, u16), | ||
| }, | ||
| #[cfg(all(target_family = "wasm", target_os = "unknown"))] | ||
| /// A URL to an image to use as the cursor. | ||
| Url { | ||
| /// Web URL to an image to use as the cursor. PNGs preferred. Cursor | ||
| /// creation can fail if the image is invalid or not reachable. | ||
| url: String, | ||
| /// X and Y coordinates of the hotspot in pixels. The hotspot must be | ||
| /// within the image bounds. | ||
| hotspot: (u16, u16), | ||
| }, | ||
| } | ||
|  | ||
| pub fn update_cursors( | ||
| mut commands: Commands, | ||
| mut windows: Query<(Entity, Ref<CursorIcon>), With<Window>>, | ||
| cursor_cache: Res<CustomCursorCache>, | ||
| images: Res<Assets<Image>>, | ||
| mut queue: Local<HashSet<Entity>>, | ||
| ) { | ||
| for (entity, cursor) in windows.iter_mut() { | ||
| if !(queue.remove(&entity) || cursor.is_changed()) { | ||
| continue; | ||
| } | ||
|  | ||
| let cursor_source = match cursor.as_ref() { | ||
| CursorIcon::Custom(CustomCursor::Image { handle, hotspot }) => { | ||
| let cache_key = match handle.id() { | ||
| AssetId::Index { index, .. } => { | ||
| CustomCursorCacheKey::AssetIndex(index.to_bits()) | ||
| } | ||
| AssetId::Uuid { uuid } => CustomCursorCacheKey::AssetUuid(uuid.as_u128()), | ||
| }; | ||
|  | ||
| if cursor_cache.0.contains_key(&cache_key) { | ||
| CursorSource::CustomCached(cache_key) | ||
| } else { | ||
| let Some(image) = images.get(handle) else { | ||
| warn!( | ||
| "Cursor image {handle:?} is not loaded yet and couldn't be used. Trying again next frame." | ||
| ); | ||
| queue.insert(entity); | ||
| continue; | ||
| }; | ||
| let Some(rgba) = image_to_rgba_pixels(image) else { | ||
| warn!("Cursor image {handle:?} not accepted because it's not rgba8 or rgba32float format"); | ||
| continue; | ||
| }; | ||
|  | ||
| let width = image.texture_descriptor.size.width; | ||
| let height = image.texture_descriptor.size.height; | ||
| let source = match bevy_winit::WinitCustomCursor::from_rgba( | ||
| rgba, | ||
| width as u16, | ||
| height as u16, | ||
| hotspot.0, | ||
| hotspot.1, | ||
| ) { | ||
| Ok(source) => source, | ||
| Err(err) => { | ||
| warn!("Cursor image {handle:?} is invalid: {err}"); | ||
| continue; | ||
| } | ||
| }; | ||
|  | ||
| CursorSource::Custom((cache_key, source)) | ||
| } | ||
| } | ||
| #[cfg(all(target_family = "wasm", target_os = "unknown"))] | ||
| CursorIcon::Custom(CustomCursor::Url { url, hotspot }) => { | ||
| let cache_key = CustomCursorCacheKey::Url(url.clone()); | ||
|  | ||
| if cursor_cache.0.contains_key(&cache_key) { | ||
| CursorSource::CustomCached(cache_key) | ||
| } else { | ||
| use bevy_winit::CustomCursorExtWebSys; | ||
| let source = | ||
| bevy_winit::WinitCustomCursor::from_url(url.clone(), hotspot.0, hotspot.1); | ||
| CursorSource::Custom((cache_key, source)) | ||
| } | ||
| } | ||
| CursorIcon::System(system_cursor_icon) => { | ||
| CursorSource::System(convert_system_cursor_icon(*system_cursor_icon)) | ||
| } | ||
| }; | ||
|  | ||
| commands | ||
| .entity(entity) | ||
| .insert(PendingCursor(Some(cursor_source))); | ||
| } | ||
| } | ||
|  | ||
| /// Returns the image data as a `Vec<u8>`. | ||
| /// Only supports rgba8 and rgba32float formats. | ||
| fn image_to_rgba_pixels(image: &Image) -> Option<Vec<u8>> { | ||
| match image.texture_descriptor.format { | ||
| TextureFormat::Rgba8Unorm | ||
| | TextureFormat::Rgba8UnormSrgb | ||
| | TextureFormat::Rgba8Snorm | ||
| | TextureFormat::Rgba8Uint | ||
| | TextureFormat::Rgba8Sint => Some(image.data.clone()), | ||
| TextureFormat::Rgba32Float => Some( | ||
| image | ||
| .data | ||
| .chunks(4) | ||
| .map(|chunk| { | ||
| let chunk = chunk.try_into().unwrap(); | ||
| let num = bytemuck::cast_ref::<[u8; 4], f32>(chunk); | ||
| (num * 255.0) as u8 | ||
| }) | ||
| .collect(), | ||
| ), | ||
| _ => None, | ||
| } | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.