spitfire_draw/
tiles.rs

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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use crate::{
    context::DrawContext,
    sprite::SpriteTexture,
    utils::{Drawable, ShaderRef, Vertex},
};
use smallvec::SmallVec;
use spitfire_glow::{
    graphics::{Graphics, GraphicsBatch},
    renderer::{GlowBlending, GlowUniformValue},
};
use std::{
    borrow::Cow,
    cell::RefCell,
    collections::{HashMap, HashSet},
    ops::{Index, IndexMut},
};
use vek::{Mat4, Quaternion, Rect, Rgba, Transform, Vec2, Vec3};

#[derive(Debug, Clone)]
pub struct TileSetItem {
    pub region: Rect<f32, f32>,
    pub page: f32,
    pub tint: Rgba<f32>,
    pub size: Vec2<usize>,
    pub offset: Vec2<isize>,
}

impl Default for TileSetItem {
    fn default() -> Self {
        Self {
            region: Rect::new(0.0, 0.0, 1.0, 1.0),
            page: 0.0,
            tint: Rgba::white(),
            size: Vec2::new(1, 1),
            offset: Default::default(),
        }
    }
}

impl TileSetItem {
    pub fn region(mut self, value: Rect<f32, f32>) -> Self {
        self.region = value;
        self
    }

    pub fn page(mut self, value: f32) -> Self {
        self.page = value;
        self
    }

    pub fn tint(mut self, value: Rgba<f32>) -> Self {
        self.tint = value;
        self
    }

    pub fn size(mut self, value: Vec2<usize>) -> Self {
        self.size = value;
        self
    }

    pub fn offset(mut self, value: Vec2<isize>) -> Self {
        self.offset = value;
        self
    }
}

#[derive(Debug, Default, Clone)]
pub struct TileSet {
    pub shader: Option<ShaderRef>,
    pub textures: SmallVec<[SpriteTexture; 4]>,
    pub uniforms: HashMap<Cow<'static, str>, GlowUniformValue>,
    pub blending: Option<GlowBlending>,
    pub mappings: HashMap<usize, TileSetItem>,
}

impl TileSet {
    pub fn single(texture: SpriteTexture) -> Self {
        Self {
            textures: vec![texture].into(),
            ..Default::default()
        }
    }

    pub fn shader(mut self, value: ShaderRef) -> Self {
        self.shader = Some(value);
        self
    }

    pub fn texture(mut self, value: SpriteTexture) -> Self {
        self.textures.push(value);
        self
    }

    pub fn uniform(mut self, key: Cow<'static, str>, value: GlowUniformValue) -> Self {
        self.uniforms.insert(key, value);
        self
    }

    pub fn blending(mut self, value: GlowBlending) -> Self {
        self.blending = Some(value);
        self
    }

    pub fn mapping(mut self, id: usize, item: TileSetItem) -> Self {
        self.mappings.insert(id, item);
        self
    }

    pub fn mappings(mut self, iter: impl IntoIterator<Item = (usize, TileSetItem)>) -> Self {
        self.mappings.extend(iter);
        self
    }
}

#[derive(Debug, Default, Clone)]
pub struct TilesEmitter {
    pub transform: Transform<f32, f32, f32>,
    pub tile_size: Vec2<f32>,
    pub screen_space: bool,
}

impl TilesEmitter {
    pub fn transform(mut self, value: Transform<f32, f32, f32>) -> Self {
        self.transform = value;
        self
    }

    pub fn position(mut self, value: Vec2<f32>) -> Self {
        self.transform.position = value.into();
        self
    }

    pub fn orientation(mut self, value: Quaternion<f32>) -> Self {
        self.transform.orientation = value;
        self
    }

    pub fn rotation(mut self, angle_radians: f32) -> Self {
        self.transform.orientation = Quaternion::rotation_z(angle_radians);
        self
    }

    pub fn scale(mut self, value: Vec2<f32>) -> Self {
        self.transform.scale = Vec3::new(value.x, value.y, 1.0);
        self
    }

    pub fn tile_size(mut self, value: Vec2<f32>) -> Self {
        self.tile_size = value;
        self
    }

