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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
use crate::{map_dir, datafile_parse, datafile_save, map_parse, map_checks};

use bitflags::bitflags;
use image::RgbaImage;
use ndarray::Array2;
use serde::{Serialize, Deserialize};
use structview::View;
use thiserror::Error;

use std::io;

#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", tag = "type")]
pub enum Version {
    DDNet06,
    Teeworlds07,
}

/// The TwMap struct represents a Teeworlds 0.7 map or a DDNet 0.6 map.
/// Which one of those it is will always be determined during the parsing process and is stored in the `version` field.
///
/// The library cares a lot about the integrity of the struct.
/// The [`check`](struct.TwMap.html#method.check) method verifies that all limitations are met.
///
/// # Parsing
///
/// TwMap has several different parsing methods: [`parse`](struct.TwMap.html#method.parse), [`parse_path`](struct.TwMap.html#method.parse_path), [`parse_file`](struct.TwMap.html#method.parse_file), [`parse_dir`](struct.TwMap.html#method.parse_dir), [`parse_datafile`](struct.TwMap.html#method.parse_datafile)
///
/// Each of them execute the [`check`](struct.TwMap.html#method.check) method to finalize the process.
///
/// If you want to leave out the checks, you can use the `_unchecked` variation of that parsing method if it is provided.
/// Note that the `_unchecked` variation might also exclude some common fixes.
///
/// # Saving
///
/// TwMap can save maps in the binary format ([`save`](struct.TwMap.html#method.save), [`save_file`](struct.TwMap.html#method.save_file)) and in the MapDir format ([`save_dir`](struct.TwMap.html#method.save_dir)).
///
/// Each saving method will first execute [`check`](struct.TwMap.html#method.check), if the map fails the check, it will not be saved.
///
/// # Loading
///
/// When loading a map from the binary format, a lot of data will be decompressed in the process.
/// Since this is the main slowdown factor, some larger data chunks will be left compressed.
/// The compressed parts are the `data` field in [`Image`](struct.Image.html)s and [`Sound`](struct.Sound.html)s and the `tiles` field in tile map layers.
/// If you want to save the map at the end anyways, then you can simply use the [`load`](struct.TwMap.html#method.load) method on the entire map.
/// If not, use the `load` method only on the images, sounds and tile map layers that you want to use.
///
/// **Note:**
/// - you can also use `load` on slices and vectors of Images, Sounds, Layers, Groups with layers,
/// - some methods rely on having parts of the map loaded, especially more abstract methods like [`mirror`](struct.TwMap.html#method.mirror) and [`rotate_right`](struct.TwMap.html#method.rotate_right)
/// - if you want to leave out the checks on the decompressed data, you can use the `load_unchecked` methods

#[derive(Debug, Clone, PartialEq)]
pub struct TwMap {
    pub version: Version,
    pub info: Info,
    pub images: Vec<Image>,
    pub envelopes: Vec<Envelope>,
    pub groups: Vec<Group>,
    pub sounds: Vec<Sound>,
}

