Skip to main content

rpfm_extensions/optimizer/
mod.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! Pack optimization system for reducing size and improving compatibility.
12//!
13//! This module provides tools to clean up and optimize mod packs by removing
14//! unnecessary data, duplicate entries, and files that are identical to vanilla.
15//! Optimization helps reduce mod size, improve load times, and increase
16//! compatibility with other mods.
17//!
18//! # Optimization Types
19//!
20//! ## Pack-Level Optimizations
21//!
22//! - **ITM File Removal**: Remove files that are byte-for-byte identical to
23//!   vanilla game files. These provide no benefit and can cause conflicts.
24//! - **Apply Compression**: Turn on the pack's `compress` flag using the
25//!   most modern compression format the active game supports (overriding
26//!   whatever the pack had configured), so the next save actually compresses
27//!   the files. No-op if the game supports no compression formats. Intended
28//!   as a final step before release on a pack you've been editing uncompressed.
29//!
30//! ## Table Optimizations (DB/Loc)
31//!
32//! - **Duplicate Removal**: Remove rows that appear multiple times
33//! - **ITM Row Removal**: Remove rows identical to vanilla data
34//! - **ITNR Row Removal**: Remove rows identical to the "new row" default
35//! - **Empty File Removal**: Delete tables with no remaining rows
36//! - **Datacore Import**: Generate `twad_key_deletes` entries for datacored tables
37//!
38//! ## Portrait Settings Optimizations
39//!
40//! - **Unused Art Set Removal**: Remove art sets not referenced by any unit
41//! - **Unused Variant Removal**: Remove variants not used in any art set
42//! - **Empty Mask Removal**: Remove portrait masks that are empty/transparent
43//! - **Empty File Removal**: Delete portrait settings with no remaining data
44//!
45//! ## Text File Optimizations
46//!
47//! - **Unused XML Removal**: Remove unused XML files in map/prefab folders
48//! - **AGF File Removal**: Remove unnecessary AGF files
49//! - **Model Statistics Removal**: Remove debug/statistics files
50//!
51//! # Configuration
52//!
53//! Use [`OptimizerOptions`] to control which optimizations are applied:
54//!
55//! ```ignore
56//! let mut options = OptimizerOptions::default();
57//! options.set_pack_remove_itm_files(true);
58//! options.set_table_remove_itm_entries(true);
59//! options.set_pts_remove_empty_masks(true);
60//! ```
61//!
62//! # Usage Example
63//!
64//! ```ignore
65//! use rpfm_extensions::optimizer::OptimizableContainer;
66//!
67//! let (deleted, optimized) = pack.optimize(
68//!     None,  // Optimize all paths
69//!     &mut dependencies,
70//!     &schema,
71//!     &game_info,
72//!     &options,
73//! )?;
74//!
75//! println!("Deleted {} files, optimized {} files", deleted.len(), optimized.len());
76//! ```
77//!
78//! # Traits
79//!
80//! - [`Optimizable`]: For individual file types that can be optimized
81//! - [`OptimizableContainer`]: For containers (like [`Pack`]) that can optimize their contents
82
83use getset::{Getters, Setters};
84use serde::{Deserialize, Serialize};
85
86use std::collections::{BTreeMap, HashMap, HashSet};
87
88use rpfm_lib::error::{RLibError, Result};
89use rpfm_lib::files::{Container, ContainerPath, db::DB, EncodeableExtraData, FileType, loc::Loc, pack::Pack, portrait_settings::PortraitSettings, RFile, RFileDecoded, table::DecodedData, text::TextFormat};
90use rpfm_lib::games::{GameInfo, supported_games::KEY_WARHAMMER_3};
91use rpfm_lib::schema::Schema;
92
93use crate::dependencies::{Dependencies, KEY_DELETES_TABLE_NAME};
94
95/// Filename suffix used to identify empty mask images.
96const EMPTY_MASK_PATH_END: &str = "empty_mask.png";
97
98/// Default path for generated key deletes table.
99const DEFAULT_KEY_DELETES_FILE: &str = "db/twad_key_deletes_tables/generated_deletes";
100
101//-------------------------------------------------------------------------------//
102//                             Trait definitions
103//-------------------------------------------------------------------------------//
104
105/// Trait for file types that can be optimized to reduce size.
106///
107/// Implementors define how their specific file format should be cleaned up
108/// and what constitutes an "empty" state that allows safe deletion.
109pub trait Optimizable {
110
111    /// Optimizes this file to reduce size and improve compatibility.
112    ///
113    /// # Arguments
114    ///
115    /// * `dependencies` - Dependencies cache for comparing against vanilla data
116    /// * `container` - Optional reference to the containing pack for cross-file operations
117    /// * `options` - Configuration controlling which optimizations to apply
118    ///
119    /// # Returns
120    ///
121    /// `true` if the file is now empty and can be safely deleted, `false` otherwise.
122    fn optimize(&mut self, dependencies: &mut Dependencies, container: Option<&BTreeMap<String, Pack>>, options: &OptimizerOptions) -> bool;
123}
124
125/// Trait for containers (like [`Pack`]) that can optimize their contents.
126///
127/// This trait provides pack-wide optimization capabilities, processing
128/// multiple files and handling deletions.
129pub trait OptimizableContainer: Container {
130
131    /// Optimizes the container's contents.
132    ///
133    /// # Arguments
134    ///
135    /// * `paths_to_optimize` - Specific paths to optimize, or `None` for all files
136    /// * `dependencies` - Dependencies cache for vanilla data comparison
137    /// * `schema` - Schema for decoding tables
138    /// * `game` - Game information for format-specific handling
139    /// * `options` - Configuration controlling which optimizations to apply
140    ///
141    /// # Returns
142    ///
143    /// A tuple of `(deleted_files, optimized_files)` containing the paths of
144    /// files that were deleted and files that were modified.
145    fn optimize(&mut self,
146        paths_to_optimize: Option<Vec<ContainerPath>>,
147        dependencies: &mut Dependencies,
148        schema: &Schema,
149        game: &GameInfo,
150        options: &OptimizerOptions,
151    ) -> Result<(HashSet<String>, HashSet<String>)>;
152}
153
154/// Configuration options for the pack optimizer.
155///
156/// Controls which optimization operations are enabled. Each option can be
157/// individually toggled to customize the optimization behavior.
158///
159/// # Default Behavior
160///
161/// By default, safe optimizations are enabled (duplicate removal, ITM removal)
162/// while potentially destructive ones are disabled (datacored table optimization,
163/// unused art set removal).
164#[derive(Clone, Debug, Getters, Setters, Deserialize, Serialize)]
165#[getset(get = "pub", set = "pub")]
166pub struct OptimizerOptions {
167
168    /// Allow the optimizer to remove files unchanged from vanilla, reducing the pack size.
169    pack_remove_itm_files: bool,
170
171    /// Allow the optimizer to apply the most modern compression format the active game supports, so the next save compresses the files.
172    ///
173    /// Overrides whatever format the pack had configured. Intended as a final step before release on a pack
174    /// that's been edited uncompressed. No-op if the active game supports no compression formats.
175    pack_apply_compression: bool,
176
177    /// Allows the optimizer to update the twad_key_deletes table using the data cored tables in your pack to guess the keys.
178    ///
179    /// IT DOESN'T DELETE THE DATACORED TABLES.
180    db_import_datacores_into_twad_key_deletes: bool,
181
182    /// Allow the optimizer to optimize datacored tables. THIS IS NOT RECOMMENDED, as datacored tables usually are they way they are for a reason.
183    ///
184    /// THIS IS NOT RECOMMENDED, as datacored tables usually are the way they are for a reason.
185    db_optimize_datacored_tables: bool,
186
187    /// Allows the optimizer to remove duplicated rows from db and loc files.
188    table_remove_duplicated_entries: bool,
189
190    /// Allows the optimizer to remove ITM (Identical To Master) rows from db and loc files.
191    table_remove_itm_entries: bool,
192
193    /// Allows the optimizer to remove ITNR (Identical To New Row) rows from db and loc files.
194    table_remove_itnr_entries: bool,
195
196    /// Allows the optimizer to remove empty db and loc files.
197    table_remove_empty_file: bool,
198
199    /// Allows the optimizer to remove unused xml files in map folders.
200    text_remove_unused_xml_map_folders: bool,
201
202    /// Allows the optimizer to remove unused xml files in the prefab folder.
203    text_remove_unused_xml_prefab_folder: bool,
204
205    /// Allows the optimizer to remove unused agf files.
206    text_remove_agf_files: bool,
207
208    /// Allows the optimizer to remove unused model_statistics files.
209    text_remove_model_statistics_files: bool,
210
211    /// Allow the optimizer to remove unused art sets in Portrait Settings files.
212    ///
213    /// Only use this after you have confirmed the unused art sets are actually unused and not caused by a typo.
214    pts_remove_unused_art_sets: bool,
215
216    /// Allow the optimizer to remove unused variants from art sets in Portrait Settings files.
217    ///
218    /// Only use this after you have confirmed the unused variants are actually unused and not caused by a typo.
219    pts_remove_unused_variants: bool,
220
221    /// Allow the optimizer to remove empty masks in Portrait Settings file, reducing their side.
222    ///
223    /// Ingame there's no difference between an empty mask and an invalid one, so it's better to remove them to reduce their size.
224    pts_remove_empty_masks: bool,
225
226    /// Allows the optimizer to remove empty Portrait Settings files.
227    pts_remove_empty_file: bool,
228}
229
230//-------------------------------------------------------------------------------//
231//                           Trait implementations
232//-------------------------------------------------------------------------------//
233
234impl Default for OptimizerOptions {
235    fn default() -> Self {
236        Self {
237            pack_remove_itm_files: true,
238            pack_apply_compression: true,
239            db_import_datacores_into_twad_key_deletes: false,
240            db_optimize_datacored_tables: false,
241            table_remove_duplicated_entries: true,
242            table_remove_itm_entries: true,
243            table_remove_itnr_entries: true,
244            table_remove_empty_file: true,
245            text_remove_unused_xml_map_folders: true,
246            text_remove_unused_xml_prefab_folder: true,
247            text_remove_agf_files: true,
248            text_remove_model_statistics_files: true,
249            pts_remove_unused_art_sets: false,
250            pts_remove_unused_variants: false,
251            pts_remove_empty_masks: false,
252            pts_remove_empty_file: true,
253        }
254    }
255}
256
257impl OptimizableContainer for Pack {
258
259    /// This function optimizes the provided [Pack] file in order to make it smaller and more compatible.
260    ///
261    /// Specifically, it performs the following optimizations:
262    ///
263    /// - DB/Loc tables (except if the table has the same name as his vanilla/parent counterpart and `optimize_datacored_tables` is false):
264    ///     - Removal of duplicated entries.
265    ///     - Removal of ITM (Identical To Master) entries.
266    ///     - Removal of ITNR (Identical To New Row) entries.
267    ///     - Removal of empty tables.
268    ///     - Conversion of datacores into twad_key_deletes_entries.
269    /// - Text files:
270    ///     - Removal of XML files in map folders (extra files resulting of Terry export process).
271    ///     - Removal of XML files in prefabs folder (extra files resulting of Terry export process).
272    ///     - Removal of .agf files (byproduct of bob exporting models).
273    ///     - Removal of .model_statistics files (byproduct of bob exporting models).
274    /// - Portrait Settings files:
275    ///     - Removal of variants not present in the variants table (unused data).
276    ///     - Removal of art sets not present in the campaign_character_arts table (unused data).
277    ///     - Removal of empty masks.
278    ///     - Removal of empty Portrait Settings files.
279    /// - Pack:
280    ///     - Remove files identical to parent/vanilla.
281    ///     - Apply the most modern compression format the active game supports, so the next save compresses the files.
282    fn optimize(&mut self,
283        paths_to_optimize: Option<Vec<ContainerPath>>,
284        dependencies: &mut Dependencies,
285        schema: &Schema,
286        game: &GameInfo,
287        options: &OptimizerOptions
288    ) -> Result<(HashSet<String>, HashSet<String>)> {
289        let mut files_to_add: HashSet<String> = HashSet::new();
290        let mut files_to_delete: HashSet<String> = HashSet::new();
291
292        // We can only optimize if we have vanilla data available.
293        if !dependencies.is_vanilla_data_loaded(false) {
294            return Err(RLibError::DependenciesCacheNotGeneratedorOutOfDate);
295        }
296
297        // If we're importing the datacored deletions, create the file for them if it doesn't exist.
298        if options.db_import_datacores_into_twad_key_deletes && game.key() == KEY_WARHAMMER_3 {
299            if let Some(def) = schema.definitions_by_table_name(KEY_DELETES_TABLE_NAME) {
300                if !def.is_empty() {
301                    let table = DB::new(&def[0], None, KEY_DELETES_TABLE_NAME);
302                    let _ = self.insert(RFile::new_from_decoded(&RFileDecoded::DB(table), 0, DEFAULT_KEY_DELETES_FILE));
303                    files_to_add.insert(DEFAULT_KEY_DELETES_FILE.to_owned());
304                }
305            }
306        }
307
308        // Cache the pack paths for the text file checks.
309        let pack_paths = self.paths().keys().map(|x| x.to_owned()).collect::<HashSet<String>>();
310        let self_copy = self.clone();
311        let self_copy_map = BTreeMap::from([("main".to_string(), self_copy)]);
312
313        // List of files to optimize.
314        let mut files_to_optimize = match paths_to_optimize {
315            Some(paths) => self.files_by_paths_mut(&paths, false),
316            None => self.files_mut().values_mut().collect::<Vec<_>>(),
317        };
318
319
320        // Import into twad_key_deletes is only supported in wh3, as that table is only in that game... for now.
321        if options.db_import_datacores_into_twad_key_deletes && game.key() == KEY_WARHAMMER_3 {
322            let mut generated_rows = vec![];
323            let datacores = files_to_optimize.iter()
324                .filter(|x| x.file_type() == FileType::DB && dependencies.file_exists(x.path_in_container_raw(), true, true, true))
325                .collect::<Vec<_>>();
326
327            for datacore in datacores {
328                if let Ok(dep_file) = dependencies.file(datacore.path_in_container_raw(), true, true, true) {
329                    if let Ok(RFileDecoded::DB(dep_table)) = dep_file.decoded() {
330                        if let Ok(RFileDecoded::DB(datacore_table)) = datacore.decoded() {
331                            let mut datacore_keys: HashSet<String> = HashSet::new();
332                            datacore_table.generate_twad_key_deletes_keys(&mut datacore_keys);
333
334                            let mut dep_keys = HashSet::new();
335                            dep_table.generate_twad_key_deletes_keys(&mut dep_keys);
336
337                            let table_name_dec_data = DecodedData::StringU8(datacore_table.table_name_without_tables().to_owned());
338                            for key in dep_keys {
339                                if !datacore_keys.contains(&key) {
340                                    generated_rows.push(vec![DecodedData::StringU8(key.to_owned()), table_name_dec_data.clone()]);
341                                }
342                            }
343                        }
344                    }
345                }
346            }
347
348            if let Some(file) = files_to_optimize.iter_mut().find(|x| x.path_in_container_raw() == DEFAULT_KEY_DELETES_FILE) {
349                if let Ok(RFileDecoded::DB(db)) = file.decoded_mut() {
350                    let _ = db.set_data(&generated_rows);
351                }
352            }
353        }
354
355        // Pass to identify and remove itms.
356        if options.pack_remove_itm_files {
357            let extra_data = Some(EncodeableExtraData::new_from_game_info(game));
358            for rfile in &mut files_to_optimize {
359                if let Ok(dep_file) = dependencies.file_mut(rfile.path_in_container_raw(), true, true) {
360                    if let Ok(local_hash) = rfile.data_hash(&extra_data) {
361                        if let Ok(dependency_hash) = dep_file.data_hash(&extra_data) {
362                            if local_hash == dependency_hash {
363                                files_to_delete.insert(rfile.path_in_container_raw().to_string());
364                            }
365                        }
366                    }
367                }
368            }
369        }
370
371        // Then, do a second pass, this time over the decodeable files that we can optimize.
372        files_to_delete.extend(files_to_optimize.iter_mut().filter_map(|rfile| {
373
374            // Only check it if it's not already marked for deletion.
375            let path = rfile.path_in_container_raw().to_owned();
376            if !files_to_delete.contains(&path) {
377
378                match rfile.file_type() {
379
380                    // Unless we specifically wanted to, ignore the same-name-as-vanilla-or-parent files,
381                    // as those are probably intended to overwrite vanilla files, not to be optimized.
382                    FileType::DB if options.db_optimize_datacored_tables || !dependencies.file_exists(&path, true, true, true) => {
383                        if let Ok(RFileDecoded::DB(db)) = rfile.decoded_mut() {
384                            if db.optimize(dependencies, Some(&self_copy_map), options) && options.table_remove_empty_file {
385                                return Some(path);
386                            }
387                        }
388                    }
389
390                    // Same as with tables, don't optimize them if they're overwriting.
391                    FileType::Loc if options.db_optimize_datacored_tables || !dependencies.file_exists(&path, true, true, true) => {
392                        if let Ok(RFileDecoded::Loc(loc)) = rfile.decoded_mut() {
393                            if loc.optimize(dependencies, Some(&self_copy_map), options) && options.table_remove_empty_file {
394                                return Some(path);
395                            }
396                        }
397                    }
398
399                    FileType::Text => {
400
401                        // agf and model_statistics are debug files outputed by bob in older games.
402                        if (options.text_remove_agf_files && path.ends_with(".agf")) ||
403                            (options.text_remove_model_statistics_files && path.ends_with(".model_statistics")) {
404                            if let Ok(Some(RFileDecoded::Text(_))) = rfile.decode(&None, false, true) {
405                                return Some(path);
406                            }
407                        }
408
409                        else if !path.is_empty() && (
410                                (options.text_remove_unused_xml_prefab_folder && path.starts_with("prefabs/")) ||
411                                (options.text_remove_unused_xml_map_folders && (
412                                    path.starts_with("terrain/battles/") ||
413                                    path.starts_with("terrain/tiles/battle/")
414                                ))
415                            )
416                            && !path.ends_with(".wsmodel")
417                            && !path.ends_with(".environment")
418                            && !path.ends_with(".environment_group")
419                            && !path.ends_with(".environment_group.override")
420
421                            // Delete all xml files that match a bin file.
422                            && (
423                                path.ends_with(".xml") && (
424                                    pack_paths.contains(&path[..path.len() - 4].to_lowercase()) ||
425                                    pack_paths.contains(&(path[..path.len() - 4].to_lowercase() + ".bin"))
426                                )
427                            )
428                         {
429                            if let Ok(Some(RFileDecoded::Text(text))) = rfile.decode(&None, false, true) {
430                                if *text.format() == TextFormat::Xml {
431                                    return Some(path);
432
433                                }
434                            }
435                        }
436                    }
437
438                    FileType::PortraitSettings => {
439
440                        // In portrait settings file we look to cleanup variants and art sets that are not referenced by the game tables.
441                        // Meaning they are not used by the game.
442                        if let Ok(RFileDecoded::PortraitSettings(ps)) = rfile.decoded_mut() {
443                            if ps.optimize(dependencies, Some(&self_copy_map), options) && options.pts_remove_empty_file {
444                                return Some(path);
445                            }
446                        }
447                    }
448
449                    // Ignore the rest.
450                    _ => {}
451                }
452            }
453
454            None
455        }).collect::<Vec<String>>());
456
457        // If a table added is also marked for deletion, don't add it.
458        files_to_add.retain(|x| !files_to_delete.contains(x));
459
460        // Delete all the files marked for deletion.
461        files_to_delete.iter().for_each(|x| { self.remove(&ContainerPath::File(x.to_owned())); });
462
463        // Apply the most modern compression format the game supports, overriding whatever the pack had set.
464        // `set_compression_format` handles the "no formats supported" case (falls back to None → compress=false).
465        if options.pack_apply_compression {
466            let cf = game.compression_formats_supported().first().cloned().unwrap_or_default();
467            self.set_compression_format(cf, game);
468        }
469
470        // Return the deleted files, so the caller can know what got removed.
471        Ok((files_to_delete, files_to_add))
472    }
473}
474
475impl Optimizable for DB {
476
477    /// This function optimizes the provided [DB] file in order to make it smaller and more compatible.
478    ///
479    /// Specifically, it performs the following optimizations:
480    ///
481    /// - Removal of duplicated entries.
482    /// - Removal of ITM (Identical To Master) entries.
483    /// - Removal of ITNR (Identical To New Row) entries.
484    ///
485    /// It returns if the DB is empty, meaning it can be safetly deleted.
486    fn optimize(&mut self, dependencies: &mut Dependencies, container: Option<&BTreeMap<String, Pack>>, options: &OptimizerOptions) -> bool {
487        let container = match container {
488            Some(container) => container,
489            None => return false,
490        };
491
492        // Get a manipulable copy of all the entries, so we can optimize it.
493        let mut entries = self.data().to_vec();
494
495        match dependencies.db_data_datacored(self.table_name(), container, true, true) {
496            Ok(mut vanilla_tables) => {
497
498                // First, merge all vanilla and parent db fragments into a single HashSet.
499                let vanilla_table = vanilla_tables.iter_mut()
500                    .filter_map(|file| {
501                        if let Ok(RFileDecoded::DB(table)) = file.decoded() {
502                            Some(table.data().to_vec())
503                        } else { None }
504                    })
505                    .flatten()
506                    .map(|x| {
507
508                        // We map all floats here to string representations of floats, so we can actually compare them reliably.
509                        let json = x.iter().map(|data|
510                            if let DecodedData::F32(value) = data {
511                                DecodedData::StringU8(format!("{value:.4}"))
512                            } else if let DecodedData::F64(value) = data {
513                                DecodedData::StringU8(format!("{value:.4}"))
514                            } else {
515                                data.to_owned()
516                            }
517                        ).collect::<Vec<DecodedData>>();
518                        serde_json::to_string(&json).unwrap()
519                    })
520                    .collect::<HashSet<String>>();
521
522                // Remove ITM and ITNR entries.
523                let new_row = self.new_row().iter().map(|data|
524                    if let DecodedData::F32(value) = data {
525                        DecodedData::StringU8(format!("{value:.4}"))
526                    } else if let DecodedData::F64(value) = data {
527                        DecodedData::StringU8(format!("{value:.4}"))
528                    } else {
529                        data.to_owned()
530                    }
531                ).collect::<Vec<DecodedData>>();
532
533                entries.retain(|entry| {
534                    let entry_json = entry.iter().map(|data|
535                        if let DecodedData::F32(value) = data {
536                            DecodedData::StringU8(format!("{value:.4}"))
537                        } else if let DecodedData::F64(value) = data {
538                            DecodedData::StringU8(format!("{value:.4}"))
539                        } else {
540                            data.to_owned()
541                        }
542                    ).collect::<Vec<DecodedData>>();
543
544                    (!options.table_remove_itm_entries || !vanilla_table.contains(&serde_json::to_string(&entry_json).unwrap())) &&
545                    (!options.table_remove_itnr_entries || entry != &new_row)
546                });
547
548                // Dedupper. This is slower than a normal dedup, but it doesn't reorder rows.
549                if options.table_remove_duplicated_entries {
550                    let mut dummy_set = HashSet::new();
551                    entries.retain(|x| dummy_set.insert(x.clone()));
552                }
553
554                // Then we overwrite the entries and return if the table is empty or now, so we can optimize it further at the Container level.
555                //
556                // NOTE: This may fail, but in that case the table will not be left empty, which we check in the next line.
557                let _ = self.set_data(&entries);
558                self.data().is_empty()
559            }
560            Err(_) => false,
561        }
562    }
563}
564
565impl Optimizable for Loc {
566
567    /// This function optimizes the provided [Loc] file in order to make it smaller and more compatible.
568    ///
569    /// Specifically, it performs the following optimizations:
570    ///
571    /// - Removal of duplicated entries.
572    /// - Removal of ITM (Identical To Master) entries.
573    /// - Removal of ITNR (Identical To New Row) entries.
574    ///
575    /// It returns if the Loc is empty, meaning it can be safetly deleted.
576    fn optimize(&mut self, dependencies: &mut Dependencies, _container: Option<&BTreeMap<String, Pack>>, options: &OptimizerOptions) -> bool {
577
578        // Get a manipulable copy of all the entries, so we can optimize it.
579        let mut entries = self.data().to_vec();
580        match dependencies.loc_data(true, true) {
581            Ok(mut vanilla_tables) => {
582
583                // First, merge all vanilla and parent locs into a single HashMap<key, value>. We don't care about the third column.
584                let vanilla_table = vanilla_tables.iter_mut()
585                    .filter_map(|file| {
586                        if let Ok(RFileDecoded::Loc(table)) = file.decoded() {
587                            Some(table.data().to_vec())
588                        } else { None }
589                    })
590                    .flat_map(|data| data.iter()
591                        .map(|data| (data[0].data_to_string().to_string(), data[1].data_to_string().to_string()))
592                        .collect::<Vec<(String, String)>>())
593                    .collect::<HashMap<String, String>>();
594
595                // Remove ITM and ITNR entries.
596                let new_row = self.new_row();
597                entries.retain(|entry| {
598                    if options.table_remove_itnr_entries && entry == &new_row {
599                        return false;
600                    }
601
602                    if options.table_remove_itm_entries {
603                        match vanilla_table.get(&*entry[0].data_to_string()) {
604                            Some(vanilla_value) => return &*entry[1].data_to_string() != vanilla_value,
605                            None => return true
606                        }
607                    }
608
609                    true
610                });
611
612                // Dedupper. This is slower than a normal dedup, but it doesn't reorder rows.
613                if options.table_remove_duplicated_entries {
614                    let mut dummy_set = HashSet::new();
615                    entries.retain(|x| dummy_set.insert(x.clone()));
616                }
617
618                // Then we overwrite the entries and return if the table is empty or now, so we can optimize it further at the Container level.
619                //
620                // NOTE: This may fail, but in that case the table will not be left empty, which we check in the next line.
621                let _ = self.set_data(&entries);
622                self.data().is_empty()
623            }
624            Err(_) => false,
625        }
626    }
627}
628
629impl Optimizable for PortraitSettings {
630
631    /// This function optimizes the provided [PortraitSettings] file in order to make it smaller.
632    ///
633    /// Specifically, it performs the following optimizations:
634    ///
635    /// - Removal of variants not present in the variants table (unused data).
636    /// - Removal of art sets not present in the campaign_character_arts table (unused data).
637    ///
638    /// It returns if the PortraitSettings is empty, meaning it can be safetly deleted.
639    fn optimize(&mut self, dependencies: &mut Dependencies, container: Option<&BTreeMap<String, Pack>>, options: &OptimizerOptions) -> bool {
640
641        // Get a manipulable copy of all the entries, so we can optimize it.
642        let mut entries = self.entries().to_vec();
643
644        // Get the list of art set ids and variant filenames to check against.
645        let art_set_ids = dependencies.db_values_from_table_name_and_column_name(container, "campaign_character_arts_tables", "art_set_id", true, true);
646        let mut variant_filenames = dependencies.db_values_from_table_name_and_column_name(container, "variants_tables", "variant_filename", true, true);
647        if variant_filenames.is_empty() {
648            variant_filenames = dependencies.db_values_from_table_name_and_column_name(container, "variants_tables", "variant_name", true, true);
649        }
650
651        // Do not do anything if we don't have ids and variants.
652        if art_set_ids.is_empty() || variant_filenames.is_empty() {
653            return false;
654        }
655
656        entries.retain_mut(|entry| {
657            entry.variants_mut().retain_mut(|variant| {
658                if options.pts_remove_empty_masks {
659                    if variant.file_mask_1().ends_with(EMPTY_MASK_PATH_END) {
660                        variant.file_mask_1_mut().clear();
661                    }
662                    if variant.file_mask_2().ends_with(EMPTY_MASK_PATH_END) {
663                        variant.file_mask_2_mut().clear();
664                    }
665                    if variant.file_mask_3().ends_with(EMPTY_MASK_PATH_END) {
666                        variant.file_mask_3_mut().clear();
667                    }
668                }
669
670                if options.pts_remove_unused_variants {
671                    variant_filenames.contains(variant.filename())
672                } else {
673                    true
674                }
675            });
676
677            if options.pts_remove_unused_art_sets {
678                art_set_ids.contains(entry.id())
679            } else {
680                true
681            }
682        });
683
684        self.set_entries(entries);
685        self.entries().is_empty()
686    }
687}