1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
use super::{
    directory_manager::DirectoryManager, errors::*, folders::*, pipelines::PipelineManager, utils,
    YyResource, YyResourceData, YyResourceHandler, YypSerialization,
};
use crate::Resource;
use anyhow::{Context, Result as AnyResult};
use object_yy::Object;
use std::{fs, path::Path};
use yy_typings::{script::Script, sprite_yy::*, utils::TrailingCommaUtility, Yyp};

static TCU: once_cell::sync::Lazy<TrailingCommaUtility> =
    once_cell::sync::Lazy::new(TrailingCommaUtility::new);

#[derive(Debug, PartialEq)]
pub struct YypBoss {
    pub directory_manager: DirectoryManager,
    pub pipeline_manager: PipelineManager,
    pub sprites: YyResourceHandler<Sprite>,
    pub scripts: YyResourceHandler<Script>,
    pub objects: YyResourceHandler<Object>,
    pub vfs: Vfs,
    yyp: Yyp,
}

impl YypBoss {
    /// Creates a new YyBoss Manager and performs startup file reading.
    pub fn new<P: AsRef<Path>>(path_to_yyp: P) -> Result<YypBoss, StartupError> {
        let yyp: Yyp = utils::deserialize_json_tc(&path_to_yyp, &TCU)?;

        let directory_manager = DirectoryManager::new(path_to_yyp.as_ref())?;

        let mut yyp_boss = Self {
            vfs: Vfs::new(&yyp.name),
            sprites: YyResourceHandler::new(),
            scripts: YyResourceHandler::new(),
            objects: YyResourceHandler::new(),
            pipeline_manager: PipelineManager::new(&directory_manager)?,
            directory_manager,
            yyp,
        };

        // Load in Folders
        yyp_boss.vfs.load_in_folders(&yyp_boss.yyp.folders);

        fn load_in_resource<T: YyResource>(
            resource: &mut YyResourceHandler<T>,
            folder_graph: &mut Vfs,
            yyp_resources: &[YypResource],
            directory_manager: &DirectoryManager,
        ) -> Result<(), StartupError> {
            for yyp_resource in yyp_resources
                .iter()
                .filter(|value| value.id.path.starts_with(T::SUBPATH_NAME))
            {
                let yy_file_path = directory_manager
                    .root_directory()
                    .join(&yyp_resource.id.path);

                let yy_file: T = utils::deserialize_json_tc(&yy_file_path, &TCU)?;

                folder_graph.load_in_file(&yy_file, yyp_resource.order)?;
                resource.load_on_startup(yy_file);
            }

            Ok(())
        }

        // Load in our Resources
        // @update_resource
        load_in_resource(
            &mut yyp_boss.sprites,
            &mut yyp_boss.vfs,
            &yyp_boss.yyp.resources,
            &yyp_boss.directory_manager,
        )?;
        load_in_resource(
            &mut yyp_boss.scripts,
            &mut yyp_boss.vfs,
            &yyp_boss.yyp.resources,
            &yyp_boss.directory_manager,
        )?;
        load_in_resource(
            &mut yyp_boss.objects,
            &mut yyp_boss.vfs,
            &yyp_boss.yyp.resources,
            &yyp_boss.directory_manager,
        )?;

        Ok(yyp_boss)
    }

    /// Gets the default texture path, if it exists. The "Default" group simply
    /// has the name `"Default"`.
    ///
    /// This method will almost certainly be refactored soon to a dedicated TextureManager.
    pub fn default_texture_path(&self) -> Option<TexturePath> {
        self.yyp
            .texture_groups
            .iter()
            .find(|tex| tex.name == "Default")
            .map(|texture_group| texture_group.into())
    }

    /// Serializes the YypBoss data to disk at the path of the Yyp.
    pub fn serialize(&mut self) -> AnyResult<()> {
        // serialize the vfs
        self.vfs
            .serialize(&mut self.yyp.folders, &mut self.yyp.resources);

        // serialize all the whatever
        // @update_resource
        self.sprites.serialize(&self.directory_manager)?;
        self.objects.serialize(&self.directory_manager)?;
        self.scripts.serialize(&self.directory_manager)?;

        // serialize the pipeline manifests
        self.pipeline_manager
            .serialize(&self.directory_manager)
            .context("serializing pipelines")?;

        // Serialize Ourselves:
        let string = self.yyp.yyp_serialization(0);
        fs::write(&self.directory_manager.yyp(), &string)?;

        Ok(())
    }

