ry-science 0.7.34

Math, stats, and geometry for Ry-Dit — Bezier curves, statistics, optical illusions
Documentation
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
//! Módulo de Geometría - Ilusiones Ópticas
//!
//! Implementa ilusiones ópticas clásicas usando matemáticas simples:
//! - Triángulo de Penrose (tribar)
//! - Cubo imposible (Necker cube)
//! - Espiral óptica

use serde_json::{json, Value};

/// Genera las coordenadas para el Triángulo de Penrose
///
/// # Parámetros
/// - `center_x`: Centro X en pantalla
/// - `center_y`: Centro Y en pantalla  
/// - `size`: Tamaño del triángulo
///
/// # Retorna
/// Array de líneas: [[x1, y1, x2, y2], ...]
pub fn penrose(center_x: f64, center_y: f64, size: f64) -> Value {
    let s = size;

    // Coordenadas de los 3 vértices principales
    let v1_x = center_x;
    let v1_y = center_y - s * 0.577; // cos(30°)

    let v2_x = center_x - s * 0.5;
    let v2_y = center_y + s * 0.289;

    let v3_x = center_x + s * 0.5;
    let v3_y = center_y + s * 0.289;

    // Grosor de las barras
    let thick = s * 0.15;

    // Barras del triángulo imposible
    // Cada barra tiene 2 líneas paralelas para dar grosor
    let lines = vec![
        // Barra 1: v1 -> v2 (con "quiebre" imposible)
        json!([
            v1_x - thick * 0.3,
            v1_y - thick * 0.5,
            v2_x + thick * 0.5,
            v2_y - thick * 0.3,
        ]),
        json!([
            v1_x + thick * 0.3,
            v1_y - thick * 0.5,
            v2_x - thick * 0.5,
            v2_y + thick * 0.3,
        ]),
        // Barra 2: v2 -> v3
        json!([
            v2_x + thick * 0.5,
            v2_y - thick * 0.3,
            v3_x - thick * 0.5,
            v3_y - thick * 0.3,
        ]),
        json!([
            v2_x + thick * 0.5,
            v2_y + thick * 0.3,
            v3_x - thick * 0.5,
            v3_y + thick * 0.3,
        ]),
        // Barra 3: v3 -> v1 (con "quiebre" imposible)
        json!([
            v3_x + thick * 0.3,
            v3_y - thick * 0.5,
            v1_x + thick * 0.3,
            v1_y + thick * 0.5,
        ]),
        json!([
            v3_x - thick * 0.3,
            v3_y + thick * 0.5,
            v1_x - thick * 0.3,
            v1_y + thick * 0.5,
        ]),
        // Líneas de conexión "imposibles" en las esquinas
        // Esquina v1
        json!([
            v1_x - thick * 0.3,
            v1_y - thick * 0.5,
            v1_x - thick * 0.3,
            v1_y + thick * 0.5,
        ]),
        json!([
            v1_x + thick * 0.3,
            v1_y - thick * 0.5,
            v1_x + thick * 0.3,
            v1_y + thick * 0.5,
        ]),
        // Esquina v2
        json!([
            v2_x - thick * 0.5,
            v2_y - thick * 0.3,
            v2_x - thick * 0.5,
            v2_y + thick * 0.3,
        ]),
        json!([
            v2_x + thick * 0.5,
            v2_y - thick * 0.3,
            v2_x + thick * 0.5,
            v2_y + thick * 0.3,
        ]),
        // Esquina v3
        json!([
            v3_x - thick * 0.5,
            v3_y - thick * 0.3,
            v3_x - thick * 0.5,
            v3_y + thick * 0.3,
        ]),
        json!([
            v3_x + thick * 0.5,
            v3_y - thick * 0.3,
            v3_x + thick * 0.5,
            v3_y + thick * 0.3,
        ]),
    ];

    json!(lines)
}

