refactor: make everything asteroids

fix: hexagon spiral

upgrade: asteroids for hotpatch

refactor: better icon handling

feat: cache icons

fix(hexagon): refinement

fix(hexagon): field transform

refactor: broken mess ahaha

fix(single): it woooorks!!!

fix: hexagon launcher!!!

refactor(hexagon_launcher): skip instrumentation dbg

fix: sirius

refactor: make it FAST on asteroids
This commit is contained in:
Nova
2025-05-30 18:08:19 -07:00
parent f5008ff5b5
commit b03a345bf3
19 changed files with 2307 additions and 1908 deletions

163
single/src/app.rs Normal file
View File

@@ -0,0 +1,163 @@
use asteroids::elements::{
Grabbable, Lines, Model, ModelPart, PointerMode, Text, line_from_points,
};
use asteroids::{CustomElement, Element, Reify, Transformable};
use glam::{Quat, Vec3};
use mint::{Quaternion, Vector3};
use protostar::application::Application;
use protostar::xdg::{DesktopFile, Icon, IconType};
use serde::{Deserialize, Serialize};
use stardust_xr_fusion::drawable::{TextBounds, TextFit};
use stardust_xr_fusion::node::NodeError;
use stardust_xr_fusion::values::ResourceID;
use stardust_xr_fusion::{
drawable::{MaterialParameter, XAlign, YAlign},
fields::{CylinderShape, Shape},
spatial::Transform,
};
use std::f32::consts::{FRAC_PI_2, PI};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::app_launcher::AppLauncher;
use crate::{ACTIVATION_DISTANCE, APP_SIZE, DEFAULT_HEX_COLOR, MODEL_SCALE};
#[derive(Debug, Serialize, Deserialize)]
pub struct App {
pub app: Application,
#[serde(skip)]
icon: OnceLock<Icon>,
pos: Vector3<f32>,
rot: Quaternion<f32>,
#[serde(skip)]
launched: AtomicBool,
}
impl App {
pub fn new(desktop_entry: DesktopFile) -> Result<Self, NodeError> {
let app = Application::create(desktop_entry)?;
Ok(App {
app,
icon: OnceLock::default(),
pos: [0.0; 3].into(),
rot: Quat::IDENTITY.into(),
launched: AtomicBool::new(false),
})
}
pub fn load_icon(&self) {
if self.icon.get().is_none()
&& let Some(icon) = self
.app
.icon(64, true)
.and_then(|i| i.cached_process(64).ok())
{
let _ = self.icon.set(icon);
}
}
// Helper functions for creating app components
fn create_model(&self) -> impl Element<Self> {
match self.icon.get().as_ref().map(|i| (i.icon_type.clone(), i)) {
Some((IconType::Gltf, icon)) => Model::direct(icon.path.clone())
.unwrap()
.transform(Transform::from_rotation_scale(
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
[MODEL_SCALE; 3],
))
.build(),
other => {
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 {
Some((IconType::Png, icon)) => model.part(ModelPart::new("Icon").mat_param(
"diffuse",
MaterialParameter::Texture(ResourceID::Direct(icon.path.clone())),
)),
_ => model,
}
.build()
}
}
}
}
impl Reify for App {
#[tracing::instrument(skip_all)]
fn reify(&self) -> impl Element<Self> {
// The field shape for the grabbable
let field_shape = Shape::Cylinder(CylinderShape {
radius: APP_SIZE / 2.0,
length: 0.01,
});
let converted = Vec3::from(self.pos);
let length = converted.length();
let direction = converted.normalize_or_zero();
Lines::new([line_from_points(vec![
Vec3::from([0.0; 3]),
(length < ACTIVATION_DISTANCE) as u32 as f32
* direction * length.clamp(0.0, ACTIVATION_DISTANCE),
])])
.build()
.child(
Grabbable::new(
field_shape,
self.pos,
self.rot,
move |state: &mut Self, pos, rot| {
state.pos = pos;
state.rot = rot;
},
)
.grab_stop({
move |state: &mut Self| {
let pos_vec = Vec3::from(state.pos);
if pos_vec.length() > ACTIVATION_DISTANCE {
// state.app.launch(launch_space)
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)
.build()
.child(self.create_model())
.children(self.launched.load(Ordering::Relaxed).then(|| {
AppLauncher::new(&self.app)
.done(|state: &mut Self| {
state.launched.store(false, Ordering::Relaxed);
state.pos = [0.0; 3].into();
state.rot = Quat::IDENTITY.into();
})
.build()
}))
.child(
Text::new(self.app.name().unwrap_or_default())
.character_height(0.005)
.bounds(TextBounds {
bounds: [0.5, 0.5].into(),
fit: TextFit::Wrap,
anchor_align_x: XAlign::Center,
anchor_align_y: YAlign::Top,
})
.text_align_x(XAlign::Center)
.text_align_y(YAlign::Center)
.pos([0.0, -APP_SIZE * 0.35, 0.001])
.rot(Quat::from_rotation_y(PI))
.build(),
),
)
}
}

View File

@@ -0,0 +1,62 @@
use asteroids::{CustomElement, ValidState};
use protostar::application::Application;
use stardust_xr_fusion::{
node::{NodeError, NodeType},
spatial::{Spatial, SpatialAspect, SpatialRef, Transform},
};
use std::fmt::Debug;
pub struct AppLauncher<State: ValidState>(Application, Box<dyn Fn(&mut State) + Send + Sync>);
impl<State: ValidState> AppLauncher<State> {
pub fn new(app: &Application) -> Self {
AppLauncher(app.clone(), Box::new(|_| {}))
}
pub fn done<F: Fn(&mut State) + Send + Sync + 'static>(mut self, f: F) -> Self {
self.1 = Box::new(f);
self
}
}
impl<State: ValidState> CustomElement<State> for AppLauncher<State> {
type Inner = (Spatial, bool);
type Resource = ();
type Error = NodeError;
fn create_inner(
&self,
_asteroids_context: &asteroids::Context,
info: asteroids::CreateInnerInfo,
_resource: &mut Self::Resource,
) -> Result<Self::Inner, Self::Error> {
let spatial = Spatial::create(
info.parent_space.client()?.get_root(),
Transform::identity(),
false,
)?;
spatial.set_relative_transform(info.parent_space, Transform::from_translation([0.0; 3]))?;
Ok((spatial, false))
}
fn diff(&self, _old_self: &Self, _inner: &mut Self::Inner, _resource: &mut Self::Resource) {}
fn frame(
&self,
_info: &stardust_xr_fusion::root::FrameInfo,
state: &mut State,
inner: &mut Self::Inner,
) {
if !inner.1 {
let _ = self.0.launch(&inner.0);
(self.1)(state);
inner.1 = true;
}
}
fn spatial_aspect(&self, inner: &Self::Inner) -> SpatialRef {
inner.0.clone().as_spatial_ref()
}
}
impl<State: ValidState> Debug for AppLauncher<State> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ImperativeSpatial").finish()
}
}

