more optimisation whatever idk really know what I am doing

This commit is contained in:
MayaTheShy
2025-11-02 00:32:46 -04:00
parent 4a761f27dd
commit 3cc68df2d9
2 changed files with 277 additions and 172 deletions

View File

@@ -8,8 +8,8 @@ use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use single::{APP_SIZE, App, BTN_COLOR, BTN_SELECTED_COLOR, MODEL_SCALE}; use single::{APP_SIZE, App, BTN_COLOR, BTN_SELECTED_COLOR, MODEL_SCALE};
use stardust_xr_asteroids::{ use stardust_xr_asteroids::{
ClientState, CustomElement, Element, Migrate, Reify, Transformable, client, ClientState, CustomElement, Element, Migrate, Reify, Transformable, client,
elements::{Button, Grabbable, Model, ModelPart}, elements::{Button, Grabbable, Model, ModelPart, PointerMode, Spatial},
}; };
use stardust_xr_fusion::{ use stardust_xr_fusion::{
drawable::MaterialParameter, drawable::MaterialParameter,
@@ -17,6 +17,8 @@ use stardust_xr_fusion::{
project_local_resources, project_local_resources,
spatial::Transform, spatial::Transform,
}; };
use stardust_xr_fusion::values::ResourceID;
use std::path::PathBuf;
use std::f32::consts::{FRAC_PI_2, PI}; use std::f32::consts::{FRAC_PI_2, PI};
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::atomic::AtomicU64; use std::sync::atomic::AtomicU64;
@@ -70,16 +72,26 @@ async fn main() {
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct HexagonLauncher { pub struct HexagonLauncher {
/// if the hexagon launcher is expanded /// if the hexagon launcher is expanded
open: bool, open: bool,
pos: Vector3<f32>, pos: Vector3<f32>,
rot: Quaternion<f32>, rot: Quaternion<f32>,
#[serde(skip)]
/// position in the vector is mapped to hex coordinates
apps: Vec<App>,
#[serde(skip)]
/// cached world coordinates for each app hex
positions: Vec<[f32; 3]>,
#[serde(skip)] #[serde(skip)]
/// position in the vector is mapped to hex coordinates /// lightweight immutable snapshots for fast per-frame reify
apps: Vec<App>, snapshots: Vec<Snapshot>,
#[serde(skip)] }
/// cached world coordinates for each app hex
positions: Vec<[f32; 3]>, #[derive(Clone)]
struct Snapshot {
name: String,
cached_texture: Option<ResourceID>,
cached_gltf: Option<PathBuf>,
} }
impl Default for HexagonLauncher { impl Default for HexagonLauncher {
@@ -90,6 +102,7 @@ impl Default for HexagonLauncher {
rot: Quat::IDENTITY.into(), rot: Quat::IDENTITY.into(),
apps: Vec::new(), apps: Vec::new(),
positions: Vec::new(), positions: Vec::new(),
snapshots: Vec::new(),
} }
} }
} }
@@ -133,23 +146,36 @@ impl ClientState for HexagonLauncher {
self.apps.par_iter().for_each(|app| { self.apps.par_iter().for_each(|app| {
// GLTF path warm: call Model::direct once (parser/cache warm-up) // GLTF path warm: call Model::direct once (parser/cache warm-up)
if let Some(gltf_path) = app.cached_gltf.get() { if let Some(gltf_path) = app.cached_gltf.get() {
let _ = Model::direct(gltf_path.to_string_lossy().to_string()); if let Ok(builder) = Model::direct(gltf_path.to_string_lossy().to_string()) {
} else if let Some(tex) = app.cached_texture.get() { let _ = CustomElement::<HexagonLauncher>::build(builder);
// Raster icon path warm: build the lightweight namespaced model }
// with the cached texture so material/texture creation happens now. } else if let Some(tex) = app.cached_texture.get() {
let _ = Model::namespaced("protostar", "hexagon/hexagon") // Raster icon path warm: build the lightweight namespaced model
.part(ModelPart::new("Hex").mat_param( // with the cached texture so material/texture creation happens now.
"color", let builder = Model::namespaced("protostar", "hexagon/hexagon")
MaterialParameter::Color(crate::BTN_COLOR), .part(ModelPart::new("Hex").mat_param(
)) "color",
.part(ModelPart::new("Icon").mat_param( MaterialParameter::Color(crate::BTN_COLOR),
"diffuse", ))
MaterialParameter::Texture(tex.clone()), .part(ModelPart::new("Icon").mat_param(
)) "diffuse",
.build(); MaterialParameter::Texture(tex.clone()),
} ));
}); let _ = CustomElement::<HexagonLauncher>::build(builder);
} }
});
// build immutable lightweight snapshots used during reify
self.snapshots = self
.apps
.iter()
.map(|a| Snapshot {
name: a.app.name().unwrap_or_default(),
cached_texture: a.cached_texture.get().cloned(),
cached_gltf: a.cached_gltf.get().cloned(),
})
.collect();
}
} }
impl Reify for HexagonLauncher { impl Reify for HexagonLauncher {
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
@@ -245,16 +271,56 @@ impl Reify for HexagonLauncher {
.iter() .iter()
.enumerate() .enumerate()
.take(take_n) .take(take_n)
.map(|(i, app)| { .map(|(i, _app)| {
Spatial::default() // use snapshot instead of reify_substate (cheap, immutable)
.pos(self.positions[i]) let snap = self.snapshots[i].clone();
.build() let pos = self.positions[i];
.child(app.reify_substate(move |state: &mut HexagonLauncher| { // build spatial + cheap model from snapshot (no per-app state access)
// log & count access to per-app substate let mut spatial = Spatial::default().pos(pos).build();
APP_REIFY_COUNT.fetch_add(1, Ordering::Relaxed); +
tracing::trace!(index = i, "accessing app substate"); + // attach model from snapshot (gltf preferred, else namespaced + texture)
state.apps.get_mut(i) + if let Some(gltf) = snap.cached_gltf {
})) + if let Ok(builder) = Model::direct(gltf.to_string_lossy().to_string()) {
+ spatial = spatial.child(builder.transform(Transform::from_rotation_scale(
+ Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
+ [MODEL_SCALE; 3],
+ )).build());
+ }
+ } else {
+ let mut mb = Model::namespaced("protostar", "hexagon/hexagon")
+ .transform(Transform::from_rotation_scale(
+ Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
+ [MODEL_SCALE; 3],
+ ))
+ .part(ModelPart::new("Hex").mat_param(
+ "color",
+ MaterialParameter::Color(if self.open {
+ BTN_SELECTED_COLOR
+ } else {
+ BTN_COLOR
+ }),
+ ));
+ if let Some(tex) = snap.cached_texture {
+ mb = mb.part(ModelPart::new("Icon").mat_param(
+ "diffuse",
+ MaterialParameter::Texture(tex),
+ ));
+ }
+ spatial = spatial.child(mb.build());
+ }
+
+ // attach a Button that mutates real state when used (captures index)
+ spatial.child(
+ Button::new(move |state: &mut HexagonLauncher| {
+ // example: toggle open / or launch the app via state.apps[i]
+ // keep mutation here, but we avoid doing this per-frame.
+ // if you need to launch: state.apps[i].launch(...);
+ tracing::debug!(index = i, "app button pressed");
+ })
+ .pos([0.0, 0.0, 0.0])
+ .size([0.01; 2])
+ .build(),
+ )
}) })
}) })
.into_iter() .into_iter()