/// Genera las coordenadas para el Cubo Imposible
///
/// # Parámetros
/// - `center_x`: Centro X en pantalla
/// - `center_y`: Centro Y en pantalla
/// - `size`: Tamaño del cubo
///
/// # Retorna
/// Array de líneas: [[x1, y1, x2, y2], ...]
pub fn impossible_cube(center_x: f64, center_y: f64, size: f64) -> Value {
    let s = size * 0.5;

    // Cubo frontal
    let f_bl_x = center_x - s; // front bottom-left
    let f_bl_y = center_y + s;
    let f_br_x = center_x + s; // front bottom-right
    let f_br_y = center_y + s;
    let f_tl_x = center_x - s; // front top-left
    let f_tl_y = center_y - s;
    let f_tr_x = center_x + s; // front top-right
    let f_tr_y = center_y - s;

    // Cubo trasero (desplazado)
    let offset = s * 0.6;
    let b_bl_x = center_x - s + offset; // back bottom-left
    let b_bl_y = center_y + s - offset;
    let b_br_x = center_x + s + offset; // back bottom-right
    let b_br_y = center_y + s - offset;
    let b_tl_x = center_x - s + offset; // back top-left
    let b_tl_y = center_y - s - offset;
    let b_tr_x = center_x + s + offset; // back top-right
    let b_tr_y = center_y - s - offset;

    let lines = vec![
        // Cara frontal
        json!([f_bl_x, f_bl_y, f_br_x, f_br_y]), // bottom
        json!([f_br_x, f_br_y, f_tr_x, f_tr_y]), // right
        json!([f_tr_x, f_tr_y, f_tl_x, f_tl_y]), // top
        json!([f_tl_x, f_tl_y, f_bl_x, f_bl_y]), // left
        // Cara trasera
        json!([b_bl_x, b_bl_y, b_br_x, b_br_y]), // bottom
        json!([b_br_x, b_br_y, b_tr_x, b_tr_y]), // right
        json!([b_tr_x, b_tr_y, b_tl_x, b_tl_y]), // top
        json!([b_tl_x, b_tl_y, b_bl_x, b_bl_y]), // left
        // Conexiones frontal-trasera (algunas "imposibles")
        json!([f_bl_x, f_bl_y, b_bl_x, b_bl_y]),
        json!([f_br_x, f_br_y, b_br_x, b_br_y]),
        json!([f_tl_x, f_tl_y, b_tl_x, b_tl_y]),
        json!([f_tr_x, f_tr_y, b_tr_x, b_tr_y]),
        // Líneas adicionales para efecto imposible
        json!([f_bl_x + s * 0.3, f_bl_y, b_bl_x - s * 0.3, b_bl_y]),
        json!([f_tr_x - s * 0.3, f_tr_y, b_tr_x + s * 0.3, b_tr_y]),
    ];

    json!(lines)
}

/// Genera las coordenadas para la Espiral Óptica
///
/// # Parámetros
/// - `center_x`: Centro X en pantalla
/// - `center_y`: Centro Y en pantalla
/// - `turns`: Número de vueltas
/// - `radius`: Radio máximo
/// - `points`: Puntos por vuelta
///
/// # Retorna
/// Array de puntos: [[x1, y1], [x2, y2], ...]
pub fn spiral(center_x: f64, center_y: f64, turns: i32, radius: f64, points: i32) -> Value {
    let mut points_arr = Vec::new();
    let total_points = turns * points;

    for i in 0..total_points {
        let t = (i as f64) / (total_points as f64); // 0.0 a 1.0
        let angle = t * turns as f64 * 2.0 * std::f64::consts::PI;
        let r = t * radius;

        let x = center_x + r * angle.cos();
        let y = center_y + r * angle.sin();

        points_arr.push(json!([x, y]));
    }

    json!(points_arr)
}

/// Genera la ilusión de Müller-Lyer
///
/// # Parámetros
/// - `center_x`: Centro X en pantalla
/// - `center_y`: Centro Y en pantalla
/// - `length`: Longitud de la línea principal
///
/// # Retorna
/// Array de líneas: [[x1, y1, x2, y2], ...]
pub fn muller_lyer(center_x: f64, center_y: f64, length: f64) -> Value {
    let half = length / 2.0;
    let arrow_size = length * 0.15;

    let mut lines = Vec::new();

    // Línea 1: Flechas hacia adentro (>)
    let y1 = center_y - length * 0.3;
    lines.push(json!([center_x - half, y1, center_x + half, y1])); // línea principal

    // Flecha izquierda adentro
    lines.push(json!([
        center_x - half,
        y1,
        center_x - half + arrow_size,
        y1 - arrow_size * 0.6
    ]));
    lines.push(json!([
        center_x - half,
        y1,
        center_x - half + arrow_size,
        y1 + arrow_size * 0.6
    ]));

    // Flecha derecha adentro
    lines.push(json!([
        center_x + half,
        y1,
        center_x + half - arrow_size,
        y1 - arrow_size * 0.6
    ]));
    lines.push(json!([
        center_x + half,
        y1,
        center_x + half - arrow_size,
        y1 + arrow_size * 0.6
    ]));

    // Línea 2: Flechas hacia afuera (<)
    let y2 = center_y + length * 0.3;
    lines.push(json!([center_x - half, y2, center_x + half, y2])); // línea principal

    // Flecha izquierda afuera
    lines.push(json!([
        center_x - half,
        y2,
        center_x - half - arrow_size,
        y2 - arrow_size * 0.6
    ]));
    lines.push(json!([
        center_x - half,
        y2,
        center_x - half - arrow_size,
        y2 + arrow_size * 0.6
    ]));

    // Flecha derecha afuera
    lines.push(json!([
        center_x + half,
        y2,
        center_x + half + arrow_size,
        y2 - arrow_size * 0.6
    ]));
    lines.push(json!([
        center_x + half,
        y2,
        center_x + half + arrow_size,
        y2 + arrow_size * 0.6
    ]));

    json!(lines)
}