15
single/src/lib.rs Normal file
View File

@@ -0,0 +1,15 @@
mod app;
mod app_launcher;
pub use app::App;
use stardust_xr_fusion::values::color::{Rgba, color_space::LinearRgb, rgba_linear};
// Constants from original implementation
pub const APP_SIZE: f32 = 0.06;
pub const PADDING: f32 = 0.005;
pub const MODEL_SCALE: f32 = 0.03;
pub const ACTIVATION_DISTANCE: f32 = 0.05;
pub const DEFAULT_HEX_COLOR: Rgba<f32, LinearRgb> = rgba_linear!(0.211, 0.937, 0.588, 1.0);
pub const BTN_SELECTED_COLOR: Rgba<f32, LinearRgb> = rgba_linear!(0.0, 1.0, 0.0, 1.0);
pub const BTN_COLOR: Rgba<f32, LinearRgb> = rgba_linear!(1.0, 1.0, 0.0, 1.0);

View File

@@ -1,15 +1,12 @@
mod single;
use asteroids::{ClientState, CustomElement, Element, Migrate, Reify, client, elements::Spatial};
use clap::Parser;
use color_eyre::{eyre::Result, Report};
use manifest_dir_macros::directory_relative_path;
use protostar::xdg::parse_desktop_file;
use stardust_xr_fusion::{client::Client, root::RootAspect};
use protostar::xdg::DesktopFile;
use serde::{Deserialize, Serialize};
use single::App;
use stardust_xr_fusion::project_local_resources;
use std::path::PathBuf;
use tracing_subscriber::EnvFilter;
use crate::single::Single;
#[derive(Debug, Parser)]
#[clap(author, version, about, long_about = None)]
struct Args {
@@ -18,45 +15,39 @@ struct Args {
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
async fn main() {
tracing_subscriber::fmt()
.compact()
.with_env_filter(EnvFilter::from_env("LOG_LEVEL"))
.init();
color_eyre::install()?;
let args = Args::parse();
let owned_client = Client::connect().await?;
let client = owned_client.handle();
let async_loop = owned_client.async_event_loop();
client
.get_root()
.set_base_prefixes(&[directory_relative_path!("../res").to_string()])?;
let mut protostar = Single::create_from_desktop_file(
client.get_root(),
[0.0, 0.0, 0.0],
parse_desktop_file(args.desktop_file).map_err(Report::msg)?,
)?;
let mut owned_client = async_loop.stop().await.unwrap();
let event_loop = owned_client.sync_event_loop(|handle, _| {
let Some(event) = handle.get_root().recv_root_event() else {
return;
};
match event {
stardust_xr_fusion::root::RootEvent::Ping { response } => response.send(Ok(())),
stardust_xr_fusion::root::RootEvent::Frame { info } => {
protostar.frame(info);
}
stardust_xr_fusion::root::RootEvent::SaveState { response } => {
response.send(protostar.save_state());
}
}
});
tokio::select! {
_ = tokio::signal::ctrl_c() => (),
e = event_loop => e?,
};
Ok(())
client::run::<Single>(&[&project_local_resources!("../res")]).await
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct Single {
app: Option<App>,
}
impl Migrate for Single {
type Old = Self;
}
impl ClientState for Single {
const APP_ID: &'static str = "org.stardustxr.protostar.single";
fn initial_state_update(&mut self) {
let desktop_file_path = Args::parse().desktop_file;
let app = App::new(DesktopFile::parse(desktop_file_path).unwrap()).unwrap();
app.load_icon();
self.app.replace(app);
}
}
impl Reify for Single {
#[tracing::instrument(skip_all)]
fn reify(&self) -> impl Element<Self> {
Spatial::default().build().maybe_child(
self.app
.as_ref()
.map(|app| app.reify_substate(|state: &mut Self| state.app.as_mut())),
)
}
}

View File

@@ -1,252 +0,0 @@
use color_eyre::eyre::Result;
use glam::{Quat, Vec3};
use protostar::{
application::Application,
xdg::{DesktopFile, Icon, IconType},
};
use stardust_xr_fusion::{
core::values::{color::rgba_linear, ResourceID, Vector3},
drawable::{
MaterialParameter, Model, ModelPartAspect, Text, TextBounds, TextFit, TextStyle, XAlign,
YAlign,
},
fields::{Field, Shape},
node::NodeType,
root::{ClientState, FrameInfo},
spatial::{Spatial, SpatialAspect, SpatialRefAspect, Transform},
};
use stardust_xr_molecules::{FrameSensitive, Grabbable, GrabbableSettings, UIElement};
use std::f32::consts::PI;
use tween::{QuartInOut, Tweener};
const MODEL_SCALE: f32 = 0.05;
const ACTIVATION_DISTANCE: f32 = 0.5;
fn model_from_icon(parent: &Spatial, icon: &Icon) -> Result<Model> {
match &icon.icon_type {
IconType::Png => {
let t = Transform::from_rotation_scale(
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
[MODEL_SCALE; 3],
);
let model = Model::create(
parent,
t,
&ResourceID::new_namespaced("protostar", "hexagon/hexagon"),
)?;
model.part("Hex")?.set_material_parameter(
"color",
MaterialParameter::Color(rgba_linear!(0.0, 1.0, 1.0, 1.0)),
)?;
model.part("Icon")?.set_material_parameter(
"diffuse",
MaterialParameter::Texture(ResourceID::Direct(icon.path.clone())),
)?;
Ok(model)
}
IconType::Gltf => Ok(Model::create(
parent,
Transform::from_scale([0.05; 3]),
&ResourceID::new_direct(icon.path.clone())?,
)?),
_ => panic!("Invalid Icon Type"),
}
}
pub struct Single {
application: Application,
root: Spatial,
position: Vector3<f32>,
grabbable: Grabbable,
_field: Field,
icon: Model,
label: Option<Text>,
grabbable_shrink: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_grow: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_move: Option<Tweener<f32, f64, QuartInOut>>,
currently_shown: bool,
}
impl Single {
pub fn create_from_desktop_file(
parent: &impl SpatialRefAspect,
position: impl Into<Vector3<f32>>,
desktop_file: DesktopFile,
) -> Result<Self> {
let root = Spatial::create(parent, Transform::identity(), false)?;
let position = position.into();
let field = Field::create(
&root,
Transform::identity(),
Shape::Box([MODEL_SCALE * 2.0; 3].into()),
)?;
let application = Application::create(desktop_file)?;
let icon = application.icon(128, false);
let grabbable = Grabbable::create(
&root,
Transform::from_translation(position),
&field,
GrabbableSettings {
max_distance: 0.01,
..Default::default()
},
)?;
grabbable.content_parent().set_spatial_parent(&root)?;
field.set_spatial_parent(grabbable.content_parent())?;
let icon = icon
.map(|i| model_from_icon(grabbable.content_parent(), &i))
.unwrap_or_else(|| {
Ok(Model::create(
grabbable.content_parent(),
Transform::from_scale([MODEL_SCALE; 3]),
&ResourceID::new_namespaced("protostar", "default_icon"),
)?)
})?;
let label_style = TextStyle {
character_height: MODEL_SCALE * 4.0,
bounds: Some(TextBounds {
bounds: [1.0; 2].into(),
fit: TextFit::Wrap,
anchor_align_x: XAlign::Center,
anchor_align_y: YAlign::Center,
}),
text_align_x: XAlign::Center,
text_align_y: YAlign::Center,
..Default::default()
};
let label = application.name().and_then(|name| {
Text::create(
&icon,
Transform::from_translation_rotation(
[0.0, 0.1, -(MODEL_SCALE * 8.0)],
Quat::from_rotation_x(PI * 0.5),
),
name,
label_style,
)
.ok()
});
Ok(Single {
root,
position,
grabbable,
_field: field,
label,
application,
icon,
grabbable_shrink: None,
grabbable_grow: None,
grabbable_move: None,
currently_shown: true,
})
}
pub fn content_parent(&self) -> &Spatial {
self.grabbable.content_parent()
}
}
impl Single {
pub fn frame(&mut self, info: FrameInfo) {
if self.grabbable.handle_events() {
self.grabbable.frame(&info);
}
if let Some(grabbable_move) = &mut self.grabbable_move {
if !grabbable_move.is_finished() {
let scale = grabbable_move.move_by(info.delta.into());
self.grabbable
.content_parent()
.set_relative_transform(
&self.root,
Transform::from_translation([
self.position.x * scale,
self.position.y * scale,
self.position.z * scale,
]),
)
.unwrap();
} else {
if grabbable_move.final_value() == 0.0001 {
self.icon.set_enabled(false).unwrap();
if let Some(label) = self.label.as_ref() {
label.set_enabled(false).unwrap()
}
}
self.grabbable_move = None;
}
}
if let Some(grabbable_shrink) = &mut self.grabbable_shrink {
if !grabbable_shrink.is_finished() {
let scale = grabbable_shrink.move_by(info.delta.into());
self.grabbable
.content_parent()
.set_relative_transform(&self.root, Transform::from_scale([scale; 3]))
.unwrap();
} else {
self.grabbable
.content_parent()
.set_spatial_parent(&self.root)
.unwrap();
if self.currently_shown {
self.grabbable_grow = Some(Tweener::quart_in_out(0.0001, 1.0, 0.25));
self.grabbable.cancel_angular_velocity();
self.grabbable.cancel_linear_velocity();
}
self.grabbable_shrink = None;
self.grabbable
.content_parent()
.set_relative_transform(&self.root, Transform::from_translation(self.position))
.unwrap();
self.grabbable
.content_parent()
.set_relative_transform(&self.root, Transform::from_rotation(Quat::default()))
.unwrap();
self.icon
.set_local_transform(Transform::from_rotation(
Quat::from_rotation_x(PI / 2.0) * Quat::from_rotation_y(PI),
))
.unwrap();
}
} else if let Some(grabbable_grow) = &mut self.grabbable_grow {
if !grabbable_grow.is_finished() {
let scale = grabbable_grow.move_by(info.delta.into());
self.grabbable
.content_parent()
.set_relative_transform(&self.root, Transform::from_scale([scale; 3]))
.unwrap();
} else {
self.grabbable
.content_parent()
.set_spatial_parent(&self.root)
.unwrap();
self.grabbable_grow = None;
}
} else if self.grabbable.grab_action().actor_stopped() {
self.grabbable_shrink = Some(Tweener::quart_in_out(MODEL_SCALE, 0.0001, 0.25));
let application = self.application.clone();
let space = self.content_parent().clone();
let root = self.root.clone();
//TODO: split the executable string for the args
tokio::task::spawn(async move {
let distance_vector = space
.get_transform(&root)
.await
.unwrap()
.translation
.unwrap();
let distance = Vec3::from(distance_vector).length_squared();
if distance > ACTIVATION_DISTANCE {
let _ = application.launch(&space);
}
});
}
}
pub fn save_state(&mut self) -> color_eyre::eyre::Result<ClientState> {
ClientState::from_root(self.content_parent())
}
}