    pub fn screen_space(mut self, value: bool) -> Self {
        self.screen_space = value;
        self
    }

    pub fn emit<'a, I: IntoIterator<Item = TileInstance>>(
        &'a self,
        set: &'a TileSet,
        instances: I,
    ) -> TilesDraw<I> {
        TilesDraw {
            emitter: self,
            tileset: set,
            instances: RefCell::new(Some(instances)),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TileInstance {
    pub id: usize,
    pub location: Vec2<usize>,
}

impl TileInstance {
    pub fn new(id: usize, location: Vec2<usize>) -> Self {
        Self { id, location }
    }
}

pub struct TilesDraw<'a, I: IntoIterator<Item = TileInstance>> {
    emitter: &'a TilesEmitter,
    tileset: &'a TileSet,
    instances: RefCell<Option<I>>,
}

impl<'a, I: IntoIterator<Item = TileInstance>> Drawable for TilesDraw<'a, I> {
    fn draw(&self, context: &mut DrawContext, graphics: &mut Graphics<Vertex>) {
        let batch = GraphicsBatch {
            shader: context.shader(self.tileset.shader.as_ref()),
            uniforms: self
                .tileset
                .uniforms
                .iter()
                .map(|(k, v)| (k.clone(), v.to_owned()))
                .chain(std::iter::once((
                    "u_projection_view".into(),
                    GlowUniformValue::M4(
                        if self.emitter.screen_space {
                            graphics.main_camera.screen_matrix()
                        } else {
                            graphics.main_camera.world_matrix()
                        }
                        .into_col_array(),
                    ),
                )))
                .chain(
                    self.tileset
                        .textures
                        .iter()
                        .enumerate()
                        .map(|(index, texture)| {
                            (texture.sampler.clone(), GlowUniformValue::I1(index as _))
                        }),
                )
                .collect(),
            textures: self
                .tileset
                .textures
                .iter()
                .filter_map(|texture| {
                    Some((context.texture(Some(&texture.texture))?, texture.filtering))
                })
                .collect(),
            blending: self
                .tileset
                .blending
                .unwrap_or_else(|| context.top_blending()),
            scissor: None,
        };
        graphics.stream.batch_optimized(batch);
        let transform = Mat4::from(context.top_transform()) * Mat4::from(self.emitter.transform);
        graphics.stream.transformed(
            move |stream| {
                let instances = match self.instances.borrow_mut().take() {
                    Some(instances) => instances,
                    None => return,
                };
                for instance in instances {
                    if let Some(tile) = self.tileset.mappings.get(&instance.id) {
                        let offset = Vec2 {
                            x: (instance.location.x as isize + tile.offset.x) as f32,
                            y: (instance.location.y as isize + tile.offset.y) as f32,
                        } * self.emitter.tile_size;
                        let size = Vec2 {
                            x: tile.size.x as f32,
                            y: tile.size.y as f32,
                        } * self.emitter.tile_size;
                        let color = tile.tint.into_array();
                        stream.quad([
                            Vertex {
                                position: [offset.x, offset.y],
                                uv: [tile.region.x, tile.region.y, tile.page],
                                color,
                            },
                            Vertex {
                                position: [offset.x + size.x, offset.y],
                                uv: [tile.region.x + tile.region.w, tile.region.y, tile.page],
                                color,
                            },
                            Vertex {
                                position: [offset.x + size.x, offset.y + size.y],
                                uv: [
                                    tile.region.x + tile.region.w,
                                    tile.region.y + tile.region.h,
                                    tile.page,
                                ],
                                color,
                            },
                            Vertex {
                                position: [offset.x, offset.y + size.y],
                                uv: [tile.region.x, tile.region.y + tile.region.h, tile.page],
                                color,
                            },
                        ]);
                    }
                }
            },
            |vertex| {
                let point = transform.mul_point(Vec2::from(vertex.position));
                vertex.position[0] = point.x;
                vertex.position[1] = point.y;
            },
        );
    }
}

#[derive(Debug, Clone)]
pub struct TileMap {
    pub include_ids: HashSet<usize>,
    pub exclude_ids: HashSet<usize>,
    size: Vec2<usize>,
    buffer: Vec<usize>,
}

impl TileMap {
    pub fn new(size: Vec2<usize>, fill_id: usize) -> Self {
        Self {
            include_ids: Default::default(),
            exclude_ids: Default::default(),
            size,
            buffer: vec![fill_id; size.x * size.y],
        }
    }

    pub fn with_buffer(size: Vec2<usize>, buffer: Vec<usize>) -> Option<Self> {
        if buffer.len() == size.x * size.y {
            Some(Self {
                include_ids: Default::default(),
                exclude_ids: Default::default(),
                size,
                buffer,
            })
        } else {
            None
        }
    }

    pub fn size(&self) -> Vec2<usize> {
        self.size
    }

    pub fn buffer(&self) -> &[usize] {
        &self.buffer
    }

    pub fn buffer_mut(&mut self) -> &mut [usize] {
        &mut self.buffer
    }

    pub fn index(&self, location: impl Into<Vec2<usize>>) -> usize {
        let location = location.into();
        (location.y % self.size.y) * self.size.x + (location.x % self.size.x)
    }

    pub fn location(&self, index: usize) -> Vec2<usize> {
        Vec2 {
            x: index % self.size.x,
            y: (index / self.size.y) % self.size.y,
        }
    }

    pub fn get(&self, location: impl Into<Vec2<usize>>) -> Option<usize> {
        let index = self.index(location);
        self.buffer.get(index).copied()
    }

    pub fn set(&mut self, location: impl Into<Vec2<usize>>, id: usize) {
        let index = self.index(location);
        if let Some(item) = self.buffer.get_mut(index) {
            *item = id;
        }
    }

    pub fn fill(&mut self, from: impl Into<Vec2<usize>>, to: impl Into<Vec2<usize>>, id: usize) {
        let from = from.into();
        let to = to.into();
        for y in from.y..to.y {
            for x in from.x..to.x {
                self.set(Vec2::new(x, y), id);
            }
        }
    }

    pub fn is_id_valid(&self, id: usize) -> bool {
        (self.include_ids.is_empty() || self.include_ids.contains(&id))
            && (self.exclude_ids.is_empty() || !self.exclude_ids.contains(&id))
    }

    pub fn emit(&self) -> impl Iterator<Item = TileInstance> + '_ {
        self.buffer.iter().enumerate().filter_map(|(index, id)| {
            if self.is_id_valid(*id) {
                Some(TileInstance {
                    id: *id,
                    location: self.location(index),
                })
            } else {
                None
            }
        })
    }

    pub fn emit_region(
        &self,
        region: impl Into<Rect<usize, usize>>,
        repeating: bool,
    ) -> impl Iterator<Item = TileInstance> + '_ {
        let mut region = region.into();
        if !repeating {
            if region.x + region.w > self.size.x {
                region.w = self.size.x.saturating_sub(region.x);
            }
            if region.y + region.h > self.size.y {
                region.h = self.size.y.saturating_sub(region.y);
            }
        }
        (region.y..(region.y + region.h)).flat_map(move |y| {
            (region.x..(region.x + region.w)).filter_map(move |x| {
                let location = Vec2 { x, y };
                if let Some(id) = self.get(location) {
                    if self.is_id_valid(id) {
                        return Some(TileInstance { id, location });
                    }
                }
                None
            })
        })
    }
}

impl<T: Into<Vec2<usize>>> Index<T> for TileMap {
    type Output = usize;

    fn index(&self, location: T) -> &Self::Output {
        let location = location.into();
        let index = self.index(location);
        self.buffer
            .get(index)
            .unwrap_or_else(|| panic!("Invalid location: {}", location))
    }
}

impl<T: Into<Vec2<usize>>> IndexMut<T> for TileMap {
    fn index_mut(&mut self, location: T) -> &mut Self::Output {
        let location = location.into();
        let index = self.index(location);
        self.buffer
            .get_mut(index)
            .unwrap_or_else(|| panic!("Invalid location: {}", location))
    }
}