repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
standbyme/jvm-rs | https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/access_flags.rs | src/rtda/heap/access_flags.rs | pub const ACC_PUBLIC: u16 = 0x0001;
pub const ACC_PRIVATE: u16 = 0x0002;
pub const ACC_PROTECTED: u16 = 0x0004;
pub const ACC_STATIC: u16 = 0x0008;
pub const ACC_FINAL: u16 = 0x0010;
pub const ACC_SUPER: u16 = 0x0020;
pub const ACC_SYNCHRONIZED: u16 = 0x0020;
pub const ACC_VOLATILE: u16 = 0x0040;
pub const ACC_BRIDGE: u16 = 0x0040;
pub const ACC_TRANSIENT: u16 = 0x0080;
pub const ACC_VARARGS: u16 = 0x0080;
pub const ACC_NATIVE: u16 = 0x0100;
pub const ACC_INTERFACE: u16 = 0x0200;
pub const ACC_ABSTRACT: u16 = 0x0400;
pub const ACC_STRICT: u16 = 0x0800;
pub const ACC_SYNTHETIC: u16 = 0x1000;
pub const ACC_ANNOTATION: u16 = 0x2000;
pub const ACC_ENUM: u16 = 0x4000;
| rust | MIT | ebdc07e9049d84688effdccec03a0a5b0aeda0bb | 2026-01-04T20:23:41.645579Z | false |
standbyme/jvm-rs | https://github.com/standbyme/jvm-rs/blob/ebdc07e9049d84688effdccec03a0a5b0aeda0bb/src/rtda/heap/class_member.rs | src/rtda/heap/class_member.rs | use classfile::member_info::MemberInfo;
use rtda::heap::access_flags::*;
#[derive(Debug)]
pub struct ClassMember {
pub access_flags: u16,
pub name: String,
pub descriptor: String,
}
impl ClassMember {
pub fn new(member_info: &MemberInfo) -> ClassMember {
let MemberInfo {
access_flags,
name,
descriptor,
..
} = member_info;
ClassMember {
access_flags: *access_flags,
name: name.to_string(),
descriptor: descriptor.to_string(),
}
}
pub fn is_static(&self) -> bool {
self.access_flags & ACC_STATIC != 0
}
pub fn is_final(&self) -> bool {
self.access_flags & ACC_FINAL != 0
}
}
| rust | MIT | ebdc07e9049d84688effdccec03a0a5b0aeda0bb | 2026-01-04T20:23:41.645579Z | false |
bahdotsh/feedr | https://github.com/bahdotsh/feedr/blob/55a6dfcd6421a77155609754f14543c4dd8402de/src/feed.rs | src/feed.rs | use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use feed_rs::parser;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::time::Duration;
use uuid::Uuid;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Feed {
pub url: String,
pub title: String,
pub items: Vec<FeedItem>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FeedItem {
pub title: String,
pub link: Option<String>,
pub description: Option<String>,
pub pub_date: Option<String>,
pub author: Option<String>,
pub formatted_date: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct FeedCategory {
pub id: String,
pub name: String,
pub feeds: HashSet<String>, // URLs of feeds in this category, using HashSet for faster lookup
pub expanded: bool, // UI state: whether the category is expanded in the UI
}
impl FeedCategory {
pub fn new(name: &str) -> Self {
Self {
id: Uuid::new_v4().to_string(),
name: name.to_string(),
feeds: HashSet::new(),
expanded: true,
}
}
pub fn add_feed(&mut self, url: &str) {
self.feeds.insert(url.to_string());
}
pub fn remove_feed(&mut self, url: &str) -> bool {
self.feeds.remove(url)
}
pub fn contains_feed(&self, url: &str) -> bool {
self.feeds.contains(url)
}
pub fn feed_count(&self) -> usize {
self.feeds.len()
}
pub fn rename(&mut self, new_name: &str) {
self.name = new_name.to_string();
}
pub fn toggle_expanded(&mut self) {
self.expanded = !self.expanded;
}
}
impl Feed {
/// Fetch and parse a feed from a URL with default timeout
pub fn from_url(url: &str) -> Result<Self> {
Self::from_url_with_config(url, 15, None)
}
/// Fetch and parse a feed from a URL with custom timeout
pub fn from_url_with_timeout(url: &str, timeout_secs: u64) -> Result<Self> {
Self::from_url_with_config(url, timeout_secs, None)
}
/// Fetch and parse a feed from a URL with custom timeout and user agent
pub fn from_url_with_config(
url: &str,
timeout_secs: u64,
user_agent: Option<&str>,
) -> Result<Self> {
let default_user_agent =
"Mozilla/5.0 (compatible; Feedr/1.0; +https://github.com/bahdotsh/feedr)";
let ua = user_agent.unwrap_or(default_user_agent);
let client = reqwest::blocking::Client::builder()
.redirect(reqwest::redirect::Policy::limited(10))
.timeout(Duration::from_secs(timeout_secs))
.build()
.context("Failed to create HTTP client")?;
let response = client
.get(url)
.header("User-Agent", ua)
.header(
"Accept",
"application/rss+xml, application/atom+xml, application/xml, text/xml, */*",
)
.header("Accept-Language", "en-US,en;q=0.9")
.header("Accept-Encoding", "gzip, deflate")
.header("Cache-Control", "no-cache")
.header("Connection", "keep-alive")
.send()
.context("Failed to fetch feed")?;
// Check if we got redirected or have an unusual status
let final_url = response.url().clone();
let status = response.status();
let content_type = response
.headers()
.get("content-type")
.and_then(|ct| ct.to_str().ok())
.unwrap_or("unknown")
.to_lowercase();
if !status.is_success() {
return Err(anyhow::anyhow!(
"HTTP error {}: Failed to fetch feed from {}",
status,
url
));
}
let content = response.bytes().context("Failed to read response body")?;
// Debug: Check if we got HTML instead of XML
if content.len() < 100 {
return Err(anyhow::anyhow!(
"Response too short ({} bytes), might be empty or an error page",
content.len()
));
}
let content_start = String::from_utf8_lossy(&content[..std::cmp::min(200, content.len())]);
if content_start.trim_start().starts_with("<!DOCTYPE html")
|| content_start.trim_start().starts_with("<html")
{
return Err(anyhow::anyhow!(
"Received HTML page instead of RSS/Atom feed. URL might be incorrect or require authentication. Final URL: {}",
final_url
));
}
let feed = parser::parse(&content[..])
.with_context(|| {
let content_preview = String::from_utf8_lossy(&content[..std::cmp::min(300, content.len())]);
format!(
"Failed to parse feed (RSS/Atom) from URL: {} (final URL: {}, {} bytes, content-type: {}, preview: {})",
url, final_url, content.len(), content_type, content_preview.trim()
)
})?;
let items = feed.entries.iter().map(FeedItem::from_feed_entry).collect();
Ok(Feed {
url: url.to_string(),
title: feed
.title
.map(|t| t.content)
.unwrap_or_else(|| "Untitled Feed".to_string()),
items,
})
}
}
impl FeedItem {
fn from_feed_entry(entry: &feed_rs::model::Entry) -> Self {
// Extract publication date - try multiple date formats
let (pub_date_string, formatted_date) = if let Some(published) = &entry.published {
let pub_string = published.to_rfc3339();
let formatted = format_date(*published);
(Some(pub_string), Some(formatted))
} else if let Some(updated) = &entry.updated {
let pub_string = updated.to_rfc3339();
let formatted = format_date(*updated);
(Some(pub_string), Some(formatted))
} else {
(None, None)
};
// Extract author information
let author = entry.authors.first().map(|author| {
if !author.name.is_empty() {
author.name.clone()
} else if let Some(email) = &author.email {
email.clone()
} else {
"Unknown".to_string()
}
});
// Extract content/description - prefer content over summary
let description = if let Some(content) = entry.content.as_ref() {
Some(content.body.clone().unwrap_or_default())
} else {
entry
.summary
.as_ref()
.map(|summary| summary.content.clone())
};
// Extract the primary link
let link = entry.links.first().map(|link| link.href.clone());
FeedItem {
title: entry
.title
.as_ref()
.map(|t| t.content.clone())
.unwrap_or_else(|| "Untitled".to_string()),
link,
description,
pub_date: pub_date_string,
author,
formatted_date,
}
}
}
fn format_date(dt: DateTime<Utc>) -> String {
// Calculate how long ago the item was published
let now = Utc::now();
let diff = now.signed_duration_since(dt);
if diff.num_minutes() < 60 {
format!("{} minutes ago", diff.num_minutes())
} else if diff.num_hours() < 24 {
format!("{} hours ago", diff.num_hours())
} else if diff.num_days() < 7 {
format!("{} days ago", diff.num_days())
} else {
// For older items, show the actual date
dt.format("%B %d, %Y").to_string()
}
}
| rust | MIT | 55a6dfcd6421a77155609754f14543c4dd8402de | 2026-01-04T20:23:30.329827Z | false |
bahdotsh/feedr | https://github.com/bahdotsh/feedr/blob/55a6dfcd6421a77155609754f14543c4dd8402de/src/config.rs | src/config.rs | use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
/// Main configuration structure for Feedr
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct Config {
#[serde(default)]
pub general: GeneralConfig,
#[serde(default)]
pub network: NetworkConfig,
#[serde(default)]
pub ui: UiConfig,
#[serde(default)]
pub default_feeds: Vec<DefaultFeed>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GeneralConfig {
/// Maximum number of items to show on the dashboard
#[serde(default = "default_max_dashboard_items")]
pub max_dashboard_items: usize,
/// Auto-refresh interval in seconds (0 = disabled)
#[serde(default)]
pub auto_refresh_interval: u64,
/// Enable automatic background refresh
#[serde(default)]
pub refresh_enabled: bool,
/// Delay in milliseconds between requests to the same domain (for rate limiting)
#[serde(default = "default_refresh_rate_limit_delay")]
pub refresh_rate_limit_delay: u64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NetworkConfig {
/// HTTP request timeout in seconds
#[serde(default = "default_http_timeout")]
pub http_timeout: u64,
/// User agent string for HTTP requests
#[serde(default = "default_user_agent")]
pub user_agent: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UiConfig {
/// Tick rate for UI updates in milliseconds
#[serde(default = "default_tick_rate")]
pub tick_rate: u64,
/// Error message display timeout in milliseconds
#[serde(default = "default_error_timeout")]
pub error_display_timeout: u64,
/// Color theme (light or dark)
#[serde(default)]
pub theme: Theme,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Theme {
Light,
Dark,
}
impl Default for Theme {
fn default() -> Self {
Self::Dark
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DefaultFeed {
pub url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
}
// Default value functions
fn default_max_dashboard_items() -> usize {
100
}
fn default_refresh_rate_limit_delay() -> u64 {
2000 // 2 seconds for Reddit safety
}
fn default_http_timeout() -> u64 {
15
}
fn default_user_agent() -> String {
"Mozilla/5.0 (compatible; Feedr/1.0; +https://github.com/bahdotsh/feedr)".to_string()
}
fn default_tick_rate() -> u64 {
100
}
fn default_error_timeout() -> u64 {
3000
}
impl Default for GeneralConfig {
fn default() -> Self {
Self {
max_dashboard_items: default_max_dashboard_items(),
auto_refresh_interval: 0,
refresh_enabled: false,
refresh_rate_limit_delay: default_refresh_rate_limit_delay(),
}
}
}
impl Default for NetworkConfig {
fn default() -> Self {
Self {
http_timeout: default_http_timeout(),
user_agent: default_user_agent(),
}
}
}
impl Default for UiConfig {
fn default() -> Self {
Self {
tick_rate: default_tick_rate(),
error_display_timeout: default_error_timeout(),
theme: Theme::default(),
}
}
}
impl Config {
/// Load configuration from the XDG config directory
/// Falls back to default configuration if file doesn't exist
pub fn load() -> Result<Self> {
let config_path = Self::config_path();
if config_path.exists() {
let contents =
fs::read_to_string(&config_path).context("Failed to read config file")?;
let config: Config =
toml::from_str(&contents).context("Failed to parse config file")?;
Ok(config)
} else {
// Config doesn't exist, create it with defaults
let config = Config::default();
// Try to save the default config for future use
if let Err(e) = config.save() {
// Don't fail if we can't save, just use defaults
eprintln!("Warning: Could not create default config file: {}", e);
}
Ok(config)
}
}
/// Save configuration to the XDG config directory
pub fn save(&self) -> Result<()> {
let config_path = Self::config_path();
// Ensure the parent directory exists
if let Some(parent) = config_path.parent() {
fs::create_dir_all(parent).context("Failed to create config directory")?;
}
let toml_string = toml::to_string_pretty(self).context("Failed to serialize config")?;
// Add helpful comments to the config file
let commented_config = Self::add_comments(&toml_string);
fs::write(&config_path, commented_config).context("Failed to write config file")?;
Ok(())
}
/// Get the path to the config file following XDG specifications
pub fn config_path() -> PathBuf {
let mut path = dirs::config_dir().unwrap_or_else(|| Path::new(".").to_path_buf());
path.push("feedr");
path.push("config.toml");
path
}
/// Add helpful comments to the generated TOML config
fn add_comments(toml: &str) -> String {
format!(
"# Feedr Configuration File\n\
# This file is automatically generated with default values.\n\
# You can modify any settings below to customize Feedr's behavior.\n\
#\n\
# For more information, visit: https://github.com/bahdotsh/feedr\n\
\n\
{}\n\
\n\
# Background Refresh Settings:\n\
# - refresh_enabled: Enable automatic background refresh (default: false)\n\
# - auto_refresh_interval: Time in seconds between auto-refreshes (default: 0/disabled)\n\
# - refresh_rate_limit_delay: Delay in milliseconds between requests to same domain (default: 2000ms)\n\
# This prevents \"too many requests\" errors, especially for Reddit feeds\n\
#\n\
# UI Theme Settings:\n\
# - theme: Choose between \"light\" or \"dark\" theme (default: dark)\n\
# You can also toggle the theme in the app by pressing 't'\n\
#\n\
# Example configuration for auto-refresh every 5 minutes:\n\
# [general]\n\
# refresh_enabled = true\n\
# auto_refresh_interval = 300\n\
# refresh_rate_limit_delay = 2000\n\
#\n\
# [ui]\n\
# theme = \"light\"\n\
#\n\
# Example default feeds configuration:\n\
# [[default_feeds]]\n\
# url = \"https://example.com/feed.xml\"\n\
# category = \"News\"\n\
#\n\
# [[default_feeds]]\n\
# url = \"https://another-example.com/rss\"\n\
# category = \"Tech\"\n",
toml
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let config = Config::default();
assert_eq!(config.general.max_dashboard_items, 100);
assert_eq!(config.network.http_timeout, 15);
assert_eq!(config.ui.tick_rate, 100);
assert_eq!(config.ui.error_display_timeout, 3000);
}
#[test]
fn test_config_serialization() {
let config = Config::default();
let toml_str = toml::to_string(&config).unwrap();
let deserialized: Config = toml::from_str(&toml_str).unwrap();
assert_eq!(
config.general.max_dashboard_items,
deserialized.general.max_dashboard_items
);
assert_eq!(
config.network.http_timeout,
deserialized.network.http_timeout
);
}
}
| rust | MIT | 55a6dfcd6421a77155609754f14543c4dd8402de | 2026-01-04T20:23:30.329827Z | false |
bahdotsh/feedr | https://github.com/bahdotsh/feedr/blob/55a6dfcd6421a77155609754f14543c4dd8402de/src/app.rs | src/app.rs | use crate::config::Config;
use crate::feed::{Feed, FeedCategory, FeedItem};
use crate::ui::extract_domain;
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;
#[derive(Clone, Debug, Default)]
pub struct FilterOptions {
pub category: Option<String>, // Filter by feed category
pub age: Option<TimeFilter>, // Filter by content age
pub has_author: Option<bool>, // Filter for items with/without author
pub read_status: Option<bool>, // Filter for read/unread items
pub min_length: Option<usize>, // Filter by content length
}
#[derive(Clone, Debug, PartialEq)]
pub enum TimeFilter {
Today,
ThisWeek,
ThisMonth,
Older,
}
impl FilterOptions {
pub fn new() -> Self {
Self::default()
}
pub fn is_active(&self) -> bool {
self.category.is_some()
|| self.age.is_some()
|| self.has_author.is_some()
|| self.read_status.is_some()
|| self.min_length.is_some()
}
pub fn reset(&mut self) {
*self = Self::default();
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum InputMode {
Normal,
InsertUrl,
SearchMode,
FilterMode,
CategoryNameInput, // For creating/renaming categories
}
#[derive(Clone, Debug, PartialEq)]
pub enum View {
Dashboard,
FeedList,
FeedItems,
FeedItemDetail,
CategoryManagement,
}
#[derive(Clone, Debug)]
pub struct App {
pub config: Config,
pub feeds: Vec<Feed>,
pub bookmarks: Vec<String>,
pub categories: Vec<FeedCategory>,
pub selected_category: Option<usize>,
pub input: String,
pub input_mode: InputMode,
pub selected_feed: Option<usize>,
pub selected_item: Option<usize>,
pub view: View,
pub error: Option<String>,
pub success_message: Option<String>,
pub success_message_time: Option<Instant>,
pub search_query: String,
pub is_searching: bool,
pub filtered_items: Vec<(usize, usize)>, // (feed_idx, item_idx) for search results
pub dashboard_items: Vec<(usize, usize)>, // (feed_idx, item_idx) for dashboard
pub is_loading: bool, // Flag to indicate loading/refreshing state
pub loading_indicator: usize, // For animated loading indicator
pub filter_options: FilterOptions,
pub filter_mode: bool, // Whether we're in filter selection mode
pub read_items: Vec<String>, // Track read item IDs
pub filtered_dashboard_items: Vec<(usize, usize)>, // Filtered items for dashboard
pub category_action: Option<CategoryAction>, // For category management
pub detail_vertical_scroll: u16, // Vertical scroll value for item detail view
pub detail_max_scroll: u16, // Maximum scroll value for current content
pub last_refresh: Option<Instant>, // Track when last refresh occurred
pub refresh_in_progress: bool, // Prevent concurrent refreshes
pub last_domain_fetch: HashMap<String, Instant>, // Track last fetch time per domain for rate limiting
}
#[derive(Clone, Debug)]
pub enum CategoryAction {
Create,
Rename(usize),
AddFeedToCategory(String), // Feed URL to add
}
#[derive(Serialize, Deserialize)]
struct SavedData {
bookmarks: Vec<String>,
categories: Vec<FeedCategory>,
read_items: Vec<String>,
}
impl Default for App {
fn default() -> Self {
Self::new()
}
}
impl App {
pub fn new() -> Self {
// Load configuration
let config = Config::load().unwrap_or_else(|e| {
eprintln!("Warning: Failed to load config, using defaults: {}", e);
Config::default()
});
let saved_data = Self::load_saved_data().unwrap_or_else(|_| SavedData {
bookmarks: vec![],
categories: vec![],
read_items: vec![],
});
let mut app = Self {
config,
feeds: Vec::new(),
bookmarks: saved_data.bookmarks,
categories: saved_data.categories,
selected_category: None,
input: String::new(),
input_mode: InputMode::Normal,
selected_feed: None,
selected_item: None,
view: View::Dashboard,
error: None,
success_message: None,
success_message_time: None,
search_query: String::new(),
is_searching: false,
filtered_items: Vec::new(),
dashboard_items: Vec::new(),
is_loading: false,
loading_indicator: 0,
filter_options: FilterOptions::new(),
filter_mode: false,
read_items: saved_data.read_items,
filtered_dashboard_items: Vec::new(),
category_action: None,
detail_vertical_scroll: 0,
detail_max_scroll: 0,
last_refresh: None,
refresh_in_progress: false,
last_domain_fetch: HashMap::new(),
};
// Load bookmarked feeds
app.load_bookmarked_feeds();
app.update_dashboard();
app
}
pub fn load_bookmarked_feeds(&mut self) {
self.feeds.clear();
let timeout = self.config.network.http_timeout;
let user_agent = &self.config.network.user_agent;
for url in &self.bookmarks {
match Feed::from_url_with_config(url, timeout, Some(user_agent)) {
Ok(feed) => self.feeds.push(feed),
Err(_) => { /* Skip failed feeds */ }
}
}
}
fn load_saved_data() -> Result<SavedData> {
let path = Self::data_path();
if !path.exists() {
return Ok(SavedData {
bookmarks: Vec::new(),
categories: Vec::new(),
read_items: Vec::new(),
});
}
let data = fs::read_to_string(path)?;
let saved_data: SavedData = serde_json::from_str(&data)?;
Ok(saved_data)
}
fn save_data(&self) -> Result<()> {
let path = Self::data_path();
if let Some(dir) = path.parent() {
fs::create_dir_all(dir)?;
}
let saved_data = SavedData {
bookmarks: self.bookmarks.clone(),
categories: self.categories.clone(),
read_items: self.read_items.clone(),
};
let json = serde_json::to_string(&saved_data)?;
fs::write(path, json)?;
Ok(())
}
/// Get the data file path with XDG support and backwards compatibility
fn data_path() -> PathBuf {
// New XDG-compliant location
let xdg_path = Self::xdg_data_path();
// Old location for backwards compatibility
let old_path = Self::legacy_data_path();
// If old location exists and new doesn't, migrate
if old_path.exists() && !xdg_path.exists() {
if let Err(e) = Self::migrate_data_file(&old_path, &xdg_path) {
eprintln!("Warning: Failed to migrate data file: {}", e);
// Fall back to old path if migration fails
return old_path;
}
eprintln!(
"Data file migrated from {} to {}",
old_path.display(),
xdg_path.display()
);
}
xdg_path
}
/// Get the XDG-compliant data path (~/.local/share/feedr/feedr_data.json)
fn xdg_data_path() -> PathBuf {
let mut path = dirs::data_local_dir().unwrap_or_else(|| Path::new(".").to_path_buf());
path.push("feedr");
path.push("feedr_data.json");
path
}
/// Get the legacy data path for backwards compatibility
fn legacy_data_path() -> PathBuf {
let mut path = dirs::data_dir().unwrap_or_else(|| Path::new(".").to_path_buf());
path.push("feedr");
path.push("feedr_data.json");
path
}
/// Migrate data from old location to new XDG location
fn migrate_data_file(old_path: &Path, new_path: &Path) -> Result<()> {
// Ensure the target directory exists
if let Some(parent) = new_path.parent() {
fs::create_dir_all(parent)?;
}
// Copy the file to the new location
fs::copy(old_path, new_path)?;
// Optionally, remove the old file after successful migration
// Commenting this out for extra safety - users can manually delete if desired
// fs::remove_file(old_path)?;
Ok(())
}
pub fn apply_filters(&mut self) {
// First update the dashboard items normally
if !self.filter_options.is_active() {
// No filters active, so filtered items are the same as dashboard items
self.filtered_dashboard_items = self.dashboard_items.clone();
return;
}
self.filtered_dashboard_items = self
.dashboard_items
.iter()
.filter(|&&(feed_idx, item_idx)| self.item_matches_filter(feed_idx, item_idx))
.cloned()
.collect();
}
fn item_matches_filter(&self, feed_idx: usize, item_idx: usize) -> bool {
let feed = match self.feeds.get(feed_idx) {
Some(f) => f,
None => return false,
};
let item = match feed.items.get(item_idx) {
Some(i) => i,
None => return false,
};
// Check category filter
if let Some(category) = &self.filter_options.category {
// Use feed URL to infer category
let feed_domain = extract_domain(&feed.url);
if !feed_domain.contains(category) {
return false;
}
}
// Check age filter
if let Some(age_filter) = &self.filter_options.age {
if let Some(date_str) = &item.pub_date {
if let Ok(date) = DateTime::parse_from_rfc2822(date_str) {
let now = Utc::now();
let duration = now.signed_duration_since(date.with_timezone(&Utc));
match age_filter {
TimeFilter::Today => {
if duration.num_hours() > 24 {
return false;
}
}
TimeFilter::ThisWeek => {
if duration.num_days() > 7 {
return false;
}
}
TimeFilter::ThisMonth => {
if duration.num_days() > 30 {
return false;
}
}
TimeFilter::Older => {
if duration.num_days() <= 30 {
return false;
}
}
}
} else {
// Can't parse date, so filter out if age filter is active
return false;
}
} else {
// No date, so filter out if age filter is active
return false;
}
}
// Check author filter
if let Some(has_author) = self.filter_options.has_author {
let item_has_author =
item.author.is_some() && !item.author.as_ref().unwrap().is_empty();
if has_author != item_has_author {
return false;
}
}
// Check read status filter
if let Some(is_read) = self.filter_options.read_status {
let item_id = self.get_item_id(feed_idx, item_idx);
let item_is_read = self.read_items.contains(&item_id);
if is_read != item_is_read {
return false;
}
}
// Check content length filter
if let Some(min_length) = self.filter_options.min_length {
if let Some(desc) = &item.description {
let plain_text = html2text::from_read(desc.as_bytes(), 80);
if plain_text.len() < min_length {
return false;
}
} else {
// No description, so it doesn't meet length requirement
return false;
}
}
true
}
// Generate a unique ID for an item to track read status
fn get_item_id(&self, feed_idx: usize, item_idx: usize) -> String {
if let Some(feed) = self.feeds.get(feed_idx) {
if let Some(item) = feed.items.get(item_idx) {
if let Some(link) = &item.link {
return link.clone();
}
return format!("{}_{}", feed.url, item.title);
}
}
String::new()
}
// Mark an item as read
pub fn mark_item_as_read(&mut self, feed_idx: usize, item_idx: usize) -> Result<()> {
let item_id = self.get_item_id(feed_idx, item_idx);
if !item_id.is_empty() && !self.read_items.contains(&item_id) {
self.read_items.push(item_id);
self.save_data()?;
}
Ok(())
}
// Toggle an item's read status and return whether it's now read
pub fn toggle_item_read(&mut self, feed_idx: usize, item_idx: usize) -> Result<bool> {
let item_id = self.get_item_id(feed_idx, item_idx);
if !item_id.is_empty() {
let is_now_read =
if let Some(pos) = self.read_items.iter().position(|id| id == &item_id) {
// Item is read, mark as unread
self.read_items.remove(pos);
false
} else {
// Item is unread, mark as read
self.read_items.push(item_id);
true
};
self.save_data()?;
Ok(is_now_read)
} else {
Ok(false)
}
}
// Check if an item is read
pub fn is_item_read(&self, feed_idx: usize, item_idx: usize) -> bool {
let item_id = self.get_item_id(feed_idx, item_idx);
self.read_items.contains(&item_id)
}
pub fn update_dashboard(&mut self) {
// Clear existing dashboard items
self.dashboard_items.clear();
// Get all feeds and sort by most recent first
let mut all_items = Vec::new();
for (feed_idx, feed) in self.feeds.iter().enumerate() {
for (item_idx, item) in feed.items.iter().enumerate() {
let date = item
.pub_date
.as_ref()
.and_then(|date_str| DateTime::parse_from_rfc2822(date_str).ok());
all_items.push((feed_idx, item_idx, date));
}
}
// Sort by date (most recent first)
all_items.sort_by(|a, b| match (&a.2, &b.2) {
(Some(a_date), Some(b_date)) => b_date.cmp(a_date),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
});
// Add items to dashboard (limited by config)
let max_items = self.config.general.max_dashboard_items;
for (feed_idx, item_idx, _) in all_items.into_iter().take(max_items) {
self.dashboard_items.push((feed_idx, item_idx));
}
// Apply any active filters
self.apply_filters();
}
pub fn add_feed(&mut self, url: &str) -> Result<()> {
let timeout = self.config.network.http_timeout;
let user_agent = &self.config.network.user_agent;
let feed = Feed::from_url_with_config(url, timeout, Some(user_agent))?;
self.feeds.push(feed);
if !self.bookmarks.contains(&url.to_string()) {
self.bookmarks.push(url.to_string());
}
self.update_dashboard();
// Save data
self.save_data()?;
Ok(())
}
fn opml_dfs(outline: &opml::Outline) -> Vec<String> {
let mut urls = Vec::<String>::new();
if let Some(url) = &outline.xml_url {
urls.push(url.to_string())
}
for o in &outline.outlines {
urls.append(&mut Self::opml_dfs(o));
}
urls
}
pub fn import_opml(&mut self, file_path: &str) -> Result<()> {
let mut opml_file = match std::fs::File::open(file_path) {
Ok(f) => f,
Err(e) => return Err(anyhow::anyhow!("Opening file {}. {}", file_path, e)),
};
let opml_data = match opml::OPML::from_reader(&mut opml_file) {
Ok(opml) => opml,
Err(e) => return Err(anyhow::anyhow!("OPML decode error. {}", e)),
};
for feed_list in opml_data.body.outlines {
for feed in Self::opml_dfs(&feed_list) {
match self.add_feed(&feed) {
Ok(_) => println!("Feed {} added", feed),
Err(e) => eprintln!("Error adding {}: {}", feed, e),
}
}
}
Ok(())
}
pub fn remove_current_feed(&mut self) -> Result<()> {
if let Some(idx) = self.selected_feed {
if idx < self.feeds.len() {
let url = self.feeds[idx].url.clone();
// Remove from feeds
self.feeds.remove(idx);
// Remove from bookmarks
if let Some(pos) = self.bookmarks.iter().position(|x| x == &url) {
self.bookmarks.remove(pos);
}
// Remove from all categories
for category in &mut self.categories {
category.remove_feed(&url);
}
// Update selected feed
if !self.feeds.is_empty() {
if idx >= self.feeds.len() {
self.selected_feed = Some(self.feeds.len() - 1);
}
} else {
self.selected_feed = None;
self.view = View::Dashboard;
}
// Update dashboard
self.update_dashboard();
// Save changes
self.save_data()?;
}
}
Ok(())
}
pub fn current_feed(&self) -> Option<&Feed> {
self.selected_feed.and_then(|idx| self.feeds.get(idx))
}
pub fn current_item(&self) -> Option<&FeedItem> {
self.current_feed()
.and_then(|feed| self.selected_item.and_then(|idx| feed.items.get(idx)))
}
pub fn dashboard_item(&self, idx: usize) -> Option<(&Feed, &FeedItem)> {
if idx < self.dashboard_items.len() {
let (feed_idx, item_idx) = self.dashboard_items[idx];
if let Some(feed) = self.feeds.get(feed_idx) {
if let Some(item) = feed.items.get(item_idx) {
return Some((feed, item));
}
}
}
None
}
pub fn open_current_item_in_browser(&self) -> Result<()> {
if let Some(item) = self.current_item() {
if let Some(link) = &item.link {
open::that(link)?;
}
}
Ok(())
}
pub fn search_feeds(&mut self, query: &str) {
self.search_query = query.to_lowercase();
self.is_searching = !query.is_empty();
if !self.is_searching {
return;
}
self.filtered_items.clear();
for (feed_idx, feed) in self.feeds.iter().enumerate() {
if feed.title.to_lowercase().contains(&self.search_query) {
// Add all items from matching feed
for item_idx in 0..feed.items.len() {
self.filtered_items.push((feed_idx, item_idx));
}
} else {
// Check individual items
for (item_idx, item) in feed.items.iter().enumerate() {
if item.title.to_lowercase().contains(&self.search_query)
|| item
.description
.as_ref()
.is_some_and(|d| d.to_lowercase().contains(&self.search_query))
{
self.filtered_items.push((feed_idx, item_idx));
}
}
}
}
}
pub fn search_item(&self, idx: usize) -> Option<(&Feed, &FeedItem)> {
if idx < self.filtered_items.len() {
let (feed_idx, item_idx) = self.filtered_items[idx];
if let Some(feed) = self.feeds.get(feed_idx) {
if let Some(item) = feed.items.get(item_idx) {
return Some((feed, item));
}
}
}
None
}
pub fn refresh_feeds(&mut self) -> Result<()> {
self.is_loading = true;
self.refresh_in_progress = true;
// Group feeds by domain for rate limiting
let mut domain_groups: HashMap<String, Vec<String>> = HashMap::new();
for url in &self.bookmarks {
let domain = Self::extract_domain_from_url(url);
domain_groups.entry(domain).or_default().push(url.clone());
}
let timeout = self.config.network.http_timeout;
let user_agent = self.config.network.user_agent.clone();
self.feeds.clear();
// Process each domain group with rate limiting
for (domain, urls) in domain_groups {
// Calculate and apply required delay for this domain
let delay = self.calculate_required_delay(&domain);
if !delay.is_zero() {
std::thread::sleep(delay);
}
// Fetch all feeds from this domain
for url in &urls {
match Feed::from_url_with_config(url, timeout, Some(&user_agent)) {
Ok(feed) => self.feeds.push(feed),
Err(e) => self.error = Some(format!("Failed to refresh feed {}: {}", url, e)),
}
}
// Update the last fetch time for this domain
self.last_domain_fetch.insert(domain, Instant::now());
}
self.update_dashboard();
self.is_loading = false;
self.refresh_in_progress = false;
self.last_refresh = Some(Instant::now());
Ok(())
}
pub fn update_loading_indicator(&mut self) {
self.loading_indicator = (self.loading_indicator + 1) % 10;
}
pub fn get_available_categories(&self) -> Vec<String> {
// Extract potential categories from feed domains
let mut categories = std::collections::HashSet::new();
for feed in &self.feeds {
let domain = extract_domain(&feed.url);
// Try to extract a category from the domain
if domain.contains("news") || domain.contains("nytimes") || domain.contains("cnn") {
categories.insert("news".to_string());
} else if domain.contains("tech")
|| domain.contains("wired")
|| domain.contains("ycombinator")
{
categories.insert("tech".to_string());
} else if domain.contains("science")
|| domain.contains("nature")
|| domain.contains("scientific")
{
categories.insert("science".to_string());
} else if domain.contains("finance")
|| domain.contains("money")
|| domain.contains("business")
{
categories.insert("finance".to_string());
} else if domain.contains("sport")
|| domain.contains("espn")
|| domain.contains("athletic")
{
categories.insert("sports".to_string());
} else {
// Use the first part of the domain as a fallback category
if let Some(first_part) = domain.split('.').next() {
categories.insert(first_part.to_string());
}
}
}
let mut result: Vec<String> = categories.into_iter().collect();
result.sort();
result
}
pub fn get_filter_stats(&self) -> (usize, usize, usize) {
let active_count = [
self.filter_options.category.is_some(),
self.filter_options.age.is_some(),
self.filter_options.has_author.is_some(),
self.filter_options.read_status.is_some(),
self.filter_options.min_length.is_some(),
]
.iter()
.filter(|&&x| x)
.count();
let filtered_count = if self.is_searching {
self.filtered_items.len()
} else {
self.filtered_dashboard_items.len()
};
let total_count = if self.is_searching {
self.filtered_items.len()
} else {
self.dashboard_items.len()
};
(active_count, filtered_count, total_count)
}
pub fn get_filter_summary(&self) -> String {
let mut parts = Vec::new();
if let Some(category) = &self.filter_options.category {
parts.push(format!("Category: {}", category));
}
if let Some(age) = &self.filter_options.age {
let age_str = match age {
TimeFilter::Today => "Today",
TimeFilter::ThisWeek => "This Week",
TimeFilter::ThisMonth => "This Month",
TimeFilter::Older => "Older than a month",
};
parts.push(format!("Age: {}", age_str));
}
if let Some(has_author) = self.filter_options.has_author {
parts.push(format!(
"Author: {}",
if has_author {
"With author"
} else {
"No author"
}
));
}
if let Some(is_read) = self.filter_options.read_status {
parts.push(format!(
"Status: {}",
if is_read { "Read" } else { "Unread" }
));
}
if let Some(length) = self.filter_options.min_length {
let length_str = match length {
100 => "Short",
500 => "Medium",
1000 => "Long",
_ => "Custom",
};
parts.push(format!("Length: {}", length_str));
}
if parts.is_empty() {
"No filters active".to_string()
} else {
parts.join(" | ")
}
}
// Category management functions
pub fn create_category(&mut self, name: &str) -> Result<()> {
// Trim the name and check if it's empty
let name = name.trim();
if name.is_empty() {
return Err(anyhow::anyhow!("Category name cannot be empty"));
}
// Check if category with same name exists
if self.categories.iter().any(|c| c.name == name) {
return Err(anyhow::anyhow!("Category with this name already exists"));
}
// Create and add the new category
let category = FeedCategory::new(name);
self.categories.push(category);
self.selected_category = Some(self.categories.len() - 1);
// Save categories
self.save_data()?;
Ok(())
}
pub fn delete_category(&mut self, idx: usize) -> Result<()> {
if idx >= self.categories.len() {
return Err(anyhow::anyhow!("Invalid category index"));
}
self.categories.remove(idx);
if !self.categories.is_empty() && self.selected_category.is_some() {
if self.selected_category.unwrap() >= self.categories.len() {
self.selected_category = Some(self.categories.len() - 1);
}
} else {
self.selected_category = None;
}
// Save categories
self.save_data()?;
Ok(())
}
pub fn rename_category(&mut self, idx: usize, new_name: &str) -> Result<()> {
let new_name = new_name.trim();
if new_name.is_empty() {
return Err(anyhow::anyhow!("Category name cannot be empty"));
}
// Check if another category already has this name
if self
.categories
.iter()
.enumerate()
.any(|(i, c)| i != idx && c.name == new_name)
{
return Err(anyhow::anyhow!("Category with this name already exists"));
}
if idx < self.categories.len() {
self.categories[idx].rename(new_name);
self.save_data()?;
Ok(())
} else {
Err(anyhow::anyhow!("Invalid category index"))
}
}
pub fn assign_feed_to_category(&mut self, feed_url: &str, category_idx: usize) -> Result<()> {
if category_idx >= self.categories.len() {
return Err(anyhow::anyhow!("Invalid category index"));
}
// Add feed to the selected category
self.categories[category_idx].add_feed(feed_url);
// Save the updated categories
self.save_data()?;
Ok(())
}
pub fn remove_feed_from_category(&mut self, feed_url: &str, category_idx: usize) -> Result<()> {
if category_idx >= self.categories.len() {
return Err(anyhow::anyhow!("Invalid category index"));
}
let removed = self.categories[category_idx].remove_feed(feed_url);
if removed {
self.save_data()?;
Ok(())
} else {
Err(anyhow::anyhow!("Feed not found in category"))
}
}
pub fn toggle_category_expanded(&mut self, idx: usize) -> Result<()> {
if idx < self.categories.len() {
self.categories[idx].toggle_expanded();
Ok(())
} else {
Err(anyhow::anyhow!("Invalid category index"))
}
}
// When managing categories in UI
pub fn get_category_for_feed(&self, feed_url: &str) -> Option<usize> {
self.categories
.iter()
.position(|c| c.contains_feed(feed_url))
}
/// Update the maximum scroll value based on content height and viewport height
pub fn update_detail_max_scroll(&mut self, content_lines: u16, viewport_height: u16) {
// Maximum scroll is the content lines minus the viewport height
// If content fits in viewport, max scroll is 0
self.detail_max_scroll = content_lines.saturating_sub(viewport_height);
}
/// Clamp the current scroll position to valid bounds
pub fn clamp_detail_scroll(&mut self) {
if self.detail_vertical_scroll > self.detail_max_scroll {
self.detail_vertical_scroll = self.detail_max_scroll;
}
}
/// Exit the detail view and reset scroll position
pub fn exit_detail_view(&mut self, new_view: View) {
self.detail_vertical_scroll = 0;
self.view = new_view;
}
/// Check if auto-refresh should trigger
pub fn should_auto_refresh(&self) -> bool {
if !self.config.general.refresh_enabled || self.config.general.auto_refresh_interval == 0 {
return false;
}
if self.refresh_in_progress {
return false;
}
if let Some(last_refresh) = self.last_refresh {
let elapsed = last_refresh.elapsed().as_secs();
elapsed >= self.config.general.auto_refresh_interval
} else {
// Never refreshed, so we should refresh
true
}
}
/// Extract domain from URL (e.g., "reddit.com" from "https://www.reddit.com/r/rust/.rss")
fn extract_domain_from_url(url: &str) -> String {
// Simple domain extraction
if let Some(domain_start) = url.find("://") {
let after_protocol = &url[domain_start + 3..];
let domain_end = after_protocol.find('/').unwrap_or(after_protocol.len());
let domain = &after_protocol[..domain_end];
// Remove www. prefix if present
domain.strip_prefix("www.").unwrap_or(domain).to_string()
} else {
// No protocol, try to extract domain directly
let domain_end = url.find('/').unwrap_or(url.len());
let domain = &url[..domain_end];
domain.strip_prefix("www.").unwrap_or(domain).to_string()
}
}
/// Calculate required delay before fetching from a domain
fn calculate_required_delay(&self, domain: &str) -> std::time::Duration {
if let Some(last_fetch) = self.last_domain_fetch.get(domain) {
let elapsed = last_fetch.elapsed();
| rust | MIT | 55a6dfcd6421a77155609754f14543c4dd8402de | 2026-01-04T20:23:30.329827Z | true |
bahdotsh/feedr | https://github.com/bahdotsh/feedr/blob/55a6dfcd6421a77155609754f14543c4dd8402de/src/lib.rs | src/lib.rs | pub mod app;
pub mod config;
pub mod feed;
pub mod tui;
pub mod ui;
| rust | MIT | 55a6dfcd6421a77155609754f14543c4dd8402de | 2026-01-04T20:23:30.329827Z | false |
bahdotsh/feedr | https://github.com/bahdotsh/feedr/blob/55a6dfcd6421a77155609754f14543c4dd8402de/src/ui.rs | src/ui.rs | use crate::app::{App, CategoryAction, InputMode, TimeFilter, View};
use crate::config::Theme;
use html2text::from_read;
use ratatui::{
backend::Backend,
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Color, Modifier, Style},
symbols::{self},
text::{Line, Span, Text},
widgets::{
canvas::{Canvas, Rectangle},
Block, BorderType, Borders, Clear, List, ListItem, ListState, Padding, Paragraph, Tabs,
Wrap,
},
Frame,
};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
/// Color scheme for the UI - supports both light and dark themes with distinct personalities
#[derive(Clone, Debug)]
pub struct ColorScheme {
pub primary: Color,
pub secondary: Color,
pub highlight: Color,
pub success: Color,
pub background: Color,
pub surface: Color,
pub selected_bg: Color,
pub text: Color,
pub text_secondary: Color,
pub muted: Color,
pub accent: Color,
pub error: Color,
pub border: Color,
pub border_focus: Color,
// Theme-specific border styles
pub border_normal: BorderType,
pub border_active: BorderType,
pub border_focus_type: BorderType,
}
impl ColorScheme {
/// Dark theme - Cyberpunk/Neon aesthetic with high contrast and futuristic vibes
pub fn dark() -> Self {
Self {
primary: Color::Rgb(0, 217, 255), // Electric cyan
secondary: Color::Rgb(255, 0, 255), // Vivid magenta
highlight: Color::Rgb(0, 255, 157), // Neon green
success: Color::Rgb(57, 255, 20), // Bright neon green
background: Color::Rgb(10, 10, 10), // Deep black
surface: Color::Rgb(15, 20, 25), // Very dark with blue tint
selected_bg: Color::Rgb(30, 30, 50), // Dark blue-purple
text: Color::Rgb(255, 255, 255), // Pure white
text_secondary: Color::Rgb(150, 200, 255), // Light cyan
muted: Color::Rgb(100, 100, 120), // Muted blue-gray
accent: Color::Rgb(255, 215, 0), // Electric gold
error: Color::Rgb(255, 20, 147), // Hot pink
border: Color::Rgb(80, 80, 120), // Blue-tinted border
border_focus: Color::Rgb(0, 217, 255), // Electric cyan focus
border_normal: BorderType::Double,
border_active: BorderType::Double,
border_focus_type: BorderType::Thick,
}
}
/// Light theme - Minimal/Zen aesthetic with soft natural colors and organic simplicity
pub fn light() -> Self {
Self {
primary: Color::Rgb(92, 138, 126), // Soft sage green
secondary: Color::Rgb(201, 112, 100), // Warm terracotta
highlight: Color::Rgb(218, 165, 32), // Gentle amber gold
success: Color::Rgb(106, 153, 85), // Muted sage
background: Color::Rgb(250, 248, 245), // Warm off-white
surface: Color::Rgb(255, 255, 252), // Cream white
selected_bg: Color::Rgb(237, 231, 220), // Soft beige selection
text: Color::Rgb(60, 50, 40), // Warm dark brown
text_secondary: Color::Rgb(120, 110, 100), // Medium warm gray
muted: Color::Rgb(170, 165, 155), // Muted stone gray
accent: Color::Rgb(184, 134, 100), // Natural wood brown
error: Color::Rgb(180, 80, 70), // Soft clay red
border: Color::Rgb(200, 195, 185), // Subtle warm border
border_focus: Color::Rgb(92, 138, 126), // Sage focus
border_normal: BorderType::Rounded,
border_active: BorderType::Rounded,
border_focus_type: BorderType::Rounded,
}
}
/// Get the color scheme for the given theme
pub fn from_theme(theme: &Theme) -> Self {
match theme {
Theme::Dark => Self::dark(),
Theme::Light => Self::light(),
}
}
/// Get theme-specific list bullet symbol
pub fn get_list_bullet(&self) -> &str {
if self.border_normal == BorderType::Double {
"◆" // Dark theme: tech diamond
} else {
"◦" // Light theme: minimal circle
}
}
/// Get theme-specific arrow right symbol
pub fn get_arrow_right(&self) -> &str {
if self.border_normal == BorderType::Double {
"▸" // Dark theme: futuristic arrow
} else {
"›" // Light theme: minimal arrow
}
}
/// Get theme-specific selection indicator
pub fn get_selection_indicator(&self) -> &str {
if self.border_normal == BorderType::Double {
"▶" // Dark theme: solid arrow
} else {
"•" // Light theme: simple bullet
}
}
/// Get theme-specific loading animation frames
pub fn get_loading_frames(&self) -> Vec<&str> {
if self.border_normal == BorderType::Double {
// Dark theme: Tech/cyber loading
vec!["◢", "◣", "◤", "◥", "◢", "◣", "◤", "◥", "◢", "◣"]
} else {
// Light theme: Minimal loading
vec!["⋯", "⋰", "⋱", "⋯", "⋰", "⋱", "⋯", "⋰", "⋱", "⋯"]
}
}
/// Get theme-specific empty feed ASCII art
pub fn get_empty_feed_art(&self) -> Vec<String> {
if self.border_normal == BorderType::Double {
// Dark theme: Cyberpunk terminal
vec![
" ".to_string(),
" ╔═══════════════════╗ ".to_string(),
" ║ ◢◣ C Y B E R ◤◥ ║ ".to_string(),
" ║ ═══════════════ ║ ".to_string(),
" ║ > NO_SIGNAL_ ║ ".to_string(),
" ║ > INIT_FEED... ║ ".to_string(),
" ╚═══════════════════╝ ".to_string(),
" ".to_string(),
]
} else {
// Light theme: Zen garden with simple plant
vec![
" ".to_string(),
" _ ".to_string(),
" ( ) ".to_string(),
" | ".to_string(),
" / \\ ".to_string(),
" / \\ ".to_string(),
" ------- ".to_string(),
" ".to_string(),
]
}
}
/// Get theme-specific dashboard welcome art
pub fn get_dashboard_art(&self) -> Vec<String> {
if self.border_normal == BorderType::Double {
// Dark theme: Cyberpunk glitch aesthetic
vec![
" ".to_string(),
" ███████╗███████╗███████╗██████╗ ██████╗ ".to_string(),
" ██╔════╝██╔════╝██╔════╝██╔══██╗██╔══██╗ ".to_string(),
" █████╗ █████╗ █████╗ ██║ ██║██████╔╝ ".to_string(),
" ██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║██╔══██╗ ".to_string(),
" ██║ ███████╗███████╗██████╔╝██║ ██║ ".to_string(),
" ╚═╝ ╚══════╝╚══════╝╚═════╝ ╚═╝ ╚═╝ ".to_string(),
" ═══════════════════════════════════════════ ".to_string(),
" ◢◣ NEURAL FEED INTERFACE v2.0 ◤◥ ".to_string(),
" ═══════════════════════════════════════════ ".to_string(),
" ".to_string(),
" ▸ INITIALIZE: Press 'a' to add feed URL ".to_string(),
" ▸ CONNECT TO DATA STREAMS ".to_string(),
" ".to_string(),
]
} else {
// Light theme: Zen minimalist
vec![
" ".to_string(),
" ".to_string(),
" F e e d r ".to_string(),
" ".to_string(),
" ───────────────── ".to_string(),
" ".to_string(),
" A mindful RSS reader ".to_string(),
" ".to_string(),
" ".to_string(),
" 🍃 Begin by adding your first feed ".to_string(),
" Press 'a' to add a feed URL ".to_string(),
" ".to_string(),
" ".to_string(),
]
}
}
/// Get theme-specific icon prefix
pub fn get_icon_feed(&self) -> &str {
if self.border_normal == BorderType::Double {
"◈" // Dark: tech diamond
} else {
"🍃" // Light: leaf
}
}
pub fn get_icon_article(&self) -> &str {
if self.border_normal == BorderType::Double {
"◇" // Dark: hollow diamond
} else {
"📄" // Light: paper
}
}
pub fn get_icon_search(&self) -> &str {
if self.border_normal == BorderType::Double {
"◎" // Dark: target
} else {
"🔍" // Light: magnifying glass
}
}
pub fn get_icon_dashboard(&self) -> &str {
if self.border_normal == BorderType::Double {
"◢◣" // Dark: tech brackets
} else {
"☀️" // Light: sun
}
}
pub fn get_icon_error(&self) -> &str {
"⚠" // Universal warning icon for both themes
}
pub fn get_icon_success(&self) -> &str {
"✓" // Universal checkmark for both themes
}
}
pub fn render<B: Backend>(f: &mut Frame<B>, app: &mut App) {
// Get the color scheme based on the current theme
let colors = ColorScheme::from_theme(&app.config.ui.theme);
// Set background color for the entire terminal
let bg_block = Block::default().style(Style::default().bg(colors.background));
f.render_widget(bg_block, f.size());
// Main layout division with better spacing
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(1)
.constraints([
Constraint::Length(4), // Title/tab bar (slightly taller)
Constraint::Min(0), // Main content
Constraint::Length(4), // Help bar (slightly taller for breathing room)
])
.split(f.size());
render_title_bar(f, app, chunks[0], &colors);
match app.view {
View::Dashboard => render_dashboard(f, app, chunks[1], &colors),
View::FeedList => render_feed_list(f, app, chunks[1], &colors),
View::FeedItems => render_feed_items(f, app, chunks[1], &colors),
View::FeedItemDetail => render_item_detail(f, app, chunks[1], &colors),
View::CategoryManagement => render_category_management(f, app, chunks[1], &colors),
}
render_help_bar(f, app, chunks[2], &colors);
// Show error if present
if let Some(error) = &app.error {
render_error_modal(f, error, &colors);
}
// Show success notification if present
if let Some(success) = &app.success_message {
render_success_notification(f, success, &colors);
}
// Show input modal when in input modes
if matches!(app.input_mode, InputMode::InsertUrl | InputMode::SearchMode) {
render_input_modal(f, app, &colors);
}
// Show filter modal when in filter mode
if app.filter_mode {
render_filter_modal(f, app, &colors);
}
// Show category input modal when in category name input mode
if app.input_mode == InputMode::CategoryNameInput {
render_category_input_modal(f, app, &colors);
}
}
fn render_title_bar<B: Backend>(f: &mut Frame<B>, app: &App, area: Rect, colors: &ColorScheme) {
// Create tabs for navigation
let titles = ["Dashboard", "Feeds", "Items", "Detail", "Categories"];
let selected_tab = match app.view {
View::Dashboard => 0,
View::FeedList => 1,
View::FeedItems => 2,
View::FeedItemDetail => 3,
View::CategoryManagement => 4,
};
// Theme-specific loading animation
let loading_symbols = colors.get_loading_frames();
// Create title with loading indicator if loading
let title = if app.is_loading {
format!(
" {} Refreshing feeds... ",
loading_symbols[app.loading_indicator % loading_symbols.len()]
)
} else {
format!(" {} Feedr ", colors.get_icon_dashboard())
};
// Create tab highlight effect with theme-specific indicators
let selection_indicator = colors.get_selection_indicator();
let tabs = Tabs::new(
titles
.iter()
.enumerate()
.map(|(i, t)| {
let prefix = if i == selected_tab {
format!("{} ", selection_indicator)
} else {
" ".to_string()
};
Line::from(vec![Span::styled(
format!("{}{}", prefix, t),
if i == selected_tab {
Style::default()
.fg(colors.highlight)
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(colors.text_secondary)
},
)])
})
.collect(),
)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(if app.is_loading {
colors.border_active
} else {
colors.border_normal
})
.border_style(Style::default().fg(if app.is_loading {
colors.highlight
} else {
colors.border
}))
.title(title)
.title_alignment(Alignment::Center)
.padding(Padding::new(2, 2, 0, 0)),
)
.style(
Style::default()
.fg(colors.text_secondary)
.bg(colors.surface),
)
.select(selected_tab)
.divider(symbols::line::VERTICAL);
f.render_widget(tabs, area);
}
fn render_dashboard<B: Backend>(f: &mut Frame<B>, app: &App, area: Rect, colors: &ColorScheme) {
let search_icon = colors.get_icon_search();
let mut title = if app.is_searching {
format!(" {} Search Results: '{}' ", search_icon, app.search_query)
} else {
format!(" {} Latest Updates ", colors.get_icon_dashboard())
};
// Add filter indicators to title if any filters are active
if app.filter_options.is_active() {
title = format!("{} | {} Filtered", title, search_icon);
}
// Use the filtered items when filters are active
let items_to_display = if app.is_searching {
&app.filtered_items
} else if app.filter_options.is_active() {
&app.filtered_dashboard_items
} else {
&app.dashboard_items
};
if items_to_display.is_empty() {
let message = if app.is_searching {
let no_results = format!("No results found for '{}'", app.search_query);
// Create a visually appealing empty search results screen
let lines = [
"",
" 🔍 ",
"",
&no_results,
"",
"Try different keywords or add more feeds",
];
lines.join("\n")
} else if app.feeds.is_empty() {
// Theme-specific ASCII art
let ascii_art = colors.get_dashboard_art();
ascii_art.join("\n")
} else {
let empty_msg = [
"",
" 📭 ",
"",
"No recent items",
"",
"Refresh with 'r' to update",
"",
];
empty_msg.join("\n")
};
// Rich text for empty dashboard with theme-specific styling
let mut text = Text::default();
if app.feeds.is_empty() && !app.is_searching {
// For welcome screen with theme-specific styling
for line in message.lines() {
// Dark theme patterns
if line.contains("███")
|| line.contains("╔")
|| line.contains("╗")
|| line.contains("║")
|| line.contains("╚")
|| line.contains("╝")
{
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default().fg(colors.primary),
)]));
} else if line.contains("◢◣") || line.contains("◤◥") || line.contains("▸")
{
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default()
.fg(colors.highlight)
.add_modifier(Modifier::BOLD),
)]));
} else if line.contains("NEURAL")
|| line.contains("INTERFACE")
|| line.contains("CYBER")
{
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default()
.fg(colors.accent)
.add_modifier(Modifier::BOLD),
)]));
} else if line.contains("═══") || line.contains("───") {
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default().fg(colors.border),
)]));
} else if line.contains("INITIALIZE")
|| line.contains("CONNECT")
|| line.contains("NO_SIGNAL")
|| line.contains("INIT_FEED")
{
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default().fg(colors.secondary),
)]));
// Light theme patterns
} else if line.contains("F e e d r") {
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default()
.fg(colors.primary)
.add_modifier(Modifier::BOLD),
)]));
} else if line.contains("mindful") || line.contains("Begin") {
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default().fg(colors.text),
)]));
} else if line.contains("Press 'a'") {
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default().fg(colors.highlight),
)]));
} else if line.contains("🍃") {
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default().fg(colors.success),
)]));
} else if line.contains("_")
|| line.contains("( )")
|| line.contains("|")
|| line.contains("/ \\")
|| line.contains("/ \\")
|| line.contains("-------")
{
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default().fg(colors.secondary),
)]));
} else {
text.lines.push(Line::from(line));
}
}
} else {
// For empty search or empty dashboard
for line in message.lines() {
if line.contains("🔍") || line.contains("📭") || line.contains(search_icon) {
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default().fg(colors.secondary),
)]));
} else if line.contains("No results") || line.contains("No recent") {
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default()
.fg(colors.text)
.add_modifier(Modifier::BOLD),
)]));
} else {
text.lines.push(Line::from(vec![Span::styled(
line,
Style::default().fg(colors.muted),
)]));
}
}
}
let paragraph = Paragraph::new(text).alignment(Alignment::Center).block(
Block::default()
.title(title)
.title_alignment(Alignment::Center)
.borders(Borders::ALL)
.border_type(colors.border_normal)
.border_style(Style::default().fg(colors.border))
.style(Style::default().bg(colors.surface))
.padding(Padding::new(2, 2, 2, 2)),
);
f.render_widget(paragraph, area);
return;
}
if app.filter_options.is_active() && items_to_display.is_empty() {
let mut text = Text::default();
text.lines.push(Line::from(""));
text.lines.push(Line::from(Span::styled(
format!(" {} ", search_icon),
Style::default().fg(colors.secondary),
)));
text.lines.push(Line::from(""));
text.lines.push(Line::from(Span::styled(
"No items match your current filters",
Style::default()
.fg(colors.text)
.add_modifier(Modifier::BOLD),
)));
text.lines.push(Line::from(""));
text.lines.push(Line::from(Span::styled(
app.get_filter_summary(),
Style::default().fg(colors.secondary),
)));
text.lines.push(Line::from(""));
text.lines.push(Line::from(Span::styled(
"Press 'f' to adjust filters or 'r' to refresh feeds",
Style::default().fg(colors.highlight),
)));
let paragraph = Paragraph::new(text).alignment(Alignment::Center).block(
Block::default()
.title(title)
.title_alignment(Alignment::Center)
.borders(Borders::ALL)
.border_type(colors.border_normal)
.border_style(Style::default().fg(colors.border))
.style(Style::default().bg(colors.surface))
.padding(Padding::new(2, 2, 2, 2)),
);
f.render_widget(paragraph, area);
return;
}
// For non-empty dashboard, create richly formatted items with theme-specific styling
let arrow = colors.get_arrow_right();
let success_icon = colors.get_icon_success();
let items: Vec<ListItem> = items_to_display
.iter()
.enumerate()
.map(|(idx, &(feed_idx, item_idx))| {
let (feed, item) = if app.is_searching {
app.search_item(idx).unwrap()
} else {
app.dashboard_item(idx).unwrap()
};
let date_str = item.formatted_date.as_deref().unwrap_or("Unknown date");
let is_selected = app.selected_item == Some(idx);
let is_read = app.is_item_read(feed_idx, item_idx);
// Create clearer visual group with theme-specific hierarchy
ListItem::new(vec![
// Feed source with theme-specific indicator
Line::from(vec![
Span::styled(
if is_selected {
format!("{} ", arrow)
} else {
" ".to_string()
},
Style::default().fg(colors.highlight),
),
Span::styled(
feed.title.to_string(),
Style::default()
.fg(if is_selected {
colors.secondary
} else {
colors.text_secondary
})
.add_modifier(Modifier::BOLD),
),
Span::styled(
if is_read {
format!(" {}", success_icon)
} else {
"".to_string()
},
Style::default().fg(colors.success),
),
]),
// Item title - cleaner layout
Line::from(vec![
Span::styled(" ", Style::default()),
Span::styled(
&item.title,
Style::default()
.fg(if is_selected {
colors.text
} else if is_read {
colors.text_secondary
} else {
colors.text
})
.add_modifier(if is_selected {
Modifier::BOLD
} else {
Modifier::empty()
}),
),
]),
// Publication date with subtle styling
Line::from(vec![
Span::styled(" ", Style::default()),
Span::styled(date_str, Style::default().fg(colors.muted)),
]),
// Spacing between items
Line::from(""),
])
.style(Style::default().fg(colors.text).bg(if is_selected {
colors.selected_bg
} else {
colors.background
}))
})
.collect();
let dashboard_list = List::new(items)
.block(
Block::default()
.title(title)
.title_alignment(Alignment::Center)
.borders(Borders::ALL)
.border_type(colors.border_normal)
.border_style(Style::default().fg(colors.border))
.style(Style::default().bg(colors.surface))
.padding(Padding::new(2, 1, 1, 1)),
)
.highlight_style(
Style::default()
.bg(colors.selected_bg)
.fg(colors.highlight)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("");
let mut state = ratatui::widgets::ListState::default();
state.select(app.selected_item);
f.render_stateful_widget(dashboard_list, area, &mut state);
}
fn render_feed_list<B: Backend>(f: &mut Frame<B>, app: &App, area: Rect, colors: &ColorScheme) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(3), Constraint::Min(0)])
.split(area);
let title_text = vec![
Line::from(Span::styled(
" Add your RSS/Atom feeds to get started ",
Style::default().fg(colors.muted),
)),
Line::from(Span::styled(
" Press 'a' to add a feed ",
Style::default().fg(colors.highlight),
)),
];
let title_para = Paragraph::new(Text::from(title_text))
.block(Block::default().borders(Borders::NONE))
.alignment(Alignment::Left);
f.render_widget(title_para, chunks[0]);
if app.feeds.is_empty() {
// Theme-specific empty feed ASCII art
let mut text = Text::default();
let art_lines = colors.get_empty_feed_art();
for line in &art_lines {
// Style based on theme
if colors.border_normal == BorderType::Double {
// Dark theme styling
if line.contains("╔")
|| line.contains("╗")
|| line.contains("║")
|| line.contains("╚")
|| line.contains("╝")
{
text.lines.push(Line::from(Span::styled(
line,
Style::default().fg(colors.primary),
)));
} else if line.contains("◢◣") || line.contains("◤◥") {
text.lines.push(Line::from(Span::styled(
line,
Style::default().fg(colors.accent),
)));
} else if line.contains("CYBER")
|| line.contains("NO_SIGNAL")
|| line.contains("INIT_FEED")
{
text.lines.push(Line::from(Span::styled(
line,
Style::default().fg(colors.secondary),
)));
} else if line.contains("═══") {
text.lines.push(Line::from(Span::styled(
line,
Style::default().fg(colors.highlight),
)));
} else {
text.lines.push(Line::from(line.as_str()));
}
} else {
// Light theme styling
if line.contains("_")
|| line.contains("( )")
|| line.contains("|")
|| line.contains("/")
|| line.contains("\\")
|| line.contains("-")
{
text.lines.push(Line::from(Span::styled(
line,
Style::default().fg(colors.primary),
)));
} else {
text.lines.push(Line::from(line.as_str()));
}
}
}
// Help message
text.lines.push(Line::from(Span::styled(
" No feeds added yet! ",
Style::default()
.fg(colors.text)
.add_modifier(Modifier::BOLD),
)));
text.lines.push(Line::from(Span::styled(
" ",
Style::default().fg(colors.muted),
)));
text.lines.push(Line::from(Span::styled(
" Press 'a' to add a feed ",
Style::default().fg(colors.highlight),
)));
let feed_icon = colors.get_icon_feed();
let paragraph = Paragraph::new(text).alignment(Alignment::Center).block(
Block::default()
.title(format!(" {} Feeds ", feed_icon))
.title_alignment(Alignment::Center)
| rust | MIT | 55a6dfcd6421a77155609754f14543c4dd8402de | 2026-01-04T20:23:30.329827Z | true |
bahdotsh/feedr | https://github.com/bahdotsh/feedr/blob/55a6dfcd6421a77155609754f14543c4dd8402de/src/main.rs | src/main.rs | use anyhow::Result;
use clap::Parser;
use feedr::app::App;
use feedr::tui;
#[derive(Parser)]
#[command(name = "feedr")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(about = "A feature-rich terminal-based RSS/Atom feed reader written in Rust")]
#[command(
long_about = "Feedr is a modern terminal-based RSS/Atom feed reader with advanced filtering, categorization, and search capabilities. It supports both RSS and Atom feeds with compression handling and provides an intuitive TUI interface."
)]
struct Cli {
/// OPML file to import
#[arg(short, long, value_name = "FILE PATH")]
import: Option<String>,
}
fn main() -> Result<()> {
let _cli = Cli::parse();
// Initialize the application
let mut app = App::new();
match _cli.import {
Some(file_path) => app.import_opml(&file_path),
None => {
// Run the terminal UI
tui::run(app)?;
Ok(())
}
}
}
| rust | MIT | 55a6dfcd6421a77155609754f14543c4dd8402de | 2026-01-04T20:23:30.329827Z | false |
bahdotsh/feedr | https://github.com/bahdotsh/feedr/blob/55a6dfcd6421a77155609754f14543c4dd8402de/src/tui.rs | src/tui.rs | use crate::app::{App, CategoryAction, InputMode, TimeFilter, View};
use crate::ui;
use anyhow::Result;
use crossterm::{
event::{
self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
backend::{Backend, CrosstermBackend},
Terminal,
};
use std::{io, time::Duration};
pub fn run(mut app: App) -> Result<()> {
// Set up terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Run the main application loop
let result = run_app(&mut terminal, &mut app);
// Clean up terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
// Handle any errors from the application
if let Err(err) = result {
println!("Error: {:?}", err);
}
Ok(())
}
fn run_app<B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> Result<()> {
let mut last_tick = std::time::Instant::now();
let tick_rate = Duration::from_millis(app.config.ui.tick_rate);
let error_timeout = Duration::from_millis(app.config.ui.error_display_timeout);
loop {
terminal.draw(|f| ui::render(f, app))?;
// If loading, use a shorter timeout for animation
let timeout = if app.is_loading {
tick_rate
.checked_sub(last_tick.elapsed())
.unwrap_or_else(|| Duration::from_secs(0))
} else if app.error.is_some() {
error_timeout
} else {
tick_rate
};
if event::poll(timeout)? {
// Handle user input
if handle_events(app)? {
return Ok(());
}
} else if last_tick.elapsed() >= tick_rate {
// Update animation frame on tick
if app.is_loading {
app.update_loading_indicator();
}
// Clear error after timeout
if app.error.is_some() && last_tick.elapsed() >= error_timeout {
app.error = None;
}
// Clear success message after a shorter timeout (1.5 seconds)
let success_timeout = Duration::from_millis(1500);
if let Some(msg_time) = app.success_message_time {
if app.success_message.is_some() && msg_time.elapsed() >= success_timeout {
app.success_message = None;
app.success_message_time = None;
}
}
// Check if auto-refresh should trigger
if app.should_auto_refresh() {
// Note: refresh_feeds() is synchronous and will block,
// but it updates the loading state for visual feedback
let _ = app.refresh_feeds();
}
last_tick = std::time::Instant::now();
}
}
}
fn handle_events(app: &mut App) -> Result<bool> {
if let Event::Key(key) = event::read()? {
if matches!(key.kind, KeyEventKind::Release) {
return Ok(false);
}
match app.input_mode {
InputMode::Normal => match app.view {
View::Dashboard => match key.code {
KeyCode::Char('q') => return Ok(true),
KeyCode::Char('f') => {
app.filter_mode = true;
app.input_mode = InputMode::FilterMode;
}
KeyCode::Char('c') => {
if key.modifiers.contains(KeyModifiers::CONTROL) {
// Switch to category management view
app.view = View::CategoryManagement;
app.selected_category = if !app.categories.is_empty() {
Some(0)
} else {
None
};
} else {
// Get available categories
let categories = app.get_available_categories();
if categories.is_empty() {
// No categories available, toggle off if on
app.filter_options.category = None;
} else {
// Cycle through available categories
if app.filter_options.category.is_none() {
// Set to first category
app.filter_options.category = Some(categories[0].clone());
} else {
// Find current index and move to next
let current = app.filter_options.category.as_ref().unwrap();
let current_idx = categories.iter().position(|c| c == current);
if let Some(idx) = current_idx {
if idx < categories.len() - 1 {
// Move to next category
app.filter_options.category =
Some(categories[idx + 1].clone());
} else {
// Wrap around to None
app.filter_options.category = None;
}
} else {
// Current category not found, set to first
app.filter_options.category = Some(categories[0].clone());
}
}
}
app.apply_filters();
}
}
KeyCode::Tab => {
// Check if shift modifier is pressed
if key.modifiers.contains(event::KeyModifiers::SHIFT) {
// With Shift+Tab, go from Feeds to Dashboard
if matches!(app.view, View::FeedList) {
app.view = View::Dashboard;
}
} else {
// With Tab, go from Dashboard to Feeds
if matches!(app.view, View::Dashboard) {
app.view = View::FeedList;
}
}
}
KeyCode::Char('a') => {
app.input.clear();
app.input_mode = InputMode::InsertUrl;
}
KeyCode::Char('r') => {
// Set loading flag before starting refresh
app.is_loading = true;
if let Err(e) = app.refresh_feeds() {
app.error = Some(format!("Failed to refresh feeds: {}", e));
}
// Refresh completed
app.is_loading = false;
}
KeyCode::Char('t') => {
// Toggle theme
if let Err(e) = app.toggle_theme() {
app.error = Some(format!("Failed to toggle theme: {}", e));
} else {
app.success_message = Some("Theme toggled".to_string());
app.success_message_time = Some(std::time::Instant::now());
}
}
KeyCode::Char('/') => {
app.input.clear();
app.input_mode = InputMode::SearchMode;
}
KeyCode::Char('1') => {
if app.feeds.is_empty() {
// Add Hacker News RSS
if let Err(e) = app.add_feed("https://news.ycombinator.com/rss") {
app.error = Some(format!("Failed to add feed: {}", e));
}
}
}
KeyCode::Char('2') => {
if app.feeds.is_empty() {
// Add TechCrunch RSS
if let Err(e) = app.add_feed("https://feeds.feedburner.com/TechCrunch")
{
app.error = Some(format!("Failed to add feed: {}", e));
}
}
}
KeyCode::Char('3') => {
if app.feeds.is_empty() {
// Add NYTimes RSS
if let Err(e) = app.add_feed(
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
) {
app.error = Some(format!("Failed to add feed: {}", e));
}
}
}
KeyCode::Up | KeyCode::Char('k') => {
if let Some(selected) = app.selected_item {
if selected > 0 {
app.selected_item = Some(selected - 1);
}
} else if !app.dashboard_items.is_empty() {
app.selected_item = Some(0);
}
}
KeyCode::Down | KeyCode::Char('j') => {
if let Some(selected) = app.selected_item {
if selected < app.dashboard_items.len() - 1 {
app.selected_item = Some(selected + 1);
}
} else if !app.dashboard_items.is_empty() {
app.selected_item = Some(0);
}
}
KeyCode::Enter => {
if let Some(selected) = app.selected_item {
if app.is_searching && selected < app.filtered_items.len() {
let (feed_idx, item_idx) = app.filtered_items[selected];
app.selected_feed = Some(feed_idx);
app.selected_item = Some(item_idx);
app.view = View::FeedItemDetail;
// Auto-mark as read when viewing detail
if let Err(e) = app.mark_item_as_read(feed_idx, item_idx) {
app.error = Some(format!("Failed to mark item as read: {}", e));
}
} else if selected < app.dashboard_items.len() {
let (feed_idx, item_idx) = app.dashboard_items[selected];
app.selected_feed = Some(feed_idx);
app.selected_item = Some(item_idx);
app.view = View::FeedItemDetail;
// Auto-mark as read when viewing detail
if let Err(e) = app.mark_item_as_read(feed_idx, item_idx) {
app.error = Some(format!("Failed to mark item as read: {}", e));
}
}
}
}
KeyCode::Char('o') => {
if app.selected_item.is_some() {
if let Err(e) = app.open_current_item_in_browser() {
app.error = Some(format!("Failed to open link: {}", e));
}
}
}
KeyCode::Char(' ') => {
if let Some(selected) = app.selected_item {
if app.is_searching && selected < app.filtered_items.len() {
let (feed_idx, item_idx) = app.filtered_items[selected];
match app.toggle_item_read(feed_idx, item_idx) {
Ok(is_now_read) => {
app.success_message = Some(if is_now_read {
"✓ Marked as read".to_string()
} else {
"○ Marked as unread".to_string()
});
app.success_message_time = Some(std::time::Instant::now());
}
Err(e) => {
app.error =
Some(format!("Failed to toggle read status: {}", e));
}
}
// Reapply filters to update the display
app.apply_filters();
} else if selected < app.dashboard_items.len() {
let (feed_idx, item_idx) = app.dashboard_items[selected];
match app.toggle_item_read(feed_idx, item_idx) {
Ok(is_now_read) => {
app.success_message = Some(if is_now_read {
"✓ Marked as read".to_string()
} else {
"○ Marked as unread".to_string()
});
app.success_message_time = Some(std::time::Instant::now());
}
Err(e) => {
app.error =
Some(format!("Failed to toggle read status: {}", e));
}
}
// Reapply filters to update the display
app.apply_filters();
}
}
}
_ => {}
},
View::FeedList => match key.code {
KeyCode::Char('q') => return Ok(true),
KeyCode::Tab => {
app.view = View::Dashboard;
}
KeyCode::Char('a') => {
app.input.clear();
app.input_mode = InputMode::InsertUrl;
}
KeyCode::Char('d') => {
if let Err(e) = app.remove_current_feed() {
app.error = Some(format!("Failed to remove feed: {}", e));
}
}
KeyCode::Char('h') | KeyCode::Esc | KeyCode::Home => {
app.view = View::Dashboard;
app.selected_item = None;
}
KeyCode::Char('/') => {
app.input.clear();
app.input_mode = InputMode::SearchMode;
}
KeyCode::Char('r') => {
// Set loading flag before starting refresh
app.is_loading = true;
if let Err(e) = app.refresh_feeds() {
app.error = Some(format!("Failed to refresh feeds: {}", e));
}
// Refresh completed
app.is_loading = false;
}
KeyCode::Char('t') => {
// Toggle theme
if let Err(e) = app.toggle_theme() {
app.error = Some(format!("Failed to toggle theme: {}", e));
} else {
app.success_message = Some("Theme toggled".to_string());
app.success_message_time = Some(std::time::Instant::now());
}
}
KeyCode::Up | KeyCode::Char('k') => {
if let Some(selected) = app.selected_feed {
if selected > 0 {
app.selected_feed = Some(selected - 1);
}
} else if !app.feeds.is_empty() {
app.selected_feed = Some(0);
}
}
KeyCode::Down | KeyCode::Char('j') => {
if let Some(selected) = app.selected_feed {
if selected < app.feeds.len() - 1 {
app.selected_feed = Some(selected + 1);
}
} else if !app.feeds.is_empty() {
app.selected_feed = Some(0);
}
}
KeyCode::Enter => {
if app.selected_feed.is_some() {
app.selected_item = Some(0);
app.view = View::FeedItems;
}
}
KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
// Switch to category management view
app.view = View::CategoryManagement;
app.selected_category = if !app.categories.is_empty() {
Some(0)
} else {
None
};
}
KeyCode::Char('c')
if app.selected_feed.is_some()
&& !key.modifiers.contains(KeyModifiers::CONTROL) =>
{
// Assign the selected feed to a category
if let Some(feed_idx) = app.selected_feed {
if feed_idx < app.feeds.len() {
let feed_url = app.feeds[feed_idx].url.clone();
app.category_action =
Some(CategoryAction::AddFeedToCategory(feed_url));
app.view = View::CategoryManagement;
}
}
}
_ => {}
},
View::FeedItems => match key.code {
KeyCode::Char('q') => return Ok(true),
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Backspace => {
app.view = View::FeedList;
app.selected_item = None;
}
KeyCode::Home => {
app.view = View::Dashboard;
app.selected_item = None;
}
KeyCode::Char('/') => {
app.input.clear();
app.input_mode = InputMode::SearchMode;
}
KeyCode::Char('r') => {
// Set loading flag before starting refresh
app.is_loading = true;
if let Err(e) = app.refresh_feeds() {
app.error = Some(format!("Failed to refresh feeds: {}", e));
}
// Refresh completed
app.is_loading = false;
}
KeyCode::Char('t') => {
// Toggle theme
if let Err(e) = app.toggle_theme() {
app.error = Some(format!("Failed to toggle theme: {}", e));
} else {
app.success_message = Some("Theme toggled".to_string());
app.success_message_time = Some(std::time::Instant::now());
}
}
KeyCode::Up | KeyCode::Char('k') => {
if let Some(selected) = app.selected_item {
if selected > 0 {
app.selected_item = Some(selected - 1);
}
}
}
KeyCode::Down | KeyCode::Char('j') => {
if let Some(selected) = app.selected_item {
let feed = app.current_feed().unwrap();
if selected < feed.items.len() - 1 {
app.selected_item = Some(selected + 1);
}
}
}
KeyCode::Enter => {
if app.selected_item.is_some() {
app.view = View::FeedItemDetail;
if let Some(feed_idx) = app.selected_feed {
if let Some(item_idx) = app.selected_item {
if let Err(e) = app.mark_item_as_read(feed_idx, item_idx) {
app.error =
Some(format!("Failed to mark item as read: {}", e));
}
}
}
}
}
KeyCode::Char('o') => {
if app.selected_item.is_some() {
if let Err(e) = app.open_current_item_in_browser() {
app.error = Some(format!("Failed to open link: {}", e));
}
}
}
KeyCode::Char(' ') => {
if let Some(feed_idx) = app.selected_feed {
if let Some(item_idx) = app.selected_item {
match app.toggle_item_read(feed_idx, item_idx) {
Ok(is_now_read) => {
app.success_message = Some(if is_now_read {
"✓ Marked as read".to_string()
} else {
"○ Marked as unread".to_string()
});
app.success_message_time = Some(std::time::Instant::now());
}
Err(e) => {
app.error =
Some(format!("Failed to toggle read status: {}", e));
}
}
}
}
}
_ => {}
},
View::FeedItemDetail => match key.code {
KeyCode::Char('q') => return Ok(true),
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Backspace => {
if app.is_searching {
// Return to search results
app.exit_detail_view(View::Dashboard);
app.selected_item = Some(0);
} else {
// Return to feed items
app.exit_detail_view(View::FeedItems);
}
}
KeyCode::Home => {
app.exit_detail_view(View::Dashboard);
app.selected_item = None;
}
KeyCode::Char('t') => {
// Toggle theme
if let Err(e) = app.toggle_theme() {
app.error = Some(format!("Failed to toggle theme: {}", e));
} else {
app.success_message = Some("Theme toggled".to_string());
app.success_message_time = Some(std::time::Instant::now());
}
}
KeyCode::Up | KeyCode::Char('k') => {
app.detail_vertical_scroll = app.detail_vertical_scroll.saturating_sub(1);
// Clamping is done in the render function, but we can also clamp here
app.clamp_detail_scroll();
}
KeyCode::Down | KeyCode::Char('j') => {
// Only scroll down if we haven't reached the bottom
if app.detail_vertical_scroll < app.detail_max_scroll {
app.detail_vertical_scroll =
app.detail_vertical_scroll.saturating_add(1);
}
}
KeyCode::PageUp | KeyCode::Char('u')
if key.modifiers.contains(KeyModifiers::CONTROL) =>
{
// Scroll up by a larger amount (10 lines)
app.detail_vertical_scroll = app.detail_vertical_scroll.saturating_sub(10);
app.clamp_detail_scroll();
}
KeyCode::PageDown | KeyCode::Char('d')
if key.modifiers.contains(KeyModifiers::CONTROL) =>
{
// Scroll down by a larger amount (10 lines), but not past the bottom
let new_scroll = app.detail_vertical_scroll.saturating_add(10);
app.detail_vertical_scroll = new_scroll.min(app.detail_max_scroll);
}
KeyCode::Char('g') => {
// Jump to the beginning (vim-style)
app.detail_vertical_scroll = 0;
}
KeyCode::Char('G') | KeyCode::End => {
// Jump to the end (vim-style with Shift or End key)
app.detail_vertical_scroll = app.detail_max_scroll;
}
KeyCode::Char('r') => {
// Set loading flag before starting refresh
app.is_loading = true;
if let Err(e) = app.refresh_feeds() {
app.error = Some(format!("Failed to refresh feeds: {}", e));
}
// Refresh completed
app.is_loading = false;
}
KeyCode::Char('o') => {
if let Err(e) = app.open_current_item_in_browser() {
app.error = Some(format!("Failed to open link: {}", e));
}
}
KeyCode::Char(' ') => {
if let Some(feed_idx) = app.selected_feed {
if let Some(item_idx) = app.selected_item {
match app.toggle_item_read(feed_idx, item_idx) {
Ok(is_now_read) => {
app.success_message = Some(if is_now_read {
"✓ Marked as read".to_string()
} else {
"○ Marked as unread".to_string()
});
app.success_message_time = Some(std::time::Instant::now());
}
Err(e) => {
app.error =
Some(format!("Failed to toggle read status: {}", e));
}
}
}
}
}
_ => {}
},
View::CategoryManagement => {
match key.code {
KeyCode::Esc | KeyCode::Char('q') => {
// Return to previous view
app.view = View::FeedList;
app.category_action = None;
}
KeyCode::Char('t') => {
// Toggle theme
if let Err(e) = app.toggle_theme() {
app.error = Some(format!("Failed to toggle theme: {}", e));
} else {
app.success_message = Some("Theme toggled".to_string());
app.success_message_time = Some(std::time::Instant::now());
}
}
KeyCode::Char('n') => {
// Create a new category
app.input.clear();
app.category_action = Some(CategoryAction::Create);
app.input_mode = InputMode::CategoryNameInput;
}
KeyCode::Char('e') if app.selected_category.is_some() => {
// Rename the selected category
if let Some(idx) = app.selected_category {
if idx < app.categories.len() {
app.input = app.categories[idx].name.clone();
app.category_action = Some(CategoryAction::Rename(idx));
app.input_mode = InputMode::CategoryNameInput;
}
}
}
KeyCode::Char('d') if app.selected_category.is_some() => {
// Delete the selected category
if let Some(idx) = app.selected_category {
if let Err(e) = app.delete_category(idx) {
app.error = Some(format!("Failed to delete category: {}", e));
}
}
}
KeyCode::Enter => {
// Add feed to category if that's the current action
if let Some(CategoryAction::AddFeedToCategory(ref feed_url)) =
app.category_action.clone()
{
if let Some(idx) = app.selected_category {
if let Err(e) = app.assign_feed_to_category(feed_url, idx) {
app.error = Some(format!(
"Failed to assign feed to category: {}",
e
));
} else {
// Success, go back to feed list
app.view = View::FeedList;
app.category_action = None;
}
}
}
}
KeyCode::Up | KeyCode::Char('k') => {
// Select previous category
if let Some(selected) = app.selected_category {
if selected > 0 {
| rust | MIT | 55a6dfcd6421a77155609754f14543c4dd8402de | 2026-01-04T20:23:30.329827Z | true |
bahdotsh/feedr | https://github.com/bahdotsh/feedr/blob/55a6dfcd6421a77155609754f14543c4dd8402de/tests/integration_test.rs | tests/integration_test.rs | use feedr::feed::Feed;
#[test]
fn test_rss_feed_parsing() {
// Test with a known RSS feed
match Feed::from_url("https://news.ycombinator.com/rss") {
Ok(feed) => {
assert!(!feed.title.is_empty());
assert!(!feed.items.is_empty());
println!("RSS feed parsed successfully: {} items", feed.items.len());
}
Err(e) => panic!("Failed to parse RSS feed: {}", e),
}
}
#[test]
fn test_mixed_feeds() {
// Test with feeds known to work (mix of formats)
let test_feeds = vec![
("TechCrunch (RSS)", "https://techcrunch.com/feed/"),
("Rust Blog (Atom)", "https://blog.rust-lang.org/feed.xml"),
("Wired (RSS)", "https://www.wired.com/feed/rss"),
];
let mut successful_parses = 0;
for (name, url) in test_feeds {
println!("Testing: {}", name);
match Feed::from_url(url) {
Ok(feed) => {
println!("✓ Successfully parsed: {}", name);
println!(" Title: {}", feed.title);
println!(" Items: {}", feed.items.len());
assert!(!feed.title.is_empty());
successful_parses += 1;
// Test first item has expected fields
if let Some(first_item) = feed.items.first() {
assert!(!first_item.title.is_empty());
println!(" First item: {}", first_item.title);
}
}
Err(e) => {
println!("✗ Failed to parse {}: {}", name, e);
// Don't fail the test immediately, just continue
}
}
}
// At least one should succeed
assert!(successful_parses > 0, "No feeds were successfully parsed");
println!("\nSuccessfully parsed {}/3 feeds", successful_parses);
}
#[test]
fn test_reddit_style_atom_feeds() {
// Test with Reddit-style feeds that claim to be RSS but are actually Atom
let reddit_feeds = vec![
"https://www.reddit.com/r/programming.rss",
"https://www.reddit.com/r/rust.rss",
];
for url in reddit_feeds {
println!("Testing Reddit feed: {}", url);
match Feed::from_url(url) {
Ok(feed) => {
println!("✓ Successfully parsed Reddit feed!");
println!(" Title: {}", feed.title);
println!(" Items: {}", feed.items.len());
assert!(!feed.title.is_empty());
if let Some(first_item) = feed.items.first() {
println!(" First item: {}", first_item.title);
assert!(!first_item.title.is_empty());
}
// Reddit feeds should work now
return;
}
Err(e) => {
println!("⚠ Reddit feed failed (may be rate limited): {}", e);
// Reddit may block automated requests, so we don't fail the test
continue;
}
}
}
println!("Note: Reddit feeds may be blocked due to rate limiting or bot detection");
}
#[test]
fn test_problematic_feeds() {
// Test feeds that are reported as not working
let problematic_feeds = vec![
("Gadgets360", "https://www.gadgets360.com/rss/feeds"),
("CNN", "http://rss.cnn.com/rss/edition.rss"),
("BBC", "http://feeds.bbci.co.uk/news/rss.xml"),
("The Verge", "https://www.theverge.com/rss/index.xml"),
(
"ArsTechnica",
"https://feeds.arstechnica.com/arstechnica/index",
),
(
"NYTimes",
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
),
];
for (name, url) in problematic_feeds {
println!("Testing problematic feed: {} - {}", name, url);
match Feed::from_url(url) {
Ok(feed) => {
println!("✓ Successfully parsed: {}", name);
println!(" Title: {}", feed.title);
println!(" Items: {}", feed.items.len());
if let Some(first_item) = feed.items.first() {
println!(" First item: {}", first_item.title);
}
}
Err(e) => {
println!("✗ Failed to parse {}: {}", name, e);
// Print the full error chain for debugging
let mut source = e.source();
let mut depth = 1;
while let Some(err) = source {
println!(" └─ Caused by ({}): {}", depth, err);
source = err.source();
depth += 1;
}
}
}
println!();
}
}
| rust | MIT | 55a6dfcd6421a77155609754f14543c4dd8402de | 2026-01-04T20:23:30.329827Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/ghx_proc_gen/src/lib.rs | ghx_proc_gen/src/lib.rs | #![warn(missing_docs)]
//! A library for 2D & 3D procedural generation with Model synthesis/Wave function Collapse.
//! Also provide grid utilities to manipulate 2d & 3d grid data.
use generator::model::{ModelIndex, ModelRotation, ModelVariantIndex};
use ghx_grid::grid::GridIndex;
pub use ghx_grid;
/// Model synthesis/Wave function Collapse generator
pub mod generator;
/// Our grid elements are called Nodes
pub type NodeIndex = GridIndex;
/// Error returned by a [`generator::Generator`] when a generation fails
#[derive(thiserror::Error, Debug, Clone, Copy)]
#[error("Failed to generate, contradiction at node with index {}", node_index)]
pub struct GeneratorError {
/// Node index at which the contradiction occurred
pub node_index: NodeIndex,
}
/// Error returned by a [`generator::rules::RulesBuilder`] when correct [`generator::rules::Rules`] cannot be built
#[derive(thiserror::Error, Debug, Clone, Copy)]
pub enum RulesBuilderError {
/// Rules cannot be built without models or sockets
#[error("Empty models or sockets collection")]
NoModelsOrSockets,
}
/// Error returned by a [`generator::Generator`] when a node set operation fails
#[derive(thiserror::Error, Debug, Clone)]
pub enum NodeSetError {
/// An invalid [`ModelVariantIndex`] was given
#[error("Invalid model variant index `{0}`, does not exist in the rules")]
InvalidModelIndex(ModelVariantIndex),
/// An invalid [`generator::rules::ModelVariantRef`] was given
#[error("Invalid model variant reference: model index `{0}` with rotation `{1:?}`, does not exist in the rules")]
InvalidModelRef(ModelIndex, ModelRotation),
/// An invalid node index was given
#[error("Invalid node index `{0}`, does not exist in the grid")]
InvalidNodeIndex(NodeIndex),
/// An operation requested to set a model on a node that does not allow it
#[error("Model variant `{0}` not allowed by the Rules on node {1}")]
IllegalModel(ModelVariantIndex, NodeIndex),
/// Wraps a [`GeneratorError`]
#[error("Generation error: {0}")]
GenerationError(#[from] GeneratorError),
}
/// Errors returned by a [`generator::builder::GeneratorBuilder`]
#[derive(thiserror::Error, Debug, Clone)]
pub enum GeneratorBuilderError {
/// Error returned by a [`generator::builder::GeneratorBuilder`] when a node set operation fails
#[error("Initial node set error: {0}")]
InitialNodeSetError(#[from] NodeSetError),
/// Error returned by a [`generator::builder::GeneratorBuilder`] when a given grid does not match the size of the builder's grid.
#[error("Given grid size {0:?} does not match the expected size {1:?}")]
InvalidGridSize(usize, usize),
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/ghx_proc_gen/src/generator.rs | ghx_proc_gen/src/generator.rs | use core::fmt;
use std::{collections::HashMap, sync::Arc};
#[cfg(feature = "bevy")]
use bevy::ecs::component::Component;
use ghx_grid::{
coordinate_system::CoordinateSystem,
grid::{Grid, GridData, NodeRef},
};
use crate::{GeneratorError, NodeIndex, NodeSetError};
use self::{
builder::{GeneratorBuilder, Unset},
internal_generator::{InternalGenerator, InternalGeneratorStatus},
model::{ModelIndex, ModelInstance, ModelRotation, ModelVariantIndex},
node_heuristic::NodeSelectionHeuristic,
observer::GenerationUpdate,
rules::{ModelInfo, ModelVariantRef, Rules},
};
/// Defines a [`GeneratorBuilder`] used to create a generator
pub mod builder;
/// Defines [`crate::generator::model::Model`] and their associated type & utilities
pub mod model;
/// Defines the different possible [`NodeSelectionHeuristic`]
pub mod node_heuristic;
/// Defines different possible observers to view the results:execution of a [`Generator`]
pub mod observer;
/// Defines the [`Rules`] used by a [`Generator`]
pub mod rules;
/// Defines [`crate::generator::socket::Socket`] and their associated type & utilities
pub mod socket;
pub(crate) mod internal_generator;
/// Defines a heuristic for the choice of a model among the possible ones when a node has been selected for generation.
#[derive(Default, Clone, Copy)]
pub enum ModelSelectionHeuristic {
/// Choses a random model among the possible ones, weighted by each model weight.
#[default]
WeightedProbability,
}
/// Different ways to seed the RNG of the generator.
///
/// Note: No matter the selected mode, on each failed generation/reset, the generator will generate and use a new `u64` seed using the previous `u64` seed.
///
/// As an example: if a generation with 50 retries is requested with a seed `s1`, but the generations fails 14 times before finally succeeding with seed `s15`, requesting the generation with any of the seeds `s1`, `s2`, ... to `s15` will give the exact same final successful result. However, while `s1` will need to redo the 14 failed generations before succeeding,`s15` will directly generate the successfull result.
#[derive(Default, Clone, Copy)]
pub enum RngMode {
/// The generator will use the given seed for its random source.
///
Seeded(u64),
/// The generator will use a random seed for its random source.
///
/// The randomly generated seed can still be retrieved on the generator once created.
#[default]
RandomSeed,
}
/// Represents the current generation state, if not failed.
#[derive(Default, Clone, Copy, Eq, PartialEq, Debug)]
pub enum GenerationStatus {
/// The generation has not ended yet.
#[default]
Ongoing,
/// The generation ended succesfully. The whole grid is generated.
Done,
}
/// Output of a [`Generator`] in the context of its [`ghx_grid::grid::Grid`].
#[derive(Clone, Copy, Debug)]
pub struct GeneratedNode {
/// Index of the node in the grid
pub node_index: NodeIndex,
/// Generated node data
pub model_instance: ModelInstance,
}
/// Information about a generation*
#[derive(Clone, Copy, Debug)]
pub struct GenInfo {
/// How many tries the generation took before succeeding
pub try_count: u32,
}
enum NodeSetStatus {
AlreadySet,
CanBeSet,
}
type Collector<'a> = Option<&'a mut Vec<GeneratedNode>>;
/// Model synthesis/WFC generator.
/// Use a [`GeneratorBuilder`] to get an instance of a [`Generator`].
#[cfg_attr(feature = "bevy", derive(Component))]
pub struct Generator<C: CoordinateSystem, G: Grid<C>> {
// === Dynamic configuration ===
max_retry_count: u32,
initial_nodes: Vec<(NodeIndex, ModelVariantIndex)>,
// === Internal state ===
internal: InternalGenerator<C, G>,
}
impl<C: CoordinateSystem, G: Grid<C>> Generator<C, G> {
/// Returns a new `GeneratorBuilder`
pub fn builder() -> GeneratorBuilder<Unset, Unset, C, G> {
GeneratorBuilder::new()
}
fn create(
rules: Arc<Rules<C>>,
grid: G,
initial_nodes: Vec<(NodeIndex, ModelVariantIndex)>,
max_retry_count: u32,
node_selection_heuristic: NodeSelectionHeuristic,
model_selection_heuristic: ModelSelectionHeuristic,
rng_mode: RngMode,
observers: Vec<crossbeam_channel::Sender<GenerationUpdate>>,
collector: &mut Collector,
) -> Result<Self, NodeSetError> {
let mut generator = Self {
max_retry_count,
initial_nodes,
internal: InternalGenerator::new(
rules,
grid,
node_selection_heuristic,
model_selection_heuristic,
rng_mode,
observers,
),
};
match generator
.internal
.pregen(collector, &generator.initial_nodes)
{
Ok(_status) => Ok(generator),
Err(err) => Err(err),
}
}
/// Returns the `max_retry_count`: how many time the [`Generator`] should retry to generate the [`Grid`] when a contradiction is encountered
pub fn max_retry_count(&self) -> u32 {
self.max_retry_count
}
/// Specifies how many time the [`Generator`] should retry to generate the [`Grid`] when a contradiction is encountered
pub fn set_max_retry_count(&mut self, max_retry_count: u32) {
self.max_retry_count = max_retry_count;
}
/// Returns the seed that was used to initialize the generator RNG for this generation. See [`RngMode`] for more information.
pub fn seed(&self) -> u64 {
self.internal.seed
}
/// Returns the [`Grid`] used by the generator
pub fn grid(&self) -> &G {
&self.internal.grid
}
/// Returns the [`Rules`] used by the generator
pub fn rules(&self) -> &Rules<C> {
&self.internal.rules
}
/// Returns how many nodes are left to generate
pub fn nodes_left(&self) -> usize {
self.internal.nodes_left_to_generate
}
/// Returns a [`GridData`] of [`ModelInstance`] with all the nodes generated if the generation is done
///
/// Returns `None` if the generation is still ongoing or currently failed
pub fn to_grid_data(&self) -> Option<GridData<C, ModelInstance, G>> {
match self.internal.status {
InternalGeneratorStatus::Ongoing => None,
InternalGeneratorStatus::Failed(_) => None,
InternalGeneratorStatus::Done => Some(self.internal.to_grid_data()),
}
}
/// Tries to generate the whole grid. If the generation fails due to a contradiction, it will retry `max_retry_count` times before returning the last encountered [`GeneratorError`]
///
/// If the generation is currently done or failed, calling this method will reinitialize the generator with the next seed before starting the generation.
///
/// If the generation was already started by previous calls to [`Generator::set_and_propagate`] or [`Generator::select_and_propagate`], this will simply continue the current generation.
pub fn generate_grid(
&mut self,
) -> Result<(GenInfo, GridData<C, ModelInstance, G>), GeneratorError> {
let gen_info = self
.internal
.generate(self.max_retry_count, &self.initial_nodes)?;
Ok((gen_info, self.internal.to_grid_data()))
}
/// Same as [`Generator::generate_grid`] but does not return the generated [`ModelInstance`] when successful.
///
/// [`Generator::to_grid_data`] can still be called to retrieve a [`GridData`] afterwards.
pub fn generate(&mut self) -> Result<GenInfo, GeneratorError> {
let gen_info = self
.internal
.generate(self.max_retry_count, &self.initial_nodes)?;
Ok(gen_info)
}
/// Advances the generation by one "step": select a node and a model via the heuristics and propagate the changes.
/// - Returns the [`GenerationStatus`] if the step executed successfully
/// - Returns a [`GeneratorError`] if the generation fails due to a contradiction.
///
/// If the generation is currently done or failed, this method will just return the done or failed status/error.
///
/// **Note**: One call to this method **can** lead to more than one node generated if the propagation phase forces some other node(s) into a definite state (due to only one possible model remaining on a node)
pub fn select_and_propagate(&mut self) -> Result<GenerationStatus, GeneratorError> {
self.internal.select_and_propagate(&mut None)
}
/// Same as [`Generator::select_and_propagate`] but collects and return the generated [`GeneratedNode`] when successful.
pub fn select_and_propagate_collected(
&mut self,
) -> Result<(GenerationStatus, Vec<GeneratedNode>), GeneratorError> {
let mut generated_nodes = Vec::new();
let status = self
.internal
.select_and_propagate(&mut Some(&mut generated_nodes))?;
Ok((status, generated_nodes))
}
/// Tries to set the node referenced by `node_ref` to the model refrenced by `model_variant_ref`. Then tries to propagate the change.
/// - Returns `Ok` and the current [`GenerationStatus`] if successful.
/// - Returns a [`NodeSetError`] if it fails.
///
/// If the generation is currently done or failed, this method will just return the done or failed status/error.
///
/// **Note**: One call to this method **can** lead to more than one node generated if the propagation phase forces some other node(s) into a definite state (due to only one possible model remaining on a node)
pub fn set_and_propagate<N: NodeRef<C, G>, M: ModelVariantRef<C>>(
&mut self,
node_ref: N,
model_variant_ref: M,
memorized: bool,
) -> Result<GenerationStatus, NodeSetError> {
let node_index = node_ref.to_index(&self.internal.grid);
let model_variant_index = model_variant_ref.to_index(&self.internal.rules)?;
let status = self
.internal
.set_and_propagate(node_index, model_variant_index, &mut None)?;
if memorized {
self.initial_nodes.push((node_index, model_variant_index));
}
Ok(status)
}
/// Same as [`Generator::set_and_propagate`] but also returns all the [`GeneratedNode`] generated by this generation operation if successful.
pub fn set_and_propagate_collected<N: NodeRef<C, G>, M: ModelVariantRef<C>>(
&mut self,
node_ref: N,
model_variant_ref: M,
memorized: bool,
) -> Result<(GenerationStatus, Vec<GeneratedNode>), NodeSetError> {
let mut generated_nodes = Vec::new();
let node_index = node_ref.to_index(&self.internal.grid);
let model_variant_index = model_variant_ref.to_index(&self.internal.rules)?;
let status = self.internal.set_and_propagate(
node_index,
model_variant_index,
&mut Some(&mut generated_nodes),
)?;
if memorized {
self.initial_nodes.push((node_index, model_variant_index));
}
Ok((status, generated_nodes))
}
/// Reinitalizes the generator with the next seed (a seed is generated from the current seed)
pub fn reinitialize(&mut self) -> GenerationStatus {
self.internal.reinitialize(&mut None, &self.initial_nodes)
}
/// Same as [`Generator::reinitialize`] but also returns all the [`GeneratedNode`] generated by this generation operation.
pub fn reinitialize_collected(&mut self) -> (GenerationStatus, Vec<GeneratedNode>) {
let mut generated_nodes = Vec::new();
let res = self
.internal
.reinitialize(&mut Some(&mut generated_nodes), &self.initial_nodes);
(res, generated_nodes)
}
/// Returns all the current possible model instances on `node_index`
pub fn get_models_on(&self, node_index: NodeIndex) -> Vec<ModelInstance> {
let mut models = Vec::new();
if !self.internal.is_valid_node_index(node_index) {
return models;
}
for model_variant_index in self.internal.possible_model_indexes(node_index) {
models.push(self.internal.rules.model(model_variant_index).clone());
}
models
}
/// Returns all the current possible model on `node_index` grouped by variations, as well as the total number of possible models
pub fn get_models_variations_on(&self, node_index: NodeIndex) -> (Vec<ModelVariations>, u32) {
let mut model_variations = Vec::new();
let mut total_models_count = 0;
if !self.internal.is_valid_node_index(node_index) {
return (model_variations, total_models_count);
}
let mut id_mapping = HashMap::new();
for model_variant_index in self.internal.possible_model_indexes(node_index) {
total_models_count += 1;
let model = self.internal.rules.model(model_variant_index);
let group_id = id_mapping
.entry(model.model_index)
.or_insert(model_variations.len());
if *group_id == model_variations.len() {
model_variations.push(ModelVariations {
index: model.model_index,
info: self.internal.rules.model_info(model_variant_index),
rotations: vec![model.rotation],
});
} else {
model_variations[*group_id].rotations.push(model.rotation);
}
}
(model_variations, total_models_count)
}
fn create_observer_queue(&mut self) -> crossbeam_channel::Receiver<GenerationUpdate> {
// We can't simply bound to the number of nodes since we might retry some generations. (and send more than number_of_nodes updates)
let (sender, receiver) = crossbeam_channel::unbounded();
self.internal.observers.push(sender);
receiver
}
}
/// Group of models variaitons based on the same input [crate::generator::model::Model] with different rotations
#[derive(Debug, Clone)]
pub struct ModelVariations {
/// Index of the original input model
pub index: ModelIndex,
/// Info about the base model
pub info: ModelInfo,
/// Rotations of the base model
pub rotations: Vec<ModelRotation>,
}
impl fmt::Display for ModelVariations {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.rotations.len() == 1 {
write!(
f,
"id: {}, {}, rotation: {:?}",
self.index, self.info, self.rotations[0]
)
} else {
write!(
f,
"id: {}, {}, rotations: {:?}",
self.index, self.info, self.rotations
)
}
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/ghx_proc_gen/src/generator/builder.rs | ghx_proc_gen/src/generator/builder.rs | use std::{marker::PhantomData, sync::Arc};
use ghx_grid::{
coordinate_system::CoordinateSystem,
grid::{Grid, GridData, NodeRef},
};
use crate::{GeneratorBuilderError, NodeIndex};
use super::{
model::ModelVariantIndex,
node_heuristic::NodeSelectionHeuristic,
observer::{GenerationUpdate, QueuedObserver, QueuedStatefulObserver},
rules::{ModelVariantRef, Rules},
Collector, GeneratedNode, Generator, ModelSelectionHeuristic, RngMode,
};
/// Default retry count for the generator
pub const DEFAULT_RETRY_COUNT: u32 = 50;
/// Internal type used to provide a type-safe builder with compatible [`Grid`] and [`Rules`]
#[derive(Copy, Clone)]
pub struct Set;
/// Internal type used to provide a type-safe builder with compatible [`Grid`] and [`Rules`]
#[derive(Copy, Clone)]
pub struct Unset;
/// Used to instantiate a new [`Generator`].
///
/// [`Rules`] and [`Grid`] are the two non-optionnal structs that are needed before being able to call `build`.
///
/// ### Example
///
/// Create a `Generator` from a `GeneratorBuilder`.
/// ```
/// use ghx_proc_gen::{generator::{builder::GeneratorBuilder, rules::{Rules, RulesBuilder}, socket::{SocketsCartesian2D, SocketCollection}, model::ModelCollection}};
/// use ghx_grid::cartesian::grid::CartesianGrid;
///
/// let mut sockets = SocketCollection::new();
/// let a = sockets.create();
/// sockets.add_connection(a, vec![a]);
///
/// let mut models = ModelCollection::new();
/// models.create(SocketsCartesian2D::Mono(a));
///
/// let rules = RulesBuilder::new_cartesian_2d(models,sockets).build().unwrap();
///
/// let grid = CartesianGrid::new_cartesian_2d(10, 10, false, false);
/// let mut generator = GeneratorBuilder::new()
/// .with_rules(rules)
/// .with_grid(grid)
/// .build();
/// ```
#[derive(Clone)]
pub struct GeneratorBuilder<G, R, C: CoordinateSystem, T: Grid<C>> {
rules: Option<Arc<Rules<C>>>,
grid: Option<T>,
max_retry_count: u32,
node_selection_heuristic: NodeSelectionHeuristic,
model_selection_heuristic: ModelSelectionHeuristic,
rng_mode: RngMode,
observers: Vec<crossbeam_channel::Sender<GenerationUpdate>>,
initial_nodes: Vec<(NodeIndex, ModelVariantIndex)>,
typestate: PhantomData<(G, R)>,
}
impl<C: CoordinateSystem, G: Grid<C>> GeneratorBuilder<Unset, Unset, C, G> {
/// Creates a [`GeneratorBuilder`] with its values set to their default.
pub fn new() -> Self {
Self {
rules: None,
grid: None,
max_retry_count: DEFAULT_RETRY_COUNT,
node_selection_heuristic: NodeSelectionHeuristic::MinimumRemainingValue,
model_selection_heuristic: ModelSelectionHeuristic::WeightedProbability,
rng_mode: RngMode::RandomSeed,
observers: Vec::new(),
initial_nodes: Vec::new(),
typestate: PhantomData,
}
}
}
impl<C: CoordinateSystem, G: Grid<C>> GeneratorBuilder<Unset, Unset, C, G> {
/// Sets the [`Rules`] to be used by the [`Generator`]
pub fn with_rules(self, rules: Rules<C>) -> GeneratorBuilder<Unset, Set, C, G> {
GeneratorBuilder {
rules: Some(Arc::new(rules)),
grid: self.grid,
max_retry_count: self.max_retry_count,
node_selection_heuristic: self.node_selection_heuristic,
model_selection_heuristic: self.model_selection_heuristic,
rng_mode: self.rng_mode,
observers: self.observers,
initial_nodes: self.initial_nodes,
typestate: PhantomData,
}
}
/// Sets the [`Rules`] to be used by the [`Generator`]. The `Generator` will hold a read-only Rc onto those `Rules` which can be safely shared by multiple `Generator`.
pub fn with_shared_rules(self, rules: Arc<Rules<C>>) -> GeneratorBuilder<Unset, Set, C, G> {
GeneratorBuilder {
rules: Some(rules),
grid: self.grid,
max_retry_count: self.max_retry_count,
node_selection_heuristic: self.node_selection_heuristic,
model_selection_heuristic: self.model_selection_heuristic,
rng_mode: self.rng_mode,
observers: self.observers,
initial_nodes: self.initial_nodes,
typestate: PhantomData,
}
}
}
impl<C: CoordinateSystem, G: Grid<C>> GeneratorBuilder<Unset, Set, C, G> {
/// Sets the [`Grid`] to be used by the [`Generator`].
pub fn with_grid(self, grid: G) -> GeneratorBuilder<Set, Set, C, G> {
GeneratorBuilder {
grid: Some(grid),
rules: self.rules,
max_retry_count: self.max_retry_count,
node_selection_heuristic: self.node_selection_heuristic,
model_selection_heuristic: self.model_selection_heuristic,
rng_mode: self.rng_mode,
observers: self.observers,
initial_nodes: self.initial_nodes,
typestate: PhantomData,
}
}
}
impl<G, R, C: CoordinateSystem, T: Grid<C>> GeneratorBuilder<G, R, C, T> {
/// Specifies how many time the [`Generator`] should retry to generate the [`Grid`] when a contradiction is encountered. Set to [`DEFAULT_RETRY_COUNT`] by default.
pub fn with_max_retry_count(mut self, max_retry_count: u32) -> Self {
self.max_retry_count = max_retry_count;
self
}
/// Specifies the [`NodeSelectionHeuristic`] to be used by the [`Generator`]. Defaults to [`NodeSelectionHeuristic::MinimumRemainingValue`].
pub fn with_node_heuristic(mut self, heuristic: NodeSelectionHeuristic) -> Self {
self.node_selection_heuristic = heuristic;
self
}
/// Specifies the [`ModelSelectionHeuristic`] to be used by the [`Generator`]. Defaults to [`ModelSelectionHeuristic::WeightedProbability`].
pub fn with_model_heuristic(mut self, heuristic: ModelSelectionHeuristic) -> Self {
self.model_selection_heuristic = heuristic;
self
}
/// Specifies the [`RngMode`] to be used by the [`Generator`]. Defaults to [`RngMode::RandomSeed`].
pub fn with_rng(mut self, rng_mode: RngMode) -> Self {
self.rng_mode = rng_mode;
self
}
/// Registers some [`NodeIndex`] [`ModelVariantIndex`] pairs to be spawned initially by the [`Generator`]. These nodes will be spawned when the generator reinitializes too.
///
/// See [`GeneratorBuilder::with_initial_nodes`] for a more versatile and easy to use method (at the price of a bit of performances during the method call).
pub fn with_initial_nodes_raw(
mut self,
initial_nodes: Vec<(NodeIndex, ModelVariantIndex)>,
) -> Self {
self.initial_nodes.extend(initial_nodes);
self
}
}
// For functions in this impl, we know that self.grid is `Some` thanks to the typing.
impl<C: CoordinateSystem, R, G: Grid<C>> GeneratorBuilder<Set, R, C, G> {
/// Adds a [`QueuedStatefulObserver`] to the [`Generator`] that will be built, and returns it.
///
/// Adding the observer before building the generator allows the observer to see the nodes than *can* be generated during a generator's initialization.
pub fn add_queued_stateful_observer(&mut self) -> QueuedStatefulObserver<C, G> {
let (sender, receiver) = crossbeam_channel::unbounded();
self.observers.push(sender);
let grid = self.grid.clone().unwrap();
QueuedStatefulObserver::create(receiver, &grid)
}
/// Adds a [`QueuedObserver`] to the [`Generator`] that will be built, and returns it.
///
/// Adding the observer before building the generator allows the observer to see the nodes than *can* be generated during a generator's initialization.
pub fn add_queued_observer(&mut self) -> QueuedObserver {
let (sender, receiver) = crossbeam_channel::unbounded();
self.observers.push(sender);
QueuedObserver::create(receiver)
}
/// Registers [`ModelVariantRef`] from a [`GridData`] to be spawned initially by the [`Generator`]. These nodes will be spawned when the generator reinitializes too.
///
/// See [`GeneratorBuilder::with_initial_grid`] for a more versatile and easy to use method (at the price of a bit of performances during the method call).
pub fn with_initial_grid_raw<M: ModelVariantRef<C>>(
mut self,
data: GridData<C, Option<ModelVariantIndex>, G>,
) -> Result<Self, GeneratorBuilderError> {
let grid = self.grid.as_ref().unwrap();
if grid.total_size() != data.grid().total_size() {
return Err(GeneratorBuilderError::InvalidGridSize(
data.grid().total_size(),
grid.total_size(),
));
} else {
for (node_index, node) in data.iter().enumerate() {
match node {
Some(model_var_index) => {
self.initial_nodes.push((node_index, *model_var_index))
}
None => (),
}
}
Ok(self)
}
}
}
// For functions in this impl, we know that self.rules and self.grid are `Some` thanks to the typing.
impl<C: CoordinateSystem, G: Grid<C>> GeneratorBuilder<Set, Set, C, G> {
/// Registers some [`NodeRef`] [`ModelVariantRef`] pairs to be spawned initially by the [`Generator`]. These nodes will be spawned when the generator reinitializes too.
///
/// See [`GeneratorBuilder::with_initial_nodes_raw`] for a bit more performant but more constrained method. The performance difference only matters during this method call in the `GeneratorBuilder`, during generation all the initial nodes are already converted to their raw format.
pub fn with_initial_nodes<N: NodeRef<C, G>, M: ModelVariantRef<C>>(
mut self,
initial_nodes: Vec<(N, M)>,
) -> Result<Self, GeneratorBuilderError> {
let grid = self.grid.as_ref().unwrap();
let rules = self.rules.as_ref().unwrap();
for (node_ref, model_ref) in initial_nodes {
self.initial_nodes
.push((node_ref.to_index(grid), model_ref.to_index(rules)?));
}
Ok(self)
}
/// Registers [`ModelVariantRef`] from a [`GridData`] to be spawned initially by the [`Generator`]. These nodes will be spawned when the generator reinitializes too.
///
/// See [`GeneratorBuilder::with_initial_grid_raw`] for a bit more performant but more constrained method. The performance difference only matters during this method call in the `GeneratorBuilder`, during generation all the initial nodes are already converted to their raw format.
pub fn with_initial_grid<M: ModelVariantRef<C>>(
mut self,
data: GridData<C, Option<M>, G>,
) -> Result<Self, GeneratorBuilderError> {
let grid = self.grid.as_ref().unwrap();
let rules = self.rules.as_ref().unwrap();
if grid.total_size() != data.grid().total_size() {
return Err(GeneratorBuilderError::InvalidGridSize(
data.grid().total_size(),
grid.total_size(),
));
} else {
for (node_index, node) in data.iter().enumerate() {
match node {
Some(model_ref) => self
.initial_nodes
.push((node_index, model_ref.to_index(rules)?)),
None => (),
}
}
Ok(self)
}
}
/// Instantiates a [`Generator`] as specified by the various builder parameters.
pub fn build(self) -> Result<Generator<C, G>, GeneratorBuilderError> {
self.internal_build(&mut None)
}
/// Instantiates a [`Generator`] as specified by the various builder parameters and return the initially generated nodes if any
pub fn build_collected(
self,
) -> Result<(Generator<C, G>, Vec<GeneratedNode>), GeneratorBuilderError> {
let mut generated_nodes = Vec::new();
let res = self.internal_build(&mut Some(&mut generated_nodes))?;
Ok((res, generated_nodes))
}
fn internal_build(
self,
collector: &mut Collector,
) -> Result<Generator<C, G>, GeneratorBuilderError> {
// We know that self.rules and self.grid are `Some` thanks to the typing.
let rules = self.rules.unwrap();
let grid = self.grid.unwrap();
Ok(Generator::create(
rules,
grid,
self.initial_nodes,
self.max_retry_count,
self.node_selection_heuristic,
self.model_selection_heuristic,
self.rng_mode,
self.observers,
collector,
)?)
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/ghx_proc_gen/src/generator/observer.rs | ghx_proc_gen/src/generator/observer.rs | use super::{model::ModelInstance, GeneratedNode, Generator};
#[cfg(feature = "bevy")]
use bevy::ecs::component::Component;
use ghx_grid::{
coordinate_system::CoordinateSystem,
grid::{Grid, GridData},
};
/// Update sent by a [`crate::generator::Generator`]
#[derive(Clone, Copy, Debug)]
pub enum GenerationUpdate {
/// A node has been generated
Generated(GeneratedNode),
/// The generator is being reinitialized to its initial state, with a new seed.
Reinitializing(u64),
/// The generation failed due to a contradiction at the specified node_index
Failed(usize),
}
/// Observer with a queue of the [`GenerationUpdate`] sent by the [`crate::generator::Generator`] which also maintains a coherent state of the current generation in a [`GridData`]
///
/// Can be used in a different thread than the generator's thread.
#[cfg_attr(feature = "bevy", derive(Component))]
pub struct QueuedStatefulObserver<T: CoordinateSystem, G: Grid<T>> {
grid_data: GridData<T, Option<ModelInstance>, G>,
receiver: crossbeam_channel::Receiver<GenerationUpdate>,
}
impl<T: CoordinateSystem, G: Grid<T>> QueuedStatefulObserver<T, G> {
/// Creates a new [`QueuedStatefulObserver`] for a given [`crate::generator::Generator`]
pub fn new(generator: &mut Generator<T, G>) -> Self {
let receiver = generator.create_observer_queue();
QueuedStatefulObserver::create(receiver, generator.grid())
}
pub(crate) fn create(
receiver: crossbeam_channel::Receiver<GenerationUpdate>,
grid: &G,
) -> Self {
QueuedStatefulObserver {
grid_data: GridData::new(grid.clone(), vec![None; grid.total_size()]),
receiver,
}
}
/// Returns a ref to the observer's [`GridData`]
pub fn grid_data(&self) -> &GridData<T, Option<ModelInstance>, G> {
&self.grid_data
}
/// Updates the internal state of the observer by dequeuing all queued updates.
pub fn dequeue_all(&mut self) {
while let Ok(update) = self.receiver.try_recv() {
match update {
GenerationUpdate::Generated(grid_node) => self
.grid_data
.set(grid_node.node_index, Some(grid_node.model_instance)),
GenerationUpdate::Reinitializing(_) => self.grid_data.reset(None),
GenerationUpdate::Failed(_) => self.grid_data.reset(None),
}
}
}
/// Updates the internal state of the observer by dequeuing 1 queued update.
///
/// Returns [`Some(GenerationUpdate)`] if there was an update to process, else returns `None`.
pub fn dequeue_one(&mut self) -> Option<GenerationUpdate> {
match self.receiver.try_recv() {
Ok(update) => {
match update {
GenerationUpdate::Generated(grid_node) => self
.grid_data
.set(grid_node.node_index, Some(grid_node.model_instance)),
GenerationUpdate::Reinitializing(_) => self.grid_data.reset(None),
GenerationUpdate::Failed(_) => self.grid_data.reset(None),
}
Some(update)
}
Err(_) => None,
}
}
}
/// Observer with just a queue of the [`GenerationUpdate`] sent by the [`crate::generator::Generator`]
///
/// Can be used in a different thread than the generator's thread.
#[cfg_attr(feature = "bevy", derive(Component))]
pub struct QueuedObserver {
receiver: crossbeam_channel::Receiver<GenerationUpdate>,
}
impl QueuedObserver {
/// Creates a new [`QueuedObserver`] for a given [`crate::generator::Generator`]
pub fn new<T: CoordinateSystem, G: Grid<T>>(generator: &mut Generator<T, G>) -> Self {
let receiver = generator.create_observer_queue();
QueuedObserver { receiver }
}
pub(crate) fn create(receiver: crossbeam_channel::Receiver<GenerationUpdate>) -> Self {
Self { receiver }
}
/// Dequeues all queued updates.
///
/// Returns all retrieved [`GenerationUpdate`] in a `Vec`.
/// The `Vec` may be empty if no update was queued.
pub fn dequeue_all(&mut self) -> Vec<GenerationUpdate> {
let mut updates = Vec::new();
while let Ok(update) = self.receiver.try_recv() {
updates.push(update);
}
updates
}
/// Dequeues 1 queued update.
///
/// Returns [`Some(GenerationUpdate)`] if there was an update to process, else returns `None`.
pub fn dequeue_one(&mut self) -> Option<GenerationUpdate> {
match self.receiver.try_recv() {
Ok(update) => Some(update),
Err(_) => None,
}
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/ghx_proc_gen/src/generator/internal_generator.rs | ghx_proc_gen/src/generator/internal_generator.rs | use std::sync::Arc;
use bitvec::{bitvec, order::LocalBits, slice::IterOnes, vec::BitVec};
use ghx_grid::{
coordinate_system::CoordinateSystem,
direction::DirectionTrait,
grid::{Grid, GridData, NodeRef},
};
use ndarray::{Array, Ix3};
use rand::{
distributions::{Distribution, WeightedIndex},
rngs::StdRng,
Rng, SeedableRng,
};
#[cfg(feature = "debug-traces")]
use tracing::{debug, info, trace};
use crate::{GeneratorError, NodeIndex, NodeSetError};
use super::{
model::{ModelInstance, ModelVariantIndex},
node_heuristic::{InternalNodeSelectionHeuristic, NodeSelectionHeuristic},
observer::GenerationUpdate,
rules::Rules,
Collector, GenInfo, GeneratedNode, GenerationStatus, ModelSelectionHeuristic, NodeSetStatus,
RngMode,
};
#[derive(Default, Debug, Clone, Copy)]
pub(crate) enum InternalGeneratorStatus {
/// Generation has not finished.
#[default]
Ongoing,
/// Generation ended succesfully.
Done,
/// Generation failed due to a contradiction.
Failed(GeneratorError),
}
struct PropagationEntry {
node_index: NodeIndex,
model_index: ModelVariantIndex,
}
pub(crate) struct InternalGenerator<C: CoordinateSystem, G: Grid<C>> {
// === Read-only configuration ===
pub(crate) grid: G,
pub(crate) rules: Arc<Rules<C>>,
// === Generation state ===
pub(crate) status: InternalGeneratorStatus,
pub(crate) nodes_left_to_generate: usize,
/// Observers signaled with updates of the nodes.
pub(crate) observers: Vec<crossbeam_channel::Sender<GenerationUpdate>>,
pub(crate) seed: u64,
rng: StdRng,
/// `nodes[node_index * self.rules.models_count() + model_index]` is true (1) if model with index `model_index` is still allowed on node with index `node_index`
nodes: BitVec<usize>,
/// Stores how many models are still possible for a given node
possible_models_counts: Vec<usize>,
node_selection_heuristic: InternalNodeSelectionHeuristic,
model_selection_heuristic: ModelSelectionHeuristic,
// === Constraint satisfaction algorithm data ===
/// Stack of bans to propagate
propagation_stack: Vec<PropagationEntry>,
/// The value at `support_count[node_index][model_index][direction]` represents the number of supports of a `model_index` at `node_index` from `direction`
supports_count: Array<usize, Ix3>,
}
impl<C: CoordinateSystem, G: Grid<C>> InternalGenerator<C, G> {
pub(crate) fn new(
rules: Arc<Rules<C>>,
grid: G,
node_selection_heuristic: NodeSelectionHeuristic,
model_selection_heuristic: ModelSelectionHeuristic,
rng_mode: RngMode,
observers: Vec<crossbeam_channel::Sender<GenerationUpdate>>,
) -> Self {
let models_count = rules.models_count();
let nodes_count = grid.total_size();
let direction_count = grid.directions_count();
let seed = match rng_mode {
RngMode::Seeded(seed) => seed,
RngMode::RandomSeed => rand::thread_rng().gen::<u64>(),
};
let node_selection_heuristic = InternalNodeSelectionHeuristic::from_external(
node_selection_heuristic,
&rules,
grid.total_size(),
);
Self {
grid,
rules,
node_selection_heuristic,
model_selection_heuristic,
rng: StdRng::seed_from_u64(seed),
seed,
status: InternalGeneratorStatus::Ongoing,
nodes: bitvec![1; nodes_count * models_count],
nodes_left_to_generate: nodes_count,
possible_models_counts: vec![models_count; nodes_count],
observers,
propagation_stack: Vec::new(),
supports_count: Array::zeros((nodes_count, models_count, direction_count)),
}
}
}
impl<C: CoordinateSystem, G: Grid<C>> InternalGenerator<C, G> {
#[inline]
fn is_model_possible(&self, node: NodeIndex, model: ModelVariantIndex) -> bool {
self.nodes[node * self.rules.models_count() + model] == true
}
#[inline]
fn get_model_index(&self, node_index: NodeIndex) -> ModelVariantIndex {
self.nodes[node_index * self.rules.models_count()
..node_index * self.rules.models_count() + self.rules.models_count()]
.first_one()
.unwrap_or(0)
}
#[inline]
pub(crate) fn is_valid_node_index(&self, node_index: NodeIndex) -> bool {
node_index < self.possible_models_counts.len()
}
pub(crate) fn possible_model_indexes(
&self,
node_index: NodeIndex,
) -> IterOnes<'_, ModelVariantIndex, LocalBits> {
self.nodes[node_index * self.rules.models_count()
..node_index * self.rules.models_count() + self.rules.models_count()]
.iter_ones()
}
fn check_if_done(&mut self) -> GenerationStatus {
if self.nodes_left_to_generate == 0 {
self.status = InternalGeneratorStatus::Done;
GenerationStatus::Done
} else {
self.status = InternalGeneratorStatus::Ongoing;
GenerationStatus::Ongoing
}
}
fn reset_with_seed(&mut self, seed: u64) {
self.seed = seed;
self.rng = StdRng::seed_from_u64(seed);
self.status = InternalGeneratorStatus::Ongoing;
let nodes_count = self.grid.total_size();
self.nodes = bitvec![1;self.rules.models_count() * nodes_count ];
self.nodes_left_to_generate = nodes_count;
self.possible_models_counts = vec![self.rules.models_count(); nodes_count];
self.propagation_stack = Vec::new();
self.node_selection_heuristic.reinitialize();
}
/// Advances the seed
pub(crate) fn reinitialize(
&mut self,
collector: &mut Collector,
initial_nodes: &Vec<(NodeIndex, ModelVariantIndex)>,
) -> GenerationStatus {
// Gen next seed from current rng
let next_seed = self.rng.gen::<u64>();
self.reset_with_seed(next_seed);
#[cfg(feature = "debug-traces")]
info!(
"Reinitializing generator with seed {}, state was {:?}",
self.seed, self.status
);
for obs in &mut self.observers {
let _ = obs.send(GenerationUpdate::Reinitializing(self.seed));
}
// Since Pre-gen succeeded. The following calls will always succeed.
let _ = self.initialize_supports_count(collector);
self.generate_initial_nodes(collector, initial_nodes)
.unwrap()
}
/// Initialize the supports counts array. This may already start to generate/ban/... some nodes according to the given constraints.
///
/// Returns `Ok` if the initialization went well and sets the internal status to [`InternalGeneratorStatus::Ongoing`] or [`InternalGeneratorStatus::Done`]. Else, sets the internal status to [`InternalGeneratorStatus::Failed`] and returns [`GeneratorError`]
fn initialize_supports_count(
&mut self,
collector: &mut Collector,
) -> Result<GenerationStatus, GeneratorError> {
#[cfg(feature = "debug-traces")]
debug!("Initializing support counts");
let mut neighbours = vec![None; self.grid.directions_count()];
for node in 0..self.grid.total_size() {
// For a given `node`, `neighbours[direction]` will hold the optionnal index of the neighbour node in `direction`
self.grid
.get_neighbours_in_all_directions(node.to_index(&self.grid), &mut neighbours);
for model in 0..self.rules.models_count() {
for direction in self.grid.coord_system().directions() {
let opposite_dir = direction.opposite();
// During initialization, the support count for a model "from" a direction is simply the count of allowed adjacent models when looking in the opposite direction, or 0 for a non-looping border (no neighbour from this direction).
match neighbours[opposite_dir.into()] {
Some(_) => {
let allowed_models_count =
self.rules.allowed_models(model, opposite_dir).len();
self.supports_count[(node, model, (*direction).into())] =
allowed_models_count;
if allowed_models_count == 0 && self.is_model_possible(node, model) {
// Ban model for node since it would 100% lead to a contradiction at some point during the generation.
if let Err(err) = self.ban_model_from_node(node, model, collector) {
self.signal_contradiction(node);
return Err(err);
}
// We don't need to process the remaining directions, iterate on the next model.
break;
}
}
None => self.supports_count[(node, model, (*direction).into())] = 0,
};
}
}
}
// Propagate the potential bans that occurred during initialization
if let Err(err) = self.propagate(collector) {
self.signal_contradiction(err.node_index);
return Err(err);
};
#[cfg(feature = "debug-traces")]
debug!("Support counts initialized successfully");
Ok(self.check_if_done())
}
/// Cannot fail since pre-gen was successful
fn generate_initial_nodes(
&mut self,
collector: &mut Collector,
initial_nodes: &Vec<(NodeIndex, ModelVariantIndex)>,
) -> Result<GenerationStatus, GeneratorError> {
for (node_index, model_variant_index) in initial_nodes.iter() {
if self.possible_models_counts[*node_index] <= 1 {
// This means node_index is already generated. And since pre-gen was successful, we know that it must be set to "model_variant_index" already. We skip this node.
continue;
}
// This cannot fail
match self.unchecked_set_and_propagate(*node_index, *model_variant_index, collector)? {
GenerationStatus::Ongoing => (),
GenerationStatus::Done => return Ok(GenerationStatus::Done),
}
}
Ok(self.check_if_done())
}
pub(crate) fn pregen(
&mut self,
collector: &mut Collector,
initial_nodes: &Vec<(NodeIndex, ModelVariantIndex)>,
) -> Result<GenerationStatus, NodeSetError> {
self.initialize_supports_count(collector)?;
// If done already, we still try to set all nodes and succeed only if initial nodes spawn requests match the already generated nodes.
self.pregen_initial_nodes(collector, initial_nodes)
}
fn pregen_initial_nodes(
&mut self,
collector: &mut Collector,
initial_nodes: &Vec<(NodeIndex, ModelVariantIndex)>,
) -> Result<GenerationStatus, NodeSetError> {
for (node_index, model_variant_index) in initial_nodes.iter() {
match self.check_set_and_propagate_parameters(*node_index, *model_variant_index)? {
NodeSetStatus::AlreadySet => continue,
NodeSetStatus::CanBeSet => (),
}
match self.unchecked_set_and_propagate(*node_index, *model_variant_index, collector)? {
GenerationStatus::Ongoing => (),
GenerationStatus::Done => return Ok(GenerationStatus::Done),
}
}
// We can't be done here, unchecked_set_and_propagate would have seen it.
Ok(GenerationStatus::Ongoing)
}
/// Returns an error if :
/// - node_index is invalid
/// - model_variant_index is invalid
/// - model_variant_index is not possible on node_index
/// Returns [`Ok(NodeSetStatus::CanBeSet)`] if model_variant_index can be generated on node_index and [`Ok(NodeSetStatus::AlreadySet)`] if node_index is already generated to model_variant_index
fn check_set_and_propagate_parameters(
&self,
node_index: NodeIndex,
model_variant_index: ModelVariantIndex,
) -> Result<NodeSetStatus, NodeSetError> {
if model_variant_index > self.rules.models_count() {
return Err(NodeSetError::InvalidModelIndex(model_variant_index));
}
if !self.is_valid_node_index(node_index) {
return Err(NodeSetError::InvalidNodeIndex(node_index));
}
if !self.is_model_possible(node_index, model_variant_index) {
return Err(NodeSetError::IllegalModel(model_variant_index, node_index));
}
if self.possible_models_counts[node_index] <= 1 {
return Ok(NodeSetStatus::AlreadySet);
}
Ok(NodeSetStatus::CanBeSet)
}
pub(crate) fn generate(
&mut self,
retry_count: u32,
initial_nodes: &Vec<(NodeIndex, ModelVariantIndex)>,
) -> Result<GenInfo, GeneratorError> {
let mut last_error = None;
for try_index in 0..=retry_count {
#[cfg(feature = "debug-traces")]
info!("Try n°{}", try_index + 1);
match self.status {
InternalGeneratorStatus::Ongoing => (),
InternalGeneratorStatus::Done | InternalGeneratorStatus::Failed(_) => {
match self.reinitialize(&mut None, initial_nodes) {
GenerationStatus::Ongoing => (),
GenerationStatus::Done => {
return Ok(GenInfo {
try_count: try_index + 1,
})
}
}
}
}
match self.generate_remaining_nodes(&mut None) {
Ok(_) => {
return Ok(GenInfo {
try_count: try_index + 1,
})
}
Err(err) => {
last_error = Some(err);
}
}
}
Err(last_error.unwrap()) // We know that last_err is Some
}
/// Top-level handler of public API calls.
fn generate_remaining_nodes(
&mut self,
collector: &mut Collector,
) -> Result<(), GeneratorError> {
// `nodes_left_to_generate` is an upper limit to the number of iterations. We avoid an unnecessary while loop.
for _i in 0..self.nodes_left_to_generate {
match self.unchecked_select_and_propagate(collector) {
Ok(GenerationStatus::Done) => return Ok(()),
Ok(GenerationStatus::Ongoing) => (),
Err(e) => return Err(e),
};
}
Ok(())
}
/// Top-level handler of public API calls.
pub(crate) fn set_and_propagate(
&mut self,
node_index: NodeIndex,
model_variant_index: ModelVariantIndex,
collector: &mut Collector,
) -> Result<GenerationStatus, NodeSetError> {
match self.status {
InternalGeneratorStatus::Ongoing => (),
InternalGeneratorStatus::Done => return Ok(GenerationStatus::Done),
InternalGeneratorStatus::Failed(err) => return Err(err.into()),
}
match self.check_set_and_propagate_parameters(node_index, model_variant_index)? {
NodeSetStatus::AlreadySet => {
// Nothing to do. We can't be done here
return Ok(GenerationStatus::Ongoing);
}
NodeSetStatus::CanBeSet => (),
}
Ok(self.unchecked_set_and_propagate(node_index, model_variant_index, collector)?)
}
/// Top-level handler of public API calls.
pub(crate) fn select_and_propagate(
&mut self,
collector: &mut Collector,
) -> Result<GenerationStatus, GeneratorError> {
match self.status {
InternalGeneratorStatus::Ongoing => (),
InternalGeneratorStatus::Done => return Ok(GenerationStatus::Done),
InternalGeneratorStatus::Failed(err) => return Err(err),
}
self.unchecked_select_and_propagate(collector)
}
/// - node_index and model_variant_index must be valid
/// - model_variant_index must be possible on node_index
/// - node_index must not be generated yet
/// - Generator internal status must be [InternalGeneratorStatus::Ongoing]
fn unchecked_set_and_propagate(
&mut self,
node_index: NodeIndex,
model_variant_index: ModelVariantIndex,
collector: &mut Collector,
) -> Result<GenerationStatus, GeneratorError> {
#[cfg(feature = "debug-traces")]
debug!(
"Set model {:?} named '{}' for node {} at position {:?}",
self.rules.model(model_variant_index),
self.rules.name_unchecked_str(model_variant_index),
node_index,
self.grid.pos_from_index(node_index)
);
if !self.observers.is_empty() {
self.signal_selection(collector, node_index, model_variant_index);
}
self.handle_selected(node_index, model_variant_index);
if let Err(err) = self.propagate(collector) {
self.signal_contradiction(err.node_index);
return Err(err);
};
Ok(self.check_if_done())
}
fn unchecked_select_and_propagate(
&mut self,
collector: &mut Collector,
) -> Result<GenerationStatus, GeneratorError> {
let node_index = match self
.node_selection_heuristic
.select_node(&self.possible_models_counts, &mut self.rng)
{
Some(index) => index,
None => {
// TODO Here, should not be able to find None anymore.
self.status = InternalGeneratorStatus::Done;
return Ok(GenerationStatus::Done);
}
};
// We found a node not yet generated. "Observe/collapse" the node: select a model for the node
let selected_model_index = self.select_model(node_index);
#[cfg(feature = "debug-traces")]
debug!(
"Heuristics selected model {:?} named '{}' for node {} at position {:?}",
self.rules.model(selected_model_index),
self.rules.name_unchecked_str(selected_model_index),
node_index,
self.grid.pos_from_index(node_index)
);
if !self.observers.is_empty() || collector.is_some() {
self.signal_selection(collector, node_index, selected_model_index);
}
self.handle_selected(node_index, selected_model_index);
if let Err(err) = self.propagate(collector) {
self.signal_contradiction(err.node_index);
return Err(err);
};
Ok(self.check_if_done())
}
/// There should at least be one possible model for this node index. May panic otherwise.
fn select_model(&mut self, node_index: NodeIndex) -> usize {
match self.model_selection_heuristic {
ModelSelectionHeuristic::WeightedProbability => {
let possible_models: Vec<ModelVariantIndex> = (0..self.rules.models_count())
.filter(|&model_index| self.is_model_possible(node_index, model_index))
.collect();
// TODO May cache the current sum of weights at each node.
let weighted_distribution = WeightedIndex::new(
possible_models
.iter()
.map(|&model_index| self.rules.weight_unchecked(model_index)),
)
.unwrap();
possible_models[weighted_distribution.sample(&mut self.rng)]
}
}
}
fn handle_selected(&mut self, node_index: usize, selected_model_index: ModelVariantIndex) {
// Iterate all the possible models because we don't have an easy way to iterate only the models possible at node_index. But we'll filter impossible models right away. TODO: benchmark iter_ones
for model_index in 0..self.rules.models_count() {
if model_index == selected_model_index {
continue;
}
if !self.is_model_possible(node_index, model_index) {
continue;
}
// Enqueue removal for propagation
self.enqueue_removal_to_propagate(node_index, model_index);
// None of these model are possible on this node now, set their support to 0
for dir in 0..self.grid.directions_count() {
self.supports_count[(node_index, model_index, dir)] = 0;
}
}
// Remove eliminated possibilities (after enqueuing the propagation entries because we currently filter on the possible models)
// TODO Remove alias ?
let models_count = self.rules.models_count();
for mut bit in self.nodes
[node_index * models_count..node_index * models_count + models_count]
.iter_mut()
{
*bit = false;
}
self.nodes
.set(node_index * models_count + selected_model_index, true);
self.possible_models_counts[node_index] = 1;
}
/// Returns [`GeneratorError`] if the node has no possible models left. Else, returns `Ok`.
///
/// Does not modify the generator internal status.
///
/// Should only be called a model that is still possible for this node
fn ban_model_from_node(
&mut self,
node_index: usize,
model: usize,
collector: &mut Collector,
) -> Result<(), GeneratorError> {
// Update the supports
for dir in 0..self.grid.directions_count() {
let supports_count = &mut self.supports_count[(node_index, model, dir)];
*supports_count = 0;
}
// Update the state
self.nodes
.set(node_index * self.rules.models_count() + model, false);
let number_of_models_left = &mut self.possible_models_counts[node_index];
*number_of_models_left = number_of_models_left.saturating_sub(1);
self.node_selection_heuristic.handle_ban(
node_index,
model,
self.rules.weight_unchecked(model),
);
#[cfg(feature = "debug-traces")]
trace!(
"Ban model {:?} named '{}' from node {} at position {:?}, {} models left",
self.rules.model(model),
self.rules.name_unchecked_str(model),
node_index,
self.grid.pos_from_index(node_index),
number_of_models_left
);
match *number_of_models_left {
0 => return Err(GeneratorError { node_index }),
1 => {
#[cfg(feature = "debug-traces")]
{
let forced_model = self.get_model_index(node_index);
debug!(
"Previous bans force model {:?} named '{}' for node {} at position {:?}",
self.rules.model(forced_model),
self.rules.name_unchecked_str(model),
node_index,
self.grid.pos_from_index(node_index)
);
}
// Check beforehand to avoid `get_model_index` call
if !self.observers.is_empty() || collector.is_some() {
self.signal_selection(collector, node_index, self.get_model_index(node_index));
}
}
_ => (),
}
// Enqueue removal for propagation
self.enqueue_removal_to_propagate(node_index, model);
Ok(())
}
fn enqueue_removal_to_propagate(&mut self, node_index: usize, model_index: ModelVariantIndex) {
#[cfg(feature = "debug-traces")]
trace!(
"Enqueue removal for propagation: model {:?} named '{}' from node {}",
self.rules.model(model_index),
self.rules.name_unchecked_str(model_index),
node_index
);
self.propagation_stack.push(PropagationEntry {
node_index,
model_index,
});
}
/// Returns [`GeneratorError`] if a node has no possible models left. Else, returns `Ok`.
///
/// Does not modify the generator internal status.
fn propagate(&mut self, collector: &mut Collector) -> Result<(), GeneratorError> {
// Clone the ref to allow for mutability of other members in the interior loops
let rules = Arc::clone(&self.rules);
let mut neighbours = vec![None; self.grid.directions_count()];
while let Some(from) = self.propagation_stack.pop() {
#[cfg(feature = "debug-traces")]
trace!(
"Propagate removal of model {:?} named '{}' for node {}",
self.rules.model(from.model_index),
self.rules.name_unchecked_str(from.model_index),
from.node_index
);
self.grid
.get_neighbours_in_all_directions(from.node_index, &mut neighbours);
for (dir, neighbour) in neighbours.iter().enumerate() {
if let Some(neighbour_index) = neighbour {
// Decrease the support count of all models previously supported by "from"
for &model in rules.allowed_models(from.model_index, dir) {
let supports_count =
&mut self.supports_count[(*neighbour_index, model, dir)];
if *supports_count > 0 {
*supports_count -= 1;
// When we find a model which is now unsupported, we queue a ban
// We check > 0 and for == because we only want to queue the event once.
if *supports_count == 0 {
self.ban_model_from_node(*neighbour_index, model, collector)?;
}
}
}
}
}
}
Ok(())
}
fn signal_selection(
&mut self,
collector: &mut Collector,
node_index: NodeIndex,
model_index: ModelVariantIndex,
) {
let grid_node = GeneratedNode {
node_index,
model_instance: self.rules.model(model_index).clone(),
};
let update = GenerationUpdate::Generated(grid_node);
for obs in &mut self.observers {
let _ = obs.send(update);
}
if let Some(collector) = collector {
collector.push(grid_node);
}
self.nodes_left_to_generate = self.nodes_left_to_generate.saturating_sub(1);
}
fn signal_contradiction(&mut self, node_index: NodeIndex) {
#[cfg(feature = "debug-traces")]
debug!("Generation failed due to a contradiction");
self.status = InternalGeneratorStatus::Failed(GeneratorError { node_index });
for obs in &mut self.observers {
let _ = obs.send(GenerationUpdate::Failed(node_index));
}
}
/// Should only be called when the nodes are fully generated
pub(crate) fn to_grid_data(&self) -> GridData<C, ModelInstance, G> {
let mut generated_nodes = Vec::with_capacity(self.nodes.len());
for node_index in 0..self.grid.total_size() {
let model_index = self.get_model_index(node_index);
generated_nodes.push(self.rules.model(model_index).clone())
}
GridData::new(self.grid.clone(), generated_nodes)
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/ghx_proc_gen/src/generator/node_heuristic.rs | ghx_proc_gen/src/generator/node_heuristic.rs | use ghx_grid::coordinate_system::CoordinateSystem;
use rand::{rngs::StdRng, Rng};
use crate::NodeIndex;
use super::rules::Rules;
/// Defines a heuristic for the choice of a node to generate. For some given Rules, each heuristic will lead to different visual results and different failure rates.
#[derive(Copy, Clone, Debug)]
pub enum NodeSelectionHeuristic {
/// The node with with the minimum count of possible models remaining will be chosen at each selection iteration. If multiple nodes have the same value, a random one is picked.
///s
/// Similar to `MinimumEntropy` when the models have all more or less the same weight.
MinimumRemainingValue,
/// The node with the minimum Shannon entropy (computed from the models weights) will be chosen at each selection iteration. If multiple nodes have the same value, a random one is picked.
///
/// Similar to `MinimumRemainingValue` when the models have all more or less the same weight.
MinimumEntropy,
/// A random node with no special features (except not being generated yet) will be chosen at each selection iteration.
///
/// Often causes a **very high generation failure rate**, except for very simple rules.
Random,
}
const MAX_NOISE_VALUE: f32 = 1E-2;
/// Defines a heuristic for the choice of a node to generate.
pub(crate) enum InternalNodeSelectionHeuristic {
MinimumRemainingValue,
MinimumEntropy {
/// Initial value of entropy data for any node
initial_node_entropy_data: NodeEntropyData,
/// Current entropy data for a given node
node_entropies: Vec<NodeEntropyData>,
/// Value of `weight * log(weight)` for a given model
models_weight_log_weights: Vec<f32>,
},
Random,
}
#[derive(Clone, Copy)]
pub(crate) struct NodeEntropyData {
/// Shannon entropy of the node
entropy: f32,
/// Sum of the weights of the models still possible on the node
weight_sum: f32,
/// Sum of `weight * log(weight)` of the models still possible on the node
weight_log_weight_sum: f32,
}
impl NodeEntropyData {
fn new(weight_sum: f32, weight_log_weight_sum: f32) -> Self {
Self {
entropy: entropy(weight_sum, weight_log_weight_sum),
weight_sum,
weight_log_weight_sum,
}
}
pub(crate) fn entropy(&self) -> f32 {
self.entropy
}
}
fn entropy(weight_sum: f32, weight_log_weight_sum: f32) -> f32 {
f32::ln(weight_sum) - weight_log_weight_sum / weight_sum
}
impl InternalNodeSelectionHeuristic {
pub(crate) fn from_external<T: CoordinateSystem + Clone>(
heuristic: NodeSelectionHeuristic,
rules: &Rules<T>,
node_count: usize,
) -> Self {
match heuristic {
NodeSelectionHeuristic::MinimumRemainingValue => {
InternalNodeSelectionHeuristic::MinimumRemainingValue
}
NodeSelectionHeuristic::Random => InternalNodeSelectionHeuristic::Random,
NodeSelectionHeuristic::MinimumEntropy => {
InternalNodeSelectionHeuristic::new_minimum_entropy(rules, node_count)
}
}
}
fn new_minimum_entropy<T: CoordinateSystem + Clone>(
rules: &Rules<T>,
node_count: usize,
) -> InternalNodeSelectionHeuristic {
let mut models_weight_log_weights = Vec::with_capacity(rules.models_count());
let mut all_models_weight_sum = 0.;
let mut all_models_weight_log_weight_sum = 0.;
for model_index in 0..rules.models_count() {
let weight = rules.weight_unchecked(model_index);
let weight_log_weight = weight * f32::ln(weight);
models_weight_log_weights.push(weight_log_weight);
all_models_weight_sum += weight;
all_models_weight_log_weight_sum += weight_log_weight;
}
let initial_node_entropy_data =
NodeEntropyData::new(all_models_weight_sum, all_models_weight_log_weight_sum);
InternalNodeSelectionHeuristic::MinimumEntropy {
initial_node_entropy_data,
node_entropies: vec![initial_node_entropy_data; node_count],
models_weight_log_weights,
}
}
pub(crate) fn reinitialize(&mut self) {
match self {
InternalNodeSelectionHeuristic::MinimumEntropy {
initial_node_entropy_data,
node_entropies,
models_weight_log_weights: _,
} => {
// `models_weight_log_weights` does not change. We just reset the nodes
for node_entropy in node_entropies {
*node_entropy = *initial_node_entropy_data;
}
}
_ => (),
}
}
pub(crate) fn handle_ban(&mut self, node_index: NodeIndex, model_index: usize, weight: f32) {
match self {
InternalNodeSelectionHeuristic::MinimumEntropy {
initial_node_entropy_data: _,
node_entropies,
models_weight_log_weights,
} => {
let node_entropy = &mut node_entropies[node_index];
node_entropy.weight_sum -= weight;
node_entropy.weight_log_weight_sum -= models_weight_log_weights[model_index];
node_entropy.entropy =
entropy(node_entropy.weight_sum, node_entropy.weight_log_weight_sum)
}
_ => (),
}
}
/// Picks a node according to the heuristic
pub(crate) fn select_node(
&self,
possible_models_counts: &Vec<usize>,
rng: &mut StdRng,
) -> Option<NodeIndex> {
match self {
InternalNodeSelectionHeuristic::MinimumRemainingValue => {
let mut min = f32::MAX;
let mut picked_node = None;
for (index, &possibilities_count) in possible_models_counts.iter().enumerate() {
// If the node is not generated yet (multiple possibilities)
if possibilities_count > 1 {
// Noise added to models count so that when evaluating multiples candidates with the same value, we pick a random one, not in the evaluation order.
let noise = MAX_NOISE_VALUE * rng.gen::<f32>();
if (possibilities_count as f32 + noise) < min {
min = possibilities_count as f32 + noise;
picked_node = Some(index);
}
}
}
picked_node
}
InternalNodeSelectionHeuristic::MinimumEntropy {
initial_node_entropy_data: _,
node_entropies,
models_weight_log_weights: _,
} => {
let mut min = f32::MAX;
let mut picked_node = None;
for (index, &possibilities_count) in possible_models_counts.iter().enumerate() {
let entropy = node_entropies[index].entropy();
if possibilities_count > 1 && entropy < min {
let noise = MAX_NOISE_VALUE * rng.gen::<f32>();
if (entropy + noise) < min {
min = entropy + noise;
picked_node = Some(index);
}
}
}
picked_node
}
InternalNodeSelectionHeuristic::Random => {
let mut picked_node = None;
let mut candidates = Vec::new();
for (index, &possibilities_count) in possible_models_counts.iter().enumerate() {
if possibilities_count > 1 {
candidates.push(index);
}
}
if candidates.len() > 0 {
picked_node = Some(candidates[rng.gen_range(0..candidates.len())]);
}
picked_node
}
}
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/ghx_proc_gen/src/generator/model.rs | ghx_proc_gen/src/generator/model.rs | use std::{borrow::Cow, collections::HashSet, fmt, marker::PhantomData};
use ghx_grid::{
cartesian::coordinates::{Cartesian2D, Cartesian3D},
coordinate_system::CoordinateSystem,
direction::{Direction, DirectionTrait},
};
#[cfg(feature = "debug-traces")]
use tracing::warn;
#[cfg(feature = "bevy")]
use bevy::ecs::component::Component;
#[cfg(feature = "reflect")]
use bevy::{ecs::reflect::ReflectComponent, reflect::Reflect};
use super::{
rules::CARTESIAN_2D_ROTATION_AXIS,
socket::{Socket, SocketId, SocketsCartesian2D, SocketsCartesian3D},
};
/// Index of an original model
pub type ModelIndex = usize;
/// Index of a model variation
pub type ModelVariantIndex = usize;
/// Default weight of [`Model`] and [`ModelTemplate`]
pub const DEFAULT_MODEL_WEIGHT: f32 = 1.0;
#[derive(Clone, Debug)]
/// Most of the information about a [`Model`] (but notably without any [`ModelIndex`]).
///
/// Can be used to create common shared templates before creating real models through a [`ModelCollection`]
pub struct ModelTemplate<C> {
/// Allowed connections for this [`ModelTemplate`] in the output.
sockets: Vec<Vec<Socket>>,
/// Weight factor influencing the density of this [`ModelTemplate`] in the generated output.
///
/// Defaults to [`DEFAULT_MODEL_WEIGHT`]
weight: f32,
/// Allowed rotations of this [`ModelTemplate`] in the output, around the rotation axis specified in the rules.
///
/// Defaults to only [`ModelRotation::Rot0`].
///
/// Notes:
/// - In 3d, sockets of a model that are on the rotation axis are rotated into new sockets when the model itself is rotated. See [`crate::generator::socket::SocketCollection`] for how to define and/or constrain sockets connections on the rotation axis.
/// - In 2d, the rotation axis cannot be modified and is set to [`Direction::ZForward`].
allowed_rotations: HashSet<ModelRotation>,
typestate: PhantomData<C>,
}
impl ModelTemplate<Cartesian3D> {
pub(crate) fn new(sockets: SocketsCartesian3D) -> ModelTemplate<Cartesian3D> {
Self {
sockets: sockets.into(),
allowed_rotations: HashSet::from([ModelRotation::Rot0]),
weight: DEFAULT_MODEL_WEIGHT,
typestate: PhantomData,
}
}
/// Returns a clone of the [`Model`] with its sockets rotated by `rotation` around `axis`.
pub fn rotated(&self, rotation: ModelRotation, axis: Direction) -> Self {
Self {
sockets: self.rotated_sockets(rotation, axis),
weight: self.weight,
allowed_rotations: self.allowed_rotations.clone(),
typestate: PhantomData,
}
}
}
impl ModelTemplate<Cartesian2D> {
pub(crate) fn new(sockets: SocketsCartesian2D) -> ModelTemplate<Cartesian2D> {
Self {
sockets: sockets.into(),
allowed_rotations: HashSet::from([ModelRotation::Rot0]),
weight: DEFAULT_MODEL_WEIGHT,
typestate: PhantomData,
}
}
/// Returns a clone of the [`Model`] with its sockets rotated by `rotation` around [`CARTESIAN_2D_ROTATION_AXIS`].
pub fn rotated(&self, rotation: ModelRotation) -> Self {
Self {
sockets: self.rotated_sockets(rotation, CARTESIAN_2D_ROTATION_AXIS),
weight: self.weight,
allowed_rotations: self.allowed_rotations.clone(),
typestate: PhantomData,
}
}
}
impl<C: CoordinateSystem> ModelTemplate<C> {
/// Specify that this [`ModelTemplate`] can be rotated in exactly one way: `rotation`
///
/// Rotations are specified as counter-clockwise
pub fn with_rotation(mut self, rotation: ModelRotation) -> Self {
self.allowed_rotations = HashSet::from([rotation]);
self
}
/// Specify that this [`ModelTemplate`] can be rotated by `rotation`, in addition to its currently allowed rotations.
///
/// Rotations are specified as counter-clockwise
pub fn with_additional_rotation(mut self, rotation: ModelRotation) -> Self {
self.allowed_rotations.insert(rotation);
self
}
/// Specify that this [`ModelTemplate`] can be rotated in every way specified in `rotations`.
///
/// Rotations are specified as counter-clockwise
pub fn with_rotations<R: Into<HashSet<ModelRotation>>>(mut self, rotations: R) -> Self {
self.allowed_rotations = rotations.into();
self
}
/// Specify that this [`ModelTemplate`] can be rotated in every way specified in `rotations` in addition to its currently allowed rotations.
///
/// Rotations are specified as counter-clockwise
pub fn with_additional_rotations<R: IntoIterator<Item = ModelRotation>>(
mut self,
rotations: R,
) -> Self {
self.allowed_rotations.extend(rotations.into_iter());
self
}
/// Specify that this [`ModelTemplate`] can be rotated in every way.
///
/// Rotations are specified as counter-clockwise
pub fn with_all_rotations(mut self) -> Self {
self.allowed_rotations = ALL_MODEL_ROTATIONS.iter().cloned().collect();
self
}
/// Specify this [`ModelTemplate`] weight. The `weight` value should be strictly superior to `0`. If it is not the case, the value will be overriden by `f32::MIN_POSITIVE`.
///
/// Used by a [`super::Generator`] when using [`super::ModelSelectionHeuristic::WeightedProbability`] and [`super::node_heuristic::NodeSelectionHeuristic::MinimumEntropy`].
///
/// All the variations (rotations) of this [`ModelTemplate`] will use the same weight.
pub fn with_weight<W: Into<f32>>(mut self, weight: W) -> Self {
let mut checked_weight = weight.into();
if checked_weight <= 0. {
#[cfg(feature = "debug-traces")]
warn!(
"Template had an invalid weight {} <= 0., weight overriden to f32::MIN: {}",
checked_weight,
f32::MIN_POSITIVE
);
checked_weight = f32::MIN_POSITIVE
};
self.weight = checked_weight;
self
}
fn rotated_sockets(&self, rotation: ModelRotation, rot_axis: C::Direction) -> Vec<Vec<Socket>> {
let mut rotated_sockets = vec![Vec::new(); self.sockets.len()];
// Not pretty: if the node sockets contain the rotation axis
if self.sockets.len() > rot_axis.into() {
// Sockets on the rotation axis are marked as rotated
for fixed_axis in [rot_axis, rot_axis.opposite()] {
rotated_sockets[fixed_axis.into()].extend(self.sockets[fixed_axis.into()].clone());
for socket in &mut rotated_sockets[fixed_axis.into()] {
socket.rotate(rotation);
}
}
}
let basis = rot_axis.rotation_basis();
let mut rotated_basis = basis.to_vec();
rotated_basis.rotate_right(rotation.index() as usize);
for i in 0..basis.len() {
rotated_sockets[basis[i].into()].extend(self.sockets[rotated_basis[i].into()].clone());
}
rotated_sockets
}
}
/// Used to create one or more [`Model`]. Created models can then be used in a [`super::rules::RulesBuilder`]
#[derive(Clone)]
pub struct ModelCollection<C: CoordinateSystem> {
models: Vec<Model<C>>,
}
impl<C: CoordinateSystem> ModelCollection<C> {
/// Creates a new [`ModelCollection`]
pub fn new() -> Self {
Self { models: Vec::new() }
}
/// Creates a new [`Model`] in this collection and returns a reference to it.
///
/// It can create a model from any type that can be turned into a [`ModelTemplate`]: sockets, a model template, or even another model.
pub fn create<T: Into<ModelTemplate<C>>>(&mut self, template: T) -> &mut Model<C> {
let model = Model::<C>::from_template(template.into(), self.models.len());
self.models.push(model);
self.models.last_mut().unwrap()
}
/// Returns how many [`Model`] are in this collection
pub fn models_count(&self) -> usize {
self.models.len()
}
/// Returns an iterator over all models in the collection
pub fn models(&self) -> std::slice::Iter<'_, Model<C>> {
self.models.iter()
}
/// Returns a mutable iterator over all models in the collection
pub fn models_mut(&mut self) -> std::slice::IterMut<'_, Model<C>> {
self.models.iter_mut()
}
/// Returns the last model in the colleciton if any
pub fn last(&self) -> Option<&Model<C>> {
self.models.last()
}
/// Returns the last model in the colleciton as mutable if any
pub fn last_mut(&mut self) -> Option<&mut Model<C>> {
self.models.last_mut()
}
pub(crate) fn create_variations(&self, rotation_axis: C::Direction) -> Vec<ModelVariation> {
let mut model_variations = Vec::new();
for model in self.models.iter() {
// Iterate on a vec of all possible node rotations and filter with the set to have a deterministic insertion order of model variations.
for rotation in ALL_MODEL_ROTATIONS {
if model.template.allowed_rotations.contains(&rotation) {
let rotated_sockets = model.template.rotated_sockets(*rotation, rotation_axis);
model_variations.push(ModelVariation {
sockets: rotated_sockets
.iter()
.map(|dir| dir.iter().map(|s| s.id()).collect())
.collect(),
weight: model.template.weight,
original_index: model.index,
rotation: *rotation,
#[cfg(feature = "models-names")]
name: model.name.clone(),
});
}
}
}
model_variations
}
}
/// Represents a model to be used by a [`crate::generator::Generator`] as a "building-block" to fill out the generated area.
#[derive(Clone, Debug)]
pub struct Model<C: CoordinateSystem> {
index: ModelIndex,
template: ModelTemplate<C>,
/// Name given to this model for debug purposes.
#[cfg(feature = "models-names")]
name: Option<Cow<'static, str>>,
}
impl<C: CoordinateSystem> Model<C> {
pub(crate) fn from_template(template: ModelTemplate<C>, index: ModelIndex) -> Model<C> {
Self {
index,
template,
#[cfg(feature = "models-names")]
name: None,
}
}
/// Returns the [`ModelIndex`] of the model
pub fn index(&self) -> ModelIndex {
self.index
}
/// Specify that this [`Model`] can be rotated in exactly one way: `rotation`
///
/// Rotations are specified as counter-clockwise
pub fn with_rotation(&mut self, rotation: ModelRotation) -> &mut Self {
self.template.allowed_rotations = HashSet::from([rotation]);
self
}
/// Specify that this [`Model`] can be rotated by `rotation`, in addition to its currently allowed rotations.
///
/// Rotations are specified as counter-clockwise
pub fn with_additional_rotation(&mut self, rotation: ModelRotation) -> &mut Self {
self.template.allowed_rotations.insert(rotation);
self
}
/// Specify that this [`Model`] can be rotated in every way specified in `rotations`.
///
/// Rotations are specified as counter-clockwise
pub fn with_rotations<R: Into<HashSet<ModelRotation>>>(&mut self, rotations: R) -> &mut Self {
self.template.allowed_rotations = rotations.into();
self
}
/// Specify that this [`Model`] can be rotated in every way specified in `rotations` in addition to its currently allowed rotations.
///
/// Rotations are specified as counter-clockwise
pub fn with_additional_rotations<R: IntoIterator<Item = ModelRotation>>(
&mut self,
rotations: R,
) -> &mut Self {
self.template
.allowed_rotations
.extend(rotations.into_iter());
self
}
/// Specify that this [`Model`] can be rotated in every way.
///
/// Rotations are specified as counter-clockwise
pub fn with_all_rotations(&mut self) -> &mut Self {
self.template.allowed_rotations = ALL_MODEL_ROTATIONS.iter().cloned().collect();
self
}
/// Specify this [`Model`] weight. The `weight` value should be strictly superior to `0`. If it is not the case, the value will be overriden by `f32::MIN_POSITIVE`.
///
/// Used by a [`super::Generator`] when using [`super::ModelSelectionHeuristic::WeightedProbability`] and [`super::node_heuristic::NodeSelectionHeuristic::MinimumEntropy`].
///
/// All the variations (rotations) of this [`Model`] will use the same weight.
pub fn with_weight<W: Into<f32>>(&mut self, weight: W) -> &mut Self {
let mut checked_weight = weight.into();
if checked_weight <= 0. {
#[cfg(feature = "debug-traces")]
warn!(
"Model with index {}, name {:?}, had an invalid weight {} <= 0., weight overriden to f32::MIN: {}",
self.index, self.name, checked_weight, f32::MIN_POSITIVE
);
checked_weight = f32::MIN_POSITIVE
};
self.template.weight = checked_weight;
self
}
#[allow(unused_mut)]
/// Register the given name for this model.
///
/// Does nothing if the `models-names` feature is not enabled.
pub fn with_name(&mut self, _name: impl Into<Cow<'static, str>>) -> &mut Self {
#[cfg(feature = "models-names")]
{
self.name = Some(_name.into());
}
self
}
pub(crate) fn first_rot(&self) -> ModelRotation {
for rot in ALL_MODEL_ROTATIONS {
if self.template.allowed_rotations.contains(rot) {
return *rot;
}
}
ModelRotation::Rot0
}
/// Creates a model instance from this model
pub fn instance(&self) -> ModelInstance {
ModelInstance {
model_index: self.index,
rotation: self.first_rot(),
}
}
}
impl<C: CoordinateSystem> Into<ModelTemplate<C>> for Model<C> {
fn into(self) -> ModelTemplate<C> {
self.template.clone()
}
}
/// This is a variation of a user [`Model`] generated by the [`crate::generator::Rules`]. One [`Model`] may be transformed into one ore more [`ModelVariation`] depending on the number of allowed rotations of the model.
#[derive(Debug)]
pub struct ModelVariation {
/// Allowed connections for this [`Model`] in the output
sockets: Vec<Vec<SocketId>>,
/// Weight factor influencing the density of this [`Model`] in the generated output. Defaults to 1
weight: f32,
/// Index of the [`Model`] this was expanded from
original_index: ModelIndex,
/// Rotation of the [`Model`]
rotation: ModelRotation,
/// Debug name for this model
#[cfg(feature = "models-names")]
pub name: Option<Cow<'static, str>>,
}
impl ModelVariation {
/// Return the sockets of the model
pub fn sockets(&self) -> &Vec<Vec<SocketId>> {
&self.sockets
}
/// Returns the weight of the model
pub fn weight(&self) -> f32 {
self.weight
}
/// Returns the index of the [`Model`] this model was expanded from
pub fn original_index(&self) -> ModelIndex {
self.original_index
}
/// Returns the rotation applied to the original [``Model`] this model was expanded from
pub fn rotation(&self) -> ModelRotation {
self.rotation
}
pub(crate) fn to_instance(&self) -> ModelInstance {
ModelInstance {
model_index: self.original_index,
rotation: self.rotation,
}
}
}
/// Used to identify a specific variation of an input model.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "bevy", derive(Component, Default))]
#[cfg_attr(feature = "reflect", derive(Reflect), reflect(Component))]
pub struct ModelInstance {
/// Index of the original [`Model`]
pub model_index: ModelIndex,
/// Rotation of the original [`Model`]
pub rotation: ModelRotation,
}
impl fmt::Display for ModelInstance {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "id: {}, rot: {}", self.model_index, self.rotation)
}
}
/// Represents a rotation around an Axis, in the trigonometric(counterclockwise) direction
#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "bevy", derive(Component))]
#[cfg_attr(feature = "reflect", derive(Reflect), reflect(Component))]
pub enum ModelRotation {
/// Rotation of 0°
#[default]
Rot0,
/// Rotation of 90°
Rot90,
/// Rotation of 180°
Rot180,
/// Rotation of 270°
Rot270,
}
impl fmt::Display for ModelRotation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value())
}
}
impl ModelRotation {
/// Returns the value of the rotation in °(degrees).
pub fn value(&self) -> u32 {
match *self {
ModelRotation::Rot0 => 0,
ModelRotation::Rot90 => 90,
ModelRotation::Rot180 => 180,
ModelRotation::Rot270 => 270,
}
}
/// Returns the value of the rotation in radians.
pub fn rad(&self) -> f32 {
f32::to_radians(self.value() as f32)
}
/// Returns the index of the enum member in the enumeration.
pub fn index(&self) -> u8 {
match *self {
ModelRotation::Rot0 => 0,
ModelRotation::Rot90 => 1,
ModelRotation::Rot180 => 2,
ModelRotation::Rot270 => 3,
}
}
#[inline]
/// Returns a new [`ModelRotation`] equal to this rotation rotated by `rotation` counter-clock
///
/// ### Example
/// ```
/// use ghx_proc_gen::generator::model::ModelRotation;
///
/// let rot_90 = ModelRotation::Rot90;
/// assert_eq!(rot_90.rotated(ModelRotation::Rot180), ModelRotation::Rot270);
/// ```
pub fn rotated(&self, rotation: ModelRotation) -> ModelRotation {
ALL_MODEL_ROTATIONS
[(self.index() as usize + rotation.index() as usize) % ALL_MODEL_ROTATIONS.len()]
}
#[inline]
/// Modifies this rotation by rotating it by `rotation` counter-clock
///
/// ### Example
/// ```
/// use ghx_proc_gen::generator::model::ModelRotation;
///
/// let mut rot = ModelRotation::Rot90;
/// rot.rotate(ModelRotation::Rot180);
/// assert_eq!(rot, ModelRotation::Rot270);
/// ```
pub fn rotate(&mut self, rotation: ModelRotation) {
*self = self.rotated(rotation);
}
#[inline]
/// Returns the next [`ModelRotation`]: this rotation rotated by 90° counter-clockwise.
///
/// ### Example
/// ```
/// use ghx_proc_gen::generator::model::ModelRotation;
///
/// let rot_90 = ModelRotation::Rot90;
/// let rot_180 = rot_90.next();
/// assert_eq!(rot_180, ModelRotation::Rot180);
/// ```
pub fn next(&self) -> ModelRotation {
self.rotated(ModelRotation::Rot90)
}
}
/// All the possible rotations for a [`Model`]
pub const ALL_MODEL_ROTATIONS: &'static [ModelRotation] = &[
ModelRotation::Rot0,
ModelRotation::Rot90,
ModelRotation::Rot180,
ModelRotation::Rot270,
];
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/ghx_proc_gen/src/generator/rules.rs | ghx_proc_gen/src/generator/rules.rs | use std::{
collections::{BTreeSet, HashMap, HashSet},
fmt,
marker::PhantomData,
};
use ghx_grid::{
cartesian::coordinates::{Cartesian2D, Cartesian3D},
coordinate_system::CoordinateSystem,
direction::{Direction, DirectionTrait},
};
use ndarray::{Array, Ix1, Ix2};
#[cfg(feature = "models-names")]
use std::borrow::Cow;
#[cfg(feature = "debug-traces")]
use tracing::trace;
#[cfg(feature = "bevy")]
use bevy::ecs::component::Component;
#[cfg(feature = "reflect")]
use bevy::{ecs::reflect::ReflectComponent, reflect::Reflect};
use super::{
model::{
Model, ModelCollection, ModelIndex, ModelInstance, ModelRotation, ModelVariantIndex,
ALL_MODEL_ROTATIONS,
},
socket::SocketCollection,
};
use crate::{NodeSetError, RulesBuilderError};
/// Rotation axis in a 2D cartesian coordinate system
pub const CARTESIAN_2D_ROTATION_AXIS: Direction = Direction::ZForward;
/// Used to create new [`Rules`]
pub struct RulesBuilder<C: CoordinateSystem> {
models: ModelCollection<C>,
socket_collection: SocketCollection,
rotation_axis: C::Direction,
coord_system: C,
}
impl RulesBuilder<Cartesian2D> {
/// Used to create Rules for a 2d cartesian grid.
///
/// ### Example
///
/// Create simple `Rules` for a chess-like pattern
/// ```
/// use ghx_proc_gen::{generator::{socket::{SocketsCartesian2D, SocketCollection}, rules::{Rules, RulesBuilder}, model::ModelCollection}};
/// use ghx_grid::cartesian::coordinates::Cartesian2D;
///
/// let mut sockets = SocketCollection::new();
/// let (white, black) = (sockets.create(), sockets.create());
/// sockets.add_connection(white, vec![black]);
///
/// let mut models = ModelCollection::<Cartesian2D>::new();
/// models.create(SocketsCartesian2D::Mono(white));
/// models.create(SocketsCartesian2D::Mono(black));
///
/// let rules = RulesBuilder::new_cartesian_2d(models, sockets).build().unwrap();
/// ```
pub fn new_cartesian_2d(
models: ModelCollection<Cartesian2D>,
socket_collection: SocketCollection,
) -> Self {
Self {
models,
socket_collection,
rotation_axis: CARTESIAN_2D_ROTATION_AXIS,
coord_system: Cartesian2D,
}
}
}
impl RulesBuilder<Cartesian3D> {
/// Used to create Rules for a 3d cartesian grid.
///
/// ### Example
///
/// Create simple `Rules` to describe an empty room with variable length pillars (with Y up in a right-handed coordinate system).
/// ```
/// use ghx_grid::cartesian::coordinates::{Cartesian2D, Cartesian3D};
/// use ghx_proc_gen::generator::{socket::{SocketsCartesian3D, SocketCollection}, rules::{Rules, RulesBuilder}, model::ModelCollection};
///
/// let mut sockets = SocketCollection::new();
/// let void = sockets.create();
/// let (pillar_base_top, pillar_core_bottom, pillar_core_top, pillar_cap_bottom) = (sockets.create(), sockets.create(), sockets.create(), sockets.create());
///
/// let mut models = ModelCollection::new();
/// models.create(SocketsCartesian3D::Mono(void));
/// models.create(SocketsCartesian3D::Simple {
/// x_pos: void,
/// x_neg: void,
/// z_pos: void,
/// z_neg: void,
/// y_pos: pillar_base_top,
/// y_neg: void,
/// });
/// models.create(SocketsCartesian3D::Simple {
/// x_pos: void,
/// x_neg: void,
/// z_pos: void,
/// z_neg: void,
/// y_pos: pillar_core_top,
/// y_neg: pillar_core_bottom,
/// });
/// models.create(SocketsCartesian3D::Simple {
/// x_pos: void,
/// x_neg: void,
/// z_pos: void,
/// z_neg: void,
/// y_pos: void,
/// y_neg: pillar_cap_bottom,
/// });
///
/// sockets.add_connections(vec![
/// (void, vec![void]),
/// (pillar_base_top, vec![pillar_core_bottom]),
/// (pillar_core_top, vec![pillar_core_bottom, pillar_cap_bottom]),
/// ]);
/// let rules = RulesBuilder::new_cartesian_3d(models, sockets).build().unwrap();
/// ```
pub fn new_cartesian_3d(
models: ModelCollection<Cartesian3D>,
socket_collection: SocketCollection,
) -> Self {
Self {
models,
socket_collection,
rotation_axis: Direction::YForward,
coord_system: Cartesian3D,
}
}
}
impl RulesBuilder<Cartesian3D> {
/// Sets the [`Direction`] to be used in the [`Rules`] as the rotation axis for the models
pub fn with_rotation_axis(mut self, rotation_axis: Direction) -> RulesBuilder<Cartesian3D> {
self.rotation_axis = rotation_axis;
self
}
}
impl<C: CoordinateSystem> RulesBuilder<C> {
/// Builds the [`Rules`] from the current configuration of the [`RulesBuilder`]
///
/// May return [`crate::RulesBuilderError::NoModelsOrSockets`] if `models` or `socket_collection` are empty.
pub fn build(self) -> Result<Rules<C>, RulesBuilderError> {
Rules::new(
self.models,
self.socket_collection,
self.rotation_axis,
self.coord_system,
)
}
}
/// Information about a Model
#[derive(Clone, Debug)]
#[cfg_attr(feature = "bevy", derive(Component, Default))]
#[cfg_attr(feature = "reflect", derive(Reflect), reflect(Component))]
pub struct ModelInfo {
/// Weight of the original [`Model`]
pub weight: f32,
/// Name given to the original [`Model`]
#[cfg(feature = "models-names")]
pub name: Cow<'static, str>,
}
impl fmt::Display for ModelInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "w: {}", self.weight)?;
#[cfg(feature = "models-names")]
write!(f, ", {}", self.name)
}
}
/// Defines the rules of a generation: the coordinate system, the models, the way they can be rotated, the sockets and their connections.
///
/// A same set of [`Rules`] can be shared by multiple generators.
#[cfg_attr(feature = "bevy", derive(Component))]
pub struct Rules<C: CoordinateSystem> {
/// Number of original input models used to build these rules.
original_models_count: usize,
/// Maps a [`super::model::ModelIndex`] and a [`super::model::ModelRotation`] to an optionnal corresponding [`ModelVariantIndex`]
models_mapping: Array<Option<ModelVariantIndex>, Ix2>,
/// All the model variations in this ruleset.
///
/// This is expanded from a given collection of base models, with added variations of rotations around an axis.
models: Vec<ModelInstance>,
weights: Vec<f32>,
#[cfg(feature = "models-names")]
names: Vec<Option<Cow<'static, str>>>,
/// The vector `allowed_neighbours[model_index][direction]` holds all the allowed adjacent models (indexes) to `model_index` in `direction`.
///
/// Calculated from models variations.
///
/// Note: this cannot be a simple 3d array since the third dimension is different for each element.
allowed_neighbours: Array<Vec<usize>, Ix2>,
typestate: PhantomData<C>,
}
impl<C: CoordinateSystem> Rules<C> {
fn new(
models: ModelCollection<C>,
socket_collection: SocketCollection,
rotation_axis: C::Direction,
coord_system: C,
) -> Result<Rules<C>, RulesBuilderError> {
let original_models_count = models.models_count();
let mut model_variations = models.create_variations(rotation_axis);
// We test the expanded models because a model may have no rotations allowed.
if model_variations.len() == 0 || socket_collection.is_empty() {
return Err(RulesBuilderError::NoModelsOrSockets);
}
// Temporary collection to reverse the relation: sockets_to_models.get(socket)[direction] will hold all the models that have 'socket' from 'direction'
let mut sockets_to_models = HashMap::new();
// Using a BTreeSet because HashSet order is not deterministic. Performance impact is non-existant since `sockets_to_models` is discarded after building the Rules.
let empty_in_all_directions: Array<BTreeSet<ModelVariantIndex>, Ix1> =
Array::from_elem(coord_system.directions_count(), BTreeSet::new());
for (model_index, model) in model_variations.iter().enumerate() {
for &direction in coord_system.directions() {
let opposite_dir: usize = direction.opposite().into();
for socket in &model.sockets()[direction.into()] {
let compatible_models = sockets_to_models
.entry(socket)
.or_insert(empty_in_all_directions.clone());
compatible_models[opposite_dir].insert(model_index);
}
}
}
let mut allowed_neighbours = Array::from_elem(
(model_variations.len(), coord_system.directions_count()),
Vec::new(),
);
for (model_index, model) in model_variations.iter().enumerate() {
for direction in 0..coord_system.directions_count() {
// We filter unique models with a Set, but waht we want in the Rules is a Vec for access speed, caching, and iteration determinism.
let mut unique_models = HashSet::new();
// For each socket of the model in this direction: get all the sockets that are compatible for connection
for socket in &model.sockets()[direction] {
if let Some(compatible_sockets) = socket_collection.get_compatibles(*socket) {
for compatible_socket in compatible_sockets {
// For each of those: get all the models that have this socket from direction
// `sockets_to_models` may not have an entry for `compatible_socket` depending on user input data (socket present in sockets_connections but not in a model)
if let Some(allowed_models) = sockets_to_models.get(&compatible_socket)
{
for allowed_model in &allowed_models[direction] {
if unique_models.insert(*allowed_model) {
allowed_neighbours[(model_index, direction)]
.push(*allowed_model);
}
}
}
}
}
}
}
}
// Discard socket information, build linear buffers containing the info needed during the generation
let mut weights = Vec::with_capacity(model_variations.len());
let mut model_instances = Vec::with_capacity(model_variations.len());
#[cfg(feature = "models-names")]
let mut names = Vec::with_capacity(model_variations.len());
let mut models_mapping =
Array::from_elem((original_models_count, ALL_MODEL_ROTATIONS.len()), None);
for (index, model_variation) in model_variations.iter_mut().enumerate() {
weights.push(model_variation.weight());
model_instances.push(model_variation.to_instance());
#[cfg(feature = "models-names")]
names.push(model_variation.name.take());
models_mapping[(
model_variation.original_index(),
model_variation.rotation().index() as usize,
)] = Some(index);
}
#[cfg(feature = "debug-traces")]
{
trace!(
"Successfully built rules, allowed_neighbours: {:?}",
allowed_neighbours
);
}
Ok(Rules {
original_models_count,
models_mapping,
models: model_instances,
weights,
#[cfg(feature = "models-names")]
names,
allowed_neighbours,
typestate: PhantomData,
})
}
#[inline]
pub(crate) fn allowed_models<Direction: Into<usize>>(
&self,
model: ModelVariantIndex,
direction: Direction,
) -> &Vec<ModelVariantIndex> {
&self.allowed_neighbours[(model, direction.into())]
}
/// Returns the number of models (expanded from the input models) present in the rules
#[inline]
pub fn models_count(&self) -> usize {
self.models.len()
}
/// Returns the number of original input models that were used to build these rules
#[inline]
pub fn original_models_count(&self) -> usize {
self.original_models_count
}
#[inline]
pub(crate) fn model(&self, index: ModelVariantIndex) -> &ModelInstance {
&self.models[index]
}
pub(crate) fn model_info(&self, model_index: ModelVariantIndex) -> ModelInfo {
ModelInfo {
weight: self.weights[model_index],
#[cfg(feature = "models-names")]
name: self.name_unchecked(model_index),
}
}
#[inline]
pub(crate) fn weight_unchecked(&self, model_index: ModelVariantIndex) -> f32 {
self.weights[model_index]
}
/// Returns the weight of a model variant as an [`Option`]. Returns [`None`] if this model variant index is not valid.
pub fn weight(&self, model_index: ModelVariantIndex) -> Option<f32> {
match self.is_valid_model_variant_index(model_index) {
true => Some(self.weights[model_index]),
false => None,
}
}
#[inline]
fn is_valid_model_variant_index(&self, model_index: ModelVariantIndex) -> bool {
model_index < self.models.len()
}
/// Returns `Some` [`ModelVariantIndex`] corresponding to the original model with index `model_index` rotated by `rot`. Returns [`None`] if this variation does not exist.
pub fn variant_index(
&self,
model_index: ModelIndex,
rot: ModelRotation,
) -> Option<ModelVariantIndex> {
if model_index < self.original_models_count {
self.models_mapping[(model_index, rot.index() as usize)]
} else {
None
}
}
#[cfg(feature = "models-names")]
#[inline]
pub(crate) fn name_unchecked(&self, model_index: ModelVariantIndex) -> Cow<'static, str> {
match self.names[model_index].as_ref() {
None => "None".into(),
Some(name) => name.clone(),
}
}
#[cfg(feature = "models-names")]
#[inline]
pub(crate) fn name_unchecked_str(&self, model_index: ModelVariantIndex) -> &str {
match self.names[model_index].as_ref() {
None => "None",
Some(name) => name,
}
}
/// Returns the name of a model variant as an [`Option`].
///
/// Returns [`None`] if this model variant index is not valid or if it does not have a name.
#[cfg(feature = "models-names")]
pub fn name_str(&self, model_index: ModelVariantIndex) -> Option<&str> {
match self.is_valid_model_variant_index(model_index) {
true => Some(self.name_unchecked_str(model_index)),
false => None,
}
}
}
/// Represents a reference to a [`super::model::ModelVariation`] of some [`Rules`]
pub trait ModelVariantRef<C: CoordinateSystem> {
/// Returns the [`ModelVariantIndex`] that is referenced by this `ModelVariantRef`.
///
/// Returns a [`NodeSetError::InvalidModelRef`] if the reference is invalid in the [`Rules`].
fn to_index(&self, rules: &Rules<C>) -> Result<ModelVariantIndex, NodeSetError>;
}
impl<C: CoordinateSystem> ModelVariantRef<C> for ModelVariantIndex {
fn to_index(&self, _rules: &Rules<C>) -> Result<ModelVariantIndex, NodeSetError> {
Ok(*self)
}
}
impl<C: CoordinateSystem> ModelVariantRef<C> for Model<C> {
fn to_index(&self, rules: &Rules<C>) -> Result<ModelVariantIndex, NodeSetError> {
let rot = self.first_rot();
rules
.variant_index(self.index(), rot)
.ok_or(NodeSetError::InvalidModelRef(self.index(), rot))
}
}
impl<C: CoordinateSystem> ModelVariantRef<C> for &Model<C> {
fn to_index(&self, rules: &Rules<C>) -> Result<ModelVariantIndex, NodeSetError> {
let rot = self.first_rot();
rules
.variant_index(self.index(), rot)
.ok_or(NodeSetError::InvalidModelRef(self.index(), rot))
}
}
impl<C: CoordinateSystem> ModelVariantRef<C> for (ModelIndex, ModelRotation) {
fn to_index(&self, rules: &Rules<C>) -> Result<ModelVariantIndex, NodeSetError> {
rules
.variant_index(self.0, self.1)
.ok_or(NodeSetError::InvalidModelRef(self.0, self.1))
}
}
impl<C: CoordinateSystem> ModelVariantRef<C> for (Model<C>, ModelRotation) {
fn to_index(&self, rules: &Rules<C>) -> Result<ModelVariantIndex, NodeSetError> {
rules
.variant_index(self.0.index(), self.1)
.ok_or(NodeSetError::InvalidModelRef(self.0.index(), self.1))
}
}
impl<C: CoordinateSystem> ModelVariantRef<C> for (&Model<C>, ModelRotation) {
fn to_index(&self, rules: &Rules<C>) -> Result<ModelVariantIndex, NodeSetError> {
rules
.variant_index(self.0.index(), self.1)
.ok_or(NodeSetError::InvalidModelRef(self.0.index(), self.1))
}
}
impl<C: CoordinateSystem> ModelVariantRef<C> for ModelInstance {
fn to_index(&self, rules: &Rules<C>) -> Result<ModelVariantIndex, NodeSetError> {
rules
.variant_index(self.model_index, self.rotation)
.ok_or(NodeSetError::InvalidModelRef(
self.model_index,
self.rotation,
))
}
}
impl<C: CoordinateSystem> ModelVariantRef<C> for &ModelInstance {
fn to_index(&self, rules: &Rules<C>) -> Result<ModelVariantIndex, NodeSetError> {
rules
.variant_index(self.model_index, self.rotation)
.ok_or(NodeSetError::InvalidModelRef(
self.model_index,
self.rotation,
))
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/ghx_proc_gen/src/generator/socket.rs | ghx_proc_gen/src/generator/socket.rs | use std::collections::{HashMap, HashSet};
use ghx_grid::cartesian::coordinates::{Cartesian2D, Cartesian3D};
use super::model::{ModelRotation, ModelTemplate, ALL_MODEL_ROTATIONS};
/// Id of a possible connection type
pub(crate) type SocketId = u64;
/// Used to create one or more [`Socket`]. Created sockets can then be used to define [`super::model::Model`] and
/// define connections between them.
#[derive(Clone)]
pub struct SocketCollection {
incremental_socket_index: u32,
/// For uniqueness
uniques: HashMap<SocketId, HashSet<SocketId>>,
/// For determinism and sequential access
compatibles: HashMap<SocketId, Vec<SocketId>>,
}
impl SocketCollection {
/// Creates a new [`SocketCollection`]
pub fn new() -> Self {
Self {
incremental_socket_index: 0,
uniques: HashMap::new(),
compatibles: HashMap::new(),
}
}
/// Creates a new [`Socket`] in the collection and returns it
pub fn create(&mut self) -> Socket {
let socket = Socket::new(self.incremental_socket_index);
self.incremental_socket_index += 1;
socket
}
/// Adds a connection between two sockets. [`super::model::Model`] with sockets `from` can connect to model with
/// sockets `to` and vice versa.
///
/// - There is **no** direction in the relation, adding a connection from`a` to `b` also adds a connection from `b` to `a`
/// - By default (until the connection is explicitly added), a socket is not "compatible" with itself.
/// ### Example
/// ```
/// use ghx_proc_gen::generator::socket::SocketCollection;
///
/// let mut sockets = SocketCollection::new();
/// let a = sockets.create();
/// let b = sockets.create();
/// sockets.add_connection(a, vec![a, b]);
/// // `a` can be connected to `a` and `b`
/// // `b` can be connected to `a`
/// ```
pub fn add_connection<I>(&mut self, from: Socket, to: I) -> &mut Self
where
I: IntoIterator<Item = Socket>,
{
for to_socket in to.into_iter() {
self.register_connection(&from, &to_socket);
}
self
}
/// Same as `add_connection` but accept multiple connections definitions at the same time.
/// ### Example
/// ```
/// use ghx_proc_gen::generator::socket::SocketCollection;
///
/// let mut sockets = SocketCollection::new();
/// let (a, b, c) = (sockets.create(), sockets.create(), sockets.create());
/// sockets.add_connections(vec![
/// (a, vec![a, b]),
/// (b, vec![c])
/// ]);
/// // `a` can be connected to `a` and `b`
/// // `b` can be connected to `a` and `c`
/// // `c` can be connected to `b`
/// ```
pub fn add_connections<I, J>(&mut self, connections: I) -> &mut Self
where
I: IntoIterator<Item = (Socket, J)>,
J: IntoIterator<Item = Socket>,
{
for (from, to_sockets) in connections.into_iter() {
for to in to_sockets.into_iter() {
self.register_connection(&from, &to);
}
}
self
}
/// Adds a connection between all possible rotations of two sockets that are on the rotation axis of the [`super::Rules`]. [`super::model::Model`] with sockets `from` can connect to model with sockets `to` and vice versa.
///
/// - There is **no** direction in the relation, adding a connection from`a` to `b` also adds a connection from `b` to `a`
/// - By default (until the connection is explicitly added), a socket is not "compatible" with itself.
/// ### Example
/// ```
/// use ghx_proc_gen::generator::{socket::{SocketCollection, SocketsCartesian3D}, model::ModelCollection};
///
/// let mut sockets = SocketCollection::new();
/// let (side_a, vertical_a) = (sockets.create(), sockets.create());
/// let (side_b, vertical_b) = (sockets.create(), sockets.create());
///
/// // If Y+ is our rotation axis. We could have such models:
/// let mut models = ModelCollection::new();
/// let model_a = models.create(SocketsCartesian3D::Simple {
/// x_pos: side_a,
/// x_neg: side_a,
/// z_pos: side_a,
/// z_neg: side_a,
/// y_pos: vertical_a,
/// y_neg: vertical_a,
/// }).with_all_rotations();
/// let model_b = models.create(SocketsCartesian3D::Simple {
/// x_pos: side_b,
/// x_neg: side_b,
/// z_pos: side_b,
/// z_neg: side_b,
/// y_pos: vertical_b,
/// y_neg: vertical_b,
/// }).with_all_rotations();
///
/// sockets.add_rotated_connection(vertical_a, vec![vertical_b]);
/// // `model_a` and `model_b` can now be stacked on top of each other (no matter their rotations)
/// // Note: here two `model_a` cannot be stacked on top of each other since `vertical_a` was not said to be connected to itself.
/// ```
pub fn add_rotated_connection(&mut self, from: Socket, to: Vec<Socket>) -> &mut Self {
for to_rotation in ALL_MODEL_ROTATIONS {
let to_rotated_sockets: Vec<Socket> =
to.iter().map(|s| s.rotated(*to_rotation)).collect();
for from_rot in ALL_MODEL_ROTATIONS {
let rotated_socket = from.rotated(*from_rot);
for to_socket in to_rotated_sockets.iter() {
self.register_connection(&rotated_socket, &to_socket);
}
}
}
self
}
/// Same as `add_rotated_connection` but accepts multiple connections definitions at the same time.
pub fn add_rotated_connections<I>(&mut self, connections: I) -> &mut Self
where
I: IntoIterator<Item = (Socket, Vec<Socket>)>,
{
for (from, to_sockets) in connections.into_iter() {
self.add_rotated_connection(from, to_sockets);
}
self
}
/// Similar to `add_rotated_connection` but with additional constraints.
///
/// Adds a connection between only the specified `relative_rotations` of two sockets that are on the rotation axis
/// of the [`super::Rules`]. [`super::model::Model`] with sockets `from`, with a given relative rotation to socket
/// `to`, can connect to model with sockets `to` (and vice versa with the opposite relative rotation).
///
/// `relative_rotations` should be defined with regard to rotation [`ModelRotation::Rot0`] of `to`. So a value of
/// [`ModelRotation::Rot90`] in `relative_rotations` means that a `from` socket can be connected to a `to` socket if
/// and only if the `from` socket is rotated 90° more than the `to` socket, no matter their absolute rotations.
///
/// - There is **no** direction in the relation, adding a connection from`a` to `b` also adds a connection from `b`
/// to `a` (here with the opposite relative rotation)
/// - By default (until the connection is explicitly added), a socket is not "compatible" with itself.
pub fn add_constrained_rotated_connection(
&mut self,
from: Socket,
mut relative_rotations: Vec<ModelRotation>,
to: Vec<Socket>,
) -> &mut Self {
for to_rotation in ALL_MODEL_ROTATIONS {
let to_rotated_sockets: Vec<Socket> =
to.iter().map(|s| s.rotated(*to_rotation)).collect();
for from_rotation in relative_rotations.iter_mut() {
let from_rotated_socket = from.rotated(*from_rotation);
for to_socket in to_rotated_sockets.iter() {
self.register_connection(&from_rotated_socket, &to_socket);
}
*from_rotation = from_rotation.next();
}
}
self
}
fn register_connection_half(&mut self, from: &Socket, to: &Socket) {
// TODO Decide if we check for existence
let connectable_sockets = self.uniques.entry(from.id()).or_insert(HashSet::new());
if connectable_sockets.insert(to.id()) {
self.compatibles
.entry(from.id())
.or_insert(Vec::new())
.push(to.id());
}
}
fn register_connection(&mut self, from: &Socket, to: &Socket) {
self.register_connection_half(from, to);
self.register_connection_half(to, from);
}
pub(crate) fn get_compatibles(&self, socket: SocketId) -> Option<&Vec<SocketId>> {
self.compatibles.get(&socket)
}
pub(crate) fn is_empty(&self) -> bool {
self.incremental_socket_index == 0
}
}
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
/// Defines a contact point of a [`super::model::Model`]. Each model may have none or multiple socket(s) on
/// each of his sides.
///
/// Relations between sockets are not defined on the socket nor on the model but rather in a [`SocketCollection`].
pub struct Socket {
/// Index of the socket. Always unique, except for rotated sockets on the rotation axis which share the same
/// `socket_index`
socket_index: u32,
/// Internal index which defines the rotation of the socket. Always [`ModelRotation::Rot0`] for sockets that are
/// not on the rotation axis of the [`crate::generator::Rules`]
rot: ModelRotation,
}
impl Socket {
pub(crate) fn new(socket_index: u32) -> Self {
Self {
socket_index,
rot: ModelRotation::Rot0,
}
}
pub(crate) fn id(&self) -> SocketId {
self.socket_index as u64 + ((self.rot.index() as u64) << 32)
}
pub(crate) fn rotated(&self, rotation: ModelRotation) -> Socket {
let mut rotated_socket = self.clone();
rotated_socket.rot = rotated_socket.rot.rotated(rotation);
rotated_socket
}
pub(crate) fn rotate(&mut self, rotation: ModelRotation) {
self.rot.rotate(rotation);
}
}
/// Sockets for a model to be used in a 2d cartesian grid.
pub enum SocketsCartesian2D {
/// The model has only 1 socket, and its is the same in all directions.
Mono(Socket),
/// The model has 1 socket per side.
Simple {
/// socket on the x+ side
x_pos: Socket,
/// socket on the x- side
x_neg: Socket,
/// socket on the y+ side
y_pos: Socket,
/// socket on the y- side
y_neg: Socket,
},
/// The model has multiple sockets per side.
Multiple {
/// sockets on the x+ side
x_pos: Vec<Socket>,
/// sockets on the x- side
x_neg: Vec<Socket>,
/// sockets on the y+ side
y_pos: Vec<Socket>,
/// sockets on the y- side
y_neg: Vec<Socket>,
},
}
impl Into<Vec<Vec<Socket>>> for SocketsCartesian2D {
fn into(self) -> Vec<Vec<Socket>> {
match self {
SocketsCartesian2D::Mono(socket) => vec![vec![socket]; 4],
SocketsCartesian2D::Simple {
x_pos,
y_pos,
x_neg,
y_neg,
} => {
vec![vec![x_pos], vec![y_pos], vec![x_neg], vec![y_neg]]
}
SocketsCartesian2D::Multiple {
x_pos,
y_pos,
x_neg,
y_neg,
} => {
vec![x_pos, y_pos, x_neg, y_neg]
}
}
}
}
impl SocketsCartesian2D {
/// Creates a [`ModelTemplate`] from its sockets definition, with default values for the other members: weight is [`super::model::DEFAULT_MODEL_WEIGHT`] and the model will not be rotated.
pub fn to_template(self) -> ModelTemplate<Cartesian2D> {
ModelTemplate::<Cartesian2D>::new(self)
}
}
impl Into<ModelTemplate<Cartesian2D>> for SocketsCartesian2D {
fn into(self) -> ModelTemplate<Cartesian2D> {
self.to_template()
}
}
/// Sockets for a model to be used in a 3d cartesian grid.
pub enum SocketsCartesian3D {
/// The model has only 1 socket, and its is the same in all directions.
Mono(Socket),
/// The model has 1 socket per side.
Simple {
/// socket on the x+ side
x_pos: Socket,
/// socket on the x- side
x_neg: Socket,
/// socket on the z+ side
z_pos: Socket,
/// socket on the z- side
z_neg: Socket,
/// socket on the y+ side
y_pos: Socket,
/// socket on the y- side
y_neg: Socket,
},
/// The model has multiple sockets per side.
Multiple {
/// sockets on the x+ side
x_pos: Vec<Socket>,
/// sockets on the x- side
x_neg: Vec<Socket>,
/// sockets on the z+ side
z_pos: Vec<Socket>,
/// sockets on the z- side
z_neg: Vec<Socket>,
/// sockets on the y+ side
y_pos: Vec<Socket>,
/// sockets on the y- side
y_neg: Vec<Socket>,
},
}
impl Into<Vec<Vec<Socket>>> for SocketsCartesian3D {
fn into(self) -> Vec<Vec<Socket>> {
match self {
SocketsCartesian3D::Mono(socket) => vec![vec![socket]; 6],
SocketsCartesian3D::Simple {
x_pos,
y_pos,
x_neg,
y_neg,
z_pos,
z_neg,
} => {
vec![
vec![x_pos],
vec![y_pos],
vec![x_neg],
vec![y_neg],
vec![z_pos],
vec![z_neg],
]
}
SocketsCartesian3D::Multiple {
x_pos,
y_pos,
x_neg,
y_neg,
z_pos,
z_neg,
} => {
vec![x_pos, y_pos, x_neg, y_neg, z_pos, z_neg]
}
}
}
}
impl Into<ModelTemplate<Cartesian3D>> for SocketsCartesian3D {
fn into(self) -> ModelTemplate<Cartesian3D> {
self.to_template()
}
}
impl SocketsCartesian3D {
/// Creates a [`ModelTemplate`] from its sockets definition, with default values for the other members: weight is [`super::model::DEFAULT_MODEL_WEIGHT`] and the model will not be rotated.
pub fn to_template(self) -> ModelTemplate<Cartesian3D> {
ModelTemplate::<Cartesian3D>::new(self)
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/lib.rs | bevy_ghx_proc_gen/src/lib.rs | #![warn(missing_docs)]
//! This library encapsulates (and re-exports) the "ghx_proc_gen" library for 2D & 3D procedural generation with Model synthesis/Wave function Collapse, for a Bevy usage.
//! Also provide grid utilities to manipulate & debug 2d & 3d grid data with Bevy.
use bevy::{
ecs::{
bundle::Bundle,
component::Component,
entity::Entity,
event::Event,
query::Added,
resource::Resource,
system::{Commands, Query, Res},
},
math::Vec3,
platform::collections::HashSet,
prelude::{Deref, DerefMut, Without},
};
use ghx_proc_gen::{
generator::{
model::{ModelIndex, ModelInstance},
GeneratedNode,
},
ghx_grid::{
cartesian::{coordinates::CartesianCoordinates, grid::CartesianGrid},
grid::GridData,
},
NodeIndex,
};
use assets::BundleInserter;
use spawner_plugin::NodesSpawner;
pub use bevy_ghx_grid;
pub use ghx_proc_gen as proc_gen;
/// Types to define and spawn assets
pub mod assets;
/// Debug plugin to run the generation with different visualization options
#[cfg(feature = "debug-plugin")]
pub mod debug_plugin;
/// Simple plugin to run the generation
#[cfg(feature = "simple-plugin")]
pub mod simple_plugin;
/// Plugin to automatically spawn generated nodes
pub mod spawner_plugin;
/// Adds default [`BundleInserter`] implementations for some common types.
///
/// **WARNING**: those default implementations each assume a specific `Rotation Axis` for the `Models` (Z+ for 2d, Y+ for 3d)
#[cfg(feature = "default-bundle-inserters")]
pub mod default_bundles;
#[cfg(feature = "egui-edit")]
pub use bevy_egui;
/// The generation with the specified entity was fully generated
#[derive(Event, Clone)]
pub struct GridGeneratedEvent<C: CartesianCoordinates>(
pub GridData<C, ModelInstance, CartesianGrid<C>>,
);
/// The generation with the specified entity was reinitialized
#[derive(Event, Clone, Debug)]
pub struct GenerationResetEvent;
/// The generation with the specified entity was updated on the specified node
#[derive(Event, Clone, Debug)]
pub struct NodesGeneratedEvent(pub Vec<GeneratedNode>);
/// Used to mark a node spawned by a [`ghx_proc_gen::generator::Generator`]. Stores the [NodeIndex] of this node
#[derive(Component)]
pub struct GridNode(pub NodeIndex);
/// Main component marker for a cursor target
#[derive(Component)]
pub struct CursorTarget;
/// Component used to store model indexes of models with no assets.
///
/// Can be used for special handling of those models (skip their generation when stepping, ...).
#[derive(Component, Default, Deref, DerefMut)]
pub struct VoidNodes(pub HashSet<ModelIndex>);
/// Utility system. Adds a [`Bundle`] (or a [`Component`]) to every [`Entity`] that has [`GridNode`] Component (this is the case of nodes spawned by the `spawn_node` system). The `Bundle` will have its default value.
///
/// ### Example
///
/// Add a `MyAnimation` Component with its default value to every newly spawned node Entity
/// ```ignore
/// #[derive(Component, Default)]
/// pub struct MyAnimation {
/// duration_sec: f32,
/// final_scale: Vec3,
/// }
/// impl Default for MyAnimation {
/// fn default() -> Self {
/// Self {
/// duration_sec: 5.,
/// final_scale: Vec3::splat(2.0),
/// }
/// }
/// }
/// // ... In the `App` initialization code:
/// app.add_systems(
/// Update,
/// insert_default_bundle_to_spawned_nodes::<MyAnimation>
/// );
/// ```
pub fn insert_default_bundle_to_spawned_nodes<B: Bundle + Default>(
mut commands: Commands,
spawned_nodes: Query<Entity, (Added<GridNode>, Without<CursorTarget>)>,
) {
for node in spawned_nodes.iter() {
commands.entity(node).try_insert(B::default());
}
}
/// Utility system. Adds a [`Bundle`] (or a [`Component`]) to every [`Entity`] that has [`GridNode`] Component (this is the case of nodes spawned by the `spawn_node` system). The `Bundle` will be cloned from a `Resource`
///
/// ### Example
///
/// Add a `MyAnimation` Component cloned from a `Resource` to every newly spawned node Entity
/// ```ignore
/// #[derive(Component, Resource)]
/// pub struct MyAnimation {
/// duration_sec: f32,
/// final_scale: Vec3,
/// }
/// app.insert_resource(MyAnimation {
/// duration_sec: 0.8,
/// final_scale: Vec3::ONE,
/// });
/// app.add_systems(
/// Update,
/// insert_bundle_from_resource_to_spawned_nodes::<MyAnimation>
/// );
/// ```
pub fn insert_bundle_from_resource_to_spawned_nodes<B: Bundle + Resource + Clone>(
mut commands: Commands,
bundle_to_clone: Res<B>,
spawned_nodes: Query<Entity, (Added<GridNode>, Without<CursorTarget>)>,
) {
for node in spawned_nodes.iter() {
commands.entity(node).try_insert(bundle_to_clone.clone());
}
}
/// Utility function to spawn grid nodes. Can work for multiple asset types.
///
/// Used by [`simple_plugin::ProcGenSimpleRunnerPlugin`] and [`debug_plugin::ProcGenDebugRunnerPlugin`] to spawn assets automatically.
///
/// ### Examples
///
/// Spawn 3d models (gltf) assets with a `Cartesian3D` grid
/// ```ignore
/// spawn_node::<Cartesian3D, Handle<Scene>>(...);
/// ```
/// Spawn 2d sprites (png, ...) assets with a `Cartesian3D` grid
/// ```ignore
/// spawn_node::<Cartesian3D, Handle<Image>>(...);
/// ```
pub fn spawn_node<C: CartesianCoordinates, A: BundleInserter>(
commands: &mut Commands,
gen_entity: Entity,
grid: &CartesianGrid<C>,
node_spawner: &NodesSpawner<A>,
instance: &ModelInstance,
node_index: NodeIndex,
) {
let node_assets = match node_spawner.assets.get(&instance.model_index) {
Some(node_assets) => node_assets,
None => return,
};
let pos = grid.pos_from_index(node_index);
for node_asset in node_assets {
let offset = &node_asset.world_offset;
let grid_offset = &node_asset.grid_offset;
// + (0.5 * size) to center `translation` in the node
let mut translation = Vec3::new(
offset.x + node_spawner.node_size.x * (pos.x as f32 + grid_offset.dx as f32 + 0.5),
offset.y + node_spawner.node_size.y * (pos.y as f32 + grid_offset.dy as f32 + 0.5),
offset.z + node_spawner.node_size.z * (pos.z as f32 + grid_offset.dz as f32 + 0.5),
);
if node_spawner.z_offset_from_y {
translation.z += node_spawner.node_size.z * (1. - pos.y as f32 / grid.size_y() as f32);
}
let node_entity = commands.spawn(GridNode(node_index)).id();
let node_entity_commands = &mut commands.entity(node_entity);
node_asset.assets_bundle.insert_bundle(
node_entity_commands,
translation,
node_spawner.spawn_scale,
instance.rotation,
);
(node_asset.spawn_commands)(node_entity_commands);
commands.entity(gen_entity).add_child(node_entity);
}
}
macro_rules! add_named_observer {
($system: expr, $app: expr) => {
$app.world_mut().spawn((
bevy::prelude::Name::new(stringify!($system)),
bevy::ecs::observer::Observer::new($system),
))
};
}
pub(crate) use add_named_observer;
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/simple_plugin.rs | bevy_ghx_proc_gen/src/simple_plugin.rs | use std::marker::PhantomData;
use bevy::{
app::{App, Plugin, PluginGroup, PluginGroupBuilder, Update},
ecs::{
entity::Entity,
query::Added,
schedule::IntoScheduleConfigs,
system::{Commands, Query, ResMut},
},
platform::collections::HashSet,
prelude::Resource,
};
#[cfg(feature = "log")]
use bevy::log::{info, warn};
use ghx_proc_gen::{
generator::Generator,
ghx_grid::cartesian::{coordinates::CartesianCoordinates, grid::CartesianGrid},
GeneratorError,
};
use crate::{spawner_plugin::ProcGenSpawnerPlugin, BundleInserter, GridGeneratedEvent};
/// A simple [`Plugin`] that automatically detects any [`Entity`] with a [`Generator`] `Component` and tries to run the contained generator once per frame until it succeeds.
///
/// Once the generation is successful, the plugin will spawn the generated nodes assets.
pub struct ProcGenSimpleRunnerPlugin<C: CartesianCoordinates> {
typestate: PhantomData<C>,
}
impl<C: CartesianCoordinates> Plugin for ProcGenSimpleRunnerPlugin<C> {
fn build(&self, app: &mut App) {
app.insert_resource(PendingGenerations::default());
app.add_systems(
Update,
(register_new_generations::<C>, generate_and_spawn::<C>).chain(),
);
}
}
impl<C: CartesianCoordinates> ProcGenSimpleRunnerPlugin<C> {
/// Constructor
pub fn new() -> Self {
Self {
typestate: PhantomData,
}
}
}
/// A group of plugins that combines simple generation and nodes spawning
#[derive(Default)]
pub struct ProcGenSimplePlugins<C: CartesianCoordinates, A: BundleInserter> {
typestate: PhantomData<(C, A)>,
}
impl<C: CartesianCoordinates, A: BundleInserter> PluginGroup for ProcGenSimplePlugins<C, A> {
fn build(self) -> PluginGroupBuilder {
PluginGroupBuilder::start::<Self>()
.add(ProcGenSimpleRunnerPlugin::<C>::new())
.add(ProcGenSpawnerPlugin::<C, A>::new())
}
}
/// Resource used by [`ProcGenSimpleRunnerPlugin`] to track generations that are yet to generate a result
#[derive(Resource)]
pub struct PendingGenerations {
pendings: HashSet<Entity>,
}
impl Default for PendingGenerations {
fn default() -> Self {
Self {
pendings: Default::default(),
}
}
}
/// System used by [`ProcGenSimpleRunnerPlugin`] to track entities with newly added [`Generator`] components
pub fn register_new_generations<C: CartesianCoordinates>(
mut pending_generations: ResMut<PendingGenerations>,
mut new_generations: Query<Entity, Added<Generator<C, CartesianGrid<C>>>>,
) {
for gen_entity in new_generations.iter_mut() {
pending_generations.pendings.insert(gen_entity);
}
}
/// System used by [`ProcGenSimpleRunnerPlugin`] to run generators
pub fn generate_and_spawn<C: CartesianCoordinates>(
mut commands: Commands,
mut pending_generations: ResMut<PendingGenerations>,
mut generations: Query<&mut Generator<C, CartesianGrid<C>>>,
) {
let mut generations_done = vec![];
for &gen_entity in pending_generations.pendings.iter() {
if let Ok(mut generation) = generations.get_mut(gen_entity) {
match generation.generate_grid() {
Ok((gen_info, grid_data)) => {
#[cfg(feature = "log")]
info!(
"Generation {:?} done, try_count: {}, seed: {}; grid: {}",
gen_entity,
gen_info.try_count,
generation.seed(),
generation.grid()
);
commands.trigger_targets(GridGeneratedEvent(grid_data), gen_entity);
generations_done.push(gen_entity);
}
Err(GeneratorError { node_index }) => {
#[cfg(feature = "log")]
warn!(
"Generation {:?} failed at node {}, seed: {}; grid: {}",
gen_entity,
node_index,
generation.seed(),
generation.grid()
);
}
}
}
}
for gen_entity in generations_done {
pending_generations.pendings.remove(&gen_entity);
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/assets.rs | bevy_ghx_proc_gen/src/assets.rs | use std::{
collections::HashMap,
ops::{Deref, DerefMut},
};
use bevy::{ecs::system::EntityCommands, math::Vec3};
use ghx_proc_gen::{
generator::model::{ModelIndex, ModelRotation},
ghx_grid::cartesian::coordinates::GridDelta,
};
/// Defines a struct which can spawn components on an Entity (for example, a [`bevy::sprite::Sprite`], a [`bevy::scene::SceneRoot`], ...).
pub trait BundleInserter: Sync + Send + Default + 'static {
/// From the `BundleSpawner` own's struct data and a position, scale and rotation, can modify the spawned node `Entity`
fn insert_bundle(
&self,
command: &mut EntityCommands,
translation: Vec3,
scale: Vec3,
rotation: ModelRotation,
);
}
/// Represents spawnable asset(s) & component(s) for a model.
///
/// They will be spawned every time this model is generated. One `ModelAsset` will spawn exactly one [`bevy::prelude::Entity`] (but note that one Model may have more than one `ModelAsset`).
#[derive(Clone, Debug)]
// pub struct ModelAsset<A: BundleSpawner, T: BundleSpawner = NoComponents> {
pub struct ModelAsset<A: BundleInserter> {
/// Stores handle(s) to the asset(s) and spawns their bundle
pub assets_bundle: A,
/// Spawn commands to add additional components to a spawned model
pub spawn_commands: fn(&mut EntityCommands),
/// Grid offset from the generated grid node position. Added to `offset`.
pub grid_offset: GridDelta,
/// World offset from the generated grid node position. Added to `grid_offset`.
pub world_offset: Vec3,
}
/// Defines a map which links a `Model` via its [`ModelIndex`] to his spawnable(s) [`ModelAsset`]
#[derive(Debug)]
pub struct ModelsAssets<A: BundleInserter> {
/// Only contains a ModelIndex if there are some assets for it. One model may have multiple [`ModelAsset`].
map: HashMap<ModelIndex, Vec<ModelAsset<A>>>,
}
impl<A: BundleInserter> Deref for ModelsAssets<A> {
type Target = HashMap<ModelIndex, Vec<ModelAsset<A>>>;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl<A: BundleInserter> DerefMut for ModelsAssets<A> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.map
}
}
impl<A: BundleInserter> ModelsAssets<A> {
/// Create a new ModelsAssets with an empty map
pub fn new() -> Self {
Self {
map: Default::default(),
}
}
/// Create a new ModelsAssets with an existing map
pub fn new_from_map(map: HashMap<ModelIndex, Vec<ModelAsset<A>>>) -> Self {
Self { map }
}
/// Adds a [`ModelAsset`] with no grid offset, to the model `index`
pub fn add_asset(&mut self, index: ModelIndex, asset: A) {
let model_asset = ModelAsset {
assets_bundle: asset,
grid_offset: Default::default(),
world_offset: Vec3::ZERO,
spawn_commands: |_| {},
};
self.add(index, model_asset);
}
/// Adds a [`ModelAsset`] to the model `index`
pub fn add(&mut self, index: ModelIndex, model_asset: ModelAsset<A>) {
match self.get_mut(&index) {
Some(assets) => {
assets.push(model_asset);
}
None => {
self.insert(index, vec![model_asset]);
}
}
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/spawner_plugin.rs | bevy_ghx_proc_gen/src/spawner_plugin.rs | use std::{marker::PhantomData, sync::Arc};
use bevy::{
app::{App, Plugin},
ecs::{
component::Component,
query::Without,
system::{Commands, Query},
world::OnAdd,
},
math::Vec3,
platform::collections::HashSet,
prelude::{Children, Entity, Trigger, With},
render::view::Visibility,
};
use ghx_proc_gen::{
generator::Generator,
ghx_grid::cartesian::{coordinates::CartesianCoordinates, grid::CartesianGrid},
};
use crate::{
add_named_observer, spawn_node, GenerationResetEvent, GridGeneratedEvent, NodesGeneratedEvent,
VoidNodes,
};
use super::{assets::ModelsAssets, BundleInserter, GridNode};
/// Plugins that automatically spawn entites & assets for generated nodes
#[derive(Default)]
pub struct ProcGenSpawnerPlugin<C: CartesianCoordinates, A: BundleInserter> {
typestate: PhantomData<(C, A)>,
}
impl<C: CartesianCoordinates, A: BundleInserter> Plugin for ProcGenSpawnerPlugin<C, A> {
fn build(&self, app: &mut App) {
add_named_observer!(default_grid_spawner::<C, A>, app);
add_named_observer!(default_node_despawner::<C>, app);
add_named_observer!(default_node_spawner::<C, A>, app);
add_named_observer!(insert_void_nodes_to_new_generations::<C, A>, app);
}
}
impl<C: CartesianCoordinates, A: BundleInserter> ProcGenSpawnerPlugin<C, A> {
/// Simple constructor
pub fn new() -> Self {
Self {
typestate: PhantomData,
}
}
}
/// Stores information needed to spawn node assets from a [`ghx_proc_gen::generator::Generator`]
#[derive(Component, Clone, Debug)]
#[require(Visibility)]
pub struct NodesSpawner<A: BundleInserter> {
/// Link a `Model` to his spawnable assets via its [`ghx_proc_gen::generator::model::ModelIndex`] (can be shared by multiple [`NodesSpawner`])
pub assets: Arc<ModelsAssets<A>>,
/// Size of a node in world units
pub node_size: Vec3,
/// Scale of the assets when spawned
pub spawn_scale: Vec3,
/// Whether to offset the z coordinate of spawned nodes from the y coordinate (used for 2d ordering of sprites)
pub z_offset_from_y: bool,
}
impl<A: BundleInserter> NodesSpawner<A> {
/// Constructor, `z_offset_from_y` defaults to `false`
pub fn new(
models_assets: ModelsAssets<A>,
node_size: Vec3,
spawn_scale: Vec3,
) -> NodesSpawner<A> {
Self {
assets: Arc::new(models_assets),
node_size,
spawn_scale,
z_offset_from_y: false,
}
}
/// Sets the `z_offset_from_y` value
pub fn with_z_offset_from_y(mut self, z_offset_from_y: bool) -> Self {
self.z_offset_from_y = z_offset_from_y;
self
}
}
/// Simple observer system that calculates and add a [`VoidNodes`] component for generator entites which don't have one yet.
pub fn insert_void_nodes_to_new_generations<C: CartesianCoordinates, A: BundleInserter>(
trigger: Trigger<OnAdd, Generator<C, CartesianGrid<C>>>,
mut commands: Commands,
mut new_generations: Query<
(
Entity,
&mut Generator<C, CartesianGrid<C>>,
&NodesSpawner<A>,
),
Without<VoidNodes>,
>,
) {
let Ok((gen_entity, generation, nodes_spawner)) = new_generations.get_mut(trigger.target())
else {
return;
};
let mut void_nodes = HashSet::new();
for model_index in 0..generation.rules().original_models_count() {
if !nodes_spawner.assets.contains_key(&model_index) {
void_nodes.insert(model_index);
}
}
commands.entity(gen_entity).insert(VoidNodes(void_nodes));
}
/// Spawns every nodes of a fully generated generator entity as children
pub fn default_grid_spawner<C: CartesianCoordinates, A: BundleInserter>(
trigger: Trigger<GridGeneratedEvent<C>>,
mut commands: Commands,
generators: Query<(&NodesSpawner<A>, &Generator<C, CartesianGrid<C>>)>,
) {
let gen_entity = trigger.target();
if let Ok((asset_spawner, generator)) = generators.get(gen_entity) {
for (node_index, model_instance) in trigger.event().0.iter().enumerate() {
spawn_node(
&mut commands,
gen_entity,
&generator.grid(),
asset_spawner,
model_instance,
node_index,
);
}
}
}
/// Despawns every children nodes of a generator entity
pub fn default_node_despawner<C: CartesianCoordinates>(
trigger: Trigger<GenerationResetEvent>,
mut commands: Commands,
generators: Query<&Children>,
existing_nodes: Query<Entity, With<GridNode>>,
) {
if let Ok(children) = generators.get(trigger.target()) {
for &child in children.iter() {
if let Ok(node) = existing_nodes.get(child) {
commands.entity(node).despawn();
}
}
}
}
/// Spawns a collection of nodes of a generator entity as children
pub fn default_node_spawner<C: CartesianCoordinates, A: BundleInserter>(
trigger: Trigger<NodesGeneratedEvent>,
mut commands: Commands,
generators: Query<(&NodesSpawner<A>, &Generator<C, CartesianGrid<C>>)>,
) {
let gen_entity = trigger.target();
if let Ok((node_spawner, generator)) = generators.get(gen_entity) {
for node in trigger.event().0.iter() {
spawn_node(
&mut commands,
gen_entity,
&generator.grid(),
node_spawner,
&node.model_instance,
node.node_index,
);
}
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/default_bundles.rs | bevy_ghx_proc_gen/src/default_bundles.rs | use bevy::{
asset::Handle,
ecs::system::EntityCommands,
image::Image,
math::{Quat, Vec3},
pbr::{Material, MeshMaterial3d, StandardMaterial},
prelude::Mesh3d,
render::mesh::Mesh,
scene::{Scene, SceneRoot},
sprite::Sprite,
transform::components::Transform,
utils::default,
};
use ghx_proc_gen::generator::model::ModelRotation;
use super::assets::BundleInserter;
/// **WARNING**: Assumes a specific `Rotation Axis` for the `Models`: Z+
impl BundleInserter for Handle<Image> {
fn insert_bundle(
&self,
commands: &mut EntityCommands,
translation: Vec3,
scale: Vec3,
rotation: ModelRotation,
) {
commands.insert((
Transform::from_translation(translation)
.with_scale(scale)
.with_rotation(Quat::from_rotation_z(rotation.rad())),
Sprite {
image: self.clone(),
..default()
},
));
}
}
/// **WARNING**: Assumes a specific `Rotation Axis` for the `Models`: Y+
impl BundleInserter for Handle<Scene> {
fn insert_bundle(
&self,
commands: &mut EntityCommands,
translation: Vec3,
scale: Vec3,
rotation: ModelRotation,
) {
commands.insert((
Transform::from_translation(translation)
.with_scale(scale)
.with_rotation(Quat::from_rotation_y(rotation.rad())),
SceneRoot(self.clone()),
));
}
}
/// Custom type to store [`Handle`] to a [`Mesh`] asset and its [`Material`]
#[derive(Default, Clone, Debug)]
pub struct MaterialMesh<M: Material> {
/// Mesh handle
pub mesh: Handle<Mesh>,
/// Material handle
pub material: Handle<M>,
}
/// Custom type to store [`Handle`] to a [`Mesh`] asset and its [`StandardMaterial`]
///
/// Specialization of [`MaterialMesh`] with [`StandardMaterial`]
#[derive(Default, Clone, Debug)]
pub struct PbrMesh {
/// Mesh handle
pub mesh: Handle<Mesh>,
/// Standard material handle
pub material: Handle<StandardMaterial>,
}
/// **WARNING**: Assumes a specific `Rotation Axis` for the `Models`: Y+
impl<M: Material + Default> BundleInserter for MaterialMesh<M> {
fn insert_bundle(
&self,
commands: &mut EntityCommands,
translation: Vec3,
scale: Vec3,
rotation: ModelRotation,
) {
commands.insert((
Transform::from_translation(translation)
.with_scale(scale)
.with_rotation(Quat::from_rotation_y(rotation.rad())),
Mesh3d(self.mesh.clone()),
MeshMaterial3d(self.material.clone()),
));
}
}
/// **WARNING**: Assumes a specific `Rotation Axis` for the `Models`: Y+
impl BundleInserter for PbrMesh {
fn insert_bundle(
&self,
commands: &mut EntityCommands,
translation: Vec3,
scale: Vec3,
rotation: ModelRotation,
) {
commands.insert((
Transform::from_translation(translation)
.with_scale(scale)
.with_rotation(Quat::from_rotation_y(rotation.rad())),
Mesh3d(self.mesh.clone()),
MeshMaterial3d(self.material.clone()),
));
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/debug_plugin/cursor.rs | bevy_ghx_proc_gen/src/debug_plugin/cursor.rs | use std::{fmt, marker::PhantomData, time::Duration};
use bevy::{
app::{App, Plugin, PostUpdate, PreUpdate, Startup, Update},
color::{palettes::css::GREEN, Color},
ecs::{
component::Component,
entity::Entity,
event::EventWriter,
name::Name,
query::{Changed, With, Without},
resource::Resource,
schedule::IntoScheduleConfigs,
system::{Commands, Local, Query, Res, ResMut},
},
input::{keyboard::KeyCode, ButtonInput},
prelude::{Text, TextUiWriter, Trigger},
render::camera::Camera,
text::{LineBreak, TextColor, TextFont, TextLayout, TextSpan},
time::{Time, Timer, TimerMode},
transform::components::GlobalTransform,
ui::{BackgroundColor, Node, PositionType, UiRect, Val},
utils::default,
};
#[cfg(feature = "log")]
use bevy::log::warn;
use bevy_ghx_grid::{
debug_plugin::markers::{spawn_marker, GridMarker, MarkerDespawnEvent},
ghx_grid::{coordinate_system::CoordinateSystem, direction::Direction},
};
use ghx_proc_gen::{
generator::{Generator, ModelVariations},
ghx_grid::cartesian::{
coordinates::{CartesianCoordinates, CartesianPosition},
grid::CartesianGrid,
},
NodeIndex,
};
#[cfg(feature = "picking")]
use bevy::prelude::Pickable;
use crate::{
add_named_observer, debug_plugin::CursorUiMode, GenerationResetEvent, NodesGeneratedEvent,
};
use super::{
generation::ActiveGeneration, DebugPluginConfig, GridCursorsUiSettings, ProcGenKeyBindings,
};
/// Picking plugin for the [super::ProcGenDebugRunnerPlugin]
#[derive(Default)]
pub(crate) struct ProcGenDebugCursorPlugin<C: CartesianCoordinates> {
/// Used to configure how the cursors UI should be displayed
pub config: DebugPluginConfig,
#[doc(hidden)]
pub typestate: PhantomData<C>,
}
impl<C: CartesianCoordinates> Plugin for ProcGenDebugCursorPlugin<C> {
fn build(&self, app: &mut App) {
app.init_resource::<SelectionCursorMarkerSettings>()
.init_resource::<CursorKeyboardMovement>()
.init_resource::<CursorKeyboardMovementSettings>();
if self.config.cursor_ui_mode != CursorUiMode::None {
app.init_resource::<GridCursorsUiSettings>();
}
app.add_systems(
Startup,
setup_cursor::<C, SelectCursor>.after(setup_cursors_overlays),
)
// Keybinds and picking events handlers run in PreUpdate
.add_systems(
PreUpdate,
(
deselect_from_keybinds,
switch_generation_selection_from_keybinds::<C>,
move_selection_from_keybinds::<C>,
),
)
.add_systems(Update, (update_cursors_info_on_cursors_changes::<C>,));
match self.config.cursor_ui_mode {
CursorUiMode::None => (),
CursorUiMode::Panel => {
app.add_systems(Startup, setup_cursors_panel)
.add_systems(PostUpdate, update_selection_cursor_panel_text);
}
CursorUiMode::Overlay => {
app.add_systems(Startup, setup_cursors_overlays)
.add_systems(Update, update_cursors_overlays);
}
}
add_named_observer!(update_cursors_info_on_generation_reset::<C>, app);
add_named_observer!(update_cursors_info_on_generated_nodes::<C>, app);
}
}
impl<C: CartesianCoordinates> ProcGenDebugCursorPlugin<C> {
/// Constructor
pub fn new(config: &DebugPluginConfig) -> Self {
Self {
config: config.clone(),
..Default::default()
}
}
}
/// Marker component to be put on a [Camera] to signal that it should be used to display cursor overlays
///
/// - **Not needed** if only a single camera is used.
/// - If used, should not be present on more than 1 camera
#[derive(Component)]
pub struct GridCursorsOverlayCamera;
/// Root marker for the cursors panel UI
#[derive(Component)]
pub struct CursorsPanelRoot;
/// Root marker for the cursors overlay UI
#[derive(Component)]
pub struct CursorsOverlaysRoot;
/// Text component marker for the cursors panel UI
#[derive(Component)]
pub struct CursorsPanelText;
/// Represents a node in a grid and its [GridMarker]
#[derive(Debug)]
pub struct TargetedNode {
/// Grid entity the node belongs to
pub grid: Entity,
/// Index of the node in its grid
pub index: NodeIndex,
/// Position of the node in its grid
pub position: CartesianPosition,
/// Marker entity for this targeted node
pub marker: Entity,
}
impl fmt::Display for TargetedNode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}, index: {}", self.position, self.index)
}
}
/// Represents a generic cursor and its optional target
#[derive(Component, Default, Debug)]
pub struct Cursor(pub Option<TargetedNode>);
/// Information about what is being pointed by a cursor
#[derive(Component, Default, Debug)]
pub struct CursorInfo {
/// How many possible models for the node pointed by the cursor
pub total_models_count: u32,
/// Groups of models for the node pointed by the cursor
pub models_variations: Vec<ModelVariations>,
}
impl CursorInfo {
/// Clear all information in the [CursorInfo]
pub fn clear(&mut self) {
self.total_models_count = 0;
self.models_variations.clear();
}
}
/// Trait implemented by cursors to customize their behavior
pub trait CursorBehavior: Component {
/// Create a new cursor
fn new() -> Self;
/// Returns whether or not this cursor should update the active generation when its target changes
fn updates_active_gen() -> bool;
}
/// Marker component for a cursor's UI overlay
#[derive(Component, Debug)]
pub struct CursorOverlay {
/// The cursor Entity
pub cursor_entity: Entity,
}
/// Trait implemented by cursors settings resources
pub trait CursorMarkerSettings: Resource {
/// Returns the color used for this type of cursor
fn color(&self) -> Color;
}
/// Settings for the selection cursor
#[derive(Resource)]
pub struct SelectionCursorMarkerSettings(pub Color);
impl Default for SelectionCursorMarkerSettings {
fn default() -> Self {
Self(Color::Srgba(GREEN))
}
}
impl CursorMarkerSettings for SelectionCursorMarkerSettings {
fn color(&self) -> Color {
self.0
}
}
/// Selection cursor marker component
#[derive(Component, Debug)]
pub struct SelectCursor;
impl CursorBehavior for SelectCursor {
fn new() -> Self {
Self
}
fn updates_active_gen() -> bool {
true
}
}
/// Used to index text sections when displaying cursors Ui in a panel
pub const OVER_CURSOR_SECTION_INDEX: usize = 0;
/// Used to index text sections when displaying cursors Ui in a panel
pub const SELECTION_CURSOR_SECTION_INDEX: usize = 1;
/// Setup system used to spawn the cursors UI panel
pub fn setup_cursors_panel(mut commands: Commands, ui_config: Res<GridCursorsUiSettings>) {
let root = commands
.spawn((
CursorsPanelRoot,
Name::new("CursorsPanelRoot"),
BackgroundColor(ui_config.background_color),
Node {
position_type: PositionType::Absolute,
right: Val::Percent(1.),
bottom: Val::Percent(1.),
top: Val::Auto,
left: Val::Auto,
padding: UiRect::all(Val::Px(4.0)),
..default()
},
))
.id();
let text = commands
.spawn((
CursorsPanelText,
TextLayout::default(),
TextFont::from_font_size(ui_config.font_size),
TextColor(ui_config.text_color),
Text("".into()),
))
// Over cursor
.with_child((
TextSpan::new(" N/A"),
TextFont::from_font_size(ui_config.font_size),
TextColor(ui_config.text_color),
))
// Selection cursor
.with_child((
TextSpan::new(" N/A"),
TextFont::from_font_size(ui_config.font_size),
TextColor(ui_config.text_color),
))
.id();
commands.entity(root).add_child(text);
}
/// Setpu system used to spawn the cursors UI overlay root
pub fn setup_cursors_overlays(mut commands: Commands) {
let root = commands
.spawn((
CursorsOverlaysRoot,
Name::new("CursorsOverlaysRoot"),
Node { ..default() },
))
.id();
#[cfg(feature = "picking")]
commands.entity(root).insert(Pickable::IGNORE);
}
/// Setup system to spawn a cursor and its overlay
pub fn setup_cursor<C: CoordinateSystem, CI: CursorBehavior>(
mut commands: Commands,
overlays_root: Query<Entity, With<CursorsOverlaysRoot>>,
) {
let cursor_entity = commands
.spawn((Cursor::default(), CursorInfo::default(), CI::new()))
.id();
let Ok(root) = overlays_root.single() else {
// No overlays
return;
};
let cursor_overlay_entity = commands.spawn(CursorOverlay { cursor_entity }).id();
commands.entity(root).add_child(cursor_overlay_entity);
#[cfg(feature = "picking")]
commands
.entity(cursor_overlay_entity)
.insert(Pickable::IGNORE);
}
/// System updating all the [CursorInfo] components when [Cursor] components are changed
pub fn update_cursors_info_on_cursors_changes<C: CartesianCoordinates>(
mut moved_cursors: Query<(&mut CursorInfo, &Cursor), Changed<Cursor>>,
generators: Query<&Generator<C, CartesianGrid<C>>>,
) {
for (mut cursor_info, cursor) in moved_cursors.iter_mut() {
match &cursor.0 {
Some(targeted_node) => {
if let Ok(generator) = generators.get(targeted_node.grid) {
(
cursor_info.models_variations,
cursor_info.total_models_count,
) = generator.get_models_variations_on(targeted_node.index);
}
}
None => cursor_info.clear(),
}
}
}
/// Observer updating all the [CursorInfo] based on [GenerationResetEvent]
pub fn update_cursors_info_on_generation_reset<C: CartesianCoordinates>(
trigger: Trigger<GenerationResetEvent>,
generators: Query<&Generator<C, CartesianGrid<C>>>,
mut cursors: Query<(&Cursor, &mut CursorInfo)>,
) {
let Ok(generator) = generators.get(trigger.target()) else {
return;
};
for (cursor, mut cursor_info) in cursors.iter_mut() {
let Some(targeted_node) = &cursor.0 else {
continue;
};
(
cursor_info.models_variations,
cursor_info.total_models_count,
) = generator.get_models_variations_on(targeted_node.index);
}
}
/// Observer updating all the [CursorInfo] based on [NodesGeneratedEvent]
pub fn update_cursors_info_on_generated_nodes<C: CartesianCoordinates>(
trigger: Trigger<NodesGeneratedEvent>,
generators: Query<&Generator<C, CartesianGrid<C>>>,
mut cursors: Query<(&Cursor, &mut CursorInfo)>,
) {
let Ok(generator) = generators.get(trigger.target()) else {
return;
};
for (cursor, mut cursor_info) in cursors.iter_mut() {
let Some(targeted_node) = &cursor.0 else {
continue;
};
for gen_node in trigger.event().0.iter() {
if targeted_node.index == gen_node.node_index {
(
cursor_info.models_variations,
cursor_info.total_models_count,
) = generator.get_models_variations_on(targeted_node.index);
}
}
}
}
/// System updating the selection cursor panel UI based on changes in [CursorInfo]
pub fn update_selection_cursor_panel_text(
mut writer: TextUiWriter,
mut cursors_panel_text: Query<Entity, With<CursorsPanelText>>,
updated_cursors: Query<(&CursorInfo, &Cursor), (Changed<CursorInfo>, With<SelectCursor>)>,
) {
if let Ok((cursor_info, cursor)) = updated_cursors.single() {
for panel_entity in &mut cursors_panel_text {
let mut ui_text = writer.text(panel_entity, SELECTION_CURSOR_SECTION_INDEX);
match &cursor.0 {
Some(grid_cursor) => {
*ui_text = format!(
"Selected:\n{}",
cursor_info_to_string(grid_cursor, cursor_info)
);
}
None => ui_text.clear(),
}
}
}
}
/// Listen to [KeyCode] to deselect the current selection cursor
pub fn deselect_from_keybinds(
keys: Res<ButtonInput<KeyCode>>,
proc_gen_key_bindings: Res<ProcGenKeyBindings>,
mut marker_events: EventWriter<MarkerDespawnEvent>,
mut selection_cursor: Query<&mut Cursor, With<SelectCursor>>,
) {
if keys.just_pressed(proc_gen_key_bindings.deselect) {
let Ok(mut cursor) = selection_cursor.single_mut() else {
return;
};
if let Some(grid_cursor) = &cursor.0 {
marker_events.write(MarkerDespawnEvent::Marker(grid_cursor.marker));
cursor.0 = None;
}
}
}
/// Simple entity collection
pub struct EntityProvider {
/// Entities in the collection
pub entities: Vec<Entity>,
/// Current index in the collection
pub index: usize,
}
impl Default for EntityProvider {
fn default() -> Self {
Self {
entities: Vec::new(),
index: 0,
}
}
}
impl EntityProvider {
/// Updates the collection with `entities` and clamp the index to the new collection length
pub fn update(&mut self, entities: Vec<Entity>) {
self.entities = entities;
self.index = (self.index + 1) % self.entities.len();
}
/// Returns the entity at the current index
pub fn get(&self) -> Entity {
self.entities[self.index]
}
}
/// System that listens to the generation switch [KeyCode] to switch the current active generation grid
pub fn switch_generation_selection_from_keybinds<C: CartesianCoordinates>(
mut local_grid_cycler: Local<EntityProvider>,
mut commands: Commands,
mut active_generation: ResMut<ActiveGeneration>,
keys: Res<ButtonInput<KeyCode>>,
selection_marker_settings: Res<SelectionCursorMarkerSettings>,
proc_gen_key_bindings: Res<ProcGenKeyBindings>,
mut marker_events: EventWriter<MarkerDespawnEvent>,
mut selection_cursor: Query<&mut Cursor, With<SelectCursor>>,
generators: Query<Entity, (With<Generator<C, CartesianGrid<C>>>, With<CartesianGrid<C>>)>,
) {
if keys.just_pressed(proc_gen_key_bindings.switch_grid) {
let Ok(mut cursor) = selection_cursor.single_mut() else {
return;
};
local_grid_cycler.update(generators.iter().collect());
let grid_entity = local_grid_cycler.get();
active_generation.0 = Some(grid_entity);
// Despawn previous if any
if let Some(grid_cursor) = &cursor.0 {
marker_events.write(MarkerDespawnEvent::Marker(grid_cursor.marker));
}
// Spawn on new selected grid
cursor.0 = Some(spawn_marker_and_create_cursor(
&mut commands,
grid_entity,
CartesianPosition::new(0, 0, 0),
0,
selection_marker_settings.color(),
));
}
}
const CURSOR_KEYS_MOVEMENT_COOLDOWN_MS: u64 = 140;
const CURSOR_KEYS_MOVEMENT_SHORT_COOLDOWN_MS: u64 = 45;
const CURSOR_KEYS_MOVEMENT_SPEED_UP_DELAY_MS: u64 = 350;
/// Resource used to customize keyboard movement of the selection cursor
#[derive(Resource)]
pub struct CursorKeyboardMovementSettings {
/// Cooldown between two movements when not sped up
pub default_cooldown_ms: u64,
/// Cooldown between two movements when sped up
pub short_cooldown_ms: u64,
/// Duration after which the cooldown between two movmeents gets sped up if
/// the move key is continuously pressed
pub speed_up_timer_duration_ms: Duration,
}
impl Default for CursorKeyboardMovementSettings {
fn default() -> Self {
Self {
default_cooldown_ms: CURSOR_KEYS_MOVEMENT_COOLDOWN_MS,
short_cooldown_ms: CURSOR_KEYS_MOVEMENT_SHORT_COOLDOWN_MS,
speed_up_timer_duration_ms: Duration::from_millis(
CURSOR_KEYS_MOVEMENT_SPEED_UP_DELAY_MS,
),
}
}
}
/// Resource used to track keyboard movement variables for the selection cursor
#[derive(Resource)]
pub struct CursorKeyboardMovement {
/// Current cooldwon to move again
pub cooldown: Timer,
/// Current timer before speeding up the movements
pub speed_up_timer: Timer,
}
impl Default for CursorKeyboardMovement {
fn default() -> Self {
Self {
cooldown: Timer::new(
Duration::from_millis(CURSOR_KEYS_MOVEMENT_COOLDOWN_MS),
TimerMode::Once,
),
speed_up_timer: Timer::new(
Duration::from_millis(CURSOR_KEYS_MOVEMENT_SPEED_UP_DELAY_MS),
TimerMode::Once,
),
}
}
}
/// System handling movements of the selection cursor from the keyboard
pub fn move_selection_from_keybinds<C: CartesianCoordinates>(
mut commands: Commands,
keys: Res<ButtonInput<KeyCode>>,
time: Res<Time>,
selection_marker_settings: Res<SelectionCursorMarkerSettings>,
proc_gen_key_bindings: Res<ProcGenKeyBindings>,
mut marker_events: EventWriter<MarkerDespawnEvent>,
key_mvmt_values: Res<CursorKeyboardMovementSettings>,
mut key_mvmt: ResMut<CursorKeyboardMovement>,
mut selection_cursor: Query<&mut Cursor, With<SelectCursor>>,
grids: Query<(Entity, &CartesianGrid<C>)>,
) {
let Ok(mut cursor) = selection_cursor.single_mut() else {
return;
};
let axis_selection = if keys.pressed(proc_gen_key_bindings.cursor_x_axis) {
Some(Direction::XForward)
} else if keys.pressed(proc_gen_key_bindings.cursor_y_axis) {
Some(Direction::YForward)
} else if keys.pressed(proc_gen_key_bindings.cursor_z_axis) {
Some(Direction::ZForward)
} else {
None
};
if let Some(axis) = axis_selection {
// Just pressed => moves
// Pressed => moves with default cooldown
// Pressed for a while => speeds up, shorter cooldown
// Sped up & no press => resets to default cooldown
let cursor_movement = if keys.just_pressed(proc_gen_key_bindings.prev_node) {
Some(-1)
} else if keys.just_pressed(proc_gen_key_bindings.next_node) {
Some(1)
} else {
let (movement, pressed) = match key_mvmt.cooldown.finished() {
true => {
if keys.pressed(proc_gen_key_bindings.prev_node) {
(Some(-1), true)
} else if keys.pressed(proc_gen_key_bindings.next_node) {
(Some(1), true)
} else {
(None, false)
}
}
false => {
if keys.pressed(proc_gen_key_bindings.prev_node)
|| keys.pressed(proc_gen_key_bindings.next_node)
{
(None, true)
} else {
(None, false)
}
}
};
if pressed {
key_mvmt.cooldown.tick(time.delta());
if !key_mvmt.speed_up_timer.finished() {
key_mvmt.speed_up_timer.tick(time.delta());
} else if key_mvmt.speed_up_timer.just_finished() {
key_mvmt
.cooldown
.set_duration(Duration::from_millis(key_mvmt_values.short_cooldown_ms));
}
} else {
if key_mvmt.speed_up_timer.finished() {
key_mvmt
.cooldown
.set_duration(Duration::from_millis(key_mvmt_values.default_cooldown_ms));
}
key_mvmt
.speed_up_timer
.set_duration(key_mvmt_values.speed_up_timer_duration_ms);
key_mvmt.speed_up_timer.reset();
}
movement
};
if let Some(movement) = cursor_movement {
key_mvmt.cooldown.reset();
let update_cursor = match &cursor.0 {
Some(grid_cursor) => {
let Ok((_grid_entity, grid)) = grids.get(grid_cursor.grid) else {
return;
};
match grid.get_index_in_direction(&grid_cursor.position, axis, movement) {
Some(node_index) => {
marker_events.write(MarkerDespawnEvent::Marker(grid_cursor.marker));
Some((
grid_cursor.grid,
node_index,
grid.pos_from_index(node_index),
))
}
None => None,
}
}
None => {
// Currently no selection cursor, spawn it on the last Grid
let Some((grid_entity, _grid)) = grids.iter().last() else {
return;
};
Some((grid_entity, 0, CartesianPosition::new(0, 0, 0)))
}
};
match update_cursor {
Some((grid_entity, node_index, position)) => {
cursor.0 = Some(spawn_marker_and_create_cursor(
&mut commands,
grid_entity,
position,
node_index,
selection_marker_settings.color(),
));
}
None => (),
}
}
}
}
/// Utility function to spawn a [GridMarker]
pub fn spawn_marker_and_create_cursor(
commands: &mut Commands,
grid_entity: Entity,
position: CartesianPosition,
node_index: NodeIndex,
color: Color,
) -> TargetedNode {
let marker = spawn_marker(commands, grid_entity, color, position);
TargetedNode {
grid: grid_entity,
index: node_index,
position,
marker,
}
}
/// Utility function to transform data from a [CursorInfo] into a [String]
pub fn cursor_info_to_string(cursor: &TargetedNode, cursor_info: &CursorInfo) -> String {
let text = if cursor_info.models_variations.len() > 1 {
format!(
"Grid: {{{}}}\n\
{} possible models, {} variations:\n\
{{{}}}\n\
{{{}}}\n\
{}",
cursor,
cursor_info.models_variations.len(),
cursor_info.total_models_count,
cursor_info.models_variations[0],
cursor_info.models_variations[1],
if cursor_info.models_variations.len() > 2 {
"...\n"
} else {
""
}
)
} else if cursor_info.models_variations.len() == 1 {
format!(
"Grid: {{{}}}\n\
Model: {{{}}}\n",
cursor, cursor_info.models_variations[0],
)
} else {
format!(
"Grid: {{{}}}\n\
No models possible\n",
cursor,
)
};
text
}
/// Local flag used as a system local resource
#[derive(Default)]
pub struct Flag(pub bool);
/// System updating the cursors overlay UI
pub fn update_cursors_overlays(
mut camera_warning_flag: Local<Flag>,
mut commands: Commands,
ui_config: Res<GridCursorsUiSettings>,
just_one_camera: Query<(&Camera, &GlobalTransform), Without<GridCursorsOverlayCamera>>,
overlay_camera: Query<(&Camera, &GlobalTransform), With<GridCursorsOverlayCamera>>,
cursor_overlays: Query<(Entity, &CursorOverlay)>,
cursors: Query<(&CursorInfo, &Cursor)>,
markers: Query<&GlobalTransform, With<GridMarker>>,
) {
let (camera, cam_gtransform) = match just_one_camera.single() {
Ok(found) => found,
Err(_) => match overlay_camera.single() {
Ok(found) => found,
Err(_) => {
if !camera_warning_flag.0 {
#[cfg(feature = "log")]
warn!("None (or too many) Camera(s) found with 'GridCursorsOverlayCamera' component to display cursors overlays. Add `GridCursorsOverlayCamera` component to a Camera or change the cursor UI mode.");
camera_warning_flag.0 = true;
}
return;
}
},
};
for (overlay_entity, overlay) in cursor_overlays.iter() {
let Ok((cursor_info, cursor)) = cursors.get(overlay.cursor_entity) else {
continue;
};
// TODO Bevy 0.15 might need to tweak the behavior to remove/update some components when there is no overlay
let Some(grid_cursor) = &cursor.0 else {
// No cursor => no text overlay
commands.entity(overlay_entity).insert(Text::default());
continue;
};
let Ok(marker_gtransform) = markers.get(grid_cursor.marker) else {
// No marker => no text overlay
commands.entity(overlay_entity).insert(Text::default());
continue;
};
let Ok(viewport_pos) =
camera.world_to_viewport(cam_gtransform, marker_gtransform.translation())
else {
continue;
};
let text = cursor_info_to_string(&grid_cursor, cursor_info);
commands.entity(overlay_entity).insert((
// TODO bevy 0.15: Insert background once ?
BackgroundColor(ui_config.background_color),
TextLayout {
linebreak: LineBreak::NoWrap,
..default()
},
TextColor(ui_config.text_color),
TextFont {
font_size: ui_config.font_size,
..default()
},
Text(text),
Node {
position_type: PositionType::Absolute,
left: Val::Px(viewport_pos.x + 5.0),
top: Val::Px(viewport_pos.y + 5.0),
..default()
},
));
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/debug_plugin/egui_editor.rs | bevy_ghx_proc_gen/src/debug_plugin/egui_editor.rs | use bevy::{
app::{App, Update},
ecs::{
event::{Event, EventReader, EventWriter},
query::With,
resource::Resource,
schedule::IntoScheduleConfigs,
system::{Query, Res, ResMut},
},
input::{mouse::MouseButton, ButtonInput},
};
#[cfg(feature = "log")]
use bevy::log::warn;
use bevy_egui::{
egui::{self, Color32, Pos2},
EguiContexts,
};
use ghx_proc_gen::{
generator::{
model::{ModelInstance, ModelRotation},
rules::ModelInfo,
Generator,
},
ghx_grid::cartesian::{coordinates::CartesianCoordinates, grid::CartesianGrid},
};
use crate::{CursorTarget, GridNode};
use super::{
cursor::{Cursor, CursorInfo, SelectCursor},
generation::ActiveGeneration,
picking::{NodeOverEvent, NodeSelectedEvent},
};
pub(crate) fn plugin<C: CartesianCoordinates>(app: &mut App) {
app.init_resource::<EditorConfig>()
.init_resource::<EditorContext>()
.add_event::<BrushEvent>();
app.add_systems(
Update,
(
draw_edition_panel::<C>,
update_brush,
update_painting_state,
paint::<C>,
)
.chain()
.run_if(editor_enabled),
);
}
/// Resource sued to track the status of the edgui editor
#[derive(Resource)]
pub struct EditorConfig {
/// Whether or not the editor is currently enabled
pub enabled: bool,
}
impl Default for EditorConfig {
fn default() -> Self {
Self { enabled: true }
}
}
/// Context of the egui editor
#[derive(Resource, Default)]
pub struct EditorContext {
/// Current brush, can be [None]
pub model_brush: Option<ModelBrush>,
/// Is the editor currently painting
pub painting: bool,
}
/// A model "brush" holding information about what model it paints
#[derive(Clone)]
pub struct ModelBrush {
/// General info about the model
pub info: ModelInfo,
/// Specific instance of the model
pub instance: ModelInstance,
}
/// Event types for model brushes
#[derive(Event)]
pub enum BrushEvent {
/// Clear the current brush
ClearBrush,
/// Update the current brush to a new one
UpdateBrush(ModelBrush),
/// Update only the rotation of the current brush
UpdateRotation(ModelRotation),
}
/// System condition to check if the egui editor is enabled
pub fn editor_enabled(editor_config: Res<EditorConfig>) -> bool {
editor_config.enabled
}
/// System that can be used to toggle on/off the egui editor
pub fn toggle_editor(mut editor_config: ResMut<EditorConfig>) {
editor_config.enabled = !editor_config.enabled;
}
/// System used to draw the editor egui window
pub fn draw_edition_panel<C: CartesianCoordinates>(
editor_context: ResMut<EditorContext>,
mut contexts: EguiContexts,
active_generation: Res<ActiveGeneration>,
mut brush_events: EventWriter<BrushEvent>,
generations: Query<&mut Generator<C, CartesianGrid<C>>>,
selection_cursor: Query<(&Cursor, &CursorInfo), With<SelectCursor>>,
) {
let Some(active_generation) = active_generation.0 else {
return;
};
let Ok(generator) = generations.get(active_generation) else {
return;
};
let Ok((cursor, cursor_info)) = selection_cursor.single() else {
return;
};
// TODO Cache ? rules models groups
egui::Window::new("Edition panel")
.title_bar(true)
// TODO Init all those values with viewport size
.default_pos(Pos2::new(10., 300.))
.show(contexts.ctx_mut(), |ui| {
ui.horizontal_wrapped(|ui| {
// TODO A rules models display
ui.label(format!("📖 Rules:",));
ui.colored_label(
Color32::WHITE,
format!(
"{} models ({} variations)",
generator.rules().original_models_count(),
generator.rules().models_count(),
),
);
});
match &cursor.0 {
Some(targeted_node) => {
ui.horizontal_wrapped(|ui| {
ui.label("⭕ Selected node: ");
ui.colored_label(
Color32::WHITE,
format!(
"{{{}}}, {} possible models ({} variations)",
targeted_node.position,
cursor_info.models_variations.len(),
cursor_info.total_models_count,
),
);
});
}
None => {
ui.label("⭕ No selected node");
}
};
ui.separator();
match &editor_context.model_brush {
Some(model) => {
ui.horizontal(|ui| {
ui.label("🖊 Current brush: ");
ui.colored_label(
Color32::WHITE,
format!("{}, {}", model.info.name, model.instance),
);
if ui.button("Clear").clicked() {
brush_events.write(BrushEvent::ClearBrush);
}
});
}
None => {
ui.label("🖊 No brush selected");
}
};
ui.separator();
egui::ScrollArea::vertical().show(ui, |ui| {
for model_group in cursor_info.models_variations.iter() {
let selected = match &editor_context.model_brush {
Some(model) => model_group.index == model.instance.model_index,
None => false,
};
ui.horizontal(|ui| {
let rot_count_tag = if model_group.rotations.len() != 1 {
format!(" ({})", model_group.rotations.len())
} else {
"".to_owned()
};
if ui
.selectable_label(
selected,
format!("▶ {}{}", model_group.info.name, rot_count_tag,),
)
.on_hover_ui(|ui| {
ui.label(format!(
"{} possible rotations, weight: {}",
model_group.rotations.len(),
model_group.info.weight
));
})
.clicked()
{
brush_events.write(BrushEvent::UpdateBrush(ModelBrush {
info: model_group.info.clone(),
instance: ModelInstance {
model_index: model_group.index,
rotation: model_group.rotations[0],
},
}));
}
if selected {
for rotation in model_group.rotations.iter() {
let is_selected = match &editor_context.model_brush {
Some(model) => *rotation == model.instance.rotation,
None => false,
};
if ui
.selectable_label(is_selected, format!("{}°", rotation.value()))
.clicked()
{
brush_events.write(BrushEvent::UpdateRotation(*rotation));
}
}
}
});
}
});
});
}
/// System reading [BrushEvent] to update the current model brush in the [EditorContext]
pub fn update_brush(
mut editor_context: ResMut<EditorContext>,
mut brush_events: EventReader<BrushEvent>,
) {
for event in brush_events.read() {
match event {
BrushEvent::ClearBrush => editor_context.model_brush = None,
BrushEvent::UpdateBrush(new_brush) => {
editor_context.model_brush = Some(new_brush.clone())
}
BrushEvent::UpdateRotation(new_rot) => {
if let Some(brush) = editor_context.model_brush.as_mut() {
brush.instance.rotation = *new_rot;
}
}
}
}
}
/// System updating the painting state in the [EditorContext] based on mouse inputs and [NodeSelectedEvent]
pub fn update_painting_state(
mut editor_context: ResMut<EditorContext>,
buttons: Res<ButtonInput<MouseButton>>,
mut node_select_events: EventReader<NodeSelectedEvent>,
cursor_targets: Query<(), With<CursorTarget>>,
) {
if editor_context.model_brush.is_none() {
editor_context.painting = false;
return;
}
if let Some(ev) = node_select_events.read().last() {
if let Ok(_) = cursor_targets.get(ev.0) {
editor_context.painting = true;
};
}
if buttons.just_released(MouseButton::Left) {
editor_context.painting = false;
}
}
/// System issuing the generation requests to the generator based on the painting state
pub fn paint<C: CartesianCoordinates>(
editor_context: ResMut<EditorContext>,
active_generation: Res<ActiveGeneration>,
mut node_over_events: EventReader<NodeOverEvent>,
mut generations: Query<&mut Generator<C, CartesianGrid<C>>>,
cursor_targets: Query<&GridNode, With<CursorTarget>>,
) {
if !editor_context.painting {
node_over_events.clear();
return;
}
let Some(model_brush) = &editor_context.model_brush else {
node_over_events.clear();
return;
};
let Some(active_generation) = active_generation.0 else {
node_over_events.clear();
return;
};
let Ok(mut generator) = generations.get_mut(active_generation) else {
node_over_events.clear();
return;
};
for ev in node_over_events.read() {
let Ok(node) = cursor_targets.get(ev.0) else {
continue;
};
if let Err(err) = generator.set_and_propagate(node.0, model_brush.instance, true) {
#[cfg(feature = "log")]
warn!(
"Failed to generate model {} on node {}: {}",
model_brush.instance, node.0, err
);
}
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/debug_plugin/generation.rs | bevy_ghx_proc_gen/src/debug_plugin/generation.rs | use std::{marker::PhantomData, time::Duration};
use bevy::{
app::{App, Plugin, Update},
color::{palettes::css::RED, Color},
ecs::{
entity::Entity,
event::EventWriter,
query::{With, Without},
schedule::IntoScheduleConfigs,
system::{Commands, Query, Res, ResMut},
},
input::{keyboard::KeyCode, ButtonInput},
prelude::{Component, Deref, DerefMut, Resource},
time::{Time, Timer, TimerMode},
};
#[cfg(feature = "log")]
use bevy::log::{info, warn};
use bevy_ghx_grid::debug_plugin::markers::{spawn_marker, MarkerDespawnEvent};
use ghx_proc_gen::{
generator::{
observer::{GenerationUpdate, QueuedObserver},
GenerationStatus, Generator,
},
ghx_grid::cartesian::{coordinates::CartesianCoordinates, grid::CartesianGrid},
GeneratorError, NodeIndex,
};
use crate::{GenerationResetEvent, NodesGeneratedEvent, VoidNodes};
use super::{DebugPluginConfig, ProcGenKeyBindings};
/// Picking plugin for the [super::ProcGenDebugRunnerPlugin]
#[derive(Default)]
pub(crate) struct ProcGenDebugGenerationPlugin<C: CartesianCoordinates> {
/// Used to configure how the cursors UI should be displayed
pub config: DebugPluginConfig,
#[doc(hidden)]
pub typestate: PhantomData<C>,
}
impl<C: CartesianCoordinates> Plugin for ProcGenDebugGenerationPlugin<C> {
fn build(&self, app: &mut App) {
app.insert_resource(self.config.generation_view_mode)
.insert_resource(ActiveGeneration::default())
.init_resource::<GenerationControl>();
app.add_systems(
Update,
(update_generation_control, update_active_generation::<C>),
);
match self.config.generation_view_mode {
GenerationViewMode::StepByStepTimed {
steps_count,
interval_ms,
} => {
app.add_systems(
Update,
(
(insert_error_markers_to_new_generations::<C>,),
step_by_step_timed_update::<C>,
dequeue_generation_updates::<C>,
)
.chain(),
);
app.insert_resource(StepByStepTimed {
steps_count,
timer: Timer::new(Duration::from_millis(interval_ms), TimerMode::Repeating),
});
}
GenerationViewMode::StepByStepManual => {
app.add_systems(
Update,
(
(insert_error_markers_to_new_generations::<C>,),
step_by_step_input_update::<C>,
dequeue_generation_updates::<C>,
)
.chain(),
);
}
GenerationViewMode::Final => {
app.add_systems(
Update,
(generate_all::<C>, dequeue_generation_updates::<C>).chain(),
);
}
}
}
}
impl<C: CartesianCoordinates> ProcGenDebugGenerationPlugin<C> {
/// Constructor
pub fn new(config: &DebugPluginConfig) -> Self {
Self {
config: config.clone(),
..Default::default()
}
}
}
/// Controls how the generation occurs.
#[derive(Resource, Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum GenerationViewMode {
/// Generates steps by steps and waits at least the specified amount (in milliseconds) between each step.
StepByStepTimed {
/// How many steps to run once the timer has finished a cycle
steps_count: u32,
/// Time to wait in ms before the next steps
interval_ms: u64,
},
/// Generates step by step and waits for a user input between each step.
StepByStepManual,
/// Generates it all at once at the start
#[default]
Final,
}
/// Used to track the status of the generation control
#[derive(Eq, PartialEq, Debug)]
pub enum GenerationControlStatus {
/// Generation control is paused, systems won't automatically step the generation
Paused,
/// Generation control is "ongoing", systems can currently step a generator
Ongoing,
}
/// Read by the systems while generating
#[derive(Resource)]
pub struct GenerationControl {
/// Current status of the generation
pub status: GenerationControlStatus,
/// Indicates whether or not the generator needs to be reinitialized before calling generation operations.
///
/// When using [`GenerationViewMode::Final`], this only controls the first reinitialization per try pool.
pub need_reinit: bool,
/// Whether or not the spawning systems do one more generation step when nodes without assets are generated.
///
/// Not used when using [`GenerationViewMode::Final`].
pub skip_void_nodes: bool,
/// Whether or not the generation should pause when successful
pub pause_when_done: bool,
/// Whether or not the generation should pause when it fails.
///
/// When using [`GenerationViewMode::Final`], this only pauses on the last error of a try pool.
pub pause_on_error: bool,
/// Whether or not the generation should pause when it reinitializes
///
/// When using [`GenerationViewMode::Final`], this only pauses on the first reinitialization of a try pool.
pub pause_on_reinitialize: bool,
}
impl Default for GenerationControl {
fn default() -> Self {
Self {
status: GenerationControlStatus::Paused,
need_reinit: false,
skip_void_nodes: true,
pause_when_done: true,
pause_on_error: true,
pause_on_reinitialize: true,
}
}
}
/// Resource to track the generation steps when using [`GenerationViewMode::StepByStepTimed`]
#[derive(Resource)]
pub struct StepByStepTimed {
/// How many steps should be done once the timer has expired
pub steps_count: u32,
/// Timer, tracking the time between the steps
pub timer: Timer,
}
/// Component used to store a collection of [`bevy_ghx_grid::debug_plugin::markers::GridMarker`] entities
#[derive(Component, Default, Deref, DerefMut)]
pub struct ErrorMarkers(pub Vec<Entity>);
/// Resource used to track the currently active generation.
///
/// The contained option can be [None] if no generation is active
#[derive(Resource, Default)]
pub struct ActiveGeneration(pub Option<Entity>);
/// System used to insert an empty [ErrorMarkers] component into new generation entities
pub fn insert_error_markers_to_new_generations<C: CartesianCoordinates>(
mut commands: Commands,
mut new_generations: Query<
Entity,
(With<Generator<C, CartesianGrid<C>>>, Without<ErrorMarkers>),
>,
) {
for gen_entity in new_generations.iter_mut() {
commands.entity(gen_entity).insert(ErrorMarkers::default());
}
}
/// System that will update the currenty active generation if it was [None]
pub fn update_active_generation<C: CartesianCoordinates>(
mut active_generation: ResMut<ActiveGeneration>,
generations: Query<Entity, With<Generator<C, CartesianGrid<C>>>>,
) {
if active_generation.0.is_some() {
return;
}
if let Some(gen_entity) = generations.iter().last() {
active_generation.0 = Some(gen_entity);
}
}
/// This system pauses/unpauses the [`GenerationControlStatus`] in the [`GenerationControl`] `Resource` on a keypress.
///
/// The keybind is read from the [`ProcGenKeyBindings`] `Resource`
pub fn update_generation_control(
keys: Res<ButtonInput<KeyCode>>,
proc_gen_key_bindings: Res<ProcGenKeyBindings>,
mut generation_control: ResMut<GenerationControl>,
) {
if keys.just_pressed(proc_gen_key_bindings.pause_toggle) {
generation_control.status = match generation_control.status {
GenerationControlStatus::Ongoing => GenerationControlStatus::Paused,
GenerationControlStatus::Paused => GenerationControlStatus::Ongoing,
};
}
}
/// - reinitializes the generator if needed
/// - returns `true` if the generation operation should continue, and `false` if it should stop
pub fn handle_reinitialization_and_continue<C: CartesianCoordinates>(
generation_control: &mut ResMut<GenerationControl>,
generator: &mut Generator<C, CartesianGrid<C>>,
) -> bool {
if generation_control.need_reinit {
generation_control.need_reinit = false;
match generator.reinitialize() {
GenerationStatus::Ongoing => (),
GenerationStatus::Done => {
#[cfg(feature = "log")]
info!(
"Generation done, seed: {}; grid: {}",
generator.seed(),
generator.grid()
);
if generation_control.pause_when_done {
generation_control.status = GenerationControlStatus::Paused;
}
generation_control.need_reinit = true;
return false;
}
}
if generation_control.pause_on_reinitialize {
generation_control.status = GenerationControlStatus::Paused;
return false;
}
}
return true;
}
/// Function used to display some info about a generation that finished,
/// as well as to properly handle reinitialization status and pause.
pub fn handle_generation_done<C: CartesianCoordinates>(
generation_control: &mut ResMut<GenerationControl>,
generator: &mut Generator<C, CartesianGrid<C>>,
gen_entity: Entity,
try_count: u32,
) {
#[cfg(feature = "log")]
info!(
"Generation done {:?}, try_count: {}, seed: {}; grid: {}",
gen_entity,
try_count,
generator.seed(),
generator.grid()
);
generation_control.need_reinit = true;
if generation_control.pause_when_done {
generation_control.status = GenerationControlStatus::Paused;
}
}
/// Function used to display some info about a generation that failed,
/// as well as to properly handle reinitialization status and pause.
pub fn handle_generation_error<C: CartesianCoordinates>(
generation_control: &mut ResMut<GenerationControl>,
generator: &mut Generator<C, CartesianGrid<C>>,
gen_entity: Entity,
node_index: NodeIndex,
) {
#[cfg(feature = "log")]
warn!(
"Generation Failed {:?} at node {}, seed: {}; grid: {}",
gen_entity,
node_index,
generator.seed(),
generator.grid()
);
generation_control.need_reinit = true;
if generation_control.pause_on_error {
generation_control.status = GenerationControlStatus::Paused;
}
}
/// This system request the full generation to a [`Generator`] component, if it is observed through a [`QueuedObserver`] component, if the current control status is [`GenerationControlStatus::Ongoing`] and if it is currently the [`ActiveGeneration`]
pub fn generate_all<C: CartesianCoordinates>(
mut generation_control: ResMut<GenerationControl>,
active_generation: Res<ActiveGeneration>,
mut observed_generatiors: Query<&mut Generator<C, CartesianGrid<C>>, With<QueuedObserver>>,
) {
let Some(active_generation) = active_generation.0 else {
return;
};
let Ok(mut generator) = observed_generatiors.get_mut(active_generation) else {
return;
};
if generation_control.status == GenerationControlStatus::Ongoing {
if !handle_reinitialization_and_continue(&mut generation_control, &mut generator) {
return;
}
match generator.generate() {
Ok(gen_info) => {
handle_generation_done(
&mut generation_control,
&mut generator,
active_generation,
gen_info.try_count,
);
}
Err(GeneratorError { node_index }) => {
handle_generation_error(
&mut generation_control,
&mut generator,
active_generation,
node_index,
);
}
}
}
}
/// This system steps a [`Generator`] component if it is observed through a [`QueuedObserver`] component, if the current control status is [`GenerationControlStatus::Ongoing`], if it is currently the [`ActiveGeneration`] and if the appropriate keys are pressed.
///
/// The keybinds are read from the [`ProcGenKeyBindings`] `Resource`
pub fn step_by_step_input_update<C: CartesianCoordinates>(
keys: Res<ButtonInput<KeyCode>>,
proc_gen_key_bindings: Res<ProcGenKeyBindings>,
mut generation_control: ResMut<GenerationControl>,
active_generation: Res<ActiveGeneration>,
mut observed_generations: Query<
(&mut Generator<C, CartesianGrid<C>>, Option<&VoidNodes>),
With<QueuedObserver>,
>,
) {
let Some(active_generation) = active_generation.0 else {
return;
};
if generation_control.status == GenerationControlStatus::Ongoing
&& (keys.just_pressed(proc_gen_key_bindings.step)
|| keys.pressed(proc_gen_key_bindings.continuous_step))
{
if let Ok((mut generation, void_nodes)) = observed_generations.get_mut(active_generation) {
step_generation(
&mut generation,
active_generation,
void_nodes,
&mut generation_control,
);
}
}
}
/// This system steps a [`Generator`] component if it is observed through a [`QueuedObserver`] component, if the current control status is [`GenerationControlStatus::Ongoing`] if it is currently the [`ActiveGeneration`] and if the timer in the [`StepByStepTimed`] `Resource` has finished.
pub fn step_by_step_timed_update<C: CartesianCoordinates>(
mut generation_control: ResMut<GenerationControl>,
mut steps_and_timer: ResMut<StepByStepTimed>,
time: Res<Time>,
active_generation: Res<ActiveGeneration>,
mut observed_generations: Query<
(&mut Generator<C, CartesianGrid<C>>, Option<&VoidNodes>),
With<QueuedObserver>,
>,
) {
let Some(active_generation) = active_generation.0 else {
return;
};
steps_and_timer.timer.tick(time.delta());
if steps_and_timer.timer.finished()
&& generation_control.status == GenerationControlStatus::Ongoing
{
if let Ok((mut generation, void_nodes)) = observed_generations.get_mut(active_generation) {
for _ in 0..steps_and_timer.steps_count {
step_generation(
&mut generation,
active_generation,
void_nodes,
&mut generation_control,
);
if generation_control.status != GenerationControlStatus::Ongoing {
return;
}
}
}
}
}
/// System used to spawn nodes, emit [GenerationResetEvent] & [NodesGeneratedEvent] and despawn markers, based on data read from a [QueuedObserver] on a generation entity
pub fn dequeue_generation_updates<C: CartesianCoordinates>(
mut commands: Commands,
mut marker_events: EventWriter<MarkerDespawnEvent>,
mut generators: Query<(
Entity,
&CartesianGrid<C>,
&mut QueuedObserver,
Option<&mut ErrorMarkers>,
)>,
) {
for (grid_entity, grid, mut observer, mut error_markers) in generators.iter_mut() {
let mut reinitialized = false;
let mut nodes_to_spawn = Vec::new();
for update in observer.dequeue_all() {
match update {
GenerationUpdate::Generated(grid_node) => {
nodes_to_spawn.push(grid_node);
}
GenerationUpdate::Reinitializing(_) => {
reinitialized = true;
nodes_to_spawn.clear();
}
GenerationUpdate::Failed(node_index) => {
if let Some(error_markers) = error_markers.as_mut() {
error_markers.push(spawn_marker(
&mut commands,
grid_entity,
Color::Srgba(RED),
grid.pos_from_index(node_index),
));
}
}
}
}
if reinitialized {
commands.trigger_targets(GenerationResetEvent, grid_entity);
if let Some(error_markers) = error_markers.as_mut() {
for marker in error_markers.iter() {
marker_events.write(MarkerDespawnEvent::Marker(*marker));
}
error_markers.clear();
}
}
if !nodes_to_spawn.is_empty() {
commands.trigger_targets(NodesGeneratedEvent(nodes_to_spawn), grid_entity);
}
}
}
fn step_generation<C: CartesianCoordinates>(
generator: &mut Generator<C, CartesianGrid<C>>,
gen_entity: Entity,
void_nodes: Option<&VoidNodes>,
generation_control: &mut ResMut<GenerationControl>,
) {
loop {
if !handle_reinitialization_and_continue(generation_control, generator) {
break;
}
let mut non_void_spawned = false;
match generator.select_and_propagate_collected() {
Ok((status, nodes_to_spawn)) => {
for grid_node in nodes_to_spawn {
// We still collect the generated nodes here even though we don't really use them to spawn entities. We just check them for void nodes (for visualization purposes)
non_void_spawned = match void_nodes {
Some(void_nodes) => {
!void_nodes.contains(&grid_node.model_instance.model_index)
}
None => true,
};
}
match status {
GenerationStatus::Ongoing => {}
GenerationStatus::Done => {
handle_generation_done(generation_control, generator, gen_entity, 1);
break;
}
}
}
Err(GeneratorError { node_index }) => {
handle_generation_error(generation_control, generator, gen_entity, node_index);
break;
}
}
// If we want to skip over void nodes, we keep looping until we spawn a non-void
if non_void_spawned | !generation_control.skip_void_nodes {
break;
}
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/debug_plugin/mod.rs | bevy_ghx_proc_gen/src/debug_plugin/mod.rs | use std::marker::PhantomData;
use bevy::{
app::{App, Plugin, PluginGroup, PluginGroupBuilder},
color::{Alpha, Color},
ecs::resource::Resource,
input::keyboard::KeyCode,
};
use bevy_ghx_grid::ghx_grid::coordinate_system::CoordinateSystem;
use cursor::ProcGenDebugCursorPlugin;
use generation::{GenerationViewMode, ProcGenDebugGenerationPlugin};
use ghx_proc_gen::ghx_grid::cartesian::coordinates::CartesianCoordinates;
use picking::ProcGenDebugPickingPlugin;
use crate::{assets::BundleInserter, spawner_plugin::ProcGenSpawnerPlugin};
/// Module with picking features, enabled with the `picking` feature
#[cfg(feature = "picking")]
pub mod picking;
/// Module providing a small egui editor, enabled with the `egui-edit` feature
#[cfg(feature = "egui-edit")]
pub mod egui_editor;
/// Module providing all the grid cursors features
pub mod cursor;
/// Module handling the generation fetaures of the debug_plugin
pub mod generation;
/// Used to configure how the cursors UI should be displayed
#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
pub enum CursorUiMode {
/// No cursor UI display
None,
/// Display as a UI panel on the screen UI
Panel,
/// Display as a small overlay panel over the [cursor::Cursor]
#[default]
Overlay,
}
/// Resource used to customize cursors UI
#[derive(Resource, Debug)]
pub struct GridCursorsUiSettings {
/// Font size in the UI panels/overlays
pub font_size: f32,
/// Background color of the UI panels/overlays
pub background_color: Color,
/// Text colors in the UI panels/overlays
pub text_color: Color,
}
impl Default for GridCursorsUiSettings {
fn default() -> Self {
Self {
font_size: 16.0,
background_color: Color::BLACK.with_alpha(0.45),
text_color: Color::WHITE,
}
}
}
/// Configuration for a [ProcGenDebugRunnerPlugin]
#[derive(Default, Clone)]
pub struct DebugPluginConfig {
/// Controls how the generation occurs.
pub generation_view_mode: GenerationViewMode,
/// Used to configure how the cursors UI should be displayed
pub cursor_ui_mode: CursorUiMode,
}
/// A [`Plugin`] useful for debug/analysis/demo. It mainly run [`ghx_proc_gen::generator::Generator`] components
///
/// It takes in a [`GenerationViewMode`] to control how the generators components will be run.
///
/// It also uses the following `Resources`: [`ProcGenKeyBindings`] and [`generation::GenerationControl`] (and will init them to their defaults if not inserted by the user).
#[derive(Default)]
pub struct ProcGenDebugRunnerPlugin<C: CoordinateSystem> {
/// Configuration of the debug plugin
pub config: DebugPluginConfig,
#[doc(hidden)]
pub typestate: PhantomData<C>,
}
impl<C: CartesianCoordinates> Plugin for ProcGenDebugRunnerPlugin<C> {
fn build(&self, app: &mut App) {
// If the resources already exists, nothing happens, else, add them with default values.
app.init_resource::<ProcGenKeyBindings>();
app.add_plugins((
ProcGenDebugGenerationPlugin::<C>::new(&self.config),
ProcGenDebugCursorPlugin::<C>::new(&self.config),
));
#[cfg(feature = "egui-edit")]
app.add_plugins(egui_editor::plugin::<C>);
#[cfg(feature = "picking")]
app.add_plugins(ProcGenDebugPickingPlugin::<C>::new(&self.config));
}
}
/// A group of plugins that combines debug generation and nodes spawning
#[derive(Default)]
pub struct ProcGenDebugPlugins<C: CartesianCoordinates, A: BundleInserter> {
/// Configuration of the debug plugin
pub config: DebugPluginConfig,
#[doc(hidden)]
pub typestate: PhantomData<(C, A)>,
}
impl<C: CartesianCoordinates, A: BundleInserter> PluginGroup for ProcGenDebugPlugins<C, A> {
fn build(self) -> PluginGroupBuilder {
PluginGroupBuilder::start::<Self>()
.add(ProcGenDebugRunnerPlugin::<C> {
config: self.config,
typestate: PhantomData,
})
.add(ProcGenSpawnerPlugin::<C, A>::new())
}
}
/// Resource available to override the default keybindings used by the [`ProcGenDebugRunnerPlugin`], usign a QWERTY layout ()
#[derive(Resource)]
pub struct ProcGenKeyBindings {
/// Key to move the selection cursor to the previous node on the current axis
pub prev_node: KeyCode,
/// Key to move the selection cursor to the next node on the current axis
pub next_node: KeyCode,
/// Key pressed to enable the X axis selection
pub cursor_x_axis: KeyCode,
/// Key pressed to enable the Y axis selection
pub cursor_y_axis: KeyCode,
/// Key pressed to enable the Z axis selection
pub cursor_z_axis: KeyCode,
/// Key to deselect the current selection
pub deselect: KeyCode,
/// Key to move the selection cursor to another grid
pub switch_grid: KeyCode,
/// Key to pause/unpause the current [`generation::GenerationControlStatus`]
pub pause_toggle: KeyCode,
/// Key used only with [`GenerationViewMode::StepByStepManual`] to step once per press
pub step: KeyCode,
/// Key used only with [`GenerationViewMode::StepByStepManual`] to step continuously as long as pressed
pub continuous_step: KeyCode,
}
impl Default for ProcGenKeyBindings {
fn default() -> Self {
Self {
prev_node: KeyCode::ArrowLeft,
next_node: KeyCode::ArrowRight,
cursor_x_axis: KeyCode::KeyX,
cursor_y_axis: KeyCode::KeyY,
cursor_z_axis: KeyCode::KeyZ,
deselect: KeyCode::Escape,
switch_grid: KeyCode::Tab,
pause_toggle: KeyCode::Space,
step: KeyCode::ArrowDown,
continuous_step: KeyCode::ArrowUp,
}
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_ghx_proc_gen/src/debug_plugin/picking.rs | bevy_ghx_proc_gen/src/debug_plugin/picking.rs | use bevy::{
app::{App, Plugin, PostUpdate, Startup, Update},
asset::{Assets, Handle},
color::{Alpha, Color},
ecs::{
component::Component,
entity::Entity,
event::{Event, EventReader, EventWriter},
hierarchy::ChildOf,
query::{Changed, With, Without},
resource::Resource,
schedule::IntoScheduleConfigs,
system::{Commands, Local, Query, Res, ResMut},
},
input::{keyboard::KeyCode, ButtonInput},
math::{primitives::Cuboid, Vec2, Vec3},
pbr::{MeshMaterial3d, NotShadowCaster, StandardMaterial},
picking::{events::Pressed, Pickable},
prelude::{
AlphaMode, Deref, DerefMut, Mesh3d, OnAdd, Out, Over, Pointer, PointerButton, TextUiWriter,
Trigger,
},
render::mesh::Mesh,
sprite::Sprite,
transform::components::Transform,
utils::default,
};
use bevy_ghx_grid::{
debug_plugin::{
get_translation_from_grid_coords_3d,
markers::{GridMarker, MarkerDespawnEvent},
view::{DebugGridView, DebugGridView2d, DebugGridView3d},
},
ghx_grid::{coordinate_system::CoordinateSystem, direction::Direction},
};
use ghx_proc_gen::{
generator::Generator,
ghx_grid::cartesian::{coordinates::CartesianCoordinates, grid::CartesianGrid},
NodeIndex,
};
use std::{fmt::Debug, marker::PhantomData};
use crate::{
add_named_observer,
debug_plugin::{
cursor::{setup_cursor, setup_cursors_overlays, SelectionCursorMarkerSettings},
CursorUiMode,
},
CursorTarget, GenerationResetEvent, GridNode,
};
use super::{
cursor::{
cursor_info_to_string, Cursor, CursorBehavior, CursorInfo, CursorMarkerSettings,
CursorsPanelText, SelectCursor, TargetedNode, OVER_CURSOR_SECTION_INDEX,
},
generation::ActiveGeneration,
DebugPluginConfig, ProcGenKeyBindings,
};
/// Picking plugin for the [super::ProcGenDebugRunnerPlugin]
#[derive(Default)]
pub(crate) struct ProcGenDebugPickingPlugin<C: CartesianCoordinates> {
/// Used to configure how the cursors UI should be displayed
pub cursor_ui_mode: CursorUiMode,
#[doc(hidden)]
pub typestate: PhantomData<C>,
}
impl<C: CartesianCoordinates> Plugin for ProcGenDebugPickingPlugin<C> {
fn build(&self, app: &mut App) {
app.init_resource::<CursorTargetAssets>()
.init_resource::<OverCursorMarkerSettings>();
app.add_event::<NodeOverEvent>()
.add_event::<NodeOutEvent>()
.add_event::<NodeSelectedEvent>();
app.add_systems(
Startup,
(
setup_picking_assets,
setup_cursor::<C, OverCursor>.after(setup_cursors_overlays),
),
)
.add_systems(
Update,
(
update_cursor_targets_nodes::<C>,
(
picking_remove_previous_over_cursor::<C>,
picking_update_cursors_position::<
C,
OverCursorMarkerSettings,
OverCursor,
NodeOverEvent,
>,
picking_update_cursors_position::<
C,
SelectionCursorMarkerSettings,
SelectCursor,
NodeSelectedEvent,
>,
)
.chain(),
),
);
add_named_observer!(insert_cursor_picking_handlers_on_grid_nodes::<C>, app);
add_named_observer!(update_over_cursor_on_generation_reset::<C>, app);
if self.cursor_ui_mode == CursorUiMode::Panel {
app.add_systems(PostUpdate, update_over_cursor_panel_text);
}
}
}
impl<C: CartesianCoordinates> ProcGenDebugPickingPlugin<C> {
/// Constructor
pub fn new(config: &DebugPluginConfig) -> Self {
Self {
cursor_ui_mode: config.cursor_ui_mode,
..Default::default()
}
}
}
/// Used to customize the color of the Over cursor [GridMarker]
#[derive(Resource)]
pub struct OverCursorMarkerSettings(pub Color);
impl Default for OverCursorMarkerSettings {
fn default() -> Self {
Self(Color::srgb(0.85, 0.85, 0.73))
}
}
impl CursorMarkerSettings for OverCursorMarkerSettings {
fn color(&self) -> Color {
self.0
}
}
/// Main component for the Over cursor
#[derive(Component, Debug)]
pub struct OverCursor;
impl CursorBehavior for OverCursor {
fn new() -> Self {
Self
}
fn updates_active_gen() -> bool {
false
}
}
/// Event raised when a node starts being overed by a mouse pointer
#[derive(Event, Deref, DerefMut, Debug, Clone)]
pub struct NodeOverEvent(pub Entity);
impl From<Entity> for NodeOverEvent {
fn from(target: Entity) -> Self {
NodeOverEvent(target)
}
}
/// Event raised when a node stops being overed by a mouse pointer
#[derive(Event, Deref, DerefMut)]
pub struct NodeOutEvent(pub Entity);
impl From<Entity> for NodeOutEvent {
fn from(target: Entity) -> Self {
NodeOutEvent(target)
}
}
/// Event raised when a node is selected by a mouse pointer
#[derive(Event, Deref, DerefMut)]
pub struct NodeSelectedEvent(pub Entity);
impl From<Entity> for NodeSelectedEvent {
fn from(target: Entity) -> Self {
NodeSelectedEvent(target)
}
}
/// System that inserts picking event handlers to entites with an added [GridNode] component
pub fn insert_cursor_picking_handlers_on_grid_nodes<C: CoordinateSystem>(
trigger: Trigger<OnAdd, GridNode>,
mut commands: Commands,
) {
commands
.entity(trigger.target())
.insert(Pickable::default())
.observe(retransmit_event::<Pointer<Over>, NodeOverEvent>)
.observe(retransmit_event::<Pointer<Out>, NodeOutEvent>)
.observe(
|trigger: Trigger<Pointer<Pressed>>,
mut selection_events: EventWriter<NodeSelectedEvent>| {
if trigger.button == PointerButton::Primary {
selection_events.write(NodeSelectedEvent(trigger.target()));
}
},
);
}
fn retransmit_event<PE: Event + Clone + Debug, NE: Event + From<Entity>>(
pointer_ev_trigger: Trigger<PE>,
mut events: EventWriter<NE>,
) {
events.write(NE::from(pointer_ev_trigger.target()));
}
/// System that update the over cursor UI panel
pub fn update_over_cursor_panel_text(
mut writer: TextUiWriter,
mut cursors_panel_text: Query<Entity, With<CursorsPanelText>>,
updated_cursors: Query<(&CursorInfo, &Cursor), (Changed<CursorInfo>, With<OverCursor>)>,
) {
if let Ok((cursor_info, cursor)) = updated_cursors.single() {
for panel_entity in &mut cursors_panel_text {
let mut ui_text = writer.text(panel_entity, OVER_CURSOR_SECTION_INDEX);
match &cursor.0 {
Some(overed_node) => {
*ui_text = format!(
"Hovered:\n{}",
cursor_info_to_string(overed_node, cursor_info)
);
}
None => ui_text.clear(),
}
}
}
}
/// Observer updating the Over [Cursor] based on [GenerationResetEvent]
pub fn update_over_cursor_on_generation_reset<C: CoordinateSystem>(
trigger: Trigger<GenerationResetEvent>,
mut marker_events: EventWriter<MarkerDespawnEvent>,
mut over_cursor: Query<&mut Cursor, With<OverCursor>>,
) {
let Ok(mut cursor) = over_cursor.single_mut() else {
return;
};
// If there is an Over cursor, force despawn it, since we will despawn the underlying node there won't be any NodeOutEvent.
if let Some(overed_node) = &cursor.0 {
if overed_node.grid == trigger.target() {
marker_events.write(MarkerDespawnEvent::Marker(overed_node.marker));
cursor.0 = None;
}
}
}
/// System used to update cursor positions from picking events
pub fn picking_update_cursors_position<
C: CartesianCoordinates,
CS: CursorMarkerSettings,
CB: CursorBehavior,
PE: Event + std::ops::DerefMut<Target = Entity>,
>(
mut commands: Commands,
cursor_marker_settings: Res<CS>,
mut active_generation: ResMut<ActiveGeneration>,
mut events: EventReader<PE>,
mut marker_events: EventWriter<MarkerDespawnEvent>,
grid_nodes: Query<(&GridNode, &ChildOf)>,
mut cursor: Query<&mut Cursor, With<CB>>,
generations: Query<(Entity, &CartesianGrid<C>), With<Generator<C, CartesianGrid<C>>>>,
) {
if let Some(event) = events.read().last() {
let Ok(mut cursor) = cursor.single_mut() else {
return;
};
let Ok((node, node_parent)) = grid_nodes.get(*event.deref()) else {
return;
};
let picked_grid_entity = node_parent.parent();
let update_cursor = match &cursor.0 {
Some(targeted_node) => {
if (targeted_node.grid != picked_grid_entity) || (targeted_node.index != node.0) {
marker_events.write(MarkerDespawnEvent::Marker(targeted_node.marker));
true
} else {
false
}
}
None => true,
};
if update_cursor {
let Ok((gen_entity, grid)) = generations.get(picked_grid_entity) else {
return;
};
if CB::updates_active_gen() {
active_generation.0 = Some(gen_entity);
}
let position = grid.pos_from_index(node.0);
let marker = commands
.spawn(GridMarker::new(cursor_marker_settings.color(), position))
.id();
commands.entity(picked_grid_entity).add_child(marker);
cursor.0 = Some(TargetedNode {
grid: picked_grid_entity,
index: node.0,
position,
marker,
});
}
}
}
/// System used to remove an Over cursor on a [NodeOutEvent]
pub fn picking_remove_previous_over_cursor<C: CoordinateSystem>(
mut out_events: EventReader<NodeOutEvent>,
mut marker_events: EventWriter<MarkerDespawnEvent>,
mut nodes: Query<&GridNode>,
mut over_cursor: Query<&mut Cursor, With<OverCursor>>,
) {
if let Some(event) = out_events.read().last() {
let Ok(mut cursor) = over_cursor.single_mut() else {
return;
};
let Some(overed_node) = &cursor.0 else {
return;
};
if let Ok(node) = nodes.get_mut(**event) {
if overed_node.index == node.0 {
marker_events.write(MarkerDespawnEvent::Marker(overed_node.marker));
cursor.0 = None;
}
}
}
}
/// Settings and assets used by the [CursorTarget]
#[derive(Resource, Default)]
pub struct CursorTargetAssets {
color: Color,
base_size: f32,
target_mesh_3d: Handle<Mesh>,
target_mat_3d: Handle<StandardMaterial>,
}
/// System used to insert default values into [CursorTargetAssets]
pub fn setup_picking_assets(
mut meshes: ResMut<Assets<Mesh>>,
mut standard_materials: ResMut<Assets<StandardMaterial>>,
mut cursor_target_assets: ResMut<CursorTargetAssets>,
) {
cursor_target_assets.color = Color::WHITE.with_alpha(0.15);
cursor_target_assets.base_size = 0.9;
cursor_target_assets.target_mesh_3d = meshes.add(Mesh::from(Cuboid {
half_size: Vec3::splat(cursor_target_assets.base_size / 2.),
}));
cursor_target_assets.target_mat_3d = standard_materials.add(StandardMaterial {
base_color: cursor_target_assets.color,
alpha_mode: AlphaMode::Blend,
unlit: true,
..default()
});
}
/// Local system resource used to cache and track cursor targets current siutation
#[derive(Default)]
pub struct ActiveCursorTargets {
/// Current axis
pub axis: Direction,
/// Current source node
pub from_node: NodeIndex,
}
/// System that spawn & despawn the cursor targets
pub fn update_cursor_targets_nodes<C: CartesianCoordinates>(
mut local_active_cursor_targets: Local<Option<ActiveCursorTargets>>,
mut commands: Commands,
keys: Res<ButtonInput<KeyCode>>,
cursor_target_assets: Res<CursorTargetAssets>,
proc_gen_key_bindings: Res<ProcGenKeyBindings>,
mut marker_events: EventWriter<MarkerDespawnEvent>,
selection_cursor: Query<&Cursor, With<SelectCursor>>,
mut over_cursor: Query<&mut Cursor, (With<OverCursor>, Without<SelectCursor>)>,
grids_with_cam3d: Query<(&CartesianGrid<C>, &DebugGridView), With<DebugGridView3d>>,
grids_with_cam2d: Query<
(&CartesianGrid<C>, &DebugGridView),
(With<DebugGridView2d>, Without<DebugGridView3d>),
>,
cursor_targets: Query<Entity, With<CursorTarget>>,
) {
let Ok(selection_cursor) = selection_cursor.single() else {
return;
};
let Some(selected_node) = &selection_cursor.0 else {
return;
};
let axis_selection = if keys.pressed(proc_gen_key_bindings.cursor_x_axis) {
Some(Direction::XForward)
} else if keys.pressed(proc_gen_key_bindings.cursor_y_axis) {
Some(Direction::YForward)
} else if keys.pressed(proc_gen_key_bindings.cursor_z_axis) {
Some(Direction::ZForward)
} else {
None
};
if let Some(axis) = axis_selection {
if let Some(active_targets) = local_active_cursor_targets.as_mut() {
if selected_node.index != active_targets.from_node {
despawn_cursor_targets(
&mut commands,
&mut marker_events,
&cursor_targets,
&mut over_cursor,
);
spawn_cursor_targets(
&mut commands,
&cursor_target_assets,
selected_node,
axis,
&grids_with_cam3d,
&grids_with_cam2d,
);
active_targets.from_node = selected_node.index;
active_targets.axis = axis;
}
} else {
spawn_cursor_targets(
&mut commands,
&cursor_target_assets,
selected_node,
axis,
&grids_with_cam3d,
&grids_with_cam2d,
);
*local_active_cursor_targets = Some(ActiveCursorTargets {
axis,
from_node: selected_node.index,
});
}
} else if local_active_cursor_targets.is_some() {
*local_active_cursor_targets = None;
despawn_cursor_targets(
&mut commands,
&mut marker_events,
&cursor_targets,
&mut over_cursor,
);
}
}
/// Function used to despawn all cursor targets and eventually the attached over cursor
pub fn despawn_cursor_targets(
commands: &mut Commands,
marker_events: &mut EventWriter<MarkerDespawnEvent>,
cursor_targets: &Query<Entity, With<CursorTarget>>,
over_cursor: &mut Query<&mut Cursor, (With<OverCursor>, Without<SelectCursor>)>,
) {
for cursor_target in cursor_targets.iter() {
commands.entity(cursor_target).despawn();
}
if let Ok(mut over_cursor) = over_cursor.single_mut() {
// If there is an Over cursor, force despawn it, since we will despawn the underlying node there won't be any NodeOutEvent.
if let Some(grid_cursor) = &over_cursor.0 {
marker_events.write(MarkerDespawnEvent::Marker(grid_cursor.marker));
over_cursor.0 = None;
}
};
}
/// Function used to spawn cursor targets
pub fn spawn_cursor_targets<C: CartesianCoordinates>(
commands: &mut Commands,
cursor_target_assets: &Res<CursorTargetAssets>,
selected_node: &TargetedNode,
axis: Direction,
grids_with_cam3d: &Query<(&CartesianGrid<C>, &DebugGridView), With<DebugGridView3d>>,
grids_with_cam2d: &Query<
(&CartesianGrid<C>, &DebugGridView),
(With<DebugGridView2d>, Without<DebugGridView3d>),
>,
) {
if let Ok((grid, grid_view)) = grids_with_cam3d.get(selected_node.grid) {
spawn_cursor_targets_3d(
commands,
&cursor_target_assets,
axis,
selected_node,
grid,
&grid_view.node_size,
);
} else if let Ok((grid, grid_view)) = grids_with_cam2d.get(selected_node.grid) {
spawn_cursor_targets_2d(
commands,
&cursor_target_assets,
axis,
selected_node,
grid,
&grid_view.node_size,
);
}
}
/// Function used to spawn cursor targets when using a 3d camera
pub fn spawn_cursor_targets_3d<C: CartesianCoordinates>(
commands: &mut Commands,
cursor_target_assets: &Res<CursorTargetAssets>,
axis: Direction,
selected_node: &TargetedNode,
grid: &CartesianGrid<C>,
node_size: &Vec3,
) {
let mut spawn_cursor_target = |x: u32, y: u32, z: u32| {
let translation = get_translation_from_grid_coords_3d(x, y, z, node_size);
let helper_node_entity = commands
.spawn((
GridNode(grid.index_from_coords(x, y, z)),
CursorTarget,
NotShadowCaster,
Transform::from_translation(translation).with_scale(*node_size),
Mesh3d(cursor_target_assets.target_mesh_3d.clone_weak()),
MeshMaterial3d(cursor_target_assets.target_mat_3d.clone_weak()),
))
.id();
commands
.entity(selected_node.grid)
.add_child(helper_node_entity);
};
match axis {
Direction::XForward => {
for x in 0..grid.size_x() {
spawn_cursor_target(x, selected_node.position.y, selected_node.position.z);
}
for y in 0..grid.size_y() {
for z in 0..grid.size_z() {
spawn_cursor_target(selected_node.position.x, y, z);
}
}
}
Direction::YForward => {
for y in 0..grid.size_y() {
spawn_cursor_target(selected_node.position.x, y, selected_node.position.z);
}
for x in 0..grid.size_x() {
for z in 0..grid.size_z() {
spawn_cursor_target(x, selected_node.position.y, z);
}
}
}
Direction::ZForward => {
for z in 0..grid.size_z() {
spawn_cursor_target(selected_node.position.x, selected_node.position.y, z);
}
for x in 0..grid.size_x() {
for y in 0..grid.size_y() {
spawn_cursor_target(x, y, selected_node.position.z);
}
}
}
_ => {}
}
}
/// Function used to spawn cursor targets when using a 2d camera
pub fn spawn_cursor_targets_2d<C: CartesianCoordinates>(
commands: &mut Commands,
cursor_target_assets: &Res<CursorTargetAssets>,
axis: Direction,
selected_node: &TargetedNode,
grid: &CartesianGrid<C>,
node_size: &Vec3,
) {
let mut spawn_cursor_target = |x: u32, y: u32, z: u32| {
let mut translation = get_translation_from_grid_coords_3d(x, y, z, node_size);
translation.z += node_size.z;
let helper_node_entity = commands
.spawn((
GridNode(grid.index_from_coords(x, y, z)),
CursorTarget,
Transform::from_translation(translation).with_scale(*node_size),
// TODO: Here MaterialMesh2dBundle + PickableBundle::default() did not interact with picking. Not sure why yet. Using Sprite instead.
Sprite {
color: cursor_target_assets.color,
custom_size: Some(Vec2::splat(cursor_target_assets.base_size)),
..default()
},
Pickable::default(),
))
.id();
commands
.entity(selected_node.grid)
.add_child(helper_node_entity);
};
match axis {
Direction::XForward | Direction::YForward => {
for x in 0..grid.size_x() {
spawn_cursor_target(x, selected_node.position.y, selected_node.position.z);
}
for y in 0..grid.size_y() {
spawn_cursor_target(selected_node.position.x, y, selected_node.position.z);
}
}
Direction::ZForward => {
for x in 0..grid.size_x() {
for y in 0..grid.size_y() {
spawn_cursor_target(x, y, selected_node.position.z);
}
}
}
_ => {}
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/examples/unicode-terrain.rs | examples/unicode-terrain.rs | use std::{
io::{stdin, stdout, Write},
thread, time,
};
use ghx_proc_gen::{
generator::{
model::{ModelCollection, ModelInstance},
node_heuristic::NodeSelectionHeuristic,
observer::QueuedStatefulObserver,
rules::RulesBuilder,
socket::{SocketCollection, SocketsCartesian2D},
GenerationStatus, ModelSelectionHeuristic,
},
ghx_grid::{
cartesian::{coordinates::Cartesian2D, grid::CartesianGrid},
grid::GridData,
},
};
use ghx_proc_gen::generator::{builder::GeneratorBuilder, RngMode};
pub enum GenerationViewMode {
/// The parameter is the number of milliseconds to wait between each step.
StepByStepTimed(u64),
StepByStepPaused,
Final,
}
// Change this to change how the generation advancess
const GENERATION_VIEW_MODE: GenerationViewMode = GenerationViewMode::Final;
fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
let mut sockets = SocketCollection::new();
let mountain = sockets.create();
let forest = sockets.create();
let meadows = sockets.create();
let beach = sockets.create();
let sea = sockets.create();
let deep_sea = sockets.create();
let mut models = ModelCollection::<Cartesian2D>::new();
let mut icons = Vec::new();
icons.push("🗻");
models.create(SocketsCartesian2D::Mono(mountain));
icons.push("🌲"); // Variation 1
models
.create(SocketsCartesian2D::Mono(forest))
.with_weight(0.5);
icons.push("🌳"); // Variation 2
models
.create(SocketsCartesian2D::Mono(forest))
.with_weight(0.5);
icons.push("🟩");
models.create(SocketsCartesian2D::Mono(meadows));
icons.push("🟨");
models.create(SocketsCartesian2D::Mono(beach));
icons.push("🟦");
models.create(SocketsCartesian2D::Mono(sea));
icons.push("🟦");
models
.create(SocketsCartesian2D::Mono(deep_sea))
.with_weight(2.);
sockets.add_connections(vec![
(mountain, vec![mountain, forest]),
(forest, vec![forest, meadows]),
(meadows, vec![meadows, beach]),
(beach, vec![beach, sea]),
(sea, vec![sea]),
(deep_sea, vec![sea]),
]);
let rules = RulesBuilder::new_cartesian_2d(models, sockets)
.build()
.unwrap();
let grid = CartesianGrid::new_cartesian_2d(35, 12, false, false);
let mut generator = GeneratorBuilder::new()
.with_rules(rules)
.with_grid(grid)
.with_max_retry_count(10)
.with_rng(RngMode::RandomSeed)
.with_node_heuristic(NodeSelectionHeuristic::Random)
.with_model_heuristic(ModelSelectionHeuristic::WeightedProbability)
.build()
.unwrap();
let mut observer = QueuedStatefulObserver::new(&mut generator);
match GENERATION_VIEW_MODE {
GenerationViewMode::Final => {
generator.generate().unwrap();
observer.dequeue_all();
println!("Final grid:");
display_grid(observer.grid_data(), &icons);
}
_ => {
let mut step = 0;
let mut done = false;
while !done {
match generator.select_and_propagate() {
Ok(status) => match status {
GenerationStatus::Ongoing => (),
GenerationStatus::Done => done = true,
},
Err(_) => (),
}
observer.dequeue_all();
println!("Grid at iteration n°{}:", step);
display_grid(observer.grid_data(), &icons);
match GENERATION_VIEW_MODE {
GenerationViewMode::StepByStepTimed(delay) => {
thread::sleep(time::Duration::from_millis(delay));
}
GenerationViewMode::StepByStepPaused => pause(),
_ => (),
}
step += 1;
}
}
}
}
fn display_grid(
data_grid: &GridData<Cartesian2D, Option<ModelInstance>, CartesianGrid<Cartesian2D>>,
icons: &Vec<&'static str>,
) {
for y in (0..data_grid.grid().size_y()).rev() {
for x in 0..data_grid.grid().size_x() {
match data_grid.get_2d(x, y) {
None => print!("❓"),
Some(node) => print!("{}", icons[node.model_index]),
}
}
println!();
}
}
fn pause() {
let mut word = String::new();
let mut stdout = stdout();
stdout.write(b"Press Enter to continue").unwrap();
stdout.flush().unwrap();
stdin().read_line(&mut word).unwrap();
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/examples/chessboard.rs | examples/chessboard.rs | use std::error::Error;
use ghx_proc_gen::{
generator::{
builder::GeneratorBuilder,
model::ModelCollection,
rules::RulesBuilder,
socket::{SocketCollection, SocketsCartesian2D},
},
ghx_grid::cartesian::{
coordinates::{Cartesian2D, CartesianPosition},
grid::CartesianGrid,
},
};
fn main() -> Result<(), Box<dyn Error>> {
// A SocketCollection is what we use to create sockets and define their connections
let mut sockets = SocketCollection::new();
// For this example, we will only need two sockets
let (white, black) = (sockets.create(), sockets.create());
// With the following, a white socket can connect to a black socket and vice-versa
sockets.add_connection(white, vec![black]);
let mut models = ModelCollection::<Cartesian2D>::new();
// We define 2 very simple models: a white tile model with the `white` socket on each side
// and a black tile model with the `black` socket on each side
models.create(SocketsCartesian2D::Mono(white));
// We keep the black model for later
let black_model = models.create(SocketsCartesian2D::Mono(black)).clone();
// We give the models and socket collection to a RulesBuilder and get our Rules
let rules = RulesBuilder::new_cartesian_2d(models, sockets)
.build()
.unwrap();
// Like a chess board, let's do an 8x8 2d grid
let grid = CartesianGrid::new_cartesian_2d(8, 8, false, false);
// There many more parameters you can tweak on a Generator before building it, explore the API.
let mut generator = GeneratorBuilder::new()
.with_rules(rules)
.with_grid(grid)
// Let's ensure that we make a chessboard, with a black square bottom-left
.with_initial_nodes(vec![(CartesianPosition::new_xy(0, 0), black_model)])?
.build()?;
// Here we directly generate the whole grid, and ask for the result to be returned.
// The generation could also be done iteratively via `generator.select_and_propagate()`, or the results could be obtained through an `Observer`
let (_gen_info, chess_pattern) = generator.generate_grid().unwrap();
let icons = vec!["◻️ ", "⬛"];
// We draw from top to bottom
for y in (0..chess_pattern.grid().size_y()).rev() {
for x in 0..chess_pattern.grid().size_x() {
print!("{}", icons[chess_pattern.get_2d(x, y).model_index]);
}
println!();
}
Ok(())
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/pillars/rules.rs | bevy_examples/pillars/rules.rs | use bevy_examples::utils::ModelAssetDef;
use bevy_ghx_proc_gen::proc_gen::{
generator::{
model::ModelCollection,
socket::{SocketCollection, SocketsCartesian3D},
},
ghx_grid::cartesian::coordinates::Cartesian3D,
};
pub(crate) fn rules_and_assets() -> (
Vec<Vec<ModelAssetDef>>,
ModelCollection<Cartesian3D>,
SocketCollection,
) {
let mut sockets = SocketCollection::new();
let void = sockets.create();
let pillar_side = sockets.create();
let pillar_base_top = sockets.create();
let pillar_base_bottom = sockets.create();
let pillar_core_bottom = sockets.create();
let pillar_core_top = sockets.create();
let pillar_cap_bottom = sockets.create();
let pillar_cap_top = sockets.create();
let mut models_assets: Vec<Vec<ModelAssetDef>> = Vec::new();
let mut models = ModelCollection::new();
models_assets.push(vec![]);
models
.create(
SocketsCartesian3D::Mono(void)
.to_template()
.with_weight(60.),
)
.with_name("void");
models_assets.push(vec![ModelAssetDef::new("pillar_base")]);
models
.create(SocketsCartesian3D::Simple {
x_pos: pillar_side,
x_neg: pillar_side,
z_pos: pillar_side,
z_neg: pillar_side,
y_pos: pillar_base_top,
y_neg: pillar_base_bottom,
})
.with_name("pillar_base");
models_assets.push(vec![ModelAssetDef::new("pillar_core")]);
models
.create(SocketsCartesian3D::Simple {
x_pos: pillar_side,
x_neg: pillar_side,
z_pos: pillar_side,
z_neg: pillar_side,
y_pos: pillar_core_top,
y_neg: pillar_core_bottom,
})
.with_name("pillar_core");
models_assets.push(vec![ModelAssetDef::new("pillar_cap")]);
models
.create(SocketsCartesian3D::Simple {
x_pos: pillar_side,
x_neg: pillar_side,
z_pos: pillar_side,
z_neg: pillar_side,
y_pos: pillar_cap_top,
y_neg: pillar_cap_bottom,
})
.with_name("pillar_cap");
sockets
.add_connections(vec![
(void, vec![void]),
(pillar_side, vec![pillar_side, void]),
])
// For this generation, our rotation axis is Y+, so we define connection on the Y axis with `add_rotated_connection` for sockets that still need to be compatible when rotated.
// Note: But in reality, in this example, we don't really need it. None of our models uses any rotation, apart from ModelRotation::Rot0 (notice that there's no call to `with_rotations` on any of the models).
// Simply using `add_connections` would give the same result (it allows connections with relative_rotation = Rot0)
.add_rotated_connections(vec![
(pillar_base_top, vec![pillar_core_bottom]),
(pillar_core_top, vec![pillar_core_bottom, pillar_cap_bottom]),
(pillar_cap_top, vec![void]),
]);
(models_assets, models, sockets)
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/pillars/pillars.rs | bevy_examples/pillars/pillars.rs | use std::{f32::consts::PI, sync::Arc};
use bevy::{
app::{App, Startup},
asset::{AssetServer, Assets, Handle},
color::{
palettes::css::{GRAY, ORANGE_RED},
Color,
},
core_pipeline::core_3d::Camera3d,
ecs::name::Name,
log::LogPlugin,
math::{EulerRot, Quat, Vec3},
pbr::{
AmbientLight, DirectionalLight, DirectionalLightShadowMap, DistanceFog, FogFalloff,
MeshMaterial3d, StandardMaterial,
},
prelude::{Commands, Mesh, Mesh3d, Plane3d, PluginGroup, Res, ResMut, Transform},
scene::Scene,
utils::default,
DefaultPlugins,
};
use bevy_editor_cam::{prelude::EditorCam, DefaultEditorCamPlugins};
use bevy_examples::{plugin::ProcGenExamplesPlugin, utils::load_assets};
use bevy_ghx_proc_gen::{
assets::ModelsAssets,
bevy_ghx_grid::debug_plugin::{view::DebugGridView, DebugGridView3dBundle},
debug_plugin::generation::GenerationViewMode,
proc_gen::{
generator::{builder::GeneratorBuilder, rules::RulesBuilder},
ghx_grid::cartesian::{coordinates::Cartesian3D, grid::CartesianGrid},
},
spawner_plugin::NodesSpawner,
};
use crate::rules::rules_and_assets;
mod rules;
// ----------------- Configurable values ---------------------------
/// Modify this value to control the way the generation is visualized
const GENERATION_VIEW_MODE: GenerationViewMode = GenerationViewMode::Final;
/// Modify these values to control the map size.
const GRID_HEIGHT: u32 = 7;
const GRID_X: u32 = 30;
const GRID_Z: u32 = 70;
// ------------------------------------------------------------------
/// Size of a block in world units
const BLOCK_SIZE: f32 = 1.;
const NODE_SIZE: Vec3 = Vec3::splat(BLOCK_SIZE);
const ASSETS_SCALE_FACTOR: f32 = BLOCK_SIZE / 4.; // Models are 4 units wide
const ASSETS_SCALE: Vec3 = Vec3::splat(ASSETS_SCALE_FACTOR);
fn setup_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let camera_position = Vec3::new(0., 3. * GRID_HEIGHT as f32, 0.75 * GRID_Z as f32);
commands.spawn((
Name::new("Camera"),
Transform::from_translation(camera_position).looking_at(Vec3::ZERO, Vec3::Y),
Camera3d::default(),
EditorCam::default(),
DistanceFog {
color: Color::srgba(0.2, 0.15, 0.1, 1.0),
falloff: FogFalloff::Linear {
start: 55.0,
end: 145.0,
},
..default()
},
));
commands.spawn((
Name::new("Ground plane"),
Transform::from_scale(Vec3::splat(10000.0)).with_translation(Vec3::new(
0.,
BLOCK_SIZE / 2.,
0.,
)),
Mesh3d(meshes.add(Mesh::from(Plane3d::default()))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::srgb(0.21, 0.21, 0.21),
..default()
})),
));
// Scene lights
commands.insert_resource(AmbientLight {
color: Color::Srgba(ORANGE_RED),
brightness: 0.05,
..default()
});
commands.spawn((
Name::new("Main light"),
Transform {
translation: Vec3::new(0.0, 0.0, 0.0),
rotation: Quat::from_euler(EulerRot::ZYX, 0., -PI / 5., -PI / 3.),
..default()
},
DirectionalLight {
shadows_enabled: true,
illuminance: 3000.,
color: Color::srgb(1.0, 0.85, 0.65),
..default()
},
));
commands.spawn((
Name::new("Back light"),
Transform {
translation: Vec3::new(5.0, 10.0, 2.0),
rotation: Quat::from_euler(EulerRot::ZYX, 0., PI * 4. / 5., -PI / 3.),
..default()
},
DirectionalLight {
shadows_enabled: false,
illuminance: 1250.,
color: Color::srgb(1.0, 0.85, 0.65),
..default()
},
));
}
fn setup_generator(mut commands: Commands, asset_server: Res<AssetServer>) {
// Get rules from rules.rs
let (models_asset_paths, models, socket_collection) = rules_and_assets();
let rules = Arc::new(
RulesBuilder::new_cartesian_3d(models, socket_collection)
.build()
.unwrap(),
);
let grid = CartesianGrid::new_cartesian_3d(GRID_X, GRID_HEIGHT, GRID_Z, false, false, false);
let gen_builder = GeneratorBuilder::new()
// We share the Rules between all the generators
.with_shared_rules(rules.clone())
.with_grid(grid.clone());
let models_assets: ModelsAssets<Handle<Scene>> =
load_assets(&asset_server, models_asset_paths, "pillars", "glb#Scene0");
let node_spawner = NodesSpawner::new(
models_assets,
NODE_SIZE,
// We spawn assets with a scale of 0 since we animate their scale in the examples
Vec3::ZERO,
);
for i in 0..=1 {
let mut gen_builder = gen_builder.clone();
let observer = gen_builder.add_queued_observer();
let generator = gen_builder.build().unwrap();
commands.spawn((
Name::new(format!("Grid n°{}", i)),
Transform::from_translation(Vec3 {
x: (grid.size_x() as f32) * (i as f32 - 1.),
y: 0.,
z: -(grid.size_z() as f32) * 0.5,
}),
grid.clone(),
generator,
observer,
// We also share the ModelsAssets between all the generators
node_spawner.clone(),
DebugGridView3dBundle {
view: DebugGridView::new(false, true, Color::Srgba(GRAY), NODE_SIZE),
..default()
},
));
}
}
fn main() {
let mut app = App::new();
app.insert_resource(DirectionalLightShadowMap { size: 4096 });
app.add_plugins((
DefaultPlugins.set(LogPlugin {
filter: "info,wgpu_core=error,wgpu_hal=error,ghx_proc_gen=debug".into(),
level: bevy::log::Level::DEBUG,
..default()
}),
DefaultEditorCamPlugins,
ProcGenExamplesPlugin::<Cartesian3D, Handle<Scene>>::new(
GENERATION_VIEW_MODE,
ASSETS_SCALE,
),
));
app.add_systems(Startup, (setup_generator, setup_scene));
app.run();
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/src/lib.rs | bevy_examples/src/lib.rs | pub mod anim;
pub mod plugin;
pub mod utils;
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/src/utils.rs | bevy_examples/src/utils.rs | use bevy::{
asset::{Asset, AssetServer, Handle},
ecs::system::Res,
math::Vec3,
prelude::EntityCommands,
};
use bevy_ghx_proc_gen::{
assets::{BundleInserter, ModelAsset, ModelsAssets},
proc_gen::ghx_grid::cartesian::coordinates::GridDelta,
};
/// Used to define an asset (not yet loaded) for a model: via an asset path, and an optionnal grid offset when spawned in Bevy
#[derive(Clone)]
pub struct ModelAssetDef {
/// Path of the asset
pub path: &'static str,
/// Offset in grid coordinates
pub grid_offset: GridDelta,
/// Offset in world coordinates
pub offset: Vec3,
pub components_spawner: fn(&mut EntityCommands),
}
impl ModelAssetDef {
pub fn new(path: &'static str) -> Self {
Self {
path,
grid_offset: GridDelta::new(0, 0, 0),
offset: Vec3::ZERO,
components_spawner: |_| {},
}
}
pub fn with_grid_offset(mut self, offset: GridDelta) -> Self {
self.grid_offset = offset;
self
}
pub fn with_offset(mut self, offset: Vec3) -> Self {
self.offset = offset;
self
}
pub fn with_components(mut self, spawn_cmds: fn(&mut EntityCommands)) -> Self {
self.components_spawner = spawn_cmds;
self
}
pub fn path(&self) -> &'static str {
self.path
}
pub fn offset(&self) -> &GridDelta {
&self.grid_offset
}
}
pub fn load_assets<A: Asset>(
asset_server: &Res<AssetServer>,
assets_definitions: Vec<Vec<ModelAssetDef>>,
assets_directory: &str,
extension: &str,
) -> ModelsAssets<Handle<A>>
where
Handle<A>: BundleInserter,
{
let mut models_assets = ModelsAssets::<Handle<A>>::new();
for (model_index, assets) in assets_definitions.iter().enumerate() {
for asset_def in assets {
models_assets.add(
model_index,
ModelAsset {
assets_bundle: asset_server.load::<A>(format!(
"{assets_directory}/{}.{extension}",
asset_def.path()
)),
grid_offset: asset_def.grid_offset.clone(),
world_offset: asset_def.offset,
spawn_commands: asset_def.components_spawner.clone(),
},
)
}
}
models_assets
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/src/anim.rs | bevy_examples/src/anim.rs | use bevy::{
ecs::{
component::Component,
entity::Entity,
resource::Resource,
system::{Commands, Query, Res},
},
math::Vec3,
time::Time,
transform::components::Transform,
};
/// Used for the examples
#[derive(Component, Clone, Resource)]
pub struct SpawningScaleAnimation {
pub duration_sec: f32,
pub progress: f32,
pub easing: fn(f32) -> f32,
pub final_scale: Vec3,
}
impl SpawningScaleAnimation {
pub fn new(duration_sec: f32, final_scale: Vec3, easing: fn(f32) -> f32) -> Self {
Self {
duration_sec,
final_scale,
easing,
progress: 0.,
}
}
pub fn advance(&mut self, delta_sec: f32) {
self.progress += delta_sec;
}
pub fn ended(&self) -> bool {
self.progress >= self.duration_sec
}
pub fn progress_factor(&self) -> f32 {
self.progress / self.duration_sec
}
pub fn current_value(&self) -> Vec3 {
self.final_scale * (self.easing)(self.progress_factor())
}
pub fn final_value(&self) -> Vec3 {
self.final_scale
}
}
pub fn animate_scale(
mut commands: Commands,
time: Res<Time>,
mut spawning_nodes: Query<(Entity, &mut Transform, &mut SpawningScaleAnimation)>,
) {
for (entity, mut transform, mut animation) in spawning_nodes.iter_mut() {
animation.advance(time.delta_secs());
if animation.ended() {
commands.entity(entity).remove::<SpawningScaleAnimation>();
transform.scale = animation.final_value();
} else {
transform.scale = animation.current_value();
}
}
}
pub fn ease_in_cubic(x: f32) -> f32 {
return x * x * x;
}
pub fn ease_in_out_cubic(x: f32) -> f32 {
if x < 0.5 {
4. * x * x * x
} else {
1. - (-2. * x + 2.).powi(3) / 2.
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/src/plugin.rs | bevy_examples/src/plugin.rs | use std::marker::PhantomData;
use bevy::{
app::{App, Plugin, PreUpdate, Startup, Update},
color::{
palettes::css::{GREEN, YELLOW_GREEN},
Alpha, Color,
},
ecs::{
component::Component,
event::Events,
query::With,
schedule::IntoScheduleConfigs,
system::{Commands, Query, Res, ResMut},
},
gizmos::config::GizmoConfigStore,
input::{
common_conditions::input_just_pressed,
keyboard::KeyCode,
mouse::{MouseButton, MouseWheel},
ButtonInput,
},
math::Vec3,
prelude::{default, Entity, MeshPickingPlugin, Pickable, Text, TextUiWriter},
render::view::Visibility,
text::{LineBreak, TextFont, TextLayout, TextSpan},
ui::{BackgroundColor, Node, PositionType, UiRect, Val},
};
use bevy_ghx_proc_gen::{
assets::BundleInserter,
bevy_egui::{self, EguiPlugin},
bevy_ghx_grid::{
debug_plugin::{
markers::MarkersGroup, toggle_debug_grids_visibilities,
toggle_grid_markers_visibilities, GridDebugPlugin,
},
ghx_grid::coordinate_system::CoordinateSystem,
},
debug_plugin::{
cursor::{CursorsOverlaysRoot, CursorsPanelRoot},
egui_editor::{paint, toggle_editor, update_painting_state, EditorContext},
generation::{GenerationControl, GenerationControlStatus, GenerationViewMode},
DebugPluginConfig, ProcGenDebugPlugins,
},
insert_bundle_from_resource_to_spawned_nodes,
proc_gen::ghx_grid::cartesian::coordinates::CartesianCoordinates,
};
use crate::anim::{animate_scale, ease_in_cubic, SpawningScaleAnimation};
pub struct ProcGenExamplesPlugin<C: CoordinateSystem, A: BundleInserter> {
generation_view_mode: GenerationViewMode,
assets_scale: Vec3,
typestate: PhantomData<(C, A)>,
}
impl<C: CoordinateSystem, A: BundleInserter> ProcGenExamplesPlugin<C, A> {
pub fn new(generation_view_mode: GenerationViewMode, assets_scale: Vec3) -> Self {
Self {
generation_view_mode,
assets_scale,
typestate: PhantomData,
}
}
}
const DEFAULT_SPAWN_ANIMATION_DURATION: f32 = 0.6;
const FAST_SPAWN_ANIMATION_DURATION: f32 = 0.1;
impl<C: CartesianCoordinates, A: BundleInserter> Plugin for ProcGenExamplesPlugin<C, A> {
fn build(&self, app: &mut App) {
app.add_plugins((
MeshPickingPlugin,
EguiPlugin {
enable_multipass_for_primary_context: false,
},
GridDebugPlugin::<C>::new(),
ProcGenDebugPlugins::<C, A> {
config: DebugPluginConfig {
generation_view_mode: self.generation_view_mode,
..default()
},
..default()
},
));
app.insert_resource(SpawningScaleAnimation::new(
DEFAULT_SPAWN_ANIMATION_DURATION,
self.assets_scale,
ease_in_cubic,
));
app.add_systems(
Startup,
(setup_examples_ui, customize_grid_markers_gizmos_config),
);
app.add_systems(
Update,
(
insert_bundle_from_resource_to_spawned_nodes::<SpawningScaleAnimation>,
animate_scale,
(
toggle_visibility::<ExamplesUiRoot>,
toggle_visibility::<CursorsPanelRoot>,
toggle_visibility::<CursorsOverlaysRoot>,
toggle_editor,
)
.run_if(input_just_pressed(KeyCode::F1)),
toggle_debug_grids_visibilities.run_if(input_just_pressed(KeyCode::F2)),
toggle_grid_markers_visibilities.run_if(input_just_pressed(KeyCode::F3)),
// toggle_auto_orbit.run_if(input_just_pressed(KeyCode::F4)),
update_generation_control_ui,
// Quick adjust of the slowish spawn animation to be more snappy when painting
adjust_spawn_animation_when_painting
.after(update_painting_state)
.before(paint::<C>),
),
);
// Quick & dirty: silence bevy events when using an egui window
app.add_systems(
PreUpdate,
absorb_egui_inputs
.after(bevy_egui::input::write_egui_input_system)
.before(bevy_egui::begin_pass_system),
);
}
}
pub fn toggle_visibility<T: Component>(mut visibilities: Query<&mut Visibility, With<T>>) {
for mut vis in &mut visibilities {
*vis = match *vis {
Visibility::Hidden => Visibility::Visible,
_ => Visibility::Hidden,
};
}
}
pub fn customize_grid_markers_gizmos_config(mut config_store: ResMut<GizmoConfigStore>) {
let markers_config = config_store.config_mut::<MarkersGroup>().0;
// Make them appear on top of everything else
markers_config.depth_bias = -1.0;
}
pub fn adjust_spawn_animation_when_painting(
editor_contex: Res<EditorContext>,
mut spawn_animation: ResMut<SpawningScaleAnimation>,
) {
if editor_contex.painting {
spawn_animation.duration_sec = FAST_SPAWN_ANIMATION_DURATION;
} else {
spawn_animation.duration_sec = DEFAULT_SPAWN_ANIMATION_DURATION;
}
}
pub const DEFAULT_EXAMPLES_FONT_SIZE: f32 = 14.;
/// Marker to find the container entity so we can show/hide the UI node
#[derive(Component)]
pub struct ExamplesUiRoot;
#[derive(Component)]
pub struct GenerationControlText;
pub fn setup_examples_ui(mut commands: Commands, view_mode: Res<GenerationViewMode>) {
let ui_root = commands
.spawn((
ExamplesUiRoot,
Node {
left: Val::Percent(1.),
height: Val::Vh(100.),
..default()
},
Pickable::IGNORE,
))
.id();
let mut keybindings_text = "Toggles:\n\
'F1' Show/hide UI\n\
'F2' Show/hide grid\n\
'F3' Show/hide markers\n\
'F4' Enable/disable camera rotation\n\
\n\
Selection:\n\
'Click' Select\n\
'x/y/z'+'Left/Right' Move selection\n\
'Esc' Deselect\n\
'Tab' Switch active grid\n"
.to_string();
if *view_mode == GenerationViewMode::StepByStepManual {
keybindings_text.push_str(
"\nGeneration:\n\
'Down' Generate 1 step\n\
'Up' Generate while pressed",
);
}
let keybindings_ui_background = commands
.spawn((
Node {
position_type: PositionType::Absolute,
top: Val::Percent(1.),
padding: UiRect {
left: Val::Px(6.),
right: Val::Px(6.),
top: Val::Px(6.),
bottom: Val::Px(6.),
},
..default()
},
BackgroundColor(Color::BLACK.with_alpha(0.6).into()),
Pickable::IGNORE,
))
.id();
let keybindings_ui = commands
.spawn((
Node {
position_type: PositionType::Relative,
..default()
},
TextLayout {
linebreak: LineBreak::NoWrap,
..default()
},
TextFont {
font_size: DEFAULT_EXAMPLES_FONT_SIZE,
..default()
},
Text(keybindings_text),
Pickable::IGNORE,
))
.id();
let status_ui = commands
.spawn((
GenerationControlText,
Node {
position_type: PositionType::Absolute,
bottom: Val::Percent(1.),
..default()
},
TextLayout {
linebreak: LineBreak::NoWrap,
..default()
},
TextFont {
font_size: DEFAULT_EXAMPLES_FONT_SIZE,
..default()
},
Pickable::IGNORE,
Text("".into()),
))
.with_child((
TextSpan::new("\nGeneration control status: "),
TextFont::from_font_size(DEFAULT_EXAMPLES_FONT_SIZE),
))
.with_child((
TextSpan::new(""),
TextFont::from_font_size(DEFAULT_EXAMPLES_FONT_SIZE),
))
.with_child((
TextSpan::new(""),
TextFont::from_font_size(DEFAULT_EXAMPLES_FONT_SIZE),
))
.with_child((
TextSpan::new(format!("\nGenerationViewMode: {:?}", *view_mode)),
TextFont::from_font_size(DEFAULT_EXAMPLES_FONT_SIZE),
))
.id();
commands
.entity(ui_root)
.add_child(keybindings_ui_background);
commands
.entity(keybindings_ui_background)
.add_child(keybindings_ui);
commands.entity(ui_root).add_child(status_ui);
}
pub const GENERATION_CONTROL_STATUS_TEXT_SECTION_ID: usize = 1;
pub const GENERATION_CONTROL_TEXT_SECTION_ID: usize = 2;
pub const GENERATION_VIEW_MODE_TEXT_SECTION_ID: usize = 3;
pub fn update_generation_control_ui(
mut writer: TextUiWriter,
gen_control: Res<GenerationControl>,
mut query: Query<Entity, With<GenerationControlText>>,
) {
for text_entity in &mut query {
let (text, color) = match gen_control.status {
GenerationControlStatus::Ongoing => ("Ongoing ('Space' to pause)".into(), GREEN.into()),
GenerationControlStatus::Paused => {
("Paused ('Space' to unpause)".into(), YELLOW_GREEN.into())
}
};
*writer.text(text_entity, GENERATION_CONTROL_STATUS_TEXT_SECTION_ID) = text;
*writer.color(text_entity, GENERATION_CONTROL_STATUS_TEXT_SECTION_ID) = color;
* writer.text(text_entity, GENERATION_CONTROL_TEXT_SECTION_ID)= format!(
"\nGenerationControl: skip_void_nodes: {}, pause_when_done: {}, pause_on_error: {}, pause_on_reinitialize: {}",
gen_control.skip_void_nodes,
gen_control.pause_when_done,
gen_control.pause_on_error,
gen_control.pause_on_reinitialize
);
}
}
// Quick & dirty: silence bevy events when using an egui window
fn absorb_egui_inputs(
mut contexts: bevy_egui::EguiContexts,
mut mouse: ResMut<ButtonInput<MouseButton>>,
mut mouse_wheel: ResMut<Events<MouseWheel>>,
) {
let ctx = contexts.ctx_mut();
if ctx.wants_pointer_input() || ctx.is_pointer_over_area() {
mouse.reset_all();
mouse_wheel.clear();
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/chessboard/chessboard.rs | bevy_examples/chessboard/chessboard.rs | use bevy::prelude::*;
use bevy_ghx_proc_gen::{
assets::ModelsAssets,
bevy_ghx_grid::ghx_grid::cartesian::coordinates::CartesianPosition,
default_bundles::PbrMesh,
proc_gen::{
generator::{
builder::GeneratorBuilder,
model::ModelCollection,
rules::RulesBuilder,
socket::{SocketCollection, SocketsCartesian2D},
},
ghx_grid::cartesian::{coordinates::Cartesian2D, grid::CartesianGrid},
},
simple_plugin::ProcGenSimplePlugins,
spawner_plugin::NodesSpawner,
};
const CUBE_SIZE: f32 = 1.;
const NODE_SIZE: Vec3 = Vec3::splat(CUBE_SIZE);
fn setup_scene(mut commands: Commands) {
// Camera
commands.spawn((
Transform::from_translation(Vec3::new(0., -11., 6.)).looking_at(Vec3::ZERO, Vec3::Y),
Camera3d { ..default() },
));
// Scene lights
commands.spawn(DirectionalLight {
illuminance: 5500.,
..default()
});
}
fn setup_generator(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// A SocketCollection is what we use to create sockets and define their connections
let mut sockets = SocketCollection::new();
// For this example, we will only need two sockets
let (white, black) = (sockets.create(), sockets.create());
// With the following, a white socket can connect to a black socket and vice-versa
sockets.add_connection(white, vec![black]);
let mut models = ModelCollection::<Cartesian2D>::new();
// We define 2 very simple models, a white tile model with the `white` socket on each side and a black tile model with the `black` socket on each side
models.create(SocketsCartesian2D::Mono(white));
// We keep track of the black model for later
let black_model = models.create(SocketsCartesian2D::Mono(black)).clone();
// We give the models and socket collection to a RulesBuilder and get our Rules
let rules = RulesBuilder::new_cartesian_2d(models, sockets)
.build()
.unwrap();
// Like a chess board, let's do an 8x8 2d grid
let grid = CartesianGrid::new_cartesian_2d(8, 8, false, false);
// There many more parameters you can tweak on a Generator before building it, explore the API.
let generator = GeneratorBuilder::new()
.with_rules(rules)
.with_grid(grid.clone())
// Let's ensure that we make a chessboard, with a black square bottom-left
.with_initial_nodes(vec![(CartesianPosition::new_xy(0, 0), black_model)])
.unwrap()
.build()
.unwrap();
// Create our assets. We define them in a separate collection for the sake of simplicity
let cube_mesh = meshes.add(Mesh::from(Cuboid {
half_size: Vec3::splat(CUBE_SIZE / 2.),
}));
let white_mat = materials.add(Color::WHITE);
let black_mat = materials.add(Color::BLACK);
let mut models_assets = ModelsAssets::<PbrMesh>::new();
models_assets.add_asset(
0,
PbrMesh {
mesh: cube_mesh.clone(),
material: white_mat,
},
);
models_assets.add_asset(
1,
PbrMesh {
mesh: cube_mesh.clone(),
material: black_mat,
},
);
// Add the generator & grid components the plugin will generate and spawn the nodes
commands.spawn((
Transform::from_translation(Vec3::new(-4., -4., 0.)),
grid,
generator,
NodesSpawner::new(models_assets, NODE_SIZE, Vec3::ONE),
));
}
fn main() {
let mut app = App::new();
app.add_plugins((
DefaultPlugins,
ProcGenSimplePlugins::<Cartesian2D, PbrMesh>::default(),
));
app.add_systems(Startup, (setup_generator, setup_scene));
app.run();
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/canyon/canyon.rs | bevy_examples/canyon/canyon.rs | use std::f32::consts::PI;
use bevy::{
color::palettes::css::{GRAY, ORANGE_RED},
log::LogPlugin,
pbr::DirectionalLightShadowMap,
prelude::*,
};
use bevy_editor_cam::{prelude::EditorCam, DefaultEditorCamPlugins};
use bevy_examples::{
anim::SpawningScaleAnimation, plugin::ProcGenExamplesPlugin, utils::load_assets,
};
use bevy_ghx_proc_gen::{
bevy_ghx_grid::debug_plugin::{view::DebugGridView, DebugGridView3dBundle},
debug_plugin::generation::{GenerationControl, GenerationViewMode},
proc_gen::{
generator::{
builder::GeneratorBuilder, node_heuristic::NodeSelectionHeuristic, rules::RulesBuilder,
ModelSelectionHeuristic, RngMode,
},
ghx_grid::cartesian::{coordinates::Cartesian3D, grid::CartesianGrid},
},
spawner_plugin::NodesSpawner,
};
use rand::Rng;
use rules::{RotationRandomizer, ScaleRandomizer, WindRotation};
use crate::rules::rules_and_assets;
mod rules;
// ----------------- Configurable values ---------------------------
/// Modify this value to control the way the generation is visualized
const GENERATION_VIEW_MODE: GenerationViewMode = GenerationViewMode::Final;
/// Modify to visualize void nodes with a transparent asset
const SEE_VOID_NODES: bool = false;
/// Modify these values to control the map size.
const GRID_HEIGHT: u32 = 6;
const GRID_X: u32 = 30;
const GRID_Z: u32 = 30;
// ------------------------------------------------------------------
const ASSETS_PATH: &str = "canyon";
/// Size of a block in world units
const BLOCK_SIZE: f32 = 1.;
/// Size of a grid node in world units
const NODE_SIZE: Vec3 = Vec3::splat(BLOCK_SIZE);
const ASSETS_SCALE_FACTOR: f32 = BLOCK_SIZE / 2.;
const ASSETS_SCALE: Vec3 = Vec3::splat(ASSETS_SCALE_FACTOR);
fn setup_scene(mut commands: Commands) {
// Camera
let camera_position = Vec3::new(0., 2.5 * GRID_HEIGHT as f32, 1.8 * GRID_Z as f32 / 2.);
let look_target = Vec3::new(0., 0., 0.);
commands.spawn((
Name::new("Camera"),
Transform::from_translation(camera_position).looking_at(look_target, Vec3::Y),
Camera3d::default(),
EditorCam::default(),
));
// Scene lights
commands.insert_resource(AmbientLight {
color: Color::Srgba(ORANGE_RED),
brightness: 0.05,
..default()
});
commands.spawn((
Name::new("Main light"),
Transform {
translation: Vec3::new(5.0, 10.0, 2.0),
rotation: Quat::from_euler(EulerRot::ZYX, 0., -PI / 5., -PI / 3.),
..default()
},
DirectionalLight {
shadows_enabled: true,
illuminance: 4000.,
color: Color::srgb(1.0, 0.85, 0.65),
..default()
},
));
commands.spawn((
Name::new("Back light"),
Transform {
translation: Vec3::new(5.0, 10.0, 2.0),
rotation: Quat::from_euler(EulerRot::ZYX, 0., PI * 4. / 5., -PI / 3.),
..default()
},
DirectionalLight {
shadows_enabled: false,
illuminance: 2000.,
color: Color::Srgba(ORANGE_RED),
..default()
},
));
}
fn setup_generator(mut commands: Commands, asset_server: Res<AssetServer>) {
let (
void_instance,
sand_instance,
water_instance,
bridge_instance,
assets_definitions,
models,
socket_collection,
) = rules_and_assets();
// Create generator
let rules = RulesBuilder::new_cartesian_3d(models, socket_collection)
.build()
.unwrap();
let grid = CartesianGrid::new_cartesian_3d(GRID_X, GRID_HEIGHT, GRID_Z, false, false, false);
let mut initial_constraints = grid.new_grid_data(None);
// Force void nodes on the upmost layer
let void_ref = Some(void_instance);
initial_constraints.set_all_y(GRID_HEIGHT - 1, void_ref);
// Force void nodes on the grid's "borders"
initial_constraints.set_all_x(0, void_ref);
initial_constraints.set_all_x(GRID_X - 1, void_ref);
initial_constraints.set_all_z(0, void_ref);
initial_constraints.set_all_z(GRID_Z - 1, void_ref);
// Force sand nodes on the grid's "borders" ground
let sand_ref = Some(sand_instance);
initial_constraints.set_all_xy(0, 0, sand_ref);
initial_constraints.set_all_xy(GRID_X - 1, 0, sand_ref);
initial_constraints.set_all_yz(0, 0, sand_ref);
initial_constraints.set_all_yz(0, GRID_Z - 1, sand_ref);
// Let's force a small lake at the center
let water_ref = Some(water_instance);
for x in 2 * GRID_X / 5..3 * GRID_X / 5 {
for z in 2 * GRID_Z / 5..3 * GRID_Z / 5 {
*initial_constraints.get_3d_mut(x, 0, z) = water_ref;
}
}
// We could hope for a water bridge, or force one !
*initial_constraints.get_3d_mut(GRID_X / 2, GRID_HEIGHT / 2, GRID_Z / 2) =
Some(bridge_instance);
let mut gen_builder = GeneratorBuilder::new()
.with_rules(rules)
.with_grid(grid.clone())
.with_max_retry_count(50)
.with_rng(RngMode::RandomSeed)
.with_node_heuristic(NodeSelectionHeuristic::MinimumEntropy)
.with_model_heuristic(ModelSelectionHeuristic::WeightedProbability)
// There are other methods to initialize the generation. See with_initial_nodes
.with_initial_grid(initial_constraints)
.unwrap();
let observer = gen_builder.add_queued_observer();
let generator = gen_builder.build().unwrap();
// Load assets
let models_assets =
load_assets::<Scene>(&asset_server, assets_definitions, ASSETS_PATH, "glb#Scene0");
commands.spawn((
Transform::from_translation(Vec3 {
x: -(grid.size_x() as f32) / 2.,
y: 0.,
z: -(grid.size_z() as f32) / 2.,
}),
grid,
generator,
NodesSpawner::new(
models_assets,
NODE_SIZE,
// We spawn assets with a scale of 0 since we animate their scale in the examples
Vec3::ZERO,
),
observer,
DebugGridView3dBundle {
view: DebugGridView::new(false, true, Color::Srgba(GRAY), NODE_SIZE),
..default()
},
));
commands.insert_resource(GenerationControl {
pause_on_error: false,
..Default::default()
});
}
fn main() {
let mut app = App::new();
app.insert_resource(DirectionalLightShadowMap { size: 4096 });
app.add_plugins((
DefaultPlugins.set(LogPlugin {
filter: "info,wgpu_core=error,wgpu_hal=error,ghx_proc_gen=debug".into(),
level: bevy::log::Level::DEBUG,
..default()
}),
DefaultEditorCamPlugins,
ProcGenExamplesPlugin::<Cartesian3D, Handle<Scene>>::new(
GENERATION_VIEW_MODE,
ASSETS_SCALE,
),
));
app.add_systems(Startup, (setup_generator, setup_scene))
.add_systems(
Update,
(apply_wind, randomize_spawn_scale, randomize_spawn_rotation),
);
app.run();
}
pub fn apply_wind(
time: Res<Time>,
mut altered_transforms: Query<&mut Transform, With<WindRotation>>,
) {
for mut transform in altered_transforms.iter_mut() {
transform.rotation = Quat::from_rotation_z(2. * time.elapsed_secs_wrapped());
}
}
pub fn randomize_spawn_scale(
mut commands: Commands,
mut altered_transforms: Query<(Entity, &mut SpawningScaleAnimation), With<ScaleRandomizer>>,
) {
let mut rng = rand::thread_rng();
for (entity, mut spawning_scale_animation) in altered_transforms.iter_mut() {
spawning_scale_animation.final_scale =
spawning_scale_animation.final_scale * rng.gen_range(0.7..1.3);
commands.entity(entity).remove::<ScaleRandomizer>();
}
}
pub fn randomize_spawn_rotation(
mut commands: Commands,
mut altered_transforms: Query<(Entity, &mut Transform), With<RotationRandomizer>>,
) {
let mut rng = rand::thread_rng();
for (entity, mut transform) in altered_transforms.iter_mut() {
transform.rotate_y(rng.gen_range(-45.0..45.0));
commands.entity(entity).remove::<RotationRandomizer>();
}
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/canyon/rules.rs | bevy_examples/canyon/rules.rs | use bevy::{ecs::component::Component, math::Vec3};
use bevy_examples::utils::ModelAssetDef;
use bevy_ghx_proc_gen::proc_gen::{
generator::{
model::{ModelCollection, ModelInstance, ModelRotation},
socket::{Socket, SocketCollection, SocketsCartesian3D},
},
ghx_grid::cartesian::coordinates::{Cartesian3D, GridDelta},
};
use crate::{BLOCK_SIZE, SEE_VOID_NODES};
pub(crate) fn rules_and_assets() -> (
ModelInstance,
ModelInstance,
ModelInstance,
ModelInstance,
Vec<Vec<ModelAssetDef>>,
ModelCollection<Cartesian3D>,
SocketCollection,
) {
let mut sockets = SocketCollection::new();
// Create our sockets
let mut s = || -> Socket { sockets.create() };
let (void, void_top, void_bottom) = (s(), s(), s());
let (water, water_border, water_top, water_bottom) = (s(), s(), s(), s());
let (sand, sand_border, sand_top, sand_bottom) = (s(), s(), s(), s());
let (ground_rock_border, ground_rock_border_top, ground_rock_border_bottom) = (s(), s(), s());
let (ground_rock_to_other, other_to_ground_rock) = (s(), s());
let (rock, rock_top, rock_bottom) = (s(), s(), s());
let (rock_border, rock_border_top, rock_border_bottom) = (s(), s(), s());
let (rock_to_other, other_to_rock) = (s(), s());
let (bridge, bridge_side, bridge_top, bridge_bottom) = (s(), s(), s(), s());
let (bridge_start_in, bridge_start_out, bridge_start_bottom) = (s(), s(), s());
let (sand_prop_border, sand_prop_top, sand_prop_bottom) = (s(), s(), s());
let (
windmill_side,
windmill_base_top,
windmill_base_bottom,
windmill_cap_top,
windmill_cap_bottom,
) = (s(), s(), s(), s(), s());
// Create our models. We declare our assets at the same time for clarity (index of the model matches the index of the assets to spawn).
let mut models = ModelCollection::<Cartesian3D>::new();
let mut assets = Vec::new();
// Utility functions to declare assets & models
let asset = |str| -> Vec<ModelAssetDef> { vec![ModelAssetDef::new(str)] };
let void_instance = models
.create(SocketsCartesian3D::Simple {
x_pos: void,
x_neg: void,
z_pos: void,
z_neg: void,
y_pos: void_top,
y_neg: void_bottom,
})
.with_weight(10.)
.instance();
assets.push(match SEE_VOID_NODES {
true => asset("void"),
false => vec![],
});
let water_instance = models
.create(SocketsCartesian3D::Multiple {
x_pos: vec![water],
x_neg: vec![water, water_border],
z_pos: vec![water],
z_neg: vec![water, water_border],
y_pos: vec![water_top],
y_neg: vec![water_bottom],
})
.with_all_rotations()
.with_weight(350.0)
.instance();
assets.push(asset("water_poly"));
let sand_instance = models
.create(SocketsCartesian3D::Multiple {
x_pos: vec![sand],
x_neg: vec![sand, sand_border],
z_pos: vec![sand],
z_neg: vec![sand, sand_border],
y_pos: vec![sand_top],
y_neg: vec![sand_bottom],
})
.with_weight(5.0)
.instance();
assets.push(asset("sand"));
const GROUND_ROCKS_WEIGHT: f32 = 0.5;
const ROCKS_WEIGHT: f32 = 0.05;
// Here we define a model template that we'll reuse multiple times
let rock_corner = SocketsCartesian3D::Simple {
x_pos: rock_border,
x_neg: other_to_rock,
z_pos: rock_border,
z_neg: rock_to_other,
y_pos: rock_border_top,
y_neg: rock_border_bottom,
}
.to_template()
.with_all_rotations()
.with_weight(ROCKS_WEIGHT);
models
.create(SocketsCartesian3D::Simple {
x_pos: ground_rock_border,
x_neg: other_to_ground_rock,
z_pos: ground_rock_border,
z_neg: ground_rock_to_other,
y_pos: ground_rock_border_top,
y_neg: ground_rock_border_bottom,
})
.with_all_rotations()
.with_weight(GROUND_ROCKS_WEIGHT);
assets.push(asset("ground_rock_corner_in"));
models
.create(SocketsCartesian3D::Simple {
x_pos: ground_rock_border,
x_neg: rock,
z_pos: other_to_ground_rock,
z_neg: ground_rock_to_other,
y_pos: ground_rock_border_top,
y_neg: ground_rock_border_bottom,
})
.with_all_rotations()
.with_weight(GROUND_ROCKS_WEIGHT);
assets.push(asset("ground_rock_side"));
// Here we reuse the same model to create variations. (We could also have 1 model, and 2 assets, with the spawner picking one of the assets at random)
models.create(rock_corner.clone());
assets.push(asset("rock_corner_in_1"));
models.create(rock_corner.clone());
assets.push(asset("rock_corner_in_2"));
models
.create(SocketsCartesian3D::Simple {
x_pos: rock_border,
x_neg: rock,
z_pos: other_to_rock,
z_neg: rock_to_other,
y_pos: rock_border_top,
y_neg: rock_border_bottom,
})
.with_all_rotations()
.with_weight(ROCKS_WEIGHT);
assets.push(asset("rock_side_1"));
models
.create(SocketsCartesian3D::Simple {
x_pos: rock,
x_neg: rock,
z_pos: rock,
z_neg: rock,
y_pos: rock_top,
y_neg: rock_bottom,
})
.with_weight(ROCKS_WEIGHT);
assets.push(asset("rock"));
models
.create(SocketsCartesian3D::Simple {
x_pos: bridge_side,
x_neg: bridge_side,
z_pos: bridge_start_out,
z_neg: bridge_start_in,
y_pos: bridge_top,
y_neg: bridge_start_bottom,
})
.with_all_rotations()
.with_weight(0.05);
assets.push(asset("bridge_start"));
let bridge_instance = models
.create(SocketsCartesian3D::Simple {
x_pos: bridge_side,
x_neg: bridge_side,
z_pos: bridge,
z_neg: bridge,
y_pos: bridge_top,
y_neg: bridge_bottom,
})
.with_all_rotations()
.with_weight(0.05)
.instance();
assets.push(asset("bridge"));
// Small rocks and cactuses
let sand_prop = SocketsCartesian3D::Simple {
x_pos: sand_prop_border,
x_neg: sand_prop_border,
z_pos: sand_prop_border,
z_neg: sand_prop_border,
y_pos: sand_prop_top,
y_neg: sand_prop_bottom,
}
.to_template()
.with_all_rotations()
.with_weight(0.25);
models.create(sand_prop.clone());
assets.push(vec![ModelAssetDef::new("cactus")
.with_grid_offset(GridDelta::new(0, -1, 0))
.with_components(|cmds| {
cmds.insert((ScaleRandomizer, RotationRandomizer));
})]);
models.create(sand_prop.clone().with_weight(0.4));
assets.push(vec![ModelAssetDef::new("small_rock")
.with_grid_offset(GridDelta::new(0, -1, 0))
.with_components(|cmds| {
cmds.insert((ScaleRandomizer, RotationRandomizer));
})]);
const WINDMILLS_WEIGHT: f32 = 0.005;
models
.create(SocketsCartesian3D::Simple {
x_pos: windmill_side,
x_neg: windmill_side,
z_pos: windmill_side,
z_neg: windmill_side,
y_pos: windmill_base_top,
y_neg: windmill_base_bottom,
})
.with_all_rotations()
.with_weight(WINDMILLS_WEIGHT);
assets.push(asset("windmill_base"));
models
.create(SocketsCartesian3D::Simple {
x_pos: windmill_side,
x_neg: windmill_side,
z_pos: windmill_side,
z_neg: windmill_side,
y_pos: windmill_cap_top,
y_neg: windmill_cap_bottom,
})
.with_weight(WINDMILLS_WEIGHT);
assets.push(vec![
ModelAssetDef::new("windmill_top"),
ModelAssetDef::new("windmill_vane"),
ModelAssetDef::new("windmill_blades")
.with_offset(Vec3::new(0., 0.7 * BLOCK_SIZE, 0.))
.with_components(|cmds| {
cmds.insert(WindRotation);
}),
]);
// For this generation, our rotation axis is Y+, so we define connection on the Y axis with `add_rotated_connection` for sockets that still need to be compatible when rotated.
sockets
// Void
.add_connection(void, vec![void])
.add_rotated_connection(void_bottom, vec![void_top])
// Water & sand
.add_connection(water, vec![water])
.add_rotated_connection(water_top, vec![void_bottom])
.add_connection(sand, vec![sand])
.add_connection(sand_border, vec![water_border])
.add_rotated_connection(sand_top, vec![void_bottom])
// Rocks
.add_connections(vec![
(ground_rock_border, vec![water, sand]),
(ground_rock_to_other, vec![other_to_ground_rock]),
])
.add_rotated_connection(
ground_rock_border_top,
vec![void_bottom, rock_border_bottom],
)
.add_connections(vec![
(rock, vec![rock]),
(rock_border, vec![void]),
(rock_to_other, vec![other_to_rock]),
])
.add_rotated_connection(rock_border_top, vec![void_bottom, rock_border_bottom])
.add_rotated_connection(rock_top, vec![rock_bottom, rock_border_bottom, void_bottom])
// Bridges
.add_connections(vec![
(bridge, vec![bridge]),
(bridge_side, vec![void, rock_border]),
(bridge_start_out, vec![void, rock_border]),
(bridge_start_in, vec![bridge]),
])
.add_rotated_connection(bridge_top, vec![void_bottom, bridge_bottom])
.add_rotated_connection(bridge_bottom, vec![void_top, sand_top, water_top])
// A bridge start model should face outwards from a rock.
.add_constrained_rotated_connection(
bridge_start_bottom,
vec![ModelRotation::Rot180, ModelRotation::Rot270],
vec![rock_border_top, ground_rock_border_top],
)
// Small rocks & Cactuses
.add_connection(sand_prop_border, vec![void, rock_border, bridge_side])
.add_rotated_connections(vec![
(sand_prop_bottom, vec![sand_top]),
(sand_prop_top, vec![void_bottom, bridge_bottom]),
])
// Windmills
.add_connection(windmill_side, vec![void, rock_border, bridge_side])
.add_rotated_connections(vec![
(windmill_base_bottom, vec![rock_top]),
(windmill_base_top, vec![windmill_cap_bottom]),
(windmill_cap_top, vec![void_bottom]),
]);
// We add a debug name to the models from their first asset name
for model in models.models_mut() {
model.with_name(
assets[model.index()]
.first()
.unwrap_or(&ModelAssetDef::new("void"))
.path(),
);
}
(
void_instance,
sand_instance,
water_instance,
bridge_instance,
assets,
models,
sockets,
)
}
#[derive(Component, Clone)]
pub struct WindRotation;
#[derive(Component, Clone)]
pub struct ScaleRandomizer;
#[derive(Component, Clone)]
pub struct RotationRandomizer;
// #[derive(Clone)]
// pub enum CustomComponents {
// Rot(WindRotation),
// ScaleRdm(ScaleRandomizer),
// RotRdm(RotationRandomizer),
// }
// impl ComponentSpawner for CustomComponents {
// fn insert(&self, command: &mut bevy::ecs::system::EntityCommands) {
// match self {
// CustomComponents::Rot(rot) => command.insert(rot.clone()),
// CustomComponents::ScaleRdm(sc) => command.insert(sc.clone()),
// CustomComponents::RotRdm(rot) => command.insert(rot.clone()),
// };
// }
// }
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/tile-layers/rules.rs | bevy_examples/tile-layers/rules.rs | use bevy_examples::utils::ModelAssetDef;
use bevy_ghx_proc_gen::{
bevy_ghx_grid::ghx_grid::direction::Direction,
proc_gen::{
generator::{
model::{ModelCollection, ModelRotation},
socket::{Socket, SocketCollection, SocketsCartesian3D},
},
ghx_grid::cartesian::coordinates::{Cartesian3D, GridDelta},
},
};
const UP_AXIS: Direction = Direction::ZForward;
pub(crate) fn rules_and_assets() -> (
Vec<Vec<ModelAssetDef>>,
ModelCollection<Cartesian3D>,
SocketCollection,
) {
let mut sockets = SocketCollection::new();
// Create our sockets
let mut s = || -> Socket { sockets.create() };
let (void, dirt) = (s(), s());
let (layer_0_down, layer_0_up) = (s(), s());
let (grass, void_and_grass, grass_and_void) = (s(), s(), s());
let (layer_1_down, layer_1_up, grass_up) = (s(), s(), s());
let yellow_grass_down = s();
let (layer_2_down, layer_2_up) = (s(), s());
let (water, void_and_water, water_and_void) = (s(), s(), s());
let (layer_3_down, layer_3_up, ground_up) = (s(), s(), s());
let (layer_4_down, layer_4_up, props_down) = (s(), s(), s());
let (big_tree_1_base, big_tree_2_base) = (s(), s());
// Create our models. We declare our assets at the same time for clarity (index of the model matches the index of the assets to spawn).
let mut models = ModelCollection::<Cartesian3D>::new();
let mut assets = Vec::new();
// Utility functions to declare assets & models
let asset = |str| -> Vec<ModelAssetDef> { vec![ModelAssetDef::new(str)] };
// ---------------------------- Layer 0 ----------------------------
models
.create(SocketsCartesian3D::Simple {
x_pos: dirt,
x_neg: dirt,
z_pos: layer_0_up,
z_neg: layer_0_down,
y_pos: dirt,
y_neg: dirt,
})
.with_weight(20.);
assets.push(asset("dirt"));
// ---------------------------- Layer 1 ----------------------------
models.create(SocketsCartesian3D::Simple {
x_pos: void,
x_neg: void,
z_pos: layer_1_up,
z_neg: layer_1_down,
y_pos: void,
y_neg: void,
});
assets.push(vec![]);
models
.create(SocketsCartesian3D::Multiple {
x_pos: vec![grass],
x_neg: vec![grass],
z_pos: vec![layer_1_up, grass_up],
z_neg: vec![layer_1_down],
y_pos: vec![grass],
y_neg: vec![grass],
})
.with_weight(5.);
assets.push(asset("green_grass"));
// Here we define models that we'll reuse multiple times
let green_grass_corner_out = SocketsCartesian3D::Simple {
x_pos: void_and_grass,
x_neg: void,
z_pos: layer_1_up,
z_neg: layer_1_down,
y_pos: void,
y_neg: grass_and_void,
}
.to_template();
let green_grass_corner_in = SocketsCartesian3D::Simple {
x_pos: grass_and_void,
x_neg: grass,
z_pos: layer_1_up,
z_neg: layer_1_down,
y_pos: grass,
y_neg: void_and_grass,
}
.to_template();
let green_grass_side = SocketsCartesian3D::Simple {
x_pos: void_and_grass,
x_neg: grass_and_void,
z_pos: layer_1_up,
z_neg: layer_1_down,
y_pos: void,
y_neg: grass,
}
.to_template();
models.create(green_grass_corner_out.clone());
assets.push(asset("green_grass_corner_out_tl"));
models.create(green_grass_corner_out.rotated(ModelRotation::Rot90, UP_AXIS));
assets.push(asset("green_grass_corner_out_bl"));
models.create(green_grass_corner_out.rotated(ModelRotation::Rot180, UP_AXIS));
assets.push(asset("green_grass_corner_out_br"));
models.create(green_grass_corner_out.rotated(ModelRotation::Rot270, UP_AXIS));
assets.push(asset("green_grass_corner_out_tr"));
models.create(green_grass_corner_in.clone());
assets.push(asset("green_grass_corner_in_tl"));
models.create(green_grass_corner_in.rotated(ModelRotation::Rot90, UP_AXIS));
assets.push(asset("green_grass_corner_in_bl"));
models.create(green_grass_corner_in.rotated(ModelRotation::Rot180, UP_AXIS));
assets.push(asset("green_grass_corner_in_br"));
models.create(green_grass_corner_in.rotated(ModelRotation::Rot270, UP_AXIS));
assets.push(asset("green_grass_corner_in_tr"));
models.create(green_grass_side.clone());
assets.push(asset("green_grass_side_t"));
models.create(green_grass_side.rotated(ModelRotation::Rot90, UP_AXIS));
assets.push(asset("green_grass_side_l"));
models.create(green_grass_side.rotated(ModelRotation::Rot180, UP_AXIS));
assets.push(asset("green_grass_side_b"));
models.create(green_grass_side.rotated(ModelRotation::Rot270, UP_AXIS));
assets.push(asset("green_grass_side_r"));
// ---------------------------- Layer 2 ----------------------------
models.create(SocketsCartesian3D::Simple {
x_pos: void,
x_neg: void,
z_pos: layer_2_up,
z_neg: layer_2_down,
y_pos: void,
y_neg: void,
});
assets.push(vec![]); // Layer 2 Void
models.create(SocketsCartesian3D::Simple {
x_pos: grass,
x_neg: grass,
z_pos: layer_2_up,
z_neg: layer_2_down,
y_pos: grass,
y_neg: grass,
});
assets.push(asset("yellow_grass"));
let yellow_grass_corner_out = SocketsCartesian3D::Simple {
x_pos: void_and_grass,
x_neg: void,
z_pos: layer_2_up,
z_neg: yellow_grass_down,
y_pos: void,
y_neg: grass_and_void,
}
.to_template();
let yellow_grass_corner_in = SocketsCartesian3D::Simple {
x_pos: grass_and_void,
x_neg: grass,
z_pos: layer_2_up,
z_neg: yellow_grass_down,
y_pos: grass,
y_neg: void_and_grass,
}
.to_template();
let yellow_grass_side = SocketsCartesian3D::Simple {
x_pos: void_and_grass,
x_neg: grass_and_void,
z_pos: layer_2_up,
z_neg: yellow_grass_down,
y_pos: void,
y_neg: grass,
}
.to_template();
models.create(yellow_grass_corner_out.clone());
assets.push(asset("yellow_grass_corner_out_tl"));
models.create(yellow_grass_corner_out.rotated(ModelRotation::Rot90, UP_AXIS));
assets.push(asset("yellow_grass_corner_out_bl"));
models.create(yellow_grass_corner_out.rotated(ModelRotation::Rot180, UP_AXIS));
assets.push(asset("yellow_grass_corner_out_br"));
models.create(yellow_grass_corner_out.rotated(ModelRotation::Rot270, UP_AXIS));
assets.push(asset("yellow_grass_corner_out_tr"));
models.create(yellow_grass_corner_in.clone());
assets.push(asset("yellow_grass_corner_in_tl"));
models.create(yellow_grass_corner_in.rotated(ModelRotation::Rot90, UP_AXIS));
assets.push(asset("yellow_grass_corner_in_bl"));
models.create(yellow_grass_corner_in.rotated(ModelRotation::Rot180, UP_AXIS));
assets.push(asset("yellow_grass_corner_in_br"));
models.create(yellow_grass_corner_in.rotated(ModelRotation::Rot270, UP_AXIS));
assets.push(asset("yellow_grass_corner_in_tr"));
models.create(yellow_grass_side.clone());
assets.push(asset("yellow_grass_side_t"));
models.create(yellow_grass_side.rotated(ModelRotation::Rot90, UP_AXIS));
assets.push(asset("yellow_grass_side_l"));
models.create(yellow_grass_side.rotated(ModelRotation::Rot180, UP_AXIS));
assets.push(asset("yellow_grass_side_b"));
models.create(yellow_grass_side.rotated(ModelRotation::Rot270, UP_AXIS));
assets.push(asset("yellow_grass_side_r"));
// ---------------------------- Layer 3 ----------------------------
models.create(SocketsCartesian3D::Multiple {
x_pos: vec![void],
x_neg: vec![void],
z_pos: vec![layer_3_up, ground_up],
z_neg: vec![layer_3_down],
y_pos: vec![void],
y_neg: vec![void],
});
assets.push(vec![]); // Layer 3 Void
models
.create(SocketsCartesian3D::Simple {
x_pos: water,
x_neg: water,
z_pos: layer_3_up,
z_neg: layer_3_down,
y_pos: water,
y_neg: water,
})
.with_weight(10. * WATER_WEIGHT);
assets.push(asset("water"));
const WATER_WEIGHT: f32 = 0.02;
let water_corner_out = SocketsCartesian3D::Simple {
x_pos: void_and_water,
x_neg: void,
z_pos: layer_3_up,
z_neg: layer_3_down,
y_pos: void,
y_neg: water_and_void,
}
.to_template()
.with_weight(WATER_WEIGHT);
let water_corner_in = SocketsCartesian3D::Simple {
x_pos: water_and_void,
x_neg: water,
z_pos: layer_3_up,
z_neg: layer_3_down,
y_pos: water,
y_neg: void_and_water,
}
.to_template()
.with_weight(WATER_WEIGHT);
let water_side = SocketsCartesian3D::Simple {
x_pos: void_and_water,
x_neg: water_and_void,
z_pos: layer_3_up,
z_neg: layer_3_down,
y_pos: void,
y_neg: water,
}
.to_template()
.with_weight(WATER_WEIGHT);
models.create(water_corner_out.clone());
assets.push(asset("water_corner_out_tl"));
models.create(water_corner_out.rotated(ModelRotation::Rot90, UP_AXIS));
assets.push(asset("water_corner_out_bl"));
models.create(water_corner_out.rotated(ModelRotation::Rot180, UP_AXIS));
assets.push(asset("water_corner_out_br"));
models.create(water_corner_out.rotated(ModelRotation::Rot270, UP_AXIS));
assets.push(asset("water_corner_out_tr"));
models.create(water_corner_in.clone());
assets.push(asset("water_corner_in_tl"));
models.create(water_corner_in.rotated(ModelRotation::Rot90, UP_AXIS));
assets.push(asset("water_corner_in_bl"));
models.create(water_corner_in.rotated(ModelRotation::Rot180, UP_AXIS));
assets.push(asset("water_corner_in_br"));
models.create(water_corner_in.rotated(ModelRotation::Rot270, UP_AXIS));
assets.push(asset("water_corner_in_tr"));
models.create(water_side.clone());
assets.push(asset("water_side_t"));
models.create(water_side.rotated(ModelRotation::Rot90, UP_AXIS));
assets.push(asset("water_side_l"));
models.create(water_side.rotated(ModelRotation::Rot180, UP_AXIS));
assets.push(asset("water_side_b"));
models.create(water_side.rotated(ModelRotation::Rot270, UP_AXIS));
assets.push(asset("water_side_r"));
// ---------------------------- Layer 4 ----------------------------
models.create(SocketsCartesian3D::Multiple {
x_pos: vec![void],
x_neg: vec![void],
z_pos: vec![layer_4_up],
z_neg: vec![layer_4_down],
y_pos: vec![void],
y_neg: vec![void],
});
assets.push(vec![]); // Layer 4 Void
const PROPS_WEIGHT: f32 = 0.025;
const ROCKS_WEIGHT: f32 = 0.008;
const PLANTS_WEIGHT: f32 = 0.025;
const STUMPS_WEIGHT: f32 = 0.012;
let prop = SocketsCartesian3D::Simple {
x_pos: void,
x_neg: void,
z_pos: layer_4_up,
z_neg: props_down,
y_pos: void,
y_neg: void,
}
.to_template()
.with_weight(PROPS_WEIGHT);
let plant_prop = prop.clone().with_weight(PLANTS_WEIGHT);
let stump_prop = prop.clone().with_weight(STUMPS_WEIGHT);
let rock_prop = prop.clone().with_weight(ROCKS_WEIGHT);
// We define 2 assets here for 1 model. Both will be spawned when the model is selected.
// We only need the generator to know about the tree base, but in the engine, we want
// to spawn and see the tree leaves on top
// (We could also just have 1 asset with a 32x64 size)
models.create(plant_prop.clone());
assets.push(vec![
ModelAssetDef::new("small_tree_bottom"),
ModelAssetDef::new("small_tree_top").with_grid_offset(GridDelta::new(0, 1, 0)),
]);
models
.create(SocketsCartesian3D::Simple {
x_pos: big_tree_1_base,
x_neg: void,
z_pos: layer_4_up,
z_neg: props_down,
y_pos: void,
y_neg: void,
})
.with_weight(PROPS_WEIGHT);
assets.push(vec![
ModelAssetDef::new("big_tree_1_bl"),
ModelAssetDef::new("big_tree_1_tl").with_grid_offset(GridDelta::new(0, 1, 0)),
]);
models
.create(SocketsCartesian3D::Simple {
x_pos: void,
x_neg: big_tree_1_base,
z_pos: layer_4_up,
z_neg: props_down,
y_pos: void,
y_neg: void,
})
.with_weight(PROPS_WEIGHT);
assets.push(vec![
ModelAssetDef::new("big_tree_1_br"),
ModelAssetDef::new("big_tree_1_tr").with_grid_offset(GridDelta::new(0, 1, 0)),
]);
models
.create(SocketsCartesian3D::Simple {
x_pos: big_tree_2_base,
x_neg: void,
z_pos: layer_4_up,
z_neg: props_down,
y_pos: void,
y_neg: void,
})
.with_weight(PROPS_WEIGHT);
assets.push(vec![
ModelAssetDef::new("big_tree_2_bl"),
ModelAssetDef::new("big_tree_2_tl").with_grid_offset(GridDelta::new(0, 1, 0)),
]);
models
.create(SocketsCartesian3D::Simple {
x_pos: void,
x_neg: big_tree_2_base,
z_pos: layer_4_up,
z_neg: props_down,
y_pos: void,
y_neg: void,
})
.with_weight(PROPS_WEIGHT);
assets.push(vec![
ModelAssetDef::new("big_tree_2_br"),
ModelAssetDef::new("big_tree_2_tr").with_grid_offset(GridDelta::new(0, 1, 0)),
]);
// Here we reuse the same models to create variations. (We could also have 1 model, and multiple assets, with the spawner picking one of the assets at random)
models.create(stump_prop.clone());
assets.push(asset("tree_stump_1"));
models.create(stump_prop.clone());
assets.push(asset("tree_stump_2"));
models.create(stump_prop.clone());
assets.push(asset("tree_stump_3"));
models.create(rock_prop.clone());
assets.push(asset("rock_1"));
models.create(rock_prop.clone());
assets.push(asset("rock_2"));
models.create(rock_prop.clone());
assets.push(asset("rock_3"));
models.create(rock_prop.clone());
assets.push(asset("rock_4"));
models.create(plant_prop.clone());
assets.push(asset("plant_1"));
models.create(plant_prop.clone());
assets.push(asset("plant_2"));
models.create(plant_prop.clone());
assets.push(asset("plant_3"));
models.create(plant_prop.clone());
assets.push(asset("plant_4"));
sockets
.add_connections(vec![
(dirt, vec![dirt]),
(void, vec![void]),
(grass, vec![grass]),
(void_and_grass, vec![grass_and_void]),
(water, vec![water]),
(water_and_void, vec![void_and_water]),
(big_tree_1_base, vec![big_tree_1_base]),
(big_tree_2_base, vec![big_tree_2_base]),
])
// For this generation, our rotation axis is Z+, so we define connection on the Z axis with `add_rotated_connection` for sockets that still need to be compatible when rotated.
// Note: But in reality, in this example, we don't really need it. None of our models uses any rotation, apart from ModelRotation::Rot0 (notice that there's no call to `with_rotations` on any of the models).
// Simply using `add_connections` would give the same result (it allows connections with relative_rotation = Rot0)
.add_rotated_connections(vec![
(layer_0_up, vec![layer_1_down]),
(layer_1_up, vec![layer_2_down]),
(layer_2_up, vec![layer_3_down]),
(layer_3_up, vec![layer_4_down]),
(yellow_grass_down, vec![grass_up]),
(props_down, vec![ground_up]),
]);
// We add a debug name to the models from their first asset name
for model in models.models_mut() {
model.with_name(
assets[model.index()]
.first()
.unwrap_or(&ModelAssetDef::new("void"))
.path(),
);
}
(assets, models, sockets)
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
Henauxg/ghx_proc_gen | https://github.com/Henauxg/ghx_proc_gen/blob/8a0e7c7dc435c1927cc51893bfd55c3b1d777241/bevy_examples/tile-layers/tile-layers.rs | bevy_examples/tile-layers/tile-layers.rs | use bevy::{
app::{App, PluginGroup, Startup},
asset::{AssetServer, Handle},
color::Color,
ecs::system::{Commands, Res},
image::Image,
log::LogPlugin,
math::Vec3,
prelude::Camera2d,
render::texture::ImagePlugin,
transform::components::Transform,
utils::default,
DefaultPlugins,
};
use bevy_examples::{plugin::ProcGenExamplesPlugin, utils::load_assets};
use bevy_ghx_proc_gen::{
bevy_ghx_grid::{
debug_plugin::{view::DebugGridView, DebugGridView2dBundle},
ghx_grid::direction::Direction,
},
debug_plugin::generation::GenerationViewMode,
proc_gen::{
generator::{
builder::GeneratorBuilder, node_heuristic::NodeSelectionHeuristic, rules::RulesBuilder,
ModelSelectionHeuristic, RngMode,
},
ghx_grid::cartesian::{coordinates::Cartesian3D, grid::CartesianGrid},
},
spawner_plugin::NodesSpawner,
};
use crate::rules::rules_and_assets;
mod rules;
// ----------------- Configurable values ---------------------------
/// Modify these values to control the map size.
const GRID_X: u32 = 25;
const GRID_Y: u32 = 18;
/// Modify this value to control the way the generation is visualized
const GENERATION_VIEW_MODE: GenerationViewMode = GenerationViewMode::StepByStepTimed {
steps_count: 2,
interval_ms: 1,
};
// ------------------------------------------------------------------
const ASSETS_PATH: &str = "tile_layers";
/// Size of a block in world units (in Bevy 2d, 1 pixel is 1 world unit)
const TILE_SIZE: f32 = 32.;
/// Size of a grid node in world units
const NODE_SIZE: Vec3 = Vec3::new(TILE_SIZE, TILE_SIZE, 1.);
const ASSETS_SCALE: Vec3 = Vec3::ONE;
/// Number of z layers in the map, do not change without adapting the rules.
const GRID_Z: u32 = 5;
fn setup_scene(mut commands: Commands) {
// Camera
commands.spawn(Camera2d::default());
}
fn setup_generator(mut commands: Commands, asset_server: Res<AssetServer>) {
// Get rules from rules.rs
let (assets_definitions, models, socket_collection) = rules_and_assets();
let rules = RulesBuilder::new_cartesian_3d(models, socket_collection)
// Use ZForward as the up axis (rotation axis for models) since we are using Bevy in 2D
.with_rotation_axis(Direction::ZForward)
.build()
.unwrap();
let grid = CartesianGrid::new_cartesian_3d(GRID_X, GRID_Y, GRID_Z, false, false, false);
let mut gen_builder = GeneratorBuilder::new()
.with_rules(rules)
.with_grid(grid.clone())
.with_rng(RngMode::RandomSeed)
.with_node_heuristic(NodeSelectionHeuristic::MinimumRemainingValue)
.with_model_heuristic(ModelSelectionHeuristic::WeightedProbability);
let gen_observer = gen_builder.add_queued_observer();
let generator = gen_builder.build().unwrap();
let models_assets = load_assets::<Image>(&asset_server, assets_definitions, ASSETS_PATH, "png");
commands.spawn((
Transform::from_translation(Vec3 {
x: -TILE_SIZE * grid.size_x() as f32 / 2.,
y: -TILE_SIZE * grid.size_y() as f32 / 2.,
z: 0.,
}),
grid,
generator,
gen_observer,
NodesSpawner::new(models_assets, NODE_SIZE, Vec3::ZERO).with_z_offset_from_y(true),
DebugGridView2dBundle {
view: DebugGridView::new(false, true, Color::WHITE, NODE_SIZE),
..default()
},
));
}
fn main() {
let mut app = App::new();
app.add_plugins((
DefaultPlugins
.set(LogPlugin {
filter: "info,wgpu_core=error,wgpu_hal=error,ghx_proc_gen=debug".into(),
level: bevy::log::Level::DEBUG,
..default()
})
.set(ImagePlugin::default_nearest()),
ProcGenExamplesPlugin::<Cartesian3D, Handle<Image>>::new(
GENERATION_VIEW_MODE,
ASSETS_SCALE,
),
));
app.add_systems(Startup, (setup_generator, setup_scene));
app.run();
}
| rust | Apache-2.0 | 8a0e7c7dc435c1927cc51893bfd55c3b1d777241 | 2026-01-04T20:23:43.614602Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/prelude.rs | src/prelude.rs | //! Prelude provides all the traits of the library in a convenient form
pub use crate::bound::{PlaneBound, Relation};
pub use crate::traits::*;
pub use crate::volume::{Aabb, MinMax};
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/lib.rs | src/lib.rs | #![crate_type = "rlib"]
#![crate_type = "dylib"]
#![forbid(unsafe_code, unstable_features)]
#![deny(
missing_docs,
missing_copy_implementations,
missing_debug_implementations,
trivial_casts,
unused_import_braces,
unused_qualifications,
rust_2018_compatibility,
rust_2018_idioms,
nonstandard_style,
unused,
future_incompatible,
clippy::semicolon_if_nothing_returned,
clippy::unreadable_literal,
clippy::unseparated_literal_suffix,
clippy::needless_pass_by_value
)]
#![allow(clippy::excessive_precision)]
//! Companion library to cgmath, dealing with collision detection centric data structures and
//! algorithms.
//!
//! This crate provides useful data structures and algorithms for doing collision detection.
//! It is organized into a few distinct parts: generic geometry (ray, line, plane, frustum etc),
//! bounding volumes (AABB, OBB, Sphere etc), collision primitives and algorithms used for
//! collision detection, distance computation etc.
//!
#[cfg(feature = "serde")]
#[macro_use]
extern crate serde_crate;
// Re-exports
pub use bound::*;
pub use contact::*;
pub use frustum::*;
pub use line::*;
pub use plane::Plane;
pub use ray::*;
pub use traits::*;
pub use volume::*;
pub mod algorithm;
pub mod dbvt;
pub mod prelude;
pub mod primitive;
// Modules
mod bound;
mod contact;
mod frustum;
mod line;
mod plane;
mod ray;
mod traits;
mod volume;
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/contact.rs | src/contact.rs | //! Collision contact manifold
use cgmath::prelude::*;
/// Collision strategy to use for collisions.
///
/// This is used both to specify what collision strategy to use for each shape, and also each
/// found contact will have this returned on it, detailing what data is relevant in the
/// [`Contact`](struct.Contact.html).
#[derive(Debug, PartialEq, Copy, Clone, PartialOrd)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub enum CollisionStrategy {
/// Compute full contact manifold for the collision
FullResolution,
/// Only report that a collision occurred, skip computing contact information for the collision.
CollisionOnly,
}
/// Contact manifold for a single collision contact point.
///
/// # Type parameters
///
/// - `P`: cgmath point type
#[derive(Debug, Clone)]
pub struct Contact<P: EuclideanSpace> {
/// The collision strategy used for this contact.
pub strategy: CollisionStrategy,
/// The collision normal. Only applicable if the collision strategy is not `CollisionOnly`
pub normal: P::Diff,
/// The penetration depth. Only applicable if the collision strategy is not `CollisionOnly`
pub penetration_depth: P::Scalar,
/// The contact point. Only applicable if the collision strategy is not `CollisionOnly`
pub contact_point: P,
/// The time of impact, only applicable for continuous collision detection, value is in
/// range 0.0..1.0
pub time_of_impact: P::Scalar,
}
impl<P> Contact<P>
where
P: EuclideanSpace,
P::Diff: VectorSpace + Zero,
{
/// Create a new contact manifold, with default collision normal and penetration depth
pub fn new(strategy: CollisionStrategy) -> Self {
Self::new_impl(strategy, P::Diff::zero(), P::Scalar::zero())
}
/// Create a new contact manifold, with the given collision normal and penetration depth
pub fn new_impl(
strategy: CollisionStrategy,
normal: P::Diff,
penetration_depth: P::Scalar,
) -> Self {
Self::new_with_point(strategy, normal, penetration_depth, P::origin())
}
/// Create a new contact manifold, complete with contact point
pub fn new_with_point(
strategy: CollisionStrategy,
normal: P::Diff,
penetration_depth: P::Scalar,
contact_point: P,
) -> Self {
Self {
strategy,
normal,
penetration_depth,
contact_point,
time_of_impact: P::Scalar::zero(),
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/plane.rs | src/plane.rs | use std::fmt;
use cgmath::prelude::*;
use cgmath::{ulps_eq, ulps_ne};
use cgmath::{AbsDiffEq, RelativeEq, UlpsEq};
use cgmath::{BaseFloat, Point3, Vector3, Vector4};
use crate::prelude::*;
use crate::Ray3;
/// A 3-dimensional plane formed from the equation: `A*x + B*y + C*z - D = 0`.
///
/// # Fields
///
/// - `n`: a unit vector representing the normal of the plane where:
/// - `n.x`: corresponds to `A` in the plane equation
/// - `n.y`: corresponds to `B` in the plane equation
/// - `n.z`: corresponds to `C` in the plane equation
/// - `d`: the distance value, corresponding to `D` in the plane equation
///
/// # Notes
///
/// The `A*x + B*y + C*z - D = 0` form is preferred over the other common
/// alternative, `A*x + B*y + C*z + D = 0`, because it tends to avoid
/// superfluous negations (see _Real Time Collision Detection_, p. 55).
#[derive(Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Plane<S> {
/// Plane normal
pub n: Vector3<S>,
/// Plane distance value
pub d: S,
}
impl<S: BaseFloat> Plane<S> {
/// Construct a plane from a normal vector and a scalar distance. The
/// plane will be perpendicular to `n`, and `d` units offset from the
/// origin.
pub fn new(n: Vector3<S>, d: S) -> Plane<S> {
Plane { n, d }
}
/// # Arguments
///
/// - `a`: the `x` component of the normal
/// - `b`: the `y` component of the normal
/// - `c`: the `z` component of the normal
/// - `d`: the plane's distance value
pub fn from_abcd(a: S, b: S, c: S, d: S) -> Plane<S> {
Plane {
n: Vector3::new(a, b, c),
d,
}
}
/// Construct a plane from the components of a four-dimensional vector
pub fn from_vector4(v: Vector4<S>) -> Plane<S> {
Plane {
n: Vector3::new(v.x, v.y, v.z),
d: v.w,
}
}
/// Construct a plane from the components of a four-dimensional vector
/// Assuming alternative representation: `A*x + B*y + C*z + D = 0`
pub fn from_vector4_alt(v: Vector4<S>) -> Plane<S> {
Plane {
n: Vector3::new(v.x, v.y, v.z),
d: -v.w,
}
}
/// Constructs a plane that passes through the the three points `a`, `b` and `c`
pub fn from_points(a: Point3<S>, b: Point3<S>, c: Point3<S>) -> Option<Plane<S>> {
// create two vectors that run parallel to the plane
let v0 = b - a;
let v1 = c - a;
// find the normal vector that is perpendicular to v1 and v2
let n = v0.cross(v1);
if ulps_eq!(n, &Vector3::zero()) {
None
} else {
// compute the normal and the distance to the plane
let n = n.normalize();
let d = -a.dot(n);
Some(Plane::new(n, d))
}
}
/// Construct a plane from a point and a normal vector.
/// The plane will contain the point `p` and be perpendicular to `n`.
pub fn from_point_normal(p: Point3<S>, n: Vector3<S>) -> Plane<S> {
Plane { n, d: p.dot(n) }
}
/// Normalize a plane.
pub fn normalize(&self) -> Option<Plane<S>> {
if ulps_eq!(self.n, &Vector3::zero()) {
None
} else {
let denom = S::one() / self.n.magnitude();
Some(Plane::new(self.n * denom, self.d * denom))
}
}
}
impl<S: AbsDiffEq> AbsDiffEq for Plane<S>
where
S::Epsilon: Copy,
S: BaseFloat,
{
type Epsilon = S::Epsilon;
#[inline]
fn default_epsilon() -> S::Epsilon {
S::default_epsilon()
}
#[inline]
fn abs_diff_eq(&self, other: &Self, epsilon: S::Epsilon) -> bool {
Vector3::abs_diff_eq(&self.n, &other.n, epsilon)
&& S::abs_diff_eq(&self.d, &other.d, epsilon)
}
}
impl<S: RelativeEq> RelativeEq for Plane<S>
where
S::Epsilon: Copy,
S: BaseFloat,
{
#[inline]
fn default_max_relative() -> S::Epsilon {
S::default_max_relative()
}
#[inline]
fn relative_eq(&self, other: &Self, epsilon: S::Epsilon, max_relative: S::Epsilon) -> bool {
Vector3::relative_eq(&self.n, &other.n, epsilon, max_relative)
&& S::relative_eq(&self.d, &other.d, epsilon, max_relative)
}
}
impl<S: UlpsEq> UlpsEq for Plane<S>
where
S::Epsilon: Copy,
S: BaseFloat,
{
#[inline]
fn default_max_ulps() -> u32 {
S::default_max_ulps()
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: S::Epsilon, max_ulps: u32) -> bool {
Vector3::ulps_eq(&self.n, &other.n, epsilon, max_ulps)
&& S::ulps_eq(&self.d, &other.d, epsilon, max_ulps)
}
}
impl<S: BaseFloat> fmt::Debug for Plane<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:?}x + {:?}y + {:?}z - {:?} = 0",
self.n.x, self.n.y, self.n.z, self.d
)
}
}
impl<S: BaseFloat> Continuous<Ray3<S>> for Plane<S> {
type Result = Point3<S>;
fn intersection(&self, r: &Ray3<S>) -> Option<Point3<S>> {
let p = self;
let t = -(p.d + r.origin.dot(p.n)) / r.direction.dot(p.n);
if t < Zero::zero() {
None
} else {
Some(r.origin + r.direction * t)
}
}
}
impl<S: BaseFloat> Discrete<Ray3<S>> for Plane<S> {
fn intersects(&self, r: &Ray3<S>) -> bool {
let p = self;
let t = -(p.d + r.origin.dot(p.n)) / r.direction.dot(p.n);
t >= Zero::zero()
}
}
/// See _Real-Time Collision Detection_, p. 210
impl<S: BaseFloat> Continuous<Plane<S>> for Plane<S> {
type Result = Ray3<S>;
fn intersection(&self, p2: &Plane<S>) -> Option<Ray3<S>> {
let p1 = self;
let d = p1.n.cross(p2.n);
let denom = d.dot(d);
if ulps_eq!(denom, &S::zero()) {
None
} else {
let p = (p2.n * p1.d - p1.n * p2.d).cross(d) / denom;
Some(Ray3::new(Point3::from_vec(p), d))
}
}
}
impl<S: BaseFloat> Discrete<Plane<S>> for Plane<S> {
fn intersects(&self, p2: &Plane<S>) -> bool {
let p1 = self;
let d = p1.n.cross(p2.n);
let denom = d.dot(d);
ulps_ne!(denom, &S::zero())
}
}
/// See _Real-Time Collision Detection_, p. 212 - 214
impl<S: BaseFloat> Continuous<(Plane<S>, Plane<S>)> for Plane<S> {
type Result = Point3<S>;
fn intersection(&self, planes: &(Plane<S>, Plane<S>)) -> Option<Point3<S>> {
let (p1, p2, p3) = (self, planes.0, planes.1);
let u = p2.n.cross(p3.n);
let denom = p1.n.dot(u);
if ulps_eq!(denom.abs(), &S::zero()) {
None
} else {
let p = (u * p1.d + p1.n.cross(p2.n * p3.d - p3.n * p2.d)) / denom;
Some(Point3::from_vec(p))
}
}
}
impl<S: BaseFloat> Discrete<(Plane<S>, Plane<S>)> for Plane<S> {
fn intersects(&self, planes: &(Plane<S>, Plane<S>)) -> bool {
let (p1, p2, p3) = (self, planes.0, planes.1);
let u = p2.n.cross(p3.n);
let denom = p1.n.dot(u);
ulps_ne!(denom.abs(), &S::zero())
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/ray.rs | src/ray.rs | //! Generic rays
use core::fmt;
use std::marker::PhantomData;
use cgmath::prelude::*;
use cgmath::{BaseFloat, BaseNum};
use cgmath::{Point2, Point3};
use cgmath::{Vector2, Vector3};
use crate::traits::{Continuous, ContinuousTransformed, Discrete, DiscreteTransformed};
/// A generic ray starting at `origin` and extending infinitely in
/// `direction`.
#[derive(Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Ray<S, P, V> {
/// Ray origin
pub origin: P,
/// Normalized ray direction
pub direction: V,
phantom_s: PhantomData<S>,
}
impl<S, V, P> Ray<S, P, V>
where
S: BaseNum,
V: VectorSpace<Scalar = S>,
P: EuclideanSpace<Scalar = S, Diff = V>,
{
/// Create a generic ray starting at `origin` and extending infinitely in
/// `direction`.
pub fn new(origin: P, direction: V) -> Ray<S, P, V> {
Ray {
origin,
direction,
phantom_s: PhantomData,
}
}
/// Create a new ray by applying a transform.
pub fn transform<T>(&self, transform: &T) -> Self
where
T: Transform<P>,
{
Self::new(
transform.transform_point(self.origin),
transform.transform_vector(self.direction),
)
}
}
impl<S, P: fmt::Debug, V: fmt::Debug> fmt::Debug for Ray<S, P, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Ray")
.field(&self.origin)
.field(&self.direction)
.finish()
}
}
/// 2D ray
pub type Ray2<S> = Ray<S, Point2<S>, Vector2<S>>;
/// 3D ray
pub type Ray3<S> = Ray<S, Point3<S>, Vector3<S>>;
impl<S, P> Continuous<Ray<S, P, P::Diff>> for P
where
S: BaseFloat,
P: EuclideanSpace<Scalar = S>,
P::Diff: InnerSpace<Scalar = S>,
{
type Result = P;
fn intersection(&self, ray: &Ray<S, P, P::Diff>) -> Option<P> {
if self.intersects(ray) {
Some(*self)
} else {
None
}
}
}
impl<S, P> Discrete<Ray<S, P, P::Diff>> for P
where
S: BaseFloat,
P: EuclideanSpace<Scalar = S>,
P::Diff: InnerSpace<Scalar = S>,
{
fn intersects(&self, ray: &Ray<S, P, P::Diff>) -> bool {
let p = *self;
let l = p - ray.origin;
let tca = l.dot(ray.direction);
tca > S::zero()
&& (tca * tca).relative_eq(
&l.magnitude2(),
S::default_epsilon(),
S::default_max_relative(),
)
}
}
impl<P, C> DiscreteTransformed<Ray<P::Scalar, P, P::Diff>> for C
where
C: Discrete<Ray<P::Scalar, P, P::Diff>>,
P: EuclideanSpace,
P::Scalar: BaseFloat,
{
type Point = P;
fn intersects_transformed<T>(&self, ray: &Ray<P::Scalar, P, P::Diff>, transform: &T) -> bool
where
T: Transform<P>,
{
self.intersects(&ray.transform(&transform.inverse_transform().unwrap()))
}
}
impl<P, C> ContinuousTransformed<Ray<P::Scalar, P, P::Diff>> for C
where
C: Continuous<Ray<P::Scalar, P, P::Diff>, Result = P>,
P: EuclideanSpace,
P::Scalar: BaseFloat,
{
type Point = P;
type Result = P;
fn intersection_transformed<T>(
&self,
ray: &Ray<P::Scalar, P, P::Diff>,
transform: &T,
) -> Option<P>
where
T: Transform<P>,
{
self.intersection(&ray.transform(&transform.inverse_transform().unwrap()))
.map(|p| transform.transform_point(p))
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/bound.rs | src/bound.rs | //! Generic spatial bounds.
use cgmath::BaseFloat;
use cgmath::Matrix4;
use cgmath::{EuclideanSpace, Point3};
use std::{cmp, fmt};
use crate::frustum::Frustum;
use crate::plane::Plane;
/// Spatial relation between two objects.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)]
#[repr(u8)]
pub enum Relation {
/// Completely inside.
In,
/// Crosses the boundary.
Cross,
/// Completely outside.
Out,
}
/// Generic 3D bound.
pub trait PlaneBound<S: BaseFloat>: fmt::Debug {
/// Classify the spatial relation with a plane.
fn relate_plane(&self, plane: Plane<S>) -> Relation;
/// Classify the relation with a projection matrix.
fn relate_clip_space(&self, projection: Matrix4<S>) -> Relation {
let frustum = match Frustum::from_matrix4(projection) {
Some(f) => f,
None => return Relation::Cross,
};
[
frustum.left,
frustum.right,
frustum.top,
frustum.bottom,
frustum.near,
frustum.far,
]
.iter()
.fold(Relation::In, |cur, p| {
let r = self.relate_plane(*p);
// If any of the planes are `Out`, the bound is outside.
// Otherwise, if any are `Cross`, the bound is crossing.
// Otherwise, the bound is fully inside.
cmp::max(cur, r)
})
}
}
impl<S: BaseFloat> PlaneBound<S> for Point3<S> {
fn relate_plane(&self, plane: Plane<S>) -> Relation {
let dist = self.dot(plane.n);
if dist > plane.d {
Relation::In
} else if dist < plane.d {
Relation::Out
} else {
Relation::Cross
}
}
fn relate_clip_space(&self, projection: Matrix4<S>) -> Relation {
use std::cmp::Ordering::*;
let p = projection * self.to_homogeneous();
match (
p.x.abs().partial_cmp(&p.w),
p.y.abs().partial_cmp(&p.w),
p.z.abs().partial_cmp(&p.w),
) {
(Some(Less), Some(Less), Some(Less)) => Relation::In,
(Some(Greater), _, _) | (_, Some(Greater), _) | (_, _, Some(Greater)) => Relation::Out,
_ => Relation::Cross,
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/line.rs | src/line.rs | //! Line segments
use std::fmt;
use std::marker::PhantomData;
use cgmath::prelude::*;
use cgmath::{BaseFloat, BaseNum};
use cgmath::{Point2, Point3};
use cgmath::{Vector2, Vector3};
use crate::prelude::*;
use crate::Ray2;
/// A generic directed line segment from `origin` to `dest`.
#[derive(Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Line<S, V, P> {
/// Origin of the line
pub origin: P,
/// Endpoint of the line
pub dest: P,
phantom_s: PhantomData<S>,
phantom_v: PhantomData<V>,
}
impl<S: BaseNum, V: VectorSpace<Scalar = S>, P: EuclideanSpace<Scalar = S, Diff = V>>
Line<S, V, P>
{
/// Create a new directed line segment from `origin` to `dest`.
pub fn new(origin: P, dest: P) -> Line<S, V, P> {
Line {
origin,
dest,
phantom_v: PhantomData,
phantom_s: PhantomData,
}
}
}
impl<S, V, P: fmt::Debug> fmt::Debug for Line<S, V, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Line")
.field(&self.origin)
.field(&self.dest)
.finish()
}
}
/// 2D directed line segment
pub type Line2<S> = Line<S, Vector2<S>, Point2<S>>;
/// 3D directed line segment
pub type Line3<S> = Line<S, Vector3<S>, Point3<S>>;
impl<S: BaseFloat> Discrete<Ray2<S>> for Line2<S> {
fn intersects(&self, ray: &Ray2<S>) -> bool {
ray.intersection(self).is_some()
}
}
impl<S: BaseFloat> Continuous<Ray2<S>> for Line2<S> {
type Result = Point2<S>;
fn intersection(&self, ray: &Ray2<S>) -> Option<Self::Result> {
ray.intersection(self)
}
}
/// Determines if an intersection between a ray and a line segment is found.
impl<S: BaseFloat> Continuous<Line2<S>> for Ray2<S> {
type Result = Point2<S>;
fn intersection(&self, line: &Line2<S>) -> Option<Point2<S>> {
let ray = self;
let p = ray.origin;
let q = line.origin;
let r = ray.direction;
let s = Vector2::new(line.dest.x - line.origin.x, line.dest.y - line.origin.y);
let cross_1 = r.perp_dot(s);
let qmp = Vector2::new(q.x - p.x, q.y - p.y);
let cross_2 = qmp.perp_dot(r);
if cross_1 == S::zero() {
if cross_2 != S::zero() {
// parallel
return None;
}
// collinear
let q2mp = Vector2::new(line.dest.x - p.x, line.dest.y - p.y);
let dot_1 = qmp.dot(r);
let dot_2 = q2mp.dot(r);
if (dot_1 <= S::zero() && dot_2 >= S::zero())
|| (dot_1 >= S::zero() && dot_2 <= S::zero())
{
return Some(p);
} else if dot_1 >= S::zero() && dot_2 >= S::zero() {
if dot_1 <= dot_2 {
return Some(q);
} else {
return Some(line.dest);
}
}
// no overlap exists
return None;
}
let t = qmp.perp_dot(s) / cross_1;
let u = cross_2 / cross_1;
if S::zero() <= t && u >= S::zero() && u <= S::one() {
return Some(Point2::new(p.x + t * r.x, p.y + t * r.y));
}
None
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/traits.rs | src/traits.rs | use cgmath::prelude::*;
use cgmath::BaseNum;
/// An intersection test with a result.
///
/// An example would be a Ray vs AABB intersection test that returns a Point in space.
///
pub trait Continuous<RHS> {
/// Result returned by the intersection test
type Result;
/// Intersection test
fn intersection(&self, _: &RHS) -> Option<Self::Result>;
}
/// A boolean intersection test.
///
pub trait Discrete<RHS> {
/// Intersection test
fn intersects(&self, _: &RHS) -> bool;
}
/// Boolean containment test.
///
pub trait Contains<RHS> {
/// Containment test
fn contains(&self, _: &RHS) -> bool;
}
/// Shape surface area
///
pub trait SurfaceArea {
/// Result type returned from surface area computation
type Scalar: BaseNum;
/// Compute surface area
fn surface_area(&self) -> Self::Scalar;
}
/// Build the union of two shapes.
///
pub trait Union<RHS = Self> {
/// Union shape created
type Output;
/// Build the union shape of self and the given shape.
fn union(&self, _: &RHS) -> Self::Output;
}
/// Bounding volume abstraction for use with algorithms
pub trait Bound {
/// Point type for the bounding volume (for dimensionality)
type Point: EuclideanSpace;
/// Minimum extents of the bounding volume
fn min_extent(&self) -> Self::Point;
/// Maximum extents of the bounding volume
fn max_extent(&self) -> Self::Point;
/// Create a new bounding volume extended by the given amount
fn with_margin(&self, add: <Self::Point as EuclideanSpace>::Diff) -> Self;
/// Apply an arbitrary transform to the bounding volume
fn transform_volume<T>(&self, transform: &T) -> Self
where
T: Transform<Self::Point>;
/// Create empty volume
fn empty() -> Self;
}
/// Primitive with bounding volume
pub trait HasBound {
/// Bounding volume type
type Bound: Bound;
/// Borrow the bounding volume
fn bound(&self) -> &Self::Bound;
}
/// Utilities for computing bounding volumes of primitives
pub trait ComputeBound<B>
where
B: Bound,
{
/// Compute the bounding volume
fn compute_bound(&self) -> B;
}
/// Minkowski support function for primitive
pub trait Primitive {
/// Point type
type Point: EuclideanSpace;
/// Get the support point on the shape in a given direction.
///
/// ## Parameters
///
/// - `direction`: The search direction in world space.
/// - `transform`: The current local to world transform for this primitive.
///
/// ## Returns
///
/// Return the point that is furthest away from the origin, in the given search direction.
/// For discrete shapes, the furthest vertex is enough, there is no need to do exact
/// intersection point computation.
///
/// ## Type parameters
///
/// - `P`: Transform type
fn support_point<T>(
&self,
direction: &<Self::Point as EuclideanSpace>::Diff,
transform: &T,
) -> Self::Point
where
T: Transform<Self::Point>;
}
/// Discrete intersection test on transformed primitive
pub trait DiscreteTransformed<RHS> {
/// Point type for transformation of self
type Point: EuclideanSpace;
/// Intersection test for transformed self
fn intersects_transformed<T>(&self, _: &RHS, _: &T) -> bool
where
T: Transform<Self::Point>;
}
/// Continuous intersection test on transformed primitive
pub trait ContinuousTransformed<RHS> {
/// Point type for transformation of self
type Point: EuclideanSpace;
/// Result of intersection test
type Result: EuclideanSpace;
/// Intersection test for transformed self
fn intersection_transformed<T>(&self, _: &RHS, _: &T) -> Option<Self::Result>
where
T: Transform<Self::Point>;
}
/// Trait used for interpolation of values
///
/// ## Type parameters:
///
/// - `S`: The scalar type used for amount
pub trait Interpolate<S> {
/// Interpolate between `self` and `other`, using amount to calculate how much of other to use.
///
/// ## Parameters:
///
/// - `amount`: amount in the range 0. .. 1.
/// - `other`: the other value to interpolate with
///
/// ## Returns
///
/// A new value approximately equal to `self * (1. - amount) + other * amount`.
fn interpolate(&self, other: &Self, amount: S) -> Self;
}
/// Trait used for interpolation of translation only in transforms
pub trait TranslationInterpolate<S> {
/// Interpolate between `self` and `other`, using amount to calculate how much of other to use.
///
/// ## Parameters:
///
/// - `amount`: amount in the range 0. .. 1.
/// - `other`: the other value to interpolate with
///
/// ## Returns
///
/// A new value approximately equal to `self * (1. - amount) + other * amount`.
fn translation_interpolate(&self, other: &Self, amount: S) -> Self;
}
mod interpolate {
use super::{Interpolate, TranslationInterpolate};
use cgmath::prelude::*;
use cgmath::{BaseFloat, Basis2, Basis3, Decomposed, Quaternion, Rad};
impl<S> Interpolate<S> for Quaternion<S>
where
S: BaseFloat,
{
fn interpolate(&self, other: &Self, amount: S) -> Self {
self.lerp(*other, amount)
}
}
impl<S> Interpolate<S> for Basis3<S>
where
S: BaseFloat,
{
fn interpolate(&self, other: &Self, amount: S) -> Self {
Basis3::from(
Quaternion::from(*self.as_ref()).lerp(Quaternion::from(*other.as_ref()), amount),
)
}
}
impl<S> Interpolate<S> for Basis2<S>
where
S: BaseFloat,
{
fn interpolate(&self, other: &Self, amount: S) -> Self {
// to complex numbers
let self_mat = self.as_ref();
let other_mat = other.as_ref();
let self_c = self_mat.x;
let other_c = other_mat.x;
// do interpolation
let c = self_c.lerp(other_c, amount);
// to basis
Rotation2::from_angle(Rad(c.x.acos()))
}
}
impl<V, R> Interpolate<V::Scalar> for Decomposed<V, R>
where
V: VectorSpace + InnerSpace,
R: Interpolate<V::Scalar>,
V::Scalar: BaseFloat,
{
fn interpolate(&self, other: &Self, amount: V::Scalar) -> Self {
Decomposed {
disp: self.disp.lerp(other.disp, amount),
rot: self.rot.interpolate(&other.rot, amount),
scale: self.scale * (V::Scalar::one() - amount) + other.scale * amount,
}
}
}
impl<V, R> TranslationInterpolate<V::Scalar> for Decomposed<V, R>
where
V: VectorSpace + InnerSpace,
R: Clone,
V::Scalar: BaseFloat,
{
fn translation_interpolate(&self, other: &Self, amount: V::Scalar) -> Self {
Decomposed {
disp: self.disp.lerp(other.disp, amount),
rot: other.rot.clone(),
scale: other.scale,
}
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/frustum.rs | src/frustum.rs | //! View frustum for visibility determination
use crate::bound::*;
use crate::Plane;
use cgmath::BaseFloat;
use cgmath::Point3;
use cgmath::{Matrix, Matrix4};
use cgmath::{Ortho, Perspective, PerspectiveFov};
/// View frustum, used for frustum culling
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Frustum<S: BaseFloat> {
/// Left plane
pub left: Plane<S>,
/// Right plane
pub right: Plane<S>,
/// Bottom plane
pub bottom: Plane<S>,
/// Top plane
pub top: Plane<S>,
/// Near plane
pub near: Plane<S>,
/// Far plane
pub far: Plane<S>,
}
impl<S: BaseFloat> Frustum<S> {
/// Construct a frustum.
pub fn new(
left: Plane<S>,
right: Plane<S>,
bottom: Plane<S>,
top: Plane<S>,
near: Plane<S>,
far: Plane<S>,
) -> Frustum<S> {
Frustum {
left,
right,
bottom,
top,
near,
far,
}
}
/// Extract frustum planes from a projection matrix.
pub fn from_matrix4(mat: Matrix4<S>) -> Option<Frustum<S>> {
Some(Frustum::new(
match Plane::from_vector4_alt(mat.row(3) + mat.row(0)).normalize() {
Some(p) => p,
None => return None,
},
match Plane::from_vector4_alt(mat.row(3) - mat.row(0)).normalize() {
Some(p) => p,
None => return None,
},
match Plane::from_vector4_alt(mat.row(3) + mat.row(1)).normalize() {
Some(p) => p,
None => return None,
},
match Plane::from_vector4_alt(mat.row(3) - mat.row(1)).normalize() {
Some(p) => p,
None => return None,
},
match Plane::from_vector4_alt(mat.row(3) + mat.row(2)).normalize() {
Some(p) => p,
None => return None,
},
match Plane::from_vector4_alt(mat.row(3) - mat.row(2)).normalize() {
Some(p) => p,
None => return None,
},
))
}
/// Find the spatial relation of a bound inside this frustum.
pub fn contains<B: PlaneBound<S>>(&self, bound: &B) -> Relation {
[
self.left,
self.right,
self.top,
self.bottom,
self.near,
self.far,
]
.iter()
.fold(Relation::In, |cur, p| {
use std::cmp::max;
let r = bound.relate_plane(*p);
// If any of the planes are `Out`, the bound is outside.
// Otherwise, if any are `Cross`, the bound is crossing.
// Otherwise, the bound is fully inside.
max(cur, r)
})
}
}
/// View frustum corner points
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct FrustumPoints<S> {
/// Near top left point
pub near_top_left: Point3<S>,
/// Near top right point
pub near_top_right: Point3<S>,
/// Near bottom left point
pub near_bottom_left: Point3<S>,
/// Near bottom right point
pub near_bottom_right: Point3<S>,
/// Far top left point
pub far_top_left: Point3<S>,
/// Far top right point
pub far_top_right: Point3<S>,
/// Far bottom left point
pub far_bottom_left: Point3<S>,
/// Far bottom right point
pub far_bottom_right: Point3<S>,
}
/// Conversion trait for converting cgmath projection types into a view frustum
pub trait Projection<S: BaseFloat>: Into<Matrix4<S>> {
/// Create a view frustum
fn to_frustum(&self) -> Frustum<S>;
}
impl<S: BaseFloat> Projection<S> for PerspectiveFov<S> {
fn to_frustum(&self) -> Frustum<S> {
// TODO: Could this be faster?
Frustum::from_matrix4((*self).into()).unwrap()
}
}
impl<S: BaseFloat> Projection<S> for Perspective<S> {
fn to_frustum(&self) -> Frustum<S> {
// TODO: Could this be faster?
Frustum::from_matrix4((*self).into()).unwrap()
}
}
impl<S: BaseFloat> Projection<S> for Ortho<S> {
fn to_frustum(&self) -> Frustum<S> {
Frustum {
left: Plane::from_abcd(S::one(), S::zero(), S::zero(), self.left),
right: Plane::from_abcd(-S::one(), S::zero(), S::zero(), self.right),
bottom: Plane::from_abcd(S::zero(), S::one(), S::zero(), self.bottom),
top: Plane::from_abcd(S::zero(), -S::one(), S::zero(), self.top),
near: Plane::from_abcd(S::zero(), S::zero(), -S::one(), self.near),
far: Plane::from_abcd(S::zero(), S::zero(), S::one(), self.far),
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/primitive2.rs | src/primitive/primitive2.rs | //! Wrapper enum for 2D primitives
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point2, Vector2};
use crate::prelude::*;
use crate::primitive::{Circle, ConvexPolygon, Particle2, Rectangle, Square};
use crate::{Aabb2, Line2, Ray2};
/// Wrapper enum for 2D primitives, that also implements the `Primitive` trait, making it easier
/// to use many different primitives in algorithms.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub enum Primitive2<S: cgmath::BaseNum> {
/// Particle
Particle(Particle2<S>),
/// Line
Line(Line2<S>),
/// Circle
Circle(Circle<S>),
/// Rectangle
Rectangle(Rectangle<S>),
/// Square
Square(Square<S>),
/// Convex polygon with any number of vertices.
ConvexPolygon(ConvexPolygon<S>),
}
impl<S: cgmath::BaseNum> From<Particle2<S>> for Primitive2<S> {
fn from(particle: Particle2<S>) -> Primitive2<S> {
Primitive2::Particle(particle)
}
}
impl<S: cgmath::BaseNum> From<Line2<S>> for Primitive2<S> {
fn from(line: Line2<S>) -> Primitive2<S> {
Primitive2::Line(line)
}
}
impl<S: cgmath::BaseNum> From<Circle<S>> for Primitive2<S> {
fn from(circle: Circle<S>) -> Primitive2<S> {
Primitive2::Circle(circle)
}
}
impl<S: cgmath::BaseNum> From<Rectangle<S>> for Primitive2<S> {
fn from(rectangle: Rectangle<S>) -> Primitive2<S> {
Primitive2::Rectangle(rectangle)
}
}
impl<S: cgmath::BaseNum> From<Square<S>> for Primitive2<S> {
fn from(rectangle: Square<S>) -> Primitive2<S> {
Primitive2::Square(rectangle)
}
}
impl<S: cgmath::BaseNum> From<ConvexPolygon<S>> for Primitive2<S> {
fn from(polygon: ConvexPolygon<S>) -> Primitive2<S> {
Primitive2::ConvexPolygon(polygon)
}
}
impl<S> ComputeBound<Aabb2<S>> for Primitive2<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb2<S> {
match *self {
Primitive2::Particle(_) => Aabb2::zero(),
Primitive2::Line(ref line) => line.compute_bound(),
Primitive2::Circle(ref circle) => circle.compute_bound(),
Primitive2::Rectangle(ref rectangle) => rectangle.compute_bound(),
Primitive2::Square(ref square) => square.compute_bound(),
Primitive2::ConvexPolygon(ref polygon) => polygon.compute_bound(),
}
}
}
impl<S> Primitive for Primitive2<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
fn support_point<T>(&self, direction: &Vector2<S>, transform: &T) -> Point2<S>
where
T: Transform<Point2<S>>,
{
match *self {
Primitive2::Particle(_) => transform.transform_point(Point2::origin()),
Primitive2::Line(ref line) => line.support_point(direction, transform),
Primitive2::Circle(ref circle) => circle.support_point(direction, transform),
Primitive2::Rectangle(ref rectangle) => rectangle.support_point(direction, transform),
Primitive2::Square(ref square) => square.support_point(direction, transform),
Primitive2::ConvexPolygon(ref polygon) => polygon.support_point(direction, transform),
}
}
}
impl<S> DiscreteTransformed<Ray2<S>> for Primitive2<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
fn intersects_transformed<T>(&self, ray: &Ray2<S>, transform: &T) -> bool
where
T: Transform<Self::Point>,
{
match *self {
Primitive2::Particle(ref particle) => particle.intersects_transformed(ray, transform),
Primitive2::Line(ref line) => line.intersects_transformed(ray, transform),
Primitive2::Circle(ref circle) => circle.intersects_transformed(ray, transform),
Primitive2::Rectangle(ref rectangle) => {
rectangle.intersects_transformed(ray, transform)
}
Primitive2::Square(ref square) => square.intersects_transformed(ray, transform),
Primitive2::ConvexPolygon(ref polygon) => {
polygon.intersects_transformed(ray, transform)
}
}
}
}
impl<S> ContinuousTransformed<Ray2<S>> for Primitive2<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
type Result = Point2<S>;
fn intersection_transformed<T>(&self, ray: &Ray2<S>, transform: &T) -> Option<Point2<S>>
where
T: Transform<Point2<S>>,
{
match *self {
Primitive2::Particle(ref particle) => particle.intersection_transformed(ray, transform),
Primitive2::Line(ref line) => line.intersection_transformed(ray, transform),
Primitive2::Circle(ref circle) => circle.intersection_transformed(ray, transform),
Primitive2::Rectangle(ref rectangle) => {
rectangle.intersection_transformed(ray, transform)
}
Primitive2::Square(ref square) => square.intersection_transformed(ray, transform),
Primitive2::ConvexPolygon(ref polygon) => {
polygon.intersection_transformed(ray, transform)
}
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/rectangle.rs | src/primitive/rectangle.rs | //! Rectangle primitive
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point2, Vector2};
use crate::prelude::*;
use crate::primitive::util::get_max_point;
use crate::{Aabb2, Ray2};
/// Rectangle primitive.
///
/// Have a cached set of corner points to speed up computation.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Rectangle<S> {
/// Dimensions of the rectangle
dim: Vector2<S>,
half_dim: Vector2<S>,
corners: [Point2<S>; 4],
}
impl<S> Rectangle<S>
where
S: BaseFloat,
{
/// Create a new rectangle primitive from component dimensions
pub fn new(dim_x: S, dim_y: S) -> Self {
Self::new_impl(Vector2::new(dim_x, dim_y))
}
/// Create a new rectangle primitive from a vector of component dimensions
pub fn new_impl(dim: Vector2<S>) -> Self {
let half_dim = dim / (S::one() + S::one());
Rectangle {
dim,
half_dim,
corners: Self::generate_corners(&half_dim),
}
}
/// Get the dimensions of the `Rectangle`
pub fn dim(&self) -> &Vector2<S> {
&self.dim
}
/// Get the half dimensions of the `Rectangle`
pub fn half_dim(&self) -> &Vector2<S> {
&self.half_dim
}
fn generate_corners(half_dim: &Vector2<S>) -> [Point2<S>; 4] {
[
Point2::new(half_dim.x, half_dim.y),
Point2::new(-half_dim.x, half_dim.y),
Point2::new(-half_dim.x, -half_dim.y),
Point2::new(half_dim.x, -half_dim.y),
]
}
}
impl<S> Primitive for Rectangle<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
fn support_point<T>(&self, direction: &Vector2<S>, transform: &T) -> Point2<S>
where
T: Transform<Point2<S>>,
{
get_max_point(self.corners.iter(), direction, transform)
}
}
impl<S> ComputeBound<Aabb2<S>> for Rectangle<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb2<S> {
Aabb2::new(
Point2::from_vec(-self.half_dim),
Point2::from_vec(self.half_dim),
)
}
}
impl<S> Discrete<Ray2<S>> for Rectangle<S>
where
S: BaseFloat,
{
/// Ray must be in object space of the rectangle
fn intersects(&self, ray: &Ray2<S>) -> bool {
self.compute_bound().intersects(ray)
}
}
impl<S> Continuous<Ray2<S>> for Rectangle<S>
where
S: BaseFloat,
{
type Result = Point2<S>;
/// Ray must be in object space of the rectangle
fn intersection(&self, ray: &Ray2<S>) -> Option<Point2<S>> {
self.compute_bound().intersection(ray)
}
}
/// Square primitive.
///
/// Have a cached set of corner points to speed up computation.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Square<S> {
rectangle: Rectangle<S>,
}
impl<S> Square<S>
where
S: BaseFloat,
{
/// Create a new square primitive from dimension
pub fn new(dim: S) -> Self {
Square {
rectangle: Rectangle::new(dim, dim),
}
}
/// Get the dimensions of the `Square`
pub fn dim(&self) -> S {
self.rectangle.dim.x
}
/// Get the half dimensions of the `Square`
pub fn half_dim(&self) -> S {
self.rectangle.half_dim.x
}
}
impl<S> Primitive for Square<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
fn support_point<T>(&self, direction: &Vector2<S>, transform: &T) -> Point2<S>
where
T: Transform<Point2<S>>,
{
self.rectangle.support_point(direction, transform)
}
}
impl<S> ComputeBound<Aabb2<S>> for Square<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb2<S> {
self.rectangle.compute_bound()
}
}
impl<S> Discrete<Ray2<S>> for Square<S>
where
S: BaseFloat,
{
/// Ray must be in object space of the rectangle
fn intersects(&self, ray: &Ray2<S>) -> bool {
self.rectangle.intersects(ray)
}
}
impl<S> Continuous<Ray2<S>> for Square<S>
where
S: BaseFloat,
{
type Result = Point2<S>;
/// Ray must be in object space of the rectangle
fn intersection(&self, ray: &Ray2<S>) -> Option<Point2<S>> {
self.rectangle.intersection(ray)
}
}
#[cfg(test)]
mod tests {
use cgmath::assert_ulps_eq;
use cgmath::{Basis2, Decomposed, Point2, Rad, Vector2};
use super::*;
#[test]
fn test_rectangle_bound() {
let r = Rectangle::new(10., 10.);
assert_eq!(bound(-5., -5., 5., 5.), r.compute_bound());
}
#[test]
fn test_rectangle_ray_discrete() {
let rectangle = Rectangle::new(10., 10.);
let ray = Ray2::new(Point2::new(20., 0.), Vector2::new(-1., 0.));
assert!(rectangle.intersects(&ray));
let ray = Ray2::new(Point2::new(20., 0.), Vector2::new(0., 1.));
assert!(!rectangle.intersects(&ray));
}
#[test]
fn test_rectangle_ray_discrete_transformed() {
let rectangle = Rectangle::new(10., 10.);
let ray = Ray2::new(Point2::new(20., 0.), Vector2::new(-1., 0.));
let t = transform(0., 0., 0.);
assert!(rectangle.intersects_transformed(&ray, &t));
let ray = Ray2::new(Point2::new(20., 0.), Vector2::new(-1., 0.));
let t = transform(0., 20., 0.);
assert!(!rectangle.intersects_transformed(&ray, &t));
}
#[test]
fn test_rectangle_ray_continuous() {
let rectangle = Rectangle::new(10., 10.);
let ray = Ray2::new(Point2::new(20., 0.), Vector2::new(-1., 0.));
assert_eq!(Some(Point2::new(5., 0.)), rectangle.intersection(&ray));
let ray = Ray2::new(Point2::new(20., 0.), Vector2::new(0., 1.));
assert_eq!(None, rectangle.intersection(&ray));
}
#[test]
fn test_rectangle_ray_continuous_transformed() {
let rectangle = Rectangle::new(10., 10.);
let ray = Ray2::new(Point2::new(20., 0.), Vector2::new(-1., 0.));
let t = transform(0., 0., 0.);
assert_eq!(
Some(Point2::new(5., 0.)),
rectangle.intersection_transformed(&ray, &t)
);
let ray = Ray2::new(Point2::new(20., 0.), Vector2::new(-1., 0.));
let t = transform(0., 20., 0.);
assert_eq!(None, rectangle.intersection_transformed(&ray, &t));
let t = transform(0., 0., 0.3);
let p = rectangle.intersection_transformed(&ray, &t).unwrap();
assert_ulps_eq!(5.233_758, p.x);
assert_ulps_eq!(0., p.y);
}
// util
fn transform(dx: f32, dy: f32, rot: f32) -> Decomposed<Vector2<f32>, Basis2<f32>> {
Decomposed {
scale: 1.,
rot: Rotation2::from_angle(Rad(rot)),
disp: Vector2::new(dx, dy),
}
}
fn bound(min_x: f32, min_y: f32, max_x: f32, max_y: f32) -> Aabb2<f32> {
Aabb2::new(Point2::new(min_x, min_y), Point2::new(max_x, max_y))
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/polygon.rs | src/primitive/polygon.rs | //! Convex polygon primitive
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point2, Vector2};
use crate::prelude::*;
use crate::primitive::util::{get_bound, get_max_point};
use crate::{Aabb2, Line2, Ray2};
/// Convex polygon primitive.
///
/// Can contain any number of vertices, but a high number of vertices will
/// affect performance of course. Vertices need to be in CCW order.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct ConvexPolygon<S> {
/// Vertices of the convex polygon.
pub vertices: Vec<Point2<S>>,
}
impl<S> ConvexPolygon<S> {
/// Create a new convex polygon from the given vertices. Vertices need to be in CCW order.
pub fn new(vertices: Vec<Point2<S>>) -> Self {
Self { vertices }
}
}
impl<S> Primitive for ConvexPolygon<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
fn support_point<T>(&self, direction: &Vector2<S>, transform: &T) -> Point2<S>
where
T: Transform<Point2<S>>,
{
if self.vertices.len() < 10 {
get_max_point(self.vertices.iter(), direction, transform)
} else {
support_point(&self.vertices, direction, transform)
}
}
}
impl<S> ComputeBound<Aabb2<S>> for ConvexPolygon<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb2<S> {
get_bound(self.vertices.iter())
}
}
impl<S> Discrete<Ray2<S>> for ConvexPolygon<S>
where
S: BaseFloat,
{
/// Ray must be in object space
fn intersects(&self, ray: &Ray2<S>) -> bool {
for j in 0..self.vertices.len() - 1 {
let i = if j == 0 {
self.vertices.len() - 1
} else {
j - 1
};
let normal = Vector2::new(
self.vertices[j].y - self.vertices[i].y,
self.vertices[i].x - self.vertices[j].x,
);
// check if edge normal points toward the ray origin
if ray.direction.dot(normal) < S::zero()
// check line ray intersection
&& ray.intersection(&Line2::new(self.vertices[i], self.vertices[j]))
.is_some()
{
return true;
}
}
false
}
}
impl<S> Continuous<Ray2<S>> for ConvexPolygon<S>
where
S: BaseFloat,
{
type Result = Point2<S>;
/// Ray must be in object space
fn intersection(&self, ray: &Ray2<S>) -> Option<Point2<S>> {
for j in 0..self.vertices.len() - 1 {
let i = if j == 0 {
self.vertices.len() - 1
} else {
j - 1
};
let normal = Vector2::new(
self.vertices[j].y - self.vertices[i].y,
self.vertices[i].x - self.vertices[j].x,
);
// check if edge normal points toward the ray origin
if ray.direction.dot(normal) < S::zero() {
// check line ray intersection
if let point @ Some(_) =
ray.intersection(&Line2::new(self.vertices[i], self.vertices[j]))
{
return point;
}
}
}
None
}
}
fn support_point<P, T>(vertices: &[P], direction: &P::Diff, transform: &T) -> P
where
P: EuclideanSpace,
P::Scalar: BaseFloat,
T: Transform<P>,
{
let direction = transform.inverse_transform_vector(*direction).unwrap();
// figure out where to start, if the direction is negative for the first vertex,
// go halfway around the polygon
let mut start_index: i32 = 0;
let mut max_dot = vertices[0].dot(direction);
if max_dot < P::Scalar::zero() {
start_index = vertices.len() as i32 / 2;
max_dot = dot_index(vertices, start_index, &direction);
}
let left_dot = dot_index(vertices, start_index - 1, &direction);
let right_dot = dot_index(vertices, start_index + 1, &direction);
// check if start is highest
let p = if start_index == 0 && max_dot > left_dot && max_dot > right_dot {
vertices[0]
} else {
// figure out iteration direction
let mut add: i32 = 1;
let mut previous_dot = left_dot;
if left_dot > max_dot && left_dot > right_dot {
add = -1;
previous_dot = right_dot;
}
// iterate
let mut index = start_index + add;
let mut current_dot = max_dot;
if index == vertices.len() as i32 {
index = 0;
}
if index == -1 {
index = vertices.len() as i32 - 1;
}
while index != start_index {
let next_dot = dot_index(vertices, index + add, &direction);
if current_dot > previous_dot && current_dot > next_dot {
break;
}
previous_dot = current_dot;
current_dot = next_dot;
index += add;
if index == vertices.len() as i32 {
index = 0;
}
if index == -1 {
index = vertices.len() as i32 - 1;
}
}
vertices[index as usize]
};
transform.transform_point(p)
}
#[inline]
fn dot_index<P>(vertices: &[P], index: i32, direction: &P::Diff) -> P::Scalar
where
P: EuclideanSpace,
P::Scalar: BaseFloat,
{
let index_u = index as usize;
if index_u == vertices.len() {
vertices[0]
} else if index == -1 {
vertices[vertices.len() - 1]
} else {
vertices[index_u]
}
.dot(*direction)
}
#[cfg(test)]
mod tests {
use cgmath::assert_ulps_eq;
use cgmath::{Basis2, Decomposed, Point2, Rad, Vector2};
use super::*;
use {Aabb2, Ray2};
#[test]
fn test_support_point() {
let vertices = vec![
Point2::new(5., 5.),
Point2::new(4., 6.),
Point2::new(3., 7.),
Point2::new(2., 6.),
Point2::new(1., 6.),
Point2::new(0., 5.),
Point2::new(-1., 4.),
Point2::new(-3., 3.),
Point2::new(-6., 1.),
Point2::new(-5., 0.),
Point2::new(-4., -1.),
Point2::new(-2., -3.),
Point2::new(0., -7.),
Point2::new(1., -8.),
Point2::new(2., -5.),
Point2::new(3., 0.),
Point2::new(4., 3.),
];
let t = transform(0., 0., 0.);
let point = support_point(&vertices, &Vector2::new(-1., 0.), &t);
assert_eq!(Point2::new(-5., 0.), point);
let point = support_point(&vertices, &Vector2::new(0., -1.), &t);
assert_eq!(Point2::new(1., -8.), point);
let point = support_point(&vertices, &Vector2::new(0., 1.), &t);
assert_eq!(Point2::new(3., 7.), point);
let point = support_point(&vertices, &Vector2::new(1., 0.), &t);
assert_eq!(Point2::new(5., 5.), point);
}
#[test]
fn test_bound() {
let vertices = vec![
Point2::new(5., 5.),
Point2::new(4., 6.),
Point2::new(3., 7.),
Point2::new(2., 6.),
Point2::new(1., 6.),
Point2::new(0., 5.),
Point2::new(-1., 4.),
Point2::new(-3., 3.),
Point2::new(-6., 1.),
Point2::new(-5., 0.),
Point2::new(-4., -1.),
Point2::new(-2., -3.),
Point2::new(0., -7.),
Point2::new(1., -8.),
Point2::new(2., -5.),
Point2::new(3., 0.),
Point2::new(4., 3.),
];
let polygon = ConvexPolygon::new(vertices);
assert_eq!(
Aabb2::new(Point2::new(-6., -8.), Point2::new(5., 7.)),
polygon.compute_bound()
);
}
#[test]
fn test_ray_discrete() {
let vertices = vec![
Point2::new(5., 5.),
Point2::new(4., 6.),
Point2::new(3., 7.),
Point2::new(2., 6.),
Point2::new(1., 6.),
Point2::new(0., 5.),
Point2::new(-1., 4.),
Point2::new(-3., 3.),
Point2::new(-6., 1.),
Point2::new(-5., 0.),
Point2::new(-4., -1.),
Point2::new(-2., -3.),
Point2::new(0., -7.),
Point2::new(1., -8.),
Point2::new(2., -5.),
Point2::new(3., 0.),
Point2::new(4., 3.),
];
let polygon = ConvexPolygon::new(vertices);
let ray = Ray2::new(Point2::new(0., 10.), Vector2::new(0., -1.));
assert!(polygon.intersects(&ray));
let ray = Ray2::new(Point2::new(0., 10.), Vector2::new(0., 1.));
assert!(!polygon.intersects(&ray));
let ray = Ray2::new(Point2::new(0., 7.2), Vector2::new(1., 0.));
assert!(!polygon.intersects(&ray));
let ray = Ray2::new(Point2::new(0., 6.8), Vector2::new(1., 0.));
assert!(polygon.intersects(&ray));
}
#[test]
fn test_ray_discrete_transformed() {
let vertices = vec![
Point2::new(5., 5.),
Point2::new(4., 6.),
Point2::new(3., 7.),
Point2::new(2., 6.),
Point2::new(1., 6.),
Point2::new(0., 5.),
Point2::new(-1., 4.),
Point2::new(-3., 3.),
Point2::new(-6., 1.),
Point2::new(-5., 0.),
Point2::new(-4., -1.),
Point2::new(-2., -3.),
Point2::new(0., -7.),
Point2::new(1., -8.),
Point2::new(2., -5.),
Point2::new(3., 0.),
Point2::new(4., 3.),
];
let polygon = ConvexPolygon::new(vertices);
let t = transform(0., 0., 0.);
let ray = Ray2::new(Point2::new(0., 10.), Vector2::new(0., -1.));
assert!(polygon.intersects_transformed(&ray, &t));
let ray = Ray2::new(Point2::new(0., 10.), Vector2::new(0., 1.));
assert!(!polygon.intersects_transformed(&ray, &t));
let ray = Ray2::new(Point2::new(0., 7.2), Vector2::new(1., 0.));
assert!(!polygon.intersects_transformed(&ray, &t));
let ray = Ray2::new(Point2::new(0., 6.8), Vector2::new(1., 0.));
assert!(polygon.intersects_transformed(&ray, &t));
let t = transform(0., -2., 0.);
assert!(!polygon.intersects_transformed(&ray, &t));
let t = transform(0., 0., 0.3);
assert!(polygon.intersects_transformed(&ray, &t));
}
#[test]
fn test_ray_continuous() {
let vertices = vec![
Point2::new(5., 5.),
Point2::new(4., 6.),
Point2::new(3., 7.),
Point2::new(2., 6.),
Point2::new(1., 6.),
Point2::new(0., 5.),
Point2::new(-1., 4.),
Point2::new(-3., 3.),
Point2::new(-6., 1.),
Point2::new(-5., 0.),
Point2::new(-4., -1.),
Point2::new(-2., -3.),
Point2::new(0., -7.),
Point2::new(1., -8.),
Point2::new(2., -5.),
Point2::new(3., 0.),
Point2::new(4., 3.),
];
let polygon = ConvexPolygon::new(vertices);
let ray = Ray2::new(Point2::new(0., 10.), Vector2::new(0., -1.));
assert_eq!(Some(Point2::new(0., 5.)), polygon.intersection(&ray));
let ray = Ray2::new(Point2::new(0., 10.), Vector2::new(0., 1.));
assert_eq!(None, polygon.intersection(&ray));
let ray = Ray2::new(Point2::new(0., 7.2), Vector2::new(1., 0.));
assert_eq!(None, polygon.intersection(&ray));
let ray = Ray2::new(Point2::new(0., 6.8), Vector2::new(1., 0.));
let p = polygon.intersection(&ray).unwrap();
assert_ulps_eq!(2.8, p.x);
assert_ulps_eq!(6.8, p.y);
}
#[test]
fn test_ray_continuous_transformed() {
let vertices = vec![
Point2::new(5., 5.),
Point2::new(4., 6.),
Point2::new(3., 7.),
Point2::new(2., 6.),
Point2::new(1., 6.),
Point2::new(0., 5.),
Point2::new(-1., 4.),
Point2::new(-3., 3.),
Point2::new(-6., 1.),
Point2::new(-5., 0.),
Point2::new(-4., -1.),
Point2::new(-2., -3.),
Point2::new(0., -7.),
Point2::new(1., -8.),
Point2::new(2., -5.),
Point2::new(3., 0.),
Point2::new(4., 3.),
];
let t = transform(0., 0., 0.);
let polygon = ConvexPolygon::new(vertices);
let ray = Ray2::new(Point2::new(0., 10.), Vector2::new(0., -1.));
assert_eq!(
Some(Point2::new(0., 5.)),
polygon.intersection_transformed(&ray, &t)
);
let ray = Ray2::new(Point2::new(0., 10.), Vector2::new(0., 1.));
assert_eq!(None, polygon.intersection_transformed(&ray, &t));
let ray = Ray2::new(Point2::new(0., 7.2), Vector2::new(1., 0.));
assert_eq!(None, polygon.intersection_transformed(&ray, &t));
let ray = Ray2::new(Point2::new(0., 6.8), Vector2::new(1., 0.));
let p = polygon.intersection_transformed(&ray, &t).unwrap();
assert_ulps_eq!(2.8, p.x);
assert_ulps_eq!(6.8, p.y);
let t = transform(0., -2., 0.);
assert_eq!(None, polygon.intersection_transformed(&ray, &t));
let t = transform(0., 0., 0.3);
let p = polygon.intersection_transformed(&ray, &t).unwrap();
assert_ulps_eq!(0.389_133_57, p.x);
assert_ulps_eq!(6.8, p.y);
}
fn transform(dx: f32, dy: f32, rot: f32) -> Decomposed<Vector2<f32>, Basis2<f32>> {
Decomposed {
scale: 1.,
rot: Rotation2::from_angle(Rad(rot)),
disp: Vector2::new(dx, dy),
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/cuboid.rs | src/primitive/cuboid.rs | use cgmath::prelude::*;
use cgmath::{BaseFloat, Point3, Vector3};
use crate::prelude::*;
use crate::primitive::util::get_max_point;
use crate::volume::Sphere;
use crate::{Aabb3, Ray3};
/// Cuboid primitive.
///
/// Have a cached set of corner points to speed up computation.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Cuboid<S> {
/// Dimensions of the box
dim: Vector3<S>,
half_dim: Vector3<S>,
corners: [Point3<S>; 8],
}
impl<S> Cuboid<S>
where
S: BaseFloat,
{
/// Create a new cuboid primitive from component dimensions
pub fn new(dim_x: S, dim_y: S, dim_z: S) -> Self {
Self::new_impl(Vector3::new(dim_x, dim_y, dim_z))
}
/// Create a new cuboid primitive from a vector of component dimensions
pub fn new_impl(dim: Vector3<S>) -> Self {
let half_dim = dim / (S::one() + S::one());
Self {
dim,
half_dim,
corners: Self::generate_corners(&half_dim),
}
}
/// Get the dimensions of the `Cuboid`
pub fn dim(&self) -> &Vector3<S> {
&self.dim
}
/// Get the half dimensions of the `Cuboid`
pub fn half_dim(&self) -> &Vector3<S> {
&self.half_dim
}
fn generate_corners(half_dim: &Vector3<S>) -> [Point3<S>; 8] {
[
Point3::new(half_dim.x, half_dim.y, half_dim.z),
Point3::new(-half_dim.x, half_dim.y, half_dim.z),
Point3::new(-half_dim.x, -half_dim.y, half_dim.z),
Point3::new(half_dim.x, -half_dim.y, half_dim.z),
Point3::new(half_dim.x, half_dim.y, -half_dim.z),
Point3::new(-half_dim.x, half_dim.y, -half_dim.z),
Point3::new(-half_dim.x, -half_dim.y, -half_dim.z),
Point3::new(half_dim.x, -half_dim.y, -half_dim.z),
]
}
}
impl<S> Primitive for Cuboid<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn support_point<T>(&self, direction: &Vector3<S>, transform: &T) -> Point3<S>
where
T: Transform<Point3<S>>,
{
get_max_point(self.corners.iter(), direction, transform)
}
}
impl<S> ComputeBound<Aabb3<S>> for Cuboid<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb3<S> {
Aabb3::new(
Point3::from_vec(-self.half_dim),
Point3::from_vec(self.half_dim),
)
}
}
impl<S> ComputeBound<Sphere<S>> for Cuboid<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Sphere<S> {
let max = self.half_dim.x.max(self.half_dim.y).max(self.half_dim.z);
Sphere {
center: Point3::origin(),
radius: max,
}
}
}
impl<S> Discrete<Ray3<S>> for Cuboid<S>
where
S: BaseFloat,
{
fn intersects(&self, ray: &Ray3<S>) -> bool {
Aabb3::new(
Point3::from_vec(-self.half_dim),
Point3::from_vec(self.half_dim),
)
.intersects(ray)
}
}
impl<S> Continuous<Ray3<S>> for Cuboid<S>
where
S: BaseFloat,
{
type Result = Point3<S>;
fn intersection(&self, ray: &Ray3<S>) -> Option<Point3<S>> {
Aabb3::new(
Point3::from_vec(-self.half_dim),
Point3::from_vec(self.half_dim),
)
.intersection(ray)
}
}
/// Cuboid primitive.
///
/// Have a cached set of corner points to speed up computation.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Cube<S> {
cuboid: Cuboid<S>,
}
impl<S> Cube<S>
where
S: BaseFloat,
{
/// Create a new cube primitive
pub fn new(dim: S) -> Self {
Cube {
cuboid: Cuboid::new(dim, dim, dim),
}
}
/// Get the dimension of the cube
pub fn dim(&self) -> S {
self.cuboid.dim.x
}
/// Get the half dimension of the cube
pub fn half_dim(&self) -> S {
self.cuboid.half_dim.x
}
}
impl<S> Primitive for Cube<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn support_point<T>(&self, direction: &Vector3<S>, transform: &T) -> Point3<S>
where
T: Transform<Point3<S>>,
{
self.cuboid.support_point(direction, transform)
}
}
impl<S> ComputeBound<Aabb3<S>> for Cube<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb3<S> {
self.cuboid.compute_bound()
}
}
impl<S> ComputeBound<Sphere<S>> for Cube<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Sphere<S> {
self.cuboid.compute_bound()
}
}
impl<S> Discrete<Ray3<S>> for Cube<S>
where
S: BaseFloat,
{
fn intersects(&self, ray: &Ray3<S>) -> bool {
self.cuboid.intersects(ray)
}
}
impl<S> Continuous<Ray3<S>> for Cube<S>
where
S: BaseFloat,
{
type Result = Point3<S>;
fn intersection(&self, ray: &Ray3<S>) -> Option<Point3<S>> {
self.cuboid.intersection(ray)
}
}
#[cfg(test)]
mod tests {
use cgmath::assert_ulps_eq;
use cgmath::{Decomposed, Point3, Quaternion, Rad, Vector3};
use super::*;
use Ray3;
#[test]
fn test_rectangle_bound() {
let r = Cuboid::new(10., 10., 10.);
assert_eq!(bound(-5., -5., -5., 5., 5., 5.), r.compute_bound());
}
#[test]
fn test_ray_discrete() {
let cuboid = Cuboid::new(10., 10., 10.);
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(-1., 0., 0.));
assert!(cuboid.intersects(&ray));
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(1., 0., 0.));
assert!(!cuboid.intersects(&ray));
}
#[test]
fn test_ray_discrete_transformed() {
let cuboid = Cuboid::new(10., 10., 10.);
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(-1., 0., 0.));
let t = transform(0., 1., 0., 0.);
assert!(cuboid.intersects_transformed(&ray, &t));
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(1., 0., 0.));
assert!(!cuboid.intersects_transformed(&ray, &t));
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(-1., 0., 0.));
let t = transform(0., 1., 0., 0.3);
assert!(cuboid.intersects_transformed(&ray, &t));
}
#[test]
fn test_ray_continuous() {
let cuboid = Cuboid::new(10., 10., 10.);
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(-1., 0., 0.));
assert_eq!(Some(Point3::new(5., 0., 0.)), cuboid.intersection(&ray));
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(1., 0., 0.));
assert_eq!(None, cuboid.intersection(&ray));
}
#[test]
fn test_ray_continuous_transformed() {
let cuboid = Cuboid::new(10., 10., 10.);
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(-1., 0., 0.));
let t = transform(0., 1., 0., 0.);
assert_eq!(
Some(Point3::new(5., 0., 0.)),
cuboid.intersection_transformed(&ray, &t)
);
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(1., 0., 0.));
assert_eq!(None, cuboid.intersection_transformed(&ray, &t));
let ray = Ray3::new(Point3::new(10., 0., 0.), Vector3::new(-1., 0., 0.));
let t = transform(0., 0., 0., 0.3);
let p = cuboid.intersection_transformed(&ray, &t).unwrap();
assert_ulps_eq!(5.233_758, p.x);
assert_ulps_eq!(0., p.y);
assert_ulps_eq!(0., p.z);
}
// util
fn transform(dx: f32, dy: f32, dz: f32, rot: f32) -> Decomposed<Vector3<f32>, Quaternion<f32>> {
Decomposed {
scale: 1.,
rot: Quaternion::from_angle_z(Rad(rot)),
disp: Vector3::new(dx, dy, dz),
}
}
fn bound(min_x: f32, min_y: f32, min_z: f32, max_x: f32, max_y: f32, max_z: f32) -> Aabb3<f32> {
Aabb3::new(
Point3::new(min_x, min_y, min_z),
Point3::new(max_x, max_y, max_z),
)
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/util.rs | src/primitive/util.rs | //! Utilities
//!
use std::ops::Neg;
use crate::{Aabb, Ray3};
use cgmath::num_traits::Float;
use cgmath::prelude::*;
use cgmath::{BaseFloat, BaseNum, Vector2};
pub(crate) fn get_max_point<'a, P: 'a, T, I>(vertices: I, direction: &P::Diff, transform: &T) -> P
where
P: EuclideanSpace,
P::Scalar: BaseFloat,
T: Transform<P>,
I: Iterator<Item = &'a P>,
{
let direction = transform.inverse_transform_vector(*direction).unwrap();
let (p, _) = vertices.map(|&v| (v, v.dot(direction))).fold(
(P::origin(), P::Scalar::neg_infinity()),
|(max_p, max_dot), (v, dot)| {
if dot > max_dot {
(v, dot)
} else {
(max_p, max_dot)
}
},
);
transform.transform_point(p)
}
pub(crate) fn get_bound<'a, I, A: 'a>(vertices: I) -> A
where
A: Aabb,
I: Iterator<Item = &'a A::Point>,
{
vertices.fold(A::zero(), |bound, p| bound.grow(*p))
}
#[allow(dead_code)]
#[inline]
pub(crate) fn triple_product<S>(a: &Vector2<S>, b: &Vector2<S>, c: &Vector2<S>) -> Vector2<S>
where
S: BaseNum,
{
let ac = a.x * c.x + a.y * c.y;
let bc = b.x * c.x + b.y * c.y;
Vector2::new(b.x * ac - a.x * bc, b.y * ac - a.y * bc)
}
/// Compute barycentric coordinates of p in relation to the triangle defined by (a, b, c).
#[allow(dead_code)]
pub(crate) fn barycentric_vector<V>(p: V, a: V, b: V, c: V) -> (V::Scalar, V::Scalar, V::Scalar)
where
V: VectorSpace + InnerSpace,
V::Scalar: BaseFloat,
{
let v0 = b - a;
let v1 = c - a;
let v2 = p - a;
let d00 = v0.dot(v0);
let d01 = v0.dot(v1);
let d11 = v1.dot(v1);
let d20 = v2.dot(v0);
let d21 = v2.dot(v1);
let inv_denom = V::Scalar::one() / (d00 * d11 - d01 * d01);
let v = (d11 * d20 - d01 * d21) * inv_denom;
let w = (d00 * d21 - d01 * d20) * inv_denom;
let u = V::Scalar::one() - v - w;
(u, v, w)
}
/// Compute barycentric coordinates of p in relation to the triangle defined by (a, b, c).
pub(crate) fn barycentric_point<P>(p: P, a: P, b: P, c: P) -> (P::Scalar, P::Scalar, P::Scalar)
where
P: EuclideanSpace,
P::Diff: InnerSpace,
P::Scalar: BaseFloat,
{
let v0 = b - a;
let v1 = c - a;
let v2 = p - a;
let d00 = v0.dot(v0);
let d01 = v0.dot(v1);
let d11 = v1.dot(v1);
let d20 = v2.dot(v0);
let d21 = v2.dot(v1);
let inv_denom = P::Scalar::one() / (d00 * d11 - d01 * d01);
let v = (d11 * d20 - d01 * d21) * inv_denom;
let w = (d00 * d21 - d01 * d20) * inv_denom;
let u = P::Scalar::one() - v - w;
(u, v, w)
}
#[inline]
pub(crate) fn get_closest_point_on_edge<V>(start: &V, end: &V, point: &V) -> V
where
V: VectorSpace + InnerSpace + Neg<Output = V>,
V::Scalar: BaseFloat,
{
let line = *end - *start;
let line_dir = line.normalize();
let v = *point - *start;
let d = v.dot(line_dir);
if d < V::Scalar::zero() {
*start
} else if (d * d) > line.magnitude2() {
*end
} else {
*start + line_dir * d
}
}
pub(crate) fn cylinder_ray_quadratic_solve<S>(r: &Ray3<S>, radius: S) -> Option<(S, S)>
where
S: BaseFloat,
{
let two = S::one() + S::one();
let a = r.direction.x * r.direction.x + r.direction.z * r.direction.z;
let b = two * (r.direction.x * r.origin.x + r.direction.z * r.origin.z);
let c = r.origin.x * r.origin.x + r.origin.z * r.origin.z - radius * radius;
let four = two + two;
let dr = b * b - four * a * c;
if dr < S::zero() {
return None;
}
let drsqrt = dr.sqrt();
let t1 = (-b + drsqrt) / (two * a);
let t2 = (-b - drsqrt) / (two * a);
Some((t1, t2))
}
#[cfg(test)]
mod tests {
use std;
use cgmath::assert_ulps_eq;
use cgmath::{Basis2, Decomposed, Point2, Rad, Rotation2, Vector2};
use super::*;
use crate::Aabb2;
#[test]
fn test_get_bound() {
let triangle = vec![
Point2::new(-1., 1.),
Point2::new(0., -1.),
Point2::new(1., 0.),
];
assert_eq!(
Aabb2::new(Point2::new(-1., -1.), Point2::new(1., 1.)),
get_bound(triangle.iter())
);
}
fn test_max_point(dx: f32, dy: f32, px: f32, py: f32, rot_angle: f32) {
let direction = Vector2::new(dx, dy);
let point = Point2::new(px, py);
let triangle = vec![
Point2::new(-1., 1.),
Point2::new(0., -1.),
Point2::new(1., 0.),
];
let t = transform(0., 0., rot_angle);
let max_point = get_max_point(triangle.iter(), &direction, &t);
assert_ulps_eq!(point.x, max_point.x);
assert_ulps_eq!(point.y, max_point.y);
}
#[test]
fn test_max_point_1() {
test_max_point(0., 1., -1., 1., 0.);
}
#[test]
fn test_max_point_2() {
test_max_point(-1., 0., -1., 1., 0.);
}
#[test]
fn test_max_point_3() {
test_max_point(0., -1., 0., -1., 0.);
}
#[test]
fn test_max_point_4() {
test_max_point(1., 0., 1., 0., 0.);
}
#[test]
fn test_max_point_5() {
test_max_point(10., 1., 1., 0., 0.);
}
#[test]
fn test_max_point_6() {
test_max_point(2., -100., 0., -1., 0.);
}
#[test]
fn test_max_point_rot() {
test_max_point(
0.,
1.,
std::f32::consts::FRAC_1_SQRT_2,
std::f32::consts::FRAC_1_SQRT_2,
std::f32::consts::PI / 4.,
);
}
#[test]
fn test_max_point_disp() {
let direction = Vector2::new(0., 1.);
let point = Point2::new(-1., 9.);
let triangle = vec![
Point2::new(-1., 1.),
Point2::new(0., -1.),
Point2::new(1., 0.),
];
let t = transform(0., 8., 0.);
assert_eq!(point, get_max_point(triangle.iter(), &direction, &t));
}
#[test]
fn test_closest_point_2d() {
let start = Vector2::new(3., -1.);
let end = Vector2::new(-1., 3.);
let point = Vector2::zero();
let p = get_closest_point_on_edge(&start, &end, &point);
assert_ulps_eq!(Vector2::new(1_f32, 1_f32), p);
let start = Vector2::new(2., -2.);
let end = Vector2::new(2., 2.);
let p = get_closest_point_on_edge(&start, &end, &point);
assert_ulps_eq!(Vector2::new(2_f32, 0_f32), p);
let start = Vector2::new(2., 4.);
let end = Vector2::new(2., 2.);
let p = get_closest_point_on_edge(&start, &end, &point);
assert_ulps_eq!(Vector2::new(2_f32, 2_f32), p);
let start = Vector2::new(2., -2.);
let end = Vector2::new(2., -4.);
let p = get_closest_point_on_edge(&start, &end, &point);
assert_ulps_eq!(Vector2::new(2_f32, -2_f32), p);
}
fn transform(dx: f32, dy: f32, rot: f32) -> Decomposed<Vector2<f32>, Basis2<f32>> {
Decomposed {
scale: 1.,
rot: Rotation2::from_angle(Rad(rot)),
disp: Vector2::new(dx, dy),
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/polyhedron.rs | src/primitive/polyhedron.rs | use std::cmp::Ordering;
use std::collections::HashMap;
use bit_set::BitSet;
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point3, Vector3};
use crate::prelude::*;
use crate::primitive::util::barycentric_point;
use crate::volume::Sphere;
use crate::{Aabb3, Plane, Ray3};
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
enum PolyhedronMode {
VertexOnly,
HalfEdge,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
struct Vertex<S> {
position: Point3<S>,
edge: usize,
ready: bool,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
struct Edge {
target_vertex: usize,
left_face: usize,
next_edge: usize,
previous_edge: usize,
twin_edge: usize,
ready: bool,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
struct Face<S>
where
S: BaseFloat,
{
edge: usize,
vertices: (usize, usize, usize),
plane: Plane<S>,
ready: bool,
}
/// Convex polyhedron primitive.
///
/// Can contain any number of vertices, but a high number of vertices will
/// affect performance of course. It is recommended for high vertex counts, to also provide the
/// faces, this will cause the support function to use hill climbing on a half edge structure,
/// resulting in better performance. The breakpoint is around 250 vertices, but the face version is
/// only marginally slower on lower vertex counts (about 1-2%), while for higher vertex counts it's
/// about 2-5 times faster.
///
///
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct ConvexPolyhedron<S>
where
S: BaseFloat,
{
mode: PolyhedronMode,
vertices: Vec<Vertex<S>>,
edges: Vec<Edge>,
faces: Vec<Face<S>>,
bound: Aabb3<S>,
max_extent: S,
}
impl<S> ConvexPolyhedron<S>
where
S: BaseFloat,
{
/// Create a new convex polyhedron from the given vertices.
pub fn new(vertices: &[Point3<S>]) -> Self {
Self {
mode: PolyhedronMode::VertexOnly,
vertices: vertices
.iter()
.map(|&v| Vertex {
position: v,
edge: 0,
ready: true,
})
.collect(),
edges: Vec::default(),
faces: Vec::default(),
bound: vertices
.iter()
.fold(Aabb3::zero(), |bound, p| bound.grow(*p)),
max_extent: vertices
.iter()
.map(|p| p.to_vec().magnitude())
.max_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal))
.unwrap_or_else(S::zero),
}
}
/// Create a new convex polyhedron from the given vertices and faces.
pub fn new_with_faces(vertices: &[Point3<S>], faces: &[(usize, usize, usize)]) -> Self {
let (vertices, edges, faces) = build_half_edges(vertices, faces);
Self {
mode: PolyhedronMode::HalfEdge,
bound: vertices
.iter()
.fold(Aabb3::zero(), |bound, p| bound.grow(p.position)),
max_extent: vertices
.iter()
.map(|p| p.position.to_vec().magnitude())
.max_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal))
.unwrap_or_else(S::zero),
vertices,
edges,
faces,
}
}
/// Create a new convex polyhedron from the given vertices and faces. Will remove any duplicate
/// vertices.
pub fn new_with_faces_dedup(vertices: &[Point3<S>], faces: &[(usize, usize, usize)]) -> Self {
let (vertices, map) = dedup_vertices(vertices);
Self::new_with_faces(&vertices, &dedup_faces(faces, &map))
}
/// Return an iterator that will yield tuples of the 3 vertices of each face
pub fn faces_iter(&self) -> FaceIterator<'_, S> {
assert_eq!(self.mode, PolyhedronMode::HalfEdge);
FaceIterator {
polyhedron: self,
current: 0,
}
}
#[inline]
fn brute_force_support_point(&self, direction: Vector3<S>) -> Point3<S> {
let (p, _) = self
.vertices
.iter()
.map(|v| (v.position, v.position.dot(direction)))
.fold(
(Point3::origin(), S::neg_infinity()),
|(max_p, max_dot), (v, dot)| {
if dot > max_dot {
(v, dot)
} else {
(max_p, max_dot)
}
},
);
p
}
#[inline]
fn hill_climb_support_point(&self, direction: Vector3<S>) -> Point3<S> {
let mut best_index = 0;
let mut best_dot = self.vertices[best_index].position.dot(direction);
loop {
let previous_best_dot = best_dot;
let mut edge_index = self.vertices[best_index].edge;
let start_edge_index = edge_index;
loop {
let vertex_index = self.edges[edge_index].target_vertex;
let dot = self.vertices[vertex_index].position.dot(direction);
if dot > best_dot {
best_index = vertex_index;
best_dot = dot;
}
edge_index = self.edges[self.edges[edge_index].twin_edge].next_edge;
if start_edge_index == edge_index {
break;
}
}
if best_dot == previous_best_dot {
break;
}
}
self.vertices[best_index].position
}
}
/// Iterate over polyhedron faces.
/// Yields a tuple with the positions of the 3 vertices of each face
#[derive(Debug)]
pub struct FaceIterator<'a, S>
where
S: BaseFloat,
{
polyhedron: &'a ConvexPolyhedron<S>,
current: usize,
}
impl<'a, S> Iterator for FaceIterator<'a, S>
where
S: BaseFloat,
{
type Item = (&'a Point3<S>, &'a Point3<S>, &'a Point3<S>);
fn next(&mut self) -> Option<Self::Item> {
if self.current >= self.polyhedron.faces.len() {
None
} else {
self.current += 1;
let face = &self.polyhedron.faces[self.current - 1];
Some((
&self.polyhedron.vertices[face.vertices.0].position,
&self.polyhedron.vertices[face.vertices.1].position,
&self.polyhedron.vertices[face.vertices.2].position,
))
}
}
}
fn dedup_vertices<S>(vertices: &[Point3<S>]) -> (Vec<Point3<S>>, HashMap<usize, usize>)
where
S: BaseFloat,
{
let mut vs = Vec::with_capacity(vertices.len() / 2);
let mut dup = HashMap::default();
for (i, &vertex) in vertices.iter().enumerate() {
let mut found = false;
for (j, &v) in vs.iter().enumerate() {
if v == vertex {
dup.insert(i, j);
found = true;
}
}
if !found {
vs.push(vertex);
}
}
(vs, dup)
}
fn dedup_faces(
faces: &[(usize, usize, usize)],
duplicates: &HashMap<usize, usize>,
) -> Vec<(usize, usize, usize)> {
faces
.iter()
.map(|&(a, b, c)| {
(
*duplicates.get(&a).unwrap_or(&a),
*duplicates.get(&b).unwrap_or(&b),
*duplicates.get(&c).unwrap_or(&c),
)
})
.collect()
}
/// Create half edge data structure from vertices and faces
fn build_half_edges<S>(
vertices: &[Point3<S>],
in_faces: &[(usize, usize, usize)],
) -> (Vec<Vertex<S>>, Vec<Edge>, Vec<Face<S>>)
where
S: BaseFloat,
{
let mut vertices: Vec<Vertex<S>> = vertices
.iter()
.map(|&v| Vertex {
position: v,
edge: 0,
ready: false,
})
.collect();
let mut edges: Vec<Edge> = vec![];
let mut faces: Vec<Face<S>> = vec![];
let mut edge_map: HashMap<(usize, usize), usize> = HashMap::default();
for &(a, b, c) in in_faces {
let face_vertices = [a, b, c];
let mut face = Face {
edge: 0,
vertices: (a, b, c),
plane: Plane::from_points(
vertices[a].position,
vertices[b].position,
vertices[c].position,
)
.unwrap(),
ready: false,
};
let face_index = faces.len();
let mut face_edge_indices = [0, 0, 0];
for j in 0..3 {
let i = if j == 0 { 2 } else { j - 1 };
let v0 = face_vertices[i];
let v1 = face_vertices[j];
let (edge_v0_v1_index, edge_v1_v0_index) = if let Some(edge) = edge_map.get(&(v0, v1)) {
(*edge, edges[*edge].twin_edge)
} else {
let edge_v0_v1_index = edges.len();
let edge_v1_v0_index = edges.len() + 1;
edges.push(Edge {
target_vertex: v1,
left_face: 0,
next_edge: 0,
previous_edge: 0,
twin_edge: edge_v1_v0_index,
ready: false,
});
edges.push(Edge {
target_vertex: v0,
left_face: 0,
next_edge: 0,
previous_edge: 0,
twin_edge: edge_v0_v1_index,
ready: false,
});
(edge_v0_v1_index, edge_v1_v0_index)
};
edge_map.insert((v0, v1), edge_v0_v1_index);
edge_map.insert((v1, v0), edge_v1_v0_index);
if !edges[edge_v0_v1_index].ready {
edges[edge_v0_v1_index].left_face = face_index;
edges[edge_v0_v1_index].ready = true;
}
if !vertices[v0].ready {
vertices[v0].edge = edge_v0_v1_index;
vertices[v0].ready = true;
}
if !face.ready {
face.edge = edge_v0_v1_index;
face.ready = true;
}
face_edge_indices[i] = edge_v0_v1_index;
}
faces.push(face);
for j in 0..3 {
let i = if j == 0 { 2 } else { j - 1 };
let edge_i = face_edge_indices[i];
let edge_j = face_edge_indices[j];
edges[edge_i].next_edge = edge_j;
edges[edge_j].previous_edge = edge_i;
}
}
(vertices, edges, faces)
}
impl<S> Primitive for ConvexPolyhedron<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn support_point<T>(&self, direction: &Vector3<S>, transform: &T) -> Point3<S>
where
T: Transform<Point3<S>>,
{
let p = match self.mode {
PolyhedronMode::VertexOnly => self
.brute_force_support_point(transform.inverse_transform_vector(*direction).unwrap()),
PolyhedronMode::HalfEdge => self
.hill_climb_support_point(transform.inverse_transform_vector(*direction).unwrap()),
};
transform.transform_point(p)
}
}
impl<S> ComputeBound<Aabb3<S>> for ConvexPolyhedron<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb3<S> {
self.bound
}
}
impl<S> ComputeBound<Sphere<S>> for ConvexPolyhedron<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Sphere<S> {
Sphere {
center: Point3::origin(),
radius: self.max_extent,
}
}
}
/// TODO: better algorithm for finding faces to intersect with?
impl<S> Discrete<Ray3<S>> for ConvexPolyhedron<S>
where
S: BaseFloat,
{
/// Ray must be in object space
fn intersects(&self, ray: &Ray3<S>) -> bool {
find_intersecting_face(self, ray).is_some()
}
}
impl<S> Continuous<Ray3<S>> for ConvexPolyhedron<S>
where
S: BaseFloat,
{
type Result = Point3<S>;
/// Ray must be in object space
fn intersection(&self, ray: &Ray3<S>) -> Option<Point3<S>> {
find_intersecting_face(self, ray).map(|(face_index, (u, v, w))| {
let f = &self.faces[face_index];
let v0 = f.vertices.0;
let v1 = f.vertices.1;
let v2 = f.vertices.2;
(self.vertices[v0].position * u)
+ (self.vertices[v1].position.to_vec() * v)
+ (self.vertices[v2].position.to_vec() * w)
})
}
}
// TODO: better algorithm for finding faces to intersect with?
// Current algorithm walks in the direction of the plane/ray intersection point for the current
// tested face, assuming the intersection point isn't on the actual face.
// It uses barycentric coordinates to find out where to walk next.
#[inline]
fn find_intersecting_face<S>(
polytope: &ConvexPolyhedron<S>,
ray: &Ray3<S>,
) -> Option<(usize, (S, S, S))>
where
S: BaseFloat,
{
let mut face = Some(0);
let mut checked = BitSet::with_capacity(polytope.faces.len());
while face.is_some() {
let face_index = face.unwrap();
checked.insert(face_index);
let uvw = match intersect_ray_face(ray, polytope, &polytope.faces[face_index]) {
Some((u, v, w)) => {
if in_range(u) && in_range(v) && in_range(w) {
return Some((face_index, (u, v, w)));
}
Some((u, v, w))
}
_ => None,
};
face = next_face_classify(polytope, face_index, uvw, &mut checked);
}
None
}
#[inline]
fn in_range<S>(v: S) -> bool
where
S: BaseFloat,
{
v >= S::zero() && v <= S::one()
}
#[inline]
fn next_face_classify<S>(
polytope: &ConvexPolyhedron<S>,
face_index: usize,
bary_coords: Option<(S, S, S)>,
checked: &mut BitSet,
) -> Option<usize>
where
S: BaseFloat,
{
if polytope.faces.len() < 10 {
if face_index == polytope.faces.len() - 1 {
None
} else {
Some(face_index + 1)
}
} else {
match bary_coords {
None => {
let mut next = face_index + 1;
while next < polytope.faces.len() && checked.contains(next) {
next += 1;
}
if next == polytope.faces.len() {
None
} else {
Some(next)
}
}
Some((u, v, _)) => {
let face = &polytope.faces[face_index];
let target_vertex_index = if u < S::zero() {
face.vertices.2
} else if v < S::zero() {
face.vertices.0
} else {
face.vertices.1
};
let face_edge = &polytope.edges[face.edge];
let edges = if face_edge.target_vertex == target_vertex_index {
[face.edge, face_edge.next_edge, face_edge.previous_edge]
} else if polytope.edges[face_edge.previous_edge].target_vertex
== target_vertex_index
{
[face_edge.previous_edge, face.edge, face_edge.next_edge]
} else {
[face_edge.next_edge, face_edge.previous_edge, face.edge]
};
for edge_index in &edges {
let twin_edge = polytope.edges[*edge_index].twin_edge;
if !checked.contains(polytope.edges[twin_edge].left_face) {
return Some(polytope.edges[twin_edge].left_face);
}
}
for i in 0..polytope.faces.len() {
if !checked.contains(i) {
return Some(i);
}
}
None
}
}
}
}
/// Compute intersection point of ray and face in barycentric coordinates.
#[inline]
fn intersect_ray_face<S>(
ray: &Ray3<S>,
polytope: &ConvexPolyhedron<S>,
face: &Face<S>,
) -> Option<(S, S, S)>
where
S: BaseFloat,
{
let n_dir = face.plane.n.dot(ray.direction);
if n_dir < S::zero() {
let v0 = face.vertices.0;
let v1 = face.vertices.1;
let v2 = face.vertices.2;
face.plane.intersection(ray).map(|p| {
barycentric_point(
p,
polytope.vertices[v0].position,
polytope.vertices[v1].position,
polytope.vertices[v2].position,
)
})
} else {
None
}
}
#[cfg(test)]
mod tests {
use cgmath::assert_ulps_eq;
use cgmath::prelude::*;
use cgmath::{Decomposed, Point3, Quaternion, Rad, Vector3};
use super::ConvexPolyhedron;
use crate::prelude::*;
use crate::{Aabb3, Ray3};
#[test]
fn test_polytope_half_edge() {
let vertices = vec![
Point3::<f32>::new(1., 0., 0.),
Point3::<f32>::new(0., 1., 0.),
Point3::<f32>::new(0., 0., 1.),
Point3::<f32>::new(0., 0., 0.),
];
let faces = vec![(1, 3, 2), (3, 1, 0), (2, 0, 1), (0, 2, 3)];
let polytope_with_faces = ConvexPolyhedron::new_with_faces(&vertices, &faces);
let polytope = ConvexPolyhedron::new(&vertices);
let t = transform(0., 0., 0., 0.);
let direction = Vector3::new(1., 0., 0.);
assert_eq!(
Point3::new(1., 0., 0.),
polytope.support_point(&direction, &t)
);
assert_eq!(
Point3::new(1., 0., 0.),
polytope_with_faces.support_point(&direction, &t)
);
let direction = Vector3::new(0., 1., 0.);
assert_eq!(
Point3::new(0., 1., 0.),
polytope.support_point(&direction, &t)
);
assert_eq!(
Point3::new(0., 1., 0.),
polytope_with_faces.support_point(&direction, &t)
);
}
#[test]
fn test_polytope_bound() {
let vertices = vec![
Point3::<f32>::new(1., 0., 0.),
Point3::<f32>::new(0., 1., 0.),
Point3::<f32>::new(0., 0., 1.),
Point3::<f32>::new(0., 0., 0.),
];
let faces = vec![(1, 3, 2), (3, 1, 0), (2, 0, 1), (0, 2, 3)];
let polytope = ConvexPolyhedron::new_with_faces(&vertices, &faces);
assert_eq!(
Aabb3::new(Point3::new(0., 0., 0.), Point3::new(1., 1., 1.)),
polytope.compute_bound()
);
}
#[test]
fn test_ray_discrete() {
let vertices = vec![
Point3::<f32>::new(1., 0., 0.),
Point3::<f32>::new(0., 1., 0.),
Point3::<f32>::new(0., 0., 1.),
Point3::<f32>::new(0., 0., 0.),
];
let faces = vec![(1, 3, 2), (3, 1, 0), (2, 0, 1), (0, 2, 3)];
let polytope = ConvexPolyhedron::new_with_faces(&vertices, &faces);
let ray = Ray3::new(Point3::new(0.25, 5., 0.25), Vector3::new(0., -1., 0.));
assert!(polytope.intersects(&ray));
let ray = Ray3::new(Point3::new(0.5, 5., 0.5), Vector3::new(0., 1., 0.));
assert!(!polytope.intersects(&ray));
}
#[test]
fn test_ray_discrete_transformed() {
let vertices = vec![
Point3::<f32>::new(1., 0., 0.),
Point3::<f32>::new(0., 1., 0.),
Point3::<f32>::new(0., 0., 1.),
Point3::<f32>::new(0., 0., 0.),
];
let faces = vec![(1, 3, 2), (3, 1, 0), (2, 0, 1), (0, 2, 3)];
let polytope = ConvexPolyhedron::new_with_faces(&vertices, &faces);
let t = transform(0., 0., 0., 0.);
let ray = Ray3::new(Point3::new(0.25, 5., 0.25), Vector3::new(0., -1., 0.));
assert!(polytope.intersects_transformed(&ray, &t));
let ray = Ray3::new(Point3::new(0.5, 5., 0.5), Vector3::new(0., 1., 0.));
assert!(!polytope.intersects_transformed(&ray, &t));
let t = transform(0., 1., 0., 0.);
let ray = Ray3::new(Point3::new(0.25, 5., 0.25), Vector3::new(0., -1., 0.));
assert!(polytope.intersects_transformed(&ray, &t));
let t = transform(0., 0., 0., 0.3);
assert!(polytope.intersects_transformed(&ray, &t));
}
#[test]
fn test_ray_continuous() {
let vertices = vec![
Point3::<f32>::new(1., 0., 0.),
Point3::<f32>::new(0., 1., 0.),
Point3::<f32>::new(0., 0., 1.),
Point3::<f32>::new(0., 0., 0.),
];
let faces = vec![(1, 3, 2), (3, 1, 0), (2, 0, 1), (0, 2, 3)];
let polytope = ConvexPolyhedron::new_with_faces(&vertices, &faces);
let ray = Ray3::new(Point3::new(0.25, 5., 0.25), Vector3::new(0., -1., 0.));
let p = polytope.intersection(&ray).unwrap();
assert_ulps_eq!(0.250_000_18, p.x);
assert_ulps_eq!(0.499_999_7, p.y);
assert_ulps_eq!(0.250_000_18, p.z);
let ray = Ray3::new(Point3::new(0.5, 5., 0.5), Vector3::new(0., 1., 0.));
assert_eq!(None, polytope.intersection(&ray));
let ray = Ray3::new(Point3::new(0., 5., 0.), Vector3::new(0., -1., 0.));
assert_eq!(Some(Point3::new(0., 1., 0.)), polytope.intersection(&ray));
}
#[test]
fn test_ray_continuous_transformed() {
let vertices = vec![
Point3::<f32>::new(1., 0., 0.),
Point3::<f32>::new(0., 1., 0.),
Point3::<f32>::new(0., 0., 1.),
Point3::<f32>::new(0., 0., 0.),
];
let faces = vec![(1, 3, 2), (3, 1, 0), (2, 0, 1), (0, 2, 3)];
let polytope = ConvexPolyhedron::new_with_faces(&vertices, &faces);
let t = transform(0., 0., 0., 0.);
let ray = Ray3::new(Point3::new(0.25, 5., 0.25), Vector3::new(0., -1., 0.));
let p = polytope.intersection_transformed(&ray, &t).unwrap();
assert_ulps_eq!(0.250_000_18, p.x);
assert_ulps_eq!(0.499_999_7, p.y);
assert_ulps_eq!(0.250_000_18, p.z);
let ray = Ray3::new(Point3::new(0.5, 5., 0.5), Vector3::new(0., 1., 0.));
assert_eq!(None, polytope.intersection_transformed(&ray, &t));
let t = transform(0., 1., 0., 0.);
let ray = Ray3::new(Point3::new(0.25, 5., 0.25), Vector3::new(0., -1., 0.));
let p = polytope.intersection_transformed(&ray, &t).unwrap();
assert_ulps_eq!(0.250_000_18, p.x);
assert_ulps_eq!(1.499_999_7, p.y);
assert_ulps_eq!(0.250_000_18, p.z);
let t = transform(0., 0., 0., 0.3);
let p = polytope.intersection_transformed(&ray, &t).unwrap();
assert_ulps_eq!(0.25, p.x);
assert_ulps_eq!(0.467_716_2, p.y);
assert_ulps_eq!(0.25, p.z);
}
#[test]
fn test_intersect_face() {
let vertices = vec![
Point3::<f32>::new(1., 0., 0.),
Point3::<f32>::new(0., 1., 0.),
Point3::<f32>::new(0., 0., 1.),
Point3::<f32>::new(0., 0., 0.),
];
let faces = vec![(1, 3, 2), (3, 1, 0), (2, 0, 1), (0, 2, 3)];
let polytope = ConvexPolyhedron::new_with_faces(&vertices, &faces);
let ray = Ray3::new(Point3::new(1., -1., 1.), Vector3::new(0., 1., 0.));
polytope.intersection(&ray);
}
fn transform(dx: f32, dy: f32, dz: f32, rot: f32) -> Decomposed<Vector3<f32>, Quaternion<f32>> {
Decomposed {
scale: 1.,
rot: Quaternion::from_angle_z(Rad(rot)),
disp: Vector3::new(dx, dy, dz),
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/circle.rs | src/primitive/circle.rs | //! Circle primitive
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point2, Vector2};
use crate::prelude::*;
use crate::{Aabb2, Ray2};
/// Circle primitive
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Circle<S> {
/// Radius of the circle
pub radius: S,
}
impl<S> Circle<S> {
/// Create a new circle primitive
pub fn new(radius: S) -> Self {
Self { radius }
}
}
impl<S> Primitive for Circle<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
fn support_point<T>(&self, direction: &Vector2<S>, transform: &T) -> Point2<S>
where
T: Transform<Point2<S>>,
{
let direction = transform.inverse_transform_vector(*direction).unwrap();
transform.transform_point(Point2::from_vec(direction.normalize_to(self.radius)))
}
}
impl<S> ComputeBound<Aabb2<S>> for Circle<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb2<S> {
Aabb2::new(
Point2::new(-self.radius, -self.radius),
Point2::new(self.radius, self.radius),
)
}
}
impl<S> Discrete<Ray2<S>> for Circle<S>
where
S: BaseFloat,
{
fn intersects(&self, r: &Ray2<S>) -> bool {
let s = self;
let l = Vector2::new(-r.origin.x, -r.origin.y);
let tca = l.dot(r.direction);
if tca < S::zero() {
return false;
}
let d2 = l.dot(l) - tca * tca;
d2 <= s.radius * s.radius
}
}
impl<S> Continuous<Ray2<S>> for Circle<S>
where
S: BaseFloat,
{
type Result = Point2<S>;
fn intersection(&self, r: &Ray2<S>) -> Option<Point2<S>> {
let s = self;
let l = Vector2::new(-r.origin.x, -r.origin.y);
let tca = l.dot(r.direction);
if tca < S::zero() {
return None;
}
let d2 = l.dot(l) - tca * tca;
if d2 > s.radius * s.radius {
return None;
}
let thc = (s.radius * s.radius - d2).sqrt();
Some(r.origin + r.direction * (tca - thc))
}
}
#[cfg(test)]
mod tests {
use std;
use crate::prelude::*;
use crate::Ray2;
use cgmath::assert_ulps_eq;
use cgmath::{Basis2, Decomposed, Point2, Rad, Rotation2, Vector2};
use super::*;
// circle
#[test]
fn test_circle_far_1() {
test_circle(1., 0., 10., 0., 0.);
}
#[test]
fn test_circle_far_2() {
test_circle(1., 1., 7.071_067_7, 7.071_067_7, 0.);
}
#[test]
fn test_circle_far_3() {
test_circle(1., 0., 10., 0., -std::f32::consts::PI / 4.);
}
#[test]
fn test_circle_far_4() {
let circle = Circle::new(10.);
let direction = Vector2::new(1., 0.);
let transform = transform(0., 10., 0.);
let point = circle.support_point(&direction, &transform);
assert_eq!(Point2::new(10., 10.), point);
}
#[test]
fn test_circle_bound() {
let circle = Circle::new(10.);
assert_eq!(bound(-10., -10., 10., 10.), circle.compute_bound());
}
#[test]
fn test_circle_ray_discrete() {
let circle = Circle::new(10.);
let ray = Ray2::new(Point2::new(25., 0.), Vector2::new(-1., 0.));
assert!(circle.intersects(&ray));
let ray = Ray2::new(Point2::new(25., -11.), Vector2::new(-1., 0.));
assert!(!circle.intersects(&ray));
}
#[test]
fn test_circle_ray_discrete_transformed() {
let circle = Circle::new(10.);
let ray = Ray2::new(Point2::new(25., 0.), Vector2::new(-1., 0.));
let t = transform(0., 0., 0.);
assert!(circle.intersects_transformed(&ray, &t));
let t = transform(0., 11., 0.);
assert!(!circle.intersects_transformed(&ray, &t));
}
#[test]
fn test_circle_ray_continuous() {
let circle = Circle::new(10.);
let ray = Ray2::new(Point2::new(25., 0.), Vector2::new(-1., 0.));
assert_eq!(Some(Point2::new(10., 0.)), circle.intersection(&ray));
let ray = Ray2::new(Point2::new(25., -11.), Vector2::new(-1., 0.));
assert_eq!(None, circle.intersection(&ray));
}
#[test]
fn test_circle_ray_continuous_transformed() {
let circle = Circle::new(10.);
let ray = Ray2::new(Point2::new(25., 0.), Vector2::new(-1., 0.));
let t = transform(0., 0., 0.);
assert_eq!(
Some(Point2::new(10., 0.)),
circle.intersection_transformed(&ray, &t)
);
let t = transform(0., 11., 0.);
assert_eq!(None, circle.intersection_transformed(&ray, &t));
}
fn test_circle(dx: f32, dy: f32, px: f32, py: f32, rot: f32) {
let circle = Circle::new(10.);
let direction = Vector2::new(dx, dy);
let transform = transform(0., 0., rot);
let point = circle.support_point(&direction, &transform);
assert_ulps_eq!(px, point.x);
assert_ulps_eq!(py, point.y);
}
// util
fn transform(dx: f32, dy: f32, rot: f32) -> Decomposed<Vector2<f32>, Basis2<f32>> {
Decomposed {
scale: 1.,
rot: Rotation2::from_angle(Rad(rot)),
disp: Vector2::new(dx, dy),
}
}
fn bound(min_x: f32, min_y: f32, max_x: f32, max_y: f32) -> Aabb2<f32> {
Aabb2::new(Point2::new(min_x, min_y), Point2::new(max_x, max_y))
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/cylinder.rs | src/primitive/cylinder.rs | use cgmath::prelude::*;
use cgmath::{BaseFloat, Point3, Vector3};
use crate::prelude::*;
use crate::primitive::util::cylinder_ray_quadratic_solve;
use crate::volume::Sphere;
use crate::{Aabb3, Ray3};
/// Cylinder primitive
/// Cylinder body is aligned with the Y axis, with local origin in the center of the cylinders.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Cylinder<S> {
half_height: S,
radius: S,
}
impl<S> Cylinder<S>
where
S: BaseFloat,
{
/// Create a new cylinder
pub fn new(half_height: S, radius: S) -> Self {
Self {
half_height,
radius,
}
}
/// Get radius
pub fn radius(&self) -> S {
self.radius
}
/// Get height
pub fn height(&self) -> S {
self.half_height + self.half_height
}
}
impl<S> Primitive for Cylinder<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn support_point<T>(&self, direction: &Vector3<S>, transform: &T) -> Point3<S>
where
T: Transform<Point3<S>>,
{
let direction = transform.inverse_transform_vector(*direction).unwrap();
let mut result = direction;
let negative = result.y.is_sign_negative();
result.y = S::zero();
if result.magnitude2().is_zero() {
result = Zero::zero();
} else {
result = result.normalize();
if result.is_zero() {
result = Zero::zero(); // cancel out any inconsistencies
} else {
result *= self.radius;
}
}
if negative {
result.y = -self.half_height;
} else {
result.y = self.half_height;
}
transform.transform_point(Point3::from_vec(result))
}
}
impl<S> ComputeBound<Aabb3<S>> for Cylinder<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb3<S> {
Aabb3::new(
Point3::new(-self.radius, -self.half_height, -self.radius),
Point3::new(self.radius, self.half_height, self.radius),
)
}
}
impl<S> ComputeBound<Sphere<S>> for Cylinder<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Sphere<S> {
Sphere {
center: Point3::origin(),
radius: ((self.radius * self.radius) + (self.half_height * self.half_height)).sqrt(),
}
}
}
impl<S> Discrete<Ray3<S>> for Cylinder<S>
where
S: BaseFloat,
{
fn intersects(&self, r: &Ray3<S>) -> bool {
if r.direction.x.is_zero() && r.direction.z.is_zero() {
if r.direction.y.is_zero() {
return false;
}
return (r.origin.y >= -self.half_height && r.direction.y <= S::zero())
|| (r.origin.y <= self.half_height && r.direction.y >= S::zero());
}
let (t1, t2) = match cylinder_ray_quadratic_solve(r, self.radius) {
None => return false,
Some(t) => t,
};
if t1 < S::zero() && t2 < S::zero() {
return false;
}
let t = if t1 < S::zero() {
t2
} else if t2 < S::zero() {
t1
} else {
t1.min(t2)
};
let pc = r.origin + r.direction * t;
if pc.y <= self.half_height && pc.y >= -self.half_height {
return true;
}
let n = -Vector3::unit_y();
let tp = -(self.half_height + r.origin.dot(n)) / r.direction.dot(n);
if tp >= S::zero() {
let p = r.origin + r.direction * tp;
if p.x * p.x + p.z * p.z < self.radius * self.radius {
return true;
}
}
let n = Vector3::unit_y();
let tb = -(-self.half_height + r.origin.dot(n)) / r.direction.dot(n);
if tb >= S::zero() {
let p = r.origin + r.direction * tb;
if p.x * p.x + p.z * p.z < self.radius * self.radius {
return true;
}
}
false
}
}
impl<S> Continuous<Ray3<S>> for Cylinder<S>
where
S: BaseFloat,
{
type Result = Point3<S>;
fn intersection(&self, r: &Ray3<S>) -> Option<Point3<S>> {
if r.direction.x.is_zero() && r.direction.z.is_zero() {
if r.direction.y.is_zero() {
return None;
}
if r.origin.y >= self.half_height && r.direction.y < S::zero() {
return Some(Point3::new(S::zero(), self.half_height, S::zero()));
}
if r.origin.y >= -self.half_height && r.direction.y < S::zero() {
return Some(Point3::new(S::zero(), -self.half_height, S::zero()));
}
if r.origin.y <= -self.half_height && r.direction.y > S::zero() {
return Some(Point3::new(S::zero(), -self.half_height, S::zero()));
}
if r.origin.y <= self.half_height && r.direction.y > S::zero() {
return Some(Point3::new(S::zero(), self.half_height, S::zero()));
}
return None;
}
let (t1, t2) = match cylinder_ray_quadratic_solve(r, self.radius) {
None => return None,
Some(t) => t,
};
if t1 < S::zero() && t2 < S::zero() {
return None;
}
let mut t = if t1 < S::zero() {
t2
} else if t2 < S::zero() {
t1
} else {
t1.min(t2)
};
let n = -Vector3::unit_y();
let tp = -(self.half_height + r.origin.dot(n)) / r.direction.dot(n);
if tp >= S::zero() && tp < t {
let p = r.origin + r.direction * tp;
if p.x * p.x + p.z * p.z < self.radius * self.radius {
t = tp;
}
}
let n = Vector3::unit_y();
let tb = -(-self.half_height + r.origin.dot(n)) / r.direction.dot(n);
if tb >= S::zero() && tb < t {
let p = r.origin + r.direction * tb;
if p.x * p.x + p.z * p.z < self.radius * self.radius {
t = tb;
}
}
let pc = r.origin + r.direction * t;
if (pc.y > self.half_height) || (pc.y < -self.half_height) {
None
} else {
Some(pc)
}
}
}
#[cfg(test)]
mod tests {
use std;
use cgmath::assert_ulps_eq;
use cgmath::{Decomposed, Quaternion, Rad, Vector3};
use super::*;
#[test]
fn test_cylinder_aabb() {
let cylinder = Cylinder::new(2., 1.);
assert_eq!(
Aabb3::new(Point3::new(-1., -2., -1.), Point3::new(1., 2., 1.)),
cylinder.compute_bound()
);
}
#[test]
fn test_cylinder_support_1() {
let cylinder = Cylinder::new(2., 1.);
let direction = Vector3::new(1., 0., 0.);
let transform = transform(0., 0., 0., 0.);
let point = cylinder.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(1., 2., 0.), point);
}
#[test]
fn test_cylinder_support_2() {
let cylinder = Cylinder::new(2., 1.);
let direction = Vector3::new(0.5, -1., 0.).normalize();
let transform = transform(0., 0., 0., 0.);
let point = cylinder.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(1., -2., 0.), point);
}
#[test]
fn test_cylinder_support_3() {
let cylinder = Cylinder::new(2., 1.);
let direction = Vector3::new(0., 1., 0.);
let transform = transform(0., 0., 0., 0.);
let point = cylinder.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(0., 2., 0.), point);
}
#[test]
fn test_cylinder_support_4() {
let cylinder = Cylinder::new(2., 1.);
let direction = Vector3::new(1., 0., 0.);
let transform = transform(10., 0., 0., 0.);
let point = cylinder.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(11., 2., 0.), point);
}
#[test]
fn test_cylinder_support_5() {
let cylinder = Cylinder::new(2., 1.);
let direction = Vector3::new(1., 0., 0.);
let transform = transform(0., 0., 0., std::f32::consts::PI);
let point = cylinder.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(1., -2., 0.), point);
}
#[test]
fn test_discrete_1() {
let cylinder = Cylinder::new(2., 1.);
let ray = Ray3::new(Point3::new(-3., 0., 0.), Vector3::new(1., 0., 0.));
assert!(cylinder.intersects(&ray));
}
#[test]
fn test_discrete_2() {
let cylinder = Cylinder::new(2., 1.);
let ray = Ray3::new(Point3::new(-3., 0., 0.), Vector3::new(-1., 0., 0.));
assert!(!cylinder.intersects(&ray));
}
#[test]
fn test_discrete_3() {
let cylinder = Cylinder::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 3., 0.),
Vector3::new(0.1, -1., 0.1).normalize(),
);
assert!(cylinder.intersects(&ray));
}
#[test]
fn test_discrete_4() {
let cylinder = Cylinder::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 3., 0.),
Vector3::new(0.1, 1., 0.1).normalize(),
);
assert!(!cylinder.intersects(&ray));
}
#[test]
fn test_continuous_1() {
let cylinder = Cylinder::new(2., 1.);
let ray = Ray3::new(Point3::new(-3., 0., 0.), Vector3::new(1., 0., 0.));
assert_eq!(Some(Point3::new(-1., 0., 0.)), cylinder.intersection(&ray));
}
#[test]
fn test_continuous_2() {
let cylinder = Cylinder::new(2., 1.);
let ray = Ray3::new(Point3::new(-3., 0., 0.), Vector3::new(-1., 0., 0.));
assert_eq!(None, cylinder.intersection(&ray));
}
#[test]
fn test_continuous_3() {
let cylinder = Cylinder::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 3., 0.),
Vector3::new(0.1, -1., 0.1).normalize(),
);
assert_eq!(Some(Point3::new(0.1, 2., 0.1)), cylinder.intersection(&ray));
}
#[test]
fn test_continuous_4() {
let cylinder = Cylinder::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 3., 0.),
Vector3::new(0.1, 1., 0.1).normalize(),
);
assert_eq!(None, cylinder.intersection(&ray));
}
#[test]
fn test_continuous_5() {
let cylinder = Cylinder::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 3., 0.),
Vector3::new(0., -1., 0.).normalize(),
);
assert_eq!(Some(Point3::new(0., 2., 0.)), cylinder.intersection(&ray));
}
// util
fn transform(dx: f32, dy: f32, dz: f32, rot: f32) -> Decomposed<Vector3<f32>, Quaternion<f32>> {
Decomposed {
scale: 1.,
rot: Quaternion::from_angle_z(Rad(rot)),
disp: Vector3::new(dx, dy, dz),
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/mod.rs | src/primitive/mod.rs | //! Collision primitives
pub use self::capsule::Capsule;
pub use self::circle::Circle;
pub use self::cuboid::{Cube, Cuboid};
pub use self::cylinder::Cylinder;
pub use self::particle::*;
pub use self::polygon::ConvexPolygon;
pub use self::polyhedron::ConvexPolyhedron;
pub use self::primitive2::Primitive2;
pub use self::primitive3::Primitive3;
pub use self::quad::Quad;
pub use self::rectangle::{Rectangle, Square};
pub use self::sphere::Sphere;
mod capsule;
mod circle;
mod cuboid;
mod cylinder;
mod line;
mod particle;
mod polygon;
mod polyhedron;
mod primitive2;
mod primitive3;
mod quad;
mod rectangle;
mod sphere;
pub(crate) mod util;
use cgmath::{EuclideanSpace, Transform};
use crate::prelude::*;
impl<B, P> HasBound for (P, B)
where
P: Primitive,
B: Bound,
{
type Bound = B;
fn bound(&self) -> &Self::Bound {
&self.1
}
}
impl<B, P> Primitive for (P, B)
where
P: Primitive,
B: Bound,
{
type Point = P::Point;
fn support_point<T>(
&self,
direction: &<Self::Point as EuclideanSpace>::Diff,
transform: &T,
) -> Self::Point
where
T: Transform<Self::Point>,
{
self.0.support_point(direction, transform)
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/quad.rs | src/primitive/quad.rs | //! Rectangular plane primitive
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point3, Vector2, Vector3};
use crate::prelude::*;
use crate::primitive::util::get_max_point;
use crate::{Aabb3, Ray3, Sphere};
/// Rectangular plane primitive. Will lie on the xy plane when not transformed.
///
/// Have a cached set of corner points to speed up computation.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Quad<S> {
/// Dimensions of the rectangle
dim: Vector2<S>,
half_dim: Vector2<S>,
corners: [Point3<S>; 4],
}
impl<S> Quad<S>
where
S: BaseFloat,
{
/// Create a new rectangle primitive from component dimensions
pub fn new(dim_x: S, dim_y: S) -> Self {
Self::new_impl(Vector2::new(dim_x, dim_y))
}
/// Create a new rectangle primitive from a vector of component dimensions
pub fn new_impl(dim: Vector2<S>) -> Self {
let half_dim = dim / (S::one() + S::one());
Quad {
dim,
half_dim,
corners: Self::generate_corners(&half_dim),
}
}
/// Get the dimensions of the `Rectangle`
pub fn dim(&self) -> &Vector2<S> {
&self.dim
}
/// Get the half dimensions of the `Rectangle`
pub fn half_dim(&self) -> &Vector2<S> {
&self.half_dim
}
fn generate_corners(half_dim: &Vector2<S>) -> [Point3<S>; 4] {
[
Point3::new(half_dim.x, half_dim.y, S::zero()),
Point3::new(-half_dim.x, half_dim.y, S::zero()),
Point3::new(-half_dim.x, -half_dim.y, S::zero()),
Point3::new(half_dim.x, -half_dim.y, S::zero()),
]
}
}
impl<S> Primitive for Quad<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn support_point<T>(&self, direction: &Vector3<S>, transform: &T) -> Point3<S>
where
T: Transform<Point3<S>>,
{
get_max_point(self.corners.iter(), direction, transform)
}
}
impl<S> ComputeBound<Aabb3<S>> for Quad<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb3<S> {
Aabb3::new(
Point3::new(-self.half_dim.x, -self.half_dim.y, S::zero()),
Point3::new(self.half_dim.x, self.half_dim.y, S::zero()),
)
}
}
impl<S> ComputeBound<Sphere<S>> for Quad<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Sphere<S> {
Sphere {
center: Point3::origin(),
radius: self.half_dim.x.max(self.half_dim.y),
}
}
}
impl<S> Discrete<Ray3<S>> for Quad<S>
where
S: BaseFloat,
{
/// Ray must be in object space of the rectangle
fn intersects(&self, ray: &Ray3<S>) -> bool {
let aabb: Aabb3<S> = self.compute_bound();
aabb.intersects(ray)
}
}
impl<S> Continuous<Ray3<S>> for Quad<S>
where
S: BaseFloat,
{
type Result = Point3<S>;
/// Ray must be in object space of the rectangle
fn intersection(&self, ray: &Ray3<S>) -> Option<Point3<S>> {
let aabb: Aabb3<S> = self.compute_bound();
aabb.intersection(ray)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::algorithm::minkowski::GJK3;
use crate::primitive::Cuboid;
use cgmath::{Decomposed, Quaternion};
fn transform(x: f32, y: f32, z: f32) -> Decomposed<Vector3<f32>, Quaternion<f32>> {
Decomposed {
disp: Vector3::new(x, y, z),
rot: Quaternion::one(),
scale: 1.,
}
}
#[test]
fn test_plane_cuboid_intersect() {
let quad = Quad::new(2., 2.);
let cuboid = Cuboid::new(1., 1., 1.);
let transform_1 = transform(0., 0., 1.);
let transform_2 = transform(0., 0., 1.1);
let gjk = GJK3::new();
assert!(gjk
.intersect(&quad, &transform_1, &cuboid, &transform_2)
.is_some());
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/particle.rs | src/primitive/particle.rs | //! Particle primitive
use std::marker;
use std::ops::Range;
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point2, Point3};
use crate::prelude::*;
use crate::Ray;
/// Represents a particle in space.
///
/// Only have implementations of intersection tests for movement,
/// using `(Particle, Range<P>)` where `P` is the positional `Point` of the particle at the start
/// and end of movement.
/// These intersection tests can be used with any primitive that has `Ray` intersection tests
/// implemented.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Particle<P> {
m: marker::PhantomData<P>,
}
impl<P> Particle<P> {
/// Create a new particle
pub fn new() -> Self {
Self {
m: marker::PhantomData,
}
}
}
/// 2D particle
pub type Particle2<S> = Particle<Point2<S>>;
/// 3D particle
pub type Particle3<S> = Particle<Point3<S>>;
impl<P, C> Discrete<(Particle<P>, Range<P>)> for C
where
C: Continuous<Ray<P::Scalar, P, P::Diff>, Result = P>,
P: EuclideanSpace,
P::Diff: InnerSpace,
P::Scalar: BaseFloat,
{
fn intersects(&self, &(_, ref range): &(Particle<P>, Range<P>)) -> bool {
let direction = range.end - range.start;
let ray = Ray::new(range.start, direction.normalize());
match self.intersection(&ray) {
None => false,
Some(p) => (p - range.start).magnitude2() <= direction.magnitude2(),
}
}
}
impl<P> Discrete<Ray<P::Scalar, P, P::Diff>> for Particle<P>
where
P: EuclideanSpace,
P::Diff: InnerSpace,
P::Scalar: BaseFloat,
{
/// Ray needs to be in particle object space
fn intersects(&self, ray: &Ray<P::Scalar, P, P::Diff>) -> bool {
P::origin().intersects(ray)
}
}
impl<P> Continuous<Ray<P::Scalar, P, P::Diff>> for Particle<P>
where
P: EuclideanSpace,
P::Diff: InnerSpace,
P::Scalar: BaseFloat,
{
type Result = P;
/// Ray needs to be in particle object space
fn intersection(&self, ray: &Ray<P::Scalar, P, P::Diff>) -> Option<P> {
P::origin().intersection(ray)
}
}
impl<P, C> DiscreteTransformed<(Particle<P>, Range<P>)> for C
where
C: ContinuousTransformed<Ray<P::Scalar, P, P::Diff>, Result = P, Point = P>,
P: EuclideanSpace,
P::Diff: InnerSpace,
P::Scalar: BaseFloat,
{
type Point = P;
fn intersects_transformed<T>(
&self,
&(_, ref range): &(Particle<P>, Range<P>),
transform: &T,
) -> bool
where
T: Transform<P>,
{
let direction = range.end - range.start;
let ray = Ray::new(range.start, direction.normalize());
match self.intersection_transformed(&ray, transform) {
None => false,
Some(p) => (p - range.start).magnitude2() <= direction.magnitude2(),
}
}
}
impl<P, C> Continuous<(Particle<P>, Range<P>)> for C
where
C: Continuous<Ray<P::Scalar, P, P::Diff>, Result = P>,
P: EuclideanSpace,
P::Diff: InnerSpace,
P::Scalar: BaseFloat,
{
type Result = P;
fn intersection(&self, &(_, ref range): &(Particle<P>, Range<P>)) -> Option<P> {
let direction = range.end - range.start;
let ray = Ray::new(range.start, direction.normalize());
self.intersection(&ray).and_then(|p| {
if (p - range.start).magnitude2() <= direction.magnitude2() {
Some(p)
} else {
None
}
})
}
}
impl<P, C> ContinuousTransformed<(Particle<P>, Range<P>)> for C
where
C: ContinuousTransformed<Ray<P::Scalar, P, P::Diff>, Result = P, Point = P>,
P: EuclideanSpace,
P::Diff: InnerSpace,
P::Scalar: BaseFloat,
{
type Point = P;
type Result = P;
fn intersection_transformed<T>(
&self,
&(_, ref range): &(Particle<P>, Range<P>),
transform: &T,
) -> Option<P>
where
T: Transform<P>,
{
let direction = range.end - range.start;
let ray = Ray::new(range.start, direction.normalize());
self.intersection_transformed(&ray, transform)
.and_then(|p| {
if (p - range.start).magnitude2() <= direction.magnitude2() {
Some(p)
} else {
None
}
})
}
}
#[cfg(test)]
mod tests {
use cgmath::assert_ulps_eq;
use cgmath::prelude::*;
use cgmath::{Basis2, Decomposed, Point2, Rad, Vector2};
use super::*;
use crate::primitive::Circle;
#[test]
fn test_discrete() {
let circle = Circle::new(4.);
assert!(circle.intersects(&(Particle::new(), Point2::new(-5., -5.)..Point2::new(5., 5.))));
assert!(!circle.intersects(&(
Particle::new(),
Point2::new(-5., -5.)..Point2::new(-8., -8.)
)));
}
#[test]
fn test_discrete_transformed() {
let circle = Circle::new(4.);
let t = transform(0., 0., 0.);
assert!(circle.intersects_transformed(
&(Particle::new(), Point2::new(-5., -5.)..Point2::new(5., 5.)),
&t
));
assert!(!circle.intersects_transformed(
&(
Particle::new(),
Point2::new(-5., -5.)..Point2::new(-8., -8.)
),
&t
));
let t = transform(10., 10., 0.);
assert!(!circle.intersects_transformed(
&(Particle::new(), Point2::new(-5., -5.)..Point2::new(5., 5.)),
&t
));
}
#[test]
fn test_continuous() {
let circle = Circle::new(4.);
assert_ulps_eq!(
Point2::new(-2.828_427_124_746_190_3, -2.828_427_124_746_190_3),
circle
.intersection(&(Particle::new(), Point2::new(-5., -5.)..Point2::new(5., 5.)))
.unwrap()
);
assert_eq!(
None,
circle.intersection(&(
Particle::new(),
Point2::new(-5., -5.)..Point2::new(-8., -8.)
))
);
}
#[test]
fn test_continuous_transformed() {
let circle = Circle::new(4.);
let t = transform(0., 0., 0.);
assert_ulps_eq!(
Point2::new(-2.828_427_124_746_190_3, -2.828_427_124_746_190_3),
circle
.intersection_transformed(
&(Particle::new(), Point2::new(-5., -5.)..Point2::new(5., 5.)),
&t
)
.unwrap()
);
assert_eq!(
None,
circle.intersection_transformed(
&(
Particle::new(),
Point2::new(-5., -5.)..Point2::new(-8., -8.)
),
&t
)
);
let t = transform(10., 10., 0.);
assert_eq!(
None,
circle.intersection_transformed(
&(Particle::new(), Point2::new(-5., -5.)..Point2::new(5., 5.)),
&t
)
);
}
fn transform(dx: f32, dy: f32, rot: f32) -> Decomposed<Vector2<f32>, Basis2<f32>> {
Decomposed {
scale: 1.,
rot: Rotation2::from_angle(Rad(rot)),
disp: Vector2::new(dx, dy),
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/line.rs | src/primitive/line.rs | use cgmath::{BaseFloat, InnerSpace, Point2, Transform, Vector2};
use crate::line::Line2;
use crate::traits::{ComputeBound, Primitive};
use crate::Aabb2;
impl<S> Primitive for Line2<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
fn support_point<T>(&self, direction: &Vector2<S>, transform: &T) -> Self::Point
where
T: Transform<Self::Point>,
{
let direction = transform.inverse_transform_vector(*direction).unwrap();
let t = direction.dot(self.dest - self.origin);
if t >= S::zero() {
transform.transform_point(self.dest)
} else {
transform.transform_point(self.origin)
}
}
}
impl<S> ComputeBound<Aabb2<S>> for Line2<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb2<S> {
Aabb2::new(self.origin, self.dest)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::algorithm::minkowski::GJK2;
use crate::primitive::Rectangle;
use cgmath::{Basis2, Decomposed, Rad, Rotation2};
fn transform(x: f32, y: f32, angle: f32) -> Decomposed<Vector2<f32>, Basis2<f32>> {
Decomposed {
disp: Vector2::new(x, y),
rot: Rotation2::from_angle(Rad(angle)),
scale: 1.,
}
}
#[test]
fn test_line_rectangle_intersect() {
let line = Line2::new(Point2::new(0., -1.), Point2::new(0., 1.));
let rectangle = Rectangle::new(1., 0.2);
let transform_1 = transform(1., 0., 0.);
let transform_2 = transform(1.1, 0., 0.);
let gjk = GJK2::new();
assert!(gjk
.intersect(&line, &transform_1, &rectangle, &transform_2)
.is_some());
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/primitive3.rs | src/primitive/primitive3.rs | //! Wrapper enum for 3D primitives
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point3, Vector3};
use crate::prelude::*;
use crate::primitive::{
Capsule, ConvexPolyhedron, Cube, Cuboid, Cylinder, Particle3, Quad, Sphere,
};
use crate::{Aabb3, Ray3};
/// Wrapper enum for 3D primitives, that also implements the `Primitive` trait, making it easier
/// to use many different primitives in algorithms.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub enum Primitive3<S>
where
S: BaseFloat,
{
/// Particle
Particle(Particle3<S>),
/// Rectangular plane
Quad(Quad<S>),
/// Sphere
Sphere(Sphere<S>),
/// Cuboid
Cuboid(Cuboid<S>),
/// Cube
Cube(Cube<S>),
/// Cylinder
Cylinder(Cylinder<S>),
/// Capsule
Capsule(Capsule<S>),
/// Convex polyhedron with any number of vertices/faces
ConvexPolyhedron(ConvexPolyhedron<S>),
}
impl<S> From<Particle3<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn from(particle: Particle3<S>) -> Primitive3<S> {
Primitive3::Particle(particle)
}
}
impl<S> From<Quad<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn from(quad: Quad<S>) -> Self {
Primitive3::Quad(quad)
}
}
impl<S> From<Sphere<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn from(sphere: Sphere<S>) -> Primitive3<S> {
Primitive3::Sphere(sphere)
}
}
impl<S> From<Cube<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn from(cuboid: Cube<S>) -> Primitive3<S> {
Primitive3::Cube(cuboid)
}
}
impl<S> From<Cuboid<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn from(cuboid: Cuboid<S>) -> Primitive3<S> {
Primitive3::Cuboid(cuboid)
}
}
impl<S> From<Cylinder<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn from(cylinder: Cylinder<S>) -> Primitive3<S> {
Primitive3::Cylinder(cylinder)
}
}
impl<S> From<Capsule<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn from(capsule: Capsule<S>) -> Primitive3<S> {
Primitive3::Capsule(capsule)
}
}
impl<S> From<ConvexPolyhedron<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn from(polyhedron: ConvexPolyhedron<S>) -> Primitive3<S> {
Primitive3::ConvexPolyhedron(polyhedron)
}
}
impl<S> ComputeBound<Aabb3<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb3<S> {
match *self {
Primitive3::Particle(_) => Aabb3::zero(),
Primitive3::Quad(ref quad) => quad.compute_bound(),
Primitive3::Cuboid(ref cuboid) => cuboid.compute_bound(),
Primitive3::Cube(ref cuboid) => cuboid.compute_bound(),
Primitive3::Sphere(ref sphere) => sphere.compute_bound(),
Primitive3::Cylinder(ref cylinder) => cylinder.compute_bound(),
Primitive3::Capsule(ref capsule) => capsule.compute_bound(),
Primitive3::ConvexPolyhedron(ref polyhedron) => polyhedron.compute_bound(),
}
}
}
impl<S> ComputeBound<crate::volume::Sphere<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> crate::volume::Sphere<S> {
match *self {
Primitive3::Particle(_) => crate::volume::Sphere {
center: Point3::origin(),
radius: S::zero(),
},
Primitive3::Quad(ref quad) => quad.compute_bound(),
Primitive3::Cuboid(ref cuboid) => cuboid.compute_bound(),
Primitive3::Cube(ref cuboid) => cuboid.compute_bound(),
Primitive3::Sphere(ref sphere) => sphere.compute_bound(),
Primitive3::Cylinder(ref cylinder) => cylinder.compute_bound(),
Primitive3::Capsule(ref capsule) => capsule.compute_bound(),
Primitive3::ConvexPolyhedron(ref polyhedron) => polyhedron.compute_bound(),
}
}
}
impl<S> Primitive for Primitive3<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn support_point<T>(&self, direction: &Vector3<S>, transform: &T) -> Point3<S>
where
T: Transform<Point3<S>>,
{
match *self {
Primitive3::Particle(_) => transform.transform_point(Point3::origin()),
Primitive3::Quad(ref quad) => quad.support_point(direction, transform),
Primitive3::Sphere(ref sphere) => sphere.support_point(direction, transform),
Primitive3::Cuboid(ref cuboid) => cuboid.support_point(direction, transform),
Primitive3::Cube(ref cuboid) => cuboid.support_point(direction, transform),
Primitive3::Cylinder(ref cylinder) => cylinder.support_point(direction, transform),
Primitive3::Capsule(ref capsule) => capsule.support_point(direction, transform),
Primitive3::ConvexPolyhedron(ref polyhedron) => {
polyhedron.support_point(direction, transform)
}
}
}
}
impl<S> DiscreteTransformed<Ray3<S>> for Primitive3<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn intersects_transformed<T>(&self, ray: &Ray3<S>, transform: &T) -> bool
where
T: Transform<Self::Point>,
{
match *self {
Primitive3::Particle(ref particle) => particle.intersects_transformed(ray, transform),
Primitive3::Quad(ref quad) => quad.intersects_transformed(ray, transform),
Primitive3::Sphere(ref sphere) => sphere.intersects_transformed(ray, transform),
Primitive3::Cuboid(ref cuboid) => cuboid.intersects_transformed(ray, transform),
Primitive3::Cube(ref cuboid) => cuboid.intersects_transformed(ray, transform),
Primitive3::Cylinder(ref cylinder) => cylinder.intersects_transformed(ray, transform),
Primitive3::Capsule(ref capsule) => capsule.intersects_transformed(ray, transform),
Primitive3::ConvexPolyhedron(ref polyhedron) => {
polyhedron.intersects_transformed(ray, transform)
}
}
}
}
impl<S> ContinuousTransformed<Ray3<S>> for Primitive3<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
type Result = Point3<S>;
fn intersection_transformed<T>(&self, ray: &Ray3<S>, transform: &T) -> Option<Point3<S>>
where
T: Transform<Point3<S>>,
{
match *self {
Primitive3::Particle(ref particle) => particle.intersection_transformed(ray, transform),
Primitive3::Quad(ref quad) => quad.intersection_transformed(ray, transform),
Primitive3::Sphere(ref sphere) => sphere.intersection_transformed(ray, transform),
Primitive3::Cuboid(ref cuboid) => cuboid.intersection_transformed(ray, transform),
Primitive3::Cube(ref cuboid) => cuboid.intersection_transformed(ray, transform),
Primitive3::Cylinder(ref cylinder) => cylinder.intersection_transformed(ray, transform),
Primitive3::Capsule(ref capsule) => capsule.intersection_transformed(ray, transform),
Primitive3::ConvexPolyhedron(ref polyhedron) => {
polyhedron.intersection_transformed(ray, transform)
}
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/capsule.rs | src/primitive/capsule.rs | use cgmath::prelude::*;
use cgmath::{BaseFloat, Point3, Vector3};
use crate::prelude::*;
use crate::primitive::util::cylinder_ray_quadratic_solve;
use crate::volume::Sphere;
use crate::{Aabb3, Ray3};
/// Capsule primitive
/// Capsule body is aligned with the Y axis, with local origin in the center of the capsule.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Capsule<S> {
half_height: S,
radius: S,
}
impl<S> Capsule<S>
where
S: BaseFloat,
{
/// Create a new Capsule
pub fn new(half_height: S, radius: S) -> Self {
Self {
half_height,
radius,
}
}
/// Get radius
pub fn radius(&self) -> S {
self.radius
}
/// Get height
pub fn height(&self) -> S {
self.half_height + self.half_height
}
}
impl<S> Primitive for Capsule<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn support_point<T>(&self, direction: &Vector3<S>, transform: &T) -> Point3<S>
where
T: Transform<Point3<S>>,
{
let direction = transform.inverse_transform_vector(*direction).unwrap();
let mut result = Point3::origin();
result.y = direction.y.signum() * self.half_height;
transform.transform_point(result + direction.normalize_to(self.radius))
}
}
impl<S> ComputeBound<Aabb3<S>> for Capsule<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb3<S> {
Aabb3::new(
Point3::new(-self.radius, -self.half_height - self.radius, -self.radius),
Point3::new(self.radius, self.half_height + self.radius, self.radius),
)
}
}
impl<S> ComputeBound<Sphere<S>> for Capsule<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Sphere<S> {
Sphere {
center: Point3::origin(),
radius: self.half_height + self.radius,
}
}
}
impl<S> Discrete<Ray3<S>> for Capsule<S>
where
S: BaseFloat,
{
fn intersects(&self, r: &Ray3<S>) -> bool {
let (t1, t2) = match cylinder_ray_quadratic_solve(r, self.radius) {
None => return false,
Some(t) => t,
};
if t1 < S::zero() && t2 < S::zero() {
return false;
}
let t = if t1 < S::zero() {
t2
} else if t2 < S::zero() {
t1
} else {
t1.min(t2)
};
let pc = r.origin + r.direction * t;
if pc.y <= self.half_height && pc.y >= -self.half_height {
return true;
}
// top sphere
let l = Vector3::new(-r.origin.x, self.half_height - r.origin.y, -r.origin.z);
let tca = l.dot(r.direction);
if tca > S::zero() {
let d2 = l.dot(l) - tca * tca;
if d2 <= self.radius * self.radius {
return true;
}
}
// bottom sphere
let l = Vector3::new(-r.origin.x, -self.half_height - r.origin.y, -r.origin.z);
let tca = l.dot(r.direction);
if tca > S::zero() {
let d2 = l.dot(l) - tca * tca;
if d2 <= self.radius * self.radius {
return true;
}
}
false
}
}
impl<S> Continuous<Ray3<S>> for Capsule<S>
where
S: BaseFloat,
{
type Result = Point3<S>;
fn intersection(&self, r: &Ray3<S>) -> Option<Point3<S>> {
let (t1, t2) = match cylinder_ray_quadratic_solve(r, self.radius) {
None => return None,
Some(t) => t,
};
if t1 < S::zero() && t2 < S::zero() {
return None;
}
let mut t = if t1 < S::zero() {
t2
} else if t2 < S::zero() {
t1
} else {
t1.min(t2)
};
// top sphere
let l = Vector3::new(-r.origin.x, self.half_height - r.origin.y, -r.origin.z);
let tca = l.dot(r.direction);
if tca > S::zero() {
let d2 = l.dot(l) - tca * tca;
if d2 <= self.radius * self.radius {
let thc = (self.radius * self.radius - d2).sqrt();
let t0 = tca - thc;
if t0 >= S::zero() && (t.is_nan() || t0 < t) {
t = t0;
}
}
}
// bottom sphere
let l = Vector3::new(-r.origin.x, -self.half_height - r.origin.y, -r.origin.z);
let tca = l.dot(r.direction);
if tca > S::zero() {
let d2 = l.dot(l) - tca * tca;
if d2 <= self.radius * self.radius {
let thc = (self.radius * self.radius - d2).sqrt();
let t0 = tca - thc;
if t0 >= S::zero() && (t.is_nan() || t0 < t) {
t = t0;
}
}
}
if t.is_nan() {
return None;
}
let pc = r.origin + r.direction * t;
let full_half_height = self.half_height + self.radius;
if (pc.y > full_half_height) || (pc.y < -full_half_height) {
None
} else {
Some(pc)
}
}
}
#[cfg(test)]
mod tests {
use std;
use cgmath::assert_ulps_eq;
use cgmath::{Decomposed, Quaternion, Rad, Vector3};
use super::*;
#[test]
fn test_capsule_aabb() {
let capsule = Capsule::new(2., 1.);
assert_eq!(
Aabb3::new(Point3::new(-1., -3., -1.), Point3::new(1., 3., 1.)),
capsule.compute_bound()
);
}
#[test]
fn test_capsule_support_1() {
let capsule = Capsule::new(2., 1.);
let direction = Vector3::new(1., 0., 0.);
let transform = transform(0., 0., 0., 0.);
let point = capsule.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(1., 2., 0.), point);
}
#[test]
fn test_capsule_support_2() {
let capsule = Capsule::new(2., 1.);
let direction = Vector3::new(0.5, -1., 0.).normalize();
let transform = transform(0., 0., 0., 0.);
let point = capsule.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(0.447_213_65, -2.894_427_3, 0.), point);
}
#[test]
fn test_capsule_support_3() {
let capsule = Capsule::new(2., 1.);
let direction = Vector3::new(0., 1., 0.);
let transform = transform(0., 0., 0., 0.);
let point = capsule.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(0., 3., 0.), point);
}
#[test]
fn test_capsule_support_4() {
let capsule = Capsule::new(2., 1.);
let direction = Vector3::new(1., 0., 0.);
let transform = transform(10., 0., 0., 0.);
let point = capsule.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(11., 2., 0.), point);
}
#[test]
fn test_capsule_support_5() {
let capsule = Capsule::new(2., 1.);
let direction = Vector3::new(1., 0., 0.);
let transform = transform(0., 0., 0., std::f32::consts::PI);
let point = capsule.support_point(&direction, &transform);
assert_ulps_eq!(Point3::new(1., -2., 0.), point);
}
#[test]
fn test_discrete_1() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(Point3::new(-3., 0., 0.), Vector3::new(1., 0., 0.));
assert!(capsule.intersects(&ray));
}
#[test]
fn test_discrete_2() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(Point3::new(-3., 0., 0.), Vector3::new(-1., 0., 0.));
assert!(!capsule.intersects(&ray));
}
#[test]
fn test_discrete_3() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 3., 0.),
Vector3::new(0.1, -1., 0.1).normalize(),
);
assert!(capsule.intersects(&ray));
}
#[test]
fn test_discrete_4() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 3., 0.),
Vector3::new(0.1, 1., 0.1).normalize(),
);
assert!(!capsule.intersects(&ray));
}
#[test]
fn test_discrete_5() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 3., 0.),
Vector3::new(0., -1., 0.).normalize(),
);
assert!(capsule.intersects(&ray));
}
#[test]
fn test_continuous_1() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(Point3::new(-3., 0., 0.), Vector3::new(1., 0., 0.));
assert_eq!(Some(Point3::new(-1., 0., 0.)), capsule.intersection(&ray));
}
#[test]
fn test_continuous_2() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(Point3::new(-3., 0., 0.), Vector3::new(-1., 0., 0.));
assert_eq!(None, capsule.intersection(&ray));
}
#[test]
fn test_continuous_3() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 4., 0.),
Vector3::new(0.1, -1., 0.1).normalize(),
);
assert_eq!(
Some(Point3::new(
0.101_025_885_148_699_44,
2.989_741_148_513_006,
0.101_025_885_148_699_44
)),
capsule.intersection(&ray)
);
}
#[test]
fn test_continuous_4() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 3., 0.),
Vector3::new(0.1, 1., 0.1).normalize(),
);
assert_eq!(None, capsule.intersection(&ray));
}
#[test]
fn test_continuous_5() {
let capsule = Capsule::new(2., 1.);
let ray = Ray3::new(
Point3::new(0., 4., 0.),
Vector3::new(0., -1., 0.).normalize(),
);
assert_eq!(Some(Point3::new(0., 3., 0.)), capsule.intersection(&ray));
}
// util
fn transform(dx: f32, dy: f32, dz: f32, rot: f32) -> Decomposed<Vector3<f32>, Quaternion<f32>> {
Decomposed {
scale: 1.,
rot: Quaternion::from_angle_z(Rad(rot)),
disp: Vector3::new(dx, dy, dz),
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/primitive/sphere.rs | src/primitive/sphere.rs | use cgmath::prelude::*;
use cgmath::{BaseFloat, Point3, Vector3};
use crate::prelude::*;
use crate::{Aabb3, Ray3};
/// Sphere primitive
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Sphere<S> {
/// Radius of the sphere
pub radius: S,
}
impl<S> Sphere<S> {
/// Create a new sphere primitive
pub fn new(radius: S) -> Self {
Self { radius }
}
}
impl<S> Primitive for Sphere<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn support_point<T>(&self, direction: &Vector3<S>, transform: &T) -> Point3<S>
where
T: Transform<Point3<S>>,
{
let direction = transform.inverse_transform_vector(*direction).unwrap();
transform.transform_point(Point3::from_vec(direction.normalize_to(self.radius)))
}
}
impl<S> ComputeBound<Aabb3<S>> for Sphere<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> Aabb3<S> {
Aabb3::new(
Point3::from_value(-self.radius),
Point3::from_value(self.radius),
)
}
}
impl<S> ComputeBound<crate::volume::Sphere<S>> for Sphere<S>
where
S: BaseFloat,
{
fn compute_bound(&self) -> crate::volume::Sphere<S> {
crate::volume::Sphere {
center: Point3::origin(),
radius: self.radius,
}
}
}
impl<S> Discrete<Ray3<S>> for Sphere<S>
where
S: BaseFloat,
{
fn intersects(&self, r: &Ray3<S>) -> bool {
let s = self;
let l = Vector3::new(-r.origin.x, -r.origin.y, -r.origin.z);
let tca = l.dot(r.direction);
if tca < S::zero() {
return false;
}
let d2 = l.dot(l) - tca * tca;
d2 <= s.radius * s.radius
}
}
impl<S> Continuous<Ray3<S>> for Sphere<S>
where
S: BaseFloat,
{
type Result = Point3<S>;
fn intersection(&self, r: &Ray3<S>) -> Option<Point3<S>> {
let s = self;
let l = Vector3::new(-r.origin.x, -r.origin.y, -r.origin.z);
let tca = l.dot(r.direction);
if tca < S::zero() {
return None;
}
let d2 = l.dot(l) - tca * tca;
if d2 > s.radius * s.radius {
return None;
}
let thc = (s.radius * s.radius - d2).sqrt();
Some(r.origin + r.direction * (tca - thc))
}
}
#[cfg(test)]
mod tests {
use std;
use cgmath::assert_ulps_eq;
use cgmath::{Decomposed, Point3, Quaternion, Rad, Rotation3, Vector3};
use super::*;
// sphere
#[test]
fn test_sphere_support_1() {
test_sphere_support(1., 0., 0., 10., 0., 0., 0.);
}
#[test]
fn test_sphere_support_2() {
test_sphere_support(
1.,
1.,
1.,
5.773_502_691_896_258,
5.773_502_691_896_258,
5.773_502_691_896_258,
0.,
);
}
#[test]
fn test_sphere_support_3() {
test_sphere_support(
1.,
0.,
0.,
10.,
0.000_000_953_674_3,
0.,
-std::f32::consts::PI / 4.,
);
}
#[test]
fn test_sphere_support_4() {
let sphere = Sphere::new(10.);
let direction = Vector3::new(1., 0., 0.);
let t = transform(0., 10., 0., 0.);
let point = sphere.support_point(&direction, &t);
assert_eq!(Point3::new(10., 10., 0.), point);
}
#[test]
fn test_sphere_bound() {
let sphere = Sphere::new(10.);
assert_eq!(
bound(-10., -10., -10., 10., 10., 10.),
sphere.compute_bound()
);
}
#[test]
fn test_ray_discrete() {
let sphere = Sphere::new(10.);
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(-1., 0., 0.));
assert!(sphere.intersects(&ray));
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(1., 0., 0.));
assert!(!sphere.intersects(&ray));
let ray = Ray3::new(Point3::new(20., -15., 0.), Vector3::new(-1., 0., 0.));
assert!(!sphere.intersects(&ray));
}
#[test]
fn test_ray_discrete_transformed() {
let sphere = Sphere::new(10.);
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(-1., 0., 0.));
let t = transform(0., 0., 0., 0.);
assert!(sphere.intersects_transformed(&ray, &t));
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(1., 0., 0.));
assert!(!sphere.intersects_transformed(&ray, &t));
let t = transform(0., 15., 0., 0.);
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(-1., 0., 0.));
assert!(!sphere.intersects_transformed(&ray, &t));
}
#[test]
fn test_ray_continuous() {
let sphere = Sphere::new(10.);
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(-1., 0., 0.));
assert_eq!(Some(Point3::new(10., 0., 0.)), sphere.intersection(&ray));
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(1., 0., 0.));
assert_eq!(None, sphere.intersection(&ray));
let ray = Ray3::new(Point3::new(20., -15., 0.), Vector3::new(-1., 0., 0.));
assert_eq!(None, sphere.intersection(&ray));
}
#[test]
fn test_ray_continuous_transformed() {
let sphere = Sphere::new(10.);
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(-1., 0., 0.));
let t = transform(0., 0., 0., 0.);
assert_eq!(
Some(Point3::new(10., 0., 0.)),
sphere.intersection_transformed(&ray, &t)
);
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(1., 0., 0.));
assert_eq!(None, sphere.intersection_transformed(&ray, &t));
let t = transform(0., 15., 0., 0.);
let ray = Ray3::new(Point3::new(20., 0., 0.), Vector3::new(-1., 0., 0.));
assert_eq!(None, sphere.intersection_transformed(&ray, &t));
}
fn test_sphere_support(dx: f32, dy: f32, dz: f32, px: f32, py: f32, pz: f32, rot: f32) {
let sphere = Sphere::new(10.);
let direction = Vector3::new(dx, dy, dz);
let t = transform(0., 0., 0., rot);
let point = sphere.support_point(&direction, &t);
assert_ulps_eq!(px, point.x);
assert_ulps_eq!(py, point.y);
assert_ulps_eq!(pz, point.z);
}
// util
fn transform(dx: f32, dy: f32, dz: f32, rot: f32) -> Decomposed<Vector3<f32>, Quaternion<f32>> {
Decomposed {
scale: 1.,
rot: Quaternion::from_angle_z(Rad(rot)),
disp: Vector3::new(dx, dy, dz),
}
}
fn bound(min_x: f32, min_y: f32, min_z: f32, max_x: f32, max_y: f32, max_z: f32) -> Aabb3<f32> {
Aabb3::new(
Point3::new(min_x, min_y, min_z),
Point3::new(max_x, max_y, max_z),
)
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/mod.rs | src/algorithm/mod.rs | //! Collision detection algorithms
pub mod broad_phase;
pub mod minkowski;
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/broad_phase/dbvt.rs | src/algorithm/broad_phase/dbvt.rs | //! [`Dynamic Bounding Volume Tree`](../../dbvt/struct.DynamicBoundingVolumeTree.html) accelerated
//! broad phase collision detection algorithm
use std::cmp::Ordering;
use crate::dbvt::{DiscreteVisitor, DynamicBoundingVolumeTree, TreeValue};
use crate::prelude::*;
/// [`Dynamic Bounding Volume Tree`](../../dbvt/struct.DynamicBoundingVolumeTree.html) accelerated
/// broad phase collision detection algorithm
#[derive(Copy, Clone, Debug)]
pub struct DbvtBroadPhase;
impl DbvtBroadPhase {
/// Create a new DbvtBroadPhase
pub fn new() -> Self {
Self {}
}
/// Find all collider pairs between the shapes in the tree. Will only process the shapes that
/// are marked as dirty in the given dirty list.
///
/// ## Returns
///
/// A list of tuples of indices into the values list in the tree, sorted by increasing left
/// index.
pub fn find_collider_pairs<T>(
&self,
tree: &DynamicBoundingVolumeTree<T>,
dirty: &[bool],
) -> Vec<(usize, usize)>
where
T: TreeValue,
T::Bound: Discrete<T::Bound>
+ Clone
+ Contains<T::Bound>
+ SurfaceArea
+ Union<T::Bound, Output = T::Bound>,
{
let mut potentials = Vec::default();
// do intersection tests against tree for each value that is dirty
for &(shape_node_index, ref shape) in tree.values() {
// We get the node index from the values list in the tree, and immediately get the value
// index of said node, so unwrapping will be safe for all cases where the tree isn't
// corrupt. The tree being corrupt is a programming error, which should be a panic.
let shape_value_index = tree.value_index(shape_node_index).unwrap();
if dirty[shape_value_index] {
for (hit_value_index, _) in
tree.query_for_indices(&mut DiscreteVisitor::<T::Bound, T>::new(shape.bound()))
{
let pair = match shape_value_index.cmp(&hit_value_index) {
Ordering::Equal => continue,
Ordering::Less => (shape_value_index, hit_value_index),
Ordering::Greater => (hit_value_index, shape_value_index),
};
if let Err(pos) = potentials.binary_search(&pair) {
potentials.insert(pos, pair);
}
}
}
}
potentials
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/broad_phase/mod.rs | src/algorithm/broad_phase/mod.rs | //! Broad phase collision detection algorithms
pub use self::brute_force::BruteForce;
pub use self::dbvt::DbvtBroadPhase;
pub use self::sweep_prune::{SweepAndPrune, SweepAndPrune2, SweepAndPrune3, Variance};
mod brute_force;
mod dbvt;
mod sweep_prune;
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/broad_phase/brute_force.rs | src/algorithm/broad_phase/brute_force.rs | use crate::prelude::*;
/// Broad phase collision detection brute force implementation.
///
/// Will simply do bounding box intersection tests for all shape combinations.
#[derive(Debug, Default, Copy, Clone)]
pub struct BruteForce;
impl BruteForce {
/// Find all potentially colliding pairs of shapes.
///
/// ## Parameters
///
/// - `shapes`: Shapes to do find potential collisions for
///
/// ## Returns
///
/// Returns tuples with the into the shapes list, of all potentially colliding pairs.
/// The first value in the tuple will always be first in the list.
pub fn find_collider_pairs<A>(&self, shapes: &[A]) -> Vec<(usize, usize)>
where
A: HasBound,
A::Bound: Discrete<A::Bound>,
{
let mut pairs = Vec::default();
if shapes.len() <= 1 {
return pairs;
}
for left_index in 0..(shapes.len() - 1) {
let left = &shapes[left_index];
for right_index in (left_index + 1)..shapes.len() {
if left.bound().intersects(shapes[right_index].bound()) {
pairs.push((left_index, right_index));
}
}
}
pairs
}
}
#[cfg(test)]
mod tests {
use cgmath::Point2;
use super::*;
use crate::Aabb2;
#[derive(Debug, Clone, PartialEq)]
pub struct BroadCollisionInfo2 {
/// The id
pub id: u32,
/// The bounding volume
pub bound: Aabb2<f32>,
index: usize,
}
impl BroadCollisionInfo2 {
/// Create a new collision info
pub fn new(id: u32, bound: Aabb2<f32>) -> Self {
Self {
id,
bound,
index: 0,
}
}
}
impl HasBound for BroadCollisionInfo2 {
type Bound = Aabb2<f32>;
fn bound(&self) -> &Aabb2<f32> {
&self.bound
}
}
#[test]
fn no_intersection_for_miss() {
let left = coll(1, 8., 8., 10., 11.);
let right = coll(2, 12., 13., 18., 18.);
let brute = BruteForce::default();
let potentials = brute.find_collider_pairs(&[left, right]);
assert_eq!(0, potentials.len());
}
#[test]
fn no_intersection_for_miss_unsorted() {
let left = coll(1, 8., 8., 10., 11.);
let right = coll(2, 12., 13., 18., 18.);
let brute = BruteForce::default();
let potentials = brute.find_collider_pairs(&[right, left]);
assert_eq!(0, potentials.len());
}
#[test]
fn intersection_for_hit() {
let left = coll(1, 8., 8., 10., 11.);
let right = coll(2, 9., 10., 18., 18.);
let brute = BruteForce::default();
let potentials = brute.find_collider_pairs(&[left, right]);
assert_eq!(1, potentials.len());
assert_eq!((0, 1), potentials[0]);
}
#[test]
fn intersection_for_hit_unsorted() {
let left = coll(1, 8., 8., 10., 11.);
let right = coll(222, 9., 10., 18., 18.);
let brute = BruteForce::default();
let potentials = brute.find_collider_pairs(&[right, left]);
assert_eq!(1, potentials.len());
assert_eq!((0, 1), potentials[0]);
}
// util
fn coll(id: u32, min_x: f32, min_y: f32, max_x: f32, max_y: f32) -> BroadCollisionInfo2 {
BroadCollisionInfo2::new(id, bound(min_x, min_y, max_x, max_y))
}
fn bound(min_x: f32, min_y: f32, max_x: f32, max_y: f32) -> Aabb2<f32> {
Aabb2::new(Point2::new(min_x, min_y), Point2::new(max_x, max_y))
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/broad_phase/sweep_prune.rs | src/algorithm/broad_phase/sweep_prune.rs | pub use self::variance::Variance;
use std::cmp::Ordering;
use cgmath::num_traits::NumCast;
use self::variance::{Variance2, Variance3};
use crate::prelude::*;
/// Broad phase sweep and prune algorithm for 2D, see
/// [SweepAndPrune](struct.SweepAndPrune.html) for more information.
pub type SweepAndPrune2<S, B> = SweepAndPrune<Variance2<S, B>>;
/// Broad phase sweep and prune algorithm for 3D, see
/// [SweepAndPrune](struct.SweepAndPrune.html) for more information.
pub type SweepAndPrune3<S, B> = SweepAndPrune<Variance3<S, B>>;
/// Sweep and prune broad phase collision detection algorithm.
///
/// Will sort the bounding boxes of the collision world along some axis, and will then sweep the
/// sorted list, and compare the bounds along the sweep axis, adding them to an active list when
/// they are encountered, and removing them from the active list when the end extent is passed.
///
/// Any shape pairs found by the base algorithm, will then do a bounding box intersection test,
/// before adding to the resulting pairs list.
///
/// # Type parameters:
///
/// - `V`: Variance type used for computing what axis to use on the next iteration.
/// [SweepAndPrune2](type.SweepAndPrune2.html) and [SweepAndPrune3](type.SweepAndPrune3.html)
/// provide a variance type for you, so they should be used if you do not have a custom type
/// implementing [Variance](trait.Variance.html).
#[derive(Debug)]
pub struct SweepAndPrune<V> {
sweep_axis: usize,
variance: V,
}
impl<V> SweepAndPrune<V>
where
V: Variance,
{
/// Create a new sweep and prune algorithm, will use the X axis as the first sweep axis
pub fn new() -> Self {
Self::with_sweep_axis(0)
}
/// Create a new sweep and prune algorithm, starting with the given axis as the first sweep axis
pub fn with_sweep_axis(sweep_axis: usize) -> Self {
Self {
sweep_axis,
variance: V::new(),
}
}
/// Get sweep axis
pub fn get_sweep_axis(&self) -> usize {
self.sweep_axis
}
/// Find all potentially colliding pairs of shapes
///
/// ## Parameters
///
/// - `shapes`: Shapes to do find potential collisions for
///
/// ## Returns
///
/// Returns tuples with indices into the shapes list, of all potentially colliding pairs.
/// The first value in the tuple will always be first in the list.
///
/// ## Side effects:
///
/// The shapes list might have been resorted. The indices in the return values will be for the
/// sorted list.
pub fn find_collider_pairs<A>(&mut self, shapes: &mut [A]) -> Vec<(usize, usize)>
where
A: HasBound,
A::Bound: Bound + Discrete<A::Bound>,
V: Variance<Bound = A::Bound>,
{
let mut pairs = Vec::default();
if shapes.len() <= 1 {
return pairs;
}
shapes.sort_by(|a, b| {
let cmp_min = a.bound().min_extent()[self.sweep_axis]
.partial_cmp(&b.bound().min_extent()[self.sweep_axis]);
match cmp_min {
Some(Ordering::Equal) => a.bound().max_extent()[self.sweep_axis]
.partial_cmp(&b.bound().max_extent()[self.sweep_axis])
.unwrap_or(Ordering::Equal),
None => Ordering::Equal,
Some(order) => order,
}
});
self.variance.clear();
self.variance.add_bound(shapes[0].bound());
let mut active = vec![0];
// Remember that the index here will be the index of the iterator, which starts at index 1
// in the shapes list, so the real shape index is + 1
for (index, shape) in shapes[1..].iter().enumerate() {
let shape_index = index + 1;
// for all currently active bounds, go through and remove any that are to the left of
// the current bound
active.retain(|active_index| {
shapes[*active_index].bound().max_extent()[self.sweep_axis]
>= shape.bound().min_extent()[self.sweep_axis]
});
// all shapes in the active list are potential hits, do a real bound intersection test
// for those, and add to pairs if the bounds intersect.
for active_index in &active {
if shapes[*active_index].bound().intersects(shape.bound()) {
pairs.push((*active_index, shape_index));
}
}
// current bound should be active for the next iteration
active.push(shape_index);
// update variance
self.variance.add_bound(shape.bound());
}
// compute sweep axis for the next iteration
let (axis, _) = self
.variance
.compute_axis(NumCast::from(shapes.len()).unwrap());
self.sweep_axis = axis;
pairs
}
}
mod variance {
use std::marker;
use crate::Bound;
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point2, Point3, Vector2, Vector3};
/// Trait for variance calculation in sweep and prune algorithm
pub trait Variance {
/// Point type
type Bound: Bound;
/// Create new variance object
fn new() -> Self;
/// Clear variance sums
fn clear(&mut self);
/// Add an extent to the variance sums
fn add_bound(&mut self, bound: &Self::Bound);
/// Compute the sweep axis based on the internal values
fn compute_axis(
&self,
n: <<Self::Bound as Bound>::Point as EuclideanSpace>::Scalar,
) -> (
usize,
<<Self::Bound as Bound>::Point as EuclideanSpace>::Scalar,
);
}
/// Variance for 2D sweep and prune
#[derive(Debug)]
pub struct Variance2<S, B> {
csum: Vector2<S>,
csumsq: Vector2<S>,
m: marker::PhantomData<B>,
}
impl<S, B> Variance for Variance2<S, B>
where
S: BaseFloat,
B: Bound<Point = Point2<S>>,
{
type Bound = B;
fn new() -> Self {
Self {
csum: Vector2::zero(),
csumsq: Vector2::zero(),
m: marker::PhantomData,
}
}
fn clear(&mut self) {
self.csum = Vector2::zero();
self.csumsq = Vector2::zero();
}
#[inline]
fn add_bound(&mut self, bound: &B) {
let min_vec = bound.min_extent().to_vec();
let max_vec = bound.max_extent().to_vec();
let sum = min_vec.add_element_wise(max_vec);
let c = sum / (S::one() + S::one());
self.csum.add_element_wise(c);
self.csumsq.add_element_wise(c.mul_element_wise(c));
}
#[inline]
fn compute_axis(&self, n: S) -> (usize, S) {
let square_n = self.csum.mul_element_wise(self.csum) / n;
let variance = self.csumsq.sub_element_wise(square_n);
let mut sweep_axis = 0;
let mut sweep_variance = variance[0];
for i in 1..2 {
let v = variance[i];
if v > sweep_variance {
sweep_axis = i;
sweep_variance = v;
}
}
(sweep_axis, sweep_variance)
}
}
/// Variance for 3D sweep and prune
#[derive(Debug)]
pub struct Variance3<S, B> {
csum: Vector3<S>,
csumsq: Vector3<S>,
m: marker::PhantomData<B>,
}
impl<S, B> Variance for Variance3<S, B>
where
S: BaseFloat,
B: Bound<Point = Point3<S>>,
{
type Bound = B;
fn new() -> Self {
Self {
csum: Vector3::zero(),
csumsq: Vector3::zero(),
m: marker::PhantomData,
}
}
fn clear(&mut self) {
self.csum = Vector3::zero();
self.csumsq = Vector3::zero();
}
#[inline]
fn add_bound(&mut self, bound: &B) {
let min_vec = bound.min_extent().to_vec();
let max_vec = bound.max_extent().to_vec();
let sum = min_vec.add_element_wise(max_vec);
let c = sum / (S::one() + S::one());
self.csum.add_element_wise(c);
self.csumsq.add_element_wise(c.mul_element_wise(c));
}
#[inline]
fn compute_axis(&self, n: S) -> (usize, S) {
let square_n = self.csum.mul_element_wise(self.csum) / n;
let variance = self.csumsq.sub_element_wise(square_n);
let mut sweep_axis = 0;
let mut sweep_variance = variance[0];
for i in 1..3 {
let v = variance[i];
if v > sweep_variance {
sweep_axis = i;
sweep_variance = v;
}
}
(sweep_axis, sweep_variance)
}
}
}
#[cfg(test)]
mod tests {
use cgmath::Point2;
use super::*;
use crate::Aabb2;
#[derive(Debug, Clone, PartialEq)]
pub struct BroadCollisionInfo2 {
/// The id
pub id: u32,
/// The bounding volume
pub bound: Aabb2<f32>,
index: usize,
}
impl BroadCollisionInfo2 {
/// Create a new collision info
pub fn new(id: u32, bound: Aabb2<f32>) -> Self {
Self {
id,
bound,
index: 0,
}
}
}
impl HasBound for BroadCollisionInfo2 {
type Bound = Aabb2<f32>;
fn bound(&self) -> &Aabb2<f32> {
&self.bound
}
}
#[test]
fn no_intersection_for_miss() {
let left = coll(1, 8., 8., 10., 11.);
let right = coll(2, 12., 13., 18., 18.);
let mut sweep = SweepAndPrune2::new();
let potentials = sweep.find_collider_pairs(&mut [left, right]);
assert_eq!(0, potentials.len());
}
#[test]
fn no_intersection_for_miss_unsorted() {
let left = coll(1, 8., 8., 10., 11.);
let right = coll(2, 12., 13., 18., 18.);
let mut sweep = SweepAndPrune2::new();
let potentials = sweep.find_collider_pairs(&mut [right, left]);
assert_eq!(0, potentials.len());
}
#[test]
fn intersection_for_hit() {
let left = coll(1, 8., 8., 10., 11.);
let right = coll(2, 9., 10., 18., 18.);
let mut sweep = SweepAndPrune2::new();
let potentials = sweep.find_collider_pairs(&mut [left, right]);
assert_eq!(1, potentials.len());
assert_eq!((0, 1), potentials[0]);
}
#[test]
fn intersection_for_hit_unsorted() {
let left = coll(1, 8., 8., 10., 11.);
let right = coll(222, 9., 10., 18., 18.);
let mut sweep = SweepAndPrune2::new();
let potentials = sweep.find_collider_pairs(&mut [right, left]);
assert_eq!(1, potentials.len());
assert_eq!((0, 1), potentials[0]);
}
// util
fn coll(id: u32, min_x: f32, min_y: f32, max_x: f32, max_y: f32) -> BroadCollisionInfo2 {
BroadCollisionInfo2::new(id, bound(min_x, min_y, max_x, max_y))
}
fn bound(min_x: f32, min_y: f32, max_x: f32, max_y: f32) -> Aabb2<f32> {
Aabb2::new(Point2::new(min_x, min_y), Point2::new(max_x, max_y))
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/minkowski/mod.rs | src/algorithm/minkowski/mod.rs | //! Algorithms using the Minkowski Sum/Difference
pub use self::epa::{EPA, EPA2, EPA3};
pub use self::gjk::{SimplexProcessor, GJK, GJK2, GJK3};
use std::ops::{Neg, Sub};
use crate::prelude::*;
use cgmath::prelude::*;
mod epa;
mod gjk;
/// Minkowski Sum/Difference support point
#[derive(Clone, Debug, Copy)]
pub struct SupportPoint<P>
where
P: EuclideanSpace,
{
v: P::Diff,
sup_a: P,
sup_b: P,
}
impl<P> SupportPoint<P>
where
P: EuclideanSpace,
{
/// Create a new support point at origin
pub fn new() -> Self {
Self {
v: P::Diff::zero(),
sup_a: P::origin(),
sup_b: P::origin(),
}
}
/// Create a new support point from the minkowski difference, using primitive support functions
pub fn from_minkowski<SL, SR, TL, TR>(
left: &SL,
left_transform: &TL,
right: &SR,
right_transform: &TR,
direction: &P::Diff,
) -> Self
where
SL: Primitive<Point = P>,
SR: Primitive<Point = P>,
P::Diff: Neg<Output = P::Diff>,
TL: Transform<P>,
TR: Transform<P>,
{
let l = left.support_point(direction, left_transform);
let r = right.support_point(&direction.neg(), right_transform);
Self {
v: l - r,
sup_a: l,
sup_b: r,
}
}
}
impl<P> Sub<P> for SupportPoint<P>
where
P: EuclideanSpace,
{
type Output = Self;
fn sub(self, rhs: P) -> Self {
SupportPoint {
v: self.v - rhs.to_vec(),
sup_a: self.sup_a,
sup_b: self.sup_b,
}
}
}
#[cfg(test)]
mod tests {
use cgmath::{Basis2, Decomposed, Rad, Rotation2, Vector2};
use super::SupportPoint;
use crate::primitive::*;
fn transform(x: f32, y: f32, angle: f32) -> Decomposed<Vector2<f32>, Basis2<f32>> {
Decomposed {
disp: Vector2::new(x, y),
rot: Rotation2::from_angle(Rad(angle)),
scale: 1.,
}
}
#[test]
fn test_support() {
let left = Rectangle::new(10., 10.);
let left_transform = transform(15., 0., 0.);
let right = Rectangle::new(10., 10.);
let right_transform = transform(-15., 0., 0.);
let direction = Vector2::new(1., 0.);
assert_eq!(
Vector2::new(40., 0.),
SupportPoint::from_minkowski(
&left,
&left_transform,
&right,
&right_transform,
&direction,
)
.v
);
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/minkowski/epa/epa2d.rs | src/algorithm/minkowski/epa/epa2d.rs | use std::marker;
use cgmath::assert_ulps_ne;
use cgmath::num_traits::NumCast;
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point2, Vector2};
use super::*;
use crate::prelude::*;
use crate::primitive::util::triple_product;
use crate::{CollisionStrategy, Contact};
/// EPA algorithm implementation for 2D. Only to be used in [`GJK`](struct.GJK.html).
#[derive(Debug)]
pub struct EPA2<S> {
m: marker::PhantomData<S>,
tolerance: S,
max_iterations: u32,
}
impl<S> EPA for EPA2<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
fn process<SL, SR, TL, TR>(
&self,
simplex: &mut Vec<SupportPoint<Point2<S>>>,
left: &SL,
left_transform: &TL,
right: &SR,
right_transform: &TR,
) -> Option<Contact<Point2<S>>>
where
SL: Primitive<Point = Self::Point>,
SR: Primitive<Point = Self::Point>,
TL: Transform<Self::Point>,
TR: Transform<Self::Point>,
{
let mut e = match closest_edge(simplex) {
None => return None,
Some(e) => e,
};
for _ in 0..self.max_iterations {
let p = SupportPoint::from_minkowski(
left,
left_transform,
right,
right_transform,
&e.normal,
);
let d = p.v.dot(e.normal);
if d - e.distance < self.tolerance {
break;
} else {
simplex.insert(e.index, p);
}
e = closest_edge(simplex).unwrap();
}
Some(Contact::new_with_point(
CollisionStrategy::FullResolution,
e.normal,
e.distance,
point(simplex, &e),
))
}
fn new() -> Self {
Self::new_with_tolerance(NumCast::from(EPA_TOLERANCE).unwrap(), MAX_ITERATIONS)
}
fn new_with_tolerance(
tolerance: <Self::Point as EuclideanSpace>::Scalar,
max_iterations: u32,
) -> Self {
Self {
m: marker::PhantomData,
tolerance,
max_iterations,
}
}
}
/// This function returns the contact point in world space coordinates on shape A.
///
/// Compute the closest point to the origin on the given simplex edge, then use that to interpolate
/// the support points coming from the A shape.
fn point<S>(simplex: &[SupportPoint<Point2<S>>], edge: &Edge<S>) -> Point2<S>
where
S: BaseFloat,
{
let b = &simplex[edge.index];
let a = if edge.index == 0 {
&simplex[simplex.len() - 1]
} else {
&simplex[edge.index - 1]
};
let oa = -a.v;
let ab = b.v - a.v;
let t = oa.dot(ab) / ab.magnitude2();
if t < S::zero() {
a.sup_a
} else if t > S::one() {
b.sup_a
} else {
a.sup_a + (b.sup_a - a.sup_a) * t
}
}
#[derive(Debug, PartialEq)]
struct Edge<S> {
pub normal: Vector2<S>,
pub distance: S,
pub index: usize,
}
impl<S> Edge<S>
where
S: BaseFloat,
{
pub fn new(normal: Vector2<S>, distance: S, index: usize) -> Self {
Self {
normal,
distance,
index,
}
}
}
fn closest_edge<S>(simplex: &[SupportPoint<Point2<S>>]) -> Option<Edge<S>>
where
S: BaseFloat,
{
if simplex.len() < 3 {
None
} else {
let mut edge = Edge::new(Vector2::zero(), S::infinity(), 0);
for i in 0..simplex.len() {
let j = if i + 1 == simplex.len() { 0 } else { i + 1 };
let a = simplex[i].v;
let b = simplex[j].v;
let e = b - a;
let oa = a;
let n = triple_product(&e, &oa, &e).normalize();
let d = n.dot(a);
if d < edge.distance {
edge = Edge::new(n, d, j);
}
}
assert_ulps_ne!(S::infinity(), edge.distance);
Some(edge)
}
}
#[cfg(test)]
mod tests {
use cgmath::assert_ulps_eq;
use cgmath::{Basis2, Decomposed, Point2, Rad, Rotation2, Vector2};
use super::*;
use crate::algorithm::minkowski::SupportPoint;
use crate::primitive::*;
#[test]
fn test_closest_edge_0() {
assert_eq!(None, closest_edge::<f32>(&[]));
}
#[test]
fn test_closest_edge_1() {
assert_eq!(None, closest_edge(&[sup(10., 10.)]));
}
#[test]
fn test_closest_edge_2() {
assert_eq!(None, closest_edge(&[sup(10., 10.), sup(-10., 5.)]));
}
#[test]
fn test_closest_edge_3() {
let edge = closest_edge(&[sup(10., 10.), sup(-10., 5.), sup(2., -5.)]);
assert!(edge.is_some());
let edge = edge.unwrap();
assert_eq!(2, edge.index);
assert_ulps_eq!(2.560_737_4, edge.distance);
assert_ulps_eq!(-0.640_184_4, edge.normal.x);
assert_ulps_eq!(-0.768_221_3, edge.normal.y);
}
#[test]
fn test_epa_0() {
let left = Rectangle::new(10., 10.);
let left_transform = transform(15., 0., 0.);
let right = Rectangle::new(10., 10.);
let right_transform = transform(7., 2., 0.);
assert!(EPA2::new()
.process(
&mut vec![],
&left,
&left_transform,
&right,
&right_transform
)
.is_none());
}
#[test]
fn test_epa_1() {
let left = Rectangle::new(10., 10.);
let left_transform = transform(15., 0., 0.);
let right = Rectangle::new(10., 10.);
let right_transform = transform(7., 2., 0.);
let mut simplex = vec![sup(-2., 8.)];
assert!(EPA2::new()
.process(
&mut simplex,
&left,
&left_transform,
&right,
&right_transform
)
.is_none());
}
#[test]
fn test_epa_2() {
let left = Rectangle::new(10., 10.);
let left_transform = transform(15., 0., 0.);
let right = Rectangle::new(10., 10.);
let right_transform = transform(7., 2., 0.);
let mut simplex = vec![sup(-2., 8.), sup(18., -12.)];
assert!(EPA2::new()
.process(
&mut simplex,
&left,
&left_transform,
&right,
&right_transform
)
.is_none());
}
#[test]
fn test_epa_3() {
let left = Rectangle::new(10., 10.);
let left_transform = transform(15., 0., 0.);
let right = Rectangle::new(10., 10.);
let right_transform = transform(7., 2., 0.);
let mut simplex = vec![sup(-2., 8.), sup(18., -12.), sup(-2., -12.)];
let contact = EPA2::new().process(
&mut simplex,
&left,
&left_transform,
&right,
&right_transform,
);
assert!(contact.is_some());
let contact = contact.unwrap();
assert_eq!(Vector2::new(-1., 0.), contact.normal);
assert!(2. - contact.penetration_depth <= f32::EPSILON);
}
fn sup(x: f32, y: f32) -> SupportPoint<Point2<f32>> {
let mut s = SupportPoint::new();
s.v = Vector2::new(x, y);
s
}
fn transform(x: f32, y: f32, angle: f32) -> Decomposed<Vector2<f32>, Basis2<f32>> {
Decomposed {
disp: Vector2::new(x, y),
rot: Rotation2::from_angle(Rad(angle)),
scale: 1.,
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/minkowski/epa/epa3d.rs | src/algorithm/minkowski/epa/epa3d.rs | use std::marker;
use cgmath::num_traits::NumCast;
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point3, Vector3};
use super::SupportPoint;
use super::*;
use crate::prelude::*;
use crate::primitive::util::barycentric_vector;
use crate::{CollisionStrategy, Contact};
/// EPA algorithm implementation for 3D. Only to be used in [`GJK`](struct.GJK.html).
#[derive(Debug)]
pub struct EPA3<S> {
m: marker::PhantomData<S>,
tolerance: S,
max_iterations: u32,
}
impl<S> EPA for EPA3<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn process<SL, SR, TL, TR>(
&self,
mut simplex: &mut Vec<SupportPoint<Point3<S>>>,
left: &SL,
left_transform: &TL,
right: &SR,
right_transform: &TR,
) -> Option<Contact<Point3<S>>>
where
SL: Primitive<Point = Self::Point>,
SR: Primitive<Point = Self::Point>,
TL: Transform<Self::Point>,
TR: Transform<Self::Point>,
{
if simplex.len() < 4 {
return None;
}
let mut polytope = Polytope::new(&mut simplex);
let mut i = 1;
loop {
let p = {
let face = polytope.closest_face_to_origin();
let p = SupportPoint::from_minkowski(
left,
left_transform,
right,
right_transform,
&face.normal,
);
let d = p.v.dot(face.normal);
if d - face.distance < self.tolerance || i >= self.max_iterations {
return contact(&polytope, face);
}
p
};
polytope.add(p);
i += 1;
}
}
fn new() -> Self {
Self::new_with_tolerance(NumCast::from(EPA_TOLERANCE).unwrap(), MAX_ITERATIONS)
}
fn new_with_tolerance(
tolerance: <Self::Point as EuclideanSpace>::Scalar,
max_iterations: u32,
) -> Self {
Self {
m: marker::PhantomData,
tolerance,
max_iterations,
}
}
}
#[inline]
fn contact<S>(polytope: &Polytope<'_, S>, face: &Face<S>) -> Option<Contact<Point3<S>>>
where
S: BaseFloat,
{
Some(Contact::new_with_point(
CollisionStrategy::FullResolution,
face.normal, // negate ?
face.distance,
point(polytope, face),
))
}
/// This function returns the contact point in world space coordinates on shape A.
///
/// Compute the closest point to the origin on the given simplex face, then use that to interpolate
/// the support points coming from the A shape.
fn point<S>(polytope: &Polytope<'_, S>, face: &Face<S>) -> Point3<S>
where
S: BaseFloat,
{
let (u, v, w) = barycentric_vector(
face.normal * face.distance,
polytope.vertices[face.vertices[0]].v,
polytope.vertices[face.vertices[1]].v,
polytope.vertices[face.vertices[2]].v,
);
polytope.vertices[face.vertices[0]].sup_a * u
+ polytope.vertices[face.vertices[1]].sup_a.to_vec() * v
+ polytope.vertices[face.vertices[2]].sup_a.to_vec() * w
}
#[derive(Debug)]
struct Polytope<'a, S>
where
S: BaseFloat,
{
vertices: &'a mut Vec<SupportPoint<Point3<S>>>,
faces: Vec<Face<S>>,
}
impl<'a, S: 'a> Polytope<'a, S>
where
S: BaseFloat,
{
pub fn new(simplex: &'a mut Vec<SupportPoint<Point3<S>>>) -> Self {
let faces = Face::new(simplex);
Self {
vertices: simplex,
faces,
}
}
pub fn closest_face_to_origin(&'a self) -> &'a Face<S> {
let mut face = &self.faces[0];
for f in self.faces[1..].iter() {
if f.distance < face.distance {
face = f;
}
}
face
}
pub fn add(&mut self, sup: SupportPoint<Point3<S>>) {
// remove faces that can see the point
let mut edges = Vec::default();
let mut i = 0;
while i < self.faces.len() {
let dot = self.faces[i]
.normal
.dot(sup.v - self.vertices[self.faces[i].vertices[0]].v);
if dot > S::zero() {
let face = self.faces.swap_remove(i);
remove_or_add_edge(&mut edges, (face.vertices[0], face.vertices[1]));
remove_or_add_edge(&mut edges, (face.vertices[1], face.vertices[2]));
remove_or_add_edge(&mut edges, (face.vertices[2], face.vertices[0]));
} else {
i += 1;
}
}
// add vertex
let n = self.vertices.len();
self.vertices.push(sup);
// add new faces
let new_faces = edges
.into_iter()
.map(|(a, b)| Face::new_impl(self.vertices, n, a, b))
.collect::<Vec<_>>();
self.faces.extend(new_faces);
}
}
#[derive(Debug)]
struct Face<S> {
pub vertices: [usize; 3],
pub normal: Vector3<S>,
pub distance: S,
}
impl<S> Face<S>
where
S: BaseFloat,
{
fn new_impl(simplex: &[SupportPoint<Point3<S>>], a: usize, b: usize, c: usize) -> Self {
let ab = simplex[b].v - simplex[a].v;
let ac = simplex[c].v - simplex[a].v;
let normal = ab.cross(ac).normalize();
let distance = normal.dot(simplex[a].v);
Self {
vertices: [a, b, c],
normal,
distance,
}
}
pub fn new(simplex: &[SupportPoint<Point3<S>>]) -> Vec<Self> {
vec![
Self::new_impl(simplex, 3, 2, 1), // ABC
Self::new_impl(simplex, 3, 1, 0), // ACD
Self::new_impl(simplex, 3, 0, 2), // ADB
Self::new_impl(simplex, 2, 0, 1), // BDC
]
}
}
#[inline]
fn remove_or_add_edge(edges: &mut Vec<(usize, usize)>, edge: (usize, usize)) {
match edges.iter().position(|e| edge.0 == e.1 && edge.1 == e.0) {
Some(i) => {
edges.remove(i);
}
None => edges.push(edge),
}
}
#[cfg(test)]
mod tests {
use cgmath::assert_ulps_eq;
use cgmath::{Decomposed, Quaternion, Rad, Vector3};
use super::*;
use crate::primitive::*;
#[test]
fn test_remove_or_add_edge_added() {
let mut edges = vec![(1, 2), (6, 5)];
remove_or_add_edge(&mut edges, (4, 3));
assert_eq!(3, edges.len());
assert_eq!((4, 3), edges[2]);
}
#[test]
fn test_remove_or_add_edge_removed() {
let mut edges = vec![(1, 2), (6, 5)];
remove_or_add_edge(&mut edges, (2, 1));
assert_eq!(1, edges.len());
assert_eq!((6, 5), edges[0]);
}
#[test]
fn test_face_impl() {
let simplex = vec![
sup(3., -3., -1.),
sup(-3., -3., -1.),
sup(0., 3., -1.),
sup(0., 0., 5.),
];
let faces = Face::new(&simplex);
assert_eq!(4, faces.len());
assert_face(
&faces[0],
3,
2,
1,
-0.872_871_5,
0.436_435_76,
0.218_217_88,
1.091_089_4,
);
assert_face(
&faces[1],
3,
1,
0,
0.,
-0.894_427_24,
0.447_213_62,
2.236_068,
);
assert_face(
&faces[2],
3,
0,
2,
0.872_871_5,
0.436_435_76,
0.218_217_88,
1.091_089_4,
);
assert_face(&faces[3], 2, 0, 1, 0., 0., -1., 1.0);
}
#[test]
fn test_polytope_closest_to_origin() {
let mut simplex = vec![
sup(3., -3., -1.),
sup(-3., -3., -1.),
sup(0., 3., -1.),
sup(0., 0., 5.),
];
let polytope = Polytope::new(&mut simplex);
let face = polytope.closest_face_to_origin();
assert_face(face, 2, 0, 1, 0., 0., -1., 1.0);
}
#[test]
fn test_polytope_add() {
let mut simplex = vec![
sup(3., -3., -1.),
sup(-3., -3., -1.),
sup(0., 3., -1.),
sup(0., 0., 5.),
];
let mut polytope = Polytope::new(&mut simplex);
polytope.add(sup(0., 0., -2.));
assert_eq!(5, polytope.vertices.len());
assert_eq!(6, polytope.faces.len());
assert_eq!([4, 2, 0], polytope.faces[3].vertices);
assert_eq!([4, 0, 1], polytope.faces[4].vertices);
assert_eq!([4, 1, 2], polytope.faces[5].vertices);
}
#[test]
fn test_epa_3d() {
let left = Cuboid::new(10., 10., 10.);
let left_transform = transform_3d(15., 0., 0., 0.);
let right = Cuboid::new(10., 10., 10.);
let right_transform = transform_3d(7., 2., 0., 0.);
let mut simplex = vec![
sup(18., -12., 0.),
sup(-2., 8., 0.),
sup(-2., -12., 0.),
sup(8., -2., -10.),
];
let contact = EPA3::new().process(
&mut simplex,
&left,
&left_transform,
&right,
&right_transform,
);
assert!(contact.is_some());
let contact = contact.unwrap();
assert_eq!(Vector3::new(-1., 0., 0.), contact.normal);
assert!(2. - contact.penetration_depth <= f32::EPSILON);
}
fn assert_face(
face: &Face<f32>,
a: usize,
b: usize,
c: usize,
nx: f32,
ny: f32,
nz: f32,
d: f32,
) {
assert_eq!([a, b, c], face.vertices);
assert_ulps_eq!(nx, face.normal.x);
assert_ulps_eq!(ny, face.normal.y);
assert_ulps_eq!(nz, face.normal.z);
assert_ulps_eq!(d, face.distance);
}
fn sup(x: f32, y: f32, z: f32) -> SupportPoint<Point3<f32>> {
let mut s = SupportPoint::new();
s.v = Vector3::new(x, y, z);
s
}
fn transform_3d(
x: f32,
y: f32,
z: f32,
angle_z: f32,
) -> Decomposed<Vector3<f32>, Quaternion<f32>> {
Decomposed {
disp: Vector3::new(x, y, z),
rot: Quaternion::from_angle_z(Rad(angle_z)),
scale: 1.,
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/minkowski/epa/mod.rs | src/algorithm/minkowski/epa/mod.rs | //! Expanding Polytope Algorithm
pub use self::epa2d::EPA2;
pub use self::epa3d::EPA3;
mod epa2d;
mod epa3d;
use cgmath::prelude::*;
use super::SupportPoint;
use crate::prelude::*;
use crate::Contact;
pub const EPA_TOLERANCE: f32 = 0.00001;
pub const MAX_ITERATIONS: u32 = 100;
/// Expanding Polytope Algorithm base trait
pub trait EPA {
/// Point type
type Point: EuclideanSpace;
/// Process the given simplex, and compute the contact point.
///
/// The given simplex must be a complete simplex for the given space, and it must enclose the
/// origin.
fn process<SL, SR, TL, TR>(
&self,
simplex: &mut Vec<SupportPoint<Self::Point>>,
left: &SL,
left_transform: &TL,
right: &SR,
right_transform: &TR,
) -> Option<Contact<Self::Point>>
where
SL: Primitive<Point = Self::Point>,
SR: Primitive<Point = Self::Point>,
TL: Transform<Self::Point>,
TR: Transform<Self::Point>;
/// Create a new EPA instance
fn new() -> Self;
/// Create a new EPA instance with the given tolerance
fn new_with_tolerance(
tolerance: <Self::Point as EuclideanSpace>::Scalar,
max_iterations: u32,
) -> Self;
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/minkowski/gjk/mod.rs | src/algorithm/minkowski/gjk/mod.rs | //! GJK distance/collision detection algorithm. For now only have implementation of collision
//! detection, not distance computation.
pub use self::simplex::SimplexProcessor;
use std::cmp::Ordering;
use std::ops::{Neg, Range};
use cgmath::num_traits::NumCast;
use cgmath::prelude::*;
use cgmath::BaseFloat;
use cgmath::UlpsEq;
use self::simplex::{Simplex, SimplexProcessor2, SimplexProcessor3};
use crate::algorithm::minkowski::{SupportPoint, EPA, EPA2, EPA3};
use crate::prelude::*;
use crate::{CollisionStrategy, Contact};
use cgmath::ulps_eq;
mod simplex;
const MAX_ITERATIONS: u32 = 100;
const GJK_DISTANCE_TOLERANCE: f32 = 0.000_001;
const GJK_CONTINUOUS_TOLERANCE: f32 = 0.000_001;
/// GJK algorithm for 2D, see [GJK](struct.GJK.html) for more information.
pub type GJK2<S> = GJK<SimplexProcessor2<S>, EPA2<S>, S>;
/// GJK algorithm for 3D, see [GJK](struct.GJK.html) for more information.
pub type GJK3<S> = GJK<SimplexProcessor3<S>, EPA3<S>, S>;
/// Gilbert-Johnson-Keerthi narrow phase collision detection algorithm.
///
/// # Type parameters:
///
/// - `S`: simplex processor type. Should be either
/// [`SimplexProcessor2`](struct.SimplexProcessor2.html) or
/// [`SimplexProcessor3`](struct.SimplexProcessor3.html)
/// - `E`: EPA algorithm implementation type. Should be either
/// [`EPA2`](struct.EPA2.html) or
/// [`EPA3`](struct.EPA3.html)
///
#[derive(Debug)]
pub struct GJK<SP, E, S> {
simplex_processor: SP,
epa: E,
distance_tolerance: S,
continuous_tolerance: S,
max_iterations: u32,
}
impl<SP, E, S> GJK<SP, E, S>
where
SP: SimplexProcessor,
SP::Point: EuclideanSpace<Scalar = S>,
S: BaseFloat,
E: EPA<Point = SP::Point>,
{
/// Create a new GJK algorithm implementation
pub fn new() -> Self {
Self {
simplex_processor: SP::new(),
epa: E::new(),
distance_tolerance: NumCast::from(GJK_DISTANCE_TOLERANCE).unwrap(),
continuous_tolerance: NumCast::from(GJK_CONTINUOUS_TOLERANCE).unwrap(),
max_iterations: MAX_ITERATIONS,
}
}
/// Create a new GJK algorithm implementation with the given tolerance settings
pub fn new_with_settings(
distance_tolerance: S,
continuous_tolerance: S,
epa_tolerance: S,
max_iterations: u32,
) -> Self {
Self {
simplex_processor: SP::new(),
epa: E::new_with_tolerance(epa_tolerance, max_iterations),
distance_tolerance,
continuous_tolerance,
max_iterations,
}
}
/// Do intersection test on the given primitives
///
/// ## Parameters:
///
/// - `left`: left primitive
/// - `left_transform`: model-to-world-transform for the left primitive
/// - `right`: right primitive,
/// - `right_transform`: model-to-world-transform for the right primitive
///
/// ## Returns:
///
/// Will return a simplex if a collision was detected. For 2D, the simplex will be a triangle,
/// for 3D, it will be a tetrahedron. The simplex will enclose the origin.
/// If no collision was detected, None is returned.
///
pub fn intersect<P, PL, PR, TL, TR>(
&self,
left: &PL,
left_transform: &TL,
right: &PR,
right_transform: &TR,
) -> Option<Simplex<P>>
where
P: EuclideanSpace<Scalar = S>,
PL: Primitive<Point = P>,
PR: Primitive<Point = P>,
SP: SimplexProcessor<Point = P>,
P::Diff: Neg<Output = P::Diff> + InnerSpace + Zero + Array<Element = S> + UlpsEq,
TL: Transform<P>,
TR: Transform<P>,
{
let left_pos = left_transform.transform_point(P::origin());
let right_pos = right_transform.transform_point(P::origin());
let mut d = right_pos - left_pos;
if ulps_eq!(d, P::Diff::zero()) {
d = P::Diff::from_value(S::one());
}
let a = SupportPoint::from_minkowski(left, left_transform, right, right_transform, &d);
if a.v.dot(d) <= S::zero() {
return None;
}
let mut simplex = Simplex::new();
simplex.push(a);
d = d.neg();
for _ in 0..self.max_iterations {
let a = SupportPoint::from_minkowski(left, left_transform, right, right_transform, &d);
if a.v.dot(d) <= S::zero() {
return None;
} else {
simplex.push(a);
if self
.simplex_processor
.reduce_to_closest_feature(&mut simplex, &mut d)
{
return Some(simplex);
}
}
}
None
}
/// Do time of impact intersection testing on the given primitives, and return a valid contact
/// at the time of impact.
///
/// ## Parameters:
///
/// - `left`: left primitive
/// - `left_transform`: model-to-world-transform for the left primitive
/// - `right`: right primitive,
/// - `right_transform`: model-to-world-transform for the right primitive
///
/// ## Returns:
///
/// Will optionally return a contact manifold at the time of impact. If no collision was
/// detected, None is returned.
#[allow(unused_variables)]
pub fn intersection_time_of_impact<P, PL, PR, TL, TR>(
&self,
left: &PL,
left_transform: &Range<&TL>,
right: &PR,
right_transform: &Range<&TR>,
) -> Option<Contact<P>>
where
P: EuclideanSpace<Scalar = S>,
PL: Primitive<Point = P>,
PR: Primitive<Point = P>,
SP: SimplexProcessor<Point = P>,
P::Diff: Neg<Output = P::Diff> + InnerSpace + Zero + Array<Element = S>,
TL: Transform<P> + TranslationInterpolate<S>,
TR: Transform<P> + TranslationInterpolate<S>,
{
// build the ray, A.velocity - B.velocity is the ray direction
let left_lin_vel = left_transform.end.transform_point(P::origin())
- left_transform.start.transform_point(P::origin());
let right_lin_vel = right_transform.end.transform_point(P::origin())
- right_transform.start.transform_point(P::origin());
let ray = right_lin_vel - left_lin_vel;
// initialize time of impact
let mut lambda = S::zero();
let mut normal = P::Diff::zero();
let mut ray_origin = P::origin();
// build simplex and get an initial support point to bootstrap the algorithm
let mut simplex = Simplex::new();
let p = SupportPoint::from_minkowski(
left,
left_transform.start,
right,
right_transform.start,
&-ray,
);
// we only need the actual support point for this
let mut v = p.v;
// if the squared magnitude is small enough, we have a hit and can stop
while v.magnitude2() > self.continuous_tolerance {
// get a new support point
let p = SupportPoint::from_minkowski(
left,
left_transform.start,
right,
right_transform.start,
&-v,
);
let vp = v.dot(p.v);
let vr = v.dot(ray);
// check if we have a hit point along the ray further than the current clipped ray
if vp > lambda * vr {
// if the hit point is in the positive ray direction, we clip the ray, clear
// the simplex and start over from a new ray origin
if vr > S::zero() {
lambda = vp / vr;
// if the clipped hit point is beyond the end of the ray,
// we can never have a hit
if lambda > S::one() {
return None;
}
ray_origin = P::from_vec(ray * lambda);
simplex.clear();
normal = -v;
} else {
// if the hitpoint is behind the ray origin, we can never have a hit
return None;
}
}
// we construct the simplex around the current ray origin (if we can)
simplex.push(p - ray_origin);
v = self
.simplex_processor
.get_closest_point_to_origin(&mut simplex);
}
if v.magnitude2() <= self.continuous_tolerance {
let transform = right_transform
.start
.translation_interpolate(right_transform.end, lambda);
let mut contact = Contact::new_with_point(
CollisionStrategy::FullResolution,
-normal.normalize(), // our convention is normal points from B towards A
v.magnitude(), // will always be very close to zero
transform.transform_point(ray_origin),
);
contact.time_of_impact = lambda;
Some(contact)
} else {
None
}
}
/// Compute the distance between the given primitives.
///
/// ## Parameters:
///
/// - `left`: left primitive
/// - `left_transform`: model-to-world-transform for the left primitive
/// - `right`: right primitive,
/// - `right_transform`: model-to-world-transform for the right primitive
///
/// ## Returns:
///
/// Will optionally return the distance between the objects. Will return None, if the objects
/// are colliding.
pub fn distance<P, PL, PR, TL, TR>(
&self,
left: &PL,
left_transform: &TL,
right: &PR,
right_transform: &TR,
) -> Option<S>
where
P: EuclideanSpace<Scalar = S>,
PL: Primitive<Point = P>,
PR: Primitive<Point = P>,
SP: SimplexProcessor<Point = P>,
P::Diff: Neg<Output = P::Diff> + InnerSpace + Zero + Array<Element = S> + UlpsEq,
TL: Transform<P>,
TR: Transform<P>,
{
let zero = P::Diff::zero();
let right_pos = right_transform.transform_point(P::origin());
let left_pos = left_transform.transform_point(P::origin());
let mut simplex = Simplex::new();
let mut d = right_pos - left_pos;
if ulps_eq!(d, P::Diff::zero()) {
d = P::Diff::from_value(S::one());
}
for d in &[d, d.neg()] {
simplex.push(SupportPoint::from_minkowski(
left,
left_transform,
right,
right_transform,
d,
));
}
for _ in 0..self.max_iterations {
let d = self
.simplex_processor
.get_closest_point_to_origin(&mut simplex);
if ulps_eq!(d, zero) {
return None;
}
let d = d.neg();
let p = SupportPoint::from_minkowski(left, left_transform, right, right_transform, &d);
let dp = p.v.dot(d);
let d0 = simplex[0].v.dot(d);
if dp - d0 < self.distance_tolerance {
return Some(d.magnitude());
}
simplex.push(p);
}
None
}
/// Given a GJK simplex that encloses the origin, compute the contact manifold.
///
/// Uses the EPA algorithm to find the contact information from the simplex.
pub fn get_contact_manifold<P, PL, PR, TL, TR>(
&self,
mut simplex: &mut Vec<SupportPoint<P>>,
left: &PL,
left_transform: &TL,
right: &PR,
right_transform: &TR,
) -> Option<Contact<P>>
where
P: EuclideanSpace<Scalar = S>,
PL: Primitive<Point = P>,
PR: Primitive<Point = P>,
TL: Transform<P>,
TR: Transform<P>,
SP: SimplexProcessor<Point = P>,
{
self.epa
.process(&mut simplex, left, left_transform, right, right_transform)
}
/// Do intersection testing on the given primitives, and return the contact manifold.
///
/// ## Parameters:
///
/// - `strategy`: strategy to use, if `CollisionOnly` it will only return a boolean result,
/// otherwise, EPA will be used to compute the exact contact point.
/// - `left`: left primitive
/// - `left_transform`: model-to-world-transform for the left primitive
/// - `right`: right primitive,
/// - `right_transform`: model-to-world-transform for the right primitive
///
/// ## Returns:
///
/// Will optionally return a `Contact` if a collision was detected. In `CollisionOnly` mode,
/// this contact will only be a boolean result. For `FullResolution` mode, the contact will
/// contain a full manifold (collision normal, penetration depth and contact point).
pub fn intersection<P, PL, PR, TL, TR>(
&self,
strategy: &CollisionStrategy,
left: &PL,
left_transform: &TL,
right: &PR,
right_transform: &TR,
) -> Option<Contact<P>>
where
P: EuclideanSpace<Scalar = S>,
P::Diff: Neg<Output = P::Diff> + InnerSpace + Zero + Array<Element = S> + UlpsEq,
PL: Primitive<Point = P>,
PR: Primitive<Point = P>,
TL: Transform<P>,
TR: Transform<P>,
SP: SimplexProcessor<Point = P>,
{
use CollisionStrategy::*;
self.intersect(left, left_transform, right, right_transform)
.and_then(|simplex| match *strategy {
CollisionOnly => Some(Contact::new(CollisionOnly)),
FullResolution => self.get_contact_manifold(
&mut simplex.into_vec(),
left,
left_transform,
right,
right_transform,
),
})
}
/// Do intersection test on the given complex shapes, and return the actual intersection point
///
/// ## Parameters:
///
/// - `strategy`: strategy to use, if `CollisionOnly` it will only return a boolean result,
/// otherwise, EPA will be used to compute the exact contact point.
/// - `left`: shape consisting of a slice of primitive + local-to-model-transform for each
/// primitive,
/// - `left_transform`: model-to-world-transform for the left shape
/// - `right`: shape consisting of a slice of primitive + local-to-model-transform for each
/// primitive,
/// - `right_transform`: model-to-world-transform for the right shape
///
/// ## Returns:
///
/// Will optionally return a `Contact` if a collision was detected. In `CollisionOnly` mode,
/// this contact will only be a boolean result. For `FullResolution` mode, the contact will
/// contain a full manifold (collision normal, penetration depth and contact point), for the
/// contact with the highest penetration depth.
pub fn intersection_complex<P, PL, PR, TL, TR>(
&self,
strategy: &CollisionStrategy,
left: &[(PL, TL)],
left_transform: &TL,
right: &[(PR, TR)],
right_transform: &TR,
) -> Option<Contact<P>>
where
P: EuclideanSpace<Scalar = S>,
P::Diff: Neg<Output = P::Diff> + InnerSpace + Zero + Array<Element = S> + UlpsEq,
PL: Primitive<Point = P>,
PR: Primitive<Point = P>,
TL: Transform<P>,
TR: Transform<P>,
SP: SimplexProcessor<Point = P>,
{
use CollisionStrategy::*;
let mut contacts = Vec::default();
for &(ref left_primitive, ref left_local_transform) in left.iter() {
let left_transform = left_transform.concat(left_local_transform);
for &(ref right_primitive, ref right_local_transform) in right.iter() {
let right_transform = right_transform.concat(right_local_transform);
if let Some(contact) = self.intersection(
strategy,
left_primitive,
&left_transform,
right_primitive,
&right_transform,
) {
match *strategy {
CollisionOnly => {
return Some(contact);
}
FullResolution => contacts.push(contact),
}
}
}
}
// CollisionOnly handling will have returned already if there was a contact, so this
// scenario will only happen when we have a contact in FullResolution mode, or no contact
// at all.
contacts.into_iter().max_by(|l, r| {
// Penetration depth defaults to 0., and can't be nan from EPA,
// so unwrapping is safe
l.penetration_depth
.partial_cmp(&r.penetration_depth)
.unwrap()
})
}
/// Compute the distance between the given shapes.
///
/// ## Parameters:
///
/// - `left`: left shape
/// - `left_transform`: model-to-world-transform for the left shape
/// - `right`: right shape,
/// - `right_transform`: model-to-world-transform for the right shape
///
/// ## Returns:
///
/// Will optionally return the smallest distance between the objects. Will return None, if the
/// objects are colliding.
pub fn distance_complex<P, PL, PR, TL, TR>(
&self,
left: &[(PL, TL)],
left_transform: &TL,
right: &[(PR, TR)],
right_transform: &TR,
) -> Option<S>
where
P: EuclideanSpace<Scalar = S>,
P::Diff: Neg<Output = P::Diff> + InnerSpace + Zero + Array<Element = S> + UlpsEq,
PL: Primitive<Point = P>,
PR: Primitive<Point = P>,
TL: Transform<P>,
TR: Transform<P>,
SP: SimplexProcessor<Point = P>,
{
let mut min_distance = None;
for &(ref left_primitive, ref left_local_transform) in left.iter() {
let left_transform = left_transform.concat(left_local_transform);
for &(ref right_primitive, ref right_local_transform) in right.iter() {
let right_transform = right_transform.concat(right_local_transform);
match self.distance(
left_primitive,
&left_transform,
right_primitive,
&right_transform,
) {
None => return None, // colliding,
Some(distance) => {
min_distance = Some(
min_distance
.map_or(distance, |min_distance| distance.min(min_distance)),
);
}
}
}
}
min_distance
}
/// Do intersection time of impact test on the given complex shapes, and return the contact at
/// the time of impact
///
/// ## Parameters:
///
/// - `strategy`: strategy to use, if `CollisionOnly` it will only return a boolean result,
/// otherwise, a full contact manifold will be returned.
/// - `left`: shape consisting of a slice of primitive + local-to-model-transform for each
/// primitive,
/// - `left_transform`: model-to-world-transform for the left shape
/// - `right`: shape consisting of a slice of primitive + local-to-model-transform for each
/// primitive,
/// - `right_transform`: model-to-world-transform for the right shape
///
/// ## Returns:
///
/// Will optionally return the contact if a collision was detected.
/// In `CollisionOnly` mode, this contact will only be a time of impact. For `FullResolution`
/// mode, the time of impact will be the earliest found among all shape primitives.
/// Will return None if no collision was found.
pub fn intersection_complex_time_of_impact<P, PL, PR, TL, TR>(
&self,
strategy: &CollisionStrategy,
left: &[(PL, TL)],
left_transform: &Range<&TL>,
right: &[(PR, TR)],
right_transform: &Range<&TR>,
) -> Option<Contact<P>>
where
P: EuclideanSpace<Scalar = S>,
P::Diff: Neg<Output = P::Diff> + InnerSpace + Zero + Array<Element = S>,
PL: Primitive<Point = P>,
PR: Primitive<Point = P>,
TL: Transform<P> + TranslationInterpolate<S>,
TR: Transform<P> + TranslationInterpolate<S>,
SP: SimplexProcessor<Point = P>,
{
use CollisionStrategy::*;
let mut contacts = Vec::default();
for &(ref left_primitive, ref left_local_transform) in left.iter() {
let left_start_transform = left_transform.start.concat(left_local_transform);
let left_end_transform = left_transform.end.concat(left_local_transform);
for &(ref right_primitive, ref right_local_transform) in right.iter() {
let right_start_transform = right_transform.start.concat(right_local_transform);
let right_end_transform = right_transform.end.concat(right_local_transform);
if let Some(mut contact) = self.intersection_time_of_impact(
left_primitive,
&(&left_start_transform..&left_end_transform),
right_primitive,
&(&right_start_transform..&right_end_transform),
) {
match *strategy {
CollisionOnly => {
contact.strategy = CollisionOnly;
return Some(contact);
}
FullResolution => contacts.push(contact),
}
}
}
}
// CollisionOnly handling will have returned already if there was a contact, so this
// scenario will only happen when we have a contact in FullResolution mode or no contact
// at all
contacts.into_iter().min_by(|l, r| {
l.time_of_impact
.partial_cmp(&r.time_of_impact)
.unwrap_or(Ordering::Equal)
})
}
}
#[cfg(test)]
mod tests {
use cgmath::assert_ulps_eq;
use cgmath::{
Basis2, Decomposed, Point2, Point3, Quaternion, Rad, Rotation2, Rotation3, Vector2, Vector3,
};
use super::*;
use crate::primitive::*;
fn transform(x: f32, y: f32, angle: f32) -> Decomposed<Vector2<f32>, Basis2<f32>> {
Decomposed {
disp: Vector2::new(x, y),
rot: Rotation2::from_angle(Rad(angle)),
scale: 1.,
}
}
fn transform_3d(
x: f32,
y: f32,
z: f32,
angle_z: f32,
) -> Decomposed<Vector3<f32>, Quaternion<f32>> {
Decomposed {
disp: Vector3::new(x, y, z),
rot: Quaternion::from_angle_z(Rad(angle_z)),
scale: 1.,
}
}
#[test]
fn test_gjk_exact() {
let shape = Rectangle::new(1., 1.);
let t = transform(0., 0., 0.);
let gjk = GJK2::new();
let p = gjk.intersection(&CollisionStrategy::FullResolution, &shape, &t, &shape, &t);
assert!(p.is_some());
let d = gjk.distance(&shape, &t, &shape, &t);
assert!(d.is_none());
}
#[test]
fn test_gjk_exact_3d() {
let shape = Cuboid::new(1., 1., 1.);
let t = transform_3d(0., 0., 0., 0.);
let gjk = GJK3::new();
let p = gjk.intersection(&CollisionStrategy::FullResolution, &shape, &t, &shape, &t);
assert!(p.is_some());
let d = gjk.distance(&shape, &t, &shape, &t);
assert!(d.is_none());
}
#[test]
fn test_gjk_sphere() {
let shape = Sphere::new(1.);
let t = transform_3d(0., 0., 0., 0.);
let gjk = GJK3::new();
let p = gjk.intersection(&CollisionStrategy::FullResolution, &shape, &t, &shape, &t);
assert!(p.is_some());
let d = gjk.distance(&shape, &t, &shape, &t);
assert!(d.is_none());
}
#[test]
fn test_gjk_miss() {
let left = Rectangle::new(10., 10.);
let left_transform = transform(15., 0., 0.);
let right = Rectangle::new(10., 10.);
let right_transform = transform(-15., 0., 0.);
let gjk = GJK2::new();
assert!(gjk
.intersect(&left, &left_transform, &right, &right_transform)
.is_none());
assert!(gjk
.intersection(
&CollisionStrategy::FullResolution,
&left,
&left_transform,
&right,
&right_transform
)
.is_none());
}
#[test]
fn test_gjk_hit() {
let left = Rectangle::new(10., 10.);
let left_transform = transform(15., 0., 0.);
let right = Rectangle::new(10., 10.);
let right_transform = transform(7., 2., 0.);
let gjk = GJK2::new();
let simplex = gjk.intersect(&left, &left_transform, &right, &right_transform);
assert!(simplex.is_some());
let contact = gjk.intersection(
&CollisionStrategy::FullResolution,
&left,
&left_transform,
&right,
&right_transform,
);
assert!(contact.is_some());
let contact = contact.unwrap();
assert_eq!(Vector2::new(-1., 0.), contact.normal);
assert!(2. - contact.penetration_depth <= f32::EPSILON);
assert_eq!(Point2::new(10., 1.), contact.contact_point);
}
#[test]
fn test_gjk_3d_hit() {
let left = Cuboid::new(10., 10., 10.);
let left_transform = transform_3d(15., 0., 0., 0.);
let right = Cuboid::new(10., 10., 10.);
let right_transform = transform_3d(7., 2., 0., 0.);
let gjk = GJK3::new();
let simplex = gjk.intersect(&left, &left_transform, &right, &right_transform);
assert!(simplex.is_some());
let contact = gjk.intersection(
&CollisionStrategy::FullResolution,
&left,
&left_transform,
&right,
&right_transform,
);
assert!(contact.is_some());
let contact = contact.unwrap();
assert_eq!(Vector3::new(-1., 0., 0.), contact.normal);
assert!(2. - contact.penetration_depth <= f32::EPSILON);
assert_ulps_eq!(Point3::new(10., 1., 5.), contact.contact_point);
}
#[test]
fn test_gjk_distance_2d() {
let left = Rectangle::new(10., 10.);
let left_transform = transform(15., 0., 0.);
let right = Rectangle::new(10., 10.);
let right_transform = transform(0., 0., 0.);
let gjk = GJK2::new();
assert_eq!(
Some(5.),
gjk.distance(&left, &left_transform, &right, &right_transform)
);
// intersects
let right_transform = transform(7., 2., 0.);
assert_eq!(
None,
gjk.distance(&left, &left_transform, &right, &right_transform)
);
}
#[test]
fn test_gjk_distance_3d() {
let left = Cuboid::new(10., 10., 10.);
let left_transform = transform_3d(15., 0., 0., 0.);
let right = Cuboid::new(10., 10., 10.);
let right_transform = transform_3d(7., 2., 0., 0.);
let gjk = GJK3::new();
assert_eq!(
None,
gjk.distance(&left, &left_transform, &right, &right_transform)
);
let right_transform = transform_3d(1., 0., 0., 0.);
assert_eq!(
Some(4.),
gjk.distance(&left, &left_transform, &right, &right_transform)
);
}
#[test]
fn test_gjk_time_of_impact_2d() {
let left = Rectangle::new(10., 20.);
let left_start_transform = transform(0., 0., 0.);
let left_end_transform = transform(30., 0., 0.);
let right = Rectangle::new(10., 11.);
let right_transform = transform(15., 0., 0.);
let gjk = GJK2::new();
let contact = gjk
.intersection_time_of_impact(
&left,
&(&left_start_transform..&left_end_transform),
&right,
&(&right_transform..&right_transform),
)
.unwrap();
assert_ulps_eq!(0.166_666_7, contact.time_of_impact);
assert_eq!(Vector2::new(-1., 0.), contact.normal);
assert!(0. - contact.penetration_depth <= f32::EPSILON);
assert_eq!(Point2::new(10., 0.), contact.contact_point);
assert!(gjk
.intersection_time_of_impact(
&left,
&(&left_start_transform..&left_start_transform),
&right,
&(&right_transform..&right_transform)
)
.is_none());
}
#[test]
fn test_gjk_time_of_impact_3d() {
let left = Cuboid::new(10., 11., 10.);
let left_start_transform = transform_3d(0., 0., 0., 0.);
let left_end_transform = transform_3d(30., 0., 0., 0.);
let right = Cuboid::new(10., 15., 10.);
let right_transform = transform_3d(15., 0., 0., 0.);
let gjk = GJK3::new();
let contact = gjk
.intersection_time_of_impact(
&left,
&(&left_start_transform..&left_end_transform),
&right,
&(&right_transform..&right_transform),
)
.unwrap();
assert_ulps_eq!(0.166_666_7, contact.time_of_impact);
assert_eq!(Vector3::new(-1., 0., 0.), contact.normal);
assert!(0. - contact.penetration_depth <= f32::EPSILON);
assert_eq!(Point3::new(10., 0., 0.), contact.contact_point);
assert!(gjk
.intersection_time_of_impact(
&left,
&(&left_start_transform..&left_start_transform),
&right,
&(&right_transform..&right_transform)
)
.is_none());
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/minkowski/gjk/simplex/simplex3d.rs | src/algorithm/minkowski/gjk/simplex/simplex3d.rs | use std::marker;
use std::ops::Neg;
use cgmath::num_traits::cast;
use cgmath::prelude::*;
use cgmath::ulps_eq;
use cgmath::{BaseFloat, Point3, Vector3};
use super::{Simplex, SimplexProcessor};
use crate::primitive::util::{barycentric_vector, get_closest_point_on_edge};
/// Simplex processor implementation for 3D. Only to be used in [`GJK`](struct.GJK.html).
#[derive(Debug)]
pub struct SimplexProcessor3<S> {
m: marker::PhantomData<S>,
}
impl<S> SimplexProcessor for SimplexProcessor3<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn reduce_to_closest_feature(
&self,
simplex: &mut Simplex<Point3<S>>,
v: &mut Vector3<S>,
) -> bool {
// 4 points, full tetrahedron, origin could be inside
if simplex.len() == 4 {
let a = simplex[3].v;
let b = simplex[2].v;
let c = simplex[1].v;
let d = simplex[0].v;
let ao = a.neg();
let ab = b - a;
let ac = c - a;
let abc = ab.cross(ac);
// origin outside plane ABC, remove D and check side
// need to check both edges
if abc.dot(ao) > S::zero() {
simplex.remove(0);
check_side(&abc, &ab, &ac, &ao, simplex, v, true, false);
} else {
let ad = d - a;
let acd = ac.cross(ad);
// origin outside plane ACD, remove B and check side
// no need to test first edge, since that region is also over ABC
if acd.dot(ao) > S::zero() {
simplex.remove(2);
check_side(&acd, &ac, &ad, &ao, simplex, v, true, true);
} else {
let adb = ad.cross(ab);
// origin outside plane ADB, remove C and check side
// no need to test edges, since those regions are covered in earlier tests
if adb.dot(ao) > S::zero() {
// [b, d, a]
simplex.remove(1);
simplex.swap(0, 1);
*v = adb;
// origin is inside simplex
} else {
return true;
}
}
}
}
// 3 points, can't do origin check, find closest feature to origin, and move that way
else if simplex.len() == 3 {
let a = simplex[2].v;
let b = simplex[1].v;
let c = simplex[0].v;
let ao = a.neg();
let ab = b - a;
let ac = c - a;
check_side(&ab.cross(ac), &ab, &ac, &ao, simplex, v, false, false);
}
// 2 points, can't do much with only an edge, only find a new search direction
else if simplex.len() == 2 {
let a = simplex[1].v;
let b = simplex[0].v;
let ao = a.neg();
let ab = b - a;
*v = cross_aba(&ab, &ao);
if ulps_eq!(*v, Vector3::zero()) {
v.x = cast(0.1).unwrap();
}
}
// 0-1 points
false
}
/// Get the closest point on the simplex to the origin.
///
/// Make simplex only retain the closest feature to the origin.
fn get_closest_point_to_origin(&self, simplex: &mut Simplex<Point3<S>>) -> Vector3<S> {
let mut d = Vector3::zero();
// reduce simplex to the closest feature to the origin
// if check_origin return true, the origin is inside the simplex, so return the zero vector
// if not, the simplex will be the closest face or edge to the origin, and d the normal of
// the feature in the direction of the origin
if self.reduce_to_closest_feature(simplex, &mut d) {
return d;
}
if simplex.len() == 1 {
simplex[0].v
} else if simplex.len() == 2 {
get_closest_point_on_edge(&simplex[1].v, &simplex[0].v, &Vector3::zero())
} else {
get_closest_point_on_face(&simplex[2].v, &simplex[1].v, &simplex[0].v, &d)
}
}
fn new() -> Self {
Self {
m: marker::PhantomData,
}
}
}
#[inline]
fn get_closest_point_on_face<S>(
a: &Vector3<S>,
b: &Vector3<S>,
c: &Vector3<S>,
normal: &Vector3<S>,
) -> Vector3<S>
where
S: BaseFloat,
{
use crate::{Continuous, Plane, Ray3};
let ap = Point3::from_vec(*a);
let bp = Point3::from_vec(*b);
let cp = Point3::from_vec(*c);
let ray = Ray3::new(Point3::origin(), -*normal);
// unwrapping is safe, because the degenerate face will have been removed by the outer algorithm
let plane = Plane::from_points(ap, bp, cp).unwrap();
match plane.intersection(&ray) {
Some(point) => {
let (u, v, w) = barycentric_vector(point.to_vec(), *a, *b, *c);
assert!(
in_range(u) && in_range(v) && in_range(w),
"Simplex processing failed to deduce that this simplex {:?} is an edge case",
[a, b, c]
);
point.to_vec()
}
_ => Vector3::zero(),
}
}
#[inline]
fn in_range<S>(v: S) -> bool
where
S: BaseFloat,
{
v >= S::zero() && v <= S::one()
}
#[inline]
fn cross_aba<S>(a: &Vector3<S>, b: &Vector3<S>) -> Vector3<S>
where
S: BaseFloat,
{
a.cross(*b).cross(*a)
}
#[inline]
fn check_side<S>(
abc: &Vector3<S>,
ab: &Vector3<S>,
ac: &Vector3<S>,
ao: &Vector3<S>,
simplex: &mut Simplex<Point3<S>>,
v: &mut Vector3<S>,
above: bool,
ignore_ab: bool,
) where
S: BaseFloat,
{
let ab_perp = ab.cross(*abc);
// origin outside AB, remove C and v = edge normal towards origin
if !ignore_ab && ab_perp.dot(*ao) > S::zero() {
simplex.remove(0);
*v = cross_aba(ab, ao);
return;
}
let ac_perp = abc.cross(*ac);
// origin outside AC, remove B and v = edge normal towards origin
if ac_perp.dot(*ao) > S::zero() {
simplex.remove(1);
*v = cross_aba(ac, ao);
return;
// origin above triangle, set v = surface normal towards origin
}
if above || abc.dot(*ao) > S::zero() {
// [c, b, a]
*v = *abc;
// origin below triangle, rewind simplex and set v = surface normal towards origin
} else {
// [b, c, a]
simplex.swap(0, 1);
*v = abc.neg();
}
}
#[cfg(test)]
mod tests {
use std::ops::Neg;
use cgmath::assert_ulps_eq;
use cgmath::{Point3, Vector3};
use smallvec::smallvec;
use super::*;
use crate::algorithm::minkowski::SupportPoint;
#[test]
fn test_check_side_outside_ab() {
let mut simplex = smallvec![sup(8., -10., 0.), sup(-1., -10., 0.), sup(3., 5., 0.)];
let v = test_check_side(&mut simplex, false, false);
assert_eq!(2, simplex.len());
assert_eq!(Vector3::new(-1., -10., 0.), simplex[0].v); // B should be last in the simplex
assert_ulps_eq!(-375., v.x);
assert_ulps_eq!(100., v.y);
assert_ulps_eq!(0., v.z);
}
#[test]
fn test_check_side_outside_ac() {
let mut simplex = smallvec![sup(2., -10., 0.), sup(-7., -10., 0.), sup(-3., 5., 0.)];
let v = test_check_side(&mut simplex, false, false);
assert_eq!(2, simplex.len());
assert_eq!(Vector3::new(2., -10., 0.), simplex[0].v); // C should be last in the simplex
assert_ulps_eq!(300., v.x);
assert_ulps_eq!(100., v.y);
assert_ulps_eq!(0., v.z);
}
#[test]
fn test_check_side_above() {
let mut simplex = smallvec![sup(5., -10., -1.), sup(-4., -10., -1.), sup(0., 5., -1.)];
let v = test_check_side(&mut simplex, false, false);
assert_eq!(3, simplex.len());
assert_eq!(Vector3::new(5., -10., -1.), simplex[0].v); // C should be last in the simplex
assert_ulps_eq!(0., v.x);
assert_ulps_eq!(0., v.y);
assert_ulps_eq!(135., v.z);
}
#[test]
fn test_check_side_below() {
let mut simplex = smallvec![sup(5., -10., 1.), sup(-4., -10., 1.), sup(0., 5., 1.)];
let v = test_check_side(&mut simplex, false, false);
assert_eq!(3, simplex.len());
assert_eq!(Vector3::new(-4., -10., 1.), simplex[0].v); // B should be last in the simplex
assert_ulps_eq!(0., v.x);
assert_ulps_eq!(0., v.y);
assert_ulps_eq!(-135., v.z);
}
#[test]
fn test_check_origin_empty() {
let mut simplex = smallvec![];
let (hit, v) = test_check_origin(&mut simplex);
assert!(!hit);
assert!(simplex.is_empty());
assert_eq!(Vector3::zero(), v);
}
#[test]
fn test_check_origin_point() {
let mut simplex = smallvec![sup(8., -10., 0.)];
let (hit, v) = test_check_origin(&mut simplex);
assert!(!hit);
assert_eq!(1, simplex.len());
assert_eq!(Vector3::zero(), v);
}
#[test]
fn test_check_origin_line() {
let mut simplex = smallvec![sup(8., -10., 0.), sup(-1., -10., 0.)];
let (hit, v) = test_check_origin(&mut simplex);
assert!(!hit);
assert_eq!(2, simplex.len());
assert_eq!(Vector3::new(0., 810., 0.), v);
}
#[test]
fn test_check_origin_triangle() {
let mut simplex = smallvec![sup(5., -10., -1.), sup(-4., -10., -1.), sup(0., 5., -1.)];
let (hit, v) = test_check_origin(&mut simplex);
assert!(!hit);
assert_eq!(3, simplex.len());
assert_eq!(Vector3::new(0., 0., 135.), v);
}
#[test]
fn test_check_origin_tetrahedron_outside_abc() {
let mut simplex = smallvec![
sup(8., -10., -1.),
sup(-1., -10., -1.),
sup(3., 5., -1.),
sup(3., -3., 5.)
];
let (hit, v) = test_check_origin(&mut simplex);
assert!(!hit);
assert_eq!(3, simplex.len());
assert_eq!(Vector3::new(-1., -10., -1.), simplex[0].v);
assert_eq!(Vector3::new(-90., 24., 32.), v);
}
#[test]
fn test_check_origin_tetrahedron_outside_acd() {
let mut simplex = smallvec![
sup(8., 0.1, -1.),
sup(-1., 0.1, -1.),
sup(3., 15., -1.),
sup(3., 7., 5.)
];
let (hit, v) = test_check_origin(&mut simplex);
assert!(!hit);
assert_eq!(3, simplex.len());
assert_eq!(Vector3::new(3., 7., 5.), simplex[2].v);
assert_eq!(Vector3::new(-1., 0.1, -1.), simplex[1].v);
assert_eq!(Vector3::new(8., 0.1, -1.), simplex[0].v);
assert_eq!(Vector3::new(0., -54., 62.1), v);
}
#[test]
fn test_check_origin_tetrahedron_outside_adb() {
let mut simplex = smallvec![
sup(2., -10., -1.),
sup(-7., -10., -1.),
sup(-3., 5., -1.),
sup(-3., -3., 5.)
];
let (hit, v) = test_check_origin(&mut simplex);
assert!(!hit);
assert_eq!(3, simplex.len());
assert_eq!(Vector3::new(-3., -3., 5.), simplex[2].v);
assert_eq!(Vector3::new(2., -10., -1.), simplex[1].v);
assert_eq!(Vector3::new(-3., 5., -1.), simplex[0].v);
assert_eq!(Vector3::new(90., 30., 40.), v);
}
#[test]
fn test_check_origin_tetrahedron_inside() {
let mut simplex = smallvec![
sup(3., -3., -1.),
sup(-3., -3., -1.),
sup(0., 3., -1.),
sup(0., 0., 5.)
];
let (hit, _) = test_check_origin(&mut simplex);
assert!(hit);
assert_eq!(4, simplex.len());
}
fn test_check_origin(simplex: &mut Simplex<Point3<f32>>) -> (bool, Vector3<f32>) {
let mut v = Vector3::zero();
let b = SimplexProcessor3::new().reduce_to_closest_feature(simplex, &mut v);
(b, v)
}
fn test_check_side(
simplex: &mut Simplex<Point3<f32>>,
above: bool,
ignore: bool,
) -> Vector3<f32> {
let ab = simplex[1].v - simplex[2].v;
let ac = simplex[0].v - simplex[2].v;
let ao = simplex[2].v.neg();
let abc = ab.cross(ac);
let mut v = Vector3::zero();
check_side(&abc, &ab, &ac, &ao, simplex, &mut v, above, ignore);
v
}
fn sup(x: f32, y: f32, z: f32) -> SupportPoint<Point3<f32>> {
let mut s = SupportPoint::new();
s.v = Vector3::new(x, y, z);
s
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/minkowski/gjk/simplex/simplex2d.rs | src/algorithm/minkowski/gjk/simplex/simplex2d.rs | use std::marker;
use std::ops::Neg;
use cgmath::prelude::*;
use cgmath::ulps_eq;
use cgmath::{BaseFloat, Point2, Vector2};
use super::{Simplex, SimplexProcessor};
use crate::primitive::util::{get_closest_point_on_edge, triple_product};
/// Simplex processor implementation for 2D. Only to be used in [`GJK`](struct.GJK.html).
#[derive(Debug)]
pub struct SimplexProcessor2<S> {
m: marker::PhantomData<S>,
}
impl<S> SimplexProcessor for SimplexProcessor2<S>
where
S: BaseFloat,
{
type Point = Point2<S>;
fn reduce_to_closest_feature(
&self,
simplex: &mut Simplex<Point2<S>>,
d: &mut Vector2<S>,
) -> bool {
// 3 points
if simplex.len() == 3 {
let a = simplex[2].v;
let b = simplex[1].v;
let c = simplex[0].v;
let ao = a.neg();
let ab = b - a;
let ac = c - a;
let abp = triple_product(&ac, &ab, &ab);
if abp.dot(ao) > S::zero() {
simplex.remove(0);
*d = abp;
} else {
let acp = triple_product(&ab, &ac, &ac);
if acp.dot(ao) > S::zero() {
simplex.remove(1);
*d = acp;
} else {
return true;
}
}
}
// 2 points
else if simplex.len() == 2 {
let a = simplex[1].v;
let b = simplex[0].v;
let ao = a.neg();
let ab = b - a;
*d = triple_product(&ab, &ao, &ab);
if ulps_eq!(*d, Vector2::zero()) {
*d = Vector2::new(-ab.y, ab.x);
}
}
// 0-1 point means we can't really do anything
false
}
/// Get the closest point on the simplex to the origin.
///
/// Make simplex only retain the closest feature to the origin.
fn get_closest_point_to_origin(&self, simplex: &mut Simplex<Point2<S>>) -> Vector2<S> {
let mut d = Vector2::zero();
// reduce simplex to the closest feature to the origin
// if check_origin return true, the origin is inside the simplex, so return the zero vector
// if not, the simplex will be the closest edge to the origin, and d the normal of the edge
// in the direction of the origin
if self.reduce_to_closest_feature(simplex, &mut d) {
return d;
}
// compute closest point to origin on the simplex (which is now an edge)
if simplex.len() == 1 {
simplex[0].v
} else {
get_closest_point_on_edge(&simplex[1].v, &simplex[0].v, &Vector2::zero())
}
}
fn new() -> Self {
Self {
m: marker::PhantomData,
}
}
}
#[cfg(test)]
mod tests {
use cgmath::Vector2;
use super::*;
use crate::algorithm::minkowski::SupportPoint;
use cgmath::assert_ulps_eq;
use smallvec::smallvec;
#[test]
fn test_check_origin_empty() {
let processor = SimplexProcessor2::new();
let mut direction = Vector2::new(1., 0.);
let mut simplex = smallvec![];
assert!(!processor.reduce_to_closest_feature(&mut simplex, &mut direction));
assert_eq!(0, simplex.len());
assert_eq!(Vector2::new(1., 0.), direction);
}
#[test]
fn test_check_origin_single() {
let processor = SimplexProcessor2::new();
let mut direction = Vector2::new(1., 0.);
let mut simplex = smallvec![sup(40., 0.)];
assert!(!processor.reduce_to_closest_feature(&mut simplex, &mut direction));
assert_eq!(1, simplex.len());
assert_eq!(Vector2::new(1., 0.), direction);
}
#[test]
fn test_check_origin_edge() {
let processor = SimplexProcessor2::new();
let mut direction = Vector2::new(1., 0.);
let mut simplex = smallvec![sup(40., 10.), sup(-10., 10.)];
assert!(!processor.reduce_to_closest_feature(&mut simplex, &mut direction));
assert_eq!(2, simplex.len());
assert!(0. - direction.x <= f32::EPSILON);
assert!(direction.y < 0.);
}
#[test]
fn test_check_origin_triangle_outside_ac() {
let processor = SimplexProcessor2::new();
let mut direction = Vector2::new(1., 0.);
let mut simplex = smallvec![sup(40., 10.), sup(-10., 10.), sup(0., 3.)];
assert!(!processor.reduce_to_closest_feature(&mut simplex, &mut direction));
assert_eq!(2, simplex.len());
assert!(direction.x < 0.);
assert!(direction.y < 0.);
}
#[test]
fn test_check_origin_triangle_outside_ab() {
let processor = SimplexProcessor2::new();
let mut direction = Vector2::new(1., 0.);
let mut simplex = smallvec![sup(40., 10.), sup(10., 10.), sup(3., -3.)];
assert!(!processor.reduce_to_closest_feature(&mut simplex, &mut direction));
assert_eq!(2, simplex.len());
assert!(direction.x < 0.);
assert!(direction.y > 0.);
}
#[test]
fn test_check_origin_triangle_hit() {
let processor = SimplexProcessor2::new();
let mut direction = Vector2::new(1., 0.);
let mut simplex = smallvec![sup(40., 10.), sup(-10., 10.), sup(0., -3.)];
assert!(processor.reduce_to_closest_feature(&mut simplex, &mut direction));
assert_eq!(3, simplex.len());
assert_eq!(Vector2::new(1., 0.), direction);
}
#[test]
fn test_closest_point_to_origin_triangle() {
let processor = SimplexProcessor2::new();
let mut simplex = smallvec![sup(40., 10.), sup(-10., 10.), sup(0., 3.)];
let p = processor.get_closest_point_to_origin(&mut simplex);
assert_eq!(2, simplex.len());
assert_ulps_eq!(Vector2::new(0., 3.), p);
}
#[test]
fn test_closest_point_to_origin_triangle_inside() {
let processor = SimplexProcessor2::new();
let mut simplex = smallvec![sup(40., 10.), sup(-10., 10.), sup(0., -3.)];
let p = processor.get_closest_point_to_origin(&mut simplex);
assert_eq!(3, simplex.len());
assert_ulps_eq!(Vector2::new(0., 0.), p);
}
#[test]
fn test_closest_point_to_origin_edge() {
let processor = SimplexProcessor2::new();
let mut simplex = smallvec![sup(40., 10.), sup(-10., 10.)];
let p = processor.get_closest_point_to_origin(&mut simplex);
assert_eq!(2, simplex.len());
assert_ulps_eq!(Vector2::new(0., 10.), p);
}
fn sup(x: f32, y: f32) -> SupportPoint<Point2<f32>> {
let mut s = SupportPoint::new();
s.v = Vector2::new(x, y);
s
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/algorithm/minkowski/gjk/simplex/mod.rs | src/algorithm/minkowski/gjk/simplex/mod.rs | pub use self::simplex2d::SimplexProcessor2;
pub use self::simplex3d::SimplexProcessor3;
mod simplex2d;
mod simplex3d;
use cgmath::prelude::*;
use smallvec::SmallVec;
use crate::algorithm::minkowski::SupportPoint;
pub type Simplex<P> = SmallVec<[SupportPoint<P>; 5]>;
/// Defined a simplex processor for use in GJK.
pub trait SimplexProcessor {
/// The point type of the processor
type Point: EuclideanSpace;
/// Check if the given simplex contains origin, and if not, update the simplex and search
/// direction.
///
/// Used by the GJK intersection test
fn reduce_to_closest_feature(
&self,
simplex: &mut Simplex<Self::Point>,
d: &mut <Self::Point as EuclideanSpace>::Diff,
) -> bool;
/// Get the closest point on the simplex to the origin.
///
/// Will also update the simplex to contain only the feature that is closest to the origin.
/// This will be an edge for 2D; and it will be an edge or a face for 3D.
/// This is primarily used by the GJK distance computation.
fn get_closest_point_to_origin(
&self,
simplex: &mut Simplex<Self::Point>,
) -> <Self::Point as EuclideanSpace>::Diff;
/// Create a new simplex processor
fn new() -> Self;
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/dbvt/visitor.rs | src/dbvt/visitor.rs | //! Concrete visitor implementations for use with
//! [`query`](struct.DynamicBoundingVolumeTree.html#method.query).
//!
use std::marker::PhantomData;
use cgmath::BaseFloat;
use super::{TreeValue, Visitor};
use crate::prelude::*;
use crate::{Frustum, PlaneBound, Relation};
/// Visitor for doing continuous intersection testing on the DBVT.
///
/// Will return the result from the
/// [`Continuous`](../trait.Continuous.html) implementation
/// of bound.intersection(self.bound).
///
#[derive(Debug)]
pub struct ContinuousVisitor<'a, B, T> {
bound: &'a B,
marker: PhantomData<T>,
}
impl<'a, B: 'a, T> ContinuousVisitor<'a, B, T>
where
T: TreeValue,
T::Bound: Continuous<B> + Discrete<B>,
{
/// Create a new visitor that will do continuous intersection tests using the given bound.
///
pub fn new(bound: &'a B) -> Self {
Self {
bound,
marker: PhantomData,
}
}
}
impl<'a, B: 'a, T> Visitor for ContinuousVisitor<'a, B, T>
where
T: TreeValue,
T::Bound: Continuous<B> + Discrete<B>,
{
type Bound = T::Bound;
type Result = <T::Bound as Continuous<B>>::Result;
fn accept(&mut self, bound: &Self::Bound, _: bool) -> Option<Self::Result> {
bound.intersection(self.bound)
}
}
/// Visitor for doing discrete intersection testing on the DBVT.
///
/// Will return () for intersections with the
/// [`Discrete`](../trait.Discrete.html) implementation
/// of bound.intersects(self.bound).
///
#[derive(Debug)]
pub struct DiscreteVisitor<'a, B, T> {
bound: &'a B,
marker: PhantomData<T>,
}
impl<'a, B: 'a, T> DiscreteVisitor<'a, B, T>
where
T: TreeValue,
T::Bound: Discrete<B>,
{
/// Create a new visitor that will do discrete intersection tests using the given bound.
pub fn new(bound: &'a B) -> Self {
Self {
bound,
marker: PhantomData,
}
}
}
impl<'a, B: 'a, T> Visitor for DiscreteVisitor<'a, B, T>
where
T: TreeValue,
T::Bound: Discrete<B>,
{
type Bound = T::Bound;
type Result = ();
fn accept(&mut self, bound: &Self::Bound, _: bool) -> Option<()> {
if bound.intersects(self.bound) {
Some(())
} else {
None
}
}
}
/// Visitor for doing frustum intersection testing on the DBVT.
///
/// Will return the relation for intersections with the
/// [`Bound`](../trait.Bound.html) implementation
/// of self.frustum.contains(bound).
///
#[derive(Debug)]
pub struct FrustumVisitor<'a, S, T>
where
S: BaseFloat,
{
frustum: &'a Frustum<S>,
marker: PhantomData<T>,
}
impl<'a, S, T> FrustumVisitor<'a, S, T>
where
S: BaseFloat,
T: TreeValue,
T::Bound: PlaneBound<S>,
{
/// Create a new visitor that will do containment tests using the given frustum
pub fn new(frustum: &'a Frustum<S>) -> Self {
Self {
frustum,
marker: PhantomData,
}
}
}
impl<'a, S, T> Visitor for FrustumVisitor<'a, S, T>
where
S: BaseFloat,
T: TreeValue,
T::Bound: PlaneBound<S>,
{
type Bound = T::Bound;
type Result = Relation;
fn accept(&mut self, bound: &Self::Bound, _: bool) -> Option<Relation> {
let r = self.frustum.contains(bound);
if r == Relation::Out {
None
} else {
Some(r)
}
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/dbvt/wrapped.rs | src/dbvt/wrapped.rs | use std::fmt::Debug;
use cgmath::{EuclideanSpace, Zero};
use super::TreeValue;
use crate::{Bound, HasBound};
/// Value together with bounding volume, for use with DBVT.
#[derive(Debug, Clone)]
pub struct TreeValueWrapped<V, B>
where
B: Bound,
<B::Point as EuclideanSpace>::Diff: Debug,
{
/// The value
pub value: V,
/// The bounding volume
pub bound: B,
margin: <B::Point as EuclideanSpace>::Diff,
}
impl<V, B> TreeValueWrapped<V, B>
where
B: Bound,
<B::Point as EuclideanSpace>::Diff: Debug,
{
/// Create a new shape
pub fn new(value: V, bound: B, margin: <B::Point as EuclideanSpace>::Diff) -> Self {
Self {
value,
bound,
margin,
}
}
}
impl<V, B> TreeValue for TreeValueWrapped<V, B>
where
V: Clone,
B: Bound + Clone,
<B::Point as EuclideanSpace>::Diff: Debug,
{
type Bound = B;
fn bound(&self) -> &Self::Bound {
&self.bound
}
fn get_bound_with_margin(&self) -> Self::Bound {
self.bound.with_margin(self.margin)
}
}
impl<V, B> HasBound for TreeValueWrapped<V, B>
where
B: Bound,
<B::Point as EuclideanSpace>::Diff: Debug,
{
type Bound = B;
fn bound(&self) -> &Self::Bound {
&self.bound
}
}
impl<V, B, P> From<(V, B, P::Diff)> for TreeValueWrapped<V, B>
where
P: EuclideanSpace,
B: Bound<Point = P> + Clone,
P::Diff: Debug,
{
fn from((value, bound, margin): (V, B, P::Diff)) -> Self {
Self::new(value, bound, margin)
}
}
impl<V, B> From<(V, B)> for TreeValueWrapped<V, B>
where
B: Bound + Clone,
<<B as Bound>::Point as EuclideanSpace>::Diff: Debug + Zero,
{
fn from((value, bound): (V, B)) -> Self {
Self::new(
value,
bound,
<<B as Bound>::Point as EuclideanSpace>::Diff::zero(),
)
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/dbvt/util.rs | src/dbvt/util.rs | //! Utilities for use with
//! [`DynamicBoundingVolumeTree`](struct.DynamicBoundingVolumeTree.html).
//!
use std::marker::PhantomData;
use cgmath::prelude::*;
use cgmath::BaseFloat;
use super::{ContinuousVisitor, DynamicBoundingVolumeTree, TreeValue, Visitor};
use crate::prelude::*;
use crate::Ray;
struct RayClosestVisitor<S, P, T>
where
S: BaseFloat,
T: TreeValue,
P: EuclideanSpace<Scalar = S>,
{
ray: Ray<S, P, P::Diff>,
min: S,
marker: PhantomData<T>,
}
impl<S, P, T> RayClosestVisitor<S, P, T>
where
S: BaseFloat,
T: TreeValue,
P: EuclideanSpace<Scalar = S>,
{
pub fn new(ray: Ray<S, P, P::Diff>) -> Self {
Self {
ray,
min: S::infinity(),
marker: PhantomData,
}
}
}
impl<S, P, T> Visitor for RayClosestVisitor<S, P, T>
where
S: BaseFloat,
T: TreeValue,
P: EuclideanSpace<Scalar = S>,
P::Diff: VectorSpace<Scalar = S> + InnerSpace,
T::Bound: Clone
+ Contains<T::Bound>
+ SurfaceArea<Scalar = S>
+ Union<T::Bound, Output = T::Bound>
+ Continuous<Ray<S, P, P::Diff>, Result = P>,
{
type Bound = T::Bound;
type Result = P;
fn accept(&mut self, bound: &Self::Bound, is_leaf: bool) -> Option<Self::Result> {
match bound.intersection(&self.ray) {
Some(point) => {
let offset = point - self.ray.origin;
let t = offset.dot(self.ray.direction);
if t < self.min {
if is_leaf {
self.min = t;
}
Some(point)
} else {
None
}
}
None => None,
}
}
}
/// Query the given tree for the closest value that intersects the given ray.
///
/// ### Parameters:
///
/// - `tree`: DBVT to query.
/// - `ray`: Ray to find the closest intersection for.
///
/// ### Returns
///
/// Optionally returns the value that had the closest intersection with the ray, along with the
/// actual intersection point.
///
pub fn query_ray_closest<'a, S, T: 'a, P>(
tree: &'a DynamicBoundingVolumeTree<T>,
ray: Ray<S, P, P::Diff>,
) -> Option<(&'a T, P)>
where
S: BaseFloat,
T: TreeValue,
P: EuclideanSpace<Scalar = S>,
P::Diff: VectorSpace<Scalar = S> + InnerSpace,
T::Bound: Clone
+ Contains<T::Bound>
+ SurfaceArea<Scalar = S>
+ Union<T::Bound, Output = T::Bound>
+ Continuous<Ray<S, P, P::Diff>, Result = P>
+ Discrete<Ray<S, P, P::Diff>>,
{
let mut saved = None;
let mut tmin = S::infinity();
let mut visitor = RayClosestVisitor::<S, P, T>::new(ray);
for (value, point) in tree.query(&mut visitor) {
let offset = point - ray.origin;
let t = offset.dot(ray.direction);
if t < tmin {
tmin = t;
saved = Some((value, point));
}
}
saved
}
/// Query the given tree for all values that intersects the given ray.
///
/// ### Parameters:
///
/// - `tree`: DBVT to query.
/// - `ray`: Ray to find intersections for.
///
/// ### Returns
///
/// Returns all values that intersected the ray, and also at which point the intersections occurred.
pub fn query_ray<'a, S, T: 'a, P>(
tree: &'a DynamicBoundingVolumeTree<T>,
ray: Ray<S, P, P::Diff>,
) -> Vec<(&'a T, P)>
where
S: BaseFloat,
T: TreeValue,
P: EuclideanSpace<Scalar = S>,
P::Diff: VectorSpace<Scalar = S> + InnerSpace,
T::Bound: Clone
+ Contains<T::Bound>
+ SurfaceArea<Scalar = S>
+ Union<T::Bound, Output = T::Bound>
+ Continuous<Ray<S, P, P::Diff>, Result = P>
+ Discrete<Ray<S, P, P::Diff>>,
{
let mut visitor = ContinuousVisitor::<_, T>::new(&ray);
tree.query(&mut visitor)
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/dbvt/mod.rs | src/dbvt/mod.rs | //! A [dynamic bounding volume tree implementation](struct.DynamicBoundingVolumeTree.html),
//! index based (not pointer based).
//!
//! The following invariants are true:
//!
//! * A branch node must have exactly two children.
//! * Only leaf nodes contain user data.
//!
//! Internal nodes may have incorrect bounding volumes and height after insertion, removal and
//! updates to values in the tree. These will be fixed during refitting, which is done by calling
//! [`do_refit`](struct.DynamicBoundingVolumeTree.html#method.do_refit).
//!
//! The main heuristic used for insertion and tree rotation, is surface area of the bounding volume.
//!
//! Updating of values in the tree, can either be performed by using the
//! [`values`](struct.DynamicBoundingVolumeTree.html#method.values) function to get a mutable
//! iterator over the values in the tree, or by using
//! [`update_node`](struct.DynamicBoundingVolumeTree.html#method.update_node).
//! It is recommended to use the latter when possible. If the former is used,
//! [`reindex_values`](struct.DynamicBoundingVolumeTree.html#method.reindex_values)
//! must be called if the order of the values is changed in any way.
//!
//! The trait [`TreeValue`](trait.TreeValue.html) needs to be implemented for a type to be usable
//! in the tree.
//!
//! # Examples
//!
//! ```
//! # extern crate cgmath;
//! # extern crate collision;
//!
//! use cgmath::{Point2, Vector2, InnerSpace};
//! use collision::{Aabb, Aabb2, Ray2};
//!
//! use collision::dbvt::{DynamicBoundingVolumeTree, TreeValue, ContinuousVisitor};
//!
//! #[derive(Debug, Clone)]
//! struct Value {
//! pub id: u32,
//! pub aabb: Aabb2<f32>,
//! fat_aabb: Aabb2<f32>,
//! }
//!
//! impl Value {
//! pub fn new(id: u32, aabb: Aabb2<f32>) -> Self {
//! Self {
//! id,
//! fat_aabb : aabb.add_margin(Vector2::new(3., 3.)),
//! aabb,
//! }
//! }
//! }
//!
//! impl TreeValue for Value {
//! type Bound = Aabb2<f32>;
//!
//! fn bound(&self) -> &Aabb2<f32> {
//! &self.aabb
//! }
//!
//! fn get_bound_with_margin(&self) -> Aabb2<f32> {
//! self.fat_aabb.clone()
//! }
//! }
//!
//! fn aabb2(minx: f32, miny: f32, maxx: f32, maxy: f32) -> Aabb2<f32> {
//! Aabb2::new(Point2::new(minx, miny), Point2::new(maxx, maxy))
//! }
//!
//! fn main() {
//! let mut tree = DynamicBoundingVolumeTree::<Value>::new();
//! tree.insert(Value::new(10, aabb2(5., 5., 10., 10.)));
//! tree.insert(Value::new(11, aabb2(21., 14., 23., 16.)));
//! tree.do_refit();
//!
//! let ray = Ray2::new(Point2::new(0., 0.), Vector2::new(-1., -1.).normalize());
//! let mut visitor = ContinuousVisitor::<Ray2<f32>, Value>::new(&ray);
//! assert_eq!(0, tree.query(&mut visitor).len());
//!
//! let ray = Ray2::new(Point2::new(6., 0.), Vector2::new(0., 1.).normalize());
//! let mut visitor = ContinuousVisitor::<Ray2<f32>, Value>::new(&ray);
//! let results = tree.query(&mut visitor);
//! assert_eq!(1, results.len());
//! assert_eq!(10, results[0].0.id);
//! assert_eq!(Point2::new(6., 5.), results[0].1);
//! }
//! ```
//!
pub use self::util::*;
pub use self::visitor::*;
pub use self::wrapped::TreeValueWrapped;
use std::cmp::max;
use std::fmt;
use cgmath::num_traits::NumCast;
use rand;
use rand::Rng;
use crate::prelude::*;
mod util;
mod visitor;
mod wrapped;
const SURFACE_AREA_IMPROVEMENT_FOR_ROTATION: f32 = 0.3;
const PERFORM_ROTATION_PERCENTAGE: u32 = 10;
/// Trait that needs to be implemented for any value that is to be used in the
/// [`DynamicBoundingVolumeTree`](struct.DynamicBoundingVolumeTree.html).
///
pub trait TreeValue: Clone {
/// Bounding volume type
type Bound;
/// Return the bounding volume of the value
fn bound(&self) -> &Self::Bound;
/// Return a fattened bounding volume. For shapes that do not move, this can be the same as the
/// base bounding volume. It is recommended for moving shapes to have a larger fat bound, so
/// tree rotations don't have to be performed every frame.
fn get_bound_with_margin(&self) -> Self::Bound;
}
/// Make it possible to run broad phase algorithms directly on the value storage in DBVT
impl<T> HasBound for (usize, T)
where
T: TreeValue,
T::Bound: Bound,
{
type Bound = T::Bound;
fn bound(&self) -> &Self::Bound {
self.1.bound()
}
}
/// Visitor trait used for [querying](struct.DynamicBoundingVolumeTree.html#method.query) the tree.
pub trait Visitor {
/// Bounding volume accepted by the visitor
type Bound;
/// Result returned by the acceptance test
type Result;
/// Acceptance test function
fn accept(&mut self, bound: &Self::Bound, is_leaf: bool) -> Option<Self::Result>;
}
/// A dynamic bounding volume tree, index based (not pointer based).
///
/// The following invariants are true:
///
/// * A branch node must have exactly two children.
/// * Only leaf nodes contain user data.
///
/// Internal nodes may have incorrect bounding volumes and height after insertion, removal and
/// updates to values in the tree. These will be fixed during refitting, which is done by calling
/// [`do_refit`](struct.DynamicBoundingVolumeTree.html#method.do_refit). This function should
/// ideally not be called more than once per frame.
///
/// The main heuristic used for insertion and tree rotation, is surface area of the bounding volume.
///
/// Updating of values in the tree, can either be performed by using the
/// [`values`](struct.DynamicBoundingVolumeTree.html#method.values) function to get a mutable
/// iterator over the values in the tree, or by using
/// [`update_node`](struct.DynamicBoundingVolumeTree.html#method.update_node).
/// It is recommended to use the latter when possible. If the former is used,
/// [`reindex_values`](struct.DynamicBoundingVolumeTree.html#method.reindex_values)
/// must be called if the order of the values is changed in any way.
///
/// # Type parameters:
///
/// - `T`: A type that implements [`TreeValue`](trait.TreeValue.html), and is usable in the tree.
/// Needs to be able to store the node index of itself, and handle its own bound and
/// fattened bound.
///
/// # Examples
///
/// ```
/// # extern crate cgmath;
/// # extern crate collision;
///
/// use cgmath::{Point2, Vector2, InnerSpace};
/// use collision::{Aabb, Aabb2, Ray2};
/// use collision::dbvt::{DynamicBoundingVolumeTree, TreeValue, ContinuousVisitor};
///
/// #[derive(Debug, Clone)]
/// struct Value {
/// pub id: u32,
/// pub aabb: Aabb2<f32>,
/// fat_aabb: Aabb2<f32>,
/// }
///
/// impl Value {
/// pub fn new(id: u32, aabb: Aabb2<f32>) -> Self {
/// Self {
/// id,
/// fat_aabb : aabb.add_margin(Vector2::new(3., 3.)),
/// aabb,
/// }
/// }
/// }
///
/// impl TreeValue for Value {
/// type Bound = Aabb2<f32>;
///
/// fn bound(&self) -> &Aabb2<f32> {
/// &self.aabb
/// }
///
/// fn get_bound_with_margin(&self) -> Aabb2<f32> {
/// self.fat_aabb.clone()
/// }
/// }
///
/// fn aabb2(minx: f32, miny: f32, maxx: f32, maxy: f32) -> Aabb2<f32> {
/// Aabb2::new(Point2::new(minx, miny), Point2::new(maxx, maxy))
/// }
///
/// fn main() {
/// let mut tree = DynamicBoundingVolumeTree::<Value>::new();
/// tree.insert(Value::new(10, aabb2(5., 5., 10., 10.)));
/// tree.insert(Value::new(11, aabb2(21., 14., 23., 16.)));
/// tree.do_refit();
///
/// let ray = Ray2::new(Point2::new(0., 0.), Vector2::new(-1., -1.).normalize());
/// let mut visitor = ContinuousVisitor::<Ray2<f32>, Value>::new(&ray);
/// assert_eq!(0, tree.query(&mut visitor).len());
///
/// let ray = Ray2::new(Point2::new(6., 0.), Vector2::new(0., 1.).normalize());
/// let mut visitor = ContinuousVisitor::<Ray2<f32>, Value>::new(&ray);
/// let results = tree.query(&mut visitor);
/// assert_eq!(1, results.len());
/// assert_eq!(10, results[0].0.id);
/// assert_eq!(Point2::new(6., 5.), results[0].1);
/// }
/// ```
///
pub struct DynamicBoundingVolumeTree<T>
where
T: TreeValue,
{
nodes: Vec<Node<T::Bound>>,
values: Vec<(usize, T)>,
free_list: Vec<usize>,
updated_list: Vec<usize>,
root_index: usize,
refit_nodes: Vec<(u32, usize)>,
}
impl<T> Default for DynamicBoundingVolumeTree<T>
where
T: TreeValue,
{
fn default() -> Self {
DynamicBoundingVolumeTree {
// we add Nil to first position so only the root node can have parent = 0
nodes: vec![Node::Nil],
values: Vec::default(),
free_list: Vec::default(),
updated_list: Vec::default(),
root_index: 0,
refit_nodes: Vec::default(),
}
}
}
impl<T> fmt::Debug for DynamicBoundingVolumeTree<T>
where
T: TreeValue,
T::Bound: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "graph tree {{")?;
for n_index in 1..self.nodes.len() {
match self.nodes[n_index] {
Node::Branch(ref b) => {
write!(f, " n_{} [label=\"{:?}\"];", n_index, b.bound)?;
write!(f, " n_{} -- n_{};", n_index, b.left)?;
write!(f, " n_{} -- n_{};", n_index, b.right)?;
}
Node::Leaf(ref l) => {
write!(f, " n_{} [label=\"{:?}\"];", n_index, l.bound)?;
}
Node::Nil => (),
}
}
write!(f, "}}")
}
}
/// Branch node
#[derive(Debug)]
struct Branch<B> {
parent: usize,
left: usize,
right: usize,
height: u32,
bound: B,
}
/// Leaf node
#[derive(Debug)]
struct Leaf<B> {
parent: usize,
value: usize,
bound: B,
}
/// Nodes
#[derive(Debug)]
enum Node<B> {
Branch(Branch<B>),
Leaf(Leaf<B>),
Nil,
}
impl<T> DynamicBoundingVolumeTree<T>
where
T: TreeValue,
T::Bound: Clone + Contains<T::Bound> + Union<T::Bound, Output = T::Bound> + SurfaceArea,
{
/// Create a new tree.
///
/// ### Type parameters:
///
/// - `T`: A type that implements [`TreeValue`](trait.TreeValue.html), and is usable in the
/// tree. Needs to be able to store the node index of itself, and handle its own bound
/// and fattened bound.
/// - `T::Bound`: Bounding volume type that implements the following collision-rs traits:
/// [`Contains`][1] on itself, [`Union`][2] on itself, and [`SurfaceArea`][3].
///
/// [1]: ../trait.Contains.html
/// [2]: ../trait.Union.html
/// [3]: ../trait.SurfaceArea.html
///
pub fn new() -> Self {
Default::default()
}
/// Return the number of nodes in the tree.
///
pub fn size(&self) -> usize {
// -1 because the first slot in the nodes vec is never used
self.nodes.len() - self.free_list.len() - 1
}
/// Return the height of the root node. Leafs are considered to have height 1.
///
pub fn height(&self) -> u32 {
if self.values.is_empty() {
0
} else {
match self.nodes[self.root_index] {
Node::Branch(ref b) => b.height,
Node::Leaf(_) => 1,
Node::Nil => 0,
}
}
}
/// Get an immutable list of all values in the tree.
///
/// ### Returns
///
/// A immutable reference to the [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html)
/// of values in the tree.
///
pub fn values(&self) -> &Vec<(usize, T)> {
&self.values
}
/// Get a mutable list of all values in the tree.
///
/// Do not insert or remove values directly in this list, instead use
/// [`insert`](struct.DynamicBoundingVolumeTree.html#method.insert) and
/// [`remove`](struct.DynamicBoundingVolumeTree.html#method.remove)
/// on the tree. It is allowed to change the order of the values, but when doing so it is
/// required to use
/// [`reindex_values`](struct.DynamicBoundingVolumeTree.html#method.reindex_values)
/// after changing the order, and before any other operation
/// is performed on the tree. Otherwise the internal consistency of the tree will be broken.
///
/// Do not change the first value in the tuple, this is the node index of the value, and without
/// that the tree will not function.
///
/// ### Returns
///
/// A mutable reference to the [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html)
/// of values in the tree.
///
pub fn values_mut(&mut self) -> &mut Vec<(usize, T)> {
&mut self.values
}
/// Reindex the values list, making sure that nodes in the tree point to the correct entry in
/// the values list.
///
/// Complexity is O(n).
///
pub fn reindex_values(&mut self) {
for i in 0..self.values.len() {
if let Node::Leaf(ref mut leaf) = self.nodes[self.values[i].0] {
leaf.value = i;
}
}
}
/// Clear the tree.
///
/// Will remove all nodes and their values.
///
pub fn clear(&mut self) {
self.root_index = 0;
self.nodes = vec![Node::Nil];
self.free_list.clear();
self.refit_nodes.clear();
self.values.clear();
}
/// Return the value index for the given node index.
pub fn value_index(&self, node_index: usize) -> Option<usize> {
match self.nodes[node_index] {
Node::Leaf(ref leaf) => Some(leaf.value),
_ => None,
}
}
/// Query the tree for all leafs that the given visitor accepts.
///
/// Will do a depth first search of the tree and pass all bounding volumes on the way to the
/// visitor.
///
/// This function have approximate complexity O(log^2 n).
///
/// ### Parameters:
///
/// - `visitor`: The visitor to check for bounding volume tests.
///
/// ### Type parameters:
///
/// - `V`: Type that implements of [`Visitor`](trait.Visitor.html)
///
/// ### Returns
///
/// Will return a list of tuples of values accepted and the result returned by the visitor for
/// the acceptance test.
///
pub fn query<V>(&self, visitor: &mut V) -> Vec<(&T, V::Result)>
where
V: Visitor<Bound = T::Bound>,
{
self.query_for_indices(visitor)
.into_iter()
.map(|(value_index, result)| (&self.values[value_index].1, result))
.collect()
}
/// Query the tree for all leafs that the given visitor accepts.
///
/// Will do a depth first search of the tree and pass all bounding volumes on the way to the
/// visitor.
///
/// This function have approximate complexity O(log^2 n).
///
/// ### Parameters:
///
/// - `visitor`: The visitor to check for bounding volume tests.
///
/// ### Type parameters:
///
/// - `V`: Type that implements of [`Visitor`](trait.Visitor.html)
///
/// ### Returns
///
/// Will return a list of tuples of value indices accepted and the result returned by the
/// visitor for the acceptance test.
///
pub fn query_for_indices<V>(&self, visitor: &mut V) -> Vec<(usize, V::Result)>
where
V: Visitor<Bound = T::Bound>,
{
let mut stack = [0; 256];
stack[0] = self.root_index;
let mut stack_pointer = 1;
let mut values = Vec::default();
while stack_pointer > 0 {
// depth search, use last added as next test subject
stack_pointer -= 1;
let node_index = stack[stack_pointer];
let node = &self.nodes[node_index];
match *node {
Node::Leaf(ref leaf) => {
// if we encounter a leaf, do a real bound intersection test, and add to return
// values if there's an intersection
if let Some(result) = visitor.accept(self.values[leaf.value].1.bound(), true) {
values.push((leaf.value, result));
}
}
// if we encounter a branch, do intersection test, and push the children if the
// branch intersected
Node::Branch(ref branch) => {
if visitor.accept(&branch.bound, false).is_some() {
stack[stack_pointer] = branch.left;
stack[stack_pointer + 1] = branch.right;
stack_pointer += 2;
}
}
Node::Nil => (),
}
}
values
}
/// Update a node in the tree with a new value.
///
/// The node will be fed its node_index after updating in the tree, so there is no need to
/// add that manually in the value.
///
/// Will cause the node to be updated and be flagged as updated, which will cause
/// [`update`](struct.DynamicBoundingVolumeTree.html#method.update) to process the node the next
/// time it is called.
///
/// ### Parameters
///
/// - `node_index`: index of the node to update
/// - `new_value`: the new value to write in that node
///
pub fn update_node(&mut self, node_index: usize, new_value: T) {
if let Node::Leaf(ref mut leaf) = self.nodes[node_index] {
self.values[leaf.value].1 = new_value;
}
self.flag_updated(node_index);
}
/// Flag a node as having been updated (moved/rotated).
///
/// Will cause [`update`](struct.DynamicBoundingVolumeTree.html#method.update) to process the
/// node the next time it is called.
///
/// ### Parameters
///
/// - `node_index`: the node index of the updated node
///
pub fn flag_updated(&mut self, node_index: usize) {
self.updated_list.push(node_index);
}
/// Go through the updated list and check the fat bounds in the tree.
///
/// After updating values in the values list, it is possible that some of the leafs values have
/// outgrown their fat bounds. If so, they may need to be moved in the tree. This is done during
/// refitting.
///
/// Note that no parents have their bounds/height updated directly by this function, instead
/// [`do_refit`](struct.DynamicBoundingVolumeTree.html#method.do_refit) should be called after
/// all insert/remove/updates have been performed this frame.
///
pub fn update(&mut self) {
let nodes = self
.updated_list
.iter()
.filter_map(|&index| {
if let Node::Leaf(ref l) = self.nodes[index] {
if !l.bound.contains(self.values[l.value].1.bound()) {
Some((
index,
l.parent,
self.values[l.value].1.get_bound_with_margin(),
))
} else {
None
}
} else {
None
}
})
.collect::<Vec<(usize, usize, T::Bound)>>();
for (node_index, parent_index, fat_bound) in nodes {
if let Node::Leaf(ref mut leaf) = self.nodes[node_index] {
leaf.bound = fat_bound;
}
self.mark_for_refit(parent_index, 2);
}
self.updated_list.clear();
}
/// Utility method to perform updates and refitting. Should be called once per frame.
///
/// Will in turn call [`update`](struct.DynamicBoundingVolumeTree.html#method.update), followed
/// by [`do_refit`](struct.DynamicBoundingVolumeTree.html#method.do_refit).
///
pub fn tick(&mut self) {
self.update();
self.do_refit();
}
/// Insert a value into the tree.
///
/// This will search the tree for the best leaf to pair the value up with, using the surface
/// area of the value's bounding volume as the main heuristic. Will always cause a new branch
/// node and a new leaf node (containing the given value) to be added to the tree.
/// This is to keep the invariant of branches always having 2 children true.
///
/// This function should have approximate complexity O(log^2 n).
///
/// Note that no parents have their bounds/height updated directly by this function, instead
/// [`do_refit`](struct.DynamicBoundingVolumeTree.html#method.do_refit) should be called after
/// all insert/remove/updates have been performed this frame.
///
/// ### Parameters
///
/// - `value`: The value to insert into the tree.
///
/// ### Returns
///
/// The node index of the inserted value. This value should never change after insertion.
///
pub fn insert(&mut self, value: T) -> usize {
let fat_bound = value.get_bound_with_margin();
let value_index = self.values.len();
self.values.push((0, value));
// Create a new leaf node for the given value
let mut new_leaf = Leaf {
parent: 0,
value: value_index,
bound: fat_bound,
};
// If the root index is 0, this is the first node inserted, and we can circumvent a lot of
// checks.
if self.root_index == 0 {
self.root_index = self.nodes.len();
self.nodes.push(Node::Leaf(new_leaf));
self.values[value_index].0 = self.root_index;
self.root_index
} else {
// Start searching from the root node
let mut node_index = self.root_index;
// We will always insert a branch node and the new leaf node, so get 2 new indices
// into the node list
let (new_branch_index, new_leaf_index) = self.next_free();
// We need to tell the value what it's node index is
self.values[value_index].0 = new_leaf_index;
// The new leaf will always be a child of the new branch node.
new_leaf.parent = new_branch_index;
let mut branch_parent_index = 0;
loop {
// If we encounter a leaf node, we've found the place where we want to add the new
// nodes. The branch node will be inserted into the tree here, and this node will be
// moved down as the left child of the new branch node, and the new leaf will be the
// right child.
let add_branch = match self.nodes[node_index] {
Node::Leaf(ref leaf) => {
let new_branch = Branch {
left: node_index, // old leaf at the current position is left child
right: new_leaf_index, // new leaf node is the right child
parent: leaf.parent, // parent of the branch is the old leaf parent
height: 2, // leafs have height 1, so new branch have height 2
bound: leaf.bound.union(&new_leaf.bound),
};
Some((node_index, new_branch))
}
// If we hit a branch, we compute the surface area of the bounding volumes for
// if the new leaf was added to the right or left. Whichever surface area is
// lowest will decide which child to go to next.
Node::Branch(ref branch) => {
let left_bound = get_bound(&self.nodes[branch.left]);
let right_bound = get_bound(&self.nodes[branch.right]);
let left_area = left_bound.union(&new_leaf.bound).surface_area();
let right_area = right_bound.union(&new_leaf.bound).surface_area();
if left_area < right_area {
node_index = branch.left;
} else {
node_index = branch.right;
}
None
}
Node::Nil => break,
};
// time to actually update the tree
if let Some((leaf_index, branch)) = add_branch {
// the old leaf node needs to point to the new branch node as its parent
if let Node::Leaf(ref mut n) = self.nodes[leaf_index] {
n.parent = new_branch_index;
};
// if the old leaf node wasn't the root of tree, we update it's parent to point
// to the new branch node instead of the old leaf node
branch_parent_index = branch.parent;
if branch.parent != 0 {
if let Node::Branch(ref mut n) = self.nodes[branch.parent] {
if n.left == leaf_index {
n.left = new_branch_index;
} else {
n.right = new_branch_index;
}
}
}
// insert to new branch and leaf nodes
self.nodes[new_branch_index] = Node::Branch(branch);
self.nodes[new_leaf_index] = Node::Leaf(new_leaf);
// if the leaf node was the root of the tree,
// the new root is the new branch node
if leaf_index == self.root_index {
self.root_index = new_branch_index;
}
break;
}
}
// mark the new branch nodes parent for bounds/height updating and possible rotation
if branch_parent_index != 0 {
self.mark_for_refit(branch_parent_index, 3);
}
new_leaf_index
}
}
/// Remove the node with the given node index.
///
/// The reason this function takes the node index and not a reference to the value, is because
/// the only way to get at the values in the tree is by doing a mutable borrow, making this
/// function unusable.
///
/// If the given node index points to a non-leaf, this function is effectively a nop.
/// Else the leaf node and it's parent branch node will be removed, and the leaf nodes sibling
/// will take the place of the parent branch node in the tree.
///
/// Note that no parents have their bounds/height updated directly by this function, instead
/// [`do_refit`](struct.DynamicBoundingVolumeTree.html#method.do_refit) should be called after
/// all insert/remove/updates have been performed this frame.
///
/// This function should have approximate complexity O(log^2 n).
///
/// ### Parameters
///
/// - `node_index`: index of the leaf to remove
///
/// ### Returns
///
/// If a value was removed, the value is returned, otherwise None.
///
pub fn remove(&mut self, node_index: usize) -> Option<T> {
let (value_index, parent_index) = if let Node::Leaf(ref leaf) = self.nodes[node_index] {
(leaf.value, leaf.parent)
} else {
// If a value points to a non-leaf something has gone wrong,
// ignore remove and continue with life
return None;
};
// remove from values list and update node list with new value indices
let (_, value) = self.values.swap_remove(value_index);
// we only need to update the node for the value that we swapped into the old values place
if value_index < self.values.len() {
// should only fail if we just removed the last value
if let Node::Leaf(ref mut leaf) = self.nodes[self.values[value_index].0] {
leaf.value = value_index;
}
}
// remove from node list and add index to free list
self.nodes[node_index] = Node::Nil;
self.free_list.push(node_index);
if parent_index != 0 {
// remove parent branch from node list and add index to free list
let (parent_parent_index, sibling_index) =
if let Node::Branch(ref branch) = self.nodes[parent_index] {
(
branch.parent,
if branch.left == node_index {
branch.right
} else {
branch.left
},
)
} else {
return Some(value);
};
self.nodes[parent_index] = Node::Nil;
self.free_list.push(parent_index);
// set sibling parent to parent.parent
match self.nodes[sibling_index] {
Node::Branch(ref mut branch) => branch.parent = parent_parent_index,
Node::Leaf(ref mut leaf) => leaf.parent = parent_parent_index,
Node::Nil => (),
}
// if parents parent is 0, the sibling is the last node in the tree and becomes the new
// root node
if parent_parent_index == 0 {
self.root_index = sibling_index;
} else {
// else we have a remaining branch, and need to update either left or right to point
// to the sibling, based on where the old branch node was
if let Node::Branch(ref mut b) = self.nodes[parent_parent_index] {
if b.left == parent_index {
b.left = sibling_index;
} else {
b.right = sibling_index;
}
}
// mark parents parent for recalculation
self.mark_for_refit(parent_parent_index, 0);
}
} else {
// if parent was 0, this was the last node in the tree, and the tree is now empty.
// reset all values.
self.clear();
}
Some(value)
}
/// Go through the list of nodes marked for refitting, update their bounds/heights and check if
/// any of them need to be rotated to new locations.
///
/// This method have worst case complexity O(m * log^2 n), where m is the number of nodes in the
/// refit list.
///
pub fn do_refit(&mut self) {
while !self.refit_nodes.is_empty() {
let (_, node_index) = self.refit_nodes.remove(0);
self.refit_node(node_index);
}
}
/// Get two new node indices, where nodes can be inserted in the tree.
///
fn next_free(&mut self) -> (usize, usize) {
(self.take_free(), self.take_free())
}
/// Get a new node index, where a node can be inserted in the tree.
///
fn take_free(&mut self) -> usize {
if self.free_list.is_empty() {
let index = self.nodes.len();
self.nodes.push(Node::Nil);
index
} else {
self.free_list.remove(0)
}
}
/// Add the given node to the refitting list.
///
/// The refit list is sorted by the height of the node, and only have the same value
/// once, any duplicates are rejected. This because we don't want to refit the same node
/// twice.
///
/// ### Parameters
///
/// - `node_index`: index of the node to do refitting on.
/// - `min_height`: the minimum height the node has. Used primarily by insertion where we can't
/// be sure that the node has been refitted yet and might have an incorrect
/// height
///
fn mark_for_refit(&mut self, node_index: usize, min_height: u32) {
let node_height = match self.nodes[node_index] {
Node::Branch(ref b) => b.height,
_ => 0,
};
let height = max(node_height, min_height);
let value = (height, node_index);
match self.refit_nodes.binary_search(&value) {
Ok(_) => (),
Err(i) => self.refit_nodes.insert(i, value),
}
}
/// Actually refit a node in the tree. This will check the node for rotation, and if rotated,
/// will update the bound/height of itself and any other rotated nodes, and also mark its parent
/// for refitting.
///
fn refit_node(&mut self, node_index: usize) {
if let Some((parent_index, height)) = self.recalculate_node(node_index) {
if parent_index != 0 {
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | true |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/volume/cylinder.rs | src/volume/cylinder.rs | //! Oriented bounding cylinder
use cgmath::Point3;
use cgmath::Vector3;
/// Bounding cylinder
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Cylinder<S> {
/// Center point
pub center: Point3<S>,
/// Axis the cylinder is aligned with
pub axis: Vector3<S>,
/// Radius of the cylinder
pub radius: S,
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/volume/mod.rs | src/volume/mod.rs | pub use self::aabb::*;
pub use self::cylinder::Cylinder;
pub use self::obb::*;
pub use self::sphere::*;
mod aabb;
mod cylinder;
mod obb;
mod sphere;
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/volume/obb.rs | src/volume/obb.rs | //! Oriented bounding boxes
use std::marker::PhantomData;
use cgmath::{Point2, Point3};
use cgmath::{Vector2, Vector3};
/// Generic object bounding box, centered on `center`, aligned with `axis`,
/// and with size `extents`.
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Obb<S, V, P> {
/// OBB center point in world space
pub center: P,
/// Axis OBB is aligned with
pub axis: V,
/// Size of the OBB
pub extents: V,
marker: PhantomData<S>,
}
impl<S, V, P> Obb<S, V, P> {
/// Create a new generic OBB with the given `center`, `axis` and `extents`
pub fn new(center: P, axis: V, extents: V) -> Self {
Self {
center,
axis,
extents,
marker: PhantomData,
}
}
}
/// 2D object bounding box
pub type Obb2<S> = Obb<S, Vector2<S>, Point2<S>>;
/// 3D object bounding box
pub type Obb3<S> = Obb<S, Vector3<S>, Point3<S>>;
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/volume/sphere.rs | src/volume/sphere.rs | //! Bounding sphere
use cgmath::prelude::*;
use cgmath::{BaseFloat, Point3, Vector3};
use crate::prelude::*;
use crate::{Aabb3, Line3, Plane, Ray3};
/// Bounding sphere.
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Sphere<S: BaseFloat> {
/// Center point of the sphere in world space
pub center: Point3<S>,
/// Sphere radius
pub radius: S,
}
impl<S> Bound for Sphere<S>
where
S: BaseFloat,
{
type Point = Point3<S>;
fn min_extent(&self) -> Point3<S> {
self.center + Vector3::from_value(-self.radius)
}
fn max_extent(&self) -> Point3<S> {
self.center + Vector3::from_value(self.radius)
}
fn with_margin(&self, add: Vector3<S>) -> Self {
let max = add.x.max(add.y).max(add.z);
Sphere {
center: self.center,
radius: self.radius + max,
}
}
fn transform_volume<T>(&self, transform: &T) -> Self
where
T: Transform<Self::Point>,
{
Sphere {
center: transform.transform_point(self.center),
radius: self.radius,
}
}
fn empty() -> Self {
Self {
center: Point3::origin(),
radius: S::zero(),
}
}
}
impl<S: BaseFloat> Continuous<Ray3<S>> for Sphere<S> {
type Result = Point3<S>;
fn intersection(&self, r: &Ray3<S>) -> Option<Point3<S>> {
let s = self;
let l = s.center - r.origin;
let tca = l.dot(r.direction);
if tca < S::zero() {
return None;
}
let d2 = l.dot(l) - tca * tca;
if d2 > s.radius * s.radius {
return None;
}
let thc = (s.radius * s.radius - d2).sqrt();
Some(r.origin + r.direction * (tca - thc))
}
}
impl<S: BaseFloat> Discrete<Ray3<S>> for Sphere<S> {
fn intersects(&self, r: &Ray3<S>) -> bool {
let s = self;
let l = s.center - r.origin;
let tca = l.dot(r.direction);
if tca < S::zero() {
return false;
}
let d2 = l.dot(l) - tca * tca;
d2 <= s.radius * s.radius
}
}
impl<S: BaseFloat> Discrete<Sphere<S>> for Sphere<S> {
fn intersects(&self, s2: &Sphere<S>) -> bool {
let s1 = self;
let distance = s1.center.distance2(s2.center);
let radiuses = s1.radius + s2.radius;
distance <= radiuses * radiuses
}
}
impl<S: BaseFloat> PlaneBound<S> for Sphere<S> {
fn relate_plane(&self, plane: Plane<S>) -> Relation {
let dist = self.center.dot(plane.n) - plane.d;
if dist > self.radius {
Relation::In
} else if dist < -self.radius {
Relation::Out
} else {
Relation::Cross
}
}
}
impl<S: BaseFloat> Contains<Aabb3<S>> for Sphere<S> {
// will return true for border hits
#[inline]
fn contains(&self, aabb: &Aabb3<S>) -> bool {
let radius_sq = self.radius * self.radius;
for c in &aabb.to_corners() {
if c.distance2(self.center) > radius_sq {
return false;
}
}
true
}
}
impl<S: BaseFloat> Contains<Point3<S>> for Sphere<S> {
#[inline]
fn contains(&self, p: &Point3<S>) -> bool {
self.center.distance2(*p) <= self.radius * self.radius
}
}
impl<S: BaseFloat> Contains<Line3<S>> for Sphere<S> {
#[inline]
fn contains(&self, line: &Line3<S>) -> bool {
self.contains(&line.origin) && self.contains(&line.dest)
}
}
impl<S: BaseFloat> Contains<Sphere<S>> for Sphere<S> {
#[inline]
fn contains(&self, other: &Sphere<S>) -> bool {
let center_dist = self.center.distance(other.center);
(center_dist + other.radius) <= self.radius
}
}
impl<S: BaseFloat> Union for Sphere<S> {
type Output = Sphere<S>;
fn union(&self, other: &Sphere<S>) -> Sphere<S> {
if self.contains(other) {
return *self;
}
if other.contains(self) {
return *other;
}
let two = S::one() + S::one();
let center_diff = other.center - self.center;
let center_diff_s = center_diff.magnitude();
let radius = (self.radius + other.radius + center_diff_s) / two;
Sphere {
radius,
center: self.center + center_diff * (radius - self.radius) / center_diff_s,
}
}
}
impl<S: BaseFloat> Union<Aabb3<S>> for Sphere<S> {
type Output = Sphere<S>;
fn union(&self, aabb: &Aabb3<S>) -> Sphere<S> {
if self.contains(aabb) {
return *self;
}
let aabb_radius = aabb.max().distance(aabb.center());
if aabb.contains(self) {
return Sphere {
center: aabb.center(),
radius: aabb_radius,
};
}
let two = S::one() + S::one();
let center_diff = aabb.center() - self.center;
let center_diff_s = aabb.center().distance(self.center);
let radius = (self.radius + aabb_radius + center_diff_s) / two;
Sphere {
center: self.center + center_diff * (radius - self.radius) / center_diff_s,
radius,
}
}
}
impl<S: BaseFloat> SurfaceArea for Sphere<S> {
type Scalar = S;
fn surface_area(&self) -> S {
use std::f64::consts::PI;
let two = S::one() + S::one();
let four = two + two;
let pi = S::from(PI).unwrap();
four * pi * self.radius * self.radius
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/volume/aabb/aabb3.rs | src/volume/aabb/aabb3.rs | //! Axis aligned bounding box for 2D.
//!
use std::fmt;
use cgmath::prelude::*;
use cgmath::{BaseFloat, BaseNum, Point3, Vector3};
use super::{max, min};
use crate::prelude::*;
use crate::{Line3, Plane, Ray3, Sphere};
/// A three-dimensional AABB, aka a rectangular prism.
#[derive(Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Aabb3<S> {
/// Minimum point of the AABB
pub min: Point3<S>,
/// Maximum point of the AABB
pub max: Point3<S>,
}
impl<S: BaseNum> Aabb3<S> {
/// Construct a new axis-aligned bounding box from two points.
#[inline]
pub fn new(p1: Point3<S>, p2: Point3<S>) -> Aabb3<S> {
Aabb3 {
min: Point3::new(min(p1.x, p2.x), min(p1.y, p2.y), min(p1.z, p2.z)),
max: Point3::new(max(p1.x, p2.x), max(p1.y, p2.y), max(p1.z, p2.z)),
}
}
/// Compute corners.
#[inline]
pub fn to_corners(&self) -> [Point3<S>; 8] {
[
self.min,
Point3::new(self.max.x, self.min.y, self.min.z),
Point3::new(self.min.x, self.max.y, self.min.z),
Point3::new(self.max.x, self.max.y, self.min.z),
Point3::new(self.min.x, self.min.y, self.max.z),
Point3::new(self.max.x, self.min.y, self.max.z),
Point3::new(self.min.x, self.max.y, self.max.z),
self.max,
]
}
}
impl<S: BaseNum> Aabb for Aabb3<S> {
type Scalar = S;
type Diff = Vector3<S>;
type Point = Point3<S>;
#[inline]
fn new(p1: Point3<S>, p2: Point3<S>) -> Aabb3<S> {
Aabb3::new(p1, p2)
}
#[inline]
fn min(&self) -> Point3<S> {
self.min
}
#[inline]
fn max(&self) -> Point3<S> {
self.max
}
#[inline]
fn add_margin(&self, margin: Self::Diff) -> Self {
Aabb3::new(
Point3::new(
self.min.x - margin.x,
self.min.y - margin.y,
self.min.z - margin.z,
),
Point3::new(
self.max.x + margin.x,
self.max.y + margin.y,
self.max.z + margin.z,
),
)
}
#[inline]
fn transform<T>(&self, transform: &T) -> Self
where
T: Transform<Point3<S>>,
{
let corners = self.to_corners();
let transformed_first = transform.transform_point(corners[0]);
let base = Self::new(transformed_first, transformed_first);
corners[1..]
.iter()
.fold(base, |u, &corner| u.grow(transform.transform_point(corner)))
}
}
impl<S: BaseNum> fmt::Debug for Aabb3<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[{:?} - {:?}]", self.min, self.max)
}
}
impl<S: BaseNum> Contains<Point3<S>> for Aabb3<S> {
#[inline]
fn contains(&self, p: &Point3<S>) -> bool {
self.min.x <= p.x
&& p.x < self.max.x
&& self.min.y <= p.y
&& p.y < self.max.y
&& self.min.z <= p.z
&& p.z < self.max.z
}
}
impl<S: BaseNum> Contains<Aabb3<S>> for Aabb3<S> {
#[inline]
fn contains(&self, other: &Aabb3<S>) -> bool {
let other_min = other.min();
let other_max = other.max();
other_min.x >= self.min.x
&& other_min.y >= self.min.y
&& other_min.z >= self.min.z
&& other_max.x <= self.max.x
&& other_max.y <= self.max.y
&& other_max.z <= self.max.z
}
}
impl<S: BaseFloat> Contains<Sphere<S>> for Aabb3<S> {
// will return true for border hits on both min and max extents
#[inline]
fn contains(&self, sphere: &Sphere<S>) -> bool {
(sphere.center.x - sphere.radius) >= self.min.x
&& (sphere.center.y - sphere.radius) >= self.min.y
&& (sphere.center.z - sphere.radius) >= self.min.z
&& (sphere.center.x + sphere.radius) <= self.max.x
&& (sphere.center.y + sphere.radius) <= self.max.y
&& (sphere.center.z + sphere.radius) <= self.max.z
}
}
impl<S: BaseNum> Contains<Line3<S>> for Aabb3<S> {
#[inline]
fn contains(&self, line: &Line3<S>) -> bool {
self.contains(&line.origin) && self.contains(&line.dest)
}
}
impl<S: BaseNum> Union for Aabb3<S> {
type Output = Aabb3<S>;
fn union(&self, other: &Aabb3<S>) -> Aabb3<S> {
self.grow(other.min()).grow(other.max())
}
}
impl<S: BaseFloat> Union<Sphere<S>> for Aabb3<S> {
type Output = Aabb3<S>;
fn union(&self, sphere: &Sphere<S>) -> Aabb3<S> {
self.grow(Point3::new(
sphere.center.x - sphere.radius,
sphere.center.y - sphere.radius,
sphere.center.z - sphere.radius,
))
.grow(sphere.center + Vector3::from_value(sphere.radius))
}
}
impl<S: BaseFloat> Continuous<Aabb3<S>> for Ray3<S> {
type Result = Point3<S>;
fn intersection(&self, aabb: &Aabb3<S>) -> Option<Point3<S>> {
let ray = self;
let inv_dir = Vector3::new(S::one(), S::one(), S::one()).div_element_wise(ray.direction);
let mut t1 = (aabb.min.x - ray.origin.x) * inv_dir.x;
let mut t2 = (aabb.max.x - ray.origin.x) * inv_dir.x;
let mut tmin = t1.min(t2);
let mut tmax = t1.max(t2);
for i in 1..3 {
t1 = (aabb.min[i] - ray.origin[i]) * inv_dir[i];
t2 = (aabb.max[i] - ray.origin[i]) * inv_dir[i];
tmin = tmin.max(t1.min(t2));
tmax = tmax.min(t1.max(t2));
}
if (tmin < S::zero() && tmax < S::zero()) || tmax < tmin {
None
} else {
let t = if tmin >= S::zero() { tmin } else { tmax };
Some(ray.origin + ray.direction * t)
}
}
}
impl<S: BaseFloat> Continuous<Ray3<S>> for Aabb3<S> {
type Result = Point3<S>;
fn intersection(&self, ray: &Ray3<S>) -> Option<Point3<S>> {
ray.intersection(self)
}
}
impl<S: BaseFloat> Discrete<Aabb3<S>> for Ray3<S> {
fn intersects(&self, aabb: &Aabb3<S>) -> bool {
let ray = self;
let inv_dir = Vector3::new(S::one(), S::one(), S::one()).div_element_wise(ray.direction);
let mut t1 = (aabb.min.x - ray.origin.x) * inv_dir.x;
let mut t2 = (aabb.max.x - ray.origin.x) * inv_dir.x;
let mut tmin = t1.min(t2);
let mut tmax = t1.max(t2);
for i in 1..3 {
t1 = (aabb.min[i] - ray.origin[i]) * inv_dir[i];
t2 = (aabb.max[i] - ray.origin[i]) * inv_dir[i];
tmin = tmin.max(t1.min(t2));
tmax = tmax.min(t1.max(t2));
}
tmax >= tmin && (tmin >= S::zero() || tmax >= S::zero())
}
}
impl<S: BaseFloat> Discrete<Ray3<S>> for Aabb3<S> {
fn intersects(&self, ray: &Ray3<S>) -> bool {
ray.intersects(self)
}
}
impl<S: BaseFloat> Discrete<Aabb3<S>> for Aabb3<S> {
fn intersects(&self, aabb: &Aabb3<S>) -> bool {
let (a0, a1) = (self.min(), self.max());
let (b0, b1) = (aabb.min(), aabb.max());
a1.x > b0.x && a0.x < b1.x && a1.y > b0.y && a0.y < b1.y && a1.z > b0.z && a0.z < b1.z
}
}
impl<S: BaseFloat> PlaneBound<S> for Aabb3<S> {
fn relate_plane(&self, plane: Plane<S>) -> Relation {
let corners = self.to_corners();
let first = corners[0].relate_plane(plane);
for p in corners[1..].iter() {
if p.relate_plane(plane) != first {
return Relation::Cross;
}
}
first
}
}
impl<S: BaseNum> SurfaceArea for Aabb3<S> {
type Scalar = S;
fn surface_area(&self) -> S {
let dim = self.dim();
let two = S::one() + S::one();
two * ((dim.x * dim.y) + (dim.x * dim.z) + (dim.y * dim.z))
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/volume/aabb/mod.rs | src/volume/aabb/mod.rs | //! Axis-aligned bounding boxes
//!
//! An AABB is a geometric object which encompasses a set of points and is not
//! rotated. It is either a rectangle or a rectangular prism (depending on the
//! dimension) where the slope of every line is either 0 or undefined. These
//! are useful for very cheap collision detection.
pub use self::aabb2::Aabb2;
pub use self::aabb3::Aabb3;
use std::cmp::{Ordering, PartialOrd};
use cgmath::prelude::*;
use cgmath::{BaseNum, Point2, Point3};
use crate::traits::Bound;
mod aabb2;
mod aabb3;
pub(crate) fn min<S: PartialOrd + Copy>(lhs: S, rhs: S) -> S {
match lhs.partial_cmp(&rhs) {
Some(Ordering::Less) | Some(Ordering::Equal) | None => lhs,
_ => rhs,
}
}
pub(crate) fn max<S: PartialOrd + Copy>(lhs: S, rhs: S) -> S {
match lhs.partial_cmp(&rhs) {
Some(Ordering::Greater) | Some(Ordering::Equal) | None => lhs,
_ => rhs,
}
}
/// Compute the minimum/maximum of the given values
pub trait MinMax {
/// Compute the minimum
fn min(a: Self, b: Self) -> Self;
/// Compute the maximum
fn max(a: Self, b: Self) -> Self;
}
impl<S: PartialOrd> MinMax for Point2<S>
where
S: BaseNum,
{
fn min(a: Point2<S>, b: Point2<S>) -> Point2<S> {
Point2::new(min(a.x, b.x), min(a.y, b.y))
}
fn max(a: Point2<S>, b: Point2<S>) -> Point2<S> {
Point2::new(max(a.x, b.x), max(a.y, b.y))
}
}
impl<S: PartialOrd> MinMax for Point3<S>
where
S: BaseNum,
{
fn min(a: Point3<S>, b: Point3<S>) -> Point3<S> {
Point3::new(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z))
}
fn max(a: Point3<S>, b: Point3<S>) -> Point3<S> {
Point3::new(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z))
}
}
/// Base trait describing an axis aligned bounding box.
pub trait Aabb: Sized {
/// Scalar type
type Scalar: BaseNum;
/// Vector type
type Diff: VectorSpace<Scalar = Self::Scalar> + ElementWise + Array<Element = Self::Scalar>;
/// Point type
type Point: EuclideanSpace<Scalar = Self::Scalar, Diff = Self::Diff> + MinMax;
/// Create a new AABB using two points as opposing corners.
fn new(p1: Self::Point, p2: Self::Point) -> Self;
/// Create a new empty AABB
fn zero() -> Self {
let p = Self::Point::origin();
Self::new(p, p)
}
/// Return a shared reference to the point nearest to (-inf, -inf).
fn min(&self) -> Self::Point;
/// Return a shared reference to the point nearest to (inf, inf).
fn max(&self) -> Self::Point;
/// Return the dimensions of this AABB.
#[inline]
fn dim(&self) -> Self::Diff {
self.max() - self.min()
}
/// Return the volume this AABB encloses.
#[inline]
fn volume(&self) -> Self::Scalar {
self.dim().product()
}
/// Return the center point of this AABB.
#[inline]
fn center(&self) -> Self::Point {
let two = Self::Scalar::one() + Self::Scalar::one();
self.min() + self.dim() / two
}
/// Returns a new AABB that is grown to include the given point.
fn grow(&self, p: Self::Point) -> Self {
Aabb::new(MinMax::min(self.min(), p), MinMax::max(self.max(), p))
}
/// Add a vector to every point in the AABB, returning a new AABB.
#[inline]
fn add_v(&self, v: Self::Diff) -> Self {
Aabb::new(self.min() + v, self.max() + v)
}
/// Add a margin of the given width around the AABB, returning a new AABB.
fn add_margin(&self, margin: Self::Diff) -> Self;
/// Multiply every point in the AABB by a scalar, returning a new AABB.
#[inline]
fn mul_s(&self, s: Self::Scalar) -> Self {
Aabb::new(self.min() * s, self.max() * s)
}
/// Multiply every point in the AABB by a vector, returning a new AABB.
fn mul_v(&self, v: Self::Diff) -> Self {
let min = Self::Point::from_vec(self.min().to_vec().mul_element_wise(v));
let max = Self::Point::from_vec(self.max().to_vec().mul_element_wise(v));
Aabb::new(min, max)
}
/// Apply an arbitrary transform to the corners of this bounding box,
/// return a new conservative bound.
fn transform<T>(&self, transform: &T) -> Self
where
T: Transform<Self::Point>;
}
impl<A> Bound for A
where
A: Aabb,
A::Point: EuclideanSpace,
{
type Point = A::Point;
fn min_extent(&self) -> A::Point {
self.min()
}
fn max_extent(&self) -> A::Point {
self.max()
}
fn with_margin(&self, add: <A::Point as EuclideanSpace>::Diff) -> Self {
self.add_margin(add)
}
fn transform_volume<T>(&self, transform: &T) -> Self
where
T: Transform<Self::Point>,
{
self.transform(transform)
}
fn empty() -> Self {
A::zero()
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/src/volume/aabb/aabb2.rs | src/volume/aabb/aabb2.rs | //! Axis aligned bounding box for 2D.
//!
use std::fmt;
use cgmath::prelude::*;
use cgmath::{BaseFloat, BaseNum, Point2, Vector2};
use super::{max, min};
use crate::prelude::*;
use crate::{Line2, Ray2};
/// A two-dimensional AABB, aka a rectangle.
#[derive(Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Aabb2<S> {
/// Minimum point of the AABB
pub min: Point2<S>,
/// Maximum point of the AABB
pub max: Point2<S>,
}
impl<S: BaseNum> Aabb2<S> {
/// Construct a new axis-aligned bounding box from two points.
#[inline]
pub fn new(p1: Point2<S>, p2: Point2<S>) -> Aabb2<S> {
Aabb2 {
min: Point2::new(min(p1.x, p2.x), min(p1.y, p2.y)),
max: Point2::new(max(p1.x, p2.x), max(p1.y, p2.y)),
}
}
/// Compute corners.
#[inline]
pub fn to_corners(&self) -> [Point2<S>; 4] {
[
self.min,
Point2::new(self.max.x, self.min.y),
Point2::new(self.min.x, self.max.y),
self.max,
]
}
}
impl<S: BaseNum> Aabb for Aabb2<S> {
type Scalar = S;
type Diff = Vector2<S>;
type Point = Point2<S>;
#[inline]
fn new(p1: Point2<S>, p2: Point2<S>) -> Aabb2<S> {
Aabb2::new(p1, p2)
}
#[inline]
fn min(&self) -> Point2<S> {
self.min
}
#[inline]
fn max(&self) -> Point2<S> {
self.max
}
#[inline]
fn add_margin(&self, margin: Self::Diff) -> Self {
Aabb2::new(
Point2::new(self.min.x - margin.x, self.min.y - margin.y),
Point2::new(self.max.x + margin.x, self.max.y + margin.y),
)
}
#[inline]
fn transform<T>(&self, transform: &T) -> Self
where
T: Transform<Point2<S>>,
{
let corners = self.to_corners();
let transformed_first = transform.transform_point(corners[0]);
let base = Self::new(transformed_first, transformed_first);
corners[1..]
.iter()
.fold(base, |u, &corner| u.grow(transform.transform_point(corner)))
}
}
impl<S: BaseNum> fmt::Debug for Aabb2<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[{:?} - {:?}]", self.min, self.max)
}
}
impl<S: BaseNum> Contains<Point2<S>> for Aabb2<S> {
#[inline]
fn contains(&self, p: &Point2<S>) -> bool {
self.min.x <= p.x && p.x < self.max.x && self.min.y <= p.y && p.y < self.max.y
}
}
impl<S: BaseNum> Contains<Aabb2<S>> for Aabb2<S> {
#[inline]
fn contains(&self, other: &Aabb2<S>) -> bool {
let other_min = other.min();
let other_max = other.max();
other_min.x >= self.min.x
&& other_min.y >= self.min.y
&& other_max.x <= self.max.x
&& other_max.y <= self.max.y
}
}
impl<S: BaseNum> Contains<Line2<S>> for Aabb2<S> {
#[inline]
fn contains(&self, line: &Line2<S>) -> bool {
self.contains(&line.origin) && self.contains(&line.dest)
}
}
impl<S: BaseNum> Union for Aabb2<S> {
type Output = Aabb2<S>;
fn union(&self, other: &Aabb2<S>) -> Aabb2<S> {
self.grow(other.min()).grow(other.max())
}
}
impl<S: BaseNum> SurfaceArea for Aabb2<S> {
type Scalar = S;
fn surface_area(&self) -> S {
self.dim().x * self.dim().y
}
}
impl<S: BaseFloat> Continuous<Aabb2<S>> for Ray2<S> {
type Result = Point2<S>;
fn intersection(&self, aabb: &Aabb2<S>) -> Option<Point2<S>> {
let ray = self;
let mut tmin = S::neg_infinity();
let mut tmax = S::infinity();
if ray.direction.x != S::zero() {
let tx1 = (aabb.min.x - ray.origin.x) / ray.direction.x;
let tx2 = (aabb.max.x - ray.origin.x) / ray.direction.x;
tmin = tmin.max(tx1.min(tx2));
tmax = tmax.min(tx1.max(tx2));
} else if ray.origin.x <= aabb.min.x || ray.origin.x >= aabb.max.x {
return None;
}
if ray.direction.y != S::zero() {
let ty1 = (aabb.min.y - ray.origin.y) / ray.direction.y;
let ty2 = (aabb.max.y - ray.origin.y) / ray.direction.y;
tmin = tmin.max(ty1.min(ty2));
tmax = tmax.min(ty1.max(ty2));
} else if ray.origin.y <= aabb.min.y || ray.origin.y >= aabb.max.y {
return None;
}
if (tmin < S::zero() && tmax < S::zero()) || tmax < tmin {
None
} else {
let t = if tmin >= S::zero() { tmin } else { tmax };
Some(ray.origin + ray.direction * t)
}
}
}
impl<S: BaseFloat> Continuous<Ray2<S>> for Aabb2<S> {
type Result = Point2<S>;
fn intersection(&self, ray: &Ray2<S>) -> Option<Point2<S>> {
ray.intersection(self)
}
}
impl<S: BaseFloat> Discrete<Aabb2<S>> for Ray2<S> {
fn intersects(&self, aabb: &Aabb2<S>) -> bool {
let ray = self;
let mut tmin = S::neg_infinity();
let mut tmax = S::infinity();
if ray.direction.x != S::zero() {
let tx1 = (aabb.min.x - ray.origin.x) / ray.direction.x;
let tx2 = (aabb.max.x - ray.origin.x) / ray.direction.x;
tmin = tmin.max(tx1.min(tx2));
tmax = tmax.min(tx1.max(tx2));
} else if ray.origin.x <= aabb.min.x || ray.origin.x >= aabb.max.x {
return false;
}
if ray.direction.y != S::zero() {
let ty1 = (aabb.min.y - ray.origin.y) / ray.direction.y;
let ty2 = (aabb.max.y - ray.origin.y) / ray.direction.y;
tmin = tmin.max(ty1.min(ty2));
tmax = tmax.min(ty1.max(ty2));
} else if ray.origin.y <= aabb.min.y || ray.origin.y >= aabb.max.y {
return false;
}
tmax >= tmin && (tmin >= S::zero() || tmax >= S::zero())
}
}
impl<S: BaseFloat> Discrete<Ray2<S>> for Aabb2<S> {
fn intersects(&self, ray: &Ray2<S>) -> bool {
ray.intersects(self)
}
}
impl<S: BaseFloat> Discrete<Aabb2<S>> for Aabb2<S> {
fn intersects(&self, aabb: &Aabb2<S>) -> bool {
let (a0, a1) = (self.min(), self.max());
let (b0, b1) = (aabb.min(), aabb.max());
a1.x > b0.x && a0.x < b1.x && a1.y > b0.y && a0.y < b1.y
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/tests/serde.rs | tests/serde.rs | #![cfg(feature = "serde")]
use cgmath::Point1;
use serde_crate::Serialize;
fn has_serialize<S: Serialize>() -> bool {
true
}
#[test]
fn test_feature_enabled() {
assert!(has_serialize::<Point1<f32>>());
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/tests/aabb.rs | tests/aabb.rs | use cgmath::InnerSpace;
use cgmath::{Point2, Point3};
use cgmath::{Vector2, Vector3};
use collision::{Aabb, Aabb2, Aabb3};
use collision::{Contains, Continuous, Discrete, SurfaceArea, Union};
use collision::{Line2, Line3, Ray2, Ray3, Sphere};
use collision::{Plane, PlaneBound, Ray, Relation};
#[test]
fn test_general() {
let aabb = Aabb2::new(
Point2::new(-20isize, 30isize),
Point2::new(10isize, -10isize),
);
assert_eq!(aabb.min(), Point2::new(-20isize, -10isize));
assert_eq!(aabb.max(), Point2::new(10isize, 30isize));
assert_eq!(aabb.dim(), Vector2::new(30isize, 40isize));
assert_eq!(aabb.volume(), 30isize * 40isize);
assert_eq!(aabb.center(), Point2::new(-5isize, 10isize));
assert!(aabb.contains(&Point2::new(0isize, 0isize)));
assert!(!aabb.contains(&Point2::new(-50isize, -50isize)));
assert!(!aabb.contains(&Point2::new(50isize, 50isize)));
assert_eq!(aabb.grow(Point2::new(0isize, 0isize)), aabb);
assert_eq!(
aabb.grow(Point2::new(100isize, 100isize)),
Aabb2::new(
Point2::new(-20isize, -10isize),
Point2::new(100isize, 100isize),
)
);
assert_eq!(
aabb.grow(Point2::new(-100isize, -100isize)),
Aabb2::new(
Point2::new(-100isize, -100isize),
Point2::new(10isize, 30isize),
)
);
assert_eq!(
aabb.add_margin(Vector2::new(2isize, 2isize)),
Aabb2::new(
Point2::new(-22isize, -12isize),
Point2::new(12isize, 32isize),
)
);
let aabb = Aabb3::new(
Point3::new(-20isize, 30isize, 5isize),
Point3::new(10isize, -10isize, -5isize),
);
assert_eq!(aabb.min(), Point3::new(-20isize, -10isize, -5isize));
assert_eq!(aabb.max(), Point3::new(10isize, 30isize, 5isize));
assert_eq!(aabb.dim(), Vector3::new(30isize, 40isize, 10isize));
assert_eq!(aabb.volume(), 30isize * 40isize * 10isize);
assert_eq!(aabb.center(), Point3::new(-5isize, 10isize, 0isize));
assert!(aabb.contains(&Point3::new(0isize, 0isize, 0isize)));
assert!(!aabb.contains(&Point3::new(-100isize, 0isize, 0isize)));
assert!(!aabb.contains(&Point3::new(100isize, 0isize, 0isize)));
assert!(aabb.contains(&Point3::new(9isize, 29isize, -1isize)));
assert!(!aabb.contains(&Point3::new(10isize, 30isize, 5isize)));
assert!(aabb.contains(&Point3::new(-20isize, -10isize, -5isize)));
assert!(!aabb.contains(&Point3::new(-21isize, -11isize, -6isize)));
assert_eq!(
aabb.add_v(Vector3::new(1isize, 2isize, 3isize)),
Aabb3::new(
Point3::new(-19isize, 32isize, 8isize),
Point3::new(11isize, -8isize, -2isize),
)
);
assert_eq!(
aabb.mul_s(2isize),
Aabb3::new(
Point3::new(-40isize, -20isize, -10isize),
Point3::new(20isize, 60isize, 10isize),
)
);
assert_eq!(
aabb.mul_v(Vector3::new(1isize, 2isize, 3isize)),
Aabb3::new(
Point3::new(-20isize, -20isize, -15isize),
Point3::new(10isize, 60isize, 15isize),
)
);
assert_eq!(
aabb.add_margin(Vector3::new(2isize, 2isize, 2isize)),
Aabb3::new(
Point3::new(-22isize, -12isize, -7isize),
Point3::new(12isize, 32isize, 7isize),
)
);
}
#[test]
fn test_ray2_intersect() {
let aabb = Aabb2::new(Point2::new(-5.0f32, 5.0), Point2::new(5.0, 10.0));
let ray1 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(0.0, 1.0));
let ray2 = Ray::new(Point2::new(-10.0f32, 0.0), Vector2::new(2.5, 1.0));
let ray3 = Ray::new(Point2::new(0.0f32, 0.0), Vector2::new(-1.0, -1.0));
let ray4 = Ray::new(Point2::new(3.0f32, 7.0), Vector2::new(1.0, 1.0));
assert_eq!(ray1.intersection(&aabb), Some(Point2::new(0.0, 5.0)));
assert!(ray1.intersects(&aabb));
assert_eq!(ray2.intersection(&aabb), Some(Point2::new(2.5, 5.0)));
assert!(ray2.intersects(&aabb));
assert_eq!(ray3.intersection(&aabb), None);
assert!(!ray3.intersects(&aabb));
assert_eq!(ray4.intersection(&aabb), Some(Point2::new(5.0, 9.0)));
assert!(ray4.intersects(&aabb));
}
#[test]
fn test_parallel_ray3_should_not_intersect() {
let aabb = Aabb3::<f32>::new(Point3::new(1.0, 1.0, 1.0), Point3::new(5.0, 5.0, 5.0));
let ray_x = Ray::new(Point3::new(0.0f32, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0));
let ray_y = Ray::new(Point3::new(0.0f32, 0.0, 0.0), Vector3::new(0.0, 1.0, 0.0));
let ray_z = Ray::new(Point3::new(0.0f32, 0.0, 0.0), Vector3::new(0.0, 0.0, 1.0));
let ray_z_imprecise = Ray::new(
Point3::new(0.0f32, 0.0, 0.0),
Vector3::new(0.0001, 0.0001, 1.0),
);
assert_eq!(ray_x.intersection(&aabb), None);
assert!(!ray_x.intersects(&aabb));
assert_eq!(ray_y.intersection(&aabb), None);
assert!(!ray_y.intersects(&aabb));
assert_eq!(ray_z.intersection(&aabb), None);
assert!(!ray_z.intersects(&aabb));
assert_eq!(ray_z_imprecise.intersection(&aabb), None);
assert!(!ray_z_imprecise.intersects(&aabb));
}
#[test]
fn test_oblique_ray3_should_intersect() {
let aabb = Aabb3::<f32>::new(Point3::new(1.0, 1.0, 1.0), Point3::new(5.0, 5.0, 5.0));
let ray1 = Ray::new(
Point3::new(0.0f32, 0.0, 0.0),
Vector3::new(1.0, 1.0, 1.0).normalize(),
);
let ray2 = Ray::new(Point3::new(0.0f32, 6.0, 0.0), Vector3::new(1.0, -1.0, 1.0));
assert_eq!(ray1.intersection(&aabb), Some(Point3::new(1.0, 1.0, 1.0)));
assert!(ray1.intersects(&aabb));
assert_eq!(ray2.intersection(&aabb), Some(Point3::new(1.0, 5.0, 1.0)));
assert!(ray2.intersects(&aabb));
}
#[test]
fn test_pointing_to_other_dir_ray3_should_not_intersect() {
let aabb = Aabb3::<f32>::new(Point3::new(1.0, 1.0, 1.0), Point3::new(5.0, 5.0, 5.0));
let ray_x = Ray::new(
Point3::new(0.0f32, 2.0, 2.0),
Vector3::new(-1.0, 0.01, 0.01),
);
let ray_y = Ray::new(
Point3::new(2.0f32, 0.0, 2.0),
Vector3::new(0.01, -1.0, 0.01),
);
let ray_z = Ray::new(
Point3::new(2.0f32, 2.0, 0.0),
Vector3::new(0.01, 0.01, -1.0),
);
let ray_x2 = Ray::new(Point3::new(6.0f32, 2.0, 2.0), Vector3::new(1.0, 0.0, 0.0));
let ray_y2 = Ray::new(Point3::new(2.0f32, 6.0, 2.0), Vector3::new(0.0, 1.0, 0.0));
let ray_z2 = Ray::new(Point3::new(2.0f32, 2.0, 6.0), Vector3::new(0.0, 0.0, 1.0));
assert_eq!(ray_x.intersection(&aabb), None);
assert!(!ray_x.intersects(&aabb));
assert_eq!(ray_y.intersection(&aabb), None);
assert!(!ray_y.intersects(&aabb));
assert_eq!(ray_z.intersection(&aabb), None);
assert!(!ray_z.intersects(&aabb));
assert_eq!(ray_x2.intersection(&aabb), None);
assert!(!ray_x2.intersects(&aabb));
assert_eq!(ray_y2.intersection(&aabb), None);
assert!(!ray_y2.intersects(&aabb));
assert_eq!(ray_z2.intersection(&aabb), None);
assert!(!ray_z2.intersects(&aabb));
}
#[test]
fn test_pointing_to_box_dir_ray3_should_intersect() {
let aabb = Aabb3::<f32>::new(Point3::new(1.0, 1.0, 1.0), Point3::new(5.0, 5.0, 5.0));
let ray_x = Ray::new(Point3::new(0.0f32, 2.0, 2.0), Vector3::new(1.0, 0.0, 0.0));
let ray_y = Ray::new(Point3::new(2.0f32, 0.0, 2.0), Vector3::new(0.0, 1.0, 0.0));
let ray_z = Ray::new(Point3::new(2.0f32, 2.0, 0.0), Vector3::new(0.0, 0.0, 1.0));
let ray_x2 = Ray::new(Point3::new(6.0f32, 2.0, 2.0), Vector3::new(-1.0, 0.0, 0.0));
let ray_y2 = Ray::new(Point3::new(2.0f32, 6.0, 2.0), Vector3::new(0.0, -1.0, 0.0));
let ray_z2 = Ray::new(Point3::new(2.0f32, 2.0, 6.0), Vector3::new(0.0, 0.0, -1.0));
assert_eq!(ray_x.intersection(&aabb), Some(Point3::new(1.0, 2.0, 2.0)));
assert!(ray_x.intersects(&aabb));
assert_eq!(ray_y.intersection(&aabb), Some(Point3::new(2.0, 1.0, 2.0)));
assert!(ray_y.intersects(&aabb));
assert_eq!(ray_z.intersection(&aabb), Some(Point3::new(2.0, 2.0, 1.0)));
assert!(ray_z.intersects(&aabb));
assert_eq!(ray_x2.intersection(&aabb), Some(Point3::new(5.0, 2.0, 2.0)));
assert!(ray_x2.intersects(&aabb));
assert_eq!(ray_y2.intersection(&aabb), Some(Point3::new(2.0, 5.0, 2.0)));
assert!(ray_y2.intersects(&aabb));
assert_eq!(ray_z2.intersection(&aabb), Some(Point3::new(2.0, 2.0, 5.0)));
assert!(ray_z2.intersects(&aabb));
}
#[test]
fn test_corners() {
let corners = Aabb2::new(Point2::new(-5.0f32, 5.0), Point2::new(5.0, 10.0)).to_corners();
assert!(corners.contains(&Point2::new(-5f32, 10.0)));
assert!(corners.contains(&Point2::new(5f32, 5.0)));
let corners = Aabb3::new(
Point3::new(-20isize, 30isize, 5isize),
Point3::new(10isize, -10isize, -5isize),
)
.to_corners();
assert!(corners.contains(&Point3::new(-20isize, 30isize, -5isize)));
assert!(corners.contains(&Point3::new(10isize, 30isize, 5isize)));
assert!(corners.contains(&Point3::new(10isize, -10isize, 5isize)));
}
#[test]
fn test_bound() {
let aabb = Aabb3::new(Point3::new(-5.0f32, 5.0, 0.0), Point3::new(5.0, 10.0, 1.0));
let plane1 =
Plane::from_point_normal(Point3::new(0f32, 0.0, 0.0), Vector3::new(0f32, 0.0, 1.0));
let plane2 =
Plane::from_point_normal(Point3::new(-5.0f32, 4.0, 0.0), Vector3::new(0f32, 1.0, 0.0));
let plane3 =
Plane::from_point_normal(Point3::new(6.0f32, 0.0, 0.0), Vector3::new(1f32, 0.0, 0.0));
assert_eq!(aabb.relate_plane(plane1), Relation::Cross);
assert_eq!(aabb.relate_plane(plane2), Relation::In);
assert_eq!(aabb.relate_plane(plane3), Relation::Out);
}
#[test]
fn test_aab3_should_not_intersect() {
use collision::Discrete;
let a = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let b = Aabb3::new(Point3::new(15., 15., 15.), Point3::new(25., 25., 25.));
assert!(!a.intersects(&b));
}
#[test]
fn test_aab3_should_intersect() {
use collision::Discrete;
let a = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let b = Aabb3::new(Point3::new(5., 5., 5.), Point3::new(15., 15., 15.));
assert!(a.intersects(&b));
}
#[test]
fn test_aabb3_should_not_intersect_overlap_x() {
use collision::Discrete;
let a = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let b = Aabb3::new(Point3::new(5., 11., 11.), Point3::new(15., 13., 13.));
assert!(!a.intersects(&b));
}
#[test]
fn test_aabb3_should_not_intersect_overlap_y() {
use collision::Discrete;
let a = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let b = Aabb3::new(Point3::new(11., 5., 11.), Point3::new(15., 13., 13.));
assert!(!a.intersects(&b));
}
#[test]
fn test_aabb3_should_not_intersect_overlap_z() {
use collision::Discrete;
let a = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let b = Aabb3::new(Point3::new(11., 11., 5.), Point3::new(15., 13., 13.));
assert!(!a.intersects(&b));
}
#[test]
fn test_aabb2_contains_point2() {
let aabb = Aabb2::new(Point2::new(0., 0.), Point2::new(10., 10.));
let inside = Point2::new(2., 2.);
let outside = Point2::new(11., 11.);
assert!(aabb.contains(&inside));
assert!(!aabb.contains(&outside));
let aabb = Aabb2::<usize>::new(Point2::new(0, 0), Point2::new(10, 10));
let inside = Point2::new(2, 2);
let outside = Point2::new(11, 11);
assert!(aabb.contains(&inside));
assert!(!aabb.contains(&outside));
}
#[test]
fn test_aabb2_contains_line2() {
let aabb = Aabb2::new(Point2::new(0., 0.), Point2::new(10., 10.));
let inside = Line2::new(Point2::new(1., 1.), Point2::new(2., 2.));
let inside_out = Line2::new(Point2::new(1., 1.), Point2::new(12., 12.));
let outside = Line2::new(Point2::new(11., 11.), Point2::new(12., 12.));
assert!(aabb.contains(&inside));
assert!(!aabb.contains(&outside));
assert!(!aabb.contains(&inside_out));
}
#[test]
fn test_aabb2_contains_aabb2() {
let aabb = Aabb2::new(Point2::new(0., 0.), Point2::new(10., 10.));
let inside = Aabb2::new(Point2::new(1., 1.), Point2::new(2., 2.));
let inside_out = Aabb2::new(Point2::new(1., 1.), Point2::new(12., 12.));
let outside = Aabb2::new(Point2::new(11., 11.), Point2::new(12., 12.));
assert!(aabb.contains(&inside));
assert!(!aabb.contains(&outside));
assert!(!aabb.contains(&inside_out));
}
#[test]
fn test_aabb3_contains_point3() {
let aabb = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let inside = Point3::new(3., 3., 3.);
let outside = Point3::new(11., 11., 11.);
assert!(aabb.contains(&inside));
assert!(!aabb.contains(&outside));
let aabb = Aabb3::<usize>::new(Point3::new(0, 0, 0), Point3::new(10, 10, 10));
let inside = Point3::new(3, 3, 3);
let outside = Point3::new(11, 11, 11);
assert!(aabb.contains(&inside));
assert!(!aabb.contains(&outside));
}
#[test]
fn test_aabb3_contains_line3() {
let aabb = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let inside = Line3::new(Point3::new(1., 1., 1.), Point3::new(2., 2., 2.));
let inside_out = Line3::new(Point3::new(1., 1., 1.), Point3::new(12., 12., 12.));
let outside = Line3::new(Point3::new(11., 11., 11.), Point3::new(12., 12., 12.));
assert!(aabb.contains(&inside));
assert!(!aabb.contains(&outside));
assert!(!aabb.contains(&inside_out));
}
#[test]
fn test_aabb3_contains_aabb3() {
let aabb = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let inside = Aabb3::new(Point3::new(1., 1., 1.), Point3::new(2., 2., 2.));
let inside_out = Aabb3::new(Point3::new(1., 1., 1.), Point3::new(12., 12., 12.));
let outside = Aabb3::new(Point3::new(11., 11., 11.), Point3::new(12., 12., 12.));
assert!(aabb.contains(&inside));
assert!(!aabb.contains(&outside));
assert!(!aabb.contains(&inside_out));
}
#[test]
fn test_aabb3_contains_sphere() {
let aabb = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let inside = Sphere {
center: Point3::new(5., 5., 5.),
radius: 1.,
};
let inside_out = Sphere {
center: Point3::new(5., 5., 5.),
radius: 10.,
};
let outside = Sphere {
center: Point3::new(20., 20., 20.),
radius: 1.,
};
assert!(aabb.contains(&inside));
assert!(!aabb.contains(&outside));
assert!(!aabb.contains(&inside_out));
}
#[test]
fn test_ray_aabb2_parallel() {
let aabb = Aabb2::new(Point2::new(5., 5.), Point2::new(10., 10.));
let ray = Ray2::new(Point2::new(2., 0.), Vector2::new(0., 1.));
assert!(!ray.intersects(&aabb));
assert!(ray.intersection(&aabb).is_none());
let ray = Ray2::new(Point2::new(0., 2.), Vector2::new(1., 0.));
assert!(!ray.intersects(&aabb));
assert!(ray.intersection(&aabb).is_none());
}
#[test]
fn test_ray_aabb3_parallel() {
let aabb = Aabb3::new(Point3::new(5., 5., 5.), Point3::new(10., 10., 10.));
let ray = Ray3::new(Point3::new(2., 0., 2.), Vector3::new(0., 1., 0.));
assert!(!ray.intersects(&aabb));
assert!(ray.intersection(&aabb).is_none());
let ray = Ray3::new(Point3::new(0., 2., 2.), Vector3::new(1., 0., 0.));
assert!(!ray.intersects(&aabb));
assert!(ray.intersection(&aabb).is_none());
let ray = Ray3::new(Point3::new(2., 2., 0.), Vector3::new(0., 0., 1.));
assert!(!ray.intersects(&aabb));
assert!(ray.intersection(&aabb).is_none());
}
#[test]
fn test_aabb2_union_aabb2() {
let base = Aabb2::new(Point2::new(0., 0.), Point2::new(10., 10.));
let inside = Aabb2::new(Point2::new(2., 2.), Point2::new(5., 5.));
let outside = Aabb2::new(Point2::new(12., 12.), Point2::new(15., 15.));
let inside_out = Aabb2::new(Point2::new(2., 2.), Point2::new(12., 12.));
assert_eq!(base, base.union(&inside));
assert_eq!(
Aabb2::new(Point2::new(0., 0.), Point2::new(15., 15.)),
base.union(&outside)
);
assert_eq!(
Aabb2::new(Point2::new(0., 0.), Point2::new(12., 12.)),
base.union(&inside_out)
);
}
#[test]
fn test_aabb3_union_aabb3() {
let base = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let inside = Aabb3::new(Point3::new(2., 2., 2.), Point3::new(5., 5., 5.));
let outside = Aabb3::new(Point3::new(12., 12., 12.), Point3::new(15., 15., 15.));
let inside_out = Aabb3::new(Point3::new(2., 2., 2.), Point3::new(12., 12., 12.));
assert_eq!(base, base.union(&inside));
assert_eq!(
Aabb3::new(Point3::new(0., 0., 0.), Point3::new(15., 15., 15.)),
base.union(&outside)
);
assert_eq!(
Aabb3::new(Point3::new(0., 0., 0.), Point3::new(12., 12., 12.)),
base.union(&inside_out)
);
}
#[test]
fn test_aabb3_union_sphere() {
let base = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 10., 10.));
let inside = Sphere {
center: Point3::new(5., 5., 5.),
radius: 1.,
};
let outside = Sphere {
center: Point3::new(14., 14., 14.),
radius: 1.,
};
let inside_out = Sphere {
center: Point3::new(8., 8., 8.),
radius: 4.,
};
assert_eq!(base, base.union(&inside));
assert_eq!(
Aabb3::new(Point3::new(0., 0., 0.), Point3::new(15., 15., 15.)),
base.union(&outside)
);
assert_eq!(
Aabb3::new(Point3::new(0., 0., 0.), Point3::new(12., 12., 12.)),
base.union(&inside_out)
);
}
#[test]
fn test_aabb2_surface_area() {
let aabb = Aabb2::new(Point2::new(0., 0.), Point2::new(10., 20.));
assert!(200. - aabb.surface_area() <= f32::EPSILON);
}
#[test]
fn test_aabb3_surface_area() {
let aabb = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 20., 30.));
// 2 * (x*y + x*z + y*z)
assert!(2200. - aabb.surface_area() <= f32::EPSILON);
}
#[test]
fn test_aabb2_transform() {
let aabb = Aabb2::new(Point2::new(0., 0.), Point2::new(10., 20.));
let transform = cgmath::Decomposed::<Vector2<f32>, cgmath::Basis2<f32>> {
disp: Vector2::new(5., 3.),
scale: 1.,
rot: cgmath::Rotation2::from_angle(cgmath::Rad(0.)),
};
assert_eq!(
Aabb2::new(Point2::new(5., 3.), Point2::new(15., 23.)),
aabb.transform(&transform)
);
}
#[test]
fn test_aabb3_transform() {
let aabb = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(10., 20., 30.));
let transform = cgmath::Decomposed::<Vector3<f32>, cgmath::Basis3<f32>> {
disp: Vector3::new(5., 3., 1.),
scale: 1.,
rot: cgmath::Rotation3::from_angle_z(cgmath::Rad(0.)),
};
assert_eq!(
Aabb3::new(Point3::new(5., 3., 1.), Point3::new(15., 23., 31.)),
aabb.transform(&transform)
);
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/tests/dbvt.rs | tests/dbvt.rs | use cgmath::prelude::*;
use cgmath::{Deg, PerspectiveFov, Point2, Point3, Vector2, Vector3};
use collision::dbvt::*;
use collision::prelude::*;
use collision::{Aabb2, Aabb3, Frustum, Projection, Ray2, Relation};
use rand::Rng;
#[derive(Debug, Clone)]
struct Value2 {
pub id: u32,
pub aabb: Aabb2<f32>,
fat_aabb: Aabb2<f32>,
}
impl Value2 {
pub fn new(id: u32, aabb: Aabb2<f32>) -> Self {
Self {
id,
fat_aabb: aabb.add_margin(Vector2::new(0., 0.)),
aabb,
}
}
}
impl TreeValue for Value2 {
type Bound = Aabb2<f32>;
fn bound(&self) -> &Aabb2<f32> {
&self.aabb
}
fn get_bound_with_margin(&self) -> Aabb2<f32> {
self.fat_aabb
}
}
#[derive(Debug, Clone)]
struct Value3 {
pub id: u32,
pub aabb: Aabb3<f32>,
fat_aabb: Aabb3<f32>,
}
impl Value3 {
pub fn new(id: u32, aabb: Aabb3<f32>) -> Self {
Self {
id,
fat_aabb: aabb.add_margin(Vector3::new(3., 3., 3.)),
aabb,
}
}
}
impl TreeValue for Value3 {
type Bound = Aabb3<f32>;
fn bound(&self) -> &Aabb3<f32> {
&self.aabb
}
fn get_bound_with_margin(&self) -> Aabb3<f32> {
self.fat_aabb
}
}
#[test]
fn test_add_1() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
assert_eq!(1, tree.values().len());
assert_eq!(1, tree.size());
assert_eq!(1, tree.height());
}
#[test]
fn test_add_2() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.do_refit();
assert_eq!(2, tree.values().len());
assert_eq!(3, tree.size());
assert_eq!(2, tree.height());
}
#[test]
fn test_add_3() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.insert(Value2::new(12, aabb2(-12., -1., 0., 0.)));
tree.do_refit();
assert_eq!(3, tree.values().len());
assert_eq!(5, tree.size());
assert_eq!(3, tree.height());
}
#[test]
fn test_add_5() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.do_refit();
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.do_refit();
tree.insert(Value2::new(12, aabb2(-12., -1., 0., 0.)));
tree.do_refit();
tree.insert(Value2::new(13, aabb2(-200., -26., -185., -20.)));
tree.do_refit();
tree.insert(Value2::new(14, aabb2(56., 58., 99., 96.)));
tree.do_refit();
assert_eq!(5, tree.values().len());
assert_eq!(9, tree.size());
assert_eq!(4, tree.height());
}
#[test]
fn test_add_20() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
let mut rng = rand::thread_rng();
for i in 0..20 {
let offset = rng.gen_range(-10.0..10.0);
tree.insert(Value2::new(
i,
aabb2(offset + 0.1, offset + 0.1, offset + 0.3, offset + 0.3),
));
tree.do_refit();
}
assert_eq!(20, tree.values().len());
assert_eq!(39, tree.size());
}
#[test]
fn test_remove_leaf_right_side() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.insert(Value2::new(12, aabb2(-12., -1., 0., 0.)));
tree.insert(Value2::new(13, aabb2(-200., -26., -185., -20.)));
tree.insert(Value2::new(14, aabb2(56., 58., 99., 96.)));
tree.do_refit();
let node_index = tree.values()[4].0;
tree.remove(node_index);
tree.do_refit();
assert_eq!(4, tree.values().len());
assert_eq!(7, tree.size());
assert_eq!(4, tree.height());
}
#[test]
fn test_remove_leaf_left_side() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.insert(Value2::new(12, aabb2(-12., -1., 0., 0.)));
tree.insert(Value2::new(13, aabb2(-200., -26., -185., -20.)));
tree.insert(Value2::new(14, aabb2(56., 58., 99., 96.)));
tree.do_refit();
let node_index = tree.values()[3].0;
tree.remove(node_index);
tree.do_refit();
assert_eq!(4, tree.values().len());
assert_eq!(7, tree.size());
assert_eq!(3, tree.height());
}
#[test]
fn test_remove_leaf_left_side_2() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.insert(Value2::new(12, aabb2(-12., -1., 0., 0.)));
tree.insert(Value2::new(13, aabb2(-200., -26., -185., -20.)));
tree.insert(Value2::new(14, aabb2(56., 58., 99., 96.)));
tree.do_refit();
let node_index = tree.values()[3].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
tree.do_refit();
assert_eq!(3, tree.values().len());
assert_eq!(5, tree.size());
assert_eq!(3, tree.height());
}
#[test]
fn test_remove_leaf_left_side_3() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.insert(Value2::new(12, aabb2(-12., -1., 0., 0.)));
tree.insert(Value2::new(13, aabb2(-200., -26., -185., -20.)));
tree.insert(Value2::new(14, aabb2(56., 58., 99., 96.)));
tree.do_refit();
let node_index = tree.values()[3].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
let node_index = tree.values()[1].0;
tree.remove(node_index);
tree.do_refit();
assert_eq!(2, tree.values().len());
assert_eq!(3, tree.size());
assert_eq!(2, tree.height());
}
#[test]
fn test_remove_leaf_left_right() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.insert(Value2::new(12, aabb2(-12., -1., 0., 0.)));
tree.insert(Value2::new(13, aabb2(-200., -26., -185., -20.)));
tree.insert(Value2::new(14, aabb2(56., 58., 99., 96.)));
tree.do_refit();
let node_index = tree.values()[3].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
tree.do_refit();
assert_eq!(2, tree.values().len());
assert_eq!(3, tree.size());
assert_eq!(2, tree.height());
}
#[test]
fn test_remove_second_to_last() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.insert(Value2::new(12, aabb2(-12., -1., 0., 0.)));
tree.insert(Value2::new(13, aabb2(-200., -26., -185., -20.)));
tree.insert(Value2::new(14, aabb2(56., 58., 99., 96.)));
tree.do_refit();
let node_index = tree.values()[3].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
tree.do_refit();
assert_eq!(1, tree.values().len());
assert_eq!(1, tree.size());
assert_eq!(1, tree.height());
}
#[test]
fn test_remove_last() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 10., 10.)));
tree.insert(Value2::new(11, aabb2(21., 14., 23., 16.)));
tree.insert(Value2::new(12, aabb2(-12., -1., 0., 0.)));
tree.insert(Value2::new(13, aabb2(-200., -26., -185., -20.)));
tree.insert(Value2::new(14, aabb2(56., 58., 99., 96.)));
tree.do_refit();
let node_index = tree.values()[3].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
let node_index = tree.values()[0].0;
tree.remove(node_index);
tree.do_refit();
assert_eq!(0, tree.values().len());
assert_eq!(0, tree.size());
assert_eq!(0, tree.height());
}
#[test]
fn test_ray_closest() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(12, aabb2(0., 0., 10., 10.)));
tree.insert(Value2::new(33, aabb2(15., 3., 3., 3.)));
tree.insert(Value2::new(13, aabb2(-145., 34., 2., 2.)));
tree.insert(Value2::new(66, aabb2(123., -10., 10., 10.)));
tree.insert(Value2::new(1, aabb2(22., 50., 16., 16.)));
tree.insert(Value2::new(76, aabb2(7., 3., 1., 1.)));
tree.insert(Value2::new(99, aabb2(19., -12., 3., 3.)));
tree.do_refit();
let result = query_ray_closest(
&tree,
Ray2::new(Point2::new(12., 12.), Vector2::new(0.5, -0.5).normalize()),
);
assert!(result.is_some());
let (v, p) = result.unwrap();
assert_eq!(33, v.id);
assert_eq!(Point2::new(18., 5.9999995), p);
}
#[test]
fn test_ray_discrete() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 5., 15.)));
tree.insert(Value2::new(11, aabb2(21., 14., 2., 2.)));
tree.do_refit();
let ray = Ray2::new(Point2::new(0., 0.), Vector2::new(-1., -1.).normalize());
let mut visitor = DiscreteVisitor::<Ray2<f32>, Value2>::new(&ray);
assert_eq!(0, tree.query(&mut visitor).len());
let ray = Ray2::new(Point2::new(6., 0.), Vector2::new(0., 1.).normalize());
let mut visitor = DiscreteVisitor::<Ray2<f32>, Value2>::new(&ray);
let results = tree.query(&mut visitor);
assert_eq!(1, results.len());
assert_eq!(10, results[0].0.id);
}
#[test]
fn test_ray_continuous() {
let mut tree = DynamicBoundingVolumeTree::<Value2>::new();
tree.insert(Value2::new(10, aabb2(5., 5., 5., 15.)));
tree.insert(Value2::new(11, aabb2(21., 14., 2., 2.)));
tree.do_refit();
let ray = Ray2::new(Point2::new(0., 0.), Vector2::new(-1., -1.).normalize());
let mut visitor = ContinuousVisitor::<Ray2<f32>, Value2>::new(&ray);
assert_eq!(0, tree.query(&mut visitor).len());
let ray = Ray2::new(Point2::new(6., 0.), Vector2::new(0., 1.).normalize());
let mut visitor = ContinuousVisitor::<Ray2<f32>, Value2>::new(&ray);
let results = tree.query(&mut visitor);
assert_eq!(1, results.len());
assert_eq!(10, results[0].0.id);
assert_eq!(Point2::new(6., 5.), results[0].1);
}
#[test]
fn test_frustum() {
let mut tree = DynamicBoundingVolumeTree::<Value3>::new();
tree.insert(Value3::new(10, aabb3(0.2, 0.2, 0.2, 10., 10., 10.)));
tree.insert(Value3::new(11, aabb3(0.2, 0.2, -0.2, 10., 10., -10.)));
tree.do_refit();
let frustum = frustum();
let mut visitor = FrustumVisitor::<f32, Value3>::new(&frustum);
let result = tree.query(&mut visitor);
assert_eq!(1, result.len());
let (v, r) = result[0];
assert_eq!(Relation::Cross, r);
assert_eq!(11, v.id);
}
fn aabb2(minx: f32, miny: f32, width: f32, height: f32) -> Aabb2<f32> {
Aabb2::new(
Point2::new(minx, miny),
Point2::new(minx + width, miny + height),
)
}
fn aabb3(minx: f32, miny: f32, minz: f32, maxx: f32, maxy: f32, maxz: f32) -> Aabb3<f32> {
Aabb3::new(Point3::new(minx, miny, minz), Point3::new(maxx, maxy, maxz))
}
// Default perspective projection is looking down the negative z axis
fn frustum() -> Frustum<f32> {
let projection = PerspectiveFov {
fovy: Deg(60.).into(),
aspect: 16. / 9.,
near: 0.1,
far: 4.0,
};
projection.to_frustum()
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/tests/plane.rs | tests/plane.rs | use cgmath::*;
use collision::*;
#[test]
fn test_from_points() {
assert_eq!(
Plane::from_points(
Point3::new(5.0f64, 0.0f64, 5.0f64),
Point3::new(5.0f64, 5.0f64, 5.0f64),
Point3::new(5.0f64, 0.0f64, -1.0f64),
),
Some(Plane::from_abcd(-1.0f64, 0.0f64, 0.0f64, 5.0f64))
);
assert_eq!(
Plane::from_points(
Point3::new(0.0f64, 5.0f64, -5.0f64),
Point3::new(0.0f64, 5.0f64, 0.0f64),
Point3::new(0.0f64, 5.0f64, 5.0f64),
),
None
); // The points are parallel
}
#[test]
fn test_ray_intersection() {
let p0 = Plane::from_abcd(1f64, 0f64, 0f64, -7f64);
let r0: Ray3<f64> = Ray::new(
Point3::new(2f64, 3f64, 4f64),
Vector3::new(1f64, 1f64, 1f64).normalize(),
);
assert!(p0.intersects(&r0));
assert_eq!(p0.intersection(&r0), Some(Point3::new(7f64, 8f64, 9f64)));
let p1 = Plane::from_points(
Point3::new(5f64, 0f64, 5f64),
Point3::new(5f64, 5f64, 5f64),
Point3::new(5f64, 0f64, -1f64),
)
.unwrap();
let r1: Ray3<f64> = Ray::new(
Point3::new(0f64, 0f64, 0f64),
Vector3::new(-1f64, 0f64, 0f64).normalize(),
);
assert_eq!(p1.intersection(&r1), None); // r1 points away from p1
assert!(!p1.intersects(&r1));
}
#[test]
fn test_plane2_intersection() {
let p0 = Plane::new(Vector3::unit_x(), 1.0f64);
let p1 = Plane::new(Vector3::unit_y(), 2.0f64);
let ray = p0.intersection(&p1);
assert!(ray.is_some());
assert!(p0.intersects(&p1));
let ray = ray.unwrap();
assert_ulps_eq!(ray.origin.x, &1.0f64);
assert_ulps_eq!(ray.origin.y, &2.0f64);
assert_ulps_eq!(ray.origin.z, &0.0f64);
assert_ulps_eq!(ray.direction.x, &0.0f64);
assert_ulps_eq!(ray.direction.y, &0.0f64);
assert_ulps_eq!(ray.direction.z, &1.0f64);
let p0 = Plane::new(Vector3::unit_y(), 1.0f64);
let p1 = Plane::new(Vector3::unit_y(), 2.0f64);
let ray = p0.intersection(&p1);
assert!(ray.is_none());
assert!(!p0.intersects(&p1));
}
#[test]
fn test_plane3_intersection() {
let p0 = Plane::new(Vector3::unit_x(), 1.0f64);
let p1 = Plane::new(Vector3::unit_y(), 2.0f64);
let p2 = Plane::new(Vector3::unit_z(), 3.0f64);
let point = p0.intersection(&(p1, p2));
assert!(point.is_some());
assert!(p0.intersects(&(p1, p2)));
let point = point.unwrap();
assert_ulps_eq!(point.x, &1.0f64);
assert_ulps_eq!(point.y, &2.0f64);
assert_ulps_eq!(point.z, &3.0f64);
let p0 = Plane::new(Vector3::unit_y(), 1.0f64);
let p1 = Plane::new(Vector3::unit_y(), 2.0f64);
let p2 = Plane::new(Vector3::unit_z(), 3.0f64);
let point = p0.intersection(&(p1, p2));
assert!(point.is_none());
assert!(!p0.intersects(&(p1, p2)));
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/tests/bound.rs | tests/bound.rs | use collision::PlaneBound;
fn _box(_: Box<dyn PlaneBound<f32>>) {}
#[test]
fn bound_box() {}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/tests/point.rs | tests/point.rs | use cgmath::assert_ulps_eq;
use cgmath::{Point3, Vector3};
use collision::{Continuous, Plane, PlaneBound, Ray3, Relation};
#[test]
fn test_homogeneous() {
let p = Point3::new(1.0f64, 2.0f64, 3.0f64);
assert_ulps_eq!(p, &Point3::from_homogeneous(p.to_homogeneous()));
}
#[test]
fn test_bound() {
let point = Point3::new(1f32, 2.0, 3.0);
let normal = Vector3::new(0f32, -0.8, -0.36);
let plane = Plane::from_point_normal(point, normal);
assert_eq!(point.relate_plane(plane), Relation::Cross);
assert_eq!((point + normal).relate_plane(plane), Relation::In);
assert_eq!((point + normal * -1.0).relate_plane(plane), Relation::Out);
}
#[test]
fn test_ray_intersect() {
let point = Point3::new(1f32, 2.0, 3.0);
// ray across the point
let ray1 = Ray3::new(Point3::new(1f32, 2.0, 0.0), Vector3::new(0.0, 0.0, 1.0));
assert_eq!(point.intersection(&ray1), Some(point));
// ray in the opposite direction
let ray2 = Ray3::new(Point3::new(1f32, 2.0, 0.0), Vector3::new(0.0, 0.0, -1.0));
assert_eq!(point.intersection(&ray2), None);
// unrelated ray
let ray3 = Ray3::new(Point3::new(1f32, 0.0, 0.0), Vector3::new(0.0, 0.0, 1.0));
assert_eq!(point.intersection(&ray3), None);
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/tests/sphere.rs | tests/sphere.rs | use cgmath::*;
use collision::*;
#[test]
fn test_intersection() {
let sphere = Sphere {
center: Point3::new(0f64, 0f64, 0f64),
radius: 1f64,
};
let r0 = Ray::new(
Point3::new(0f64, 0f64, 5f64),
Vector3::new(0f64, 0f64, -5f64).normalize(),
);
let r1 = Ray::new(
Point3::new(1f64.cos(), 0f64, 5f64),
Vector3::new(0f64, 0f64, -5f64).normalize(),
);
let r2 = Ray::new(
Point3::new(1f64, 0f64, 5f64),
Vector3::new(0f64, 0f64, -5f64).normalize(),
);
let r3 = Ray::new(
Point3::new(2f64, 0f64, 5f64),
Vector3::new(0f64, 0f64, -5f64).normalize(),
);
assert_eq!(
sphere.intersection(&r0),
Some(Point3::new(0f64, 0f64, 1f64))
);
assert!(sphere.intersects(&r0));
assert_ulps_eq!(
sphere.intersection(&r1).unwrap(),
&Point3::new(1f64.cos(), 0f64, 1f64.sin())
);
assert!(sphere.intersects(&r1));
assert_eq!(
sphere.intersection(&r2),
Some(Point3::new(1f64, 0f64, 0f64))
);
assert!(sphere.intersects(&r2));
assert_eq!(sphere.intersection(&r3), None);
assert!(!sphere.intersects(&r3));
}
#[test]
fn test_bound() {
let point = Point3::new(1f32, 2.0, 3.0);
let sphere = Sphere {
center: point,
radius: 1.0,
};
let normal = vec3(0f32, 0.0, 1.0);
assert_eq!(
sphere.relate_plane(Plane::from_point_normal(point, normal)),
Relation::Cross
);
assert_eq!(
sphere.relate_plane(Plane::from_point_normal(point + normal * -3.0, normal)),
Relation::In
);
assert_eq!(
sphere.relate_plane(Plane::from_point_normal(point + normal * 3.0, normal)),
Relation::Out
);
}
#[test]
fn test_sphere_contains_point() {
let sphere = Sphere {
center: Point3::new(1f32, 2., 3.),
radius: 1.,
};
let inside_p = Point3::new(1f32, 2.2, 3.);
let outside_p = Point3::new(11f32, 2.2, 3.);
assert!(sphere.contains(&inside_p));
assert!(!sphere.contains(&outside_p));
}
#[test]
fn test_sphere_contains_line() {
let sphere = Sphere {
center: Point3::new(1f32, 2., 3.),
radius: 1.,
};
let inside = Line3::new(Point3::new(1f32, 2., 3.), Point3::new(1f32, 2.2, 3.));
let outside = Line3::new(Point3::new(11f32, 2., 3.), Point3::new(11f32, 2.2, 3.));
let inside_out = Line3::new(Point3::new(1f32, 2., 3.), Point3::new(11f32, 2.2, 3.));
assert!(sphere.contains(&inside));
assert!(!sphere.contains(&outside));
assert!(!sphere.contains(&inside_out));
}
#[test]
fn test_sphere_contains_sphere() {
let sphere = Sphere {
center: Point3::new(1f32, 2., 3.),
radius: 1.,
};
let inside = Sphere {
center: Point3::new(1f32, 2., 3.),
radius: 0.1,
};
let outside = Sphere {
center: Point3::new(11f32, 2., 3.),
radius: 0.1,
};
let inside_out = Sphere {
center: Point3::new(1f32, 2., 3.),
radius: 10.,
};
assert!(sphere.contains(&inside));
assert!(!sphere.contains(&outside));
assert!(!sphere.contains(&inside_out));
}
#[test]
fn test_sphere_contains_aabb() {
let sphere = Sphere {
center: Point3::new(1f32, 2., 3.),
radius: 1.,
};
let inside = Aabb3::new(Point3::new(1f32, 2., 3.), Point3::new(1f32, 2.2, 3.));
let outside = Aabb3::new(Point3::new(11f32, 2., 3.), Point3::new(11f32, 2.2, 3.));
let inside_out = Aabb3::new(Point3::new(1f32, 2., 3.), Point3::new(11f32, 2.2, 3.));
let edge_case = Aabb3::new(Point3::new(1f32, 1.01, 3.), Point3::new(1.99f32, 2., 3.99));
assert!(sphere.contains(&inside));
assert!(!sphere.contains(&outside));
assert!(!sphere.contains(&inside_out));
assert!(!sphere.contains(&edge_case));
}
#[test]
fn test_sphere_union_sphere() {
let base = Sphere {
center: Point3::new(0., 0., 0.),
radius: 5.,
};
let inside = Sphere {
center: Point3::new(1., 1., 1.),
radius: 1.,
};
let outside = Sphere {
center: Point3::new(8., 8., 8.),
radius: 1.,
};
let inside_out = Sphere {
center: Point3::new(4., 4., 4.),
radius: 3.,
};
assert_eq!(base, base.union(&inside));
assert_eq!(
Sphere {
center: Point3::new(2.8452994616207485, 2.8452994616207485, 2.8452994616207485),
radius: 9.928203230275509,
},
base.union(&outside)
);
assert_eq!(
Sphere {
center: Point3::new(1.4226497308103743, 1.4226497308103743, 1.4226497308103743),
radius: 7.464101615137754,
},
base.union(&inside_out)
);
}
#[test]
fn test_sphere_union_aabb3() {
let base = Sphere {
center: Point3::new(0., 0., 0.),
radius: 5.,
};
let inside = Aabb3::new(Point3::new(0., 0., 0.), Point3::new(2., 2., 2.));
let outside = Aabb3::new(Point3::new(6., 6., 6.), Point3::new(9., 9., 9.));
let inside_out = Aabb3::new(Point3::new(4., 4., 4.), Point3::new(7., 7., 7.));
assert_eq!(base, base.union(&inside));
assert_eq!(
Sphere {
center: Point3::new(3.0566243270259355, 3.0566243270259355, 3.0566243270259355),
radius: 10.294228634059948,
},
base.union(&outside)
);
assert_eq!(
Sphere {
center: Point3::new(2.0566243270259355, 2.0566243270259355, 2.0566243270259355),
radius: 8.56217782649107,
},
base.union(&inside_out)
);
}
#[test]
fn test_surface_area() {
let base = Sphere {
center: Point3::new(2., 1., -4.),
radius: 2.,
};
// 4 * pi * r^2
assert!((4. * std::f64::consts::PI * 2. * 2.) - base.surface_area() <= f64::EPSILON);
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/tests/frustum.rs | tests/frustum.rs | use cgmath::{PerspectiveFov, Point3, Rad};
use collision::{Projection, Relation, Sphere};
#[test]
fn test_contains() {
let frustum = PerspectiveFov {
fovy: Rad(1f32),
aspect: 1f32,
near: 1f32,
far: 10f32,
}
.to_frustum();
assert_eq!(
frustum.contains(&Sphere {
center: Point3::new(0f32, 0f32, -5f32),
radius: 1f32,
}),
Relation::In
);
assert_eq!(
frustum.contains(&Sphere {
center: Point3::new(0f32, 3f32, -5f32),
radius: 1f32,
}),
Relation::Cross
);
assert_eq!(
frustum.contains(&Sphere {
center: Point3::new(0f32, 0f32, 5f32),
radius: 1f32,
}),
Relation::Out
);
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/benches/dbvt.rs | benches/dbvt.rs | #![feature(test)]
extern crate test;
use cgmath::prelude::*;
use cgmath::{Point2, Vector2};
use collision::dbvt::*;
use collision::prelude::*;
use collision::{Aabb2, Ray2};
use rand::Rng;
use test::Bencher;
#[derive(Debug, Clone)]
struct Value {
pub id: u32,
pub aabb: Aabb2<f32>,
fat_aabb: Aabb2<f32>,
}
impl Value {
pub fn new(id: u32, aabb: Aabb2<f32>) -> Self {
Self {
id,
fat_aabb: aabb.add_margin(Vector2::new(0., 0.)),
aabb,
}
}
}
impl TreeValue for Value {
type Bound = Aabb2<f32>;
fn bound(&self) -> &Aabb2<f32> {
&self.aabb
}
fn get_bound_with_margin(&self) -> Aabb2<f32> {
self.fat_aabb
}
}
#[bench]
fn benchmark_insert(b: &mut Bencher) {
let mut rng = rand::thread_rng();
let mut tree = DynamicBoundingVolumeTree::<Value>::new();
let mut i = 0;
b.iter(|| {
let offset = rng.gen_range(0.0..100.0);
tree.insert(Value::new(
i,
aabb2(offset + 2., offset + 2., offset + 4., offset + 4.),
));
i += 1;
});
}
#[bench]
fn benchmark_do_refit(b: &mut Bencher) {
let mut rng = rand::thread_rng();
let mut tree = DynamicBoundingVolumeTree::<Value>::new();
let mut i = 0;
b.iter(|| {
let offset = rng.gen_range(0.0..100.0);
tree.insert(Value::new(
i,
aabb2(offset + 2., offset + 2., offset + 4., offset + 4.),
));
tree.do_refit();
i += 1;
});
}
#[bench]
fn benchmark_query(b: &mut Bencher) {
let mut rng = rand::thread_rng();
let mut tree = DynamicBoundingVolumeTree::<Value>::new();
for i in 0..100000 {
let neg_y = if rng.gen::<bool>() { -1. } else { 1. };
let neg_x = if rng.gen::<bool>() { -1. } else { 1. };
let offset_x = neg_x * rng.gen_range(9000.0..10000.0);
let offset_y = neg_y * rng.gen_range(9000.0..10000.0);
tree.insert(Value::new(
i,
aabb2(offset_x + 2., offset_y + 2., offset_x + 4., offset_y + 4.),
));
tree.tick();
}
let rays: Vec<Ray2<f32>> = (0..1000)
.map(|_| {
let p = Point2::new(
rng.gen_range(-10000.0..10000.0),
rng.gen_range(-10000.0..10000.0),
);
let d = Vector2::new(rng.gen_range(-1.0..1.0), rng.gen_range(-1.0..1.0)).normalize();
Ray2::new(p, d)
})
.collect();
let mut visitors: Vec<DiscreteVisitor<Ray2<f32>, Value>> = rays
.iter()
.map(|ray| DiscreteVisitor::<Ray2<f32>, Value>::new(ray))
.collect();
let mut i = 0;
b.iter(|| {
tree.query(&mut visitors[i % 1000]).len();
i += 1;
});
}
#[bench]
fn benchmark_ray_closest_query(b: &mut Bencher) {
let mut rng = rand::thread_rng();
let mut tree = DynamicBoundingVolumeTree::<Value>::new();
for i in 0..100000 {
let neg_y = if rng.gen::<bool>() { -1. } else { 1. };
let neg_x = if rng.gen::<bool>() { -1. } else { 1. };
let offset_x = neg_x * rng.gen_range(9000.0..10000.0);
let offset_y = neg_y * rng.gen_range(9000.0..10000.0);
tree.insert(Value::new(
i,
aabb2(offset_x + 2., offset_y + 2., offset_x + 4., offset_y + 4.),
));
tree.tick();
}
let rays: Vec<Ray2<f32>> = (0..1000)
.map(|_| {
let p = Point2::new(
rng.gen_range(-10000.0..10000.0),
rng.gen_range(-10000.0..10000.0),
);
let d = Vector2::new(rng.gen_range(-1.0..1.0), rng.gen_range(-1.0..1.0)).normalize();
Ray2::new(p, d)
})
.collect();
let mut i = 0;
b.iter(|| {
query_ray_closest(&tree, rays[i % 1000]);
i += 1;
});
}
fn aabb2(minx: f32, miny: f32, maxx: f32, maxy: f32) -> Aabb2<f32> {
Aabb2::new(Point2::new(minx, miny), Point2::new(maxx, maxy))
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
rustgd/collision-rs | https://github.com/rustgd/collision-rs/blob/29090c42a1716d80c1a4fb12e4e1dc2d9c18580e/benches/polyhedron.rs | benches/polyhedron.rs | #![feature(test)]
extern crate test;
use cgmath::prelude::*;
use cgmath::{Decomposed, Point3, Quaternion, Vector3};
use collision::prelude::*;
use collision::primitive::ConvexPolyhedron;
use genmesh::generators::{IndexedPolygon, SharedVertex, SphereUV};
use genmesh::Triangulate;
use rand::Rng;
use test::{black_box, Bencher};
#[bench]
fn test_polyhedron_10(bench: &mut Bencher) {
test_polyhedron(bench, 10, false);
}
#[bench]
fn test_polyhedron_faces_10(bench: &mut Bencher) {
test_polyhedron(bench, 10, true);
}
#[bench]
fn test_polyhedron_20(bench: &mut Bencher) {
test_polyhedron(bench, 20, false);
}
#[bench]
fn test_polyhedron_faces_20(bench: &mut Bencher) {
test_polyhedron(bench, 20, true);
}
#[bench]
fn test_polyhedron_30(bench: &mut Bencher) {
test_polyhedron(bench, 30, false);
}
#[bench]
fn test_polyhedron_faces_30(bench: &mut Bencher) {
test_polyhedron(bench, 30, true);
}
#[bench]
fn test_polyhedron_50(bench: &mut Bencher) {
test_polyhedron(bench, 50, false);
}
#[bench]
fn test_polyhedron_faces_50(bench: &mut Bencher) {
test_polyhedron(bench, 50, true);
}
#[bench]
fn test_polyhedron_500(bench: &mut Bencher) {
test_polyhedron(bench, 500, false);
}
#[bench]
fn test_polyhedron_faces_500(bench: &mut Bencher) {
test_polyhedron(bench, 500, true);
}
fn test_polyhedron(bench: &mut Bencher, n: usize, with_faces: bool) {
let polyhedron = sphere(n, with_faces);
let dirs = dirs(1000);
let transform = Decomposed::<Vector3<f32>, Quaternion<f32>>::one();
let mut i = 0;
bench.iter(|| {
black_box(polyhedron.support_point(&dirs[i % 1000], &transform));
i += 1;
});
}
fn dirs(n: usize) -> Vec<Vector3<f32>> {
let mut rng = rand::thread_rng();
(0..n)
.map(|_| {
Vector3::new(
rng.gen_range(-1.0..1.0),
rng.gen_range(-1.0..1.0),
rng.gen_range(-1.0..1.0),
)
})
.collect::<Vec<_>>()
}
fn sphere(n: usize, with_faces: bool) -> ConvexPolyhedron<f32> {
let gen = SphereUV::new(n, n);
let vertices = gen
.shared_vertex_iter()
.map(|v| Point3::from(v.pos))
.collect::<Vec<_>>();
if with_faces {
let faces = gen
.indexed_polygon_iter()
.triangulate()
.map(|f| (f.x, f.y, f.z))
.collect::<Vec<_>>();
ConvexPolyhedron::new_with_faces(&vertices, &faces)
} else {
ConvexPolyhedron::new(&vertices)
}
}
| rust | Apache-2.0 | 29090c42a1716d80c1a4fb12e4e1dc2d9c18580e | 2026-01-04T20:23:49.286122Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.