/// Genera la ilusión de Ponzo (perspectiva)
///
/// # Parámetros
/// - `center_x`: Centro X en pantalla
/// - `center_y`: Centro Y en pantalla
/// - `height`: Altura de la perspectiva
/// - `width_top`: Ancho superior
/// - `width_bottom`: Ancho inferior
///
/// # Retorna
/// Array de líneas: [[x1, y1, x2, y2], ...]
pub fn ponzo(
    center_x: f64,
    center_y: f64,
    height: f64,
    width_top: f64,
    width_bottom: f64,
) -> Value {
    let mut lines = Vec::new();

    // Líneas de perspectiva (rieles)
    let top_y = center_y - height / 2.0;
    let bottom_y = center_y + height / 2.0;

    lines.push(json!([
        center_x - width_top / 2.0,
        top_y,
        center_x - width_bottom / 2.0,
        bottom_y
    ]));
    lines.push(json!([
        center_x + width_top / 2.0,
        top_y,
        center_x + width_bottom / 2.0,
        bottom_y
    ]));

    // Líneas horizontales (la de arriba parece más larga)
    let top_line_width = width_top * 0.8;
    let bottom_line_width = width_bottom * 0.8;

    // Línea superior
    lines.push(json!([
        center_x - top_line_width / 2.0,
        top_y + height * 0.2,
        center_x + top_line_width / 2.0,
        top_y + height * 0.2
    ]));

    // Línea inferior (misma longitud real, parece más corta)
    lines.push(json!([
        center_x - bottom_line_width / 2.0,
        bottom_y - height * 0.2,
        center_x + bottom_line_width / 2.0,
        bottom_y - height * 0.2
    ]));

    // Líneas adicionales para reforzar la perspectiva
    let mid_y = (top_y + bottom_y) / 2.0;
    let mid_line_width = (width_top + width_bottom) * 0.4;
    lines.push(json!([
        center_x - mid_line_width / 2.0,
        mid_y,
        center_x + mid_line_width / 2.0,
        mid_y
    ]));
    lines.push(json!([
        center_x - mid_line_width / 2.0 * 0.5,
        mid_y + height * 0.15,
        center_x + mid_line_width / 2.0 * 0.5,
        mid_y + height * 0.15
    ]));

    json!(lines)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_penrose_returns_lines() {
        let result = penrose(400.0, 300.0, 100.0);
        let lines = result.as_array().unwrap();

        assert!(!lines.is_empty());
        assert!(lines.len() >= 10); // Al menos 10 líneas

        // Cada línea es [x1, y1, x2, y2]
        let first_line = lines[0].as_array().unwrap();
        assert_eq!(first_line.len(), 4);
    }

    #[test]
    fn test_impossible_cube_returns_lines() {
        let result = impossible_cube(400.0, 300.0, 100.0);
        let lines = result.as_array().unwrap();

        assert!(!lines.is_empty());
        assert!(lines.len() >= 12); // Cubo tiene 12 aristas + extra

        let first_line = lines[0].as_array().unwrap();
        assert_eq!(first_line.len(), 4);
    }

    #[test]
    fn test_spiral_returns_points() {
        let result = spiral(400.0, 300.0, 3, 100.0, 20);
        let points = result.as_array().unwrap();

        assert_eq!(points.len(), 60); // 3 turns * 20 points

        let first_point = points[0].as_array().unwrap();
        assert_eq!(first_point.len(), 2); // [x, y]
    }

    #[test]
    fn test_muller_lyer_returns_lines() {
        let result = muller_lyer(400.0, 300.0, 200.0);
        let lines = result.as_array().unwrap();

        assert_eq!(lines.len(), 10); // 2 líneas principales + 8 flechas

        let first_line = lines[0].as_array().unwrap();
        assert_eq!(first_line.len(), 4);
    }

    #[test]
    fn test_ponzo_returns_lines() {
        let result = ponzo(400.0, 300.0, 300.0, 100.0, 300.0);
        let lines = result.as_array().unwrap();

        assert_eq!(lines.len(), 6); // 2 rieles + 4 horizontales

        let first_line = lines[0].as_array().unwrap();
        assert_eq!(first_line.len(), 4);
    }

    #[test]
    fn test_spiral_center_point() {
        // El primer punto debe estar cerca del centro
        let result = spiral(400.0, 300.0, 1, 100.0, 10);
        let points = result.as_array().unwrap();
        let first_point = points[0].as_array().unwrap();

        let x = first_point[0].as_f64().unwrap();
        let y = first_point[1].as_f64().unwrap();

        assert!((x - 400.0).abs() < 1.0); // Cerca del centro
        assert!((y - 300.0).abs() < 1.0);
    }

    #[test]
    fn test_spiral_outer_point() {
        // El último punto debe estar cerca del radio máximo
        let result = spiral(400.0, 300.0, 1, 100.0, 10);
        let points = result.as_array().unwrap();
        let last_point = points[points.len() - 1].as_array().unwrap();

        let x = last_point[0].as_f64().unwrap();
        let y = last_point[1].as_f64().unwrap();

        // Distancia desde el centro debería ser ~100 (radio máximo)
        // Nota: como es espiral de 1 vuelta, el último punto está cerca del radio máximo
        let dist = ((x - 400.0).powi(2) + (y - 300.0).powi(2)).sqrt();
        assert!(dist > 80.0 && dist < 120.0); // Rango razonable para espiral de 1 vuelta
    }
}