    pub fn version_string(&self) -> &str {
        &self.yyp.meta_data.ide_version
    }

    pub fn tcu(&self) -> &TrailingCommaUtility {
        &TCU
    }

    pub fn yyp(&self) -> &Yyp {
        &self.yyp
    }
}

// for generics
impl YypBoss {
    /// Adds a new resource, which must not already exist within the project.
    pub fn add_resource<T: YyResource>(
        &mut self,
        yy_file: T,
        associated_data: T::AssociatedData,
    ) -> Result<(), ResourceManipulationError> {
        if let Some(r) = self.vfs.resource_names.get(yy_file.name()) {
            return Err(ResourceManipulationError::BadAdd(r.resource));
        }

        self.vfs.new_resource_end(&yy_file)?;
        let handler = T::get_handler_mut(self);

        if handler.set(yy_file, associated_data).is_some() {
            Err(ResourceManipulationError::InternalError)
        } else {
            Ok(())
        }
    }

    /// Adds a new resource, which must not already exist within the project.
    pub fn remove_resource<T: YyResource>(
        &mut self,
        name: &str,
    ) -> Result<(T, Option<T::AssociatedData>), ResourceManipulationError> {
        // remove the file from the VFS...
        self.vfs.remove_resource(name, T::RESOURCE)?;

        let handler = T::get_handler_mut(self);
        handler
            .remove(name, &TCU)
            .ok_or_else(|| ResourceManipulationError::InternalError)
    }

    /// Move a resource within the Asset Tree
    pub fn move_resource<T: YyResource>(
        &mut self,
        name: &str,
        new_parent: ViewPath,
    ) -> Result<(), ResourceManipulationError> {
        // vfs
        self.vfs
            .move_resource(name, T::RESOURCE, &new_parent.path)
            .map_err(ResourceManipulationError::FolderGraphError)?;

        let handler = T::get_handler_mut(self);
        handler
            .remove(name, &TCU)
            .ok_or_else(|| ResourceManipulationError::InternalError)?;

        handler.edit_parent(name, new_parent);

        Ok(())
    }

    /// Gets a resource via the type. Users should probably not use this method unless they're doing
    /// some generic code. Instead, simply use each resources manager as appropriate -- for example,
    /// to get an object's data, use `yyp_boss.objects.get`.
    ///
    /// *Nb*: `YyResourceData` might not have any AssociatedData on it. See its warning on how Associated
    /// Data is held lazily.
    pub fn get_resource<T: YyResource>(&self, name: &str) -> Option<&YyResourceData<T>> {
        let handler = T::get_handler(self);
        handler.get(name)
    }
}

// resource handling!
impl YypBoss {
    /// Move a resource within the Asset Tree, using the passed in resource type
    pub fn move_resource_dynamic(
        &mut self,
        name: &str,
        new_parent: ViewPath,
        resource: Resource,
    ) -> Result<(), ResourceManipulationError> {
        match resource {
            Resource::Sprite => self.move_resource::<Sprite>(name, new_parent),
            Resource::Script => self.move_resource::<Script>(name, new_parent),
            Resource::Object => self.move_resource::<Object>(name, new_parent),
        }
    }

    /// Removes a folder RECURSIVELY. **All resources within will be removed**. Be careful out there.
    pub fn remove_folder(
        &mut self,
        folder: &ViewPathLocation,
    ) -> Result<(), ResourceManipulationError> {
        // easy!
        if self.vfs.remove_empty_folder(folder).is_ok() {
            return Ok(());
        }

        // okay okay, more complex operation
        let deleted_resources = self.vfs.remove_non_empty_folder(folder)?;

        for (fsys, descriptor) in deleted_resources {
            match descriptor.resource {
                Resource::Sprite => {
                    self.scripts.remove(&fsys.name, &TCU);
                }
                Resource::Script => {
                    self.scripts.remove(&fsys.name, &TCU);
                }
                Resource::Object => {
                    self.objects.remove(&fsys.name, &TCU);
                }
            }
        }

        Ok(())
    }
}