From 9fea54871ab876ee730400d8ac10204b5c2be256 Mon Sep 17 00:00:00 2001 From: leonidarider <358984476+leonidarider@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:50:43 +0100 Subject: [PATCH] Eliminate remaining 51 GTA VI drawable/world/RPF9 process-global statics into Gta6Session --- src/photo/gta6.rs | 29 ++- src/render/gta6_drawable/mod.rs | 12 +- src/render/gta6_drawable/wheels.rs | 27 +- src/render/gta6_hair.rs | 4 +- src/render/gta6_meshlets/mod.rs | 2 +- src/render/gta6_ped_pose.rs | 4 +- src/render/viewport/bones.rs | 2 +- src/render/viewport/game_shaders.rs | 7 +- src/render/viewport/mod.rs | 4 +- src/render/viewport/world.rs | 12 +- src/self_check/shots/perf.rs | 8 +- src/self_check/shots/world.rs | 28 +- src/state/convert.rs | 2 +- src/state/document/gta6_meta_strings.rs | 4 +- src/state/document/gta6_script/build/mod.rs | 3 +- src/state/document/gta6_script/jobs.rs | 3 +- src/state/document/location.rs | 5 +- src/state/document/meta/mod.rs | 14 +- src/state/document/mod.rs | 33 ++- src/state/document_io.rs | 15 +- src/state/file_index/mod.rs | 17 +- .../file_index/searching_every_archive.rs | 4 +- src/state/files_view/mod.rs | 6 +- src/state/gta6/anim/gta6_bone_edit/mod.rs | 26 +- src/state/gta6/anim/gta6_bone_edit/tests.rs | 22 +- src/state/gta6/anim/gta6_entry_skeletons.rs | 8 +- src/state/gta6/anim/gta6_face/mod.rs | 4 +- src/state/gta6/bodies/gta6_meta_save/mod.rs | 5 +- .../gta6/bodies/gta6_meta_save/splice.rs | 4 +- .../gta6_resource_save/awc_in_extent.rs | 18 +- .../gta6/bodies/gta6_resource_save/mod.rs | 3 +- src/state/gta6/drawable/gta6_effects.rs | 67 ++--- src/state/gta6/drawable/gta6_export.rs | 2 +- .../gta6/drawable/gta6_gltf_import/mod.rs | 37 ++- .../gta6/drawable/gta6_gltf_import/tests.rs | 4 +- src/state/gta6/drawable/gta6_head.rs | 45 ++-- src/state/gta6/drawable/gta6_selected.rs | 7 +- .../drawable/gta6_shaders/global_textures.rs | 18 +- .../gta6/drawable/gta6_shaders/layer_index.rs | 32 ++- src/state/gta6/drawable/gta6_shaders/mod.rs | 57 +++-- .../drawable/gta6_shaders/ped_assets/mod.rs | 59 +++-- .../gta6_shaders/ped_assets/skin_tones.rs | 17 +- .../drawable/gta6_shaders/terrain_tile.rs | 60 +++-- .../gta6/drawable/gta6_shaders/timecycle.rs | 12 +- src/state/gta6/drawable/gta6_weapon_parts.rs | 25 +- src/state/gta6/drawable/mod.rs | 17 ++ src/state/gta6/install/gta6_first_entry.rs | 2 +- src/state/gta6/install/gta_vi.rs | 12 +- src/state/gta6/modding/batch_export.rs | 6 +- src/state/gta6/modding/mod_package_changes.rs | 3 +- .../gta6/modding/mod_package_install/mod.rs | 12 +- src/state/gta6/modding/references.rs | 24 +- src/state/gta6/modding/text_search/mod.rs | 10 +- .../gta6/physics/gta6_collision_edit/mod.rs | 2 +- .../gta6/physics/gta6_navmesh_delete/look.rs | 18 +- src/state/gta6/session.rs | 3 + .../gta6/textures/gta6_embedded_edit/mod.rs | 37 +-- src/state/gta6/textures/gta6_texture_index.rs | 4 +- src/state/gta6/world/gta6_map/entity.rs | 38 ++- src/state/gta6/world/gta6_map/links/mod.rs | 120 ++++++--- src/state/gta6/world/gta6_map/links/tests.rs | 10 +- src/state/gta6/world/gta6_map/mod.rs | 143 +++++++---- src/state/gta6/world/gta6_map/tests.rs | 4 +- src/state/gta6/world/gta6_map/types_edit.rs | 2 +- src/state/gta6/world/gta6_map/world_delete.rs | 2 +- src/state/gta6/world/gta6_map_edit.rs | 14 +- src/state/gta6/world/gta6_world/fill.rs | 38 +-- src/state/gta6/world/gta6_world/mod.rs | 28 +- .../gta6/world/gta6_world/worldview/edit.rs | 78 +++--- .../gta6/world/gta6_world/worldview/grass.rs | 2 +- .../gta6/world/gta6_world/worldview/index.rs | 5 +- .../gta6/world/gta6_world/worldview/keys.rs | 22 +- .../gta6/world/gta6_world/worldview/mod.rs | 26 +- .../gta6/world/gta6_world/worldview/pick.rs | 12 +- .../gta6_world/worldview/reference/mod.rs | 9 +- .../gta6/world/gta6_world/worldview/sky.rs | 9 +- .../gta6_world/worldview/water/ground.rs | 20 +- .../world/gta6_world/worldview/water/mod.rs | 13 +- .../gta6/world/gta6_world/worldview/whole.rs | 241 +++++++++++------- src/state/gta6/world/gta6_world_edit.rs | 2 +- src/state/gta6/world/gta6_world_fits.rs | 26 +- src/state/gta6/world/mod.rs | 12 + src/state/jobs.rs | 16 +- src/state/mod.rs | 8 +- src/state/photo_documents.rs | 10 +- src/state/rpf/mod.rs | 22 ++ src/state/rpf/rpf9_counted_names.rs | 20 +- src/state/rpf/rpf9_scan/ciphered/mod.rs | 30 ++- src/state/rpf/rpf9_scan/mod.rs | 126 +++++---- src/state/rpf/rpf9_scan/payload.rs | 18 +- .../rpf9_table/gta6_archive_save/mod.rs | 55 ++-- .../rpf9_table/gta6_archive_save/tests.rs | 49 +++- .../rpf9_scan/rpf9_table/gta6_keys_held.rs | 44 +++- src/state/rpf/rpf9_scan/rpf9_table/mod.rs | 76 +++--- src/state/rpf/rpf9_scan/rpf9_tree_actions.rs | 10 +- src/state/rpf/rpf_archive_open/mod.rs | 32 ++- .../rpf_archive_open/tree_open/bind/mod.rs | 24 +- .../rpf_archive_open/tree_open/bind/tests.rs | 7 +- .../rpf/rpf_archive_open/tree_open/mod.rs | 158 +++++++----- .../rpf_archive_open/tree_open/names_tests.rs | 3 +- .../tree_verbs/adopt/archive_size_tests.rs | 4 +- .../rpf_archive_open/tree_verbs/adopt/mod.rs | 9 +- .../tree_verbs/adopt/tests.rs | 5 +- .../headerless_tests/saves_per_kind/mod.rs | 5 +- .../rpf/rpf_archive_open/tree_verbs/mod.rs | 81 +++--- .../rpf_archive_open/tree_verbs/plan_job.rs | 62 +++-- .../rpf/rpf_archive_open/tree_verbs/tests.rs | 3 +- src/state/tests/opening_an_rpf9_archive.rs | 12 +- src/state/viewport_camera.rs | 4 +- src/state/world_session/gta6.rs | 46 ++-- src/state/world_session/mod.rs | 6 +- src/ui/panels/hierarchy/gta6/drawable.rs | 10 +- src/ui/panels/hierarchy/gta6/install.rs | 2 +- src/ui/panels/inspector/gta6/anim/play.rs | 9 +- .../inspector/gta6/drawable/bone_edit.rs | 2 +- src/ui/panels/inspector/gta6/drawable/head.rs | 2 +- .../inspector/gta6/drawable/selected.rs | 2 +- src/ui/panels/inspector/rpf9.rs | 2 +- src/ui/panels/inspector/summary.rs | 5 +- src/ui/panels/inspector/text.rs | 4 +- src/ui/panels/maps/plan.rs | 7 +- src/ui/panels/maps/scanned.rs | 2 +- src/ui/panels/maps/world.rs | 26 +- src/ui/panels/settings/games.rs | 4 +- src/ui/panels/status_bar.rs | 2 +- src/ui/panels/text_editor/mod.rs | 4 +- src/ui/panels/viewport/drawable_row.rs | 4 +- src/ui/panels/world_viewer/mod.rs | 7 +- src/ui/panels/world_viewer/side.rs | 3 +- 129 files changed, 1825 insertions(+), 1020 deletions(-) diff --git a/src/photo/gta6.rs b/src/photo/gta6.rs index 58b74b869..045a52f1b 100644 --- a/src/photo/gta6.rs +++ b/src/photo/gta6.rs @@ -191,7 +191,7 @@ pub(super) fn photograph( }; let (models, kits) = super::timing::time("04 gta6: models", || { crate::state::gta6_models_and_kits( - &state.gta6.install, + &state.gta6, &root, under, only.as_ref(), @@ -204,7 +204,7 @@ pub(super) fn photograph( root.display() ); if ctx.wheels.is_some() { - let found = crate::state::gta6_models(&state.gta6.install, &root, WHEELS_UNDER, None)?; + let found = crate::state::gta6_models(&state.gta6, &root, WHEELS_UNDER, None)?; println!("{} wheel models", found.len()); ctx.wheel_models = Some(found.into_iter().map(|m| (m.name.clone(), m)).collect()); } @@ -212,7 +212,7 @@ pub(super) fn photograph( // A part's layers come from the build's layered materials, which a worker reads once: a // picture drawn before it ends shows every part with no material. let until = Instant::now() + FIRST_SETTLE; - while crate::state::gta6_shaders::layer_index::under(&root).is_none() + while crate::state::gta6_shaders::layer_index::under(&state.gta6.drawable, &root).is_none() && Instant::now() < until { std::thread::sleep(Duration::from_millis(50)); @@ -319,7 +319,7 @@ pub(super) fn photograph( let file = std::fs::File::open(&model.archive).ok()?; Some(crate::state::gta6_weapon_parts::read_part(&file, model.offset)?.1) }; - crate::render::gta6_drawable::wheel_parts(doc, wheels, &read) + crate::render::gta6_drawable::wheel_parts(&state.gta6.rpf9, doc, wheels, &read) }); bridge.gta6_overrides_mut().set_beside(beside); if ctx.shaded { @@ -600,15 +600,15 @@ fn photograph_kits( // A part's maps are the ones its state names in the build's asset lists, which a worker reads. let until = Instant::now() + FIRST_SETTLE; let lists = loop { - match index::under(root) { + match index::under(&state.gta6.drawable, root) { Some(read) => break read, None if Instant::now() < until => std::thread::sleep(Duration::from_millis(50)), None => return Err("the build's ped asset lists were not read in time".into()), } }; println!("the build's ped asset lists are read"); - let poses = crate::render::gta6_ped_pose::load_human_poses(root); - let hair_lib = crate::render::gta6_hair::HairLibrary::load(root); + let poses = crate::render::gta6_ped_pose::load_human_poses(&state.gta6.rpf9, root); + let hair_lib = crate::render::gta6_hair::HairLibrary::load(&state.gta6.rpf9, root); let mut settle = FIRST_SETTLE; for (name, kit) in kits { let target = options @@ -722,11 +722,14 @@ fn photograph_kits( overrides.ped_pose = pose; overrides.set_beside(Some(beside)); } - index::dress(Some( - (parts.iter()) - .map(|(model, textures)| (drawable_word(&model.name), textures.clone())) - .collect(), - )); + index::dress( + &state.gta6.drawable, + Some( + (parts.iter()) + .map(|(model, textures)| (drawable_word(&model.name), textures.clone())) + .collect(), + ), + ); let look = Some(kit_look(dressing.kind)); let made = state.hold_gta6_model(parts[0].0, root).and_then(|id| { state.active_document = Some(id); @@ -735,7 +738,7 @@ fn photograph_kits( state.let_go(&[id]); drawn.and_then(|image| save(&image, &target)) }); - index::dress(None); + index::dress(&state.gta6.drawable, None); tally.record(name, made); } Ok(()) diff --git a/src/render/gta6_drawable/mod.rs b/src/render/gta6_drawable/mod.rs index f1929a195..6fbe8beb9 100644 --- a/src/render/gta6_drawable/mod.rs +++ b/src/render/gta6_drawable/mod.rs @@ -42,7 +42,7 @@ pub(crate) fn meshes(req: &GeometryRequest<'_>) -> Vec { let posed = crate::state::gta6_anim_play::gta6_posed(req.state); let own = posed .as_ref() - .and_then(|_| own_skeleton(&req.state.gta6.anim, req.doc, req.selection)); + .and_then(|_| own_skeleton(&req.state.gta6, req.doc, req.selection)); let posing = (posed.as_ref()).map(|p| (p.skeleton, own.as_ref())); let (lod, channel) = ( req.state.preview_scene.lod, @@ -221,7 +221,7 @@ pub(crate) fn parts_drawn( doc: &crate::state::Document, ) -> Option>> { (state.preview_scene.assemble_parts) - .then(|| crate::state::gta6_weapon_parts::of(doc.path.as_deref()?)) + .then(|| crate::state::gta6_weapon_parts::of(&state.gta6.drawable, doc.path.as_deref()?)) .flatten() } @@ -385,11 +385,11 @@ pub(crate) fn drawn_geometries( /// The skeleton of a scanned drawable or fragment, or of the dictionary entry `selection` is in, /// read when it opened. fn own_skeleton( - anim: &crate::state::gta6::anim::AnimSession, + gta6: &crate::state::gta6::session::Gta6Session, doc: &crate::state::Document, selection: Option, ) -> Option { - crate::state::gta6_entry_skeletons::shown(anim, doc, selection) + crate::state::gta6_entry_skeletons::shown(gta6, doc, selection) } /// The level of detail `lod`, or the first where that one has no models. @@ -449,7 +449,7 @@ pub(crate) fn meshes_at( /// Each geometry of the drawn level of `doc` that does not join `skeleton`: its model, its index and why. pub(crate) fn unjoined( - anim: &crate::state::gta6::anim::AnimSession, + gta6: &crate::state::gta6::session::Gta6Session, doc: &crate::state::Document, selection: Option, lod: usize, @@ -461,7 +461,7 @@ pub(crate) fn unjoined( let Some(drawable) = drawable_of(resource, selection) else { return Vec::new(); }; - let own = own_skeleton(anim, doc, selection); + let own = own_skeleton(gta6, doc, selection); let mut out = Vec::new(); for (m, model) in drawn_level(drawable, lod).enumerate() { for (g, geometry) in model.geometries.iter().enumerate() { diff --git a/src/render/gta6_drawable/wheels.rs b/src/render/gta6_drawable/wheels.rs index 4f6822d7f..f9f9bd4e7 100644 --- a/src/render/gta6_drawable/wheels.rs +++ b/src/render/gta6_drawable/wheels.rs @@ -10,17 +10,18 @@ pub(crate) type Wheel = (String, u32, [f32; 4], f32, [u8; 3]); /// Each of `wheels` as a part on its bone of `doc`'s skeleton at bind, its model read by `read`; /// a wheel whose bone the skeleton lacks, or whose model does not read, is left out. pub(crate) fn wheel_parts( + rpf9: &crate::state::rpf::Rpf9Session, doc: &crate::state::Document, wheels: &[Wheel], read: &dyn Fn(&str) -> Option, ) -> Vec { - let skeleton = - (doc.path.as_deref()).and_then(|path| crate::state::rpf9_scan::scanned_skeleton(path).ok()); + let skeleton = (doc.path.as_deref()) + .and_then(|path| crate::state::rpf9_scan::scanned_skeleton(rpf9, path).ok()); let Some(skeleton) = skeleton else { return Vec::new(); }; let world = or_anim::gta6::skeleton(&skeleton).bind_world; - let sizes = wheel_sizes(doc); + let sizes = wheel_sizes(rpf9, doc); let read: Vec> = wheels.iter().map(|(model, ..)| read(model)).collect(); // A wheel's models are made one across and are sized by their tyre: its radius to the // radius the vehicle states for the bone, its width along the axle, which is the models' x, @@ -60,7 +61,10 @@ pub(crate) fn wheel_parts( /// The radius and the width the bound of each wheel of `doc` states, by its bone's hash: a /// disc's radius and twice its margin, a cylinder's radius and height, a frustum's wider radius /// and height. A bone with several keeps the widest across. -fn wheel_sizes(doc: &crate::state::Document) -> std::collections::HashMap { +fn wheel_sizes( + rpf9: &crate::state::rpf::Rpf9Session, + doc: &crate::state::Document, +) -> std::collections::HashMap { use or_io::gta6::headerless::ChildBound; let mut sizes = std::collections::HashMap::new(); let DocPayload::Gta6Drawable(resource) = &doc.payload else { @@ -96,7 +100,8 @@ fn wheel_sizes(doc: &crate::state::Document) -> std::collections::HashMap kept.0 && width > 0.0 { *kept = (radius, width); @@ -107,8 +112,12 @@ fn wheel_sizes(doc: &crate::state::Document) -> std::collections::HashMap Option { - let skeleton = crate::state::rpf9_scan::scanned_skeleton(doc.path.as_deref()?).ok()?; +fn fragment_bone_name( + rpf9: &crate::state::rpf::Rpf9Session, + doc: &crate::state::Document, + hash: u32, +) -> Option { + let skeleton = crate::state::rpf9_scan::scanned_skeleton(rpf9, doc.path.as_deref()?).ok()?; let bone = skeleton.bones.iter().find(|bone| bone.hash == hash)?; Some(bone.name.to_ascii_lowercase()) } @@ -136,8 +145,8 @@ pub(crate) fn wheels( wheels: &[Wheel], read: &dyn Fn(&str) -> Option, ) -> Vec { - let skeleton = - (doc.path.as_deref()).and_then(|path| crate::state::rpf9_scan::scanned_skeleton(path).ok()); + let skeleton = (doc.path.as_deref()) + .and_then(|path| crate::state::rpf9_scan::scanned_skeleton(&state.gta6.rpf9, path).ok()); let Some(skeleton) = skeleton else { return Vec::new(); }; diff --git a/src/render/gta6_hair.rs b/src/render/gta6_hair.rs index 038ec6df3..c6650c95f 100644 --- a/src/render/gta6_hair.rs +++ b/src/render/gta6_hair.rs @@ -59,8 +59,8 @@ pub(crate) struct HairLibrary { impl HairLibrary { /// Load the secondary-motion asset map, cloth entry index, and hair colour database from `root`. - pub(crate) fn load(root: &Path) -> Option { - let Ok(keys) = crate::state::rpf9_scan::rpf9_table::keys() else { + pub(crate) fn load(rpf9: &crate::state::rpf::Rpf9Session, root: &Path) -> Option { + let Ok(keys) = crate::state::rpf9_scan::rpf9_table::keys(rpf9) else { tracing::warn!("could not load GTA VI keys to build hair library"); return None; }; diff --git a/src/render/gta6_meshlets/mod.rs b/src/render/gta6_meshlets/mod.rs index 1193983df..c85f7ef3a 100644 --- a/src/render/gta6_meshlets/mod.rs +++ b/src/render/gta6_meshlets/mod.rs @@ -722,7 +722,7 @@ pub(crate) fn meshlets( &mut |drawable, models, placement| { let name = drawable.name.as_str(); let sources = Sources { - shading: >a6_shaders::shading, + shading: &|hash, data| gta6_shaders::shading(&state.gta6.drawable, hash, data), effect_name: &|hash| effect_name(&state.gta6.bodies, hash), map: &|key| session.decoded(key, || stored(key)), layered: &|| gta6_layer_index::worn_as(state, name, true), diff --git a/src/render/gta6_ped_pose.rs b/src/render/gta6_ped_pose.rs index f34e50f5d..6c24afd62 100644 --- a/src/render/gta6_ped_pose.rs +++ b/src/render/gta6_ped_pose.rs @@ -126,8 +126,8 @@ pub(crate) struct HumanPoses { } /// Load the canonical male and female standing neutral idle poses from `root`. -pub(crate) fn load_human_poses(root: &Path) -> HumanPoses { - let Ok(keys) = crate::state::rpf9_scan::rpf9_table::keys() else { +pub(crate) fn load_human_poses(rpf9: &crate::state::rpf::Rpf9Session, root: &Path) -> HumanPoses { + let Ok(keys) = crate::state::rpf9_scan::rpf9_table::keys(rpf9) else { tracing::warn!("could not load GTA VI keys to build human standing poses"); return HumanPoses::default(); }; diff --git a/src/render/viewport/bones.rs b/src/render/viewport/bones.rs index 8abb4adc9..b6bb57bfe 100644 --- a/src/render/viewport/bones.rs +++ b/src/render/viewport/bones.rs @@ -118,7 +118,7 @@ fn gta6_rest(state: &AppState) -> Option<(DocumentId, Named, Arc)> { let named = entry.map_or(Named::Drawable, Named::Entry); let data = entry.map_or(usize::MAX, |code| code as usize); let skeleton = kept((doc.id, doc.payload_epoch(), data), || { - let read = shown(&state.gta6.anim, doc, selection)?; + let read = shown(&state.gta6, doc, selection)?; (!read.bones.is_empty()).then(|| or_anim::gta6::skeleton(&read)) })?; Some((doc.id, named, skeleton)) diff --git a/src/render/viewport/game_shaders.rs b/src/render/viewport/game_shaders.rs index 3e94d71e6..7c31d11ea 100644 --- a/src/render/viewport/game_shaders.rs +++ b/src/render/viewport/game_shaders.rs @@ -448,6 +448,7 @@ impl RenderBridge { }) }; gta6_shaders::request( + &state.gta6.drawable, &crate::render::gta6_meshlets::worn(state, self.gta6.overrides.beside()), install, self.gta6.hardware_adapter, @@ -458,8 +459,8 @@ impl RenderBridge { self.gta6.maps = Default::default(); self.start_decoding_gta6(state); } - let running = gta6_shaders::running(); - let pack = gta6_shaders::pack(); + let running = gta6_shaders::running(&state.gta6.drawable); + let pack = gta6_shaders::pack(&state.gta6.drawable); let key = MeshCacheKey::of(state, doc, pack.as_ref().map_or(0, |(number, _)| *number)); // A map learnt or decoded since the scene was bound is bound where it is read self.take_on_gta6_maps(state, key); @@ -561,7 +562,7 @@ impl RenderBridge { ); } let said = crate::render::gta6_shaded::said( - >a6_shaders::status(hashes), + >a6_shaders::status(&state.gta6.drawable, hashes), drawn, drawn + left_out.len(), ); diff --git a/src/render/viewport/mod.rs b/src/render/viewport/mod.rs index 62f1c64e2..c27670342 100644 --- a/src/render/viewport/mod.rs +++ b/src/render/viewport/mod.rs @@ -149,7 +149,9 @@ impl MeshCacheKey { gta6_posed_on: crate::state::gta6_anim_play::gta6_model_drawn(state).or_else(|| { crate::state::gta6_anim_play::gta6_posed(state).map(|p| (p.model, true)) }), - terrain_tiles: crate::state::gta6_shaders::terrain_tile::reads_ended(), + terrain_tiles: crate::state::gta6_shaders::terrain_tile::reads_ended( + &state.gta6.drawable, + ), } } diff --git a/src/render/viewport/world.rs b/src/render/viewport/world.rs index 8cd023ade..0c4e856d2 100644 --- a/src/render/viewport/world.rs +++ b/src/render/viewport/world.rs @@ -355,14 +355,14 @@ impl RenderBridge { /// Draw the GTA VI world this frame in the plain pass: put the models and textures that /// arrived on the device, and lay out the instances of the last selection the camera sees. - pub fn refresh_world(&mut self) { + pub fn refresh_world(&mut self, world_session: &crate::state::gta6::world::WorldSession) { let started = Instant::now(); (self.world.cost.laid, self.world.cost.uploaded) = (false, (0, 0)); - self.lay_world(); + self.lay_world(world_session); self.world.cost.refresh = started.elapsed(); } - fn lay_world(&mut self) { + fn lay_world(&mut self, world_session: &crate::state::gta6::world::WorldSession) { self.world.shown = true; self.world.frame += 1; // No program of GTA VI draws its world yet. @@ -370,7 +370,7 @@ impl RenderBridge { self.frame.mode = self.world_plain_mode(); let bc = (self.device.features()).contains(wgpu::Features::TEXTURE_COMPRESSION_BC); let budgets = self.world_budgets(); - let mut viewer = crate::state::gta6_world::worldview::viewer(); + let mut viewer = crate::state::gta6_world::worldview::viewer(world_session); let eye = viewer.camera.position; let now = Instant::now(); let lead = self.world.was.map_or(eye, |(then, was)| { @@ -451,6 +451,7 @@ impl RenderBridge { (per_metre, budgets.most_side), ); self.schedule_world_textures( + world_session, &selected, touched, (view_proj, eye, lod_scale), @@ -531,6 +532,7 @@ impl RenderBridge { /// Rebuild touched materials with their current colour maps and report wanted models and textures to the viewer. fn schedule_world_textures( &mut self, + world_session: &crate::state::gta6::world::WorldSession, selected: &Selected, touched: Vec, (view_proj, eye, lod_scale): (glam::Mat4, Vec3, f32), @@ -605,7 +607,7 @@ impl RenderBridge { .collect(); let mut wanted = merged(wanted); world.textures.hold(&mut wanted); - let mut viewer = crate::state::gta6_world::worldview::viewer(); + let mut viewer = crate::state::gta6_world::worldview::viewer(world_session); viewer.see_models(in_view); viewer.want_textures(wanted); } diff --git a/src/self_check/shots/perf.rs b/src/self_check/shots/perf.rs index 8b951f046..5bc20fa5c 100644 --- a/src/self_check/shots/perf.rs +++ b/src/self_check/shots/perf.rs @@ -63,7 +63,7 @@ impl Shell { .find(|(s, _)| *s == name) .map(|s| s.1) }; - let viewer = viewer(); + let viewer = viewer(&state.gta6.world); Ok(json!({ "frame_ms": ms(frame), "refresh_ms": ms(cost.refresh), @@ -127,7 +127,7 @@ impl Shell { self.bridge.relay_world(); relaid.push(self.measured(state)?); } - let pose = Pose::of(&viewer().camera); + let pose = Pose::of(&viewer(&state.gta6.world).camera); let unix = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH); let json = json!({ "camera": pose.line(), @@ -149,12 +149,12 @@ impl Shell { over: Duration, path: &Path, ) -> Result<(), String> { - let from = Pose::of(&viewer().camera); + let from = Pose::of(&viewer(&state.gta6.world).camera); let started = Instant::now(); let mut frames = Vec::new(); loop { let t = (started.elapsed().as_secs_f32() / over.as_secs_f32()).min(1.0); - between(&from, to, t).put(&mut viewer().camera); + between(&from, to, t).put(&mut viewer(&state.gta6.world).camera); let mut frame = self.measured(state)?; frame["t"] = json!(t); frames.push(frame); diff --git a/src/self_check/shots/world.rs b/src/self_check/shots/world.rs index 761ec3f62..de48ec3da 100644 --- a/src/self_check/shots/world.rs +++ b/src/self_check/shots/world.rs @@ -347,8 +347,8 @@ impl Settle { } /// What the viewer holds and waits for now, or why it has no index. -fn found() -> Result { - let viewer = viewer(); +fn found(state: &AppState) -> Result { + let viewer = viewer(&state.gta6.world); if let Some(why) = &viewer.failed { return Err(format!("the GTA VI world was not indexed: {why}")); } @@ -399,13 +399,14 @@ fn hex(names: &[u32]) -> Vec { /// the textures the device holds of it (`textures`). /// `whole` is the models told once whole, the seconds they waited on the device for their maps in all, and the most; `frame` is what the last frame drew. fn dump( + state: &AppState, path: &Path, (version, open): (u64, Vec), textures: Vec, whole: (usize, f64, f32), frame: serde_json::Value, ) -> Result<(), String> { - let mut viewer = viewer(); + let mut viewer = viewer(&state.gta6.world); let selected = (viewer.selected(&mut Vec::new())) .ok_or("no world streams yet: put `world settle` before `world dump`")?; let pose = Pose::of(&viewer.camera); @@ -509,12 +510,12 @@ impl Shell { WorldStep::Camera(pose) => { // ⚠ The viewer puts its camera over the middle of the maps as it takes the index, so a camera is set after that. self.indexed(state)?; - let mut viewer = viewer(); + let mut viewer = viewer(&state.gta6.world); pose.put(&mut viewer.camera); } WorldStep::Hour(hour) => { // What is placed for some hours alone follows the viewer's hour, and the Time bar says the same one. - viewer().hour = *hour; + viewer(&state.gta6.world).hour = *hour; let day = &mut state.drivers.time_of_day; day.set_hour(*hour); // ⚠ A day that runs would move the hour under a run. @@ -544,6 +545,7 @@ impl Shell { "bytes": drawn.bytes, }); dump( + state, &out.join(name), open, textures, @@ -552,13 +554,13 @@ impl Shell { )?; } // The groups follow the modes, as they do on the screen until a group is ticked. - WorldStep::Modes(modes) => viewer().enabled.modes = *modes, + WorldStep::Modes(modes) => viewer(&state.gta6.world).enabled.modes = *modes, WorldStep::Fly(velocity, seconds) => self.fly(state, *velocity, *seconds, false)?, WorldStep::Glide(velocity, seconds) => self.fly(state, *velocity, *seconds, true)?, WorldStep::Perf(name, frames) => self.perf(state, *frames, &out.join(name))?, WorldStep::Move(to, over, name) => self.walk(state, to, *over, &out.join(name))?, WorldStep::Group(id, on) => { - let mut viewer = viewer(); + let mut viewer = viewer(&state.gta6.world); viewer.groups_chosen = true; viewer.enabled.groups.retain(|g| g != id); if *on { @@ -611,12 +613,12 @@ impl Shell { true => or_transport::clock::now(), false => Instant::now(), }; - let (started, from) = (clock(), viewer().camera.position); + let (started, from) = (clock(), viewer(&state.gta6.world).camera.position); // ⚠ The last frame is not cut short at `seconds`: a short last step would read as a camera // slowing to a stop, and a dump after the flight is to see it still flying. loop { let flown = clock().duration_since(started); - viewer().camera.position = from + velocity * flown.as_secs_f32(); + viewer(&state.gta6.world).camera.position = from + velocity * flown.as_secs_f32(); self.idle(state, 1)?; if flown >= seconds { return Ok(()); @@ -627,7 +629,7 @@ impl Shell { /// Draw frames until the install's index is held. fn indexed(&mut self, state: &mut AppState) -> Result<(), String> { let until = Instant::now() + INDEX_DEADLINE; - while !found()?.indexed { + while !found(state)?.indexed { if Instant::now() > until { return Err(format!( "the GTA VI world was still being indexed after {} minutes", @@ -641,8 +643,8 @@ impl Shell { } /// What this frame finds, with what came to the device. - fn found_on_device(&self) -> Result { - let mut found = found()?; + fn found_on_device(&self, state: &AppState) -> Result { + let mut found = found(state)?; found.device = self.bridge.world_changes(); Ok(found) } @@ -656,7 +658,7 @@ impl Shell { self.idle(state, 1)?; frames += 1; let now = started.elapsed(); - let found = self.found_on_device()?; + let found = self.found_on_device(state)?; if rule.settled(now, found) { println!( " settled after {:.1} s; last waited for: {}", diff --git a/src/state/convert.rs b/src/state/convert.rs index 9873662fb..b1d5f2b14 100644 --- a/src/state/convert.rs +++ b/src/state/convert.rs @@ -346,7 +346,7 @@ impl AppState { /// The edition the open document `doc` converts to, or why it does not convert. pub fn document_conversion_to(&self, doc: DocumentId) -> Result { let document = self.document(doc).ok_or("That document is closed")?; - if super::rpf9_scan::from_gta_vi(document.path.as_deref()) { + if super::rpf9_scan::from_gta_vi(&self.gta6.rpf9, document.path.as_deref()) { return Err(tr!( "A GTA VI body is of neither GTA V edition, so it does not convert" )); diff --git a/src/state/document/gta6_meta_strings.rs b/src/state/document/gta6_meta_strings.rs index 61a3705fb..7cbeaadd8 100644 --- a/src/state/document/gta6_meta_strings.rs +++ b/src/state/document/gta6_meta_strings.rs @@ -74,8 +74,8 @@ impl DocumentStrings { } /// GTA VI's keys as every app path loads them, where they are found. -pub fn install_keys() -> Option> { - match crate::state::rpf9_scan::rpf9_table::keys() { +pub(crate) fn install_keys(rpf9: &crate::state::rpf::Rpf9Session) -> Option> { + match crate::state::rpf9_scan::rpf9_table::keys(rpf9) { Ok(keys) => Some(keys), Err(e) => { tracing::debug!(error = %e, "no GTA VI keys"); diff --git a/src/state/document/gta6_script/build/mod.rs b/src/state/document/gta6_script/build/mod.rs index 6c4cad0e7..0094a06fa 100644 --- a/src/state/document/gta6_script/build/mod.rs +++ b/src/state/document/gta6_script/build/mod.rs @@ -72,12 +72,13 @@ pub(super) fn is_archive(path: &Path) -> bool { // ⚠ A worker's call, never the UI thread's: every enciphered entry is deciphered to tell. pub(super) fn build( state: &BuildState, + rpf9: &crate::state::rpf::Rpf9Session, archive: &Path, folder: &Path, building: &Building, progress: &Progress, ) -> Result { - let keys = crate::state::rpf9_scan::rpf9_table::keys()?; + let keys = crate::state::rpf9_scan::rpf9_table::keys(rpf9)?; let (bodies, unread) = programs(archive, &keys, building, progress)?; // The natives lists the names folder holds, whose word types what they state, graded so. let shipped = or_io::container::rpf::shipped_script_names_dir(); diff --git a/src/state/document/gta6_script/jobs.rs b/src/state/document/gta6_script/jobs.rs index 8e51a1968..7637bce8e 100644 --- a/src/state/document/gta6_script/jobs.rs +++ b/src/state/document/gta6_script/jobs.rs @@ -133,9 +133,10 @@ impl AppState { let building = Arc::new(Building::default()); let stage = Arc::clone(&building); let session = self.gta6.script.clone(); + let rpf9 = self.gta6.rpf9.clone(); let work = move |progress: &Progress| { let built = super::guarded(|| { - build::build(&session.build, &archive, &folder, &stage, progress) + build::build(&session.build, &rpf9, &archive, &folder, &stage, progress) }); match built { Ok(Ok(_)) => script.again(&session, &asked, progress), diff --git a/src/state/document/location.rs b/src/state/document/location.rs index 88f2acddf..bb57f41a7 100644 --- a/src/state/document/location.rs +++ b/src/state/document/location.rs @@ -6,7 +6,10 @@ impl Document { /// Its file; the two files a comparison sets side by side; else that it was never saved. pub fn location(&self) -> String { match (&self.path, &self.payload) { - (Some(path), _) => (crate::state::rpf_archive_open::tree_open::shown(path)) + (Some(path), _) => self + .rpf9 + .as_ref() + .and_then(|rpf9| crate::state::rpf_archive_open::tree_open::shown(rpf9, path)) .map_or_else(|| path.display().to_string(), |p| p.display().to_string()), (None, DocPayload::Compare(compared)) => { let [left, right] = &compared.places; diff --git a/src/state/document/meta/mod.rs b/src/state/document/meta/mod.rs index cceb6ddaa..429372ceb 100644 --- a/src/state/document/meta/mod.rs +++ b/src/state/document/meta/mod.rs @@ -83,6 +83,7 @@ pub struct MetaDocument { /// The elements of a GTA VI data XML its library does not type, counted when its text is read. pub gta6_untyped_elements: usize, install: crate::state::gta6::install::InstallSession, + pub(crate) rpf9: crate::state::rpf::Rpf9Session, } /// GTA VI's library where `gta6` and one is installed, else the default. @@ -92,24 +93,26 @@ fn library_for(gta6: bool) -> &'static or_io::meta::SchemaLibrary { } impl MetaDocument { + #[cfg(test)] pub fn from_bytes(bytes: Vec) -> Self { - Self::from_bytes_with(bytes, Default::default()) + Self::from_bytes_with(bytes, Default::default(), Default::default()) } pub(crate) fn from_bytes_with( bytes: Vec, install: crate::state::gta6::install::InstallSession, + rpf9: crate::state::rpf::Rpf9Session, ) -> Self { use or_io::meta::binary::ContainerLayout; let parse_result = or_io::meta::MetaDocument::parse(meta_schema(), bytes.clone()); let layout = parse_result.as_ref().ok().and_then(|d| d.layout.as_ref()); let strings = match layout.map(|l| &l.container) { Some(ContainerLayout::Pso(p)) if p.is_table_form() || p.is_gta_vi() => { - DocumentStrings::of(&bytes, super::gta6_meta_strings::install_keys) + DocumentStrings::of(&bytes, || super::gta6_meta_strings::install_keys(&rpf9)) } _ => DocumentStrings::default(), }; - Self::from_parse(bytes, parse_result, strings, install) + Self::from_parse(bytes, parse_result, strings, install, rpf9) } /// GTA VI data XML `bytes` as `instance` read through GTA VI's library, which lacks `untyped`. @@ -131,6 +134,7 @@ impl MetaDocument { Ok(parsed), DocumentStrings::default(), Default::default(), + Default::default(), ); Self { gta6_library: true, @@ -172,6 +176,7 @@ impl MetaDocument { Ok(parsed), DocumentStrings::default(), install, + Default::default(), )) } @@ -180,6 +185,7 @@ impl MetaDocument { parse_result: or_io::meta::Result, strings: DocumentStrings, install: crate::state::gta6::install::InstallSession, + rpf9: crate::state::rpf::Rpf9Session, ) -> Self { let (parsed, parse_error, source_format, layout) = match parse_result { Ok(parsed_doc) => ( @@ -227,6 +233,7 @@ impl MetaDocument { gta6_untyped: None, gta6_untyped_elements: 0, install, + rpf9, } } @@ -251,6 +258,7 @@ impl MetaDocument { gta6_untyped: None, gta6_untyped_elements: 0, install: Default::default(), + rpf9: Default::default(), } } diff --git a/src/state/document/mod.rs b/src/state/document/mod.rs index 71321d2a5..03d29d531 100644 --- a/src/state/document/mod.rs +++ b/src/state/document/mod.rs @@ -153,14 +153,13 @@ pub struct Document { decoded_bytes: usize, rebuild: image::Rebuild, pub history: super::EditHistory, + rpf9: Option, } impl Document { pub fn new(id: DocumentId, path: Option, payload: DocPayload) -> Self { - let shown = path - .as_deref() - .and_then(super::rpf_archive_open::tree_open::shown); - let name = (shown.as_ref().or(path.as_ref())) + let name = path + .as_ref() .and_then(|p| p.file_stem().and_then(|s| s.to_str())) .unwrap_or(tr!("Untitled")) .to_string(); @@ -183,7 +182,27 @@ impl Document { decoded_bytes: 0, rebuild: Default::default(), history: Default::default(), + rpf9: None, + } + } + + /// Attach the owning app's RPF9 session so tree-opened documents show their tree path and name. + pub(in crate::state) fn with_rpf9(mut self, rpf9: crate::state::rpf::Rpf9Session) -> Self { + if let Some(shown) = self + .path + .as_deref() + .and_then(|p| super::rpf_archive_open::tree_open::shown(&rpf9, p)) + { + if let Some(stem) = shown.file_stem().and_then(|s| s.to_str()) { + self.name = stem.to_string(); + } } + self.rpf9 = Some(rpf9); + self + } + + pub(crate) fn rpf9_session(&self) -> Option<&crate::state::rpf::Rpf9Session> { + self.rpf9.as_ref() } pub fn kind(&self) -> DocumentKind { @@ -397,7 +416,11 @@ impl Document { /// Its file's name, extension included, or its name while it has no file. pub fn file_name(&self) -> String { - let shown = (self.path.as_deref()).and_then(super::rpf_archive_open::tree_open::shown); + let shown = self.rpf9.as_ref().and_then(|rpf9| { + self.path + .as_deref() + .and_then(|p| super::rpf_archive_open::tree_open::shown(rpf9, p)) + }); (shown.as_deref().or(self.path.as_deref())) .and_then(Path::file_name) .map_or_else(|| self.name.clone(), |n| n.to_string_lossy().into_owned()) diff --git a/src/state/document_io.rs b/src/state/document_io.rs index 88274fbbd..717a56d2a 100644 --- a/src/state/document_io.rs +++ b/src/state/document_io.rs @@ -217,11 +217,11 @@ pub(super) fn parse_payload_from_path( // ⚠ Before the whole read: a GTA VI archive can be tens of gigabytes, and is scanned instead, as is the tab of one read again. if matches!(kind, DocumentKind::Rpf | DocumentKind::Rpf9) { // Where a key opens its table it is the tree every archive opens as, and no scan runs. - if let Some(tree) = super::rpf_archive_open::gta6_tree(path) { + if let Some(tree) = super::rpf_archive_open::gta6_tree(>a6.rpf9, path) { return Ok((tree, None)); } // Else its scan lists it, and a toast says why. - super::rpf9_scan::rpf9_table::offer(path); + super::rpf9_scan::rpf9_table::offer(>a6.rpf9, path); if let Some(scan) = super::rpf9_scan::Rpf9ScanDocument::open(path)? { return Ok((DocPayload::Rpf9(Arc::new(scan)), None)); } @@ -293,6 +293,7 @@ pub(super) fn parse_payload_with( return Ok(DocPayload::Meta(document::MetaDocument::from_bytes_with( data.to_vec(), gta6.install.clone(), + gta6.rpf9.clone(), ))); } } @@ -376,6 +377,7 @@ pub(super) fn parse_payload_with( DocumentKind::Meta => Ok(DocPayload::Meta(document::MetaDocument::from_bytes_with( data.to_vec(), gta6.install.clone(), + gta6.rpf9.clone(), ))), DocumentKind::Hex | DocumentKind::Gta6Save if gta6_save::is_save(data) => { gta6_save::open(>a6.bodies, data) @@ -425,6 +427,7 @@ pub(super) fn text_payload_with( DocumentKind::Meta => DocPayload::Meta(document::MetaDocument::from_bytes_with( data, gta6.install.clone(), + gta6.rpf9.clone(), )), _ => text_or_hex(path, data), } @@ -488,10 +491,10 @@ pub(super) fn serialize_payload( None => serialize_archive_records(v.session.file_records()?, rpf_mode, crypto), }, DocPayload::Text(t) => Ok(t.encode()), - DocPayload::Meta(m) => { - super::gta6_meta_save::meta_bytes(m, || super::rpf9_scan::rpf9_table::keys().ok()) - .map_err(|e| format!("meta serialize: {e}")) - } + DocPayload::Meta(m) => super::gta6_meta_save::meta_bytes(m, || { + super::rpf9_scan::rpf9_table::keys(&m.rpf9).ok() + }) + .map_err(|e| format!("meta serialize: {e}")), DocPayload::Hex(_) => Err(READ_ONLY_HEX.to_string()), DocPayload::Ttpf(ttpf) => ttpf.save(), DocPayload::Rpf9(_) => Err(crate::i18n::tr(READ_ONLY_RPF9).to_string()), diff --git a/src/state/file_index/mod.rs b/src/state/file_index/mod.rs index 935a7fdc2..c653d5201 100644 --- a/src/state/file_index/mod.rs +++ b/src/state/file_index/mod.rs @@ -191,7 +191,7 @@ impl Root { self.walk.is_some() } - fn start(&mut self, source: Source) { + fn start(&mut self, rpf9: crate::state::rpf::Rpf9Session, source: Source) { let previous = self.walked.then(|| Arc::clone(&self.listing)); let root = self.path.clone(); // A first walk takes the index kept from the last run, if one was, and checks it. @@ -221,7 +221,7 @@ impl Root { cancel: stop, }; // A GTA VI install's archives open only with the keys of its own build. - let provider = gta6_provider(&root).unwrap_or(provider); + let provider = gta6_provider(&rpf9, &root).unwrap_or(provider); tracing::info!(root = %root.display(), "a file index walk began"); walk_disk(&walk, provider, previous); let ms = began.elapsed().as_millis(); @@ -763,7 +763,10 @@ fn walk_disk( /// The GTA VI session the first RPF9 archive below `root` opens with, `None` where there is none /// or no key is held; it waits for the names, so only a walk's worker asks. -fn gta6_provider(root: &Path) -> Option> { +fn gta6_provider( + rpf9: &crate::state::rpf::Rpf9Session, + root: &Path, +) -> Option> { let mut folders = vec![root.to_path_buf()]; while let Some(folder) = folders.pop() { for entry in std::fs::read_dir(&folder).into_iter().flatten().flatten() { @@ -771,7 +774,7 @@ fn gta6_provider(root: &Path) -> Option> { if path.is_dir() { folders.push(path); } else if ends_rpf(&entry.file_name().to_string_lossy()) && is_rpf9(&path) { - return super::rpf_archive_open::gta6_crypto(&path); + return super::rpf_archive_open::gta6_crypto(rpf9, &path); } } } @@ -892,9 +895,10 @@ impl AppState { } else { Some(Source::Disk(self.keys.provider())) }; + let rpf9 = self.gta6.rpf9.clone(); let root = &mut self.find.file_index.roots[at]; match source { - Some(source) => root.start(source), + Some(source) => root.start(rpf9, source), None => root.settle_empty(), } } @@ -963,8 +967,9 @@ mod tests { const WHAT: &str = "a GTA VI row is found by the name hash its table states"; const ARCHIVES: usize = 8; let build_root = std::env::var_os("OPENRAGE_GTA6_BUILD").map(PathBuf::from); + let rpf9 = crate::state::rpf::Rpf9Session::default(); let (Some(build_root), Ok(keys)) = - (build_root, crate::state::rpf9_scan::rpf9_table::keys()) + (build_root, crate::state::rpf9_scan::rpf9_table::keys(&rpf9)) else { or_test_support::skip_install(WHAT, "set OPENRAGE_GTA6_BUILD and OPENRAGE_GTA6_KEYS"); return; diff --git a/src/state/file_index/searching_every_archive.rs b/src/state/file_index/searching_every_archive.rs index 926e2fb33..781047a75 100644 --- a/src/state/file_index/searching_every_archive.rs +++ b/src/state/file_index/searching_every_archive.rs @@ -20,7 +20,9 @@ fn every_row_of_the_builds_smallest_archives_keeps_its_size_kind_and_hash() { const WHAT: &str = "a walk of the build keeps each row's size, kind and table hash"; const ARCHIVES: usize = 4; let build_root = std::env::var_os("OPENRAGE_GTA6_BUILD").map(PathBuf::from); - let (Some(build_root), Ok(keys)) = (build_root, crate::state::rpf9_scan::rpf9_table::keys()) + let rpf9 = crate::state::rpf::Rpf9Session::default(); + let (Some(build_root), Ok(keys)) = + (build_root, crate::state::rpf9_scan::rpf9_table::keys(&rpf9)) else { or_test_support::skip_install(WHAT, "set OPENRAGE_GTA6_BUILD and OPENRAGE_GTA6_KEYS"); return; diff --git a/src/state/files_view/mod.rs b/src/state/files_view/mod.rs index 815874e91..e97fab185 100644 --- a/src/state/files_view/mod.rs +++ b/src/state/files_view/mod.rs @@ -689,8 +689,9 @@ mod tests { const ARCHIVES: usize = 16; let _serial = crate::ui::theme::serial(); let build_root = std::env::var_os("OPENRAGE_GTA6_BUILD").map(PathBuf::from); + let rpf9 = crate::state::rpf::Rpf9Session::default(); let (Some(build_root), Ok(keys)) = - (build_root, crate::state::rpf9_scan::rpf9_table::keys()) + (build_root, crate::state::rpf9_scan::rpf9_table::keys(&rpf9)) else { or_test_support::skip_install( WHAT, @@ -764,8 +765,9 @@ mod tests { const WHAT: &str = "a GTA VI root's total counts a nested archive past 4 GiB whole"; let _serial = crate::ui::theme::serial(); let build_root = std::env::var_os("OPENRAGE_GTA6_BUILD").map(PathBuf::from); + let rpf9 = crate::state::rpf::Rpf9Session::default(); let (Some(build_root), Ok(keys)) = - (build_root, crate::state::rpf9_scan::rpf9_table::keys()) + (build_root, crate::state::rpf9_scan::rpf9_table::keys(&rpf9)) else { or_test_support::skip_install( WHAT, diff --git a/src/state/gta6/anim/gta6_bone_edit/mod.rs b/src/state/gta6/anim/gta6_bone_edit/mod.rs index 749720764..bcc8295f3 100644 --- a/src/state/gta6/anim/gta6_bone_edit/mod.rs +++ b/src/state/gta6/anim/gta6_bone_edit/mod.rs @@ -27,11 +27,17 @@ enum Whose { } /// `skeleton` swapped with the one held for the scanned body at `path`; `false` where none is. -fn swap_held(anim: &AnimSession, path: &Path, whose: Whose, skeleton: &mut Skeleton) -> bool { +fn swap_held( + anim: &AnimSession, + rpf9: &crate::state::rpf::Rpf9Session, + path: &Path, + whose: Whose, + skeleton: &mut Skeleton, +) -> bool { if let Whose::Entry(code) = whose { return crate::state::gta6_entry_skeletons::swap(anim, path, code, skeleton); } - match crate::state::rpf9_scan::skeletons().get_mut(path) { + match crate::state::rpf9_scan::skeletons(rpf9).get_mut(path) { Some(Ok(held)) => { std::mem::swap(held, skeleton); true @@ -45,6 +51,7 @@ fn swap_held(anim: &AnimSession, path: &Path, whose: Whose, skeleton: &mut Skele // the Outline and the export read. struct Bones { anim: AnimSession, + rpf9: crate::state::rpf::Rpf9Session, path: PathBuf, whose: Whose, other: Skeleton, @@ -52,7 +59,13 @@ struct Bones { impl Swap for Bones { fn swap(&mut self, _: &mut DocPayload) -> bool { - swap_held(&self.anim, &self.path, self.whose, &mut self.other) + swap_held( + &self.anim, + &self.rpf9, + &self.path, + self.whose, + &mut self.other, + ) } } @@ -146,7 +159,7 @@ impl AppState { let path = (document.path.clone()) .ok_or_else(|| tr!("This document has no file, so it holds no GTA VI skeleton."))?; let mut after = match whose { - Whose::Own => crate::state::rpf9_scan::scanned_skeleton(&path)?, + Whose::Own => crate::state::rpf9_scan::scanned_skeleton(&self.gta6.rpf9, &path)?, Whose::Entry(code) => { crate::state::gta6_entry_skeletons::of(&self.gta6.anim, &path, code).ok_or_else( || { @@ -164,7 +177,7 @@ impl AppState { BoneEdit::Scale(_) => (tr!("Scale bone {name}", name = name), "scale"), BoneEdit::Name(_) => (tr!("Rename bone {name}", name = name), "name"), }; - if !swap_held(&self.gta6.anim, &path, whose, &mut after) { + if !swap_held(&self.gta6.anim, &self.gta6.rpf9, &path, whose, &mut after) { return Err(tr!("The skeleton this body opened with is no longer held.").to_string()); } let key = match whose { @@ -175,6 +188,7 @@ impl AppState { key: Some(key), parts: vec![Box::new(Bones { anim: self.gta6.anim.clone(), + rpf9: self.gta6.rpf9.clone(), path, whose, other: after, @@ -201,7 +215,7 @@ pub(in crate::state) fn edited_save( // Each skeleton held, `None` the body's own, else the dictionary entry's code. let skeletons: Vec<(Option, Skeleton)> = match **resource { Resource::Drawable(_) | Resource::DrawableWithBound(_) => { - (crate::state::rpf9_scan::scanned_skeleton(path) + (crate::state::rpf9_scan::scanned_skeleton(>a6.rpf9, path) .ok() .into_iter()) .map(|skeleton| (None, skeleton)) diff --git a/src/state/gta6/anim/gta6_bone_edit/tests.rs b/src/state/gta6/anim/gta6_bone_edit/tests.rs index 5346c8ecb..7ecb0704d 100644 --- a/src/state/gta6/anim/gta6_bone_edit/tests.rs +++ b/src/state/gta6/anim/gta6_bone_edit/tests.rs @@ -90,8 +90,8 @@ fn read_back(path: &Path) -> Vec { .virtual_section } -fn held(path: &Path) -> or_io::gta6::headerless::Skeleton { - crate::state::rpf9_scan::scanned_skeleton(path).expect("the skeleton it opened with") +fn held(rpf9: &crate::state::rpf::Rpf9Session, path: &Path) -> or_io::gta6::headerless::Skeleton { + crate::state::rpf9_scan::scanned_skeleton(rpf9, path).expect("the skeleton it opened with") } #[test] @@ -111,7 +111,7 @@ fn a_bone_edit_undoes_and_saves_over_its_loose_resource_with_the_inverse_binds_u settle(&mut state); let doc = (state.active_document).unwrap_or_else(|| panic!("opened: {}", state.error_dialog.message)); - let opened_as = held(&path); + let opened_as = held(&state.gta6.rpf9, &path); assert_eq!(opened_as.bones.len(), 2); // Refused, and nothing changes: an empty name, a scale of 0, a bone past the count. @@ -127,14 +127,14 @@ fn a_bone_edit_undoes_and_saves_over_its_loose_resource_with_the_inverse_binds_u "{edit:?}" ); } - assert_eq!(held(&path), opened_as); + assert_eq!(held(&state.gta6.rpf9, &path), opened_as); assert!(state.document(doc).is_some_and(|d| !d.dirty)); // The head moves a quarter metre along x: its inverse bind undoes the root's metre and its own. state .edit_gta6_bone(doc, 1, BoneEdit::Position([0.25, 0.0, 0.5])) .expect("a finite position"); - let edited = held(&path); + let edited = held(&state.gta6.rpf9, &path); assert_eq!(edited.bones[1].translation, [0.25, 0.0, 0.5]); let identity = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; let [x, y, z] = identity; @@ -147,9 +147,17 @@ fn a_bone_edit_undoes_and_saves_over_its_loose_resource_with_the_inverse_binds_u state.active_document = Some(doc); assert!(state.undo().is_some()); - assert_eq!(held(&path), opened_as, "undone, it is as it opened"); + assert_eq!( + held(&state.gta6.rpf9, &path), + opened_as, + "undone, it is as it opened" + ); assert!(state.redo().is_some()); - assert_eq!(held(&path), edited, "redone, the edit is back"); + assert_eq!( + held(&state.gta6.rpf9, &path), + edited, + "redone, the edit is back" + ); // Saved over its own file: the skeleton reads back as edited, the shaders as they were. assert!(state.save_active_document()); diff --git a/src/state/gta6/anim/gta6_entry_skeletons.rs b/src/state/gta6/anim/gta6_entry_skeletons.rs index 4bcad80a8..ded08e56c 100644 --- a/src/state/gta6/anim/gta6_entry_skeletons.rs +++ b/src/state/gta6/anim/gta6_entry_skeletons.rs @@ -99,16 +99,16 @@ pub(crate) fn entry_bone_of(selection: SelectionKey) -> Option<(u32, usize)> { /// The skeleton `doc` shows for `selection`: its own, the selected dictionary entry's, or for an /// unselected dictionary its first entry's skeleton. pub(crate) fn shown( - anim: &AnimSession, + gta6: &crate::state::gta6::session::Gta6Session, doc: &Document, selection: Option, ) -> Option { let path = doc.path.as_deref()?; match entry_of(doc, selection) { - Some(code) => of(anim, path, code), - None => crate::state::rpf9_scan::scanned_skeleton(path) + Some(code) => of(>a6.anim, path, code), + None => crate::state::rpf9_scan::scanned_skeleton(>a6.rpf9, path) .ok() - .or_else(|| all(anim, path).into_iter().next().map(|(_, s)| s)), + .or_else(|| all(>a6.anim, path).into_iter().next().map(|(_, s)| s)), } } diff --git a/src/state/gta6/anim/gta6_face/mod.rs b/src/state/gta6/anim/gta6_face/mod.rs index 967021dd8..b164b29ff 100644 --- a/src/state/gta6/anim/gta6_face/mod.rs +++ b/src/state/gta6/anim/gta6_face/mod.rs @@ -297,7 +297,7 @@ pub(crate) fn model_skeleton( doc: DocumentId, path: &Path, ) -> Result { - let own = crate::state::rpf9_scan::scanned_skeleton(path); + let own = crate::state::rpf9_scan::scanned_skeleton(&state.gta6.rpf9, path); let drawable = match state.document(doc).map(|d| &d.payload) { Some(DocPayload::Gta6Drawable(resource)) => match &**resource { Resource::Drawable(d) => d, @@ -306,7 +306,7 @@ pub(crate) fn model_skeleton( Resource::Dictionary(_) => { let selected = state.selection.selected(doc); let entry = (state.document(doc)).and_then(|d| { - crate::state::gta6_entry_skeletons::shown(&state.gta6.anim, d, selected) + crate::state::gta6_entry_skeletons::shown(&state.gta6, d, selected) }); return entry.ok_or_else(|| { tr!("Select a drawable of this dictionary that holds a skeleton, then pick the model again.") diff --git a/src/state/gta6/bodies/gta6_meta_save/mod.rs b/src/state/gta6/bodies/gta6_meta_save/mod.rs index c7d13a897..178a5d743 100644 --- a/src/state/gta6/bodies/gta6_meta_save/mod.rs +++ b/src/state/gta6/bodies/gta6_meta_save/mod.rs @@ -98,10 +98,13 @@ impl AppState { } // The text is parsed and the body written on the save's worker, never on the UI thread. let meta = meta.clone(); + let rpf9 = self.gta6.rpf9.clone(); let write: Arc = Arc::new(move || { let mut meta = meta.clone(); meta.ensure_text_current(); - meta_bytes(&meta, || crate::state::rpf9_scan::rpf9_table::keys().ok()) + meta_bytes(&meta, || { + crate::state::rpf9_scan::rpf9_table::keys(&rpf9).ok() + }) }); let item = ExtractItem::written(name.clone(), write); Some(self.start_scanned_extraction(name, dest, reads, vec![item], OnClash::Save)) diff --git a/src/state/gta6/bodies/gta6_meta_save/splice.rs b/src/state/gta6/bodies/gta6_meta_save/splice.rs index 2f2eda66f..6865a3cf7 100644 --- a/src/state/gta6/bodies/gta6_meta_save/splice.rs +++ b/src/state/gta6/bodies/gta6_meta_save/splice.rs @@ -471,7 +471,9 @@ mod tests { const DOCS: usize = 16; let build = (std::env::var_os(BUILD_ENV).map(std::path::PathBuf::from)).filter(|p| p.is_dir()); - let keys = (build.as_ref()).and_then(|_| crate::state::rpf9_scan::rpf9_table::keys().ok()); + let rpf9 = crate::state::rpf::Rpf9Session::default(); + let keys = + (build.as_ref()).and_then(|_| crate::state::rpf9_scan::rpf9_table::keys(&rpf9).ok()); let (Some(build), Some(keys)) = (build, keys) else { or_test_support::skip_install( "gta6 data XML splice", diff --git a/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs b/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs index 52e1b3c50..30478a9f4 100644 --- a/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs +++ b/src/state/gta6/bodies/gta6_resource_save/awc_in_extent.rs @@ -30,11 +30,11 @@ pub(super) fn edited( return Some(awc.to_bytes().map(EditedSave::Bytes)); }; let (path, archive, awc) = (path.to_path_buf(), archive.to_path_buf(), awc.clone()); - let install = gta6.install.clone(); + let gta6 = gta6.clone(); let write: Arc = Arc::new(move || { let mut awc = awc.clone(); let whole = awc.to_bytes()?; - let fitted = (as_read(&install, &path, &archive, offset)) + let fitted = (as_read(>a6, &path, &archive, offset)) .and_then(|source| laid(&source, awc.file(AwcKey::default())?)); Ok(fitted.unwrap_or_else(|why| { tracing::warn!( @@ -52,13 +52,13 @@ pub(super) fn edited( /// The container the body at `offset` of `archive` opened as under `path`, read again by the door /// it opened through: its tree row's table, else a scan's read. fn as_read( - install: &crate::state::gta6::install::InstallSession, + gta6: &crate::state::gta6::session::Gta6Session, path: &Path, archive: &Path, offset: u64, ) -> Result, String> { - match tree_open::read(path, archive, offset) { - None => crate::state::rpf9_scan::extracted_body(install, archive, offset), + match tree_open::read(>a6.rpf9, path, archive, offset) { + None => crate::state::rpf9_scan::extracted_body(>a6.install, archive, offset), Some(read) => match read? { TableRead::Body(_, bytes) => Ok(bytes), TableRead::Plain(DocPayload::Hex(hex)) => Ok(hex.bytes), @@ -280,7 +280,7 @@ mod tests { // ⚠ A built archive deflates every body, which a scan names no audio container, so the // document the tree's door would open is put in place by hand on the row's path. let path = body_path(&place.file, place.offset, View::Audio); - leave(&path, &place, start, synthetic_keys, None); + leave(&state.gta6.rpf9, &path, &place, start, synthetic_keys, None); name(&state, &path, DOC, node); let awc = crate::audio::AwcDocument::open(&container()).expect("an ADAT container"); let doc = state.insert_document(path.clone(), DocPayload::Awc(awc), None, None); @@ -340,7 +340,9 @@ mod tests { let started = Instant::now(); let wait = || (Instant::now() + WAIT).min(started + END); let build = (std::env::var_os(BUILD_ENV).map(PathBuf::from)).filter(|p| p.is_dir()); - let keys = (build.as_ref()).and_then(|_| crate::state::rpf9_scan::rpf9_table::keys().ok()); + let rpf9 = crate::state::rpf::Rpf9Session::default(); + let keys = + (build.as_ref()).and_then(|_| crate::state::rpf9_scan::rpf9_table::keys(&rpf9).ok()); let (Some(build), Some(keys)) = (build, keys) else { or_test_support::skip_install( WHAT, @@ -507,7 +509,7 @@ mod tests { continue; } let (archive, offset) = scanned_body(&path).expect("a body of the archive"); - let source = as_read(&state.gta6.install, &path, archive, offset) + let source = as_read(&state.gta6, &path, archive, offset) .expect("the container as read"); let in_extent = laid(&source, state.awc_file(doc).expect("its container")); match &in_extent { diff --git a/src/state/gta6/bodies/gta6_resource_save/mod.rs b/src/state/gta6/bodies/gta6_resource_save/mod.rs index bca938bd3..11b257df7 100644 --- a/src/state/gta6/bodies/gta6_resource_save/mod.rs +++ b/src/state/gta6/bodies/gta6_resource_save/mod.rs @@ -140,7 +140,8 @@ impl AppState { // A body shown as the lines its reader reads is never written as those lines. let edited_text = doc.dirty && matches!(doc.payload, crate::state::DocPayload::Text(_)) - && (doc.path.as_deref()).is_some_and(crate::state::rpf9_scan::opened_as_text); + && (doc.path.as_deref()) + .is_some_and(|p| crate::state::rpf9_scan::opened_as_text(&self.gta6.rpf9, p)); let item = match &doc.payload { crate::state::DocPayload::Meta(meta) if xml => { // A GTA VI form's name comments are display-only; the file is the comment-free XML. diff --git a/src/state/gta6/drawable/gta6_effects.rs b/src/state/gta6/drawable/gta6_effects.rs index 239a60f8d..171c559ad 100644 --- a/src/state/gta6/drawable/gta6_effects.rs +++ b/src/state/gta6/drawable/gta6_effects.rs @@ -9,7 +9,7 @@ use std::sync::{Arc, Mutex}; use or_io::container::rpf::{read_rpf9_body, Rpf9ScanFind}; use or_job::{Cancel, Progress}; -use crate::state::gta6::bodies::BodiesSession; +use crate::state::gta6::session::Gta6Session; use crate::state::jobs::{file_name, JobKind, Outcome, RunningJob, Then}; use crate::state::{AppState, DocPayload}; @@ -32,7 +32,7 @@ pub struct EffectsRead { impl EffectsRead { /// Read the container `find` of `archive`, at most `limit` bytes, on a worker. pub(in crate::state) fn start( - bodies: BodiesSession, + gta6: Gta6Session, archive: &Path, find: Rpf9ScanFind, limit: u64, @@ -44,23 +44,19 @@ impl EffectsRead { ); let archive = archive.to_path_buf(); Self::run(doing, move |cancel, progress| { - effects(&bodies, &archive, find, limit, cancel, progress) + effects(>a6, &archive, find, limit, cancel, progress) }) } /// Read every `SGD5` container a scan of `archive` finds, at most `limit` bytes each, on a worker. - pub(in crate::state) fn every_container( - bodies: BodiesSession, - archive: &Path, - limit: u64, - ) -> Self { + pub(in crate::state) fn every_container(gta6: Gta6Session, archive: &Path, limit: u64) -> Self { let doing = tr!( "Reading the effects of {archive}", archive = file_name(archive) ); let archive = archive.to_path_buf(); Self::run(doing, move |cancel, progress| { - every_container(&bodies, &archive, limit, cancel, progress) + every_container(>a6, &archive, limit, cancel, progress) }) } @@ -126,7 +122,7 @@ impl Drop for EffectsRead { /// The container's bytes read through a file that reports how far it has got and stops when asked. fn effects( - bodies: &BodiesSession, + gta6: &Gta6Session, archive: &Path, find: Rpf9ScanFind, limit: u64, @@ -148,14 +144,14 @@ fn effects( } let platform = or_io::container::rpf::rpf9_platform_of(archive).unwrap_or(or_io::Platform::XboxSeries); - let count = crate::state::gta6_resource::learn_effects(bodies, &bytes, platform)?; - crate::state::gta6_shaders::add_source(archive, find.offset, &bytes, platform); + let count = crate::state::gta6_resource::learn_effects(>a6.bodies, &bytes, platform)?; + crate::state::gta6_shaders::add_source(>a6.drawable, archive, find.offset, &bytes, platform); Ok(count) } /// The effects of each `SGD5` container a scan of `archive` finds, the scan's place its progress. fn every_container( - bodies: &BodiesSession, + gta6: &Gta6Session, archive: &Path, limit: u64, cancel: &Cancel, @@ -176,8 +172,14 @@ fn every_container( if matches!(find.kind, Rpf9BodyKind::Sgd5 { .. }) { let (_, bytes) = read_rpf9_body(&file, find.offset, limit).map_err(|e| e.to_string())?; - learned += crate::state::gta6_resource::learn_effects(bodies, &bytes, platform)?; - crate::state::gta6_shaders::add_source(archive, find.offset, &bytes, platform); + learned += crate::state::gta6_resource::learn_effects(>a6.bodies, &bytes, platform)?; + crate::state::gta6_shaders::add_source( + >a6.drawable, + archive, + find.offset, + &bytes, + platform, + ); } } Ok(learned) @@ -185,22 +187,27 @@ fn every_container( /// The read of the effects of the GTA VI install folder's `shaders.rpf`, under the folder it was /// started for; `None` beside a folder where none was started. -// ponytail: one read for the whole app, started once per install folder. -static INSTALL_READ: Mutex)>> = Mutex::new(None); +type InstallReadSlot = Option<(std::path::PathBuf, Option)>; + +#[derive(Clone, Default)] +pub(super) struct InstallReadCache(Arc>); -fn install_read( -) -> std::sync::MutexGuard<'static, Option<(std::path::PathBuf, Option)>> { - INSTALL_READ.lock().unwrap_or_else(|p| p.into_inner()) +fn install_read(drawable: &super::DrawableSession) -> std::sync::MutexGuard<'_, InstallReadSlot> { + drawable + .install_read + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// The install folder's effects read while it runs, as the job list draws it. -pub(in crate::state) fn install_job() -> Option { - install_read().as_ref()?.1.as_ref()?.job() +pub(in crate::state) fn install_job(drawable: &super::DrawableSession) -> Option { + install_read(drawable).as_ref()?.1.as_ref()?.job() } /// Ask the install folder's effects read to stop. -pub(in crate::state) fn stop_install_read() { - if let Some((_, Some(read))) = install_read().as_ref() { +pub(in crate::state) fn stop_install_read(drawable: &super::DrawableSession) { + if let Some((_, Some(read))) = install_read(drawable).as_ref() { read.stop(); } } @@ -244,15 +251,15 @@ impl AppState { if !crate::state::gta6_resource::kept_effects_ready(&self.gta6.bodies) { return; } - let mut read = install_read(); + let mut read = install_read(&self.gta6.drawable); if read.as_ref().is_some_and(|(tried, _)| tried == root) { return; } let archive = root.join("shaders.rpf"); let start = !crate::state::gta6_resource::effects_known(&self.gta6.bodies) && archive.is_file(); - let started = start - .then(|| EffectsRead::every_container(self.gta6.bodies.clone(), &archive, 1 << 30)); + let started = + start.then(|| EffectsRead::every_container(self.gta6.clone(), &archive, 1 << 30)); *read = Some((root.clone(), started)); } @@ -268,7 +275,9 @@ impl AppState { // ⚠ Only by the state whose folder it was started for: another state of the process would // say the end in its own job list, and the one that asked would wait for it for ever. let root = crate::state::gta_vi::install(&self.prefs).map(|(_, root)| root); - if let Some((_, read)) = (install_read().as_mut()).filter(|(of, _)| root == Some(of)) { + if let Some((_, read)) = + (install_read(&self.gta6.drawable).as_mut()).filter(|(of, _)| root == Some(of)) + { if let Some(end) = read.as_ref().and_then(EffectsRead::ended) { ended.push(end); *read = None; @@ -295,6 +304,6 @@ impl AppState { }; self.jobs.record(JobKind::EffectsRead, outcome, said); } - crate::state::gta6_shaders::poll(&mut self.jobs); + crate::state::gta6_shaders::poll(&self.gta6.drawable, &mut self.jobs); } } diff --git a/src/state/gta6/drawable/gta6_export.rs b/src/state/gta6/drawable/gta6_export.rs index 0eb973a7b..bbf4306b6 100644 --- a/src/state/gta6/drawable/gta6_export.rs +++ b/src/state/gta6/drawable/gta6_export.rs @@ -33,7 +33,7 @@ impl Gta6Export { let path = document.path.as_deref(); let skeleton = match &**body { Resource::Drawable(_) | Resource::DrawableWithBound(_) => { - crate::state::rpf9_scan::scanned_skeleton(path?).ok() + crate::state::rpf9_scan::scanned_skeleton(&state.gta6.rpf9, path?).ok() } // A dictionary's entry is skinned to the skeleton it holds itself, where it holds one. Resource::Dictionary(_) => { diff --git a/src/state/gta6/drawable/gta6_gltf_import/mod.rs b/src/state/gta6/drawable/gta6_gltf_import/mod.rs index 9ccbe131b..96c2fb3ed 100644 --- a/src/state/gta6/drawable/gta6_gltf_import/mod.rs +++ b/src/state/gta6/drawable/gta6_gltf_import/mod.rs @@ -39,16 +39,22 @@ pub(in crate::state) struct Choice { } /// The imports made to each scanned body, by its document's path, oldest first. -// ponytail: one map for the whole app, as the scan's skeletons are; an undo swaps a path's list. -static IMPORTS: Mutex>> = Mutex::new(BTreeMap::new()); +type ImportsMap = BTreeMap>; -fn imports() -> MutexGuard<'static, BTreeMap>> { - IMPORTS.lock().unwrap_or_else(|p| p.into_inner()) +#[derive(Clone, Default)] +pub(super) struct GltfImportsCache(Arc>); + +fn imports(drawable: &super::DrawableSession) -> MutexGuard<'_, ImportsMap> { + drawable + .gltf_imports + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// Forget the imports of the body at `path`, which opens anew with none. -pub(in crate::state) fn forget(path: &Path) { - imports().remove(path); +pub(in crate::state) fn forget(drawable: &super::DrawableSession, path: &Path) { + imports(drawable).remove(path); } /// What a worker needs to replace a scanned body's geometry from a glTF, and the mesh it read. @@ -81,7 +87,7 @@ impl Gta6Import { ); return Some(Err(why.to_string())); }; - let earlier = path.and_then(|p| imports().get(p).cloned()); + let earlier = path.and_then(|p| imports(&state.gta6.drawable).get(p).cloned()); let earlier = earlier.unwrap_or_default(); Some(Ok(Self { archive: archive.to_path_buf(), @@ -225,13 +231,14 @@ pub(in crate::state) fn drawable_mut( /// A step's list of imports of the body at `path`: the one the map does not hold now. struct Imports { + cache: GltfImportsCache, path: PathBuf, other: Vec, } impl Swap for Imports { fn swap(&mut self, _: &mut DocPayload) -> bool { - let mut held = imports(); + let mut held = self.cache.0.lock().unwrap_or_else(|p| p.into_inner()); let now = held.entry(self.path.clone()).or_default(); std::mem::swap(now, &mut self.other); true @@ -280,16 +287,22 @@ impl AppState { let before = std::mem::replace(&mut held.levels, levels); let min = std::mem::replace(&mut held.box_min, box_min); let max = std::mem::replace(&mut held.box_max, box_max); - let mut list = imports().get(&path).cloned().unwrap_or_default(); + let cache = self.gta6.drawable.gltf_imports.clone(); + let mut list = imports(&self.gta6.drawable) + .get(&path) + .cloned() + .unwrap_or_default(); list.push((code, scene, choice)); - let other = imports().insert(path.clone(), list).unwrap_or_default(); + let other = imports(&self.gta6.drawable) + .insert(path.clone(), list) + .unwrap_or_default(); let mut change = Change::part("gta6 gltf import", before, move |p| { drawable_mut(p, code).map(|d| &mut d.levels) }) .and_part(min, move |p| drawable_mut(p, code).map(|d| &mut d.box_min)) .and_part(max, move |p| drawable_mut(p, code).map(|d| &mut d.box_max)); if let Change::Part { parts, .. } = &mut change { - parts.push(Box::new(Imports { path, other })); + parts.push(Box::new(Imports { cache, path, other })); } let name = crate::state::jobs::file_name(mesh); self.record(doc, tr!("Replace from {mesh}", mesh = name), change); @@ -311,7 +324,7 @@ pub(in crate::state) fn edited_save( gta6: &crate::state::gta6::session::Gta6Session, ) -> Option> { let save = crate::state::gta6_embedded_edit::edited_save(document, gta6)?; - let held = (document.path.as_deref()).and_then(|p| imports().get(p).cloned()); + let held = (document.path.as_deref()).and_then(|p| imports(>a6.drawable).get(p).cloned()); let Some(held) = held.filter(|h| !h.is_empty()) else { return Some(save); }; diff --git a/src/state/gta6/drawable/gta6_gltf_import/tests.rs b/src/state/gta6/drawable/gta6_gltf_import/tests.rs index db680f76e..f171134f0 100644 --- a/src/state/gta6/drawable/gta6_gltf_import/tests.rs +++ b/src/state/gta6/drawable/gta6_gltf_import/tests.rs @@ -243,9 +243,9 @@ fn a_gltf_replaces_a_gta_vi_drawable_s_geometry_as_a_step_that_undoes_and_saves( assert_eq!(g.triangles, triangles); // The body opened anew, as after a close that did not save, holds none of its imports. - assert!(imports().contains_key(&path)); + assert!(imports(&state.gta6.drawable).contains_key(&path)); crate::state::rpf9_scan::read_body(&state.gta6, &path, &path, 0).expect("it opens again"); - assert!(!imports().contains_key(&path)); + assert!(!imports(&state.gta6.drawable).contains_key(&path)); } #[test] diff --git a/src/state/gta6/drawable/gta6_head.rs b/src/state/gta6/drawable/gta6_head.rs index 150f3b0c2..f16f7cfa7 100644 --- a/src/state/gta6/drawable/gta6_head.rs +++ b/src/state/gta6/drawable/gta6_head.rs @@ -29,15 +29,17 @@ struct Kept { /// The head of each scanned drawable or fragment opened last, read on the load's worker, oldest /// first. -static HEADS: Mutex> = Mutex::new(Vec::new()); +#[derive(Clone, Default)] +pub(super) struct HeadsCache(Arc>>); -fn heads() -> MutexGuard<'static, Vec> { - (HEADS.lock()).unwrap_or_else(|poisoned| poisoned.into_inner()) +fn heads(drawable: &super::DrawableSession) -> MutexGuard<'_, Vec> { + (drawable.heads.0.lock()).unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Read the head of the drawable, or of the fragment's drawable where `fragment`, that the scanned /// body at `path` holds, and keep it for `resource`, the body read. pub(in crate::state) fn keep( + drawable: &super::DrawableSession, path: &Path, resource: &Arc, virtual_section: &[u8], @@ -50,12 +52,17 @@ pub(in crate::state) fn keep( e = e ) }); - hold(path, resource, head); + hold(drawable, path, resource, head); } -fn hold(path: &Path, resource: &Arc, head: Result) { +fn hold( + drawable: &super::DrawableSession, + path: &Path, + resource: &Arc, + head: Result, +) { let at = Arc::as_ptr(resource) as usize; - let mut heads = heads(); + let mut heads = heads(drawable); // A body read again replaces its head, and a resource where a gone one lay replaces that one's. heads.retain(|k| k.path != path && k.resource != at); heads.push(Kept { @@ -66,9 +73,12 @@ fn hold(path: &Path, resource: &Arc, head: Result, open: impl Fn(&Path) -> bool) { @@ -82,8 +92,8 @@ fn trim_kept(heads: &mut Vec, open: impl Fn(&Path) -> bool) { } /// The head the scanned body at `path` was last read with; `None` for any other document. -pub(crate) fn head_of(path: &Path) -> Option { - let heads = heads(); +pub(crate) fn head_of(drawable: &super::DrawableSession, path: &Path) -> Option { + let heads = heads(drawable); let found = heads.iter().rev().find(|k| k.path == path); found.map(|k| Arc::clone(&k.head)) } @@ -104,7 +114,7 @@ pub(in crate::state) fn texture_named<'p>( .flat_map(|s| s.texture_keys.iter().flatten()) .copied() .find(|key| texture_name(gta6, *key).eq_ignore_ascii_case(name))?; - let heads = heads(); + let heads = heads(>a6.drawable); // Only the head read with this very body: another of the same name may embed other pixels. let (path, head) = (heads.iter()) .filter(|k| k.resource == Arc::as_ptr(resource) as usize) @@ -292,9 +302,10 @@ mod tests { #[test] fn a_kept_head_leaves_its_body_editable_and_a_body_read_again_replaces_it() { + let session = super::super::DrawableSession::default(); let path = Path::new("gta6_head_test_again"); let mut opened = drawable("gta6_head_test_again.#dr"); - hold(path, resource(&opened), Ok(head("first"))); + hold(&session, path, resource(&opened), Ok(head("first"))); let DocPayload::Gta6Drawable(r) = &mut opened else { unreachable!("a GTA VI drawable") }; @@ -303,10 +314,11 @@ mod tests { "an edit takes the body as its own" ); let again = drawable("gta6_head_test_again.#dr"); - hold(path, resource(&again), Ok(head("second"))); - let kept = heads().iter().filter(|k| k.path == path).count(); + hold(&session, path, resource(&again), Ok(head("second"))); + let kept = heads(&session).iter().filter(|k| k.path == path).count(); assert_eq!(kept, 1); - let name = head_of(path).and_then(|h| h.as_ref().as_ref().ok().map(|h| h.name.clone())); + let name = + head_of(&session, path).and_then(|h| h.as_ref().as_ref().ok().map(|h| h.name.clone())); assert_eq!(name.as_deref(), Some("second")); } @@ -330,7 +342,9 @@ mod tests { extra_skeletons: Vec::new(), }))); let colours = vec![[0x10, 0x80, 0x30, 0xFF], [0xF0, 0x40, 0x20, 0xFF]]; + let gta6 = crate::state::gta6::session::Gta6Session::default(); hold( + >a6.drawable, path, resource(&opened), Ok(DrawableHead { @@ -346,7 +360,6 @@ mod tests { unlisted_vertex_buffers: 0, }), ); - let gta6 = crate::state::gta6::session::Gta6Session::default(); let found = texture_named(>a6, &opened, None, &texture_name(>a6, PAL_KEY)) .expect("palette key resolves to a 1D RGBA8 texture"); let Texture::Owned(grc) = found else { diff --git a/src/state/gta6/drawable/gta6_selected.rs b/src/state/gta6/drawable/gta6_selected.rs index 01e543e55..48f6a6826 100644 --- a/src/state/gta6/drawable/gta6_selected.rs +++ b/src/state/gta6/drawable/gta6_selected.rs @@ -62,7 +62,7 @@ pub(crate) fn summary(name: &str, selection: SelectionKey) -> Option { /// What `doc`, a scanned GTA VI body, states of the part `selection` names; `None` where it names /// none, or one the body does not hold. pub(crate) fn selected_rows( - anim: &crate::state::gta6::anim::AnimSession, + gta6: &crate::state::gta6::session::Gta6Session, doc: &Document, selection: SelectionKey, ) -> Option { @@ -70,11 +70,12 @@ pub(crate) fn selected_rows( return None; }; if let Some(bone) = bone_of(selection) { - let skeleton = crate::state::rpf9_scan::scanned_skeleton(doc.path.as_deref()?).ok()?; + let skeleton = + crate::state::rpf9_scan::scanned_skeleton(>a6.rpf9, doc.path.as_deref()?).ok()?; return bone_rows(&skeleton, bone); } if let Some((_, bone)) = crate::state::gta6_entry_skeletons::entry_bone_of(selection) { - let skeleton = crate::state::gta6_entry_skeletons::shown(anim, doc, Some(selection))?; + let skeleton = crate::state::gta6_entry_skeletons::shown(gta6, doc, Some(selection))?; return bone_rows(&skeleton, bone); } let part = part_of(selection)?; diff --git a/src/state/gta6/drawable/gta6_shaders/global_textures.rs b/src/state/gta6/drawable/gta6_shaders/global_textures.rs index c148532ad..4309ccb31 100644 --- a/src/state/gta6/drawable/gta6_shaders/global_textures.rs +++ b/src/state/gta6/drawable/gta6_shaders/global_textures.rs @@ -24,13 +24,23 @@ const BODY_LIMIT: u64 = 1 << 30; pub(crate) type Slices = Arc; type Slot = Arc>>>; +type GlobalTexturesMap = BTreeMap<(PathBuf, u32), Slot>; -static READ: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::gta6::drawable) struct GlobalTexturesCache(Arc>); /// The texture whose name hashes to `name` in the archive under `root`: `Err` while a worker reads /// it, which the first ask starts; `None` where no dictionary of the archive holds it. -pub(crate) fn under(root: &Path, name: u32) -> Result, ()> { - let mut read = READ.lock().unwrap_or_else(|p| p.into_inner()); +pub(crate) fn under( + drawable: &crate::state::gta6::drawable::DrawableSession, + root: &Path, + name: u32, +) -> Result, ()> { + let mut read = drawable + .global_textures + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()); let key = (root.to_path_buf(), name); if let Some(slot) = read.get(&key) { return slot @@ -69,7 +79,7 @@ pub(crate) fn under(root: &Path, name: u32) -> Result, ()> { pub(crate) fn worn(state: &crate::state::AppState, name: u32) -> Result, ()> { let doc = state.active_document().ok_or(())?; match crate::state::gta6_texture_index::root_of(state, doc) { - Some(root) => under(&root, name), + Some(root) => under(&state.gta6.drawable, &root, name), None => Ok(None), } } diff --git a/src/state/gta6/drawable/gta6_shaders/layer_index.rs b/src/state/gta6/drawable/gta6_shaders/layer_index.rs index db5875596..44f3bd8d7 100644 --- a/src/state/gta6/drawable/gta6_shaders/layer_index.rs +++ b/src/state/gta6/drawable/gta6_shaders/layer_index.rs @@ -384,12 +384,12 @@ pub(crate) fn worn_as( let doc = state.active_document()?; let root = crate::state::gta6_texture_index::root_of(state, doc)?; let index = match start { - true => under(&root)?, - false => held(&root)?, + true => under(&state.gta6.drawable, &root)?, + false => held(&state.gta6.drawable, &root)?, }; // A ped's part wears the material its kit names, which no weapon definition states. let kit = || { - let worn = crate::state::gta6_shaders::ped_assets::dressed(name)?; + let worn = crate::state::gta6_shaders::ped_assets::dressed(&state.gta6.drawable, name)?; index.layered.materials.get(&worn.layered) }; let material = index.material_of(name).or_else(kit)?.clone(); @@ -415,12 +415,21 @@ pub(in crate::state) fn tile_keys( } type Slot = Arc>>>; +type LayerIndexMap = BTreeMap; -static BUILT: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::gta6::drawable) struct LayerIndexCache(Arc>); /// The index of the install or folder at `root` where one is read. -fn held(root: &Path) -> Option> { - let built = BUILT.lock().unwrap_or_else(|p| p.into_inner()); +fn held( + drawable: &crate::state::gta6::drawable::DrawableSession, + root: &Path, +) -> Option> { + let built = drawable + .layer_index + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()); let slot = Arc::clone(built.get(root)?); let index = slot.lock().unwrap_or_else(|p| p.into_inner()).clone(); index @@ -430,8 +439,15 @@ fn held(root: &Path) -> Option> { /// ask starts. // ⚠ Where the index is kept is found here, on the caller's thread: a test's configuration folder // is its own thread's. -pub(crate) fn under(root: &Path) -> Option> { - let mut built = BUILT.lock().unwrap_or_else(|p| p.into_inner()); +pub(crate) fn under( + drawable: &crate::state::gta6::drawable::DrawableSession, + root: &Path, +) -> Option> { + let mut built = drawable + .layer_index + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()); if let Some(slot) = built.get(root) { return slot.lock().unwrap_or_else(|p| p.into_inner()).clone(); } diff --git a/src/state/gta6/drawable/gta6_shaders/mod.rs b/src/state/gta6/drawable/gta6_shaders/mod.rs index 966a7f4c7..8a5cfec01 100644 --- a/src/state/gta6/drawable/gta6_shaders/mod.rs +++ b/src/state/gta6/drawable/gta6_shaders/mod.rs @@ -25,6 +25,7 @@ use or_io::gta6::hash::name_hash32; use or_job::{Cancel, Progress}; use or_renderer::game_shaders::pack::GamePack; +use super::DrawableSession; use crate::state::jobs::{JobKind, JobLog, Outcome as Ended, RunningJob, Then}; /// The bytes one effect container is read to while an install's archive is searched for them. @@ -154,11 +155,11 @@ pub(crate) enum Status { }, } -// ponytail: one session's translations for the whole app, as the effects database is. -static SHADERS: Mutex> = Mutex::new(None); +#[derive(Clone, Default)] +pub(in crate::state::gta6::drawable) struct ShadersCache(Arc>>); -fn with(f: impl FnOnce(&mut Shaders) -> T) -> T { - let mut held = SHADERS.lock().unwrap_or_else(|p| p.into_inner()); +fn with(drawable: &DrawableSession, f: impl FnOnce(&mut Shaders) -> T) -> T { + let mut held = drawable.shaders.0.lock().unwrap_or_else(|p| p.into_inner()); f(held.get_or_insert_with(Shaders::default)) } @@ -169,6 +170,7 @@ fn stopped() -> String { /// Keep the `SGD5` container `bytes`, read at `base` of `archive`, as a place programs are read from. // ponytail: opens the container a second time beside the effects read; one open when it shows. pub(in crate::state) fn add_source( + drawable: &DrawableSession, archive: &Path, base: u64, bytes: &[u8], @@ -183,7 +185,7 @@ pub(in crate::state) fn add_source( file, whole: true, }; - with(|s| keep(s, vec![Arc::new(source)])); + with(drawable, |s| keep(s, vec![Arc::new(source)])); } fn keep(s: &mut Shaders, sources: Vec>) { @@ -206,8 +208,13 @@ fn keep(s: &mut Shaders, sources: Vec>) { /// for others is stopped. `install` is the GTA VI install's `shaders.rpf`, asked for when a job /// starts and searched once a session where no container read holds one. `hardware` says whether /// the drawing adapter is hardware rather than software. -pub(crate) fn request(worn: &[Worn], install: impl FnOnce() -> Option, hardware: bool) { - with(|s| { +pub(crate) fn request( + drawable: &DrawableSession, + worn: &[Worn], + install: impl FnOnce() -> Option, + hardware: bool, +) { + with(drawable, |s| { if let Some((input, wanted)) = asked(s, worn, install, hardware) { s.running = Some(Running::start(input, wanted)); } @@ -836,8 +843,8 @@ fn search( /// Take what a job that ended found into the session's translations, build their pack, and say /// in the job list how it went. -pub(in crate::state) fn poll(jobs: &mut JobLog) { - let said = with(|s| { +pub(in crate::state) fn poll(drawable: &DrawableSession, jobs: &mut JobLog) { + let said = with(drawable, |s| { let result = (s.running.as_ref()?.ended.lock()) .unwrap_or_else(|p| p.into_inner()) .take()?; @@ -957,15 +964,15 @@ fn pack_of(s: &Shaders) -> GamePack { } /// The pack of what is translated so far and its number; `None` before a job has ended. -pub(crate) fn pack() -> Option<(u64, Arc)> { - with(|s| s.pack.clone()) +pub(crate) fn pack(drawable: &DrawableSession) -> Option<(u64, Arc)> { + with(drawable, |s| s.pack.clone()) } /// The pass that draws a geometry whose vertex data is `vertex_data` with the effect whose name /// hashes to `hash`, or why the renderer cannot be handed one; `None` before a job has /// translated it. -pub(crate) fn shading(hash: u32, vertex_data: &[u8]) -> Shading { - with(|s| shading_in(s, hash, vertex_data)) +pub(crate) fn shading(drawable: &DrawableSession, hash: u32, vertex_data: &[u8]) -> Shading { + with(drawable, |s| shading_in(s, hash, vertex_data)) } /// [`shading`], of the session `s`. @@ -981,13 +988,13 @@ fn picked(s: &Shaders, hash: u32, streams: u32) -> Shading { } /// Whether a translation job runs. -pub(crate) fn running() -> bool { - with(|s| s.running.is_some()) +pub(crate) fn running(drawable: &DrawableSession) -> bool { + with(drawable, |s| s.running.is_some()) } /// Where the effects `hashes` name stand. -pub(crate) fn status(hashes: &[u32]) -> Status { - with(|s| status_of(s, hashes)) +pub(crate) fn status(drawable: &DrawableSession, hashes: &[u32]) -> Status { + with(drawable, |s| status_of(s, hashes)) } fn status_of(s: &Shaders, hashes: &[u32]) -> Status { @@ -1014,10 +1021,12 @@ fn status_of(s: &Shaders, hashes: &[u32]) -> Status { } /// The translation while it runs, as the job list draws it. -pub(in crate::state) fn job() -> Option { - with(|s| { +pub(in crate::state) fn job(drawable: &DrawableSession) -> Option { + with(drawable, |s| { let running = s.running.as_ref()?; - let ended = (running.ended.lock()) + let ended = running + .ended + .lock() .unwrap_or_else(|p| p.into_inner()) .is_some(); (!ended).then(|| RunningJob { @@ -1031,12 +1040,8 @@ pub(in crate::state) fn job() -> Option { } /// Ask the translation to stop; its end is said by [`poll`]. -pub(in crate::state) fn stop() { - with(|s| { - if let Some(running) = &s.running { - running.cancel.set(); - } - }); +pub(in crate::state) fn stop(drawable: &DrawableSession) { + with(drawable, |s| s.running.iter().for_each(|r| r.cancel.set())); } impl crate::state::AppState { diff --git a/src/state/gta6/drawable/gta6_shaders/ped_assets/mod.rs b/src/state/gta6/drawable/gta6_shaders/ped_assets/mod.rs index b5fdb6ae8..4bc96512f 100644 --- a/src/state/gta6/drawable/gta6_shaders/ped_assets/mod.rs +++ b/src/state/gta6/drawable/gta6_shaders/ped_assets/mod.rs @@ -261,13 +261,26 @@ fn build(root: &Path) -> Index { } type Slot = Arc>>>; +type BuiltMap = BTreeMap; +type DressedMap = Option>>; -static BUILT: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::gta6::drawable) struct PedAssetsCache { + built: Arc>, + dressed: Arc>, +} /// The index of the install or folder at `root`: `None` while a worker reads it, which the first /// ask starts. -pub(crate) fn under(root: &Path) -> Option> { - let mut built = BUILT.lock().unwrap_or_else(|p| p.into_inner()); +pub(crate) fn under( + drawable: &crate::state::gta6::drawable::DrawableSession, + root: &Path, +) -> Option> { + let mut built = drawable + .ped_assets + .built + .lock() + .unwrap_or_else(|p| p.into_inner()); if let Some(slot) = built.get(root) { return slot.lock().unwrap_or_else(|p| p.into_inner()).clone(); } @@ -289,24 +302,40 @@ pub(crate) fn joined(index: &Index, name: &str) -> Option { ped_assets::join(word, &index.catalogues, &index.lists) } -/// The textures of each drawable a run shows as a ped's part, by the drawable's word: what the -/// character that wears it states, which the join by a drawable's name alone cannot tell. -static DRESSED: Mutex>>> = Mutex::new(None); - /// Have the drawables shown from now on wear `parts`, each by its word, or what they join to. -pub(crate) fn dress(parts: Option>) { - *DRESSED.lock().unwrap_or_else(|p| p.into_inner()) = parts.map(Arc::new); +pub(crate) fn dress( + drawable: &crate::state::gta6::drawable::DrawableSession, + parts: Option>, +) { + *drawable + .ped_assets + .dressed + .lock() + .unwrap_or_else(|p| p.into_inner()) = parts.map(Arc::new); } /// What [`dress`] gave the drawable named `name`. -pub(crate) fn dressed(name: &str) -> Option { - let dressed = DRESSED.lock().unwrap_or_else(|p| p.into_inner()).clone(); +pub(crate) fn dressed( + drawable: &crate::state::gta6::drawable::DrawableSession, + name: &str, +) -> Option { + let dressed = drawable + .ped_assets + .dressed + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone(); dressed?.get(&ped_assets::drawable_word(name)).cloned() } /// The key of every texture [`dress`] gave a drawable. -pub(crate) fn dressed_keys() -> Vec { - let dressed = DRESSED.lock().unwrap_or_else(|p| p.into_inner()).clone(); +pub(crate) fn dressed_keys(drawable: &crate::state::gta6::drawable::DrawableSession) -> Vec { + let dressed = drawable + .ped_assets + .dressed + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone(); let parts = dressed.iter().flat_map(|parts| parts.values()); parts .flat_map(|t| { @@ -320,12 +349,12 @@ pub(crate) fn dressed_keys() -> Vec { /// What the GTA VI drawable named `name` the active document shows joins to; `None` where the /// document is in no folder. The first ask has a worker read the index of its install. pub(crate) fn worn(state: &crate::state::AppState, name: &str) -> Option { - if let Some(worn) = dressed(name) { + if let Some(worn) = dressed(&state.gta6.drawable, name) { return Some(Worn::Joined(Some(worn))); } let doc = state.active_document()?; let root = crate::state::gta6_texture_index::root_of(state, doc)?; - Some(match under(&root) { + Some(match under(&state.gta6.drawable, &root) { Some(index) => Worn::Joined(joined(&index, name)), None => Worn::Reading, }) diff --git a/src/state/gta6/drawable/gta6_shaders/ped_assets/skin_tones.rs b/src/state/gta6/drawable/gta6_shaders/ped_assets/skin_tones.rs index 2b911f77b..07a13fed5 100644 --- a/src/state/gta6/drawable/gta6_shaders/ped_assets/skin_tones.rs +++ b/src/state/gta6/drawable/gta6_shaders/ped_assets/skin_tones.rs @@ -173,13 +173,22 @@ fn read(root: &Path) -> Option { } type Slot = Arc>>>>; +type SkinTonesMap = BTreeMap; -static READ: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::gta6::drawable) struct SkinTonesCache(Arc>); /// The skin tones of the install at `root`: `Err` while a worker reads them, which the first ask /// starts; `None` where no archive holds them. -fn under(root: &Path) -> Result>, ()> { - let mut read_ = READ.lock().unwrap_or_else(|p| p.into_inner()); +fn under( + drawable: &crate::state::gta6::drawable::DrawableSession, + root: &Path, +) -> Result>, ()> { + let mut read_ = drawable + .skin_tones + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()); if let Some(slot) = read_.get(root) { return slot .lock() @@ -211,7 +220,7 @@ pub(crate) fn worn(state: &crate::state::AppState) -> Result under(&root), + Some(root) => under(&state.gta6.drawable, &root), None => Ok(None), } } diff --git a/src/state/gta6/drawable/gta6_shaders/terrain_tile.rs b/src/state/gta6/drawable/gta6_shaders/terrain_tile.rs index 19d63f1f7..937ec892a 100644 --- a/src/state/gta6/drawable/gta6_shaders/terrain_tile.rs +++ b/src/state/gta6/drawable/gta6_shaders/terrain_tile.rs @@ -41,23 +41,21 @@ impl Tile { type Tiles = Arc>; type Slot = Arc>>; +type TerrainTilesMap = BTreeMap; -/// The tiles of each archive of images asked for, by where it was asked from: `None` in a slot -/// while a worker reads it. -static READ: Mutex> = Mutex::new(BTreeMap::new()); - -/// How many reads of an archive of images have ended, which a drawable drawn without its tile is -/// prepared again by. -static ENDED: AtomicU64 = AtomicU64::new(0); - -/// The tiles said found, so each is logged once. -static SAID: Mutex> = Mutex::new(BTreeSet::new()); +/// Per-instance terrain tile caches, read completion counter, and logged-tiles set. +#[derive(Clone, Default)] +pub(in crate::state::gta6::drawable) struct TerrainTileCache { + read: Arc>, + ended: Arc, + said: Arc>>, +} const STACK: usize = 8 << 20; /// How many reads of a tile's archive of images have ended. -pub(crate) fn reads_ended() -> u64 { - ENDED.load(Ordering::Acquire) +pub(crate) fn reads_ended(drawable: &crate::state::gta6::drawable::DrawableSession) -> u64 { + drawable.terrain_tile.ended.load(Ordering::Acquire) } /// Where a tile's bodies are read from. @@ -81,9 +79,16 @@ pub(crate) fn worn(state: &AppState) -> Option> { crate::state::gta6_resource::drawable_of(resource, state.selection.selected(doc.id))?; let (tile, cell) = terrain_tile::cell_of(&drawable.name)?; let (key, source) = source_of(state, doc, tile)?; - let tiles = tiles_of(key, source)?; + let tiles = tiles_of(&state.gta6, key, source)?; let (bounds, material) = tiles.iter().find(|(b, _)| b.name == tile)?; - let said = (SAID.lock().unwrap_or_else(|p| p.into_inner())).insert(tile.to_owned()); + let said = (state + .gta6 + .drawable + .terrain_tile + .said + .lock() + .unwrap_or_else(|p| p.into_inner())) + .insert(tile.to_owned()); if said { tracing::info!( tile, @@ -174,20 +179,31 @@ fn nested_around( /// The tiles `source` holds, kept by `key`: `None` while a worker reads them, which the first /// ask starts. -fn tiles_of(key: String, source: Source) -> Option { - let mut read = READ.lock().unwrap_or_else(|p| p.into_inner()); +fn tiles_of( + gta6: &crate::state::gta6::session::Gta6Session, + key: String, + source: Source, +) -> Option { + let mut read = gta6 + .drawable + .terrain_tile + .read + .lock() + .unwrap_or_else(|p| p.into_inner()); if let Some(slot) = read.get(&key) { return slot.lock().unwrap_or_else(|p| p.into_inner()).clone(); } let slot = Slot::default(); read.insert(key.clone(), Arc::clone(&slot)); drop(read); + let ended = Arc::clone(>a6.drawable.terrain_tile.ended); + let rpf9 = gta6.rpf9.clone(); static POOL: OnceLock = OnceLock::new(); let pool = POOL.get_or_init(|| or_job::Pool::new(2, STACK, || {})); let started = pool.run(move || { let tiles = Arc::new(match source { Source::Tree(outer, beside) => read_tiles(&outer, &beside), - Source::Scanned(archive) => scanned_tiles(&archive, &key), + Source::Scanned(archive) => scanned_tiles(&rpf9, &archive, &key), }); tracing::info!( key, @@ -195,7 +211,7 @@ fn tiles_of(key: String, source: Source) -> Option { "read the terrain tiles of an archive of images" ); *slot.lock().unwrap_or_else(|p| p.into_inner()) = Some(tiles); - ENDED.fetch_add(1, Ordering::Release); + ended.fetch_add(1, Ordering::Release); }); if let Err(why) = started { tracing::warn!(%why, "no worker reads a terrain tile's bodies"); @@ -205,10 +221,14 @@ fn tiles_of(key: String, source: Source) -> Option { /// The tiles beside the tile named in `key` (after its `|`) of the archive file `archive`, whose /// table the app's keys open and whose rows the app's names name. -fn scanned_tiles(archive: &Path, key: &str) -> Vec<(TileBounds, TileMaterial)> { +fn scanned_tiles( + rpf9: &crate::state::rpf::Rpf9Session, + archive: &Path, + key: &str, +) -> Vec<(TileBounds, TileMaterial)> { let tile = key.rsplit('|').next().unwrap_or_default(); let read = || -> Result, String> { - let keys = crate::state::rpf9_scan::rpf9_table::keys()?; + let keys = crate::state::rpf9_scan::rpf9_table::keys(rpf9)?; let mut file = File::open(archive).map_err(|e| e.to_string())?; let top = Gta6Mount::open_root(&mut file, &keys).map_err(|e| e.to_string())?; let names = crate::state::rpf9_scan::rpf9_table::resolver(); diff --git a/src/state/gta6/drawable/gta6_shaders/timecycle.rs b/src/state/gta6/drawable/gta6_shaders/timecycle.rs index 6dd4c0f43..642e82300 100644 --- a/src/state/gta6/drawable/gta6_shaders/timecycle.rs +++ b/src/state/gta6/drawable/gta6_shaders/timecycle.rs @@ -26,8 +26,8 @@ struct Held { read: Vec<(PathBuf, Read)>, } -// ponytail: read again each session, about a second; kept beside the effects if it shows. -static HELD: Mutex> = Mutex::new(None); +#[derive(Clone, Default)] +pub(in crate::state::gta6::drawable) struct TimecycleCache(Arc>>); /// The install's folder where one is set, else the folder above the active document that holds /// the archive. @@ -65,7 +65,13 @@ fn read(archive: &Path) -> Result { /// them; `None` before, and where no install is found or it states none. pub(crate) fn timecycle(state: &AppState) -> Option> { let document = state.active_document().and_then(|d| d.path.clone()); - let mut held = HELD.lock().unwrap_or_else(|p| p.into_inner()); + let mut held = state + .gta6 + .drawable + .timecycle + .0 + .lock() + .unwrap_or_else(|p| p.into_inner()); let held = held.get_or_insert_with(Held::default); if held.asked.as_ref().map(|(of, _)| of) != Some(&document) { let archive = archive_of(state, document.as_deref()); diff --git a/src/state/gta6/drawable/gta6_weapon_parts.rs b/src/state/gta6/drawable/gta6_weapon_parts.rs index d721d8f00..5baf259be 100644 --- a/src/state/gta6/drawable/gta6_weapon_parts.rs +++ b/src/state/gta6/drawable/gta6_weapon_parts.rs @@ -36,33 +36,38 @@ pub(crate) fn state_parts(table: std::collections::HashMap>) let _ = STATED.set(table); } -static PARTS: Mutex>>> = Mutex::new(BTreeMap::new()); +type PartsMap = BTreeMap>>; -fn held() -> MutexGuard<'static, BTreeMap>>> { - PARTS +#[derive(Clone, Default)] +pub(super) struct WeaponPartsCache(Arc>); + +fn held(drawable: &super::DrawableSession) -> MutexGuard<'_, PartsMap> { + drawable + .weapon_parts + .0 .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// The parts kept for the weapon the scanned body at `path` is; `None` for any other body. -pub(crate) fn of(path: &Path) -> Option>> { - held().get(path).cloned() +pub(crate) fn of(drawable: &super::DrawableSession, path: &Path) -> Option>> { + held(drawable).get(path).cloned() } /// Read and keep the parts of `read`, the body at `path` of `archive`, where its skeleton offers a /// point and the archive's names are kept; a body opened again keeps what this read finds. pub(in crate::state) fn keep( - install: &crate::state::gta6::install::InstallSession, + gta6: &crate::state::gta6::session::Gta6Session, path: &Path, archive: &Path, read: &Resource, ) { - let parts = crate::state::rpf9_scan::scanned_skeleton(path) + let parts = crate::state::rpf9_scan::scanned_skeleton(>a6.rpf9, path) .ok() .zip(crate::state::gta6_resource::drawable_of(read, None)) .filter(|(skeleton, _)| !points(skeleton, Mat4::IDENTITY).is_empty()) .map(|(skeleton, drawable)| { - let labels = crate::state::gta6_names::labels(install, archive); + let labels = crate::state::gta6_names::labels(>a6.install, archive); let Ok(file) = File::open(archive) else { return Vec::new(); }; @@ -75,8 +80,8 @@ pub(in crate::state) fn keep( }) .unwrap_or_default(); match parts.is_empty() { - true => held().remove(path), - false => held().insert(path.to_path_buf(), Arc::new(parts)), + true => held(>a6.drawable).remove(path), + false => held(>a6.drawable).insert(path.to_path_buf(), Arc::new(parts)), }; } diff --git a/src/state/gta6/drawable/mod.rs b/src/state/gta6/drawable/mod.rs index dec2f2eb5..590a73981 100644 --- a/src/state/gta6/drawable/mod.rs +++ b/src/state/gta6/drawable/mod.rs @@ -14,3 +14,20 @@ pub(crate) mod gta6_selected; pub(crate) mod gta6_shaders; pub(crate) mod gta6_summaries; pub(crate) mod gta6_weapon_parts; + +/// Per-instance drawable, shader, ped, and terrain caches owned by +/// [`crate::state::gta6::session::Gta6Session`]. +#[derive(Clone, Default)] +pub(crate) struct DrawableSession { + install_read: gta6_effects::InstallReadCache, + heads: gta6_head::HeadsCache, + weapon_parts: gta6_weapon_parts::WeaponPartsCache, + gltf_imports: gta6_gltf_import::GltfImportsCache, + shaders: gta6_shaders::ShadersCache, + global_textures: gta6_shaders::global_textures::GlobalTexturesCache, + layer_index: gta6_shaders::layer_index::LayerIndexCache, + terrain_tile: gta6_shaders::terrain_tile::TerrainTileCache, + timecycle: gta6_shaders::timecycle::TimecycleCache, + ped_assets: gta6_shaders::ped_assets::PedAssetsCache, + skin_tones: gta6_shaders::ped_assets::skin_tones::SkinTonesCache, +} diff --git a/src/state/gta6/install/gta6_first_entry.rs b/src/state/gta6/install/gta6_first_entry.rs index 1190b4889..456dcf49a 100644 --- a/src/state/gta6/install/gta6_first_entry.rs +++ b/src/state/gta6/install/gta6_first_entry.rs @@ -295,7 +295,7 @@ mod tests { Ok(held) ); let path = body_path(&archive, entry, View::Bytes); - let origin = scan_origin(&path).map(|(find, _)| find.offset); + let origin = scan_origin(&state.gta6.rpf9, &path).map(|(find, _)| find.offset); assert_eq!(origin, Some(entry), "its origin is kept for the inspector"); } diff --git a/src/state/gta6/install/gta_vi.rs b/src/state/gta6/install/gta_vi.rs index 3da215568..ca7709ada 100644 --- a/src/state/gta6/install/gta_vi.rs +++ b/src/state/gta6/install/gta_vi.rs @@ -191,11 +191,13 @@ pub(crate) fn read_by_scan(game: Game) -> bool { /// What opening the folder at `root` says when it holds a title that is not opened as an install, /// and whether that is a warning: a title read by scan is browsed as it is meant to be. -pub(in crate::state) fn plain_folder_note(root: &Path) -> Option<(String, bool)> { - folder_note( - root, - crate::state::rpf9_scan::rpf9_table::gta6_keys_held::gta6_keys, - ) +pub(in crate::state) fn plain_folder_note( + rpf9: &crate::state::rpf::Rpf9Session, + root: &Path, +) -> Option<(String, bool)> { + folder_note(root, || { + crate::state::rpf9_scan::rpf9_table::gta6_keys_held::gta6_keys(rpf9) + }) } /// [`plain_folder_note`] with GTA VI's keys as `keys` says they stand. diff --git a/src/state/gta6/modding/batch_export.rs b/src/state/gta6/modding/batch_export.rs index 5567429e6..9716baa02 100644 --- a/src/state/gta6/modding/batch_export.rs +++ b/src/state/gta6/modding/batch_export.rs @@ -252,12 +252,13 @@ impl AppState { dry_run: false, }; let label = tr!("{count} row(s) as files people open", count = rows.len()); + let rpf9 = self.gta6.rpf9.clone(); self.bg.extract_jobs.start( JobKind::Export, label, folder, reads, - move |cancel, progress| exported(&roots, &ask, &cancel, &progress), + move |cancel, progress| exported(&rpf9, &roots, &ask, &cancel, &progress), ); true } @@ -266,6 +267,7 @@ impl AppState { /// The export run on the worker with the keys and names the app holds, as the report the jobs /// list ends with. fn exported( + rpf9: &crate::state::rpf::Rpf9Session, roots: &[Gta6BulkRoot], ask: &Gta6BulkExport, cancel: &Cancel, @@ -273,7 +275,7 @@ fn exported( ) -> Report { use crate::state::rpf9_scan::rpf9_table; let started = Instant::now(); - let run = rpf9_table::keys().and_then(|keys| { + let run = rpf9_table::keys(rpf9).and_then(|keys| { let names = rpf9_table::resolver(); or_cli::gta6_bulk_export(roots, ask, &keys, &names, cancel, progress) }); diff --git a/src/state/gta6/modding/mod_package_changes.rs b/src/state/gta6/modding/mod_package_changes.rs index 766439964..f51a7566d 100644 --- a/src/state/gta6/modding/mod_package_changes.rs +++ b/src/state/gta6/modding/mod_package_changes.rs @@ -48,8 +48,9 @@ impl AppState { install = install.display() )); self.panels.get_or_default_mut::().running = Some(Arc::clone(&job)); + let rpf9 = self.gta6.rpf9.clone(); std::thread::spawn(move || { - let compared = rpf9_table::keys().and_then(|keys| { + let compared = rpf9_table::keys(&rpf9).and_then(|keys| { let resolver = rpf9_table::resolver(); or_cli::gta6_mod_changes( &install, diff --git a/src/state/gta6/modding/mod_package_install/mod.rs b/src/state/gta6/modding/mod_package_install/mod.rs index 171967fa8..a86e3018f 100644 --- a/src/state/gta6/modding/mod_package_install/mod.rs +++ b/src/state/gta6/modding/mod_package_install/mod.rs @@ -112,7 +112,12 @@ fn keep_listed(install: &Path, folders: Vec) -> Result<(), String> { /// Read each package of `folders` and bring the install at `install` to them in that order, telling /// `job` the bytes done; none takes every package out. How it ended. -fn apply(install: &Path, asked: &Apply, job: &Running) -> Result { +fn apply( + rpf9: &crate::state::rpf::Rpf9Session, + install: &Path, + asked: &Apply, + job: &Running, +) -> Result { let folders = &asked.folders; if folders.is_empty() { gta6_mod::uninstall_all(install).map_err(|e| e.to_string())?; @@ -123,7 +128,7 @@ fn apply(install: &Path, asked: &Apply, job: &Running) -> Result restored: asked.restored.len(), }); } - let keys = crate::state::rpf9_scan::rpf9_table::keys()?; + let keys = crate::state::rpf9_scan::rpf9_table::keys(rpf9)?; let mut packages = Vec::with_capacity(folders.len()); for folder in folders { let package = ModPackage::read(folder).map_err(|e| e.to_string())?; @@ -345,9 +350,10 @@ impl AppState { ), }); self.panels.get_or_default_mut::().running = Some(Arc::clone(&job)); + let rpf9 = self.gta6.rpf9.clone(); std::thread::spawn(move || { // A stop that came after the moves began does not stop them, so what ended wins. - let ended = match apply(&asked.install, &asked, &job) { + let ended = match apply(&rpf9, &asked.install, &asked, &job) { Ok(ended) => ended, Err(_) if job.cancel.is_set() => Ended::Stopped, Err(why) => Ended::Failed(why), diff --git a/src/state/gta6/modding/references.rs b/src/state/gta6/modding/references.rs index 919a71444..ea7e43fc9 100644 --- a/src/state/gta6/modding/references.rs +++ b/src/state/gta6/modding/references.rs @@ -88,7 +88,11 @@ impl Gta6Refs { } /// The index of `root`; the read is started where none is held. - fn index(&mut self, root: &Path) -> Result, Answer> { + fn index( + &mut self, + rpf9: &crate::state::rpf::Rpf9Session, + root: &Path, + ) -> Result, Answer> { if self.root.as_deref() != Some(root) { self.root = Some(root.to_path_buf()); self.forget(); @@ -98,7 +102,7 @@ impl Gta6Refs { Some(Stage::Read(Err(why))) => Err(Answer::Cannot(why.clone())), Some(Stage::Reading(_)) => Err(Answer::Looking), None => { - self.stage = Some(Stage::Reading(start(root.to_path_buf()))); + self.stage = Some(Stage::Reading(start(rpf9.clone(), root.to_path_buf()))); Err(Answer::Looking) } } @@ -127,12 +131,12 @@ impl Gta6Refs { } /// The read of the install at `root` on a worker. -fn start(root: PathBuf) -> Reading { +fn start(rpf9: crate::state::rpf::Rpf9Session, root: PathBuf) -> Reading { let (cancel, progress) = (Cancel::new(), Progress::new()); let (tx, receiver) = channel(); let (worker_cancel, worker_progress) = (cancel.clone(), progress.clone()); std::thread::spawn(move || { - let _ = tx.send(read(&root, &worker_cancel, &worker_progress)); + let _ = tx.send(read(&rpf9, &root, &worker_cancel, &worker_progress)); }); Reading { cancel, @@ -149,9 +153,14 @@ fn kept_file(root: &Path) -> Option { } /// Read the install at `root` with the app's keys and names, taking what is kept where it is unchanged, and keep what was read. -fn read(root: &Path, cancel: &Cancel, progress: &Progress) -> Result<(Index, String), String> { +fn read( + rpf9: &crate::state::rpf::Rpf9Session, + root: &Path, + cancel: &Cancel, + progress: &Progress, +) -> Result<(Index, String), String> { progress.now_on(tr!("Loading the keys and the names")); - let keys = crate::state::rpf9_scan::rpf9_table::keys()?; + let keys = crate::state::rpf9_scan::rpf9_table::keys(rpf9)?; let names = crate::state::rpf9_scan::rpf9_table::resolver(); let file = kept_file(root); let kept = match file.as_deref().map(kept::load) { @@ -260,8 +269,9 @@ impl AppState { let Some((root, path)) = self.gta6_place(doc, row) else { return Answer::Cannot(tr!("This file is in no GTA VI install folder").to_string()); }; + let rpf9 = self.gta6.rpf9.clone(); let refs = &mut self.bg.dependencies.gta6; - let index = match refs.index(&root) { + let index = match refs.index(&rpf9, &root) { Ok(index) => index, Err(answer) => return answer, }; diff --git a/src/state/gta6/modding/text_search/mod.rs b/src/state/gta6/modding/text_search/mod.rs index b6868063a..831b02ac5 100644 --- a/src/state/gta6/modding/text_search/mod.rs +++ b/src/state/gta6/modding/text_search/mod.rs @@ -407,10 +407,11 @@ impl AppState { cancel: cancel.clone(), progress: progress.clone(), }); + let rpf9 = self.gta6.rpf9.clone(); std::thread::spawn(move || { // A panic still ends the job, or the view waits on it for ever. let ran = std::panic::catch_unwind(AssertUnwindSafe(|| { - let keys = rpf9_table::keys()?; + let keys = rpf9_table::keys(&rpf9)?; let resolver = rpf9_table::resolver(); let archives = or_title::install::gta6_files::list(&root).archive_paths(); let (most, stop, tick) = (MOST_KEYS, &cancel, &progress); @@ -455,11 +456,13 @@ impl AppState { ciphered: table.ciphered, }; let path = body_path(&line.archive, table.offset, View::Bytes); + let rpf9 = self.gta6.rpf9.clone(); crate::state::rpf_archive_open::tree_open::leave( + &self.gta6.rpf9, &path, &place, table.start, - rpf9_table::keys, + move || rpf9_table::keys(&rpf9), None, ); *lock(&self.gta6.modding.text_search.focus) = Some((path.clone(), key)); @@ -510,9 +513,10 @@ impl AppState { cancel, progress, }); + let rpf9 = self.gta6.rpf9.clone(); std::thread::spawn(move || { let written = std::panic::catch_unwind(AssertUnwindSafe(|| { - let keys = rpf9_table::keys()?; + let keys = rpf9_table::keys(&rpf9)?; Ok::<_, String>(write_edits(&edits, &folder, &keys)) })) .unwrap_or_else(|_| Err(tr!("It stopped on an internal error").to_string())); diff --git a/src/state/gta6/physics/gta6_collision_edit/mod.rs b/src/state/gta6/physics/gta6_collision_edit/mod.rs index a2e311f64..79c8265f5 100644 --- a/src/state/gta6/physics/gta6_collision_edit/mod.rs +++ b/src/state/gta6/physics/gta6_collision_edit/mod.rs @@ -114,7 +114,7 @@ impl AppState { .ok_or_else(|| { tr!("This document has no file, so it holds no GTA VI skeleton.") })?; - crate::state::rpf9_scan::scanned_skeleton(&path)?.bones + crate::state::rpf9_scan::scanned_skeleton(&self.gta6.rpf9, &path)?.bones } _ => Vec::new(), }; diff --git a/src/state/gta6/physics/gta6_navmesh_delete/look.rs b/src/state/gta6/physics/gta6_navmesh_delete/look.rs index b3a908dea..65ae260c3 100644 --- a/src/state/gta6/physics/gta6_navmesh_delete/look.rs +++ b/src/state/gta6/physics/gta6_navmesh_delete/look.rs @@ -79,9 +79,14 @@ fn bodies_of( } /// Look through the table of `archive` on a worker for a navigation row of each of `wanted`. -fn look_through(cache: LooksCache, archive: PathBuf, wanted: Vec) { +fn look_through( + rpf9: crate::state::rpf::Rpf9Session, + cache: LooksCache, + archive: PathBuf, + wanted: Vec, +) { std::thread::spawn(move || { - let keys = rpf9_table::keys(); + let keys = rpf9_table::keys(&rpf9); let keyless = keys.is_err(); let found = bodies_of(&archive, keys, &wanted); let mut held = cache.lock(); @@ -106,7 +111,7 @@ impl AppState { let mut held = cache.lock(); let look = held.entry(archive.to_path_buf()).or_default(); if look.keyless { - look.refresh(rpf9_table::keys().is_ok()); + look.refresh(rpf9_table::keys(&self.gta6.rpf9).is_ok()); } let unknown: Vec = (near.iter()) .filter(|(c, body)| body.is_none() && !look.found.contains_key(c)) @@ -117,7 +122,12 @@ impl AppState { } if !look.running { look.running = true; - look_through(cache.clone(), archive.to_path_buf(), unknown.clone()); + look_through( + self.gta6.rpf9.clone(), + cache.clone(), + archive.to_path_buf(), + unknown.clone(), + ); } let cells: Vec = unknown.iter().map(u32::to_string).collect(); Err(cells.join(", ")) diff --git a/src/state/gta6/session.rs b/src/state/gta6/session.rs index 67d32381e..5e7c28766 100644 --- a/src/state/gta6/session.rs +++ b/src/state/gta6/session.rs @@ -12,11 +12,14 @@ pub(crate) struct Gta6SessionInner { pub(crate) anim: super::anim::AnimSession, pub(crate) audio: super::audio::AudioSession, pub(crate) bodies: super::bodies::BodiesSession, + pub(crate) drawable: super::drawable::DrawableSession, pub(crate) particles: super::particles::ParticlesSession, pub(crate) physics: super::physics::PhysicsSession, pub(crate) textures: super::textures::TexturesSession, pub(crate) modding: super::modding::ModdingSession, pub(crate) install: super::install::InstallSession, + pub(crate) world: super::world::WorldSession, + pub(crate) rpf9: crate::state::rpf::Rpf9Session, pub(crate) ttpf: crate::state::ttpf_document::TtpfSession, pub(crate) script: crate::state::document::gta6_script::ScriptSession, } diff --git a/src/state/gta6/textures/gta6_embedded_edit/mod.rs b/src/state/gta6/textures/gta6_embedded_edit/mod.rs index 93cce89bc..a1ed0a415 100644 --- a/src/state/gta6/textures/gta6_embedded_edit/mod.rs +++ b/src/state/gta6/textures/gta6_embedded_edit/mod.rs @@ -93,13 +93,17 @@ fn bound_key(state: &AppState, doc: DocumentId, name: &str) -> Option<(PathBuf, /// The texture the document shows embedded under `key` in the body at `path`, if it reads, and /// whether it is a 2D texture of one slice; `None` where none is embedded. -fn shown(textures: &TexturesSession, path: &Path, key: u64) -> Option<(Option, bool)> { - match edited(textures, path, key) { +fn shown( + gta6: &crate::state::gta6::session::Gta6Session, + path: &Path, + key: u64, +) -> Option<(Option, bool)> { + match edited(>a6.textures, path, key) { Some(Held::Texture(texture)) => return Some((Some(texture), true)), Some(Held::Removed) => return None, None => {} } - let head = crate::state::gta6_head::head_of(path)?; + let head = crate::state::gta6_head::head_of(>a6.drawable, path)?; let found = ((*head).as_ref().ok()?.textures.iter()) .flatten() .find(|t| t.key == key)?; @@ -109,11 +113,11 @@ fn shown(textures: &TexturesSession, path: &Path, key: u64) -> Option<(Option BTreeSet { - let head = crate::state::gta6_head::head_of(path); +fn shown_keys(gta6: &crate::state::gta6::session::Gta6Session, path: &Path) -> BTreeSet { + let head = crate::state::gta6_head::head_of(>a6.drawable, path); let read = (head.iter()).flat_map(|h| (**h).as_ref().ok().map(|h| &h.textures)); let mut keys: BTreeSet = read.flatten().flatten().map(|t| t.key).collect(); - for (key, held) in edits(textures).get(path).into_iter().flatten() { + for (key, held) in edits(>a6.textures).get(path).into_iter().flatten() { match held { Held::Texture(_) => keys.insert(*key), Held::Removed => keys.remove(key), @@ -126,17 +130,20 @@ fn shown_keys(textures: &TexturesSession, path: &Path) -> BTreeSet { /// of `doc` binds and shows embedded; `None` where it embeds none of that name. fn embedded_key(state: &AppState, doc: DocumentId, name: &str) -> Option<(PathBuf, bool, u64)> { let (path, fragment, key, _) = bound_key(state, doc, name)?; - is_shown(&state.gta6.textures, &path, key).then_some((path, fragment, key)) + is_shown(&state.gta6, &path, key).then_some((path, fragment, key)) } /// Whether [`shown`] finds a texture, without copying its pixels: the preview asks every frame. -fn is_shown(textures: &TexturesSession, path: &Path, key: u64) -> bool { - match edits(textures).get(path).and_then(|held| held.get(&key)) { +fn is_shown(gta6: &crate::state::gta6::session::Gta6Session, path: &Path, key: u64) -> bool { + match edits(>a6.textures) + .get(path) + .and_then(|held| held.get(&key)) + { Some(Held::Texture(_)) => return true, Some(Held::Removed) => return false, None => {} } - crate::state::gta6_head::head_of(path).is_some_and(|head| { + crate::state::gta6_head::head_of(>a6.drawable, path).is_some_and(|head| { (*head) .as_ref() .is_ok_and(|h| h.textures.iter().flatten().any(|t| t.key == key)) @@ -292,7 +299,7 @@ impl AppState { image: &Path, (format, options): (FormatChoice, &TextureBuildOptions), ) -> Result { - let (read, one_slice) = shown(&self.gta6.textures, &path, key) + let (read, one_slice) = shown(&self.gta6, &path, key) .ok_or_else(|| tr!("{name} is not in this dictionary", name = name))?; if !one_slice { return Err(tr!( @@ -329,16 +336,14 @@ impl AppState { ) -> Option> { let (path, _, key, _) = bound_key(self, doc, &texture.name)?; let name = texture.name.clone(); - let others = shown_keys(&self.gta6.textures, &path) - .into_iter() - .any(|k| k != key); + let others = shown_keys(&self.gta6, &path).into_iter().any(|k| k != key); if others { return Some(Err(tr!( "This drawable already embeds another texture, and a dictionary of two was never measured, so {name} is not embedded.", name = name ))); } - let replaced = shown(&self.gta6.textures, &path, key).is_some(); + let replaced = shown(&self.gta6, &path, key).is_some(); let held = match of_grc(key, texture) { Ok(held) => held, Err(why) => return Some(Err(why)), @@ -356,7 +361,7 @@ impl AppState { name: &str, ) -> Option> { let (path, _, key, slots) = bound_key(self, doc, name)?; - if shown(&self.gta6.textures, &path, key).is_none() { + if shown(&self.gta6, &path, key).is_none() { return Some(Err(tr!( "{name} is not carried by this drawable", name = name diff --git a/src/state/gta6/textures/gta6_texture_index.rs b/src/state/gta6/textures/gta6_texture_index.rs index 9ec35c40d..8d10ac9d8 100644 --- a/src/state/gta6/textures/gta6_texture_index.rs +++ b/src/state/gta6/textures/gta6_texture_index.rs @@ -458,7 +458,9 @@ fn unheld_material_keys( .chain(beside) .flat_map(|drawable| &drawable.shaders); let keys = shaders.flat_map(|s| s.texture_keys.iter().flatten().copied()); - let keys = keys.chain(crate::state::gta6_shaders::ped_assets::dressed_keys()); + let keys = keys.chain(crate::state::gta6_shaders::ped_assets::dressed_keys( + &state.gta6.drawable, + )); keys.filter(|key| !held(*key)).collect() } diff --git a/src/state/gta6/world/gta6_map/entity.rs b/src/state/gta6/world/gta6_map/entity.rs index 3a09b44d9..ca4346ffc 100644 --- a/src/state/gta6/world/gta6_map/entity.rs +++ b/src/state/gta6/world/gta6_map/entity.rs @@ -212,6 +212,7 @@ fn related( /// A body's document as an edit leaves it, holding the other side: its tree, its layout and the /// sections of each side, so a swap reads the side it puts in as the Map screen's map again. pub(super) struct MapPart { + world: crate::state::gta6::world::WorldSession, path: PathBuf, tree: MetaInstance, layout: Option, @@ -233,7 +234,12 @@ impl Swap for MapPart { std::mem::swap(&mut meta.layout, &mut self.layout); std::mem::swap(&mut self.other, &mut self.here); meta.after_visual_edit_in_place(); - super::keep(&self.path, &self.here.virtual_section, &self.here.physical); + super::keep( + &self.world, + &self.path, + &self.here.virtual_section, + &self.here.physical, + ); true } } @@ -256,11 +262,11 @@ impl Drop for Job { } } -// ponytail: one edit for the whole app; another started in its place drops it, and says nothing of it. -static JOB: Mutex> = Mutex::new(None); +#[derive(Clone, Default)] +pub(in crate::state::gta6::world) struct EntityJobCache(Arc>>); -fn running_job() -> MutexGuard<'static, Option> { - JOB.lock().unwrap_or_else(|p| p.into_inner()) +fn running_job(world: &crate::state::gta6::world::WorldSession) -> MutexGuard<'_, Option> { + world.entity_job.0.lock().unwrap_or_else(|p| p.into_inner()) } fn has_ended(job: &Job) -> bool { @@ -272,8 +278,8 @@ fn has_ended(job: &Job) -> bool { /// The edit while it reads, as the job list draws it. // ponytail: listed as an archetype search, whose Stop stops it, as the world's fill is. -pub(super) fn job() -> Option { - let held = running_job(); +pub(super) fn job(world: &crate::state::gta6::world::WorldSession) -> Option { + let held = running_job(world); let job = held.as_ref().filter(|job| !has_ended(job))?; Some(RunningJob { kind: JobKind::ArchetypeSearch, @@ -287,8 +293,8 @@ pub(super) fn job() -> Option { }) } -pub(super) fn stop() { - if let Some(job) = running_job().as_ref() { +pub(super) fn stop(world: &crate::state::gta6::world::WorldSession) { + if let Some(job) = running_job(world).as_ref() { job.cancel.set(); } } @@ -492,7 +498,7 @@ impl AppState { let Some(p) = d.path.as_deref().filter(|p| *p != path.as_path()) else { continue; }; - if !matches!(super::opened_map(p), Some(Ok(_))) { + if !matches!(super::opened_map(&self.gta6.world, p), Some(Ok(_))) { continue; } let Some((a, at)) = scanned_body(p) else { @@ -544,14 +550,14 @@ impl AppState { .unwrap_or_else(|_| Err("The map entity edit stopped unexpectedly".into())); *ended.lock().unwrap_or_else(|p| p.into_inner()) = Some(outcome); }); - *running_job() = Some(job); + *running_job(&self.gta6.world) = Some(job); Ok(()) } /// Say in the job list how the edit that ended went, and make it where it was made. pub(super) fn poll_entity_edit(&mut self) { let job = { - let mut held = running_job(); + let mut held = running_job(&self.gta6.world); if !held.as_ref().is_some_and(has_ended) { return; } @@ -658,7 +664,12 @@ impl AppState { &before.physical, self.gta6.install.clone(), )?; - super::keep(path, &before.virtual_section, &before.physical); + super::keep( + &self.gta6.world, + path, + &before.virtual_section, + &before.physical, + ); let (active, workspace) = (self.active_document, self.active_workspace); let doc = self.insert_document(path.to_path_buf(), DocPayload::Meta(meta), None, None); (self.active_document, self.active_workspace) = (active, workspace); @@ -675,6 +686,7 @@ impl AppState { label: String, ) -> Result<(), String> { let mut part = MapPart { + world: self.gta6.world.clone(), path: path.to_path_buf(), tree: after.tree, layout: Some(after.layout), diff --git a/src/state/gta6/world/gta6_map/links/mod.rs b/src/state/gta6/world/gta6_map/links/mod.rs index 41b160079..0bf82ec49 100644 --- a/src/state/gta6/world/gta6_map/links/mod.rs +++ b/src/state/gta6/world/gta6_map/links/mod.rs @@ -20,7 +20,7 @@ use or_io::gta6::map::{Archetype, ArchetypeClass, InstanceList, MapBody, MapData use or_job::{Cancel, Progress}; use or_renderer::LineVertex; -use super::{opened, ScannedMap, Source, BODY_LIMIT, KNOWN}; +use super::{opened, ScannedMap, Source, BODY_LIMIT}; use crate::state::jobs::{JobKind, Outcome, RunningJob, Then}; use crate::state::workbench::dressed::scene::{DressedScene, Geometry, ScenePart}; use crate::state::workbench::PickKind; @@ -35,56 +35,87 @@ pub const MOST_MODELS: usize = 48; const LINK: [f32; 4] = [0.9, 0.55, 0.95, 0.9]; type LinksBy = BTreeMap, String>>; +type InteriorsBy = BTreeMap<(PathBuf, u64), Arc>; +type KeysBy = BTreeMap>>; + +#[derive(Clone)] +pub(in crate::state::gta6::world) struct LinksCache { + links: Arc>, + interiors: Arc>, + keys: Arc>, + /// Names each scene of models read, so the viewport builds its draws again for a new one alone. + reads: Arc, +} + +impl Default for LinksCache { + fn default() -> Self { + Self { + links: Arc::default(), + interiors: Arc::default(), + keys: Arc::default(), + reads: Arc::new(AtomicU64::new(1)), + } + } +} /// What each scanned map body opened links to, or why that was refused, by its path. -// ponytail: one map for the whole app, which no close empties, as the map bodies' is. -fn links() -> MutexGuard<'static, LinksBy> { - static LINKS: Mutex = Mutex::new(BTreeMap::new()); - LINKS.lock().unwrap_or_else(|p| p.into_inner()) +fn links(world: &crate::state::gta6::world::WorldSession) -> MutexGuard<'_, LinksBy> { + world.links.links.lock().unwrap_or_else(|p| p.into_inner()) } /// The interiors read, by the body open or the archive searched that holds them and their name word. -type InteriorsBy = BTreeMap<(PathBuf, u64), Arc>; - -fn interiors() -> MutexGuard<'static, InteriorsBy> { - static INTERIORS: Mutex = Mutex::new(BTreeMap::new()); - INTERIORS.lock().unwrap_or_else(|p| p.into_inner()) +fn interiors(world: &crate::state::gta6::world::WorldSession) -> MutexGuard<'_, InteriorsBy> { + world + .links + .interiors + .lock() + .unwrap_or_else(|p| p.into_inner()) } /// Each drawable dictionary body of an archive whose index is whole, by the key of each of its /// drawables: every body that holds the key. -type KeysBy = BTreeMap>>; - -fn dictionary_keys() -> MutexGuard<'static, KeysBy> { - static KEYS: Mutex = Mutex::new(BTreeMap::new()); - KEYS.lock().unwrap_or_else(|p| p.into_inner()) +fn dictionary_keys(world: &crate::state::gta6::world::WorldSession) -> MutexGuard<'_, KeysBy> { + world.links.keys.lock().unwrap_or_else(|p| p.into_inner()) } /// Keep what the map body at `path`, which the map reader read, links to. -pub(super) fn keep(path: &Path, virtual_section: &[u8], physical: &[u8]) { +pub(super) fn keep( + world: &crate::state::gta6::world::WorldSession, + path: &Path, + virtual_section: &[u8], + physical: &[u8], +) { let Ok((_, read)) = map_links::open(virtual_section, physical) else { return; }; if let Ok(Links::Types(found)) = &read { - keep_interiors(path, found); + keep_interiors(world, path, found); } - links().insert( + links(world).insert( path.to_path_buf(), read.map(Arc::new).map_err(|e| e.to_string()), ); - KNOWN.fetch_add(1, Ordering::Relaxed); + world.map.known.fetch_add(1, Ordering::Relaxed); } /// The interior of name word `word` that the first of `held_by`, bodies open or archives searched, /// lays out. -pub(crate) fn interior_in(held_by: &[&Path], word: u64) -> Option> { - let kept = interiors(); +pub(crate) fn interior_in( + world: &crate::state::gta6::world::WorldSession, + held_by: &[&Path], + word: u64, +) -> Option> { + let kept = interiors(world); (held_by.iter()).find_map(|p| kept.get(&(p.to_path_buf(), word)).cloned()) } /// Keep the interiors a map types body of `held_by`, a body open or an archive searched, links to. -pub(crate) fn keep_interiors(held_by: &Path, found: &[Interior]) { - let mut kept = interiors(); +pub(crate) fn keep_interiors( + world: &crate::state::gta6::world::WorldSession, + held_by: &Path, + found: &[Interior], +) { + let mut kept = interiors(world); for interior in found { kept.insert( (held_by.to_path_buf(), interior.name_word), @@ -94,14 +125,19 @@ pub(crate) fn keep_interiors(held_by: &Path, found: &[Interior]) { } /// Keep the interiors of what a map types body of the archive `archive` links to. -pub(super) fn keep_read_interiors(archive: &Path, read: &Result) { +pub(super) fn keep_read_interiors( + world: &crate::state::gta6::world::WorldSession, + archive: &Path, + read: &Result, +) { if let Ok(Links::Types(found)) = read { - keep_interiors(archive, found); + keep_interiors(world, archive, found); } } /// The interior entity `index`'s archetype lays out, or why its links were refused; `None` for none read. pub(crate) fn interior_of( + gta6: &crate::state::gta6::session::Gta6Session, scanned: &ScannedMap, index: usize, ) -> Option, String>> { @@ -111,7 +147,7 @@ pub(crate) fn interior_of( } let held_by = match source { Source::Open(path) => { - if let Some(Err(why)) = links().get(path) { + if let Some(Err(why)) = links(>a6.world).get(path) { return Some(Err(why.clone())); } path.clone() @@ -120,7 +156,10 @@ pub(crate) fn interior_of( .0 .to_path_buf(), }; - interiors().get(&(held_by, a.name_word)).cloned().map(Ok) + interiors(>a6.world) + .get(&(held_by, a.name_word)) + .cloned() + .map(Ok) } /// An element's level-of-detail parent, and what it names there once that map body is open. @@ -165,8 +204,12 @@ fn parent_at(p: &MapData, pl: Option<&MapLinks>, target: LodTarget) -> Option Shown { - let read = links().get(path).cloned(); +pub(super) fn shown( + world: &crate::state::gta6::world::WorldSession, + path: &Path, + m: &MapData, +) -> Shown { + let read = links(world).get(path).cloned(); let links_of = match read { None => return Shown::default(), Some(Err(why)) => { @@ -180,14 +223,14 @@ pub(super) fn shown(path: &Path, m: &MapData) -> Shown { let Links::Data(l) = &*links_of else { return Shown::default(); }; - let maps: HashMap)> = (opened().iter()) + let maps: HashMap)> = (opened(world).iter()) .filter_map(|(p, b)| match b.as_ref().ok().map(|b| (&**b, b)) { Some((MapBody::Data(d), b)) => Some((d.name, (p.clone(), Arc::clone(b)))), _ => None, }) .collect(); let parent_links: HashMap> = { - let kept = links(); + let kept = links(world); (maps.values()) .filter_map(|(p, _)| Some((p.clone(), Arc::clone(kept.get(p)?.as_ref().ok()?)))) .collect() @@ -249,13 +292,14 @@ pub(crate) fn lod_lines(state: &AppState) -> &[LineVertex] { /// Index every drawable dictionary body at `offsets` of `file`, the archive at `archive`, by its /// drawables' keys, unless that archive's index is whole already; nothing is kept when stopped. pub(super) fn index_dictionaries( + world: &crate::state::gta6::world::WorldSession, archive: &Path, file: &File, offsets: &[u64], (cancel, progress): (&Cancel, &Progress), (done, total): (&mut u64, u64), ) { - if dictionary_keys().contains_key(archive) { + if dictionary_keys(world).contains_key(archive) { return; } let mut keys: HashMap> = HashMap::new(); @@ -269,8 +313,8 @@ pub(super) fn index_dictionaries( keys.entry(code).or_default().push(*offset); } } - dictionary_keys().insert(archive.to_path_buf(), keys); - KNOWN.fetch_add(1, Ordering::Relaxed); + dictionary_keys(world).insert(archive.to_path_buf(), keys); + world.map.known.fetch_add(1, Ordering::Relaxed); } /// The keys of the drawables of the dictionary body at `offset`, none for another body. @@ -315,6 +359,7 @@ fn sole_holder(keys: &HashMap>, names: &HashSet) -> Option, archetypes: &[Option<(Source, Archetype)>], models: &mut [Option], @@ -322,7 +367,7 @@ pub(super) fn dictionary_models( let Some(archive) = archive else { return; }; - let index = dictionary_keys(); + let index = dictionary_keys(world); let Some(keys) = index.get(archive) else { return; }; @@ -522,9 +567,6 @@ impl Drop for ModelsRead { } } -/// Names each scene of models read, so the viewport builds its draws again for a new one alone. -static READS: AtomicU64 = AtomicU64::new(1); - impl AppState { /// Read the models to draw in place again when the map, the entity selected or the radius /// changed since, and take what a read that ended found. @@ -567,7 +609,7 @@ impl AppState { parts.len(), of = of ); - let key = READS.fetch_add(1, Ordering::Relaxed); + let key = self.gta6.world.links.reads.fetch_add(1, Ordering::Relaxed); place.scene = Some(Arc::new(DressedScene::new(key, parts))); (Outcome::Done(Then::Nothing), said) } diff --git a/src/state/gta6/world/gta6_map/links/tests.rs b/src/state/gta6/world/gta6_map/links/tests.rs index 118efcba4..b91faa90a 100644 --- a/src/state/gta6/world/gta6_map/links/tests.rs +++ b/src/state/gta6/world/gta6_map/links/tests.rs @@ -109,11 +109,12 @@ fn a_child_finds_its_parent_in_a_map_body_open_and_a_line_joins_them() { vec![link(None, -1, -1)], vec![vec![[5.0; 3], [6.0, 7.0, 8.0]]], ); - opened().insert(parent_at.clone(), Ok(Arc::new(MapBody::Data(parent)))); - links().insert(child_at.clone(), Ok(Arc::new(child_links))); - links().insert(parent_at.clone(), Ok(Arc::new(parent_links))); + let world = crate::state::gta6::world::WorldSession::default(); + opened(&world).insert(parent_at.clone(), Ok(Arc::new(MapBody::Data(parent)))); + links(&world).insert(child_at.clone(), Ok(Arc::new(child_links))); + links(&world).insert(parent_at.clone(), Ok(Arc::new(parent_links))); - let shown = shown(&child_at, &child); + let shown = shown(&world, &child_at, &child); let found: Vec<_> = (shown.parents.iter()) .map(|p| p.as_ref().and_then(|p| p.found.clone())) .collect(); @@ -140,6 +141,7 @@ fn a_child_finds_its_parent_in_a_map_body_open_and_a_line_joins_them() { assert_eq!(shown.points.len(), 3); let none = super::shown( + &world, Path::new("no-links-test.rpf/0x30.ymap"), &map(1, Vec::new(), Vec::new()), ); diff --git a/src/state/gta6/world/gta6_map/mod.rs b/src/state/gta6/world/gta6_map/mod.rs index 2f31624d5..c311d7618 100644 --- a/src/state/gta6/world/gta6_map/mod.rs +++ b/src/state/gta6/world/gta6_map/mod.rs @@ -28,10 +28,16 @@ const BODY_LIMIT: u64 = 256 << 20; type Opened = BTreeMap, String>>; /// What each scanned map body opened read to, by its path. -// ponytail: one map for the whole app, which no close empties, as the skeletons' is; a map body is small once its lists are counted. -fn opened() -> MutexGuard<'static, Opened> { - static OPENED: Mutex = Mutex::new(BTreeMap::new()); - OPENED.lock().unwrap_or_else(|p| p.into_inner()) +#[derive(Clone, Default)] +pub(in crate::state::gta6::world) struct MapCache { + opened: Arc>, + found: Arc>, + models: Arc>, + known: Arc, +} + +fn opened(world: &super::WorldSession) -> MutexGuard<'_, Opened> { + world.map.opened.lock().unwrap_or_else(|p| p.into_inner()) } /// An archetype a search of a scan found, with the offset of the body that holds it. @@ -44,25 +50,25 @@ pub(crate) struct Found { /// The archetypes found so far, by the archive searched and their name word. type FoundBy = BTreeMap>; -fn found() -> MutexGuard<'static, FoundBy> { - static FOUND: Mutex = Mutex::new(BTreeMap::new()); - FOUND.lock().unwrap_or_else(|p| p.into_inner()) +fn found(world: &super::WorldSession) -> MutexGuard<'_, FoundBy> { + world.map.found.lock().unwrap_or_else(|p| p.into_inner()) } /// The drawable and fragment bodies found so far, by the archive searched and the word their stated /// name hashes to: each one's offset. type ModelsBy = BTreeMap>; -fn models() -> MutexGuard<'static, ModelsBy> { - static MODELS: Mutex = Mutex::new(BTreeMap::new()); - MODELS.lock().unwrap_or_else(|p| p.into_inner()) +fn models(world: &super::WorldSession) -> MutexGuard<'_, ModelsBy> { + world.map.models.lock().unwrap_or_else(|p| p.into_inner()) } -/// Bumped whenever an archetype becomes known, so a scene placed before is placed again. -static KNOWN: AtomicU64 = AtomicU64::new(0); - /// Keep what the map reader reads of the scanned body at `path`, when its root is a map class. -pub(in crate::state) fn keep(path: &Path, virtual_section: &[u8], physical: &[u8]) -> bool { +pub(in crate::state) fn keep( + world: &super::WorldSession, + path: &Path, + virtual_section: &[u8], + physical: &[u8], +) -> bool { let Some(root) = map::root_type(virtual_section) else { return false; }; @@ -72,25 +78,28 @@ pub(in crate::state) fn keep(path: &Path, virtual_section: &[u8], physical: &[u8 let read = map::open(virtual_section, physical).map(Arc::new); let kept = read.is_ok(); if kept { - links::keep(path, virtual_section, physical); + links::keep(world, path, virtual_section, physical); } if matches!(read, Ok(ref body) if matches!(**body, MapBody::Types(_))) { - KNOWN.fetch_add(1, Ordering::Relaxed); + world.map.known.fetch_add(1, Ordering::Relaxed); } - opened().insert(path.to_path_buf(), read.map_err(|e| e.to_string())); + opened(world).insert(path.to_path_buf(), read.map_err(|e| e.to_string())); kept } /// Keep `body` as what the scanned body at `path` read to. #[cfg(test)] -pub(crate) fn keep_read(path: &Path, body: MapBody) { - KNOWN.fetch_add(1, Ordering::Relaxed); - opened().insert(path.to_path_buf(), Ok(Arc::new(body))); +pub(crate) fn keep_read(world: &super::WorldSession, path: &Path, body: MapBody) { + world.map.known.fetch_add(1, Ordering::Relaxed); + opened(world).insert(path.to_path_buf(), Ok(Arc::new(body))); } /// What the map reader read of the scanned body at `path`, or why it refused it; `None` for a body that is no map body. -pub(crate) fn opened_map(path: &Path) -> Option, String>> { - opened().get(path).cloned() +pub(crate) fn opened_map( + world: &super::WorldSession, + path: &Path, +) -> Option, String>> { + opened(world).get(path).cloned() } /// Where an entity's archetype was found. @@ -262,7 +271,11 @@ impl AppState { // ⚠ `each` runs while the search's map is locked, so it must not lock it again. pub(crate) fn each_known_archetype(&self, mut each: impl FnMut(&Archetype)) { for d in &self.documents { - if let Some(Ok(b)) = d.path.as_deref().and_then(opened_map) { + if let Some(Ok(b)) = d + .path + .as_deref() + .and_then(|p| opened_map(&self.gta6.world, p)) + { if let MapBody::Types(t) = &*b { t.archetypes.iter().for_each(&mut each); } @@ -270,7 +283,7 @@ impl AppState { } let archive = (self.scanned_map()).and_then(|s| scanned_body(&s.path)); if let Some((archive, _)) = archive { - if let Some(held) = found().get(archive) { + if let Some(held) = found(&self.gta6.world).get(archive) { held.values().for_each(|f| each(&f.archetype)); } } @@ -280,7 +293,7 @@ impl AppState { pub(in crate::state) fn refresh_scanned_map(&mut self) { let shown = (self.active_document()) .and_then(|d| d.path.clone()) - .and_then(|path| match opened_map(&path) { + .and_then(|path| match opened_map(&self.gta6.world, &path) { Some(Ok(body)) if matches!(*body, MapBody::Data(_)) => Some((path, body)), _ => None, }); @@ -295,7 +308,7 @@ impl AppState { }; let open: Vec<(PathBuf, Arc)> = (self.documents.iter()) .filter_map(|d| d.path.clone()) - .filter_map(|p| match opened_map(&p) { + .filter_map(|p| match opened_map(&self.gta6.world, &p) { Some(Ok(b)) if matches!(*b, MapBody::Types(_)) => Some((p, b)), _ => None, }) @@ -303,7 +316,12 @@ impl AppState { // An edited tree's revision only grows, so the sum changes whenever either does. let (revision, tree) = self.edited_map_tree(&path); let key = ( - KNOWN.load(Ordering::Relaxed).wrapping_add(revision), + self.gta6 + .world + .map + .known + .load(Ordering::Relaxed) + .wrapping_add(revision), open.len(), ); let same = |s: &ScannedMap| s.path == path && s.key == key; @@ -322,10 +340,14 @@ impl AppState { }; let archive = scanned_body(&path).map(|(a, _)| a.to_path_buf()); let from_scan: Vec = (archive.as_ref()) - .and_then(|a| found().get(a).map(|f| f.values().cloned().collect())) + .and_then(|a| { + found(&self.gta6.world) + .get(a) + .map(|f| f.values().cloned().collect()) + }) .unwrap_or_default(); let bodies = (archive.as_ref()) - .and_then(|a| models().get(a).cloned()) + .and_then(|a| models(&self.gta6.world).get(a).cloned()) .unwrap_or_default(); let mut known: Vec<(Source, &Archetype)> = Vec::new(); for (p, b) in &open { @@ -340,8 +362,13 @@ impl AppState { ); let placed = placed(&path.display().to_string(), m, &known, &bodies); let mut models = placed.models; - links::dictionary_models(archive.as_deref(), &placed.archetypes, &mut models); - let links = Arc::new(links::shown(&path, m)); + links::dictionary_models( + &self.gta6.world, + archive.as_deref(), + &placed.archetypes, + &mut models, + ); + let links = Arc::new(links::shown(&self.gta6.world, &path, m)); let work = &mut self.workbench.maps; if work.gta6.scanned.as_ref().is_none_or(|s| s.path != path) { work.selected = None; @@ -437,7 +464,12 @@ impl AppState { dictionaries, }; let offsets = [types, bodies, dictionary_bodies]; - (self.gta6_finders.map_search).push(ArchetypeSearch::start(archive, offsets, looked_for)); + (self.gta6_finders.map_search).push(ArchetypeSearch::start( + self.gta6.world.clone(), + archive, + offsets, + looked_for, + )); Ok(()) } @@ -463,10 +495,10 @@ impl AppState { .iter() .filter_map(ArchetypeSearch::job)) .chain(self.models_in_place_job()) - .chain(crate::state::gta6_world::fill::job()) - .chain(entity::job()) + .chain(crate::state::gta6_world::fill::job(&self.gta6.world)) + .chain(entity::job(&self.gta6.world)) .chain((self.workbench.maps.gta6.world_removal.as_ref()).and_then(WorldRemoval::job)) - .chain(crate::state::gta6_world::worldview::viewer().job()) + .chain(crate::state::gta6_world::worldview::viewer(&self.gta6.world).job()) } /// Ask every search to stop; each says it stopped once its worker sees the stop. @@ -476,8 +508,8 @@ impl AppState { .iter() .for_each(|s| s.cancel.set()); self.stop_models_in_place(); - crate::state::gta6_world::fill::stop(); - entity::stop(); + crate::state::gta6_world::fill::stop(&self.gta6.world); + entity::stop(&self.gta6.world); if let Some(removal) = &self.workbench.maps.gta6.world_removal { removal.stop(); } @@ -527,12 +559,12 @@ impl AppState { self.jobs.record(JobKind::ArchetypeSearch, outcome, said); } // ponytail: a fill of the world is listed as an archetype search, whose Stop stops it; a kind of its own if the two are ever told apart in the list. - if let Some((outcome, said)) = crate::state::gta6_world::fill::ended() { + if let Some((outcome, said)) = crate::state::gta6_world::fill::ended(&self.gta6.world) { self.jobs.record(JobKind::ArchetypeSearch, outcome, said); } self.poll_entity_edit(); self.poll_world_removal(); - let indexed = crate::state::gta6_world::worldview::viewer().ended(); + let indexed = crate::state::gta6_world::worldview::viewer(&self.gta6.world).ended(); if let Some((outcome, said)) = indexed { self.jobs.record(JobKind::WorldIndex, outcome, said); } @@ -616,7 +648,12 @@ impl ArchetypeSearch { /// found, then the drawable and fragment bodies at `offsets[1]` until each model it names or /// those archetypes name is, then indexes the dictionary bodies at `offsets[2]` by their /// drawables' keys where a drawable dictionary is wanted, on a worker. - fn start(archive: PathBuf, offsets: [Vec; 3], mut wanted: Wanted) -> Self { + fn start( + world: super::WorldSession, + archive: PathBuf, + offsets: [Vec; 3], + mut wanted: Wanted, + ) -> Self { let search = Self { doing: tr!( "Looking for GTA VI archetypes in {archive}", @@ -644,7 +681,7 @@ impl ArchetypeSearch { } progress.reached(done, total); done += 1; - for archetype in types_at(&archive, &file, *offset) { + for archetype in types_at(&world, &archive, &file, *offset) { if wanted.archetypes.remove(&archetype.name_word) { wanted.dictionaries |= archetype.drawable_dictionary != 0; if wants_a_model(&archetype) { @@ -656,14 +693,14 @@ impl ArchetypeSearch { offset: *offset, archetype, }; - (found().entry(archive.clone()).or_default()) + (found(&world).entry(archive.clone()).or_default()) .insert(at.archetype.name_word, at); - KNOWN.fetch_add(1, Ordering::Relaxed); + world.map.known.fetch_add(1, Ordering::Relaxed); } } } // A model a search found before is not looked for again. - if let Some(known) = models().get(&archive) { + if let Some(known) = models(&world).get(&archive) { wanted.models.retain(|w| !known.contains_key(w)); } let models = wanted.models.len(); @@ -677,14 +714,15 @@ impl ArchetypeSearch { continue; }; if wanted.models.remove(&word) { - (self::models().entry(archive.clone()).or_default()) + (self::models(&world).entry(archive.clone()).or_default()) .insert(word, *offset); - KNOWN.fetch_add(1, Ordering::Relaxed); + world.map.known.fetch_add(1, Ordering::Relaxed); } } if wanted.dictionaries { let at = (&mut done, total); links::index_dictionaries( + &world, &archive, &file, &offsets[2], @@ -732,7 +770,12 @@ impl Drop for ArchetypeSearch { /// The archetypes of the map types body at `offset` of `file`, the archive at `archive`, none when /// it is another body; its interiors are kept. -fn types_at(archive: &Path, file: &File, offset: u64) -> Vec { +fn types_at( + world: &super::WorldSession, + archive: &Path, + file: &File, + offset: u64, +) -> Vec { let Ok((find, bytes)) = read_rpf9_body(file, offset, BODY_LIMIT) else { return Vec::new(); }; @@ -749,8 +792,8 @@ fn types_at(archive: &Path, file: &File, offset: u64) -> Vec { } match map::links::open(virtual_section, physical) { Ok((MapBody::Types(t), read)) => { - links::keep_read_interiors(archive, &read); - crate::state::gta6_world::keep_searched_types(&t, virtual_section, physical); + links::keep_read_interiors(world, archive, &read); + crate::state::gta6_world::keep_searched_types(world, &t, virtual_section, physical); t.archetypes } _ => Vec::new(), @@ -773,7 +816,7 @@ fn model_at(file: &File, offset: u64) -> Option { pub(crate) mod links; -mod entity; +pub(super) mod entity; mod world_delete; pub(crate) use world_delete::WorldRemoval; diff --git a/src/state/gta6/world/gta6_map/tests.rs b/src/state/gta6/world/gta6_map/tests.rs index 919add4a6..c41d4fd53 100644 --- a/src/state/gta6/world/gta6_map/tests.rs +++ b/src/state/gta6/world/gta6_map/tests.rs @@ -150,7 +150,7 @@ fn an_archetype_a_map_names_is_found_among_the_bodies_of_its_scan_as_a_job() { let mut state = AppState::new(); let scan = scanned(&mut state, archive.clone()); let map_path = body_path(&archive, 0x8000, View::Headerless); - keep_read(&map_path, map()); + keep_read(&state.gta6.world, &map_path, map()); let doc = open(&mut state, map_path); state.active_document = Some(doc); state.refresh_scanned_map(); @@ -224,8 +224,8 @@ fn what_another_screen_asked_for_is_selected_once_its_map_is_shown_and_let_go_wh let _serial = crate::ui::theme::serial(); let dir = tempfile::tempdir().expect("a scratch directory"); let (map_path, lost) = (dir.path().join("0x10.rbm"), dir.path().join("0x30.rbm")); - keep_read(&map_path, map()); let mut state = AppState::new(); + keep_read(&state.gta6.world, &map_path, map()); let before = state.active_workspace; assert_ne!(before, Workspace::Map); diff --git a/src/state/gta6/world/gta6_map/types_edit.rs b/src/state/gta6/world/gta6_map/types_edit.rs index d318be2ea..3278769cb 100644 --- a/src/state/gta6/world/gta6_map/types_edit.rs +++ b/src/state/gta6/world/gta6_map/types_edit.rs @@ -225,7 +225,7 @@ impl AppState { }; } let path = self.active_document()?.path.clone()?; - match super::opened_map(&path) { + match super::opened_map(&self.gta6.world, &path) { Some(Ok(body)) if matches!(*body, MapBody::Types(_)) => Some((path, None)), _ => None, } diff --git a/src/state/gta6/world/gta6_map/world_delete.rs b/src/state/gta6/world/gta6_map/world_delete.rs index 2663c7837..7dc37b24b 100644 --- a/src/state/gta6/world/gta6_map/world_delete.rs +++ b/src/state/gta6/world/gta6_map/world_delete.rs @@ -227,7 +227,7 @@ impl AppState { let Some(p) = d.path.as_deref().filter(|p| *p != path.as_path()) else { continue; }; - if !matches!(super::opened_map(p), Some(Ok(_))) { + if !matches!(super::opened_map(&self.gta6.world, p), Some(Ok(_))) { continue; } let DocPayload::Meta(meta) = &d.payload else { diff --git a/src/state/gta6/world/gta6_map_edit.rs b/src/state/gta6/world/gta6_map_edit.rs index 33322a14f..738085875 100644 --- a/src/state/gta6/world/gta6_map_edit.rs +++ b/src/state/gta6/world/gta6_map_edit.rs @@ -216,7 +216,7 @@ impl AppState { { held.push(archive); } - crate::state::gta6_map::links::interior_in(&held, word) + crate::state::gta6_map::links::interior_in(&self.gta6.world, &held, word) } /// The archetypes entity `index` of the scanned map shown may take, as (word, name). @@ -509,10 +509,14 @@ mod tests { entity(false, OTHER, 0xBBBB_0002), entity(true, 0x55, 0xCCCC_0003), ]; - crate::state::gta6_map::keep_read(&path, MapBody::Data(map(entities.clone()))); + let mut state = AppState::new(); + crate::state::gta6_map::keep_read( + &state.gta6.world, + &path, + MapBody::Data(map(entities.clone())), + ); let mut meta = MetaDocument::empty(); meta.parsed.as_mut().expect("a tree").instance = tree(&entities); - let mut state = AppState::new(); let doc = state.insert_document(path.clone(), DocPayload::Meta(meta), None, None); state.active_document = Some(doc); state.refresh_scanned_map(); @@ -582,7 +586,8 @@ mod tests { let mut e = entity(false, WORD, 0xAAAA_0001); e.lod_dist = 40.0; let read = map(vec![e.clone()]); - crate::state::gta6_map::keep_read(&path, MapBody::Data(read.clone())); + let mut state = AppState::new(); + crate::state::gta6_map::keep_read(&state.gta6.world, &path, MapBody::Data(read.clone())); let mut root = tree(std::slice::from_ref(&e)); let extents = [ ("entitiesExtentsMin", read.entities_extents.min), @@ -595,7 +600,6 @@ mod tests { } let mut meta = MetaDocument::empty(); meta.parsed.as_mut().expect("a tree").instance = root; - let mut state = AppState::new(); let doc = state.insert_document(path.clone(), DocPayload::Meta(meta), None, None); state.active_document = Some(doc); state.refresh_scanned_map(); diff --git a/src/state/gta6/world/gta6_world/fill.rs b/src/state/gta6/world/gta6_world/fill.rs index fdb2b28c9..4f2811357 100644 --- a/src/state/gta6/world/gta6_world/fill.rs +++ b/src/state/gta6/world/gta6_world/fill.rs @@ -621,11 +621,11 @@ impl Drop for Fill { } } -// ponytail: one fill for the whole app, of the archive it was last started for. -static FILL: Mutex> = Mutex::new(None); +#[derive(Clone, Default)] +pub(in crate::state::gta6::world) struct FillCache(Arc>>); -fn held() -> MutexGuard<'static, Option> { - FILL.lock().unwrap_or_else(|p| p.into_inner()) +fn held(world: &crate::state::gta6::world::WorldSession) -> MutexGuard<'_, Option> { + world.fill.0.lock().unwrap_or_else(|p| p.into_inner()) } fn ended_of(fill: &Fill) -> Option { @@ -634,7 +634,12 @@ fn ended_of(fill: &Fill) -> Option { /// Read the world of `archive` on a worker, in place of any fill before; the plan draws what it /// read once it ends. -pub(super) fn start(archive: &Path, offsets: Option>, region: Option) { +pub(super) fn start( + world: crate::state::gta6::world::WorldSession, + archive: &Path, + offsets: Option>, + region: Option, +) { let fill = Fill { archive: archive.to_path_buf(), cancel: Cancel::new(), @@ -648,6 +653,7 @@ pub(super) fn start(archive: &Path, offsets: Option>, region: Option>, region: Option Ended::Stopped, @@ -669,23 +675,25 @@ pub(super) fn start(archive: &Path, offsets: Option>, region: Option bool { - held().as_ref().is_some_and(|fill| ended_of(fill).is_none()) +pub(crate) fn running(world: &crate::state::gta6::world::WorldSession) -> bool { + held(world) + .as_ref() + .is_some_and(|fill| ended_of(fill).is_none()) } -pub(crate) fn stop() { - if let Some(fill) = held().as_ref() { +pub(crate) fn stop(world: &crate::state::gta6::world::WorldSession) { + if let Some(fill) = held(world).as_ref() { fill.cancel.set(); } } /// The fill while it runs, as the job list draws it. -pub(crate) fn job() -> Option { - let held = held(); +pub(crate) fn job(world: &crate::state::gta6::world::WorldSession) -> Option { + let held = held(world); let fill = held.as_ref().filter(|fill| ended_of(fill).is_none())?; Some(RunningJob { kind: JobKind::ArchetypeSearch, @@ -700,8 +708,8 @@ pub(crate) fn job() -> Option { } /// How the fill ended, as the job list says it, once. -pub(crate) fn ended() -> Option<(Outcome, String)> { - let mut held = held(); +pub(crate) fn ended(world: &crate::state::gta6::world::WorldSession) -> Option<(Outcome, String)> { + let mut held = held(world); let fill = held.as_mut().filter(|fill| !fill.said)?; let told = match ended_of(fill)? { Ended::Read { diff --git a/src/state/gta6/world/gta6_world/mod.rs b/src/state/gta6/world/gta6_world/mod.rs index d4348da2a..7724e60de 100644 --- a/src/state/gta6/world/gta6_world/mod.rs +++ b/src/state/gta6/world/gta6_world/mod.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use or_io::gta6::map::lanes::{self, Junction, LaneBody, Link, NodeAddress, PathNode}; use or_io::gta6::map::lights::{self, LightEffect, LightOwner, MapLights, Pose}; @@ -225,22 +225,29 @@ pub struct World { pub area: Option>, } +#[derive(Clone, Default)] +pub(in crate::state::gta6::world) struct WorldCache(Arc>); + /// What is kept, locked: the plan draws from it and the readers add to it. -pub fn world() -> MutexGuard<'static, World> { - static WORLD: LazyLock> = LazyLock::new(Mutex::default); - WORLD.lock().unwrap_or_else(|p| p.into_inner()) +pub(crate) fn world(session: &super::WorldSession) -> MutexGuard<'_, World> { + session.world.0.lock().unwrap_or_else(|p| p.into_inner()) } /// Keep what the world readers read of the scanned body at `path`, after the map reader kept it. -pub(in crate::state) fn keep(path: &Path, virtual_section: &[u8], physical: &[u8]) { +pub(in crate::state) fn keep( + gta6: &crate::state::gta6::session::Gta6Session, + path: &Path, + virtual_section: &[u8], + physical: &[u8], +) { let Some(kind) = map::root_type(virtual_section).and_then(WorldKind::of_root) else { return; }; match kind { WorldKind::MapData | WorldKind::MapTypes => { - let body = crate::state::gta6_map::opened_map(path).and_then(Result::ok); + let body = crate::state::gta6_map::opened_map(>a6.world, path).and_then(Result::ok); let found = lights::open(virtual_section, physical).ok(); - let mut world = world(); + let mut world = world(>a6.world); match (body.as_deref(), &found) { (Some(MapBody::Data(m)), _) => world.index(path, m), (Some(MapBody::Types(t)), Some(found)) => world.keep_archetype_lights(t, found), @@ -253,7 +260,7 @@ pub(in crate::state) fn keep(path: &Path, virtual_section: &[u8], physical: &[u8 } WorldKind::LaneNodes | WorldKind::LaneLinks | WorldKind::LaneJunctions => { if let Ok(body) = lanes::open(virtual_section, physical) { - world().lanes.keep(body); + world(>a6.world).lanes.keep(body); } } WorldKind::EntityGroup => {} @@ -264,13 +271,14 @@ pub(in crate::state) fn keep(path: &Path, virtual_section: &[u8], physical: &[u8 /// sections. // ponytail: the light reader reads the body's tables again after the map reader; hand it the model if a search is slow. pub(in crate::state) fn keep_searched_types( + session: &super::WorldSession, types: &MapTypes, virtual_section: &[u8], physical: &[u8], ) { if let Ok(found) = lights::open(virtual_section, physical) { if !found.effects.is_empty() { - world().keep_archetype_lights(types, &found); + world(session).keep_archetype_lights(types, &found); } } } @@ -441,7 +449,7 @@ impl crate::state::AppState { } _ => None, }); - fill::start(&archive, offsets, region); + fill::start(self.gta6.world.clone(), &archive, offsets, region); Ok(()) } diff --git a/src/state/gta6/world/gta6_world/worldview/edit.rs b/src/state/gta6/world/gta6_world/worldview/edit.rs index d2129ebcc..37b878299 100644 --- a/src/state/gta6/world/gta6_world/worldview/edit.rs +++ b/src/state/gta6/world/gta6_world/worldview/edit.rs @@ -2,7 +2,7 @@ //! map, the next selection draws it where it was moved, and Undo of that document puts it back. use std::path::PathBuf; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; +use std::sync::{Arc, MutexGuard}; use std::time::{Duration, Instant}; use glam::Vec3; @@ -31,10 +31,9 @@ use crate::ui::commands::{self, Action}; /// Where the one lamp of the map's list of props stands, left of the tree. const LIST_AT: [f32; 3] = [-6.0, 20.0, 0.0]; -/// The viewer the session of this test is a shell over, in place of the one of the process. -fn made_up_viewer() -> MutexGuard<'static, Viewer> { - static VIEWER: LazyLock> = LazyLock::new(Mutex::default); - VIEWER.lock().unwrap_or_else(|p| p.into_inner()) +/// The viewer the session of this test is a shell over. +fn made_up_viewer(state: &AppState) -> MutexGuard<'_, Viewer> { + super::viewer(&state.gta6.world) } /// The record the map's body holds of the entity the streamer reads as `e`. @@ -102,22 +101,22 @@ fn click(state: &mut AppState, at: [f32; 3]) -> Picking { /// Give the device the two models the world waits for, as the bridge does. fn models_come(state: &mut AppState) { - until(state, "the models waited for", |_| { - let mut viewer = made_up_viewer(); + until(state, "the models waited for", |state| { + let mut viewer = made_up_viewer(state); let selected = viewer.selected(&mut Vec::new()); selected.is_some_and(|s| s.wanted.len() == 2) }); - let wanted = (made_up_viewer().selected(&mut Vec::new())).expect("a selection"); + let wanted = (made_up_viewer(state).selected(&mut Vec::new())).expect("a selection"); for (_, model) in &wanted.wanted { - let mut viewer = made_up_viewer(); + let mut viewer = made_up_viewer(state); viewer.hold_shape(*model, cube()); viewer.selected(&mut vec![(*model, Some(true))]); } } /// Where the selection the viewer holds draws the instances of the map's first entity. -fn tree_drawn_at() -> Vec<[f32; 3]> { - let selected = made_up_viewer().selected(&mut Vec::new()); +fn tree_drawn_at(state: &AppState) -> Vec<[f32; 3]> { + let selected = made_up_viewer(state).selected(&mut Vec::new()); let instances = selected.iter().flat_map(|s| s.instances.iter()); instances .filter(|i| i.node == (MAP, 0)) @@ -126,8 +125,8 @@ fn tree_drawn_at() -> Vec<[f32; 3]> { } /// The rows the selection the viewer holds draws the map's first entity by, where it draws it once. -fn tree_rows() -> Option<[[f32; 4]; 3]> { - let selected = made_up_viewer().selected(&mut Vec::new()); +fn tree_rows(state: &AppState) -> Option<[[f32; 4]; 3]> { + let selected = made_up_viewer(state).selected(&mut Vec::new()); let instances = selected.iter().flat_map(|s| s.instances.iter()); let mut drawn = instances.filter(|i| i.node == (MAP, 0)).map(|i| i.rows); drawn.next().filter(|_| drawn.next().is_none()) @@ -194,8 +193,14 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ [0.0, 0.0, 1.0, LIST_AT[2]], ]], }); - *made_up_viewer() = Viewer { - root: Some(install.clone()), + let key = WorldKey { + game: Game::GtaVI, + install: install.clone(), + options: Vec::new(), + }; + let mut state = AppState::new(); + *made_up_viewer(&state) = Viewer { + root: Some(install), world: Some(World::of_maps( Arc::clone(&index), Vec3::ZERO, @@ -206,22 +211,15 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ camera: camera(), ..Viewer::default() }; - let key = WorldKey { - game: Game::GtaVI, - install, - options: Vec::new(), - }; - let mut state = AppState::new(); - state - .world - .hold(Box::new(Gta6Session::over(key, made_up_viewer))); + let world = state.gta6.world.clone(); + state.world.hold(Box::new(Gta6Session::over(key, world))); assert!(state.world_is_of_documents()); assert_eq!(state.world_edit_refused(), None, "no project is asked for"); // The two models come to the device, and the tree is selected by a click. models_come(&mut state); - until(&mut state, "the two entities drawn", |_| { - tree_drawn_at() == [TREE_AT] + until(&mut state, "the two entities drawn", |state| { + tree_drawn_at(state) == [TREE_AT] }); // A lamp of a list of props has no record of its own: its move is refused with that reason before any document is opened for it. let Picking::Picked(lamp) = click(&mut state, LIST_AT) else { @@ -292,7 +290,7 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ prop_lists: Vec::new(), grass_lists: Vec::new(), }; - crate::state::gta6_map::keep_read(&path, MapBody::Data(read)); + crate::state::gta6_map::keep_read(&state.gta6.world, &path, MapBody::Data(read)); let mut meta = MetaDocument::empty(); let mut read_tree = tree(&records); // ⚠ A height scale the tree states to more places than what is drawn holds: a move that wrote the drawn scale back would change it. @@ -363,8 +361,8 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ ); // The next selection draws it there and nowhere else, with nothing read again and nothing written. - until(&mut state, "the tree drawn where it was moved", |_| { - tree_drawn_at() == [up] + until(&mut state, "the tree drawn where it was moved", |state| { + tree_drawn_at(state) == [up] }); assert!(matches!(click(&mut state, TREE_AT), Picking::Missed(_))); let Picking::Picked(moved) = click(&mut state, up) else { @@ -373,7 +371,7 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ assert_eq!((moved.name.place, moved.position), (0, Vec3::from(up))); // The world gone, as while its index is built again, and the document changed meanwhile: it stays the one drawn, and nothing is said of it. - made_up_viewer().world = None; + made_up_viewer(&state).world = None; assert_eq!(state.undo(), Some(label.clone())); let said = state.toasts.iter().count(); for _ in 0..2 { @@ -387,7 +385,7 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ state.redo(); // Another world in its place, the viewer counting no restart, as an index built again leaves it: the map is laid over that one. { - let mut viewer = made_up_viewer(); + let mut viewer = made_up_viewer(&state); let maps = vec![made_up.clone()]; viewer.world = Some(World::of_maps(Arc::clone(&index), Vec3::ZERO, 1.0, maps)); (viewer.world_restarts, viewer.sent) = (0, None); @@ -398,7 +396,7 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ until( &mut state, "the tree drawn where it was moved, in the new world", - |_| tree_drawn_at() == [up], + |state| tree_drawn_at(state) == [up], ); let Picking::Picked(_) = click(&mut state, up) else { panic!("the click in the new world picked nothing"); @@ -435,8 +433,8 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ back.picked().expect("still selected").position, Vec3::from(TREE_AT) ); - until(&mut state, "the tree drawn where it stood", |_| { - tree_drawn_at() == [TREE_AT] + until(&mut state, "the tree drawn where it stood", |state| { + tree_drawn_at(state) == [TREE_AT] }); // Its document closed, the map is drawn as the build has it and no document is followed. @@ -445,7 +443,7 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ until( &mut state, "the tree drawn where it was moved again", - |_| tree_drawn_at() == [up], + |state| tree_drawn_at(state) == [up], ); let revision = match state.document(doc).map(|d| &d.payload) { Some(DocPayload::Meta(meta)) => meta.revision(), @@ -460,8 +458,8 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ assert_eq!(tree_position(&state, doc), Value::Vec3(up)); assert_eq!(tree_member(&state, doc, SCALE_Z), stated); let near = |a: f32, b: f32| (a - b).abs() < 1e-4; - until(&mut state, "the tree drawn turned", |_| { - tree_rows().is_some_and(|rows| near(rows[1][0], 1.0) && near(rows[0][1], -1.0)) + until(&mut state, "the tree drawn turned", |state| { + tree_rows(state).is_some_and(|rows| near(rows[1][0], 1.0) && near(rows[0][1], -1.0)) }); // Scaled twice across and three times up: the two scales alone change, and it is drawn so along its turned axes. @@ -470,8 +468,8 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ assert_eq!(tree_member(&state, doc, SCALE_Z), Value::Float(3.0)); assert_eq!(tree_member(&state, doc, ROTATION), stored); assert_eq!(history(&state), Some(format!("Scaled 0x{TREE:016X}"))); - until(&mut state, "the tree drawn scaled", |_| { - tree_rows().is_some_and(|rows| { + until(&mut state, "the tree drawn scaled", |state| { + tree_rows(state).is_some_and(|rows| { near(rows[1][0], 2.0) && near(rows[0][1], -2.0) && near(rows[2][2], 3.0) }) }); @@ -512,7 +510,7 @@ fn what_a_click_selected_is_moved_in_its_maps_document_drawn_where_it_was_moved_ until( &mut state, "the tree drawn as the other document has it", - |_| tree_drawn_at() == [aside], + |state| tree_drawn_at(state) == [aside], ); state.close_document(again); diff --git a/src/state/gta6/world/gta6_world/worldview/grass.rs b/src/state/gta6/world/gta6_world/worldview/grass.rs index c14bc25ce..6180ad01b 100644 --- a/src/state/gta6/world/gta6_world/worldview/grass.rs +++ b/src/state/gta6/world/gta6_world/worldview/grass.rs @@ -3,6 +3,6 @@ impl super::Viewer { /// The height of the ground at `x`, `y` by the install's height map, once it is read: where a camera stands on the grass. pub fn ground_under(&self, x: f32, y: f32) -> Option { - super::water::ground(self.root.as_deref()?)?.ground(x, y) + super::water::ground(&self.ground, self.root.as_deref()?)?.ground(x, y) } } diff --git a/src/state/gta6/world/gta6_world/worldview/index.rs b/src/state/gta6/world/gta6_world/worldview/index.rs index 234248a44..3ee01c8c8 100644 --- a/src/state/gta6/world/gta6_world/worldview/index.rs +++ b/src/state/gta6/world/gta6_world/worldview/index.rs @@ -53,6 +53,9 @@ impl super::Viewer { let Some(root) = self.root.as_deref() else { return (None, None); }; - (super::water::ground(root), super::water::water(root)) + ( + super::water::ground(&self.ground, root), + super::water::water(&self.water, root), + ) } } diff --git a/src/state/gta6/world/gta6_world/worldview/keys.rs b/src/state/gta6/world/gta6_world/worldview/keys.rs index e85540784..e912742fc 100644 --- a/src/state/gta6/world/gta6_world/worldview/keys.rs +++ b/src/state/gta6/world/gta6_world/worldview/keys.rs @@ -6,7 +6,6 @@ use glam::{Vec2, Vec3}; -use super::Viewer; use crate::state::prefs::Game; use crate::state::the_world_screen_has_a_manipulator::{key, moved, SIZE}; use crate::state::AppState; @@ -56,25 +55,14 @@ pub(super) fn showing(install: &std::path::Path) -> AppState { state } -/// Puts the viewer of the process back at rest when the test that drew GTA VI's view ends. -// ⚠ The view opens that viewer on the test's folder, and the index it began stays a running job of the whole process until a frame polls it: every test that counts the jobs would list it. Held after the serial lock, so it goes first. -pub(super) struct AtRest; - -impl Drop for AtRest { - fn drop(&mut self) { - *super::viewer() = Viewer::default(); - } -} - -fn flown() -> Vec3 { - super::viewer().camera.position +fn flown(state: &AppState) -> Vec3 { + super::viewer(&state.gta6.world).camera.position } #[test] fn a_letter_typed_into_a_field_beside_gta_vis_view_is_the_fields_and_flies_the_camera_only_once_no_field_holds_the_keyboard( ) { let _serial = crate::ui::theme::serial(); - let _rest = AtRest; let dir = tempfile::tempdir().expect("a scratch folder"); let mut state = showing(dir.path()); let (ctx, mut text) = (egui::Context::default(), String::new()); @@ -82,7 +70,7 @@ fn a_letter_typed_into_a_field_beside_gta_vis_view_is_the_fields_and_flies_the_c ctx.memory_mut(|memory| memory.request_focus(egui::Id::new(FIELD))); frame(&ctx, &mut state, &mut text, Vec::new()); assert!(ctx.egui_wants_keyboard_input(), "the field holds the keys"); - let stood = flown(); + let stood = flown(&state); // W goes down and stays down for some frames, with the pointer over the view all the while. let w = vec![key(egui::Key::W), egui::Event::Text("w".to_owned())]; @@ -91,7 +79,7 @@ fn a_letter_typed_into_a_field_beside_gta_vis_view_is_the_fields_and_flies_the_c frame(&ctx, &mut state, &mut text, Vec::new()); assert_eq!(text, "w"); assert_eq!( - flown(), + flown(&state), stood, "a letter typed into a field flew the camera" ); @@ -101,5 +89,5 @@ fn a_letter_typed_into_a_field_beside_gta_vis_view_is_the_fields_and_flies_the_c frame(&ctx, &mut state, &mut text, Vec::new()); frame(&ctx, &mut state, &mut text, Vec::new()); assert_eq!(text, "w"); - assert_ne!(flown(), stood); + assert_ne!(flown(&state), stood); } diff --git a/src/state/gta6/world/gta6_world/worldview/mod.rs b/src/state/gta6/world/gta6_world/worldview/mod.rs index f07406043..d1d5fc900 100644 --- a/src/state/gta6/world/gta6_world/worldview/mod.rs +++ b/src/state/gta6/world/gta6_world/worldview/mod.rs @@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet}; use std::fs::File; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use glam::Vec3; use or_job::{Cancel, Progress}; @@ -163,6 +163,9 @@ pub struct Viewer { /// Where the camera stood the frame before, and how many times it jumped from there. last_eye: Option, pub jumps: usize, + sky: sky::SkyCache, + water: water::WaterCache, + ground: water::GroundCache, } impl Default for Viewer { @@ -211,6 +214,9 @@ impl Default for Viewer { stale: [0; 2], last_eye: None, jumps: 0, + sky: sky::SkyCache::default(), + water: water::WaterCache::default(), + ground: water::GroundCache::default(), } } } @@ -237,11 +243,12 @@ impl PickStanding { } } +#[derive(Clone, Default)] +pub(in crate::state::gta6::world) struct ViewerCache(Arc>); + /// The viewer, locked: the screen draws from it and the render bridge asks it what draws. -// ponytail: one viewer for the whole app, of the install it was last opened on. -pub fn viewer() -> MutexGuard<'static, Viewer> { - static VIEWER: LazyLock> = LazyLock::new(Mutex::default); - VIEWER.lock().unwrap_or_else(|p| p.into_inner()) +pub(crate) fn viewer(world: &crate::state::gta6::world::WorldSession) -> MutexGuard<'_, Viewer> { + world.viewer.0.lock().unwrap_or_else(|p| p.into_inner()) } impl Viewer { @@ -256,6 +263,9 @@ impl Viewer { camera: self.camera.clone(), lod_scale: self.lod_scale, hour: self.hour, + sky: self.sky.clone(), + water: self.water.clone(), + ground: self.ground.clone(), ..Self::default() }; self.start(false); @@ -503,7 +513,11 @@ impl Viewer { self.aspect, ); world.look(eye, self.distance_scale(), sight); - if let Some(tables) = self.root.as_deref().and_then(sky::tables) { + if let Some(tables) = self + .root + .as_deref() + .and_then(|root| sky::tables(&self.sky, root)) + { world.set_fade(stream::fade_of(&tables.visual_settings)); } // The groups the world-state data has on at this hour and these modes, unless the person chose them. diff --git a/src/state/gta6/world/gta6_world/worldview/pick.rs b/src/state/gta6/world/gta6_world/worldview/pick.rs index 07237e9f7..81eca6a01 100644 --- a/src/state/gta6/world/gta6_world/worldview/pick.rs +++ b/src/state/gta6/world/gta6_world/worldview/pick.rs @@ -2,7 +2,7 @@ //! its viewer selected and the shapes the viewer holds, and tells the viewer what the bridge tints. use std::path::PathBuf; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; +use std::sync::Arc; use std::time::{Duration, Instant}; use glam::Vec3; @@ -32,12 +32,6 @@ pub(super) const ASPECT: f32 = 16.0 / 9.0; pub(super) const TREE_AT: [f32; 3] = [0.0, 20.0, 0.0]; pub(super) const LAMP_AT: [f32; 3] = [6.0, 20.0, 0.0]; -/// The viewer the session of these tests is a shell over, in place of the one of the process. -fn made_up_viewer() -> MutexGuard<'static, Viewer> { - static VIEWER: LazyLock> = LazyLock::new(Mutex::default); - VIEWER.lock().unwrap_or_else(|p| p.into_inner()) -} - fn entity(word: u64, at: [f32; 3]) -> StreamEntity { StreamEntity { archetype_word: word, @@ -154,6 +148,8 @@ fn a_click_at_a_pixel_selects_the_entity_that_stands_there_and_a_click_on_the_sk Vec::new(), )); let install = PathBuf::from("a-build"); + let world = crate::state::gta6::world::WorldSession::default(); + let made_up_viewer = || super::viewer(&world); *made_up_viewer() = Viewer { root: Some(install.clone()), world: Some(World::of_maps( @@ -171,7 +167,7 @@ fn a_click_at_a_pixel_selects_the_entity_that_stands_there_and_a_click_on_the_sk install, options: Vec::new(), }; - let mut session = Gta6Session::over(key, made_up_viewer); + let mut session = Gta6Session::over(key, world.clone()); // Nothing is on the device yet: nothing draws, and a click on the tree meets nothing. until(&mut session, "the models waited for", |_| { diff --git a/src/state/gta6/world/gta6_world/worldview/reference/mod.rs b/src/state/gta6/world/gta6_world/worldview/reference/mod.rs index c214a09d2..2eb9f5a4a 100644 --- a/src/state/gta6/world/gta6_world/worldview/reference/mod.rs +++ b/src/state/gta6/world/gta6_world/worldview/reference/mod.rs @@ -556,12 +556,17 @@ fn digests(root: &Path) -> Digests { said("the textures"); // The day's tables and the water, each read once on a worker. - let tables = wait_for("the day's tables", || sky::tables(root)); let reading = Viewer { root: Some(root.to_path_buf()), ..Viewer::default() }; - let seen = || (water::water(root), water::ground(root)); + let tables = wait_for("the day's tables", || sky::tables(&reading.sky, root)); + let seen = || { + ( + water::water(&reading.water, root), + water::ground(&reading.ground, root), + ) + }; let mut quiet = 0; wait_for("the water", || { let _ = seen(); diff --git a/src/state/gta6/world/gta6_world/worldview/sky.rs b/src/state/gta6/world/gta6_world/worldview/sky.rs index 0333b54e9..7ad771e44 100644 --- a/src/state/gta6/world/gta6_world/worldview/sky.rs +++ b/src/state/gta6/world/gta6_world/worldview/sky.rs @@ -10,14 +10,15 @@ use or_world_gta6::day::{read_day, DayTables}; const ARCHIVE: &str = "common.rpf"; type Read = Arc>>; +type HeldList = Vec<(PathBuf, Read)>; -// ponytail: read again each session, about a second; kept beside the world index if it shows. -static HELD: Mutex> = Mutex::new(Vec::new()); +#[derive(Clone, Default)] +pub(super) struct SkyCache(Arc>); /// The day's tables of the install at `root`, read once on a worker and held: `None` until they are read, and where the install states none. -pub fn tables(root: &Path) -> Option> { +pub(super) fn tables(cache: &SkyCache, root: &Path) -> Option> { let archive = root.join(ARCHIVE); - let mut held = HELD.lock().unwrap_or_else(|p| p.into_inner()); + let mut held = cache.0.lock().unwrap_or_else(|p| p.into_inner()); let slot = match held.iter().find(|(path, _)| *path == archive) { Some((_, slot)) => Arc::clone(slot), None => { diff --git a/src/state/gta6/world/gta6_world/worldview/water/ground.rs b/src/state/gta6/world/gta6_world/worldview/water/ground.rs index 37fd86cd9..d7a354f8d 100644 --- a/src/state/gta6/world/gta6_world/worldview/water/ground.rs +++ b/src/state/gta6/world/gta6_world/worldview/water/ground.rs @@ -28,21 +28,25 @@ const BODY_LIMIT: u64 = 16 << 20; // stream the tiles by the grid's radius at their own size if a shore needs the metre. const KEPT: u32 = 128; -type Read = Arc>>>; - /// What [`held`] keeps: each install's root and its slot, empty while it is read. pub(super) type Slots = Mutex>>>)>>; -static HELD: Mutex> = Mutex::new(Vec::new()); +#[derive(Clone, Default)] +pub(in crate::state::gta6::world::gta6_world::worldview) struct GroundCache( + Arc>, +); /// The ground under the water of the install at `root`, read once on a worker and held: `None` until it is read, and where the install's tables give none or it does not read. -pub fn ground(root: &Path) -> Option> { - held(&HELD, root, "the ground under the water", read) +pub(in crate::state::gta6::world::gta6_world::worldview) fn ground( + cache: &GroundCache, + root: &Path, +) -> Option> { + held(&cache.0, root, "the ground under the water", read) } /// What `read` makes of the install at `root`, read once on a worker and held in `slots`: `None` until it is read, and where it does not read. pub(super) fn held( - slots: &'static Slots, + slots: &Slots, root: &Path, what: &'static str, read: fn(&Path, &GtaViKeys) -> Result, @@ -92,8 +96,8 @@ pub(super) fn reading(slots: &Slots, root: &Path) -> bool { } /// Whether the ground under the water of the install at `root` was asked for and is still being read. -pub fn ground_reading(root: &Path) -> bool { - reading(&HELD, root) +pub(super) fn ground_reading(cache: &GroundCache, root: &Path) -> bool { + reading(&cache.0, root) } /// The grid the document `entry` of the install at `root` states. diff --git a/src/state/gta6/world/gta6_world/worldview/water/mod.rs b/src/state/gta6/world/gta6_world/worldview/water/mod.rs index 182b0561a..76c1baf5f 100644 --- a/src/state/gta6/world/gta6_world/worldview/water/mod.rs +++ b/src/state/gta6/world/gta6_world/worldview/water/mod.rs @@ -13,7 +13,7 @@ use or_io::gta6::water::WaterData; mod ground; -pub use ground::ground; +pub(super) use ground::{ground, GroundCache}; /// The archive of an install the water document is in, and the document's path in it. const ARCHIVE: &str = "levels.rpf"; @@ -22,8 +22,10 @@ const ENTRY: &str = "levels/americas/water"; const BODY_LIMIT: u64 = 16 << 20; type Read = Arc>>>; +type WaterSlots = Vec<(PathBuf, Read)>; -static HELD: Mutex> = Mutex::new(Vec::new()); +#[derive(Clone, Default)] +pub(super) struct WaterCache(Arc>); /// The water document at `offset` of the GTA VI archive at `archive`. pub fn read(archive: &Path, offset: u64) -> Result { @@ -33,9 +35,9 @@ pub fn read(archive: &Path, offset: u64) -> Result { } /// The water of the install at `root`, read once on a worker and held: `None` until it is read, and where the install's table gives no such document or it does not read. -pub fn water(root: &Path) -> Option> { +pub(super) fn water(cache: &WaterCache, root: &Path) -> Option> { let archive = root.join(ARCHIVE); - let mut held = HELD.lock().unwrap_or_else(|p| p.into_inner()); + let mut held = cache.0.lock().unwrap_or_else(|p| p.into_inner()); let slot = match held.iter().find(|(path, _)| *path == archive) { Some((_, slot)) => Arc::clone(slot), None => { @@ -73,7 +75,8 @@ impl super::Viewer { /// Whether a part of the install's water that was asked for is still being read: its quads or the ground under them. pub fn water_reading(&self) -> bool { self.root.as_deref().is_some_and(|root| { - ground::reading(&HELD, &root.join(ARCHIVE)) || ground::ground_reading(root) + ground::reading(&self.water.0, &root.join(ARCHIVE)) + || ground::ground_reading(&self.ground, root) }) } } diff --git a/src/state/gta6/world/gta6_world/worldview/whole.rs b/src/state/gta6/world/gta6_world/worldview/whole.rs index aac38981d..2ea8fc307 100644 --- a/src/state/gta6/world/gta6_world/worldview/whole.rs +++ b/src/state/gta6/world/gta6_world/worldview/whole.rs @@ -7,7 +7,7 @@ use std::io::Cursor; use std::path::{Path, PathBuf}; -use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; +use std::sync::{Arc, MutexGuard}; use std::time::{Duration, Instant}; use glam::{Vec2, Vec3}; @@ -43,10 +43,11 @@ const EYE: Vec3 = Vec3::new(0.5, 0.0, -3.0); /// The size of the view the manipulator is drawn in, in points. const SIZE: Vec2 = Vec2::new(1600.0, 900.0); -/// The viewer the sessions of these tests are a shell over, in place of the one of the process. -fn made_up_viewer() -> MutexGuard<'static, Viewer> { - static VIEWER: LazyLock> = LazyLock::new(Mutex::default); - VIEWER.lock().unwrap_or_else(|p| p.into_inner()) +use crate::state::gta6::world::WorldSession; + +/// The viewer the sessions of these tests are a shell over. +fn made_up_viewer(world: &WorldSession) -> MutexGuard<'_, Viewer> { + super::viewer(world) } /// Where a hand-built entity of seed `seed` stands. @@ -62,6 +63,7 @@ fn word(seed: u32) -> u64 { /// A world of three maps in one archive, and the app that shows it. struct Fixture { state: AppState, + world: WorldSession, /// The document path of each map's body: the map, the map that names it, and its first entity's parent map. map: PathBuf, child: PathBuf, @@ -159,7 +161,8 @@ fn fixture_of(install: PathBuf) -> Fixture { )); let mut camera = super::pick::camera(); camera.position = EYE; - *made_up_viewer() = Viewer { + let world = WorldSession::default(); + *made_up_viewer(&world) = Viewer { root: Some(install.clone()), world: Some(World::of_maps(Arc::clone(&index), EYE, 1.0, maps)), index: Some(index), @@ -174,13 +177,14 @@ fn fixture_of(install: PathBuf) -> Fixture { let mut state = AppState::new(); state .world - .hold(Box::new(Gta6Session::over(key, made_up_viewer))); + .hold(Box::new(Gta6Session::over(key, world.clone()))); state.active_workspace = Workspace::World; let [map, child, parent] = <[PathBuf; 3]>::try_from(paths).expect("three maps"); // Every plan of a save finds the synthetic keys. state.world_fit_is_asked_with(&map, synthetic_keys); Fixture { state, + world, map, child, parent, @@ -190,8 +194,8 @@ fn fixture_of(install: PathBuf) -> Fixture { /// Where the selection the viewer holds draws the node `place` of the map named `map`: `None` where it draws it nowhere, or at two places. // ⚠ A node is listed once for each chunk that may draw it, so the same place twice is one place. -fn drawn_at(map: u32, place: u32) -> Option<[f32; 3]> { - let selected = made_up_viewer().selected(&mut Vec::new()); +fn drawn_at(world: &WorldSession, map: u32, place: u32) -> Option<[f32; 3]> { + let selected = made_up_viewer(world).selected(&mut Vec::new()); let instances = selected.iter().flat_map(|s| s.instances.iter()); let mut places = instances .filter(|i| i.node == (map, place)) @@ -201,16 +205,21 @@ fn drawn_at(map: u32, place: u32) -> Option<[f32; 3]> { } /// Poll the session, the removal and the manipulator, giving the device each model the world waits for, until `done` says so. -fn until(state: &mut AppState, what: &str, done: impl Fn(&mut AppState) -> bool) { +fn until( + state: &mut AppState, + world: &WorldSession, + what: &str, + done: impl Fn(&mut AppState) -> bool, +) { let limit = Instant::now() + Duration::from_secs(25); loop { state.world.session().expect("a session").poll(); state.poll_world_removal(); state.world_follows_the_documents(); state.world_tool_settles(); - let wanted = made_up_viewer().selected(&mut Vec::new()); + let wanted = made_up_viewer(world).selected(&mut Vec::new()); for (_, model) in wanted.iter().flat_map(|s| s.wanted.iter()) { - let mut viewer = made_up_viewer(); + let mut viewer = made_up_viewer(world); viewer.hold_shape(*model, cube()); viewer.selected(&mut vec![(*model, Some(true))]); } @@ -230,20 +239,23 @@ fn until(state: &mut AppState, what: &str, done: impl Fn(&mut AppState) -> bool) } /// Click the view at the place `at` is drawn, and what the click came to once it is answered. -fn click(state: &mut AppState, at: [f32; 3]) -> Picking { +fn click(state: &mut AppState, world: &WorldSession, at: [f32; 3]) -> Picking { let session = state.world.session().expect("a session"); let (across, down) = pixel_of(&session.camera(), at); let ray = ray_through(&session.camera(), ASPECT, across, down).expect("a ray"); session.click(ray); - until(state, "the answer of a click", |state| { + until(state, world, "the answer of a click", |state| { !state.world.session().expect("a session").pick_pending() }); state.world.session().expect("a session").picking() } /// The map the body of the document at `path` reads to, as the document holds it now. -fn held(path: &Path) -> MapData { - match opened_map(path).expect("the map is open").as_deref() { +fn held(state: &AppState, path: &Path) -> MapData { + match opened_map(&state.gta6.world, path) + .expect("the map is open") + .as_deref() + { Ok(MapBody::Data(map)) => map.clone(), _ => panic!("no map data at {}", path.display()), } @@ -290,16 +302,17 @@ fn an_entity_taken_out_from_the_world_screen_renumbers_each_map_that_names_its_m let _english = crate::i18n::pin("en"); let Fixture { mut state, + world, map, child, parent, _dir, } = fixture(); let stored = [&map, &child, &parent].map(|path| stored(path)); - until(&mut state, "the first entity drawn", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the first entity drawn", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(picked) = click(&mut state, at(1)) else { + let Picking::Picked(picked) = click(&mut state, &world, at(1)) else { panic!("the click on the first entity picked nothing"); }; assert_eq!((picked.name.place, picked.position), (0, Vec3::from(at(1)))); @@ -309,7 +322,7 @@ fn an_entity_taken_out_from_the_world_screen_renumbers_each_map_that_names_its_m state.delete_world_selection(); assert_eq!(errors(&state), Vec::::new()); assert!(state.world_removal_runs() || state.documents.len() == 3); - until(&mut state, "the removal", |state| { + until(&mut state, &world, "the removal", |state| { !state.world_removal_runs() && state.workbench.maps.gta6.world_removal.is_none() }); assert_eq!(errors(&state), Vec::::new()); @@ -326,24 +339,29 @@ fn an_entity_taken_out_from_the_world_screen_renumbers_each_map_that_names_its_m ); } // The map lost its first entity, the child names the same entity one place lower, and the parent counts one child fewer. - assert_eq!(held(&map).entities.len(), 3); - assert_eq!(held(&map).entities[0].position, at(2)); - assert_eq!(held(&child).entities[0].parent_index, 2); - assert_eq!(held(&parent).entities[0].num_children, 1); + assert_eq!(held(&state, &map).entities.len(), 3); + assert_eq!(held(&state, &map).entities[0].position, at(2)); + assert_eq!(held(&state, &child).entities[0].parent_index, 2); + assert_eq!(held(&state, &parent).entities[0].num_children, 1); // One group of three steps, nothing selected, and the world draws each of the three from its document. assert_eq!(state.workbench.maps.gta6.world_groups.len(), 1); assert_eq!(state.workbench.maps.gta6.world_groups[0].len(), 3); let session = state.world.session().expect("a session"); assert!(matches!(session.picking(), Picking::Nothing)); assert_eq!(session.laid_documents().len(), 3); - let bodies = made_up_viewer().world().expect("a world").bodies(); + let bodies = made_up_viewer(&world).world().expect("a world").bodies(); assert_eq!(bodies.read(MAP).expect("the map").entities.len(), 3); let named = bodies.read(CHILD).expect("the child").entities[0].parent; assert_eq!(named.map(|parent| parent.index), Some(2), "{named:?}"); - until(&mut state, "the world drawn without the entity", |_| { - let gone = (0..4).all(|place| drawn_at(MAP, place) != Some(at(1))); - gone && drawn_at(MAP, 1) == Some(at(3)) - }); + until( + &mut state, + &world, + "the world drawn without the entity", + |_| { + let gone = (0..4).all(|place| drawn_at(&world, MAP, place) != Some(at(1))); + gone && drawn_at(&world, MAP, 1) == Some(at(3)) + }, + ); // Said when it is made: the body shrank, so only a rebuilt archive holds it. let WorldFit::Rebuilt(why) = fit(&mut state) else { panic!("a map that lost an entity fits its place"); @@ -365,20 +383,20 @@ fn an_entity_taken_out_from_the_world_screen_renumbers_each_map_that_names_its_m ); assert_eq!(now.physical, was.physical, "{}", path.display()); } - assert_eq!(held(&map).entities.len(), 4); - assert_eq!(held(&child).entities[0].parent_index, 3); - assert_eq!(held(&parent).entities[0].num_children, 2); - until(&mut state, "the entity drawn again", |_| { - drawn_at(MAP, 0) == Some(at(1)) && drawn_at(MAP, 2) == Some(at(3)) + assert_eq!(held(&state, &map).entities.len(), 4); + assert_eq!(held(&state, &child).entities[0].parent_index, 3); + assert_eq!(held(&state, &parent).entities[0].num_children, 2); + until(&mut state, &world, "the entity drawn again", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) && drawn_at(&world, MAP, 2) == Some(at(3)) }); // Nothing is left to save, so nothing is said of a fit. assert_eq!(fit(&mut state), WorldFit::Unedited); // One Redo takes it out of all three again; an Undo asked of the child's document alone takes the others with it. assert_eq!(state.redo(), removed); - assert_eq!(held(&map).entities.len(), 3); - assert_eq!(held(&child).entities[0].parent_index, 2); - assert_eq!(held(&parent).entities[0].num_children, 1); + assert_eq!(held(&state, &map).entities.len(), 3); + assert_eq!(held(&state, &child).entities[0].parent_index, 2); + assert_eq!(held(&state, &parent).entities[0].num_children, 1); let other = state .meta_document_at(&child) .expect("the child's document"); @@ -386,25 +404,28 @@ fn an_entity_taken_out_from_the_world_screen_renumbers_each_map_that_names_its_m state.step(other, crate::state::EditDirection::Undo), removed ); - assert_eq!(held(&map).entities.len(), 4); - assert_eq!(held(&parent).entities[0].num_children, 2); + assert_eq!(held(&state, &map).entities.len(), 4); + assert_eq!(held(&state, &parent).entities[0].num_children, 2); assert_eq!(errors(&state), Vec::::new()); // A move keeps the body's length: it fits, and a patched copy holds it. - until(&mut state, "the entity drawn once more", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the entity drawn once more", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(_) = click(&mut state, at(1)) else { + let Picking::Picked(_) = click(&mut state, &world, at(1)) else { panic!("the click on the entity put back picked nothing"); }; let up = Vec3::from(at(1)) + Vec3::Z; state.move_world_selection(up); assert_eq!(errors(&state), Vec::::new()); - assert_eq!(held(&map).entities.len(), 4); + assert_eq!(held(&state, &map).entities.len(), 4); assert_eq!(fit(&mut state), WorldFit::Patched); - until(&mut state, "the entity drawn where it was moved", |_| { - drawn_at(MAP, 0) == Some(up.to_array()) - }); + until( + &mut state, + &world, + "the entity drawn where it was moved", + |_| drawn_at(&world, MAP, 0) == Some(up.to_array()), + ); } #[test] @@ -413,14 +434,15 @@ fn a_drag_of_a_handle_draws_the_picked_entity_under_the_pointer_and_is_one_step_ let _english = crate::i18n::pin("en"); let Fixture { mut state, + world, map, _dir, .. } = fixture(); - until(&mut state, "the first entity drawn", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the first entity drawn", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(_) = click(&mut state, at(1)) else { + let Picking::Picked(_) = click(&mut state, &world, at(1)) else { panic!("the click on the first entity picked nothing"); }; let camera = state.world.session().expect("a session").camera(); @@ -441,13 +463,15 @@ fn a_drag_of_a_handle_draws_the_picked_entity_under_the_pointer_and_is_one_step_ state.world_drag_moves(&screen, to); let dragged = (state.workbench.maps.world_tool.dragged_to()).expect("a drag under way"); assert!(dragged.position.z > stood.z + 0.1, "{dragged:?}"); - let (_, shift) = made_up_viewer().picked_shift.expect("the drag is drawn"); + let (_, shift) = made_up_viewer(&world) + .picked_shift + .expect("the drag is drawn"); assert!(shift.transform_point3(stood).distance(dragged.position) < 1e-3); assert_eq!(state.documents.len(), 0); // Escape gives it up: the shift ends, and nothing was changed. assert!(state.world_drag_given_up()); - assert_eq!(made_up_viewer().picked_shift, None); + assert_eq!(made_up_viewer(&world).picked_shift, None); assert_eq!(state.documents.len(), 0); // Dragged again and let go: one step of the map's document, and the shift stands until the selection draws it there itself. @@ -457,19 +481,24 @@ fn a_drag_of_a_handle_draws_the_picked_entity_under_the_pointer_and_is_one_step_ assert_eq!(errors(&state), Vec::::new()); let (_, undo) = written(&state, &map); assert_eq!(undo, Some(format!("Moved 0x{:016X}", word(1)))); - assert_eq!(held(&map).entities.len(), 4); + assert_eq!(held(&state, &map).entities.len(), 4); let doc = state.meta_document_at(&map).expect("the map's document"); assert_eq!(state.document(doc).expect("it").history.done().len(), 1); assert!( - made_up_viewer().picked_shift.is_some(), + made_up_viewer(&world).picked_shift.is_some(), "the entity would be drawn where it stood until the map is read again" ); - until(&mut state, "the entity drawn where it was dragged", |_| { - let drawn = drawn_at(MAP, 0); - drawn.is_some_and(|at| Vec3::from(at).distance(dragged.position) < 1e-3) - }); - until(&mut state, "the shift of the drag ended", |_| { - made_up_viewer().picked_shift.is_none() + until( + &mut state, + &world, + "the entity drawn where it was dragged", + |_| { + let drawn = drawn_at(&world, MAP, 0); + drawn.is_some_and(|at| Vec3::from(at).distance(dragged.position) < 1e-3) + }, + ); + until(&mut state, &world, "the shift of the drag ended", |_| { + made_up_viewer(&world).picked_shift.is_none() }); assert_eq!(state.undo(), undo); } @@ -480,12 +509,12 @@ fn the_key_of_delete_pressed_while_gta_vis_view_holds_the_keyboard_takes_out_wha use crate::state::the_world_screen_has_a_manipulator::{button, key, moved}; let _serial = crate::ui::theme::serial(); - let _rest = super::keys::AtRest; let _english = crate::i18n::pin("en"); // The build's folder stands, so the view keeps the session of it that this test made. let build = tempfile::tempdir().expect("a scratch folder"); let Fixture { state: mut made, + world, map, _dir, .. @@ -493,10 +522,10 @@ fn the_key_of_delete_pressed_while_gta_vis_view_holds_the_keyboard_takes_out_wha let mut state = showing(build.path()); state.world = std::mem::take(&mut made.world); state.world_fit_is_asked_with(&map, synthetic_keys); - until(&mut state, "the first entity drawn", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the first entity drawn", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(_) = click(&mut state, at(1)) else { + let Picking::Picked(_) = click(&mut state, &world, at(1)) else { panic!("the click on the first entity picked nothing"); }; let (ctx, mut text) = (egui::Context::default(), String::new()); @@ -529,12 +558,12 @@ fn the_key_of_delete_pressed_while_gta_vis_view_holds_the_keyboard_takes_out_wha assert!(picked(&mut state)); frame(&ctx, &mut state, &mut text, vec![key(egui::Key::Delete)]); assert_eq!(errors(&state), Vec::::new()); - until(&mut state, "the removal", |state| { + until(&mut state, &world, "the removal", |state| { !state.world_removal_runs() && state.workbench.maps.gta6.world_removal.is_none() }); assert_eq!(errors(&state), Vec::::new()); assert_eq!( - held(&map).entities.len(), + held(&state, &map).entities.len(), 3, "Delete's key took nothing out" ); @@ -550,14 +579,15 @@ fn a_change_of_a_map_whose_document_writes_back_as_no_body_is_refused_when_it_is let _english = crate::i18n::pin("en"); let Fixture { mut state, + world, map, _dir, .. } = fixture(); - until(&mut state, "the first entity drawn", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the first entity drawn", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(_) = click(&mut state, at(1)) else { + let Picking::Picked(_) = click(&mut state, &world, at(1)) else { panic!("the click on the first entity picked nothing"); }; let up = Vec3::from(at(1)) + Vec3::Z; @@ -605,20 +635,23 @@ fn a_removal_one_of_its_maps_cannot_take_is_made_in_none_of_them() { let _english = crate::i18n::pin("en"); let Fixture { mut state, + world, map, child, parent, _dir, } = fixture(); - until(&mut state, "the first entity drawn", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the first entity drawn", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(_) = click(&mut state, at(1)) else { + let Picking::Picked(_) = click(&mut state, &world, at(1)) else { panic!("the click on the first entity picked nothing"); }; // Both maps the removal renumbers are open, the parent's first: it is the first to take its step. - (state.open_linked_map(&parent, &stored(&parent))).expect("the parent's document"); - let lost = (state.open_linked_map(&child, &stored(&child))).expect("the child's document"); + let parent_sections = stored(&parent); + (state.open_linked_map(&parent, &parent_sections)).expect("the parent's document"); + let child_sections = stored(&child); + let lost = (state.open_linked_map(&child, &child_sections)).expect("the child's document"); state.delete_world_selection(); assert_eq!(errors(&state), Vec::::new()); read_ends(&state); @@ -634,8 +667,8 @@ fn a_removal_one_of_its_maps_cannot_take_is_made_in_none_of_them() { assert_eq!(undo, None, "a step was left in {}", path.display()); } assert!(state.workbench.maps.gta6.world_groups.is_empty()); - assert_eq!(held(&map).entities.len(), 4); - assert_eq!(held(&parent).entities[0].num_children, 2); + assert_eq!(held(&state, &map).entities.len(), 4); + assert_eq!(held(&state, &parent).entities[0].num_children, 2); } #[test] @@ -644,15 +677,16 @@ fn a_map_opened_as_another_body_while_a_removal_read_it_keeps_what_its_document_ let _english = crate::i18n::pin("en"); let Fixture { mut state, + world, map, child, _dir, .. } = fixture(); - until(&mut state, "the first entity drawn", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the first entity drawn", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(_) = click(&mut state, at(1)) else { + let Picking::Picked(_) = click(&mut state, &world, at(1)) else { panic!("the click on the first entity picked nothing"); }; state.delete_world_selection(); @@ -671,7 +705,7 @@ fn a_map_opened_as_another_body_while_a_removal_read_it_keeps_what_its_document_ assert_eq!(undo, None); assert_eq!(now.virtual_section, other.virtual_section); assert_eq!(written(&state, &map).1, None); - assert_eq!(held(&map).entities.len(), 4); + assert_eq!(held(&state, &map).entities.len(), 4); } #[test] @@ -683,14 +717,15 @@ fn a_changed_map_whose_save_cannot_be_planned_says_so_and_not_that_nothing_is_to let _english = crate::i18n::pin("en"); let Fixture { mut state, + world, map, _dir, .. } = fixture(); - until(&mut state, "the first entity drawn", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the first entity drawn", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(_) = click(&mut state, at(1)) else { + let Picking::Picked(_) = click(&mut state, &world, at(1)) else { panic!("the click on the first entity picked nothing"); }; state.move_world_selection(Vec3::from(at(1)) + Vec3::Z); @@ -717,14 +752,15 @@ fn what_is_selected_is_changed_and_taken_out_only_where_its_maps_document_holds_ let _english = crate::i18n::pin("en"); let Fixture { mut state, + world, map, _dir, .. } = fixture(); - until(&mut state, "the first entity drawn", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the first entity drawn", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(_) = click(&mut state, at(1)) else { + let Picking::Picked(_) = click(&mut state, &world, at(1)) else { panic!("the click on the first entity picked nothing"); }; // The map's document, as another screen left it and the world does not draw it: another entity stands first. @@ -766,11 +802,11 @@ fn a_handle_dragged_with_the_pointer_over_gta_vis_view_draws_the_entity_under_it use crate::state::the_world_screen_has_a_manipulator::{button, moved}; let _serial = crate::ui::theme::serial(); - let _rest = super::keys::AtRest; let _english = crate::i18n::pin("en"); let build = tempfile::tempdir().expect("a scratch folder"); let Fixture { state: mut made, + world, map, _dir, .. @@ -778,17 +814,17 @@ fn a_handle_dragged_with_the_pointer_over_gta_vis_view_draws_the_entity_under_it let mut state = showing(build.path()); state.world = std::mem::take(&mut made.world); state.world_fit_is_asked_with(&map, synthetic_keys); - until(&mut state, "the first entity drawn", |_| { - drawn_at(MAP, 0) == Some(at(1)) + until(&mut state, &world, "the first entity drawn", |_| { + drawn_at(&world, MAP, 0) == Some(at(1)) }); - let Picking::Picked(_) = click(&mut state, at(1)) else { + let Picking::Picked(_) = click(&mut state, &world, at(1)) else { panic!("the click on the first entity picked nothing"); }; let (ctx, mut text) = (egui::Context::default(), String::new()); frame(&ctx, &mut state, &mut text, Vec::new()); - // ⚠ The view draws its handles through the camera of the process's viewer: it is stood where the session's looks from. + // ⚠ The view draws its handles through the camera of the state's viewer: it is stood where the session's looks from. let camera = state.world.session().expect("a session").camera(); - super::viewer().camera = camera.clone(); + super::viewer(&state.gta6.world).camera = camera.clone(); frame(&ctx, &mut state, &mut text, Vec::new()); let [left, top, width, height] = (state.workbench.maps.world_tool.view).expect("the view was drawn"); @@ -815,11 +851,13 @@ fn a_handle_dragged_with_the_pointer_over_gta_vis_view_draws_the_entity_under_it } assert!(state.workbench.maps.world_tool.dragging()); let stood = Vec3::from(at(1)); - let (_, shift) = made_up_viewer().picked_shift.expect("the drag is drawn"); + let (_, shift) = made_up_viewer(&world) + .picked_shift + .expect("the drag is drawn"); let (stands, wanted) = (shift.transform_point3(stood), stood + up * dragged); assert!(stands.distance(wanted) < 0.02, "{stands} is not {wanted}"); assert_eq!(state.documents.len(), 0); - let looks = super::viewer().camera.clone(); + let looks = super::viewer(&state.gta6.world).camera.clone(); assert_eq!( (looks.yaw, looks.pitch), (camera.yaw, camera.pitch), @@ -834,11 +872,16 @@ fn a_handle_dragged_with_the_pointer_over_gta_vis_view_draws_the_entity_under_it assert_eq!(undo, Some(format!("Moved 0x{:016X}", word(1)))); let doc = state.meta_document_at(&map).expect("the map's document"); assert_eq!(state.document(doc).expect("it").history.done().len(), 1); - until(&mut state, "the entity drawn where it was dragged", |_| { - let drawn = drawn_at(MAP, 0); - drawn.is_some_and(|at| Vec3::from(at).distance(wanted) < 0.02) - }); - until(&mut state, "the shift of the drag ended", |_| { - made_up_viewer().picked_shift.is_none() + until( + &mut state, + &world, + "the entity drawn where it was dragged", + |_| { + let drawn = drawn_at(&world, MAP, 0); + drawn.is_some_and(|at| Vec3::from(at).distance(wanted) < 0.02) + }, + ); + until(&mut state, &world, "the shift of the drag ended", |_| { + made_up_viewer(&world).picked_shift.is_none() }); } diff --git a/src/state/gta6/world/gta6_world_edit.rs b/src/state/gta6/world/gta6_world_edit.rs index 5129b4ee4..f6ce07b95 100644 --- a/src/state/gta6/world/gta6_world_edit.rs +++ b/src/state/gta6/world/gta6_world_edit.rs @@ -111,7 +111,7 @@ impl AppState { None => self.open_world_map(&path)?, }; let no_record = || crate::i18n::tr(NO_RECORD.key()).to_string(); - let e = match opened_map(&path) { + let e = match opened_map(&self.gta6.world, &path) { Some(Ok(body)) => match &*body { MapBody::Data(m) => m.entities.get(place).cloned().ok_or_else(no_record)?, MapBody::Types(_) => return Err(no_record()), diff --git a/src/state/gta6/world/gta6_world_fits.rs b/src/state/gta6/world/gta6_world_fits.rs index 6b8912f72..f14dc2f43 100644 --- a/src/state/gta6/world/gta6_world_fits.rs +++ b/src/state/gta6/world/gta6_world_fits.rs @@ -15,7 +15,7 @@ use crate::state::rpf_archive_open::tree_verbs::Writes; use crate::state::{AppState, DocPayload}; /// Where a plan finds the keys the archive's tables open with. -pub(crate) type Keys = fn() -> Result, String>; +pub(crate) type Keys = Arc Result, String> + Send + Sync>; /// What a save of a changed map into a copy of its archive would write. #[derive(Debug, Clone, PartialEq, Eq)] @@ -80,16 +80,26 @@ pub struct WorldFits { impl AppState { /// Ask whether the map document at `path` still fits its place, as it stands now: a worker plans its save and [`Self::world_fit`] says the answer. pub(in crate::state) fn world_fit_is_asked(&mut self, path: &Path) { - let keys = self.workbench.maps.gta6.world_fits.keys; - self.world_fit_is_asked_with( - path, - keys.unwrap_or(crate::state::rpf9_scan::rpf9_table::keys), - ); + let keys = (self.workbench.maps.gta6.world_fits.keys.clone()).unwrap_or_else(|| { + let rpf9 = self.gta6.rpf9.clone(); + Arc::new(move || crate::state::rpf9_scan::rpf9_table::keys(&rpf9)) + }); + self.world_fit_ask(path, keys); } /// [`Self::world_fit_is_asked`], the plan and every later one finding its keys through `keys`. - pub(crate) fn world_fit_is_asked_with(&mut self, path: &Path, keys: Keys) { - self.workbench.maps.gta6.world_fits.keys = Some(keys); + #[cfg(test)] + pub(crate) fn world_fit_is_asked_with( + &mut self, + path: &Path, + keys: impl Fn() -> Result, String> + Send + Sync + 'static, + ) { + let keys: Keys = Arc::new(keys); + self.workbench.maps.gta6.world_fits.keys = Some(Arc::clone(&keys)); + self.world_fit_ask(path, keys); + } + + fn world_fit_ask(&mut self, path: &Path, keys: Keys) { let Some(doc) = self.meta_document_at(path) else { return; }; diff --git a/src/state/gta6/world/mod.rs b/src/state/gta6/world/mod.rs index d0b96adb7..f1c61a61b 100644 --- a/src/state/gta6/world/mod.rs +++ b/src/state/gta6/world/mod.rs @@ -3,3 +3,15 @@ pub(crate) mod gta6_map_edit; pub(crate) mod gta6_world; pub(crate) mod gta6_world_edit; pub(crate) mod gta6_world_fits; + +/// Per-instance GTA VI world, map, and viewer state owned by +/// [`crate::state::gta6::session::Gta6Session`]. +#[derive(Clone, Default)] +pub(crate) struct WorldSession { + world: gta6_world::WorldCache, + fill: gta6_world::fill::FillCache, + viewer: gta6_world::worldview::ViewerCache, + entity_job: gta6_map::entity::EntityJobCache, + map: gta6_map::MapCache, + links: gta6_map::links::LinksCache, +} diff --git a/src/state/jobs.rs b/src/state/jobs.rs index 95aafd3ae..9a5d160d7 100644 --- a/src/state/jobs.rs +++ b/src/state/jobs.rs @@ -238,8 +238,8 @@ impl AppState { .flatten() .chain(self.archive_scans().filter_map(|scan| scan.job())) .chain(self.archive_scans().filter_map(|scan| scan.effects_job())) - .chain(super::gta6_effects::install_job()) - .chain(super::gta6_shaders::job()) + .chain(super::gta6_effects::install_job(&self.gta6.drawable)) + .chain(super::gta6_shaders::job(&self.gta6.drawable)) .chain(self.texture_naming_jobs()) .chain(self.neighbour_search_job()) .chain(self.set_finding_jobs()) @@ -250,7 +250,9 @@ impl AppState { .chain(super::gta6_install_scan::job(&self.gta6.install)) .chain(super::gta6_modding::text_search::job(&self.gta6.modding)) .chain(super::ttpf_document::calibration::job(&self.gta6.ttpf)) - .chain(super::rpf_archive_open::tree_verbs::plan_job::jobs()) + .chain(super::rpf_archive_open::tree_verbs::plan_job::jobs( + &self.gta6.rpf9, + )) .collect() } @@ -291,7 +293,7 @@ impl AppState { JobKind::Save => { self.cancel_save(); // ⚠ A GTA VI tree's save being planned says its end once its worker sees the stop. - super::rpf_archive_open::tree_verbs::plan_job::stop(); + super::rpf_archive_open::tree_verbs::plan_job::stop(&self.gta6.rpf9); false } JobKind::Conversion => { @@ -341,8 +343,8 @@ impl AppState { // ⚠ Its end is said once its worker sees the stop, by `poll_effects_reads`. JobKind::EffectsRead => { self.archive_scans().for_each(|scan| scan.stop_effects()); - super::gta6_effects::stop_install_read(); - super::gta6_shaders::stop(); + super::gta6_effects::stop_install_read(&self.gta6.drawable); + super::gta6_shaders::stop(&self.gta6.drawable); false } // ⚠ Its end is said once its worker sees the stop, by `poll_texture_naming`. @@ -367,7 +369,7 @@ impl AppState { } // ⚠ Its end is said once its worker sees the stop, by `poll_map_search`. JobKind::WorldIndex => { - super::gta6_world::worldview::viewer().stop(); + super::gta6_world::worldview::viewer(&self.gta6.world).stop(); false } // ⚠ Its end shows in the audio game data's view once its worker sees the stop. diff --git a/src/state/mod.rs b/src/state/mod.rs index b158a2dd2..7a13b056c 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -446,7 +446,7 @@ impl AppState { if or_title::game::registry::detect(&folder).is_some() { self.decline_adoption(&folder); } - match gta_vi::plain_folder_note(&folder) { + match gta_vi::plain_folder_note(&self.gta6.rpf9, &folder) { Some((note, true)) => self.show_warning_toast(note), Some((note, false)) => self.show_info_toast(note), None => self.show_toast("Folder opened"), @@ -677,7 +677,9 @@ impl AppState { resource: Option>, ) -> DocumentId { let id = self.alloc_doc_id(); - let mut doc = Document::new(id, Some(path.clone()), payload).with_resource(resource); + let mut doc = Document::new(id, Some(path.clone()), payload) + .with_rpf9(self.gta6.rpf9.clone()) + .with_resource(resource); doc.rpf_entry_binding = binding; if rpf9_scan::scanned_body(&path).is_some() { doc.read_only = Some(rpf9_scan::READ_ONLY_BODY); @@ -699,7 +701,7 @@ impl AppState { // A dictionary opens on its first entry: the viewport draws an entry only while it is selected. let first_entry = selection_lookup::ydd_first_entry_hash(&doc.payload); self.documents.push(doc); - gta6_head::trim(&self.documents); + gta6_head::trim(&self.gta6.drawable, &self.documents); self.remember_where_the_front_document_is_seen(id); self.active_document = Some(id); self.hide_start_page(); diff --git a/src/state/photo_documents.rs b/src/state/photo_documents.rs index 9af890878..b85940745 100644 --- a/src/state/photo_documents.rs +++ b/src/state/photo_documents.rs @@ -42,24 +42,24 @@ fn level_of(leaf: &str, only: Option<&HashSet>) -> Option<(String, usize /// Every drawable and fragment whose path starts with `under`, in every archive below `root`, /// nested ones included: one per model, at the most detailed level it has, in name order. pub(crate) fn gta6_models( - install: &crate::state::gta6::install::InstallSession, + gta6: &crate::state::gta6::session::Gta6Session, root: &Path, under: &str, only: Option<&HashSet>, ) -> Result, String> { - Ok(gta6_models_and_kits(install, root, under, only, None)?.0) + Ok(gta6_models_and_kits(gta6, root, under, only, None)?.0) } /// [`gta6_models`], and in the same walk the ped catalogue of each kit `kits` names, by the /// kit's name: the metadata body of that name in an archive that holds paths under `under`. pub(crate) fn gta6_models_and_kits( - install: &crate::state::gta6::install::InstallSession, + gta6: &crate::state::gta6::session::Gta6Session, root: &Path, under: &str, only: Option<&HashSet>, kits: Option<&HashSet>, ) -> Result<(Vec, BTreeMap), String> { - let keys = super::rpf9_scan::rpf9_table::keys()?; + let keys = super::rpf9_scan::rpf9_table::keys(>a6.rpf9)?; let names = super::rpf9_scan::rpf9_table::resolver(); let mut archives = Vec::new(); archives_under(root, &mut archives) @@ -90,7 +90,7 @@ pub(crate) fn gta6_models_and_kits( // A weapon's parts are found by the names of the bodies beside it. let labels = std::mem::take(&mut walk.labels); if !labels.is_empty() { - super::gta6_names::add_labels(install, path, labels); + super::gta6_names::add_labels(>a6.install, path, labels); } } let models = found.into_values().map(|(_, model)| model).collect(); diff --git a/src/state/rpf/mod.rs b/src/state/rpf/mod.rs index 441cf0abb..eb7d96615 100644 --- a/src/state/rpf/mod.rs +++ b/src/state/rpf/mod.rs @@ -12,3 +12,25 @@ pub(crate) mod rpf_records; pub(crate) mod rpf_session; pub(crate) mod rpf_tree; pub(crate) mod rpf_undo; + +/// Per-`AppState` session state for GTA VI RPF9 scanning, key loading, and archive tree operations. +#[derive(Clone, Default)] +pub(crate) struct Rpf9Session { + counted_names: rpf9_counted_names::CountedNamesCache, + origins: rpf9_scan::OriginsCache, + skeletons: rpf9_scan::SkeletonsCache, + ciphered: rpf9_scan::ciphered::CipheredCache, + keys_held: rpf9_scan::rpf9_table::gta6_keys_held::KeysHeldCache, + table: rpf9_scan::rpf9_table::Rpf9TableCache, + archive_save: rpf9_scan::rpf9_table::gta6_archive_save::ArchiveSaveCache, + tree_verbs: rpf_archive_open::tree_verbs::TreeVerbsCache, + plan_job: rpf_archive_open::tree_verbs::plan_job::PlanJobCache, + tree_open: rpf_archive_open::tree_open::TreeOpenCache, + tree_bind: rpf_archive_open::tree_open::bind::TreeBindCache, +} + +impl std::fmt::Debug for Rpf9Session { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Rpf9Session").finish_non_exhaustive() + } +} diff --git a/src/state/rpf/rpf9_counted_names.rs b/src/state/rpf/rpf9_counted_names.rs index d3a56c640..c1c703bad 100644 --- a/src/state/rpf/rpf9_counted_names.rs +++ b/src/state/rpf/rpf9_counted_names.rs @@ -4,19 +4,22 @@ use std::collections::BTreeMap; use std::fs::File; use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use or_io::container::rpf::{rpf9_names_by_count_at, Rpf9BodyKind, Rpf9NamesByCount, Rpf9ScanFind}; use or_job::{Cancel, Progress}; +use crate::state::rpf::Rpf9Session; use crate::state::rpf9_scan::{Ended, Found, Row, MAX_ROWS}; +type CountedNamesMap = BTreeMap<(PathBuf, u64), Rpf9ScanFind>; + /// The names each nested archive opened from its parent's list ends with, by archive and header. -// ponytail: one map for the whole app, which no close empties; a find is a few dozen bytes. -static NAMES: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct CountedNamesCache(Arc>); -fn known() -> MutexGuard<'static, BTreeMap<(PathBuf, u64), Rpf9ScanFind>> { - (NAMES.lock()).unwrap_or_else(|poisoned| poisoned.into_inner()) +fn known(rpf9: &Rpf9Session) -> MutexGuard<'_, CountedNamesMap> { + (rpf9.counted_names.0.lock()).unwrap_or_else(|poisoned| poisoned.into_inner()) } fn lock(found: &Mutex) -> MutexGuard<'_, Found> { @@ -26,20 +29,21 @@ fn lock(found: &Mutex) -> MutexGuard<'_, Found> { } /// Keep the names `found`, the list of `archive`, holds for the archive nested at `offset`. -pub(in crate::state) fn remember(archive: &Path, found: &Found, offset: u64) { +pub(in crate::state) fn remember(rpf9: &Rpf9Session, archive: &Path, found: &Found, offset: u64) { let own = Rpf9BodyKind::Names { archive: offset }; let names = found.rows.iter().find_map(|row| match row { Row::Body(find) if find.kind == own => Some(**find), _ => None, }); if let Some(names) = names { - known().insert((archive.to_path_buf(), offset), names); + known(rpf9).insert((archive.to_path_buf(), offset), names); } } /// The scan of `path` from `start`, with the names placed by count added once a whole file's /// scan ends; a nested archive whose names are known is scanned to them and ended there. pub(in crate::state) fn counted_scan( + rpf9: &Rpf9Session, path: &Path, start: u64, len: u64, @@ -48,7 +52,7 @@ pub(in crate::state) fn counted_scan( progress: &Progress, ) -> Result { let key = (path.to_path_buf(), start); - let names = known().get(&key).copied().filter(|_| start > 0); + let names = known(rpf9).get(&key).copied().filter(|_| start > 0); let Some(names) = names else { let ended = crate::state::rpf9_scan::scan(path, start, len, found, cancel, progress)?; if start == 0 && ended == Ended::Whole && !cancel.is_set() { diff --git a/src/state/rpf/rpf9_scan/ciphered/mod.rs b/src/state/rpf/rpf9_scan/ciphered/mod.rs index 0dce479cc..ea000b3c5 100644 --- a/src/state/rpf/rpf9_scan/ciphered/mod.rs +++ b/src/state/rpf/rpf9_scan/ciphered/mod.rs @@ -2,6 +2,7 @@ //! the decipher on the load worker, and the view the deciphered body opens in. use super::*; +use crate::state::rpf::Rpf9Session; /// The payload a decrypted, inflated body opens as: a PSO or RBF through the metadata reader, text /// as text, else its bytes under the reason none reads them. A headerless body (a compiled script, a @@ -12,7 +13,11 @@ fn decrypted_payload( bytes: Vec, ) -> DocPayload { if bytes.starts_with(b"PSIN") || bytes.starts_with(b"RBF0") { - return DocPayload::Meta(MetaDocument::from_bytes_with(bytes, gta6.install.clone())); + return DocPayload::Meta(MetaDocument::from_bytes_with( + bytes, + gta6.install.clone(), + gta6.rpf9.clone(), + )); } if crate::state::document_io::is_text(&bytes) { return super::gta6_data_xml::payload(path, bytes); @@ -39,25 +44,26 @@ pub(super) struct CipheredRequest { /// Requests the GTA VI archive explorer left for its content-ciphered opens, keyed by the synthetic /// body path [`body_path`] made, taken by [`read_body`] when it opens that path. A request is a few /// words, not the plaintext, and the decipher runs on the load worker, not the UI thread. -static CIPHERED: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct CipheredCache(Arc>>); /// Keep a request to decipher the leaf `entry` of the archive at `base`, for the next open of `path`. -pub(crate) fn remember_ciphered(path: &Path, base: u64, entry: u32) { - (CIPHERED.lock()) +pub(crate) fn remember_ciphered(rpf9: &Rpf9Session, path: &Path, base: u64, entry: u32) { + (rpf9.ciphered.0.lock()) .unwrap_or_else(|p| p.into_inner()) .insert(path.to_path_buf(), CipheredRequest { base, entry }); } /// Drop any pending decrypt request remembered for `path`. -pub(crate) fn forget_ciphered(path: &Path) { - (CIPHERED.lock()) +pub(crate) fn forget_ciphered(rpf9: &Rpf9Session, path: &Path) { + (rpf9.ciphered.0.lock()) .unwrap_or_else(|p| p.into_inner()) .remove(path); } /// Take the decrypt request remembered for `path`, if any; a body opens from it once. -pub(super) fn take_ciphered(path: &Path) -> Option { - (CIPHERED.lock()) +pub(super) fn take_ciphered(rpf9: &Rpf9Session, path: &Path) -> Option { + (rpf9.ciphered.0.lock()) .unwrap_or_else(|p| p.into_inner()) .remove(path) } @@ -69,11 +75,12 @@ pub(super) mod gta6_script_view; #[cfg(test)] pub(crate) fn decipher_entry( + rpf9: &Rpf9Session, archive: &Path, base: u64, entry_index: u32, ) -> Result, String> { - let (keys, mut file, mount) = mount_ciphered(archive, base)?; + let (keys, mut file, mount) = mount_ciphered(rpf9, archive, base)?; let entry = (mount.archive.entries.iter()) .find(|e| e.index == entry_index) .ok_or_else(|| format!("entry {entry_index} is not in this table"))?; @@ -92,7 +99,7 @@ pub(super) fn ciphered_payload( archive: &Path, req: CipheredRequest, ) -> Result { - let (keys, mut file, mount) = mount_ciphered(archive, req.base)?; + let (keys, mut file, mount) = mount_ciphered(>a6.rpf9, archive, req.base)?; let entry = (mount.archive.entries.iter()) .find(|e| e.index == req.entry) .ok_or_else(|| format!("entry {} is not in this table", req.entry))?; @@ -111,10 +118,11 @@ pub(super) fn ciphered_payload( /// Load the GTA VI key snapshot and mount the archive whose header is at `base` in the file at /// `archive`, returning the keys, the open file and the mount so one open deciphers one entry. fn mount_ciphered( + rpf9: &Rpf9Session, archive: &Path, base: u64, ) -> Result<(std::sync::Arc, File, Gta6Mount), String> { - let keys = super::rpf9_table::keys()?; + let keys = super::rpf9_table::keys(rpf9)?; let mut file = File::open(archive).map_err(|e| format!("{}: {e}", archive.display()))?; let mounted = open_at(&mut file, base, &keys).map_err(|e| e.to_string())?; Ok(( diff --git a/src/state/rpf/rpf9_scan/mod.rs b/src/state/rpf/rpf9_scan/mod.rs index 9f91effee..7ec4da016 100644 --- a/src/state/rpf/rpf9_scan/mod.rs +++ b/src/state/rpf/rpf9_scan/mod.rs @@ -17,6 +17,7 @@ use or_job::{Cancel, Progress}; use crate::state::document::{DocPayload, HexDocument, MetaDocument}; use crate::state::extract_job::{run_extraction, ExtractItem, OnClash}; use crate::state::jobs::{file_name, JobKind, RunningJob}; +use crate::state::rpf::Rpf9Session; use crate::state::rpf9_counted_names::counted_scan; use crate::state::rpf9_kept::Kept; @@ -110,6 +111,7 @@ pub struct Rpf9ScanDocument { list: Mutex, /// Where the scan is kept once it has read the whole archive; `None` for a nested archive's. kept: Option, + rpf9: Rpf9Session, } impl Rpf9ScanDocument { @@ -128,19 +130,39 @@ impl Rpf9ScanDocument { return Ok(None); }; let kept = Kept::of(path, &meta); - Ok(Some(Self::scanned(path, header, meta.len(), 0, kept))) + Ok(Some(Self::scanned( + Rpf9Session::default(), + path, + header, + meta.len(), + 0, + kept, + ))) } /// The archive nested at `offset` of the file at `path`, with `header`, its scan started from /// its header and ending at the names the scan places after its last entry. - pub fn open_nested(path: &Path, offset: u64, header: Rpf9Header) -> Result { + pub(crate) fn open_nested( + rpf9: Rpf9Session, + path: &Path, + offset: u64, + header: Rpf9Header, + ) -> Result { let file_len = std::fs::metadata(path) .map_err(|e| format!("{}: {e}", path.display()))? .len(); - Ok(Self::scanned(path, Some(header), file_len, offset, None)) + Ok(Self::scanned( + rpf9, + path, + Some(header), + file_len, + offset, + None, + )) } fn scanned( + rpf9: Rpf9Session, path: &Path, header: Option, file_len: u64, @@ -163,6 +185,7 @@ impl Rpf9ScanDocument { effects: Mutex::default(), list: Mutex::default(), kept, + rpf9, }; doc.work(); doc @@ -178,6 +201,7 @@ impl Rpf9ScanDocument { ); let (path, start, file_len) = (self.path.clone(), self.start, self.file_len); let kept = self.kept.clone(); + let rpf9 = self.rpf9.clone(); std::thread::spawn(move || { let ended = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let reading_kept = lock(&found).reading_kept; @@ -188,7 +212,7 @@ impl Rpf9ScanDocument { } lock(&found).reading_kept = false; } - let ended = counted_scan(&path, start, file_len, &found, &cancel, &progress) + let ended = counted_scan(&rpf9, &path, start, file_len, &found, &cancel, &progress) .unwrap_or_else(Ended::Failed); if let (Ended::Whole, Some(kept)) = (&ended, &kept) { if let Err(error) = kept.keep(&found) { @@ -393,7 +417,7 @@ pub use view::{view_of, View}; pub(crate) mod rpf9_table; -mod ciphered; +pub(crate) mod ciphered; #[cfg(test)] pub(crate) use ciphered::decipher_entry; use ciphered::{ciphered_payload, take_ciphered}; @@ -462,21 +486,23 @@ pub(in crate::state) fn read_body( offset: u64, ) -> Result { // A body opened anew holds none of the edits a closed document of it kept, through either door. - crate::state::gta6_gltf_import::forget(path); + crate::state::gta6_gltf_import::forget(>a6.drawable, path); crate::state::gta6_embedded_edit::forget(>a6.textures, path); crate::state::gta6_modding::model_replace::forget(>a6.modding, path); // A content-ciphered entry the archive explorer opened left a decrypt request here, keyed by // this synthetic path; the decipher runs on this worker, not the UI thread. The clear reader // below reads only bytes stored in the clear. - if let Some(req) = take_ciphered(path) { + if let Some(req) = take_ciphered(>a6.rpf9, path) { return ciphered_payload(gta6, path, archive, req); } // A clear row the archive's tree opened is read by its table, under the kind its start names. - if let Some(read) = crate::state::rpf_archive_open::tree_open::read(path, archive, offset) { + if let Some(read) = + crate::state::rpf_archive_open::tree_open::read(>a6.rpf9, path, archive, offset) + { use crate::state::rpf_archive_open::tree_open::TableRead; return match read? { TableRead::Body(find, bytes) => { - origins().insert(path.to_path_buf(), (find, false)); + origins(>a6.rpf9).insert(path.to_path_buf(), (find, false)); body_payload(gta6, path, archive, find, bytes) } TableRead::Plain(payload) => Ok(payload), @@ -485,7 +511,7 @@ pub(in crate::state) fn read_body( let file = File::open(archive).map_err(|e| format!("{}: {e}", archive.display()))?; let (find, bytes) = match read_rpf9_body(&file, offset, BODY_LIMIT) { Err(Rpf9ScanError::ExtentNotKnown { .. }) if offset > 0 => { - return nested(archive, &file, offset) + return nested(>a6.rpf9, archive, &file, offset) } // A first entry whose end is not stated ends where its list's next row starts. Err(e) => { @@ -499,7 +525,7 @@ pub(in crate::state) fn read_body( ) { Some(opened) => { let (find, hex) = opened?; - origins().insert(path.to_path_buf(), (find, false)); + origins(>a6.rpf9).insert(path.to_path_buf(), (find, false)); return Ok(DocPayload::Hex(hex)); } None => return Err(e.to_string()), @@ -507,12 +533,17 @@ pub(in crate::state) fn read_body( } Ok(read) => read, }; - origins().insert(path.to_path_buf(), (find, path == archive)); + origins(>a6.rpf9).insert(path.to_path_buf(), (find, path == archive)); body_payload(gta6, path, archive, find, bytes) } /// The archive nested at `offset` of `file`, the file at `archive`, as a scan of its own. -fn nested(archive: &Path, mut file: &File, offset: u64) -> Result { +fn nested( + rpf9: &Rpf9Session, + archive: &Path, + mut file: &File, + offset: u64, +) -> Result { let at = |e: std::io::Error| format!("{}: {e}", archive.display()); file.seek(SeekFrom::Start(offset)).map_err(at)?; let mut head = Vec::with_capacity(RPF9_HEADER_SIZE); @@ -520,43 +551,46 @@ fn nested(archive: &Path, mut file: &File, offset: u64) -> Result; + /// What the scan found of each body opened from its list, by the path [`body_path`] made, read /// when it opened, and whether the body is a file of its own. -// ponytail: one map for the whole app, which no close empties; a find is a few dozen bytes. -static ORIGINS: Mutex> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct OriginsCache(Arc>); -fn origins() -> MutexGuard<'static, BTreeMap> { - (ORIGINS.lock()).unwrap_or_else(|poisoned| poisoned.into_inner()) +fn origins(rpf9: &Rpf9Session) -> MutexGuard<'_, OriginsMap> { + (rpf9.origins.0.lock()).unwrap_or_else(|poisoned| poisoned.into_inner()) } /// The find the body at `path` was read from once it has opened, and whether it is a file of its own. -pub(crate) fn scan_origin(path: &Path) -> Option<(Rpf9ScanFind, bool)> { - origins().get(path).copied() +pub(crate) fn scan_origin(rpf9: &Rpf9Session, path: &Path) -> Option<(Rpf9ScanFind, bool)> { + origins(rpf9).get(path).copied() } /// Whether the document at `path` is a body read from a GTA VI archive. -pub(crate) fn from_gta_vi(path: Option<&Path>) -> bool { - path.is_some_and(|p| scan_origin(p).is_some()) +pub(crate) fn from_gta_vi(rpf9: &Rpf9Session, path: Option<&Path>) -> bool { + path.is_some_and(|p| scan_origin(rpf9, p).is_some()) } /// Whether the body at `path` opened as the lines OpenRage writes of what its reader reads. -pub(crate) fn opened_as_facts(path: &Path) -> bool { - scan_origin(path).is_some_and(|(find, _)| matches!(view_of(&find), Ok(View::Facts(_)))) +pub(crate) fn opened_as_facts(rpf9: &Rpf9Session, path: &Path) -> bool { + scan_origin(rpf9, path).is_some_and(|(find, _)| matches!(view_of(&find), Ok(View::Facts(_)))) } /// Whether the body at `path` opened as text it stores, which an edit can be written back as. -pub(crate) fn opened_as_text(path: &Path) -> bool { - scan_origin(path).is_some_and(|(find, _)| matches!(view_of(&find), Ok(View::Xml | View::Text))) +pub(crate) fn opened_as_text(rpf9: &Rpf9Session, path: &Path) -> bool { + scan_origin(rpf9, path) + .is_some_and(|(find, _)| matches!(view_of(&find), Ok(View::Xml | View::Text))) } /// Whether the Text panel keeps `doc` from edits: a scanned body takes them only as its own text. -pub(crate) fn text_takes_no_edit(doc: &crate::state::Document) -> bool { +pub(crate) fn text_takes_no_edit(rpf9: &Rpf9Session, doc: &crate::state::Document) -> bool { doc.read_only.is_some_and(|why| { - why != READ_ONLY_BODY || !doc.path.as_deref().is_some_and(opened_as_text) + why != READ_ONLY_BODY || !doc.path.as_deref().is_some_and(|p| opened_as_text(rpf9, p)) }) } @@ -602,7 +636,7 @@ fn animation(find: &Rpf9ScanFind, bytes: &[u8]) -> Result { /// A headerless resource through GTA VI's RBM reader, from `bytes`, a read of `resource`. fn headerless( - install: &crate::state::gta6::install::InstallSession, + gta6: &crate::state::gta6::session::Gta6Session, path: &Path, resource: &Rpf9Resource, bytes: &[u8], @@ -611,15 +645,16 @@ fn headerless( return Err(tr!("This body starts with four zero bytes but has no 0DRP at 0x10, so what it is and which reader fits it are not known.").to_string()); } let (virtual_section, physical) = resource.sections(bytes); - let map = crate::state::gta6_map::keep(path, virtual_section, physical); - crate::state::gta6_world::keep(path, virtual_section, physical); + let map = crate::state::gta6_map::keep(>a6.world, path, virtual_section, physical); + crate::state::gta6_world::keep(gta6, path, virtual_section, physical); let why = |e: String| { tr!( "GTA VI's RBM reader does not read this body's two sections: {e}", e = e ) }; - match MetaDocument::from_gta_vi_headerless_with(virtual_section, physical, install.clone()) { + match MetaDocument::from_gta_vi_headerless_with(virtual_section, physical, gta6.install.clone()) + { Ok(doc) => Ok(DocPayload::Meta(doc)), // The map reader needs the tables alone, so the Map screen shows a map whose tree is not read. Err(e) if map => { @@ -716,13 +751,18 @@ impl crate::state::AppState { match view { // A nested archive's list is where its bodies open from, so its tab is kept. Ok(View::Archive) => { - crate::state::rpf9_counted_names::remember(&scan.path, &scan.found(), find.offset); + crate::state::rpf9_counted_names::remember( + &self.gta6.rpf9, + &scan.path, + &scan.found(), + find.offset, + ); self.load_file(body_path(&scan.path, find.offset, View::Archive)) } Ok(view) => { // An effect container's effects are learned as a job of its own, with a Stop. if matches!(view, View::Effects) { - scan.read_effects(self.gta6.bodies.clone(), *find); + scan.read_effects(self.gta6.clone(), *find); self.show_info_toast(tr!("Its effects are read in the background, and a GTA VI drawable then names its shaders and their parameters by them.")); } let path = body_path(&scan.path, find.offset, view); @@ -874,11 +914,11 @@ impl Rpf9ScanDocument { /// Read the effects of the `SGD5` container `find` on a worker, in place of any read before it. pub(in crate::state) fn read_effects( &self, - bodies: crate::state::gta6::bodies::BodiesSession, + gta6: crate::state::gta6::session::Gta6Session, find: Rpf9ScanFind, ) { *self.effects() = Some(crate::state::gta6_effects::EffectsRead::start( - bodies, &self.path, find, BODY_LIMIT, + gta6, &self.path, find, BODY_LIMIT, )); } @@ -909,19 +949,19 @@ impl Rpf9ScanDocument { } type Skeleton = or_io::gta6::headerless::Skeleton; +type SkeletonsMap = BTreeMap>; /// What each scanned drawable or fragment opened says of its skeleton, read on the load's worker. -// ponytail: one map for the whole app, which no close empties; skeletons are small. -static SKELETONS: Mutex>> = Mutex::new(BTreeMap::new()); +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct SkeletonsCache(Arc>); -pub(in crate::state) fn skeletons( -) -> MutexGuard<'static, BTreeMap>> { - (SKELETONS.lock()).unwrap_or_else(|poisoned| poisoned.into_inner()) +pub(in crate::state) fn skeletons(rpf9: &Rpf9Session) -> MutexGuard<'_, SkeletonsMap> { + (rpf9.skeletons.0.lock()).unwrap_or_else(|poisoned| poisoned.into_inner()) } /// The skeleton of the scanned drawable or fragment a path [`body_path`] made names, read when it opened. -pub(crate) fn scanned_skeleton(path: &Path) -> Result { - skeletons().get(path).cloned().unwrap_or_else(|| { +pub(crate) fn scanned_skeleton(rpf9: &Rpf9Session, path: &Path) -> Result { + skeletons(rpf9).get(path).cloned().unwrap_or_else(|| { Err(tr!("This document is no drawable or fragment found by a scan of a GTA VI archive, so it holds no GTA VI skeleton.").to_string()) }) } diff --git a/src/state/rpf/rpf9_scan/payload.rs b/src/state/rpf/rpf9_scan/payload.rs index 609dfda08..e0557bc21 100644 --- a/src/state/rpf/rpf9_scan/payload.rs +++ b/src/state/rpf/rpf9_scan/payload.rs @@ -41,9 +41,10 @@ pub(super) fn body_payload( return Ok(DocPayload::Meta(MetaDocument::from_bytes_with( bytes, gta6.install.clone(), + gta6.rpf9.clone(), ))); } - View::Headerless => headerless(>a6.install, path, &resource()?, &bytes), + View::Headerless => headerless(gta6, path, &resource()?, &bytes), View::TextTable => gta6_text::Gta6TextDocument::open(resource()?.sections(&bytes).0) .inspect(|text| gta6_dialogue::note_table(>a6.audio, &text.table)) .map(|text| DocPayload::Gta6Text(Box::new(text))), @@ -71,7 +72,7 @@ pub(super) fn body_payload( let (virtual_section, physical) = resource.sections(&bytes); match gta6_face::learn(>a6.anim, path, signature, virtual_section) { Some(gta6_face::Learned::Skeleton(skeleton)) => { - skeletons().insert(path.to_path_buf(), Ok(skeleton)); + skeletons(>a6.rpf9).insert(path.to_path_buf(), Ok(skeleton)); } Some(gta6_face::Learned::Expressions(set)) => { return Ok(DocPayload::Gta6Expressions(Arc::from(set))) @@ -137,7 +138,7 @@ pub(super) fn body_payload( }; if let Some(fragment) = fragment { let skeleton = skeleton_of(virtual_section, fragment); - skeletons().insert(path.to_path_buf(), skeleton); + skeletons(>a6.rpf9).insert(path.to_path_buf(), skeleton); // Keep the stated model name so a hash-named tree row can show the drawable's // or fragment's own leaf name in place of its hash. let label = if fragment { "fragment" } else { "drawable" }; @@ -157,8 +158,15 @@ pub(super) fn body_payload( read.map(|read| { let read = Arc::new(read); if let Some(fragment) = fragment { - gta6_head::keep(path, &read, virtual_section, physical, fragment); - gta6_weapon_parts::keep(>a6.install, path, archive, &read); + gta6_head::keep( + >a6.drawable, + path, + &read, + virtual_section, + physical, + fragment, + ); + gta6_weapon_parts::keep(gta6, path, archive, &read); } DocPayload::Gta6Drawable(read) }) diff --git a/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/mod.rs b/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/mod.rs index 3188565a2..fcaa20127 100644 --- a/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/mod.rs +++ b/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/mod.rs @@ -15,6 +15,7 @@ use crate::state::extract_job::ExtractItem; use crate::state::gta6_modding::mod_package::in_game_folder; use crate::state::gta6_resource_save::EditedSave; use crate::state::jobs::{JobKind, Outcome, Then}; +use crate::state::rpf::Rpf9Session; use crate::state::rpf_archive_open::tree_verbs::plan_job::{ plan_save_with, save_tracked, Tick, Unplanned, SAVE_OPTIMAL_CAP, }; @@ -40,19 +41,16 @@ struct Pending { body: Body, } -// ponytail: one list for the process; a poll takes the saves of the documents its app holds, so a -// save of a document closed before it ended stays in the list unsaid. -static ENDED: Mutex> = Mutex::new(Vec::new()); +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct ArchiveSaveCache(Arc>>); -fn ended() -> MutexGuard<'static, Vec> { - ENDED +fn ended(rpf9: &Rpf9Session) -> MutexGuard<'_, Vec> { + rpf9.archive_save + .0 .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } -/// Where a save finds the keys the archive's tables open with. -type Keys = fn() -> Result, String>; - /// Which copy a planned save would write, and why each row named keeps it from being patched in place. pub(crate) type CopyPlanned = (Writes, Vec); @@ -90,7 +88,7 @@ impl AppState { .rpf9_place(*entry_index)?; // The row's path inside the file on disk: the tree's path is from its root, which may be a // folder holding the archive. - let shown = crate::state::rpf_archive_open::tree_open::shown(path); + let shown = crate::state::rpf_archive_open::tree_open::shown(&self.gta6.rpf9, path); let inner = (shown .as_deref() .and_then(|s| s.strip_prefix(&place.file).ok())) @@ -139,10 +137,14 @@ impl AppState { /// Ask where the copy of the active document's archive goes, then write its edits there on a /// worker; the toast after says which copy it is. pub(crate) fn ask_and_save_into_archive_copy(&mut self) -> bool { - self.ask_and_save_with(super::keys) + let rpf9 = self.gta6.rpf9.clone(); + self.ask_and_save_with(move || super::keys(&rpf9)) } - fn ask_and_save_with(&mut self, keys: Keys) -> bool { + fn ask_and_save_with( + &mut self, + keys: impl FnOnce() -> Result, String> + Send + 'static, + ) -> bool { let Some(name) = self.archive_copy_name() else { return false; }; @@ -162,7 +164,7 @@ impl AppState { pub(in crate::state) fn save_into_archive_copy_with( &mut self, out: PathBuf, - keys: Keys, + keys: impl FnOnce() -> Result, String> + Send + 'static, ) -> bool { match self.pending_copy() { Ok(pending) => self.write_copy_on_worker(pending, out, keys), @@ -200,7 +202,7 @@ impl AppState { .ok_or_else(|| refused().to_string())?; // The row's name as the tree shows it, where the document was opened from a tree's row. let name = (doc.path.as_deref()) - .and_then(crate::state::rpf_archive_open::tree_open::shown) + .and_then(|p| crate::state::rpf_archive_open::tree_open::shown(&self.gta6.rpf9, p)) .and_then(|shown| Some(shown.file_name()?.to_string_lossy().into_owned())); Ok(Pending { id, @@ -211,7 +213,12 @@ impl AppState { }) } - fn write_copy_on_worker(&mut self, pending: Pending, out: PathBuf, keys: Keys) -> bool { + fn write_copy_on_worker( + &mut self, + pending: Pending, + out: PathBuf, + keys: impl FnOnce() -> Result, String> + Send + 'static, + ) -> bool { match self.gate_permits(Some(&out)) { GateOutcome::Proceed => {} GateOutcome::Refused => return false, @@ -228,12 +235,13 @@ impl AppState { body, } = pending; self.say_the_checksum_is_kept(id); + let rpf9 = self.gta6.rpf9.clone(); std::thread::spawn(move || { let said = (keys().map_err(Unplanned::Refused)).and_then(|keys| { let body = body()?; - write_copy(&archive, offset, name, body, &out, &keys) + write_copy(&rpf9, &archive, offset, name, body, &out, &keys) }); - ended().push((id, out, said)); + ended(&rpf9).push((id, out, said)); }); true } @@ -254,12 +262,12 @@ impl AppState { if let Some((place, inner)) = self.tree_row_place(path) { return Some((place.file, inner)); } - let shown = crate::state::rpf_archive_open::tree_open::shown(path)?; + let shown = crate::state::rpf_archive_open::tree_open::shown(&self.gta6.rpf9, path)?; let (source, _) = crate::state::rpf9_scan::scanned_body(path)?; // A tree saved as a copy shows its rows under the copy, the file on disk its path starts with. let archive = match shown.starts_with(source) { true => source.to_path_buf(), - false => crate::state::rpf_archive_open::tree_open::copy_of(path)?, + false => crate::state::rpf_archive_open::tree_open::copy_of(&self.gta6.rpf9, path)?, }; let inner = shown.strip_prefix(&archive).ok()?; let inner = (inner.iter().map(|p| p.to_string_lossy())) @@ -272,7 +280,7 @@ impl AppState { pub(in crate::state) fn poll_archive_saves(&mut self) { self.poll_tree_saves(); let done: Vec = { - let mut list = ended(); + let mut list = ended(&self.gta6.rpf9); let (mine, rest) = std::mem::take(&mut *list) .into_iter() .partition(|(id, ..)| self.document(*id).is_some()); @@ -355,9 +363,10 @@ fn archive_body( // A metadata body's text is parsed and written on the worker, never on the UI thread; // a form edit reaches the text there too. let mut meta = meta.clone(); + let rpf9 = gta6.rpf9.clone(); return Ok(Box::new(move || { meta.ensure_text_current(); - let keys = || crate::state::rpf9_scan::rpf9_table::keys().ok(); + let keys = || crate::state::rpf9_scan::rpf9_table::keys(&rpf9).ok(); crate::state::gta6_meta_save::meta_bytes(&meta, keys) })); } @@ -377,7 +386,8 @@ fn archive_item( // An edited text body is written in the encoding and line endings it was read with. DocPayload::Text(text) if doc.dirty - && (doc.path.as_deref()).is_some_and(crate::state::rpf9_scan::opened_as_text) => + && (doc.path.as_deref()) + .is_some_and(|p| crate::state::rpf9_scan::opened_as_text(>a6.rpf9, p)) => { return Ok(ExtractItem::bytes(name, text.encode())); } @@ -409,6 +419,7 @@ fn archive_item( /// by its offset. A headerless resource's entry takes `body` as its loose form, any other its bytes, /// and the writer refuses what it would not read back. fn write_copy( + rpf9: &Rpf9Session, archive: &Path, offset: u64, name: Option, @@ -417,7 +428,7 @@ fn write_copy( keys: &GtaViKeys, ) -> Result { let (row, writer) = replaced(archive, offset, name, body, keys)?; - save_tracked(archive, out, keys, &[row], writer) + save_tracked(rpf9, archive, out, keys, &[row], writer) } /// `body` as the row a save writes in place of the entry whose body is at `offset` of the archive diff --git a/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/tests.rs b/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/tests.rs index ded8ea117..652f31929 100644 --- a/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/tests.rs +++ b/src/state/rpf/rpf9_scan/rpf9_table/gta6_archive_save/tests.rs @@ -155,20 +155,21 @@ fn a_row_saved_on_its_own_is_a_listed_job_whose_stop_leaves_no_file_and_logs_not ); let (_, start) = start_of(&std::fs::read(&source).expect("the source"), BIG); let out = dir.path().join("copy.rpf"); + let rpf9 = Rpf9Session::default(); let worker = { - let (source, out) = (source.clone(), out.clone()); + let (source, out, rpf9) = (source.clone(), out.clone(), rpf9.clone()); let body = vec![b'b'; 1 << 20]; - std::thread::spawn(move || write_copy(&source, start, None, body, &out, &keys)) + std::thread::spawn(move || write_copy(&rpf9, &source, start, None, body, &out, &keys)) }; // Stopped as Cancel on the job's row stops it, as soon as the list shows it. let mut seen = Vec::new(); while !worker.is_finished() { - let now = jobs(); + let now = jobs(&rpf9); if !now.is_empty() { if seen.is_empty() { seen = now; } - stop(); + stop(&rpf9); } } let stopped = worker.join().expect("the save's worker ends"); @@ -178,7 +179,7 @@ fn a_row_saved_on_its_own_is_a_listed_job_whose_stop_leaves_no_file_and_logs_not }; assert_eq!(job.kind, JobKind::Save); assert!(job.doing.contains("source.rpf"), "{}", job.doing); - assert!(jobs().is_empty(), "a stopped save leaves the job list"); + assert!(jobs(&rpf9).is_empty(), "a stopped save leaves the job list"); assert_eq!(listed(dir.path()), ["source.rpf"], "and no file"); // The poll says nothing was written, and shows no error. @@ -187,7 +188,7 @@ fn a_row_saved_on_its_own_is_a_listed_job_whose_stop_leaves_no_file_and_logs_not body_path(&source, start, View::Bytes), DocPayload::Meta(meta), ); - ended().push(( + ended(&state.gta6.rpf9).push(( crate::state::DocumentId(9_000), out.clone(), Err(Unplanned::Stopped), @@ -251,19 +252,45 @@ fn the_archive_read_is_never_written_and_what_names_no_entry_is_refused() { let (_, start) = start_of(&before, PSO); let keys = synthetic_keys().expect("the synthetic snapshot parses"); + let rpf9 = Rpf9Session::default(); let over = refused( - write_copy(&source, start, None, table_form_pso(), &source, &keys) - .expect_err("over the source"), + write_copy( + &rpf9, + &source, + start, + None, + table_form_pso(), + &source, + &keys, + ) + .expect_err("over the source"), ); assert!(over.contains("never written"), "{over}"); let existing = dir.path().join("existing.rpf"); std::fs::write(&existing, b"kept").expect("written"); - assert!(write_copy(&source, start, None, table_form_pso(), &existing, &keys).is_err()); + assert!(write_copy( + &rpf9, + &source, + start, + None, + table_form_pso(), + &existing, + &keys + ) + .is_err()); assert_eq!(std::fs::read(&existing).expect("kept"), b"kept"); let none = dir.path().join("none.rpf"); let why = refused( - write_copy(&source, start + 4, None, table_form_pso(), &none, &keys) - .expect_err("no entry there"), + write_copy( + &rpf9, + &source, + start + 4, + None, + table_form_pso(), + &none, + &keys, + ) + .expect_err("no entry there"), ); assert!(why.contains("no entry"), "{why}"); assert!(!none.exists(), "a refused save leaves no file"); diff --git a/src/state/rpf/rpf9_scan/rpf9_table/gta6_keys_held.rs b/src/state/rpf/rpf9_scan/rpf9_table/gta6_keys_held.rs index b19b77c74..00d8a63c5 100644 --- a/src/state/rpf/rpf9_scan/rpf9_table/gta6_keys_held.rs +++ b/src/state/rpf/rpf9_scan/rpf9_table/gta6_keys_held.rs @@ -2,9 +2,10 @@ //! frame never waits on unmasking the keys or reading the names. use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Duration, Instant}; +use crate::state::rpf::Rpf9Session; use crate::state::rpf9_scan::rpf9_table; /// What the app knows of GTA VI's keys. @@ -21,35 +22,50 @@ pub(crate) enum Gta6Keys { /// How long an answer stands before it is asked again: the install folder set may change. const AGAIN: Duration = Duration::from_secs(2); -static ANSWER: Mutex<(Option, Gta6Keys)> = Mutex::new((None, Gta6Keys::Asking)); -static ASKING: AtomicBool = AtomicBool::new(false); +#[derive(Clone)] +pub(in crate::state::rpf) struct KeysHeldCache { + answer: Arc, Gta6Keys)>>, + asking: Arc, +} + +impl Default for KeysHeldCache { + fn default() -> Self { + Self { + answer: Arc::new(Mutex::new((None, Gta6Keys::Asking))), + asking: Arc::new(AtomicBool::new(false)), + } + } +} -fn answer() -> MutexGuard<'static, (Option, Gta6Keys)> { - ANSWER.lock().unwrap_or_else(|p| p.into_inner()) +fn answer(cache: &KeysHeldCache) -> MutexGuard<'_, (Option, Gta6Keys)> { + cache.answer.lock().unwrap_or_else(|p| p.into_inner()) } /// What is known of GTA VI's keys now; a worker asks again once the answer is [`AGAIN`] old. -pub(crate) fn gta6_keys() -> Gta6Keys { - let mut held = answer(); +pub(crate) fn gta6_keys(rpf9: &Rpf9Session) -> Gta6Keys { + let cache = &rpf9.keys_held; + let mut held = answer(cache); let stale = held.0.is_none_or(|at| at.elapsed() >= AGAIN); - if stale && !ASKING.swap(true, Ordering::Relaxed) { + if stale && !cache.asking.swap(true, Ordering::Relaxed) { held.0 = Some(Instant::now()); - std::thread::spawn(|| { - let now = match rpf9_table::keys() { + let rpf9 = rpf9.clone(); + std::thread::spawn(move || { + let cache = &rpf9.keys_held; + let now = match rpf9_table::keys(&rpf9) { Err(why) => Gta6Keys::Missing(why), Ok(_) => { // The count said before stands while the resolver is built. - let before = match &answer().1 { + let before = match &answer(cache).1 { Gta6Keys::Held { names } => *names, _ => None, }; - answer().1 = Gta6Keys::Held { names: before }; + answer(cache).1 = Gta6Keys::Held { names: before }; let names = Some(rpf9_table::resolver().len()); Gta6Keys::Held { names } } }; - answer().1 = now; - ASKING.store(false, Ordering::Relaxed); + answer(cache).1 = now; + cache.asking.store(false, Ordering::Relaxed); }); } held.1.clone() diff --git a/src/state/rpf/rpf9_scan/rpf9_table/mod.rs b/src/state/rpf/rpf9_scan/rpf9_table/mod.rs index b85d679ae..6e83c4e95 100644 --- a/src/state/rpf/rpf9_scan/rpf9_table/mod.rs +++ b/src/state/rpf/rpf9_scan/rpf9_table/mod.rs @@ -5,11 +5,13 @@ use std::collections::BTreeMap; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; use or_io::container::rpf::{open_at, GtaViKeys, NameResolver, RPF9_MAGIC}; use crate::state::jobs::file_name; +use crate::state::rpf::Rpf9Session; use crate::state::DocPayload; /// Whether the table of the archive at `path` opens with `keys`, else the sentence that says a scan lists it. @@ -36,35 +38,49 @@ fn scanned(path: &Path, why: String) -> String { /// Where the keys are loaded from: the executable that unmasks them and the snapshot the /// environment names. type KeySource = (Option, Option); +type HeldKeys = BTreeMap, String>>; + +/// Per-session cache of unmasked GTA VI keys, resolver warm-up flag, and unopened-table toasts. +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct Rpf9TableCache { + keys: Arc>, + warming: Arc, + offers: Arc>>, +} /// GTA VI's keys as the app loads them, held with the failure when none are found: unmasking a /// snapshot reads and hashes a large executable. They are loaded again once their source changes. -pub(crate) fn keys() -> Result, String> { - keys_from(gta6_keys_flow::executable()) +pub(crate) fn keys(rpf9: &Rpf9Session) -> Result, String> { + keys_from(rpf9, gta6_keys_flow::executable()) } /// The keys of the build of `platform`, which an archive states in its header, where that build's install folder is set; else [`keys`]. -pub(crate) fn keys_of(platform: Option) -> Result, String> { +pub(crate) fn keys_of( + rpf9: &Rpf9Session, + platform: Option, +) -> Result, String> { let exe = platform.and_then(gta6_keys_flow::executable_of); - keys_from(exe.or_else(gta6_keys_flow::executable)) + keys_from(rpf9, exe.or_else(gta6_keys_flow::executable)) } /// The keys the executable `exe` unmasks, held for each source they were loaded from, so two builds' keys are held side by side. -fn keys_from(exe: Option) -> Result, String> { - type Held = std::collections::BTreeMap, String>>; - static KEYS: Mutex = Mutex::new(Held::new()); +fn keys_from(rpf9: &Rpf9Session, exe: Option) -> Result, String> { let source: KeySource = ( exe, std::env::var_os(or_io::container::rpf::GTA6_SNAPSHOT_ENV), ); - let mut held = KEYS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut held = rpf9 + .table + .keys + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); if let Some(keys) = held.get(&source) { return keys.clone(); } let keys = gta6_keys_flow::load_gta6_keys_with(source.0.as_deref()).map(Arc::new); held.insert(source, keys.clone()); if keys.is_ok() { - warm_names(); + warm_names(rpf9); } keys } @@ -104,60 +120,57 @@ fn names_from(dir: Option<&Path>, config: Option<&Path>) -> NameResolver { } /// Builds [`resolver`] on a worker once a run where keys are held, before an archive asks for it. -pub(crate) fn warm_names() { +pub(crate) fn warm_names(rpf9: &Rpf9Session) { if RESOLVER.get().is_some() { return; } - static WARMING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - if WARMING.swap(true, std::sync::atomic::Ordering::AcqRel) { + if rpf9.table.warming.swap(true, Ordering::AcqRel) { return; } - std::thread::spawn(|| { + let rpf9 = rpf9.clone(); + std::thread::spawn(move || { // Names are read only for a run that holds keys: an archive opens with none otherwise. - if keys().is_ok() { + if keys(&rpf9).is_ok() { resolver(); } - WARMING.store(false, std::sync::atomic::Ordering::Release); + rpf9.table.warming.store(false, Ordering::Release); }); } -/// Why the scan lists each archive opened from disk, by its path, until the app that opened it says so. -// ponytail: one map for the process; an open whose document never arrives leaves its entry behind. -static OFFERS: Mutex> = Mutex::new(BTreeMap::new()); - -fn offers() -> MutexGuard<'static, BTreeMap> { - OFFERS +fn offers(rpf9: &Rpf9Session) -> MutexGuard<'_, BTreeMap> { + rpf9.table + .offers .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// On the load's worker, keep why the scan lists the RPF9 archive at `path` where its table does not open. -pub(in crate::state) fn offer(path: &Path) { +pub(in crate::state) fn offer(rpf9: &Rpf9Session, path: &Path) { let mut head = [0u8; 4]; - let rpf9 = File::open(path) + let rpf9_file = File::open(path) .and_then(|mut f| f.read_exact(&mut head)) .is_ok() && u32::from_le_bytes(head) == RPF9_MAGIC; - if !rpf9 { + if !rpf9_file { return; } - let keys = keys(); + let keys = keys(rpf9); if let Err(why) = table_opens(path, keys.as_deref().map_err(Clone::clone)) { // What `offer_unopened` kept of the tree's own open says more, and stays. - offers().entry(path.to_path_buf()).or_insert(why); + offers(rpf9).entry(path.to_path_buf()).or_insert(why); } } /// On the load's worker, keep `why` the RPF9 archive at `path` did not open as a tree with the keys held, for the toast its scan's tab says. -pub(in crate::state) fn offer_unopened(path: &Path, why: String) { - offers().insert(path.to_path_buf(), scanned(path, why)); +pub(in crate::state) fn offer_unopened(rpf9: &Rpf9Session, path: &Path, why: String) { + offers(rpf9).insert(path.to_path_buf(), scanned(path, why)); } impl crate::state::AppState { /// Say in a toast why the scan lists each archive whose tab is open, once that tab is open. pub(in crate::state) fn poll_table_opens(&mut self) { let opened: Vec = { - let offers = offers(); + let offers = offers(&self.gta6.rpf9); if offers.is_empty() { return; } @@ -172,7 +185,8 @@ impl crate::state::AppState { .collect() }; for path in opened { - if let Some(why) = offers().remove(&path) { + let why = offers(&self.gta6.rpf9).remove(&path); + if let Some(why) = why { self.show_info_toast(why); } } @@ -185,4 +199,4 @@ pub(crate) mod gta6_keys_flow; mod names_cache; -mod gta6_archive_save; +pub(crate) mod gta6_archive_save; diff --git a/src/state/rpf/rpf9_scan/rpf9_tree_actions.rs b/src/state/rpf/rpf9_scan/rpf9_tree_actions.rs index 3445e9dcd..b197370dd 100644 --- a/src/state/rpf/rpf9_scan/rpf9_tree_actions.rs +++ b/src/state/rpf/rpf9_scan/rpf9_tree_actions.rs @@ -86,7 +86,15 @@ impl AppState { .and_then(|ext| DocumentKind::from_path(Path::new(&format!("row.{ext}")))); if shown.is_some_and(|kind| self.active_workspace.handles_kind(kind)) { let path = body_path(&place.file, place.offset, View::Bytes); - tree_open::leave(&path, &place, row_start, rpf9_table::keys, edited); + let rpf9 = self.gta6.rpf9.clone(); + tree_open::leave( + &self.gta6.rpf9, + &path, + &place, + row_start, + move || rpf9_table::keys(&rpf9), + edited, + ); tree_open::name(self, &path, doc, node); self.open_scanned_path(path, true); } diff --git a/src/state/rpf/rpf_archive_open/mod.rs b/src/state/rpf/rpf_archive_open/mod.rs index c196c1cd0..6edae03ac 100644 --- a/src/state/rpf/rpf_archive_open/mod.rs +++ b/src/state/rpf/rpf_archive_open/mod.rs @@ -3,14 +3,24 @@ use std::sync::Arc; use or_io::container::{RpfArchive, RpfCryptoProvider}; +use crate::state::rpf::Rpf9Session; + pub fn open_archive_from_disk( path: &Path, crypto: Arc, +) -> Result, String> { + open_archive_from_disk_with(&Rpf9Session::default(), path, crypto) +} + +pub(in crate::state) fn open_archive_from_disk_with( + rpf9: &Rpf9Session, + path: &Path, + crypto: Arc, ) -> Result, String> { // A GTA VI archive is read with the keys and names this app holds, carried into the open; any // other archive keeps the crypto it was handed. let crypto = match is_rpf9(path) { - true => gta6_crypto(path).unwrap_or(crypto), + true => gta6_crypto(rpf9, path).unwrap_or(crypto), false => crypto, }; let opened = RpfArchive::open_with(path, crypto); @@ -21,11 +31,14 @@ pub fn open_archive_from_disk( } /// A GTA VI archive on disk as the tree every archive opens as, read entry by entry from its file; `None` for any other file, with no key, and, said in a toast, where it does not open. -pub(in crate::state) fn gta6_tree(path: &Path) -> Option { +pub(in crate::state) fn gta6_tree( + rpf9: &Rpf9Session, + path: &Path, +) -> Option { if !is_rpf9(path) { return None; } - let crypto = gta6_crypto(path)?; + let crypto = gta6_crypto(rpf9, path)?; let opened = RpfArchive::open_with(path, crypto) .map_err(|e| { crate::state::gta_vi::rpf9_unopened_at(path, &e).unwrap_or_else(|| e.to_string()) @@ -34,7 +47,7 @@ pub(in crate::state) fn gta6_tree(path: &Path) -> Option Some(crate::state::DocPayload::Rpf(tree)), Err(why) => { - crate::state::rpf9_scan::rpf9_table::offer_unopened(path, why); + crate::state::rpf9_scan::rpf9_table::offer_unopened(rpf9, path, why); None } } @@ -54,11 +67,14 @@ fn is_rpf9(path: &Path) -> bool { /// handed; `None` when the app holds no keys, so the archive is refused rather than read. // ⚠ Waits until the names are built, so it is reached only from a load's or a tree row's worker, // whose loading row shows meanwhile. -pub(in crate::state) fn gta6_crypto(path: &Path) -> Option> { +pub(in crate::state) fn gta6_crypto( + rpf9: &Rpf9Session, + path: &Path, +) -> Option> { use or_io::container::rpf::Gta6Context; // The keys are those of the build whose platform letter the archive's header states at 0x19. let platform = or_io::container::rpf::rpf9_platform_of(path); - let keys = crate::state::rpf9_scan::rpf9_table::keys_of(platform).ok()?; + let keys = crate::state::rpf9_scan::rpf9_table::keys_of(rpf9, platform).ok()?; Some(Arc::new(Gta6Context { keys, names: crate::state::rpf9_scan::rpf9_table::resolver(), @@ -141,11 +157,13 @@ impl crate::state::AppState { }; let view = crate::state::rpf9_scan::View::Bytes; let path = crate::state::rpf9_scan::body_path(&place.file, place.offset, view); + let rpf9 = self.gta6.rpf9.clone(); tree_open::leave( + &self.gta6.rpf9, &path, &place, row_start, - crate::state::rpf9_scan::rpf9_table::keys, + move || crate::state::rpf9_scan::rpf9_table::keys(&rpf9), edited, ); tree_open::name(self, &path, parent, entry); diff --git a/src/state/rpf/rpf_archive_open/tree_open/bind/mod.rs b/src/state/rpf/rpf_archive_open/tree_open/bind/mod.rs index a71330a70..56a728641 100644 --- a/src/state/rpf/rpf_archive_open/tree_open/bind/mod.rs +++ b/src/state/rpf/rpf_archive_open/tree_open/bind/mod.rs @@ -3,13 +3,14 @@ //! writes a file. use std::path::PathBuf; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use or_io::container::rpf::BodyForm; use crate::state::document::DocumentId; use crate::state::extract_job::ExtractItem; use crate::state::gta6_resource_save::EditedSave; +use crate::state::rpf::Rpf9Session; use crate::state::{AppState, DocPayload, Document, RpfEntryBinding}; /// A save into a row that ended on its worker: the document and its path, the edit it was at, the @@ -25,12 +26,12 @@ type Ended = ( /// What makes a row's new body on the save's worker. type Body = Box Result, String> + Send>; -// ponytail: one list for the process, taken by the next poll of the app holding the document; two -// saves of one document in flight land in the order they end, add a per-document epoch if that bites. -static ENDED: Mutex> = Mutex::new(Vec::new()); +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct TreeBindCache(Arc>>); -fn ended() -> MutexGuard<'static, Vec> { - ENDED +fn ended(rpf9: &Rpf9Session) -> MutexGuard<'_, Vec> { + rpf9.tree_bind + .0 .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } @@ -46,9 +47,10 @@ fn row_body( // A metadata body's text is parsed and written on the worker, never on the UI thread; // a form edit reaches the text there too, so the row holds what the Text view shows. let mut meta = meta.clone(); + let rpf9 = gta6.rpf9.clone(); return Ok(Box::new(move || { meta.ensure_text_current(); - let keys = || crate::state::rpf9_scan::rpf9_table::keys().ok(); + let keys = || crate::state::rpf9_scan::rpf9_table::keys(&rpf9).ok(); crate::state::gta6_meta_save::meta_bytes(&meta, keys) })); } @@ -66,7 +68,8 @@ fn row_item( // An edited text body is stored in the encoding and line endings it was read with. DocPayload::Text(text) if doc.dirty - && (doc.path.as_deref()).is_some_and(crate::state::rpf9_scan::opened_as_text) => + && (doc.path.as_deref()) + .is_some_and(|p| crate::state::rpf9_scan::opened_as_text(>a6.rpf9, p)) => { return Ok(ExtractItem::bytes(name, text.encode())); } @@ -108,9 +111,10 @@ impl AppState { match row_body(doc, &self.gta6) { Ok(body) => { self.say_the_checksum_is_kept(doc_id); + let rpf9 = self.gta6.rpf9.clone(); std::thread::spawn(move || { let body = body(); - ended().push((doc_id, path, at, row, body)); + ended(&rpf9).push((doc_id, path, at, row, body)); }); Some(true) } @@ -125,7 +129,7 @@ impl AppState { /// and bind the document to the row. pub(in crate::state) fn poll_tree_row_saves(&mut self) { let done: Vec = { - let mut list = ended(); + let mut list = ended(&self.gta6.rpf9); let (mine, rest) = std::mem::take(&mut *list) .into_iter() diff --git a/src/state/rpf/rpf_archive_open/tree_open/bind/tests.rs b/src/state/rpf/rpf_archive_open/tree_open/bind/tests.rs index b41796c33..ce76b4a2d 100644 --- a/src/state/rpf/rpf_archive_open/tree_open/bind/tests.rs +++ b/src/state/rpf/rpf_archive_open/tree_open/bind/tests.rs @@ -131,7 +131,7 @@ fn opened(state: &mut AppState, node: RpfNodeId) -> DocumentId { (place, start) }; let path = body_path(&place.file, place.offset, View::Bytes); - leave(&path, &place, start, synthetic_keys, None); + leave(&state.gta6.rpf9, &path, &place, start, synthetic_keys, None); name(state, &path, DOC, node); state.load_file(path.clone()); settle(state); @@ -251,7 +251,8 @@ fn a_text_row_of_the_build_saved_from_its_document_reads_back_from_a_patched_cop const ARCHIVES: usize = 8; const OPENS: usize = 48; let build = (std::env::var_os(BUILD_ENV).map(PathBuf::from)).filter(|p| p.is_dir()); - let keys = (build.as_ref()).and_then(|_| crate::state::rpf9_scan::rpf9_table::keys().ok()); + let rpf9 = crate::state::rpf::Rpf9Session::default(); + let keys = (build.as_ref()).and_then(|_| crate::state::rpf9_scan::rpf9_table::keys(&rpf9).ok()); let (Some(build), Some(keys)) = (build, keys) else { or_test_support::skip_install(WHAT, format_args!("set OPENRAGE_GTA6_KEYS and {BUILD_ENV}")); return; @@ -321,7 +322,7 @@ fn a_text_row_of_the_build_saved_from_its_document_reads_back_from_a_patched_cop }; let text = match state.document(doc).map(|d| (&d.payload, d.path.as_deref())) { Some((DocPayload::Text(text), Some(path))) - if crate::state::rpf9_scan::opened_as_text(path) => + if crate::state::rpf9_scan::opened_as_text(&state.gta6.rpf9, path) => { text.text.to_string() } diff --git a/src/state/rpf/rpf_archive_open/tree_open/mod.rs b/src/state/rpf/rpf_archive_open/tree_open/mod.rs index f81c21719..c1b1bf4df 100644 --- a/src/state/rpf/rpf_archive_open/tree_open/mod.rs +++ b/src/state/rpf/rpf_archive_open/tree_open/mod.rs @@ -13,10 +13,11 @@ use or_io::container::rpf::{ use or_io::gta6::other_bodies::OtherBody; use crate::state::document::{DocumentId, HexDocument, MetaDocument, RpfNodeId}; +use crate::state::rpf::Rpf9Session; use crate::state::{document_io, AppState, DocPayload, RpfEntryBinding}; /// Where the worker finds the keys the archive's tables open with. -pub(in crate::state) type Keys = fn() -> Result, String>; +pub(in crate::state) type Keys = Arc Result, String> + Send + Sync>; /// The most a row opened from the tree inflates to, as for a body opened from a scan's list. const LIMIT: u64 = 1 << 30; @@ -31,52 +32,56 @@ struct Row { edited: Option>>, } -/// The rows the tree left for the load worker, by the path their body opens under. -// ponytail: one map for the whole app, which no close empties; a row is a few words, and it stays -// so a reload of the body reads by its table again. -static ROWS: Mutex> = Mutex::new(BTreeMap::new()); +type NamedMap = BTreeMap; -fn rows() -> MutexGuard<'static, BTreeMap> { - ROWS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct TreeOpenCache { + rows: Arc>>, + named: Arc>, + copies: Arc>>, +} + +fn rows(rpf9: &Rpf9Session) -> MutexGuard<'_, BTreeMap> { + rpf9.tree_open + .rows + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Leave the read the load worker opens `path`, the body of `place`, with: the body `edited` a save into the row left, a ciphered row's decipher, or a clear row's table; a headerless resource's row, whose body starts past the slot at `row_start`, reads as a scan does. pub(in crate::state) fn leave( + rpf9: &Rpf9Session, path: &Path, place: &Rpf9Place, row_start: u64, - keys: Keys, + keys: impl Fn() -> Result, String> + Send + Sync + 'static, edited: Option>>, ) { let row = Row { base: place.base, entry: place.entry, - keys, + keys: Arc::new(keys), edited, }; if row.edited.is_some() { - crate::state::rpf9_scan::forget_ciphered(path); - rows().insert(path.to_path_buf(), row); + crate::state::rpf9_scan::forget_ciphered(rpf9, path); + rows(rpf9).insert(path.to_path_buf(), row); } else if place.ciphered { - rows().remove(path); - crate::state::rpf9_scan::remember_ciphered(path, place.base, place.entry); + rows(rpf9).remove(path); + crate::state::rpf9_scan::remember_ciphered(rpf9, path, place.base, place.entry); } else if place.offset == row_start { - crate::state::rpf9_scan::forget_ciphered(path); - rows().insert(path.to_path_buf(), row); + crate::state::rpf9_scan::forget_ciphered(rpf9, path); + rows(rpf9).insert(path.to_path_buf(), row); } else { // A row whose edit is gone reads what the file holds again. - crate::state::rpf9_scan::forget_ciphered(path); - rows().remove(path); + crate::state::rpf9_scan::forget_ciphered(rpf9, path); + rows(rpf9).remove(path); } } -/// A row the tree opened, by the path its body opens under: the path its document shows, as a -/// GTA V entry's does, and the row. -// ponytail: one map for the whole app, which no close empties, as the rows above. -static NAMED: Mutex> = Mutex::new(BTreeMap::new()); - -fn named() -> MutexGuard<'static, BTreeMap> { - NAMED +fn named(rpf9: &Rpf9Session) -> MutexGuard<'_, NamedMap> { + rpf9.tree_open + .named .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } @@ -97,29 +102,28 @@ pub(in crate::state) fn name(state: &AppState, path: &Path, parent: DocumentId, parent_doc_id: parent, entry_id: node, }; - named().insert(path.to_path_buf(), (shown, row)); + named(&state.gta6.rpf9).insert(path.to_path_buf(), (shown, row)); } /// The path the body at `path` shows once the tree opened it; `None` for any other path. -pub(in crate::state) fn shown(path: &Path) -> Option { - named().get(path).map(|(shown, _)| shown.clone()) +pub(in crate::state) fn shown(rpf9: &Rpf9Session, path: &Path) -> Option { + named(rpf9).get(path).map(|(shown, _)| shown.clone()) } /// The tree row the body at `path` was opened from, while the tree holding it is open. pub(in crate::state) fn row_of(state: &AppState, path: &Path) -> Option { - let row = named().get(path).map(|(_, row)| *row)?; + let row = named(&state.gta6.rpf9).get(path).map(|(_, row)| *row)?; state.document(row.parent_doc_id).is_some().then_some(row) } /// Show every body the tree `tree` opened under the copy `to` it became, in place of the archive `from`. // The body's own path stays its key: every read, origin and held edit of the body is keyed by it. -pub(in crate::state) fn follow_copy(tree: DocumentId, from: &Path, to: &Path) { - let mut copies = copies(); - for (body, (shown, row)) in named().iter_mut() { +pub(in crate::state) fn follow_copy(rpf9: &Rpf9Session, tree: DocumentId, from: &Path, to: &Path) { + let mut copies = copies(rpf9); + for (body, (shown, row)) in named(rpf9).iter_mut() { if row.parent_doc_id != tree { continue; } - // Ids repeat across apps of one process: only a body shown under this tree's archive moves. if let Ok(inner) = shown.strip_prefix(from) { *shown = to.join(inner); copies.insert(body.clone(), to.to_path_buf()); @@ -127,19 +131,16 @@ pub(in crate::state) fn follow_copy(tree: DocumentId, from: &Path, to: &Path) { } } -/// The copy on disk the body at `path` shows under since its tree was saved as one, kept so a -/// frame never asks the disk which part of the path is a file. -static COPIES: Mutex> = Mutex::new(BTreeMap::new()); - -fn copies() -> MutexGuard<'static, BTreeMap> { - COPIES +fn copies(rpf9: &Rpf9Session) -> MutexGuard<'_, BTreeMap> { + rpf9.tree_open + .copies .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// The archive file the body at `path` shows under after its tree was saved as a copy. -pub(in crate::state) fn copy_of(path: &Path) -> Option { - copies().get(path).cloned() +pub(in crate::state) fn copy_of(rpf9: &Rpf9Session, path: &Path) -> Option { + copies(rpf9).get(path).cloned() } /// What a row's read gives the views. @@ -154,20 +155,22 @@ pub(in crate::state) enum TableRead { /// The read of the row the tree left for `path`, whose body is at `offset` of the file at `archive`; `None` for a path no row was left for. pub(in crate::state) fn read( + rpf9: &Rpf9Session, path: &Path, archive: &Path, offset: u64, ) -> Option> { - let row = rows().get(path).cloned()?; + let row = rows(rpf9).get(path).cloned()?; if let Some(edited) = &row.edited { - return Some(read_edited(path, archive, offset, edited)); + return Some(read_edited(rpf9, path, archive, offset, edited)); } - Some(read_row(path, archive, offset, row)) + Some(read_row(rpf9, path, archive, offset, row)) } /// The body `edited` a save left in the row whose body is at `offset` of `archive`: a headerless /// resource's loose form read as a loose file is, any other body under the kind the file's start names. fn read_edited( + rpf9: &Rpf9Session, path: &Path, archive: &Path, offset: u64, @@ -185,11 +188,17 @@ fn read_edited( stated(&mut find, stored, edited); Ok(TableRead::Body(find, edited.to_vec())) } - Err(_) => Ok(TableRead::Plain(by_head(path, edited.to_vec()))), + Err(_) => Ok(TableRead::Plain(by_head(rpf9, path, edited.to_vec()))), } } -fn read_row(path: &Path, archive: &Path, offset: u64, row: Row) -> Result { +fn read_row( + rpf9: &Rpf9Session, + path: &Path, + archive: &Path, + offset: u64, + row: Row, +) -> Result { let keys = (row.keys)()?; let mut file = File::open(archive).map_err(|e| format!("{}: {e}", archive.display()))?; let mount = Gta6Mount { @@ -222,7 +231,7 @@ fn read_row(path: &Path, archive: &Path, offset: u64, row: Row) -> Result TableRead::Plain(by_head(path, bytes)), + Err(_) => TableRead::Plain(by_head(rpf9, path, bytes)), }) } @@ -255,9 +264,13 @@ fn stated(find: &mut Rpf9ScanFind, stored: u64, bytes: &[u8]) { } /// `bytes` opened by their head: metadata, text, else its bytes under the reason none reads them. -fn by_head(path: &Path, bytes: Vec) -> DocPayload { +fn by_head(rpf9: &Rpf9Session, path: &Path, bytes: Vec) -> DocPayload { if bytes.starts_with(b"PSIN") || bytes.starts_with(b"RBF0") { - return DocPayload::Meta(MetaDocument::from_bytes(bytes)); + return DocPayload::Meta(MetaDocument::from_bytes_with( + bytes, + Default::default(), + rpf9.clone(), + )); } if document_io::is_text(&bytes) { return crate::state::rpf9_scan::gta6_data_xml::payload(path, bytes); @@ -266,7 +279,7 @@ fn by_head(path: &Path, bytes: Vec) -> DocPayload { DocPayload::Hex(HexDocument { bytes, banner }) } -mod bind; +pub(crate) mod bind; #[cfg(test)] mod names_tests; @@ -291,10 +304,13 @@ mod tests { const MAX_DEPTH: usize = 3; const MAX_TRIES: usize = 400; + let gta6 = crate::state::gta6::session::Gta6Session::default(); let root = std::env::var_os(BUILD_ENV) .map(PathBuf::from) .filter(|p| p.is_dir()); - let keys = root.as_ref().and_then(|_| rpf9_table::keys().ok()); + let keys = root + .as_ref() + .and_then(|_| rpf9_table::keys(>a6.rpf9).ok()); let (Some(root), Some(keys)) = (root, keys) else { or_test_support::skip_install( "gta6 tree row open", @@ -372,8 +388,16 @@ mod tests { match shape { 0 => { let real = entry.real.expect("a chunked row states its size"); - leave(&path, &place, start, rpf9_table::keys, None); - let len = match read(&path, &disk, offset) { + let rpf9 = gta6.rpf9.clone(); + leave( + >a6.rpf9, + &path, + &place, + start, + move || rpf9_table::keys(&rpf9), + None, + ); + let len = match read(>a6.rpf9, &path, &disk, offset) { Some(Ok(TableRead::Body(f, _))) if is_resource(&f) => continue, Some(Ok(TableRead::Body(_, bytes))) => Some(bytes.len()), Some(Ok(TableRead::Plain(payload))) => match payload { @@ -391,14 +415,21 @@ mod tests { } } 1 => { - leave(&path, &place, start, rpf9_table::keys, None); - assert!(read(&path, &disk, offset).is_none()); - let gta6 = crate::state::gta6::session::Gta6Session::default(); + let rpf9 = gta6.rpf9.clone(); + leave( + >a6.rpf9, + &path, + &place, + start, + move || rpf9_table::keys(&rpf9), + None, + ); + assert!(read(>a6.rpf9, &path, &disk, offset).is_none()); if read_body(>a6, &path, &disk, offset).is_err() { continue; } let stated = nested.map_or(0, |n| n.stored_size()); - if let Some((find, _)) = scan_origin(&path) { + if let Some((find, _)) = scan_origin(>a6.rpf9, &path) { assert!( find.stored_len.is_none_or(|s| s + RPF9_SLOT <= stated), "row {}'s body lies inside the extent its row states", @@ -407,7 +438,9 @@ mod tests { } } _ => { - let Ok(bytes) = decipher_entry(&disk, mount.base, entry.index) else { + let Ok(bytes) = + decipher_entry(>a6.rpf9, &disk, mount.base, entry.index) + else { continue; }; if let Some(real) = entry.real { @@ -416,8 +449,15 @@ mod tests { } } // The read works, so the open does. - leave(&path, &place, start, rpf9_table::keys, None); - let gta6 = crate::state::gta6::session::Gta6Session::default(); + let rpf9 = gta6.rpf9.clone(); + leave( + >a6.rpf9, + &path, + &place, + start, + move || rpf9_table::keys(&rpf9), + None, + ); if let Err(e) = read_body(>a6, &path, &disk, offset) { panic!("{}: row {} opens: {e}", disk.display(), entry.index); } diff --git a/src/state/rpf/rpf_archive_open/tree_open/names_tests.rs b/src/state/rpf/rpf_archive_open/tree_open/names_tests.rs index d4478c1f5..191ad0093 100644 --- a/src/state/rpf/rpf_archive_open/tree_open/names_tests.rs +++ b/src/state/rpf/rpf_archive_open/tree_open/names_tests.rs @@ -118,9 +118,10 @@ fn rows_of_a_real_archive_opened_from_the_tree_are_named_by_their_rows() { const WHAT: &str = "gta6 tree row names"; const ROWS: usize = 3; let build = (std::env::var_os(BUILD_ENV).map(PathBuf::from)).filter(|p| p.is_dir()); + let rpf9 = crate::state::rpf::Rpf9Session::default(); let keys = build .as_ref() - .and_then(|_| crate::state::rpf9_scan::rpf9_table::keys().ok()); + .and_then(|_| crate::state::rpf9_scan::rpf9_table::keys(&rpf9).ok()); let (Some(build), Some(keys)) = (build, keys) else { let why = format_args!("set OPENRAGE_GTA6_KEYS and {BUILD_ENV}"); or_test_support::skip_install(WHAT, why); diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/adopt/archive_size_tests.rs b/src/state/rpf/rpf_archive_open/tree_verbs/adopt/archive_size_tests.rs index 60a31bff4..9015f7557 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/adopt/archive_size_tests.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/adopt/archive_size_tests.rs @@ -16,7 +16,9 @@ fn details_sizes_a_nested_archive_as_its_column_does_past_4_gib_too() { const WHAT: &str = "Details sizes a nested GTA VI archive as its column does"; let _serial = crate::ui::theme::serial(); let build_root = std::env::var_os("OPENRAGE_GTA6_BUILD").map(PathBuf::from); - let (Some(build_root), Ok(keys)) = (build_root, crate::state::rpf9_scan::rpf9_table::keys()) + let rpf9 = crate::state::rpf::Rpf9Session::default(); + let (Some(build_root), Ok(keys)) = + (build_root, crate::state::rpf9_scan::rpf9_table::keys(&rpf9)) else { or_test_support::skip_install(WHAT, "set OPENRAGE_GTA6_BUILD and OPENRAGE_GTA6_KEYS"); return; diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/adopt/mod.rs b/src/state/rpf/rpf_archive_open/tree_verbs/adopt/mod.rs index 59c7d82ad..c433addb1 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/adopt/mod.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/adopt/mod.rs @@ -121,7 +121,12 @@ pub(super) fn reopened( /// Make the tree `doc` the copy `written` at `out`, named for it; false, the tree left as it was, /// where the copy holds no entry of a row's path. -pub(super) fn become_copy(doc: &mut Document, written: Reopened, out: &Path) -> bool { +pub(super) fn become_copy( + rpf9: &crate::state::rpf::Rpf9Session, + doc: &mut Document, + written: Reopened, + out: &Path, +) -> bool { let DocPayload::Rpf(rpf) = &mut doc.payload else { return false; }; @@ -150,7 +155,7 @@ pub(super) fn become_copy(doc: &mut Document, written: Reopened, out: &Path) -> } rpf.session = session; if let Some(from) = &doc.path { - crate::state::rpf_archive_open::tree_open::follow_copy(doc.id, from, out); + crate::state::rpf_archive_open::tree_open::follow_copy(rpf9, doc.id, from, out); } doc.path = Some(out.to_path_buf()); if let Some(stem) = out.file_stem().and_then(|s| s.to_str()) { diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/adopt/tests.rs b/src/state/rpf/rpf_archive_open/tree_verbs/adopt/tests.rs index 44b21857a..f5b1b6a62 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/adopt/tests.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/adopt/tests.rs @@ -106,7 +106,7 @@ fn opened(state: &mut AppState, node: RpfNodeId) -> DocumentId { (place, start) }; let path = body_path(&place.file, place.offset, View::Bytes); - leave(&path, &place, start, synthetic_keys, None); + leave(&state.gta6.rpf9, &path, &place, start, synthetic_keys, None); name(state, &path, DOC, node); state.load_file(path.clone()); let deadline = Instant::now() + Duration::from_secs(30); @@ -150,9 +150,10 @@ fn a_row_s_document_follows_its_tree_into_the_copy_and_its_next_save_lands_in_th std::fs::copy(&disk, &out).expect("the copy is written"); let chains = listed(session(&state)); let written = reopened(&out, gta6_session::crypto(), &chains).expect("the copy reopens"); + let rpf9 = state.gta6.rpf9.clone(); let tree = state.document_mut(DOC).expect("the tree"); assert!( - become_copy(tree, written, &out), + become_copy(&rpf9, tree, written, &out), "the tree becomes the copy" ); diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs b/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs index c663059d2..9c803c4de 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/headerless_tests/saves_per_kind/mod.rs @@ -299,7 +299,7 @@ fn kind_of( "particles" } DocPayload::Meta(meta) => { - if let Some(Ok(body)) = crate::state::gta6_map::opened_map(path) { + if let Some(Ok(body)) = crate::state::gta6_map::opened_map(>a6.world, path) { return Some(match &*body { MapBody::Data(_) => "map data", MapBody::Types(_) => "map types", @@ -814,7 +814,8 @@ fn kept(census: &[Walked], settled: &HashSet) -> HashSet { fn every_kind_the_app_edits_saved_through_its_tree_row_of_the_build_plans_patched_or_says_why() { let began = Instant::now(); let build = (std::env::var_os(BUILD_ENV).map(PathBuf::from)).filter(|p| p.is_dir()); - let keys = (build.as_ref()).and_then(|_| crate::state::rpf9_scan::rpf9_table::keys().ok()); + let rpf9 = crate::state::rpf::Rpf9Session::default(); + let keys = (build.as_ref()).and_then(|_| crate::state::rpf9_scan::rpf9_table::keys(&rpf9).ok()); let (Some(build), Some(keys)) = (build, keys) else { or_test_support::skip_install(WHAT, format_args!("set OPENRAGE_GTA6_KEYS and {BUILD_ENV}")); return; diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/mod.rs b/src/state/rpf/rpf_archive_open/tree_verbs/mod.rs index 1e87c7571..49ce98c70 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/mod.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/mod.rs @@ -26,13 +26,11 @@ use crate::platform::file_dialogs; use crate::state::document::{ArchiveId, DocumentId, RpfNodeId}; use crate::state::extract_job::{plan, ExtractItem, TypeFilter}; use crate::state::jobs::{JobKind, Outcome, Then}; +use crate::state::rpf::Rpf9Session; use crate::state::rpf_node::{ArchiveSource, RpfNodeBacking}; use crate::state::rpf_session::RpfEditSession; use crate::state::{AppState, DocPayload}; -/// Where a save finds the keys the archive's tables open with. -type Keys = fn() -> Result, String>; - /// How a save of a tree ended: its document, the edit it was at, the new file, and how it was /// written with the file read back as an archive where it reopens, or why it was refused. type Ended = ( @@ -264,15 +262,22 @@ struct Plan { planned: Planned, } -// ponytail: lists for the process, emptied by the next frame's poll: the saves that ended, the plans -// whose question has not been asked, the plan whose question waits on its answer (one at a time, a -// later plan taking its place), and the plan whose dialog picked the file the save writes. -static ENDED: Mutex> = Mutex::new(Vec::new()); -static PLANNED: Mutex)>> = Mutex::new(Vec::new()); -static ASKED: Mutex> = Mutex::new(None); -static HELD: Mutex> = Mutex::new(None); +type PlannedList = Vec<(DocumentId, Result)>; + +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct TreeVerbsCache { + ended: Arc>>, + planned: Arc>, + asked: Arc>>, + held: Arc>>, +} -fn lock(list: &'static Mutex) -> MutexGuard<'static, T> { +#[cfg(test)] +fn push_ended(rpf9: &Rpf9Session, entry: Ended) { + lock(&rpf9.tree_verbs.ended).push(entry); +} + +fn lock(list: &Mutex) -> MutexGuard<'_, T> { list.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } @@ -626,13 +631,16 @@ pub(crate) fn write_plan( /// Plan the archive at `source` with `edits` made as a job the list shows, reading only, then write /// it into the new file `out` as planned, as the same job. fn write_tree( + rpf9: &Rpf9Session, source: &Path, edits: &[Edit], out: &Path, keys: &GtaViKeys, ) -> Result { - let planned = plan_job::tracked(source, |tick| plan_tree_with(source, edits, keys, tick))?; - plan_job::tracked_write(source, out, |tick| { + let planned = plan_job::tracked(rpf9, source, |tick| { + plan_tree_with(source, edits, keys, tick) + })?; + plan_job::tracked_write(rpf9, source, out, |tick| { write_planned_with(source, out, keys, &planned, tick) }) } @@ -736,10 +744,18 @@ impl AppState { doc_id: DocumentId, out: &Path, ) -> Option { - self.save_gta6_tree_with(doc_id, out, crate::state::rpf9_scan::rpf9_table::keys) + let rpf9 = self.gta6.rpf9.clone(); + self.save_gta6_tree_with(doc_id, out, move || { + crate::state::rpf9_scan::rpf9_table::keys(&rpf9) + }) } - fn save_gta6_tree_with(&mut self, doc_id: DocumentId, out: &Path, keys: Keys) -> Option { + fn save_gta6_tree_with( + &mut self, + doc_id: DocumentId, + out: &Path, + keys: impl FnOnce() -> Result, String> + Send + 'static, + ) -> Option { let doc = self.document(doc_id)?; let DocPayload::Rpf(rpf) = &doc.payload else { return None; @@ -761,19 +777,20 @@ impl AppState { } }; // The plan the dialog showed is the one written; a save asked with no dialog plans first. - let held = (lock(&HELD).take()) + let held = (lock(&self.gta6.rpf9.tree_verbs.held).take()) .filter(|plan| plan.doc_id == doc_id && plan.at == at && plan.source == source); let out = out.to_path_buf(); + let rpf9 = self.gta6.rpf9.clone(); std::thread::spawn(move || { let said = match held { - Some(plan) => plan_job::tracked_write(&source, &out, |tick| { + Some(plan) => plan_job::tracked_write(&rpf9, &source, &out, |tick| { write_planned_with(&source, &out, &plan.keys, &plan.planned, tick) }), None => (keys().map_err(Unplanned::Refused)) - .and_then(|keys| write_tree(&source, &edits, &out, &keys)), + .and_then(|keys| write_tree(&rpf9, &source, &edits, &out, &keys)), }; let said = said.map(|saved| (saved, adopt::reopened(&out, crypto, &listed))); - lock(&ENDED).push((doc_id, at, out, said)); + lock(&rpf9.tree_verbs.ended).push((doc_id, at, out, said)); }); Some(true) } @@ -781,7 +798,10 @@ impl AppState { /// Plan a save of the GTA VI tree `doc_id` on a worker, writing nothing, for the next poll to say /// in the save dialog; false for any other document. pub(crate) fn plan_gta6_tree_save(&self, doc_id: DocumentId) -> bool { - self.plan_tree_save(doc_id, crate::state::rpf9_scan::rpf9_table::keys) + let rpf9 = self.gta6.rpf9.clone(); + self.plan_tree_save(doc_id, move || { + crate::state::rpf9_scan::rpf9_table::keys(&rpf9) + }) } fn plan_tree_save( @@ -801,10 +821,11 @@ impl AppState { }; let at = doc.history.at(); let edits = tree_edits(&rpf.session); + let rpf9 = self.gta6.rpf9.clone(); std::thread::spawn(move || { let plan = edits.map_err(Unplanned::from).and_then(|edits| { let keys = keys()?; - let planned = plan_job::tracked(&source, |tick| { + let planned = plan_job::tracked(&rpf9, &source, |tick| { plan_tree_with(&source, &edits, &keys, tick) })?; Ok(Plan { @@ -815,7 +836,7 @@ impl AppState { planned, }) }); - lock(&PLANNED).push((doc_id, plan)); + lock(&rpf9.tree_verbs.planned).push((doc_id, plan)); }); true } @@ -823,7 +844,7 @@ impl AppState { /// The short title and the full sentence of the planned save whose question waits, for a tree /// this app shows. pub(crate) fn planned_save_question(&self) -> Option<(&'static str, String)> { - let asked = lock(&ASKED); + let asked = lock(&self.gta6.rpf9.tree_verbs.asked); let plan = asked.as_ref().filter(|p| self.shows(p))?; let file = crate::state::jobs::file_name(&plan.source); let title = planned_title(&plan.planned); @@ -837,7 +858,7 @@ impl AppState { /// Answer the planned save's question: `go` asks where the copy goes and writes it there. pub(crate) fn answer_planned_save(&mut self, go: bool) { - let plan = lock(&ASKED).take_if(|p| self.shows(p)); + let plan = lock(&self.gta6.rpf9.tree_verbs.asked).take_if(|p| self.shows(p)); let Some(plan) = plan.filter(|_| go) else { return; }; @@ -849,7 +870,7 @@ impl AppState { return; }; let doc_id = plan.doc_id; - *lock(&HELD) = Some(plan); + *lock(&self.gta6.rpf9.tree_verbs.held) = Some(plan); // Save as… asks what every save asks, the retail gate included, then writes the plan held. let previous = self.active_document.replace(doc_id); self.save_active_document_as(out); @@ -859,8 +880,7 @@ impl AppState { /// Hold each tree's save planned for its question, which says what the save writes and why. fn ask_where_planned_saves_go(&mut self) { let arrived: Vec<_> = { - let mut planned = lock(&PLANNED); - // ponytail: a plan of another app's document is left for that app's poll. + let mut planned = lock(&self.gta6.rpf9.tree_verbs.planned); let (here, others): (Vec<_>, Vec<_>) = (std::mem::take(&mut *planned).into_iter()) .partition(|(doc_id, _)| self.document(*doc_id).is_some()); *planned = others; @@ -891,7 +911,7 @@ impl AppState { self.plan_tree_save(doc_id, move || Ok(keys)); continue; } - *lock(&ASKED) = Some(plan); + *lock(&self.gta6.rpf9.tree_verbs.asked) = Some(plan); } } @@ -899,7 +919,7 @@ impl AppState { pub(in crate::state) fn poll_tree_saves(&mut self) { self.ask_where_planned_saves_go(); let done: Vec<_> = { - let mut ended = lock(&ENDED); + let mut ended = lock(&self.gta6.rpf9.tree_verbs.ended); // A save of another app's document is left for that app's poll, as a plan is. let (here, others): (Vec<_>, Vec<_>) = (std::mem::take(&mut *ended).into_iter()) .partition(|(doc_id, ..)| self.document(*doc_id).is_some()); @@ -927,9 +947,10 @@ impl AppState { }; // The tree becomes the new file, which holds its edits; one that cannot keeps every edit // marked, and one edited since the save began stays unsaved. + let rpf9 = self.gta6.rpf9.clone(); if let Some(doc) = self.document_mut(doc_id) { let current = doc.history.at() == at; - if !current || copy.is_some_and(|copy| adopt::become_copy(doc, copy, &out)) { + if !current || copy.is_some_and(|copy| adopt::become_copy(&rpf9, doc, copy, &out)) { doc.saved_as_of(at); } } diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/plan_job.rs b/src/state/rpf/rpf_archive_open/tree_verbs/plan_job.rs index a69499837..426fa1625 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/plan_job.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/plan_job.rs @@ -11,6 +11,7 @@ use or_job::{Cancel, Progress}; use super::{lock, stored_body, Planned, Replaced}; use crate::state::jobs::{file_name, JobKind, RunningJob}; +use crate::state::rpf::Rpf9Session; /// What a plan tells its job: the row in hand, and the bytes planned of all; `false` stops it. pub(crate) type Tick<'a> = &'a mut dyn FnMut(&str, u64, u64) -> bool; @@ -43,25 +44,29 @@ struct Planning { progress: Progress, } -// ponytail: a list for the process, as the save's own lists are; each plan leaves it as it ends. -static PLANNING: Mutex>> = Mutex::new(Vec::new()); +#[derive(Clone, Default)] +pub(in crate::state::rpf) struct PlanJobCache(Arc>>>); -/// Takes its plan out of [`PLANNING`] however the plan ends, a panic included. -struct Listed(Arc); +/// Takes its plan out of its session's planning list however the plan ends, a panic included. +struct Listed { + list: Arc>>>, + job: Arc, +} impl Drop for Listed { fn drop(&mut self) { - lock(&PLANNING).retain(|job| !Arc::ptr_eq(job, &self.0)); + lock(&self.list).retain(|job| !Arc::ptr_eq(job, &self.job)); } } /// Run `plan` of a save of the archive at `source` as a job the list shows, telling it the row in /// hand and the bytes planned; a stop ends it as [`Unplanned::Stopped`], whatever it returned. pub(super) fn tracked( + rpf9: &Rpf9Session, source: &Path, plan: impl FnOnce(Tick<'_>) -> Result, ) -> Result { - run_listed(source, None, |job| { + run_listed(rpf9, source, None, |job| { plan(&mut |row: &str, done: u64, total: u64| { job.progress.now_on(row); job.progress.reached(done, total); @@ -73,11 +78,12 @@ pub(super) fn tracked( /// Run `write` of a planned save into the new file `out` as the same job, telling it the bytes /// written of all; a stop ends it as [`Unplanned::Stopped`] and leaves no file at `out`. pub(super) fn tracked_write( + rpf9: &Rpf9Session, source: &Path, out: &Path, write: impl FnOnce(&mut dyn FnMut(u64, u64) -> bool) -> Result, ) -> Result { - run_listed(source, Some(out), |job| { + run_listed(rpf9, source, Some(out), |job| { let written = write(&mut |done: u64, total: u64| { job.progress.reached(done, total); !job.cancel.is_set() @@ -93,6 +99,7 @@ pub(super) fn tracked_write( /// Plan `replaced` into the archive at `source`, then write it into the new file `out`, each as the /// job a tree's save is; a stop ends it as [`Unplanned::Stopped`] and leaves no file at `out`. pub(crate) fn save_tracked( + rpf9: &Rpf9Session, source: &Path, out: &Path, keys: &GtaViKeys, @@ -100,16 +107,17 @@ pub(crate) fn save_tracked( writer: Rpf9ArchiveWriter, ) -> Result { let cap = SAVE_OPTIMAL_CAP; - let planned = tracked(source, |tick| { + let planned = tracked(rpf9, source, |tick| { plan_save_with(source, keys, replaced, Vec::new(), writer, cap, tick) })?; - tracked_write(source, out, |tick| { + tracked_write(rpf9, source, out, |tick| { super::write_planned_with(source, out, keys, &planned, tick) }) } /// Run `run` as a job the list shows while it runs; a stop ends it as [`Unplanned::Stopped`]. fn run_listed( + rpf9: &Rpf9Session, source: &Path, writing: Option<&Path>, run: impl FnOnce(&Planning) -> Result, @@ -120,18 +128,19 @@ fn run_listed( cancel: Cancel::new(), progress: Progress::new(), }); - lock(&PLANNING).push(Arc::clone(&job)); - let listed = Listed(job); - let ran = run(&listed.0); - if listed.0.cancel.is_set() { + let list = Arc::clone(&rpf9.plan_job.0); + lock(&list).push(Arc::clone(&job)); + let listed = Listed { list, job }; + let ran = run(&listed.job); + if listed.job.cancel.is_set() { return Err(Unplanned::Stopped); } ran.map_err(Unplanned::Refused) } /// Each save being planned or written, as the job list draws it. -pub(in crate::state) fn jobs() -> Vec { - (lock(&PLANNING).iter()) +pub(in crate::state) fn jobs(rpf9: &Rpf9Session) -> Vec { + (lock(&rpf9.plan_job.0).iter()) .map(|job| { let at = job.progress.snapshot(); let (done, total) = ( @@ -177,8 +186,10 @@ pub(in crate::state) fn jobs() -> Vec { } /// Stop every save being planned or written: each ends within a part of the optimal parse or of the copy, and leaves no file. -pub(in crate::state) fn stop() { - lock(&PLANNING).iter().for_each(|job| job.cancel.set()); +pub(in crate::state) fn stop(rpf9: &Rpf9Session) { + lock(&rpf9.plan_job.0) + .iter() + .for_each(|job| job.cancel.set()); } /// How far `got` bytes are from the `want` a row or a chunk states. @@ -304,7 +315,7 @@ mod tests { use super::super::tests::{ archive_of, listed, reading_with, row_holding, showing, synthetic_keys, tree, DOC, }; - use super::super::{plan_tree_with, tree_edits, write_planned_with, Edit, ENDED}; + use super::super::{plan_tree_with, push_ended, tree_edits, write_planned_with, Edit}; use super::*; use crate::state::jobs::{Outcome, Then}; use crate::state::rpf_session::RpfDocument; @@ -343,10 +354,11 @@ mod tests { plan_tree_with(&path, &edits, &keys, &mut |_, _, _| true).expect("the save plans"); let out = dir.path().join("copy.rpf"); - let stopped = tracked_write(&path, &out, |tick| { + let rpf9 = Rpf9Session::default(); + let stopped = tracked_write(&rpf9, &path, &out, |tick| { write_planned_with(&path, &out, &keys, &planned, &mut |done, total| { // Stopped as Cancel on the job's row stops it. - stop(); + stop(&rpf9); tick(done, total) }) }); @@ -355,11 +367,17 @@ mod tests { "{:?}", stopped.err() ); - assert!(jobs().is_empty(), "a stopped write leaves the job list"); + assert!( + jobs(&rpf9).is_empty(), + "a stopped write leaves the job list" + ); assert_eq!(listed(dir.path()), ["source.rpf"], "and no file"); let mut state = showing(path.clone(), tree); - lock(&ENDED).push((DOC, 0, out.clone(), Err(Unplanned::Stopped))); + push_ended( + &state.gta6.rpf9, + (DOC, 0, out.clone(), Err(Unplanned::Stopped)), + ); state.poll_archive_saves(); let ended = state.jobs.ended().first().map(|e| e.outcome.clone()); assert_eq!(ended, Some(Outcome::Stopped(Then::Nothing))); diff --git a/src/state/rpf/rpf_archive_open/tree_verbs/tests.rs b/src/state/rpf/rpf_archive_open/tree_verbs/tests.rs index b317dec1a..8d418b8ea 100644 --- a/src/state/rpf/rpf_archive_open/tree_verbs/tests.rs +++ b/src/state/rpf/rpf_archive_open/tree_verbs/tests.rs @@ -420,7 +420,8 @@ fn a_small_clear_row_of_a_real_archive_replaced_into_a_copy_reads_back() { let edits = tree_edits(&tree.session).expect("the tree's edits"); let dir = tempfile::tempdir().expect("a scratch directory"); let out = dir.path().join("copy.rpf"); - write_tree(path, &edits, &out, &keys).expect("the copy is written"); + write_tree(&Rpf9Session::default(), path, &edits, &out, &keys) + .expect("the copy is written"); let mut copy = File::open(&out).expect("the copy"); let mount = Gta6Mount::open_root(&mut copy, &keys).expect("the copy opens"); let entry = (mount.archive.entries.iter()) diff --git a/src/state/tests/opening_an_rpf9_archive.rs b/src/state/tests/opening_an_rpf9_archive.rs index b05551720..f64315bab 100644 --- a/src/state/tests/opening_an_rpf9_archive.rs +++ b/src/state/tests/opening_an_rpf9_archive.rs @@ -339,10 +339,14 @@ fn a_body_of_a_gta_vi_archive_is_of_no_gta_v_edition_and_does_not_convert() { .filter(|&d| d != archive) .expect("the body opens"); let path = state.document(doc).and_then(|d| d.path.clone()); - assert!(crate::state::rpf9_scan::from_gta_vi(path.as_deref())); + assert!(crate::state::rpf9_scan::from_gta_vi( + &state.gta6.rpf9, + path.as_deref() + )); let refused = state.document_conversion_to(doc).unwrap_err(); assert!(refused.contains("neither GTA V edition"), "{refused}"); - assert!(!crate::state::rpf9_scan::from_gta_vi(Some(Path::new( - "loose.ytd" - )))); + assert!(!crate::state::rpf9_scan::from_gta_vi( + &state.gta6.rpf9, + Some(Path::new("loose.ytd")) + )); } diff --git a/src/state/viewport_camera.rs b/src/state/viewport_camera.rs index 2f63a04ab..b8bb65f4c 100644 --- a/src/state/viewport_camera.rs +++ b/src/state/viewport_camera.rs @@ -62,7 +62,9 @@ impl AppState { if self.active_workspace == crate::state::Workspace::World { self.cameras.world = match self.world.session() { Some(session) => session.camera().as_orbit(), - None => super::gta6_world::worldview::viewer().camera.as_orbit(), + None => super::gta6_world::worldview::viewer(&self.gta6.world) + .camera + .as_orbit(), }; return &self.cameras.world; } diff --git a/src/state/world_session/gta6.rs b/src/state/world_session/gta6.rs index 2743765fb..25cee75dd 100644 --- a/src/state/world_session/gta6.rs +++ b/src/state/world_session/gta6.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, MutexGuard}; +use std::sync::{Arc, Mutex}; use or_renderer::FlyCamera; use or_world::caps::{Capability, WorldCaps}; @@ -31,8 +31,8 @@ type Answer = Result, PickError>; /// The session of a GTA VI build's folder. pub struct Gta6Session { key: WorldKey, - /// The viewer it is a shell over: the one of the process. - viewer: fn() -> MutexGuard<'static, Viewer>, + /// The viewer it is a shell over: the owning `AppState`'s world session. + world: crate::state::gta6::world::WorldSession, picking: Picking, /// What the bridge tints, as the viewer is told at each poll. tinted: Option, @@ -59,18 +59,22 @@ pub struct Gta6Session { } impl Gta6Session { - pub(crate) fn new(key: WorldKey, install: crate::state::gta6::install::InstallSession) -> Self { + pub(crate) fn new( + key: WorldKey, + install: crate::state::gta6::install::InstallSession, + world: crate::state::gta6::world::WorldSession, + ) -> Self { Self { install, - ..Self::over(key, viewer) + ..Self::over(key, world) } } - /// The session of `key` as a shell over the viewer `viewer` gives. - pub(crate) fn over(key: WorldKey, viewer: fn() -> MutexGuard<'static, Viewer>) -> Self { + /// The session of `key` as a shell over the viewer of `world`. + pub(crate) fn over(key: WorldKey, world: crate::state::gta6::world::WorldSession) -> Self { Self { key, - viewer, + world, picking: Picking::Nothing, tinted: None, kind: None, @@ -162,7 +166,7 @@ impl WorldSession for Gta6Session { fn poll(&mut self) { self.take_answer(); - let mut viewer = (self.viewer)(); + let mut viewer = viewer(&self.world); viewer.open(&self.key.install); viewer.poll(); // ⚠ After the open: a viewer opened on another install is made anew, with nothing picked. @@ -187,7 +191,7 @@ impl WorldSession for Gta6Session { } fn standing(&self) -> Standing { - let viewer = (self.viewer)(); + let viewer = viewer(&self.world); match (viewer.building(), &viewer.failed) { (Some(done), _) => Standing::Opening(done), (None, Some(why)) => Standing::Failed(why.clone()), @@ -205,23 +209,23 @@ impl WorldSession for Gta6Session { } fn camera(&self) -> FlyCamera { - (self.viewer)().camera.clone() + viewer(&self.world).camera.clone() } fn set_camera(&mut self, camera: FlyCamera) { - (self.viewer)().camera = camera; + viewer(&self.world).camera = camera; } fn hour(&self) -> f32 { - (self.viewer)().hour + viewer(&self.world).hour } fn set_hour(&mut self, hour: f32) { - (self.viewer)().hour = hour; + viewer(&self.world).hour = hour; } fn waiting(&self) -> Waiting { - let viewer = (self.viewer)(); + let viewer = viewer(&self.world); Waiting { maps: viewer.streaming().maps_waiting, models: viewer.models_waiting, @@ -241,7 +245,7 @@ impl WorldSession for Gta6Session { fn click(&mut self, ray: Ray) { self.asked += 1; // With no world selected yet there is nothing to click. - let Some(standing) = (self.viewer)().pick_standing() else { + let Some(standing) = viewer(&self.world).pick_standing() else { self.open = false; return; }; @@ -261,7 +265,7 @@ impl WorldSession for Gta6Session { self.asked += 1; (self.picking, self.tinted, self.body, self.open) = (Picking::Nothing, None, None, false); (self.kind, self.shift, self.settling) = (None, None, false); - let mut viewer = (self.viewer)(); + let mut viewer = viewer(&self.world); (viewer.picked, viewer.picked_shift) = (None, None); } @@ -290,11 +294,11 @@ impl WorldSession for Gta6Session { if self.shift.is_none() { self.settling = false; } - (self.viewer)().picked_shift = self.shift; + viewer(&self.world).picked_shift = self.shift; } fn renumbered_with(&self, path: &Path, parent: Option) -> Option> { - let viewer = (self.viewer)(); + let viewer = viewer(&self.world); let index = viewer.index.as_ref()?; let (archive, offset) = body_of(path)?; let at = index.archives.iter().position(|a| a == archive)?; @@ -320,7 +324,7 @@ impl WorldSession for Gta6Session { fn lay_document(&mut self, path: &Path, tree: Option>) -> Result<(), String> { let no_map = || tr!("The world holds no map of this document").to_string(); - let mut viewer = (self.viewer)(); + let mut viewer = viewer(&self.world); // ⚠ With no world yet, as while its index is built, nothing is laid and nothing forgotten: the world that comes is laid afresh. let Some(world) = viewer.world() else { return Ok(()); @@ -437,7 +441,7 @@ mod tests { install: PathBuf::from("a-build"), options: Vec::new(), }; - let mut session = Gta6Session::over(key, viewer); + let mut session = Gta6Session::over(key, Default::default()); // Two clicks, the second still open; its thread ends first, then the first's. (session.asked, session.open) = (2, true); answered(&session.answer, 2, Ok(None)); diff --git a/src/state/world_session/mod.rs b/src/state/world_session/mod.rs index 5510eedee..430a68c0f 100644 --- a/src/state/world_session/mod.rs +++ b/src/state/world_session/mod.rs @@ -413,7 +413,11 @@ impl AppState { self.world.drop_session(); if let Some(key) = wanted { let session: Box = match key.game.is_gta_vi() { - true => Box::new(gta6::Gta6Session::new(key, self.gta6.install.clone())), + true => Box::new(gta6::Gta6Session::new( + key, + self.gta6.install.clone(), + self.gta6.world.clone(), + )), false => Box::new(driven::DrivenSession::of_install(key, &self.prefs)), }; self.world.hold(session); diff --git a/src/ui/panels/hierarchy/gta6/drawable.rs b/src/ui/panels/hierarchy/gta6/drawable.rs index 13546eefb..af3aa6e38 100644 --- a/src/ui/panels/hierarchy/gta6/drawable.rs +++ b/src/ui/panels/hierarchy/gta6/drawable.rs @@ -42,7 +42,11 @@ fn outline_of<'a>(d: &'a Drawable, bones: Option>) -> DrawableOutli } /// The bone names of `doc`'s scanned skeleton, kept while its payload is the same. -fn bone_names(ui: &egui::Ui, doc: &Document) -> Option>> { +fn bone_names( + ui: &egui::Ui, + rpf9: &crate::state::rpf::Rpf9Session, + doc: &Document, +) -> Option>> { let id = egui::Id::new(("gta6_outline_bones", doc.id)); let epoch = doc.payload_epoch(); type Kept = (u64, Option>>); @@ -51,7 +55,7 @@ fn bone_names(ui: &egui::Ui, doc: &Document) -> Option>> { return names; } } - let skeleton = crate::state::rpf9_scan::scanned_skeleton(doc.path.as_deref()?).ok(); + let skeleton = crate::state::rpf9_scan::scanned_skeleton(rpf9, doc.path.as_deref()?).ok(); let names = skeleton.map(|s| Arc::new(s.bones.into_iter().map(|b| b.name).collect())); ui.data_mut(|d| d.insert_temp(id, (epoch, names.clone()))); names @@ -116,7 +120,7 @@ pub(crate) fn draw_gta6_drawable(ui: &mut egui::Ui, state: &mut AppState, doc_id return; }; let resource = Arc::clone(resource); - let bones = bone_names(ui, doc); + let bones = bone_names(ui, &state.gta6.rpf9, doc); let drawable = match &*resource { Resource::Drawable(d) => d, Resource::DrawableWithBound(r) => &r.drawable, diff --git a/src/ui/panels/hierarchy/gta6/install.rs b/src/ui/panels/hierarchy/gta6/install.rs index a03985713..25c44492d 100644 --- a/src/ui/panels/hierarchy/gta6/install.rs +++ b/src/ui/panels/hierarchy/gta6/install.rs @@ -23,7 +23,7 @@ pub(crate) fn draw(ui: &mut egui::Ui, state: &mut AppState, doc: DocumentId) { if !is_gta_vi(ui, &root) { return; } - fallback(ui, state, &root, >a6_keys()); + fallback(ui, state, &root, >a6_keys(&state.gta6.rpf9)); } /// The scan and the harvest over the folder at `root`, drawn only while `keys` says none is held: diff --git a/src/ui/panels/inspector/gta6/anim/play.rs b/src/ui/panels/inspector/gta6/anim/play.rs index 63a15be96..20085246b 100644 --- a/src/ui/panels/inspector/gta6/anim/play.rs +++ b/src/ui/panels/inspector/gta6/anim/play.rs @@ -109,13 +109,8 @@ fn unjoined_lines(state: &AppState, model: &mut Model) -> Vec { state.preview_scene.lod, ); if model.unjoined.as_ref().is_none_or(|(k, _)| *k != key) { - let found = crate::render::gta6_drawable::unjoined( - &state.gta6.anim, - doc, - selection, - key.3, - skeleton, - ); + let found = + crate::render::gta6_drawable::unjoined(&state.gta6, doc, selection, key.3, skeleton); let lines = found .iter() .map(|(m, g, why)| { diff --git a/src/ui/panels/inspector/gta6/drawable/bone_edit.rs b/src/ui/panels/inspector/gta6/drawable/bone_edit.rs index 9fceb0adc..36d002534 100644 --- a/src/ui/panels/inspector/gta6/drawable/bone_edit.rs +++ b/src/ui/panels/inspector/gta6/drawable/bone_edit.rs @@ -39,7 +39,7 @@ pub(super) fn draw( let shown = match ui.data(|d| d.get_temp::(id)) { Some((s, shown)) if s == stamp => shown, _ => { - let skeleton = shown_skeleton(&state.gta6.anim, doc, selection); + let skeleton = shown_skeleton(&state.gta6, doc, selection); let shown = skeleton.and_then(|s| { let b = s.bones.get(bone)?; let [x, y, z, w] = b.rotation; diff --git a/src/ui/panels/inspector/gta6/drawable/head.rs b/src/ui/panels/inspector/gta6/drawable/head.rs index 46b387f01..1213545d3 100644 --- a/src/ui/panels/inspector/gta6/drawable/head.rs +++ b/src/ui/panels/inspector/gta6/drawable/head.rs @@ -13,7 +13,7 @@ const SWATCH: f32 = 6.0; pub(super) fn draw(ui: &mut egui::Ui, state: &AppState, doc_id: DocumentId) { let Some(head) = (state.document(doc_id)) .and_then(|d| d.path.as_deref()) - .and_then(head_of) + .and_then(|p| head_of(&state.gta6.drawable, p)) else { return; }; diff --git a/src/ui/panels/inspector/gta6/drawable/selected.rs b/src/ui/panels/inspector/gta6/drawable/selected.rs index 3cfc8754d..062b02677 100644 --- a/src/ui/panels/inspector/gta6/drawable/selected.rs +++ b/src/ui/panels/inspector/gta6/drawable/selected.rs @@ -22,7 +22,7 @@ pub(super) fn draw( let shown = match ui.data(|d| d.get_temp::(id)) { Some((s, shown)) if s == stamp => shown, _ => { - let shown = selected_rows(&state.gta6.anim, doc, sel).map(Arc::new); + let shown = selected_rows(&state.gta6, doc, sel).map(Arc::new); ui.data_mut(|d| d.insert_temp(id, (stamp, shown.clone()))); shown } diff --git a/src/ui/panels/inspector/rpf9.rs b/src/ui/panels/inspector/rpf9.rs index 3ad0245e2..66c6457c8 100644 --- a/src/ui/panels/inspector/rpf9.rs +++ b/src/ui/panels/inspector/rpf9.rs @@ -480,7 +480,7 @@ pub(super) fn draw_scan_origin(ui: &mut egui::Ui, state: &AppState, doc_id: Docu let Some(path) = state.document(doc_id).and_then(|d| d.path.as_deref()) else { return; }; - let Some((find, loose)) = crate::state::rpf9_scan::scan_origin(path) else { + let Some((find, loose)) = crate::state::rpf9_scan::scan_origin(&state.gta6.rpf9, path) else { return; }; // A body opened from a tree's row names the row; only one a scan with no key found says scan. diff --git a/src/ui/panels/inspector/summary.rs b/src/ui/panels/inspector/summary.rs index f44271075..14ca1e860 100644 --- a/src/ui/panels/inspector/summary.rs +++ b/src/ui/panels/inspector/summary.rs @@ -58,7 +58,10 @@ pub(super) fn draw_facts_grid(ui: &mut egui::Ui, id: &str, facts: &Facts) { /// `Legacy, version 165`: the edition a resource's own version names, and the file's own version once a save would write another. pub(super) fn edition(doc: &crate::state::Document) -> Option { // A GTA VI body is of neither GTA V edition, whatever its resource's version reads as. - if crate::state::rpf9_scan::from_gta_vi(doc.path.as_deref()) { + if doc + .rpf9_session() + .is_some_and(|rpf9| crate::state::rpf9_scan::from_gta_vi(rpf9, doc.path.as_deref())) + { return None; } let version = doc.resource.as_ref()?.seal.version(); diff --git a/src/ui/panels/inspector/text.rs b/src/ui/panels/inspector/text.rs index 65855c2b1..359d04a33 100644 --- a/src/ui/panels/inspector/text.rs +++ b/src/ui/panels/inspector/text.rs @@ -34,7 +34,9 @@ pub(super) fn draw_text(ui: &mut egui::Ui, state: &AppState, doc_id: crate::stat if super::gta6::move_network::draw_scanned(ui, &state.gta6, doc.path.as_deref()) { return; } - if (doc.path.as_deref()).is_some_and(crate::state::rpf9_scan::opened_as_facts) { + if (doc.path.as_deref()) + .is_some_and(|p| crate::state::rpf9_scan::opened_as_facts(&state.gta6.rpf9, p)) + { ui.label(tr!("The Document panel lists what GTA VI's headerless reader reads from this binary body, in lines OpenRage writes.")); return; } diff --git a/src/ui/panels/maps/plan.rs b/src/ui/panels/maps/plan.rs index 58e20043f..1703733ef 100644 --- a/src/ui/panels/maps/plan.rs +++ b/src/ui/panels/maps/plan.rs @@ -303,7 +303,12 @@ fn canvas(ui: &mut egui::Ui, state: &mut AppState, shown: &mut MapsUi) { let ctrl = ui.input(|i| i.modifiers.command); // Ctrl and a click marks an entity, or unmarks it, for Duplicate. if !super::scanned_author::marked_by_click(ui.ctx(), key.as_ref(), index, ctrl) { - (shown.world).pick(world.to_array(), map.view.pixels_per_metre, hit.is_some()); + (shown.world).pick( + &state.gta6.world, + world.to_array(), + map.view.pixels_per_metre, + hit.is_some(), + ); pick = Some(hit.map(|(i, _)| Pick { source: scene.placed[i].source.clone(), kind: PickKind::Entity(scene.placed[i].index), diff --git a/src/ui/panels/maps/scanned.rs b/src/ui/panels/maps/scanned.rs index 628cf9dfc..4c52c4262 100644 --- a/src/ui/panels/maps/scanned.rs +++ b/src/ui/panels/maps/scanned.rs @@ -383,7 +383,7 @@ fn parent_row( /// What the interior entity `index` places holds, or why it is not read. fn interior_rows(ui: &mut egui::Ui, state: &AppState, scanned: &ScannedMap, index: usize) { - match links::interior_of(scanned, index) { + match links::interior_of(&state.gta6, scanned, index) { Some(Ok(i)) => { row( ui, diff --git a/src/ui/panels/maps/world.rs b/src/ui/panels/maps/world.rs index 2ae1edcfb..406b90217 100644 --- a/src/ui/panels/maps/world.rs +++ b/src/ui/panels/maps/world.rs @@ -46,8 +46,17 @@ pub(super) struct Shown { impl Shown { /// Pick the entity of the fill nearest `at`, a click on the plan where a metre is /// `pixels_per_metre` pixels; none where the click took an entity of the map shown. - pub(super) fn pick(&mut self, at: [f32; 2], pixels_per_metre: f32, taken: bool) { - self.picked = match (taken || !self.others, gta6_world::world().area.as_ref()) { + pub(super) fn pick( + &mut self, + world: &crate::state::gta6::world::WorldSession, + at: [f32; 2], + pixels_per_metre: f32, + taken: bool, + ) { + self.picked = match ( + taken || !self.others, + gta6_world::world(world).area.as_ref(), + ) { (false, Some(area)) => area.pick(at, PICK_PIXELS / pixels_per_metre), _ => None, }; @@ -95,8 +104,9 @@ pub(super) fn tools(ui: &mut egui::Ui, state: &mut AppState, shown: &mut Shown) let Some(scanned) = state.scanned_map() else { return; }; - let area = (gta6_world::world().area.clone()).filter(|a| a.holds(&scanned.path)); - let running = gta6_world::fill::running(); + let area = + (gta6_world::world(&state.gta6.world).area.clone()).filter(|a| a.holds(&scanned.path)); + let running = gta6_world::fill::running(&state.gta6.world); let mut asked = None; let mut hints: Vec = Vec::new(); ui.horizontal_wrapped(|ui| { @@ -153,7 +163,7 @@ pub(super) fn tools(ui: &mut egui::Ui, state: &mut AppState, shown: &mut Shown) )); } None => { - let mut world = gta6_world::world(); + let mut world = gta6_world::world(&state.gta6.world); if shown.lights && world.lights_of(scanned).is_empty() { hints .push(tr!("This map and the archetypes read so far hold no light").to_string()); @@ -203,7 +213,7 @@ pub(super) fn tools(ui: &mut egui::Ui, state: &mut AppState, shown: &mut Shown) state.show_info_toast(why); } } - Some(Asked::Stop) => gta6_world::fill::stop(), + Some(Asked::Stop) => gta6_world::fill::stop(&state.gta6.world), Some(Asked::Open(archive, offset)) => state.open_gta6_map_body(&archive, offset), None => {} } @@ -377,13 +387,13 @@ pub(super) fn draw_on_plan( // The pixels a metre is, from two points a metre apart. let per_metre = (at([lo[0] + 1.0, lo[1]]).x - at(lo).x).abs(); let area: Option> = - (gta6_world::world().area.clone()).filter(|a| a.holds(&scanned.path)); + (gta6_world::world(&state.gta6.world).area.clone()).filter(|a| a.holds(&scanned.path)); if let Some(area) = area { let show_lod = state.workbench.maps.show_lod; draw_area(painter, &area, *shown, show_lod, (lo, hi), per_metre, &at); return; } - let mut world = gta6_world::world(); + let mut world = gta6_world::world(&state.gta6.world); if shown.others { let dot = theme::TEXT_SECONDARY.get(); let except = Some(scanned.path.as_path()); diff --git a/src/ui/panels/settings/games.rs b/src/ui/panels/settings/games.rs index 401665215..4cb5a747a 100644 --- a/src/ui/panels/settings/games.rs +++ b/src/ui/panels/settings/games.rs @@ -76,7 +76,9 @@ fn draw_game_row(ui: &mut egui::Ui, state: &mut AppState, game: Game) { ui.colored_label(theme::SUCCESS, tr!("(active)")); } if crate::state::gta_vi::read_by_scan(game) { - let keys = crate::state::rpf9_scan::rpf9_table::gta6_keys_held::gta6_keys(); + let keys = crate::state::rpf9_scan::rpf9_table::gta6_keys_held::gta6_keys( + &state.gta6.rpf9, + ); if keys == crate::state::rpf9_scan::rpf9_table::gta6_keys_held::Gta6Keys::Asking { ui.ctx() .request_repaint_after(std::time::Duration::from_millis(200)); diff --git a/src/ui/panels/status_bar.rs b/src/ui/panels/status_bar.rs index 4ed7c45a9..36445d8bd 100644 --- a/src/ui/panels/status_bar.rs +++ b/src/ui/panels/status_bar.rs @@ -45,7 +45,7 @@ fn world_title(state: &AppState) -> Option { let on = state.active_workspace == crate::ui::dock::Workspace::World; let shown = on && crate::ui::panels::world_viewer::offered(state); let failed = || { - crate::state::gta6_world::worldview::viewer() + crate::state::gta6_world::worldview::viewer(&state.gta6.world) .failed .is_some() }; diff --git a/src/ui/panels/text_editor/mod.rs b/src/ui/panels/text_editor/mod.rs index 58c9b8cdd..55284c6ae 100644 --- a/src/ui/panels/text_editor/mod.rs +++ b/src/ui/panels/text_editor/mod.rs @@ -202,8 +202,8 @@ fn draw_script_doc(ui: &mut egui::Ui, app_state: &AppState, doc_id: crate::state fn draw_text_doc(ui: &mut egui::Ui, app_state: &mut AppState, doc_id: crate::state::DocumentId) { let editor_id = ui.id().with(("virtual_text_editor_v3", doc_id)); let state_handle = load_state(ui.ctx(), doc_id); - let read_only = - (app_state.document(doc_id)).is_some_and(crate::state::rpf9_scan::text_takes_no_edit); + let read_only = (app_state.document(doc_id)) + .is_some_and(|d| crate::state::rpf9_scan::text_takes_no_edit(&app_state.gta6.rpf9, d)); if let Some(doc) = app_state.document(doc_id) { if let DocPayload::Text(t) | DocPayload::NameTable(t) = &doc.payload { let state = state_handle diff --git a/src/ui/panels/viewport/drawable_row.rs b/src/ui/panels/viewport/drawable_row.rs index 60a417afb..2d1e8a5dc 100644 --- a/src/ui/panels/viewport/drawable_row.rs +++ b/src/ui/panels/viewport/drawable_row.rs @@ -42,7 +42,9 @@ pub(crate) fn draw(ui: &mut egui::Ui, rect: egui::Rect, top: f32, state: &mut Ap skeleton: bones::can_draw(state), weapon: (state.active_document()) .and_then(|doc| doc.path.as_deref()) - .is_some_and(|path| crate::state::gta6_weapon_parts::of(path).is_some()), + .is_some_and(|path| { + crate::state::gta6_weapon_parts::of(&state.gta6.drawable, path).is_some() + }), export: gta6_model(state) .and_then(|doc| commands::on(state, Action::ExportGltf, Target::Document(doc))), }; diff --git a/src/ui/panels/world_viewer/mod.rs b/src/ui/panels/world_viewer/mod.rs index 0fcaa3479..a55df35a9 100644 --- a/src/ui/panels/world_viewer/mod.rs +++ b/src/ui/panels/world_viewer/mod.rs @@ -213,7 +213,8 @@ pub fn draw_view(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut Re let clean = held.clean; // The session of this install is held: another game's, where one was, ends here. state.world_session(); - let mut viewer = gta6_worldview::viewer(); + let world = state.gta6.world.clone(); + let mut viewer = gta6_worldview::viewer(&world); viewer.open(&root); viewer.poll(); remember(ui, state, &mut viewer, &root); @@ -256,7 +257,7 @@ pub fn draw_view(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut Re if holds_keys { moving |= keys::fly(ui, &response, &mut turned); } - let mut viewer = gta6_worldview::viewer(); + let mut viewer = gta6_worldview::viewer(&state.gta6.world); viewer.camera = turned; if response.hovered() { let notches = ui.input(|i| i.smooth_scroll_delta.y) / 50.0; @@ -314,7 +315,7 @@ pub fn draw_view(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut Re (rect.width() * ppp).round() as u32, (rect.height() * ppp).round() as u32, ); - bridge.refresh_world(); + bridge.refresh_world(&state.gta6.world); bridge.push_inputs(Default::default()); match bridge.texture_id() { Some(texture) => { diff --git a/src/ui/panels/world_viewer/side.rs b/src/ui/panels/world_viewer/side.rs index bb52cad8d..90b28e4df 100644 --- a/src/ui/panels/world_viewer/side.rs +++ b/src/ui/panels/world_viewer/side.rs @@ -141,7 +141,8 @@ pub fn draw_side(ui: &mut egui::Ui, state: &mut AppState, bridge: Option<&mut Re let removing = state.world_removal_runs(); let mut typed = std::mem::take(&mut state.panels.get_or_default_mut::().typed); let mut selection = None; - let mut viewer = gta6_worldview::viewer(); + let world = state.gta6.world.clone(); + let mut viewer = gta6_worldview::viewer(&world); egui::ScrollArea::vertical().show(ui, |ui| { if blocked(ui, state, &mut viewer) { ui.separator();