#[derive(Error, Debug)]
pub enum Error {
    #[error("Map - {0}")]
    Map(#[from] map_checks::MapError),
    #[error("Map from Datafile - {0}")]
    MapFromDatafile(#[from] map_parse::MapFromDatafileError),
    #[error("Datafile saving - {0}")]
    DatafileSaving(#[from] datafile_save::SizeError),
    #[error("Datafile parsing - {0}")]
    DatafileParse(#[from] datafile_parse::DatafileParseError),
    #[error("IO - {0}")]
    Io(#[from] io::Error),
    #[error("MapDir - {0}")]
    Dir(#[from] map_dir::MapDirError),
}

#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)]
// identifier for all relevant types of layers
pub enum LayerKind {
    Game,
    Tiles,
    Quads,
    Front,
    Tele,
    Speedup,
    Switch,
    Tune,
    Sounds,
    Invalid(InvalidLayerKind),
}

#[derive(Debug, Eq, PartialOrd, PartialEq, Copy, Clone, Hash)]
pub enum InvalidLayerKind {
    Unknown(i32), // unknown value of 'LAYERTYPE' identifier
    UnknownTileMap(i32), // 'LAYERTYPE' identified a tile layer, unknown value of 'TILESLAYERFLAG' identifier
    NoType, // layer item too short to get 'LAYERTYPE' identifier
    NoTypeTileMap, // 'LAYERTYPE' identified a tile layer, layer item too short to get 'TILESLAYERFLAG' identifier
}

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
// identifies type of a map item by type_id
pub enum ItemType {
    Version,
    Info,
    Image,
    Envelope,
    Group,
    Layer,
    EnvPoints,
    Sound,
    AutoMapper,
    Unknown(u16),
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
// for holding compressed data, since decompression is expensive
pub enum CompressedData<T, U> {
    Compressed(Vec<u8>, usize, U),
    Loaded(T),
}

#[derive(Debug, Default, PartialEq, Clone, Serialize, Deserialize)]
pub struct Info {
    pub author: String,
    pub version: String,
    pub credits: String,
    pub license: String,
    pub settings: Vec<String>,
}

#[derive(Debug, PartialEq, Clone)]
pub enum Image {
    External(ExternalImage),
    Embedded(EmbeddedImage),
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct ExternalImage {
    #[serde(skip)]
    pub name: String, // file name sanitized

    pub width: i32,
    pub height: i32,
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub struct ImageLoadInfo {
    pub width: i32,
    pub height: i32,
}

#[derive(Debug, PartialEq, Clone)]
pub struct EmbeddedImage {
    pub name: String, // file name sanitized

    pub image: CompressedData<RgbaImage, ImageLoadInfo>, // None if the image is external (not embedded)
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Group {
    pub name: String,
    // offsets the layer from the upper left corner of the map (in tiles)
    pub offset_x: i32,
    pub offset_y: i32,
    // parallax of the group
    pub parallax_x: i32,
    pub parallax_y: i32,
    // which layers belong to the group
    #[serde(skip)]
    pub layers: Vec<Layer>,
    // lets the group's layers disappear at some distance
    pub clipping: bool,
    pub clip_x: i32,
    pub clip_y: i32,
    pub clip_width: i32,
    pub clip_height: i32,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Sound {
    pub name: String,
    pub data: CompressedData<Vec<u8>, ()>,
}

#[derive(Default, Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct AutoMapper {
    pub config: Option<u16>,
    pub seed: i32,
    pub automatic: bool,
}

#[derive(Debug, Copy, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BezierCurve<T> {
    pub in_tangent_dx: T,
    pub in_tangent_dy: T,
    pub out_tangent_dx: T,
    pub out_tangent_dy: T,
}

#[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
// for envelopes points, how the value changes in between 2 values (curve type is at second point)
pub enum CurveKind<T> {
    Step,           // abrupt drop at second point
    Linear,         // linear value change
    Slow,           // first slow, later much faster value change
    Fast,           // first fast, later much slower value change
    Smooth,         // slow, faster then once more slow value change
    Bezier(BezierCurve<T>),      // very flexible curve, each channel individually
    Unknown(i32),   // for forwards compatibility, will error on check
}

#[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)]
// envelope point for a ColorEnvelope
pub struct EnvPoint<T> {
    pub time: i32, // in ms
    pub content: T,
    #[serde(flatten)]
    pub curve: CurveKind<T>,
}

/// Default bezier tangent values are all zeroes.
/// This trait implements the constructors for those values.
/// only I32Color needs to implement this manually, since volume (i32) and Position are already all zeroes in their default values.
pub trait BezierDefault: Default {
    fn bezier_default() -> Self {
        Default::default()
    }
}

#[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)]
pub struct Position {
    pub x: i32,
    pub y: i32,
    pub rotation: i32, // any value, sets rotation in degrees (positive -> clockwise)
}

#[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)]
// each r g b a value is any i32, but will be internally divided by 1024
pub struct I32Color {
    pub r: i32,
    pub g: i32,
    pub b: i32,
    pub a: i32,
}

#[derive(Default, Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Env<T> {
    pub name: String,
    pub synchronized: bool,
    pub points: Vec<EnvPoint<T>>,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
// to allow all envelope types to coexist in a vector
pub enum Envelope {
    Position(Env<Position>),
    Color(Env<I32Color>),
    Sound(Env<i32>),
}

#[derive(PartialEq, Debug, Clone)]
pub struct TilesLoadInfo {
    pub width: i32,
    pub height: i32,
    pub compression: bool,
}

pub struct OutdatedTileVersion {
    pub bytes_per_tile: usize,
    pub convert_fnc: fn(&[u8]) -> Vec<u8>,
}

unsafe impl View for TileFlags {} // deriving directly didn't work
bitflags! {
    #[repr(C)]
    #[derive(Default, Serialize, Deserialize)]
    #[serde(into = "map_dir::DirTileFlags", try_from = "map_dir::DirTileFlags")]
    pub struct TileFlags: u8 {
        const FLIP_V = 0b0001;
        const FLIP_H = 0b0010;
        const OPAQUE = 0b0100;
        const ROTATE = 0b1000;
    }
}

#[derive(Debug, Copy, Clone, View, PartialEq, Default, Serialize, Deserialize)]
#[repr(C)]
pub struct Tile { // for TilesLayer
    pub id: u8,
    pub flags: TileFlags,
    #[serde(skip)]
    pub(crate) skip: u8, // used for 0.7 tile compression
    #[serde(skip)]
    pub(crate) unused: u8,
}

#[derive(Debug, Copy, Clone, View, PartialEq, Default, Serialize, Deserialize)]
#[repr(C)]
pub struct GameTile { // for GameLayer and FrontLayer
    pub id: u8,
    pub flags: TileFlags,
    #[serde(skip)]
    pub(crate) skip: u8, // used for 0.7 tile compression
    #[serde(skip)]
    pub(crate) unused: u8,
}

#[derive(Debug, Copy, Clone, View, PartialEq, Default, Serialize, Deserialize)]
#[repr(C)]
pub struct Tele {
    pub number: u8,
    pub id: u8,
}

#[derive(Debug, Copy, Clone, View, PartialEq, Default, Serialize, Deserialize)]
#[repr(C)]
pub struct I16 { // little endian 1-byte-aligned i16
    pub(crate) bytes: [u8; 2],
}

#[derive(Debug, Copy, Clone, View, PartialEq, Default, Serialize, Deserialize)]
#[repr(C)]
pub struct Speedup {
    pub force: u8,
    pub max_speed: u8,
    pub id: u8,
    #[serde(skip)]
    pub(crate) unused_padding: u8, // padding, unused
    pub angle: I16,
}

#[derive(Debug, Copy, Clone, View, PartialEq, Default, Serialize, Deserialize)]
#[repr(C)]
pub struct Switch {
    pub number: u8,
    pub id: u8,
    pub flags: TileFlags,
    pub delay: u8,
}

#[derive(Debug, Copy, Clone, View, PartialEq, Default, Serialize, Deserialize)]
#[repr(C)]
pub struct Tune {
    pub number: u8,
    pub id: u8
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct GameLayer {
    #[serde(flatten, with = "map_dir::tiles_serialization")]
    pub tiles: CompressedData<Array2<GameTile>, TilesLoadInfo>,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct FrontLayer {
    #[serde(flatten, with = "map_dir::tiles_serialization")]
    pub tiles: CompressedData<Array2<GameTile>, TilesLoadInfo>,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct TeleLayer {
    #[serde(flatten, with = "map_dir::tiles_serialization")]
    pub tiles: CompressedData<Array2<Tele>, TilesLoadInfo>
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct SpeedupLayer {
    #[serde(flatten, with = "map_dir::tiles_serialization")]
    pub tiles: CompressedData<Array2<Speedup>, TilesLoadInfo>,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct SwitchLayer {
    #[serde(flatten, with = "map_dir::tiles_serialization")]
    pub tiles: CompressedData<Array2<Switch>, TilesLoadInfo>
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct TuneLayer {
    #[serde(flatten, with = "map_dir::tiles_serialization")]
    pub tiles: CompressedData<Array2<Tune>, TilesLoadInfo>,
}

#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct TilesLayer {
    pub name: String,
    pub detail: bool,
    pub color: Color,
    #[serde(with = "map_dir::envelope_index_serialization")]
    pub color_env: Option<u16>,
    pub color_env_offset: i32,
    #[serde(with = "map_dir::image_index_serialization")]
    pub image: Option<u16>,
    #[serde(flatten, with = "map_dir::tiles_serialization")]
    pub tiles: CompressedData<Array2<Tile>, TilesLoadInfo>,
    pub auto_mapper: AutoMapper,
}

#[derive(Debug, Default, Copy, Clone, PartialEq, Serialize, Deserialize)]
pub struct Point { // 22.10 fixed point
    pub x: i32,
    pub y: i32,
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Quad {
    pub corners: [Point; 4], // top-left, top-right, bottom-left, bottom-right
    pub position: Point,
    pub colors: [Color; 4],
    pub texture_coords: [Point; 4], // represents the stretching done by shift+dragging of corners in the editor
    #[serde(with = "map_dir::envelope_index_serialization")]
    pub position_env: Option<u16>,
    pub position_env_offset: i32,
    #[serde(with = "map_dir::envelope_index_serialization")]
    pub color_env: Option<u16>,
    pub color_env_offset: i32,
}

#[derive(Default, Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct QuadsLayer {
    pub name: String,
    pub detail: bool,
    pub quads: Vec<Quad>,
    #[serde(with = "map_dir::image_index_serialization")]
    pub image: Option<u16>, // index to its image
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
// shape of the sound in which it is audible
pub enum SoundShape {
    Rectangle { width: i32, height: i32 },
    Circle { radius: i32 },
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct SoundSource {
    pub position: Point,
    pub looping: bool,
    pub panning: bool,
    pub delay: i32,
    pub falloff: u8,
    #[serde(with = "map_dir::envelope_index_serialization")]
    pub position_env: Option<u16>,
    pub position_env_offset: i32,
    #[serde(with = "map_dir::envelope_index_serialization")]
    pub sound_env: Option<u16>,
    pub sound_env_offset: i32,
    pub shape: SoundShape,
}

#[derive(Default, Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct SoundsLayer {
    pub name: String,
    pub detail: bool,
    pub sources: Vec<SoundSource>,
    #[serde(with = "map_dir::sound_index_serialization")]
    pub sound: Option<u16>, // index of used sound
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum Layer {
    Game(GameLayer),
    Tiles(TilesLayer),
    Quads(QuadsLayer),
    Front(FrontLayer),
    Tele(TeleLayer),
    Speedup(SpeedupLayer),
    Switch(SwitchLayer),
    Tune(TuneLayer),
    Sounds(SoundsLayer),
    #[serde(skip)]
    Invalid(InvalidLayerKind),
}

pub trait TileMapLayer: AnyLayer {
    type TileType: AnyTile;

    fn tiles(&self) -> &CompressedData<Array2<Self::TileType>, TilesLoadInfo>;

    fn tiles_mut(&mut self) -> &mut CompressedData<Array2<Self::TileType>, TilesLoadInfo>;
}

pub trait AnyTile: Default + PartialEq + Copy + Clone + map_checks::TileChecking + View {
    fn id(&self) -> u8;

    fn flags(&self) -> Option<TileFlags>;
}

// functionality for all layer types
pub trait AnyLayer: Sized {
    fn kind() -> LayerKind;

    fn get(layer: &Layer) -> Option<&Self>;

    fn get_mut(layer: &mut Layer) -> Option<&mut Self>;
}