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
//! M.C. Escher-style tessellation pattern generator.
//!
//! Generates parallelogram lattices, hexagonal tilings, simplified lizard
//! patterns, and wallpaper-group symmetry transforms.
use std::f64::consts::PI;
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/// Which Escher-inspired tessellation style to produce.
#[derive(Debug, Clone, PartialEq)]
pub enum TessellationType {
/// Plain polygon lattice in the spirit of Escher's regular divisions.
RegularDivision,
/// Simplified interlocking lizard shapes.
LizardPattern,
/// Fish-shaped tiles.
FishPattern,
/// Bird-shaped tiles.
BirdPattern,
/// Tiling driven by a wallpaper symmetry group, identified by number.
SymmetryGroup(u8),
}
/// A single tile shape: a polygon with a fill colour.
#[derive(Debug, Clone)]
pub struct TileShape {
/// Polygon vertices in pixels, in order.
pub vertices: Vec<(f64, f64)>,
/// Fill colour (RGB).
pub color: [u8; 3],
}
// ---------------------------------------------------------------------------
// EscherGenerator
// ---------------------------------------------------------------------------
/// Generates Escher-style tessellations as lists of polygons.
pub struct EscherGenerator;
impl EscherGenerator {
/// Create a generator.
pub fn new() -> Self {
Self
}
// -----------------------------------------------------------------------
// Parallelogram tiling
// -----------------------------------------------------------------------
/// Generate a parallelogram lattice defined by basis vectors `a` and `b`.
///
/// `cols` × `rows` tiles are generated, with colours cycling through
/// `colors`.
pub fn generate_parallelogram_tiling(
&self,
a: (f64, f64),
b: (f64, f64),
cols: u32,
rows: u32,
colors: &[[u8; 3]],
) -> Vec<TileShape> {
if colors.is_empty() {
return vec![];
}
let mut tiles = Vec::new();
for row in 0..rows {
for col in 0..cols {
let ox = col as f64 * a.0 + row as f64 * b.0;
let oy = col as f64 * a.1 + row as f64 * b.1;
let vertices = vec![
(ox, oy),
(ox + a.0, oy + a.1),
(ox + a.0 + b.0, oy + a.1 + b.1),
(ox + b.0, oy + b.1),
];
let color_idx = (row * cols + col) as usize % colors.len();
tiles.push(TileShape {
vertices,
color: colors[color_idx],
});
}
}
tiles
}
// -----------------------------------------------------------------------
// Hexagonal tiling
// -----------------------------------------------------------------------
/// Generate a regular hexagon tessellation.
///
/// Each hexagon is centred at a lattice point derived from `center`,
/// `radius`, and hex grid offsets for `cols` × `rows` cells.
pub fn generate_hexagonal_tiling(
&self,
center: (f64, f64),
radius: f64,
cols: u32,
rows: u32,
colors: &[[u8; 3]],
) -> Vec<TileShape> {
if colors.is_empty() {
return vec![];
}
let w = radius * 3.0_f64.sqrt(); // horizontal spacing
let h = radius * 1.5; // vertical spacing
let mut tiles = Vec::new();
for row in 0..rows {
for col in 0..cols {
let cx = center.0 + col as f64 * w + if row % 2 == 1 { w / 2.0 } else { 0.0 };
let cy = center.1 + row as f64 * h;
let vertices: Vec<(f64, f64)> = (0..6)
.map(|i| {
let angle = PI / 3.0 * i as f64 - PI / 6.0;
(cx + radius * angle.cos(), cy + radius * angle.sin())
})
.collect();
let color_idx = (row * cols + col) as usize % colors.len();
tiles.push(TileShape {
vertices,
color: colors[color_idx],
});
}
}
tiles
}
// -----------------------------------------------------------------------
// Lizard pattern
// -----------------------------------------------------------------------
/// Generate a simplified Escher-inspired lizard pattern.
///
/// Produces interlocking L-shaped tiles on a grid, with each tile
/// rotated 0°, 90°, 180°, or 270° based on a seeded pattern.
pub fn generate_lizard_pattern(
&self,
width: u32,
height: u32,
scale: f64,
seed: u64,
) -> Vec<Vec<[u8; 3]>> {
let w = width as usize;
let h = height as usize;
let mut canvas = vec![vec![[30u8, 30u8, 30u8]; w]; h];
let tile_size = (scale * 20.0).max(4.0) as usize;
let colors: [[u8; 3]; 4] = [[200, 80, 50], [50, 160, 80], [60, 80, 200], [200, 160, 50]];
let mut rng = seed;
let cols = (w / tile_size).max(1);
let rows = (h / tile_size).max(1);
for row in 0..rows {
for col in 0..cols {
rng = rng
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
let rotation = (rng >> 33) as usize % 4; // 0, 1, 2, 3 → 0°, 90°, 180°, 270°
let color = colors[((row + col + rotation) % colors.len())];
// Draw an L-shape occupying roughly 75% of the tile
let base_x = col * tile_size;
let base_y = row * tile_size;
let arm = (tile_size * 3 / 4).max(2);
let (lx, ly, lw, lh) = match rotation % 4 {
0 => (base_x, base_y, arm, tile_size),
1 => (base_x, base_y + tile_size - arm, tile_size, arm),
2 => (base_x + tile_size - arm, base_y, arm, tile_size),
_ => (base_x, base_y, tile_size, arm),
};
for py in ly..((ly + lh).min(h)) {
for px in lx..((lx + lw).min(w)) {
canvas[py][px] = color;
}
}
}
}
canvas
}
// -----------------------------------------------------------------------
// Tile rasteriser
// -----------------------------------------------------------------------
/// Rasterise a set of [`TileShape`] polygons onto a pixel canvas.
pub fn render_tiles(
&self,
tiles: &[TileShape],
width: u32,
height: u32,
bg: [u8; 3],
) -> Vec<Vec<[u8; 3]>> {
let w = width as usize;
let h = height as usize;
let mut canvas = vec![vec![bg; w]; h];
for tile in tiles {
fill_polygon(&tile.vertices, tile.color, &mut canvas, w, h);
}
canvas
}
// -----------------------------------------------------------------------
// Symmetry transform
// -----------------------------------------------------------------------
/// Apply wallpaper group symmetry operations to `point`.
///
/// Supported groups: 1 (identity), 2 (180° rotation), 4 (4-fold rotation),
/// 6 (6-fold rotation).
pub fn symmetry_transform(&self, point: (f64, f64), group: u8) -> Vec<(f64, f64)> {
let (x, y) = point;
match group {
1 => vec![(x, y)],
2 => vec![(x, y), (-x, -y)],
4 => vec![(x, y), (-y, x), (-x, -y), (y, -x)],
6 => {
// 60° rotations
let angles: Vec<f64> = (0..6).map(|k| k as f64 * PI / 3.0).collect();
angles
.iter()
.map(|&a| {
let cos_a = a.cos();
let sin_a = a.sin();
(x * cos_a - y * sin_a, x * sin_a + y * cos_a)
})
.collect()
}
_ => vec![(x, y)],
}
}
}
impl Default for EscherGenerator {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// Polygon rasterisation (scan-line fill)
// ---------------------------------------------------------------------------
fn fill_polygon(
vertices: &[(f64, f64)],
color: [u8; 3],
canvas: &mut Vec<Vec<[u8; 3]>>,
width: usize,
height: usize,
) {
if vertices.len() < 3 || width == 0 || height == 0 {
return;
}
let min_y = vertices
.iter()
.map(|v| v.1)
.fold(f64::INFINITY, f64::min)
.max(0.0) as usize;
let max_y = vertices
.iter()
.map(|v| v.1)
.fold(f64::NEG_INFINITY, f64::max)
.min((height - 1) as f64) as usize;
for y in min_y..=max_y {
let yf = y as f64 + 0.5;
let mut intersections: Vec<f64> = Vec::new();
let n = vertices.len();
for i in 0..n {
let (x0, y0) = vertices[i];
let (x1, y1) = vertices[(i + 1) % n];
if (y0 <= yf && y1 > yf) || (y1 <= yf && y0 > yf) {
let t = (yf - y0) / (y1 - y0);
intersections.push(x0 + t * (x1 - x0));
}
}
intersections.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
for pair in intersections.chunks(2) {
if pair.len() < 2 {
break;
}
let x_start = pair[0].max(0.0).round() as usize;
let x_end = pair[1].min((width - 1) as f64).round() as usize;
for x in x_start..=x_end {
canvas[y][x] = color;
}
}
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
fn gen() -> EscherGenerator {
EscherGenerator::new()
}
// --- parallelogram ---
#[test]
fn parallelogram_tile_count() {
let g = gen();
let colors = [[255u8, 0, 0], [0, 255, 0]];
let tiles = g.generate_parallelogram_tiling((50.0, 0.0), (0.0, 50.0), 4, 3, &colors);
assert_eq!(tiles.len(), 12);
}
#[test]
fn parallelogram_each_tile_has_4_vertices() {
let g = gen();
let colors = [[100u8, 100, 100]];
let tiles = g.generate_parallelogram_tiling((30.0, 0.0), (0.0, 30.0), 2, 2, &colors);
assert!(tiles.iter().all(|t| t.vertices.len() == 4));
}
#[test]
fn parallelogram_empty_colors_returns_empty() {
let g = gen();
let tiles = g.generate_parallelogram_tiling((10.0, 0.0), (0.0, 10.0), 5, 5, &[]);
assert!(tiles.is_empty());
}
// --- hexagonal ---
#[test]
fn hexagonal_tile_count() {
let g = gen();
let colors = [[0u8, 0, 255]];
let tiles = g.generate_hexagonal_tiling((0.0, 0.0), 30.0, 3, 4, &colors);
assert_eq!(tiles.len(), 12);
}
#[test]
fn hexagonal_each_tile_has_6_vertices() {
let g = gen();
let colors = [[200u8, 200, 200], [100, 100, 100]];
let tiles = g.generate_hexagonal_tiling((0.0, 0.0), 20.0, 2, 2, &colors);
assert!(tiles.iter().all(|t| t.vertices.len() == 6));
}
#[test]
fn hexagonal_empty_colors_returns_empty() {
let g = gen();
let tiles = g.generate_hexagonal_tiling((0.0, 0.0), 20.0, 3, 3, &[]);
assert!(tiles.is_empty());
}
// --- lizard pattern ---
#[test]
fn lizard_pattern_correct_dimensions() {
let g = gen();
let canvas = g.generate_lizard_pattern(200, 150, 1.0, 42);
assert_eq!(canvas.len(), 150);
assert!(canvas.iter().all(|row| row.len() == 200));
}
#[test]
fn lizard_pattern_has_coloured_pixels() {
let g = gen();
let canvas = g.generate_lizard_pattern(100, 100, 1.0, 99);
let bg: [u8; 3] = [30, 30, 30];
let non_bg = canvas.iter().flatten().filter(|&&p| p != bg).count();
assert!(non_bg > 0, "Expected drawn pixels");
}
#[test]
fn lizard_pattern_zero_size() {
let g = gen();
let canvas = g.generate_lizard_pattern(0, 0, 1.0, 0);
assert!(canvas.is_empty());
}
// --- render_tiles ---
#[test]
fn render_tiles_fills_background() {
let g = gen();
let bg = [50u8, 50, 50];
let canvas = g.render_tiles(&[], 100, 80, bg);
assert!(canvas.iter().flatten().all(|&p| p == bg));
}
#[test]
fn render_tiles_draws_polygon() {
let g = gen();
let tile = TileShape {
vertices: vec![(10.0, 10.0), (90.0, 10.0), (90.0, 70.0), (10.0, 70.0)],
color: [255, 0, 0],
};
let canvas = g.render_tiles(&[tile], 100, 80, [0, 0, 0]);
let red_pixels = canvas
.iter()
.flatten()
.filter(|&&p| p == [255u8, 0, 0])
.count();
assert!(red_pixels > 0);
}
// --- symmetry_transform ---
#[test]
fn symmetry_group_1_identity() {
let g = gen();
let pts = g.symmetry_transform((3.0, 4.0), 1);
assert_eq!(pts, vec![(3.0, 4.0)]);
}
#[test]
fn symmetry_group_2_two_points() {
let g = gen();
let pts = g.symmetry_transform((1.0, 2.0), 2);
assert_eq!(pts.len(), 2);
assert_eq!(pts[0], (1.0, 2.0));
assert!((pts[1].0 - (-1.0)).abs() < 1e-9);
assert!((pts[1].1 - (-2.0)).abs() < 1e-9);
}
#[test]
fn symmetry_group_4_four_points() {
let g = gen();
let pts = g.symmetry_transform((1.0, 0.0), 4);
assert_eq!(pts.len(), 4);
// First is identity
assert_eq!(pts[0], (1.0, 0.0));
// Second is 90° rotation: (-y, x) = (0, 1)
assert!((pts[1].0 - 0.0).abs() < 1e-9);
assert!((pts[1].1 - 1.0).abs() < 1e-9);
}
#[test]
fn symmetry_group_6_six_points() {
let g = gen();
let pts = g.symmetry_transform((1.0, 0.0), 6);
assert_eq!(pts.len(), 6);
// All points should lie on a unit circle
for (x, y) in &pts {
let dist = (x * x + y * y).sqrt();
assert!((dist - 1.0).abs() < 1e-9, "dist={dist}");
}
}
#[test]
fn symmetry_unknown_group_returns_identity() {
let g = gen();
let pts = g.symmetry_transform((5.0, 7.0), 99);
assert_eq!(pts, vec![(5.0, 7.0)]);
}
}