From 1e73312e49fc90479d8c9c645ffd85a59233067c Mon Sep 17 00:00:00 2001 From: Nicola Papale Date: Mon, 26 Jun 2023 18:38:31 +0200 Subject: [PATCH] Use AHash to get color from entity in bevy_gizmos (#8960) # Objective `color_from_entity` uses the poor man's hash to get a fixed random color for an entity. While the poor man's hash is succinct, it has a tendency to clump. As a result, bevy_gizmos has a tendency to re-use very similar colors for different entities. This is bad, we would want non-similar colors that take the whole range of possible hues. This way, each bevy_gizmos aabb gizmo is easy to identify. ## Solution AHash is a nice and fast hash that just so happen to be available to use, so we use it. --- crates/bevy_gizmos/src/lib.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/bevy_gizmos/src/lib.rs b/crates/bevy_gizmos/src/lib.rs index 23c53c895d..a98a95aafa 100644 --- a/crates/bevy_gizmos/src/lib.rs +++ b/crates/bevy_gizmos/src/lib.rs @@ -16,6 +16,7 @@ //! //! See the documentation on [`Gizmos`](crate::gizmos::Gizmos) for more examples. +use std::hash::{Hash, Hasher}; use std::mem; use bevy_app::{Last, Plugin, Update}; @@ -52,6 +53,7 @@ use bevy_render::{ Extract, ExtractSchedule, Render, RenderApp, RenderSet, }; use bevy_transform::components::{GlobalTransform, Transform}; +use bevy_utils::AHasher; pub mod gizmos; @@ -229,7 +231,12 @@ fn draw_all_aabbs( } fn color_from_entity(entity: Entity) -> Color { - let hue = entity.to_bits() as f32 * 100_000. % 360.; + const U64_TO_DEGREES: f32 = 360.0 / u64::MAX as f32; + + let mut hasher = AHasher::default(); + entity.hash(&mut hasher); + + let hue = hasher.finish() as f32 * U64_TO_DEGREES; Color::hsl(hue, 1., 0.5) }