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
use crate::{
    composite_renderer::{Command, Image},
    sprite_sheet_asset_protocol::SpriteSheetAsset,
};
use core::{
    assets::{
        asset::{Asset, AssetId},
        database::AssetsDatabase,
        protocol::{AssetLoadResult, AssetProtocol, AssetVariant, Meta},
    },
    Ignite, Scalar,
};
use serde::{Deserialize, Serialize};
use std::{any::Any, collections::HashMap};

#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub struct LayerObject {
    pub name: String,
    pub object_type: String,
    pub visible: bool,
    pub x: isize,
    pub y: isize,
    pub width: usize,
    pub height: usize,
}

#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub enum LayerData {
    Tiles(Vec<usize>),
    Objects(Vec<LayerObject>),
}

impl LayerData {
    pub fn tiles(&self) -> Option<&[usize]> {
        if let LayerData::Tiles(data) = self {
            Some(data)
        } else {
            None
        }
    }

    pub fn objects(&self) -> Option<&[LayerObject]> {
        if let LayerData::Objects(data) = self {
            Some(data)
        } else {
            None
        }
    }
}

#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub struct Layer {
    pub name: String,
    pub data: LayerData,
}

#[derive(Ignite, Debug, Clone, Serialize, Deserialize)]
pub struct Map {
    pub cols: usize,
    pub rows: usize,
    pub tile_width: usize,
    pub tile_height: usize,
    pub sprite_sheets: Vec<String>,
    pub tiles_mapping: HashMap<usize, (String, String)>,
    pub layers: Vec<Layer>,
}

impl Map {
    pub fn size(&self) -> (usize, usize) {
        (self.cols * self.tile_width, self.rows * self.tile_height)
    }

    pub fn layer_by_name(&self, name: &str) -> Option<&Layer> {
        self.layers.iter().find(|layer| layer.name == name)
    }

    pub fn build_render_commands_from_layer_by_name<'a>(
        &self,
        name: &str,
        chunk_offset: (usize, usize),
        chunk_size: Option<(usize, usize)>,
        assets: &AssetsDatabase,
    ) -> Option<Vec<Command<'a>>> {
        let index = self.layers.iter().position(|layer| layer.name == name)?;
        self.build_render_commands_from_layer(index, chunk_offset, chunk_size, assets)
    }

    pub fn build_render_commands_from_layer<'a>(
        &self,
        index: usize,
        chunk_offset: (usize, usize),
        chunk_size: Option<(usize, usize)>,
        assets: &AssetsDatabase,
    ) -> Option<Vec<Command<'a>>> {
        if self.tiles_mapping.is_empty() {
            return None;
        }
        let layer = self.layers.get(index)?;
        if let LayerData::Tiles(data) = &layer.data {
            let atlases = self
                .sprite_sheets
                .iter()
                .map(|s| {
                    let info = assets
                        .asset_by_path(&format!("atlas://{}", s))?
                        .get::<SpriteSheetAsset>()?
                        .info();
                    Some((s.clone(), info))
                })
                .collect::<Option<HashMap<_, _>>>()?;
            let mut commands = Vec::with_capacity(2 + self.cols * self.rows);
            commands.push(Command::Store);
            let width = self.tile_width as Scalar;
            let height = self.tile_height as Scalar;
            let chunk_size = chunk_size.unwrap_or((self.cols, self.rows));
            let cols_start = chunk_offset.0.min(self.cols);
            let cols_end = (chunk_offset.0 + chunk_size.0).min(self.cols);
            let rows_start = chunk_offset.1.min(self.rows);
            let rows_end = (chunk_offset.1 + chunk_size.1).min(self.rows);
            for col in cols_start..cols_end {
                for row in rows_start..rows_end {
                    let i = self.cols * row + col;
                    let id = data.get(i).unwrap_or(&0);
                    if let Some((sprite_sheet, name)) = &self.tiles_mapping.get(id) {
                        let info = atlases.get(sprite_sheet)?;
                        let x = width * col as Scalar;
                        let y = height * row as Scalar;
                        let frame = info.frames.get(name)?.frame;
                        commands.push(Command::Draw(
                            Image::new_owned(info.meta.image_name())
                                .source(Some(frame))
                                .destination(Some([x, y, width, height].into()))
                                .into(),
                        ));
                    }
                }
            }
            commands.push(Command::Restore);
            Some(commands)
        } else {
            None
        }
    }
}

pub struct MapAsset {
    map: Map,
    sprite_sheet_assets: Vec<AssetId>,
}

impl MapAsset {
    pub fn map(&self) -> &Map {
        &self.map
    }

    pub fn sprite_sheet_assets(&self) -> &[AssetId] {
        &self.sprite_sheet_assets
    }
}

pub struct MapAssetProtocol;

impl AssetProtocol for MapAssetProtocol {
    fn name(&self) -> &str {
        "map"
    }

    fn on_load(&mut self, data: Vec<u8>) -> AssetLoadResult {
        let map: Map = bincode::deserialize(&data).unwrap();
        let list = map
            .sprite_sheets
            .iter()
            .map(|s| (s.clone(), format!("atlas://{}", s)))
            .collect::<Vec<_>>();
        AssetLoadResult::Yield(Some(Box::new(map)), list)
    }

    fn on_resume(&mut self, payload: Meta, list: &[(&str, &Asset)]) -> AssetLoadResult {
        let map = *(payload.unwrap() as Box<dyn Any + Send>)
            .downcast::<Map>()
            .unwrap();
        let sprite_sheet_assets = list.iter().map(|(_, asset)| asset.id()).collect::<Vec<_>>();
        AssetLoadResult::Data(Box::new(MapAsset {
            map,
            sprite_sheet_assets,
        }))
    }

    fn on_unload(&mut self, asset: &Asset) -> Option<Vec<AssetVariant>> {
        asset.get::<MapAsset>().map(|asset| {
            asset
                .sprite_sheet_assets
                .iter()
                .map(|a| AssetVariant::Id(*a))
                .collect::<Vec<_>>()
        })
    }
}