Skip to content

Commit

Permalink
#78 load images from cache
Browse files Browse the repository at this point in the history
  • Loading branch information
angel-git committed May 1, 2024
1 parent 4a3c5d6 commit e387ef5
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 20 deletions.
7 changes: 7 additions & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ chrono = "0.4.31"
rand = "0.8.5"
url = "2.4.0"
sysinfo = "0.30.11"
base64 = "0.22.0"

[features]
# this feature is used for production builds or when `devPath` points to the filesystem and the built-in dev server is disabled.
Expand Down
2 changes: 0 additions & 2 deletions src-tauri/src/stash/stash_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1138,8 +1138,6 @@ mod tests {
.expect("Items missing");

let items: Vec<InventoryItem> = serde_json::from_value(items_option.clone()).unwrap();
println!("items {:?}", items);
// main item tpl: 583990e32459771419544dd2, it should have location, upd, parentId and slot
let main = items
.iter()
.find(|i| i._tpl == "583990e32459771419544dd2")
Expand Down
22 changes: 22 additions & 0 deletions src-tauri/src/ui_profile/ui_profile_serializer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use serde_json::Map;
use std::collections::{HashMap, HashSet};

pub use crate::prelude::*;
use crate::spt::spt_profile_serializer::TarkovProfile;
use crate::utils::cache_utils::{load_cache_icon_index_file, load_image_from_cache};

#[derive(Deserialize, Serialize, Debug)]
pub struct UIProfile {
Expand Down Expand Up @@ -55,6 +57,8 @@ pub struct Item {
pub slot_items: Option<HashSet<SlotItem>>,
#[serde(rename = "presetImageId")]
pub preset_image_id: Option<String>,
#[serde(rename = "cacheImage")]
pub cache_image: Option<String>,
}

#[derive(Deserialize, Serialize, Debug)]
Expand Down Expand Up @@ -135,12 +139,15 @@ pub fn convert_profile_to_ui(
let stash = &tarkov_profile.characters.pmc.inventory.stash;
let (stash_size_x, stash_size_y) = calculate_stash_size(&tarkov_profile, bsg_items_root);

let cache_icon_index_file = load_cache_icon_index_file();

let items: Vec<Item> = parse_items(
tarkov_profile.characters.pmc.inventory.items,
bsg_items_root,
stash.as_str(),
"hideout",
globals,
&cache_icon_index_file,
)?;

let mut bsg_items: HashMap<String, BsgItem> = HashMap::new();
Expand Down Expand Up @@ -231,6 +238,7 @@ fn parse_items(
parent_slot: &str,
parent_item_slot: &str,
globals: &HashMap<String, Value>,
index_cache: &Option<Map<String, Value>>,
) -> Result<Vec<Item>, String> {
let mut items: Vec<Item> = Vec::new();

Expand Down Expand Up @@ -283,6 +291,7 @@ fn parse_items(
item._id.as_str(),
grid_name,
globals,
&index_cache,
)?;

let grid_item = GridItem {
Expand Down Expand Up @@ -403,9 +412,20 @@ fn parse_items(
grid_items,
slot_items,
preset_image_id,
cache_image: if index_cache.is_some() {
load_image_from_cache(
item,
&profile_items,
bsg_items_root,
index_cache.as_ref().unwrap(),
)
} else {
None
},
};
items.push(i)
}

Ok(items)
}

Expand Down Expand Up @@ -595,6 +615,7 @@ mod tests {
stash.as_str(),
"hideout",
&HashMap::new(),
&None,
)
.ok()
.unwrap();
Expand Down Expand Up @@ -636,6 +657,7 @@ mod tests {
stash.as_str(),
"hideout",
&HashMap::new(),
&None,
)
.ok()
.unwrap();
Expand Down
96 changes: 79 additions & 17 deletions src-tauri/src/utils/cache_utils.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,87 @@
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;

use serde_json::Value;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use log::{info, warn};
use serde_json::{Map, Value};

use crate::spt::spt_profile_serializer::InventoryItem;

pub fn get_item_hash(
pub fn load_cache_icon_index_file() -> Option<Map<String, Value>> {
let cache_index_file = get_cache_index_path();
let exists = cache_index_file.exists();
if !exists {
warn!(
"Couldn't not load images cache file: {}",
cache_index_file.display()
);
return None;
}
if cache_index_file.exists() {
let index_json = fs::read_to_string(cache_index_file).unwrap();
let index_json_value: Value = serde_json::from_str(index_json.as_str()).unwrap();
Some(index_json_value.as_object().unwrap().clone())
} else {
None
}
}

pub fn load_image_from_cache(
item: &InventoryItem,
items: &[InventoryItem],
bsg_items_root: &HashMap<String, Value>,
index_cache: &Map<String, Value>,
) -> Option<String> {
let hash = get_item_hash(item, items, bsg_items_root);
match index_cache.get(hash.to_string().as_str()) {
Some(index) => load_image(index.as_u64().unwrap().to_string().as_str()),
None => {
warn!(
"Couldn't find hash {} for item {} in cache index.json",
hash, item._id
);
None
}
}
}

fn get_cache_index_path() -> PathBuf {
get_cache_path().join("index.json")
}

fn get_cache_path() -> PathBuf {
let temp_dir = std::env::temp_dir();
temp_dir
.join("Battlestate Games")
.join("EscapeFromTarkov")
.join("Icon Cache")
.join("live")
}

fn load_image(index_name: &str) -> Option<String> {
let image_path = get_cache_path().join(index_name.to_owned() + ".png");
let mut file_content = Vec::new();
match File::open(image_path)
.unwrap()
.read_to_end(&mut file_content)
{
Ok(_) => {
let base64_encoded = BASE64_STANDARD.encode(file_content);
let image_url = format!("data:image/png;base64,{}", base64_encoded);
Some(image_url)
}
Err(e) => {
warn!("Couldn't load image {}: {}", index_name, e);
None
}
}
}

fn get_item_hash(
item: &InventoryItem,
items: &[InventoryItem],
bsg_items_root: &HashMap<String, Value>,
Expand Down Expand Up @@ -38,7 +115,6 @@ fn smethod_0(
hash_seed = hash_seed.wrapping_mul(6529);
let children_items = get_children(top_level_item, items);
if !children_items.is_empty() {
println!("has_cartridges_or_slots {:?}", children_items);
children_items.iter().for_each(|child| {
let mut num = 0;
let mut num2 = hash_seed ^ get_hash_sum(child, items);
Expand All @@ -52,7 +128,6 @@ fn smethod_0(
}

hashes.sort();
println!("smehtod_0 {} {:?}", top_level_item._tpl, hashes);
hashes
}

Expand All @@ -64,9 +139,6 @@ fn get_hash_sum(item: &InventoryItem, items: &[InventoryItem]) -> i32 {
num = num.wrapping_add(
7901_i32.wrapping_mul(get_deterministic_hash_code(parent_item._tpl.as_str())),
);

println!("get_hash_sum {} {}", container_id.unwrap(), num);

num
}

Expand Down Expand Up @@ -111,23 +183,17 @@ fn smethod_1(
.and_then(|a| a.foldable.clone())
.map(|a| a.folded)
.unwrap_or(false);
println!("FOLDABLE ITEM!!!! {}", is_folded);

hash ^= (23 + (if is_folded { 1 } else { 0 })) << 1;
}

if is_magazine_item(&item._tpl, bsg_items_root) {
println!("is magazine item, id: {}", &item._id);
// TODO do we have to calculate here all bullets inside??? i don't think so...
let all_ammo_inside_magazine = items
.iter()
.filter(|i| i.parent_id.is_some() && i.parent_id.as_ref().unwrap() == item._id.as_str())
.fold(0, |acc, i| {
acc + i.upd.as_ref().unwrap().stack_objects_count.unwrap()
});

println!("all ammo in magazine {}", all_ammo_inside_magazine);

let max_visible_ammo = get_max_visible_ammo(
all_ammo_inside_magazine as u16,
bsg_items_root
Expand All @@ -140,12 +206,8 @@ fn smethod_1(
.as_str()
.unwrap(),
);

println!("max_visible_ammo {}", max_visible_ammo);

hash ^= (23 + max_visible_ammo as i32) << 2;
}
println!("smethod_1 {} {}", item._tpl, hash);
hash
}

Expand Down
6 changes: 5 additions & 1 deletion src/routes/stash/item/stash-item.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@
const backgroundImageUrl = item.presetImageId
? `https://assets.tarkov.dev/${item.presetImageId}-base-image.png`
: `https://assets.tarkov.dev/${item.tpl}-base-image.png`;
return `${transform.rotate}; ${transform.translate} ; background-image: url(${backgroundImageUrl}); background-repeat: no-repeat; width: ${width}px; height: ${height}px;`;
if (item.cacheImage) {
return `${transform.rotate}; ${transform.translate} ; background-image: url(${item.cacheImage}); background-repeat: no-repeat; width: ${width}px; height: ${height}px;`;
} else {
return `${transform.rotate}; ${transform.translate} ; background-image: url(${backgroundImageUrl}); background-repeat: no-repeat; width: ${width}px; height: ${height}px;`;
}
}
</script>

Expand Down
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export interface Item {
gridItems: Array<GridItem> | null;
slotItems?: Array<SlotItem>;
presetImageId?: string;
cacheImage?: string;
}

export interface SlotItem {
Expand Down

0 comments on commit e387ef5

Please sign in to comment.