1use std::cell::RefCell;
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use bevy::asset::io::Reader;
18use bevy::asset::{Asset, AssetId, AssetLoader, AssetPath, LoadContext};
19use bevy::ecs::system::SystemParamItem;
20use bevy::image::{Image, ImageLoaderSettings};
21use bevy::log::warn;
22use bevy::prelude::Handle;
23use bevy::reflect::TypePath;
24use bevy::render::render_asset::{PrepareAssetError, RenderAsset};
25use ssplayer_wgpu::{SSPack, SSPlayer, SSRuntimeError};
26
27#[derive(Asset, TypePath, Clone)]
34pub struct SsPack {
35 pub(crate) packs: Vec<SSPack>,
39 pub(crate) path: AssetPath<'static>,
43 #[dependency]
45 pub(crate) atlases: Vec<Handle<Image>>,
46 pub(crate) atlas_keys: Vec<u32>,
48}
49
50impl SsPack {
51 pub fn pack(&self) -> &SSPack {
53 &self.packs[0]
54 }
55}
56
57pub(crate) struct RenderSsPack {
61 pub(crate) packs: Vec<SSPack>,
62 pub(crate) path: AssetPath<'static>,
63 pub(crate) atlases: Vec<(u32, AssetId<Image>)>,
64 pub(crate) generation: u64,
65}
66
67impl RenderAsset for RenderSsPack {
68 type SourceAsset = SsPack;
69 type Param = ();
70
71 fn prepare_asset(source: SsPack, _id: AssetId<SsPack>, _param: &mut SystemParamItem<()>, _previous: Option<&Self>) -> Result<Self, PrepareAssetError<SsPack>> {
72 static GENERATION: AtomicU64 = AtomicU64::new(0);
73 let atlases = source.atlas_keys.iter().copied().zip(source.atlases.iter().map(Handle::id)).collect();
74 Ok(Self { packs: source.packs, path: source.path, atlases, generation: GENERATION.fetch_add(1, Ordering::Relaxed) })
75 }
76}
77
78#[derive(Debug)]
80pub enum SsPackLoadError {
81 Io(std::io::Error),
82 Parse(SSRuntimeError),
83}
84
85impl std::fmt::Display for SsPackLoadError {
86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 match self {
88 Self::Io(err) => write!(f, "could not read the .ssab: {err}"),
89 Self::Parse(err) => write!(f, "not a valid .ssab: {err}"),
90 }
91 }
92}
93
94impl std::error::Error for SsPackLoadError {}
95
96#[derive(Default, TypePath)]
98pub struct SsPackLoader;
99
100impl AssetLoader for SsPackLoader {
101 type Asset = SsPack;
102 type Settings = ();
103 type Error = SsPackLoadError;
104
105 async fn load(&self, reader: &mut dyn Reader, _settings: &(), load_context: &mut LoadContext<'_>) -> Result<SsPack, SsPackLoadError> {
106 let mut bytes = Vec::new();
107 reader.read_to_end(&mut bytes).await.map_err(SsPackLoadError::Io)?;
108 let main = SSPack::load(&bytes).map_err(SsPackLoadError::Parse)?;
109 let path = load_context.path().clone_owned();
110
111 let mut walk = Walk { ctx: load_context, base: path.clone(), siblings: Vec::new(), atlases: RefCell::new(Vec::new()) };
115 let mut player = SSPlayer::new();
116 player.add_pack(&main);
117 player.load_assets(&mut walk, main.name()).await;
118
119 let Walk { ctx, siblings, atlases, .. } = walk;
120 let mut atlas_keys = Vec::new();
121 let mut handles = Vec::new();
122 for (key, atlas) in atlases.into_inner() {
123 if atlas_keys.contains(&key) {
125 continue;
126 }
127 let handle = ctx.load_builder().with_settings(|settings: &mut ImageLoaderSettings| settings.is_srgb = false).load(atlas);
130 atlas_keys.push(key);
131 handles.push(handle);
132 }
133
134 let mut packs = vec![main];
135 packs.extend(siblings);
136 Ok(SsPack { packs, path, atlases: handles, atlas_keys })
137 }
138
139 fn extensions(&self) -> &[&str] {
140 &["ssab"]
141 }
142}
143
144pub(crate) fn atlas_key(path: &AssetPath<'_>) -> u32 {
147 path.to_string().bytes().fold(2166136261u32, |hash, byte| (hash ^ byte as u32).wrapping_mul(16777619))
149}
150
151struct Walk<'a, 'ctx> {
159 ctx: &'a mut LoadContext<'ctx>,
160 base: AssetPath<'static>,
161 siblings: Vec<SSPack>,
164 atlases: RefCell<Vec<(u32, AssetPath<'static>)>>,
167}
168
169impl ssplayer_wgpu::AssetLoader for Walk<'_, '_> {
170 fn reset_base(&mut self) {}
172
173 fn set_base(&mut self, _src: &str) {}
174
175 async fn read(&mut self, paths: &[String]) -> Vec<Option<Vec<u8>>> {
176 let mut out = Vec::with_capacity(paths.len());
177 for path in paths {
178 let bytes = match self.base.resolve_embed_str(path) {
179 Ok(resolved) => self.ctx.read_asset_bytes(resolved).await.ok(),
180 Err(_) => None,
181 };
182 if let Some(pack) = bytes.as_deref().and_then(|bytes| SSPack::load(bytes).ok()) {
183 self.siblings.push(pack);
184 }
185 out.push(bytes);
186 }
187 out
188 }
189
190 fn texture_key(&self, path: &str, cellmap_hash: u32) -> u32 {
191 let Ok(resolved) = self.base.resolve_embed_str(path) else { return cellmap_hash };
192 let key = atlas_key(&resolved);
193 self.atlases.borrow_mut().push((key, resolved));
194 key
195 }
196
197 fn has_texture(&self, _key: u32) -> bool {
198 true
199 }
200
201 async fn supply_texture(&mut self, _key: u32, _encoded: &[u8]) {}
202
203 fn warn(&self, message: &str) {
204 warn!("ssplayer-bevy: {} — {message}", self.base);
205 }
206}
207
208pub(crate) struct Keys<'a> {
211 pub(crate) base: &'a AssetPath<'static>,
212}
213
214impl ssplayer_wgpu::AssetLoader for Keys<'_> {
215 fn reset_base(&mut self) {}
216
217 fn set_base(&mut self, _src: &str) {}
218
219 async fn read(&mut self, paths: &[String]) -> Vec<Option<Vec<u8>>> {
220 vec![None; paths.len()]
221 }
222
223 fn texture_key(&self, path: &str, cellmap_hash: u32) -> u32 {
224 self.base.resolve_embed_str(path).map(|resolved| atlas_key(&resolved)).unwrap_or(cellmap_hash)
225 }
226
227 fn has_texture(&self, _key: u32) -> bool {
228 true
229 }
230
231 async fn supply_texture(&mut self, _key: u32, _encoded: &[u8]) {}
232
233 fn warn(&self, message: &str) {
234 warn!("ssplayer-bevy: {} — {message}", self.base);
235 }
236}