View File

@@ -7,14 +7,12 @@ use stardust_xr_asteroids::elements::{
Grabbable, Lines, Model, ModelPart, PointerMode, Text, line_from_points, Grabbable, Lines, Model, ModelPart, PointerMode, Text, line_from_points,
}; };
use stardust_xr_asteroids::{CustomElement, Element, Reify, Transformable}; use stardust_xr_asteroids::{CustomElement, Element, Reify, Transformable};
use stardust_xr_fusion::drawable::{TextBounds, TextFit}; use stardust_xr_fusion::drawable::{TextBounds, TextFit, MaterialParameter, XAlign, YAlign};
use stardust_xr_fusion::node::NodeError; use stardust_xr_fusion::fields::{CylinderShape, Shape};
use stardust_xr_fusion::spatial::Transform;
use stardust_xr_fusion::values::ResourceID; use stardust_xr_fusion::values::ResourceID;
use stardust_xr_fusion::{ use stardust_xr_fusion::node::NodeError;
drawable::{MaterialParameter, XAlign, YAlign}, use std::path::PathBuf;
fields::{CylinderShape, Shape},
spatial::Transform,
};
use std::f32::consts::{FRAC_PI_2, PI}; use std::f32::consts::{FRAC_PI_2, PI};
use std::sync::OnceLock; use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
@@ -24,140 +22,181 @@ use crate::{ACTIVATION_DISTANCE, APP_SIZE, DEFAULT_HEX_COLOR, MODEL_SCALE};
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct App { pub struct App {
pub app: Application, pub app: Application,
#[serde(skip)] #[serde(skip)]
icon: OnceLock<Icon>, icon: OnceLock<Icon>,
pos: Vector3<f32>, // cached lightweight handles derived from the icon:
rot: Quaternion<f32>, // - for PNG/raster icons we cache a ResourceID::Direct for the texture
#[serde(skip)] #[serde(skip)]
launched: AtomicBool, pub cached_texture: OnceLock<ResourceID>,
#[serde(skip)]
pub cached_gltf: OnceLock<PathBuf>,
pos: Vector3<f32>,
rot: Quaternion<f32>,
#[serde(skip)]
launched: AtomicBool,
} }
impl App { impl App {
pub fn new(desktop_entry: DesktopFile) -> Result<Self, NodeError> { pub fn new(desktop_entry: DesktopFile) -> Result<Self, NodeError> {
let app = Application::create(desktop_entry)?; let app = Application::create(desktop_entry)?;
Ok(App { Ok(App {
app, app,
icon: OnceLock::default(), icon: OnceLock::default(),
pos: [0.0; 3].into(), cached_texture: OnceLock::default(),
rot: Quat::IDENTITY.into(), cached_gltf: OnceLock::default(),
launched: AtomicBool::new(false), pos: [0.0; 3].into(),
}) rot: Quat::IDENTITY.into(),
} launched: AtomicBool::new(false),
})
}
pub fn load_icon(&self) { pub fn load_icon(&self) {
if self.icon.get().is_none() // Only attempt to load/process the icon once
&& let Some(icon) = self if self.icon.get().is_none() {
.app if let Some(icon) = self
.icon(64, true) .app
.and_then(|i| i.cached_process(64).ok()) .icon(64, true)
{ .and_then(|i| i.cached_process(64).ok())
let _ = self.icon.set(icon); {
} // store raw icon
} let _ = self.icon.set(icon.clone());
// Helper functions for creating app components // cache lightweight handles derived from the icon so reify can be cheap
fn create_model(&self) -> impl Element<Self> { match &icon.icon_type {
match self.icon.get().as_ref().map(|i| (i.icon_type.clone(), i)) { IconType::Gltf => {
Some((IconType::Gltf, icon)) => Model::direct(icon.path.clone()) // cache the gltf path (PathBuf) so we don't call Model::direct() discovery per-reify
.unwrap() let _ = self.cached_gltf.set(icon.path.clone());
.transform(Transform::from_rotation_scale( }
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI), IconType::Png => {
[MODEL_SCALE; 3], // cache a ResourceID::Direct for the texture
)) let _ = self
.build(), .cached_texture
other => { .set(ResourceID::Direct(icon.path.clone()));
let model = Model::namespaced("protostar", "hexagon/hexagon") }
.transform(Transform::from_rotation_scale( _ => {}
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI), }
[APP_SIZE / 2.0; 3], }
)) }
.part( }
ModelPart::new("Hex")
.mat_param("color", MaterialParameter::Color(DEFAULT_HEX_COLOR)),
);
match other { // Helper functions for creating app components
Some((IconType::Png, icon)) => model.part(ModelPart::new("Icon").mat_param( fn create_model(&self) -> impl Element<Self> {
"diffuse", // prefer cached gltf path if present (avoids repeated Model::direct parsing)
MaterialParameter::Texture(ResourceID::Direct(icon.path.clone())), if let Some(gltf_path) = self.cached_gltf.get() {
)), // Model::direct accepts a string/path — convert PathBuf to String here to be safe
_ => model, if let Ok(builder) = Model::direct(gltf_path.to_string_lossy().to_string()) {
} return builder
.build() .transform(Transform::from_rotation_scale(
} Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
} [MODEL_SCALE; 3],
} ))
.build();
}
}
// fallback / raster icon path: use a namespaced hex model and attach a cached texture
let mut model = Model::namespaced("protostar", "hexagon/hexagon")
.transform(Transform::from_rotation_scale(
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
[APP_SIZE / 2.0; 3],
))
.part(ModelPart::new("Hex").mat_param(
"color",
MaterialParameter::Color(DEFAULT_HEX_COLOR),
));
if let Some(tex) = self.cached_texture.get() {
model = model.part(ModelPart::new("Icon").mat_param(
"diffuse",
MaterialParameter::Texture(tex.clone()),
));
} else if let Some(icon) = self.icon.get() {
// fallback to using icon path directly if caching didn't happen for some reason
if let IconType::Png = icon.icon_type {
model = model.part(ModelPart::new("Icon").mat_param(
"diffuse",
MaterialParameter::Texture(ResourceID::Direct(icon.path.clone())),
));
}
}
model.build()
}
} }
impl Reify for App { impl Reify for App {
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
fn reify(&self) -> impl Element<Self> { fn reify(&self) -> impl Element<Self> {
// The field shape for the grabbable // The field shape for the grabbable
let field_shape = Shape::Cylinder(CylinderShape { let field_shape = Shape::Cylinder(CylinderShape {
radius: APP_SIZE / 2.0, radius: APP_SIZE / 2.0,
length: 0.01, length: 0.01,
}); });
let converted = Vec3::from(self.pos); let converted = Vec3::from(self.pos);
let length = converted.length(); let length = converted.length();
let direction = converted.normalize_or_zero(); let direction = converted.normalize_or_zero();
Lines::new([line_from_points(vec![ // cull models that are far away to avoid heavy model builds every frame
Vec3::from([0.0; 3]), const CULL_DISTANCE: f32 = 4.0;
(length < ACTIVATION_DISTANCE) as u32 as f32 let should_render_model = length <= CULL_DISTANCE;
* direction * length.clamp(0.0, ACTIVATION_DISTANCE),
])]) Lines::new([line_from_points(vec![
.build() Vec3::from([0.0; 3]),
.child( (length < ACTIVATION_DISTANCE) as u32 as f32
Grabbable::new( * direction * length.clamp(0.0, ACTIVATION_DISTANCE),
field_shape, ])])
self.pos, .build()
self.rot, .child(
move |state: &mut Self, pos, rot| { Grabbable::new(
state.pos = pos; field_shape,
state.rot = rot; self.pos,
}, self.rot,
) move |state: &mut Self, pos, rot| {
.grab_stop({ state.pos = pos;
move |state: &mut Self| { state.rot = rot;
let pos_vec = Vec3::from(state.pos); },
if pos_vec.length() > ACTIVATION_DISTANCE { )
// state.app.launch(launch_space) .grab_stop({
state.launched.store(true, Ordering::Relaxed); move |state: &mut Self| {
} else { let pos_vec = Vec3::from(state.pos);
state.pos = [0.0; 3].into(); if pos_vec.length() > ACTIVATION_DISTANCE {
state.rot = Quat::IDENTITY.into(); state.launched.store(true, Ordering::Relaxed);
} } else {
} state.pos = [0.0; 3].into();
}) state.rot = Quat::IDENTITY.into();
.field_transform(Transform::from_rotation(Quat::from_rotation_x(FRAC_PI_2))) }
.pointer_mode(PointerMode::Align) }
.max_distance(0.05) })
.reparentable(false) .field_transform(Transform::from_rotation(Quat::from_rotation_x(FRAC_PI_2)))
.build() .pointer_mode(PointerMode::Align)
.child(self.create_model()) .max_distance(0.05)
.children(self.launched.load(Ordering::Relaxed).then(|| { .reparentable(false)
AppLauncher::new(&self.app) .build()
.done(|state: &mut Self| { // only build the (potentially expensive) model element when the hex is close enough
state.launched.store(false, Ordering::Relaxed); .children(should_render_model.then(|| self.create_model()).into_iter())
state.pos = [0.0; 3].into(); .children(self.launched.load(Ordering::Relaxed).then(|| {
state.rot = Quat::IDENTITY.into(); AppLauncher::new(&self.app)
}) .done(|state: &mut Self| {
.build() state.launched.store(false, Ordering::Relaxed);
})) state.pos = [0.0; 3].into();
.child( state.rot = Quat::IDENTITY.into();
Text::new(self.app.name().unwrap_or_default()) })
.character_height(0.005) .build()
.bounds(TextBounds { }))
bounds: [0.04, 0.04].into(), .child(
fit: TextFit::Wrap, Text::new(self.app.name().unwrap_or_default())
anchor_align_x: XAlign::Center, .character_height(0.005)
anchor_align_y: YAlign::Bottom, .bounds(TextBounds {
}) bounds: [0.04, 0.04].into(),
.align_x(XAlign::Center) fit: TextFit::Wrap,
.align_y(YAlign::Bottom) anchor_align_x: XAlign::Center,
.pos([0.0, -APP_SIZE * 0.35, 0.002]) anchor_align_y: YAlign::Bottom,
.build(), })
), .align_x(XAlign::Center)
) .align_y(YAlign::Bottom)
} .pos([0.0, -APP_SIZE * 0.35, 0.002])
.build(),
),
)
}
} }