ry-gfx 0.10.8

Ry Graphics Layer - SDL2 Backend + GPU Instancing + FSR 1.0 for Termux and low-end devices
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
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
//! # RyDit Render Queue - Command Queue + Double Buffering + Platform Sync
//!
//! **TRES CAPAS CRÍTICAS PARA RENDIMIENTO Y COMPATIBILIDAD**
//!
//! 1. **Command Queue (8192+ draw calls)** - Acumular comandos de dibujado
//! 2. **Double Buffering** - Separar lógica de renderizado
//! 3. **Platform Sync (XFlush/XSync)** - Sincronización con X11
//!
//! ## Arquitectura
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────┐
//! │  RYDIT RENDER QUEUE                                     │
//! ├─────────────────────────────────────────────────────────┤
//! │                                                         │
//! │  ┌─────────────────────────────────────────────────┐   │
//! │  │  1. COMMAND QUEUE (8192+ draw calls)            │   │
//! │  │  - Acumular: circle, rect, line, text, etc.     │   │
//! │  │  - Ejecutar: batch processing                   │   │
//! │  │  - Buffer circular: head, tail, capacity        │   │
//! │  └─────────────────────────────────────────────────┘   │
//! │                         │                               │
//! │  ┌──────────────────────▼──────────────────────────┐   │
//! │  │  2. DOUBLE BUFFERING                            │   │
//! │  │  - Front buffer: lógica (executor)              │   │
//! │  │  - Back buffer: render (draw calls)             │   │
//! │  │  - Swap: intercambiar buffers por frame         │   │
//! │  └─────────────────────────────────────────────────┘   │
//! │                         │                               │
//! │  ┌──────────────────────▼──────────────────────────┐   │
//! │  │  3. PLATFORM SYNC (X11)                         │   │
//! │  │  - XFlush: forzar flush de comandos             │   │
//! │  │  - XSync: sincronizar con servidor X11          │   │
//! │  │  - glFlush: OpenGL buffer swap                  │   │
//! │  └─────────────────────────────────────────────────┘   │
//! │                                                         │
//! └─────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Uso
//!
//! ```rust,no_run
//! use ry_gfx::render_queue::{RenderQueue, DrawCommand};
//!
//! let mut queue = RenderQueue::with_capacity(8192);
//!
//! // Acumular comandos (front buffer - lógica)
//! queue.push(DrawCommand::Circle { x: 400, y: 300, radius: 50, color: "rojo" });
//! queue.push(DrawCommand::Rect { x: 100, y: 100, w: 100, h: 100, color: "verde" });
//!
//! // Ejecutar todos los comandos (back buffer - render)
//! queue.execute(&mut gfx);
//!
//! // Platform sync (X11)
//! queue.platform_sync();
//! ```

use crate::Assets;
use crate::{ColorRydit, RyditGfx};
use std::collections::VecDeque;

// ✅ v0.10.8: PlatformSync ahora viene de v-shield
pub use v_shield::platform_sync::{PlatformSync, PlatformSyncMode};

// ============================================================================
// DRAW COMMANDS - Tipos de comandos de dibujado
// ============================================================================

/// Comandos de dibujado para la queue
#[derive(Debug, Clone)]
pub enum DrawCommand {
    /// draw.circle(x, y, radius, color)
    Circle {
        x: i32,
        y: i32,
        radius: i32,
        color: ColorRydit,
    },
    /// draw.rect(x, y, w, h, color)
    Rect {
        x: i32,
        y: i32,
        w: i32,
        h: i32,
        color: ColorRydit,
    },
    /// draw.line(x1, y1, x2, y2, color)
    Line {
        x1: i32,
        y1: i32,
        x2: i32,
        y2: i32,
        color: ColorRydit,
    },
    /// draw.text(text, x, y, size, color)
    Text {
        text: String,
        x: i32,
        y: i32,
        size: i32,
        color: ColorRydit,
    },
    /// draw.triangle(v1, v2, v3, color)
    Triangle {
        v1: (i32, i32),
        v2: (i32, i32),
        v3: (i32, i32),
        color: ColorRydit,
    },
    /// draw.texture(id, x, y, scale, rotation, color)
    Texture {
        id: String,
        x: f32,
        y: f32,
        scale: f32,
        rotation: f32,
        color: ColorRydit,
    },
    /// Limpiar pantalla
    Clear { color: ColorRydit },
}

// ============================================================================
// RENDER QUEUE - Command Queue (8192+ draw calls)
// ============================================================================

/// Command Queue para draw calls
///
/// **Capacidad**: 8192+ comandos por frame
/// **Estrategia**: Buffer circular con head/tail
pub struct RenderQueue {
    /// Cola de comandos (buffer circular)
    commands: VecDeque<DrawCommand>,
    /// Capacidad máxima
    capacity: usize,
    /// Comandos acumulados en este frame
    frame_count: usize,
    /// Total de comandos ejecutados
    total_executed: usize,
    /// Estadísticas: máximo de comandos en un frame
    max_frame_count: usize,
}

impl RenderQueue {
    /// Crear queue con capacidad por defecto (8192)
    pub fn new() -> Self {
        Self::with_capacity(8192)
    }

    /// Crear queue con capacidad custom
    pub fn with_capacity(capacity: usize) -> Self {
        println!(
            "[RENDER QUEUE] Command Queue creada: capacidad={} (8192+ draw calls)",
            capacity
        );
        Self {
            commands: VecDeque::with_capacity(capacity),
            capacity,
            frame_count: 0,
            total_executed: 0,
            max_frame_count: 0,
        }
    }

    /// Push de comando a la queue
    pub fn push(&mut self, command: DrawCommand) {
        // Verificar overflow
        if self.commands.len() >= self.capacity {
            // Buffer lleno: remover el comando más antiguo (política FIFO)
            self.commands.pop_front();
            #[cfg(debug_assertions)]
            eprintln!(
                "[RENDER QUEUE] WARNING: Buffer lleno ({}), removiendo comando antiguo",
                self.capacity
            );
        }

        self.commands.push_back(command);
        self.frame_count += 1;
    }

    /// Ejecutar todos los comandos acumulados
    pub fn execute(&mut self, gfx: &mut RyditGfx, assets: &Assets) {
        if self.commands.is_empty() {
            return;
        }

        // Actualizar estadísticas
        if self.frame_count > self.max_frame_count {
            self.max_frame_count = self.frame_count;
        }
        self.total_executed += self.frame_count;

        #[cfg(debug_assertions)]
        eprintln!(
            "[RENDER QUEUE] Ejecutando {} comandos (total: {}, max frame: {})",
            self.frame_count, self.total_executed, self.max_frame_count
        );

        // Ejecutar todos los comandos EN UN SOLO begin_draw
        {
            let mut d = gfx.begin_draw();

            for command in self.commands.drain(..) {
                match command {
                    DrawCommand::Circle {
                        x,
                        y,
                        radius,
                        color,
                    } => {
                        d.draw_circle(x, y, radius, color);
                    }
                    DrawCommand::Rect { x, y, w, h, color } => {
                        d.draw_rectangle(x, y, w, h, color);
                    }
                    DrawCommand::Line {
                        x1,
                        y1,
                        x2,
                        y2,
                        color,
                    } => {
                        d.draw_line(x1, y1, x2, y2, color);
                    }
                    DrawCommand::Text {
                        text,
                        x,
                        y,
                        size,
                        color,
                    } => {
                        d.draw_text(&text, x, y, size, color);
                    }
                    DrawCommand::Triangle { v1, v2, v3, color } => {
                        d.draw_triangle(v1, v2, v3, color);
                    }
                    DrawCommand::Texture {
                        id,
                        x,
                        y,
                        scale,
                        rotation,
                        color,
                    } => {
                        // Dibujar textura con escala y rotación
                        assets.draw_texture_ex_by_id(
                            &mut d.draw,
                            &id,
                            x,
                            y,
                            scale,
                            rotation,
                            color,
                        );
                    }
                    DrawCommand::Clear { color } => {
                        d.clear(color);
                    }
                }
            }

            // Drop EXPLÍCITO para forzar buffer swap (fix Zink/Vulkan)
            drop(d);
        }

        // Reset contador de frame
        self.frame_count = 0;
    }

    /// ✅ v0.10.4: Ejecutar comandos con DrawHandle existente (para integrar con partículas)
    pub fn execute_with_handle(&mut self, d: &mut crate::DrawHandle, assets: &Assets) {
        if self.commands.is_empty() {
            return;
        }

        // Actualizar estadísticas
        if self.frame_count > self.max_frame_count {
            self.max_frame_count = self.frame_count;
        }
        self.total_executed += self.frame_count;

        for command in self.commands.drain(..) {
            match command {
                DrawCommand::Circle {
                    x,
                    y,
                    radius,
                    color,
                } => {
                    d.draw_circle(x, y, radius, color);
                }
                DrawCommand::Rect { x, y, w, h, color } => {
                    d.draw_rectangle(x, y, w, h, color);
                }
                DrawCommand::Line {
                    x1,
                    y1,
                    x2,
                    y2,
                    color,
                } => {
                    d.draw_line(x1, y1, x2, y2, color);
                }
                DrawCommand::Text {
                    text,
                    x,
                    y,
                    size,
                    color,
                } => {
                    d.draw_text(&text, x, y, size, color);
                }
                DrawCommand::Triangle { v1, v2, v3, color } => {
                    d.draw_triangle(v1, v2, v3, color);
                }
                DrawCommand::Texture {
                    id,
                    x,
                    y,
                    scale,
                    rotation,
                    color,
                } => {
                    // d es DrawHandle, usar d.draw para obtener RaylibDrawHandle
                    assets.draw_texture_ex_by_id(&mut d.draw, &id, x, y, scale, rotation, color);
                }
                DrawCommand::Clear { color } => {
                    d.clear(color);
                }
            }
        }

        // Reset contador de frame
        self.frame_count = 0;
    }

    /// Limpiar queue sin ejecutar
    pub fn clear(&mut self) {
        self.commands.clear();
        self.frame_count = 0;
    }

    /// Obtener cantidad de comandos pendientes
    pub fn len(&self) -> usize {
        self.commands.len()
    }

    /// Verificar si está vacía
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    /// Obtener capacidad máxima
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Obtener estadísticas
    pub fn stats(&self) -> RenderQueueStats {
        RenderQueueStats {
            pending: self.commands.len(),
            frame_count: self.frame_count,
            total_executed: self.total_executed,
            max_frame_count: self.max_frame_count,
            capacity: self.capacity,
        }
    }
}

impl Default for RenderQueue {
    fn default() -> Self {
        Self::new()
    }
}

/// Estadísticas de la render queue
#[derive(Debug, Clone, Default)]
pub struct RenderQueueStats {
    pub pending: usize,
    pub frame_count: usize,
    pub total_executed: usize,
    pub max_frame_count: usize,
    pub capacity: usize,
}

impl std::fmt::Display for RenderQueueStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "RenderQueue {{ pending: {}, frame: {}, total: {}, max: {}, capacity: {} }}",
            self.pending,
            self.frame_count,
            self.total_executed,
            self.max_frame_count,
            self.capacity
        )
    }
}

// ============================================================================
// DOUBLE BUFFERING - Separar lógica de renderizado
// ============================================================================

/// Double Buffer para draw commands
///
/// **Front Buffer**: Lógica acumula comandos (executor)
/// **Back Buffer**: Render ejecuta comandos (gfx)
/// **Swap**: Intercambiar buffers al final del frame
pub struct DoubleBuffer {
    /// Front buffer (acumulación - lógica)
    front: RenderQueue,
    /// Back buffer (ejecución - render)
    back: RenderQueue,
    /// Frame actual
    frame: u64,
}

impl DoubleBuffer {
    /// Crear double buffer con capacidad
    pub fn new(capacity: usize) -> Self {
        println!("[DOUBLE BUFFER] Creado con capacidad={}", capacity);
        Self {
            front: RenderQueue::with_capacity(capacity),
            back: RenderQueue::with_capacity(capacity),
            frame: 0,
        }
    }

    /// Push al front buffer (lógica)
    pub fn push(&mut self, command: DrawCommand) {
        self.front.push(command);
    }

    /// Swap de buffers: front → back
    /// Retorna el back buffer anterior para ejecutar
    pub fn swap(&mut self) {
        self.frame += 1;

        // Intercambiar buffers
        std::mem::swap(&mut self.front, &mut self.back);

        #[cfg(debug_assertions)]
        eprintln!(
            "[DOUBLE BUFFER] Frame {} - Swap completado (back: {} comandos)",
            self.frame,
            self.back.len()
        );
    }

    /// Ejecutar back buffer
    pub fn execute(&mut self, gfx: &mut RyditGfx, assets: &Assets) {
        self.back.execute(gfx, assets);
        self.back.clear();
    }

    /// Swap + execute (operación combinada)
    pub fn swap_and_execute(&mut self, gfx: &mut RyditGfx, assets: &Assets) {
        self.swap();
        self.execute(gfx, assets);
    }

    /// Obtener frame actual
    pub fn frame(&self) -> u64 {
        self.frame
    }

    /// Obtener estadísticas de ambos buffers
    pub fn stats(&self) -> (RenderQueueStats, RenderQueueStats) {
        (self.front.stats(), self.back.stats())
    }
}

// ✅ v0.10.8: PlatformSync migrado a v-shield (re-export arriba)

// ============================================================================
// INTEGRACIÓN CON RyditGfx
// ============================================================================

/// Extensión para RyditGfx con render queue
pub trait RyditGfxExt {
    /// Ejecutar comandos desde queue
    fn execute_queue(&mut self, queue: &mut RenderQueue, assets: &Assets);

    /// Platform sync (X11)
    fn platform_sync(&mut self);
}

impl RyditGfxExt for RyditGfx {
    fn execute_queue(&mut self, queue: &mut RenderQueue, assets: &Assets) {
        queue.execute(self, assets);
    }

    fn platform_sync(&mut self) {
        // Platform sync se maneja externamente
        // El buffer swap ya ocurre en Drop de DrawHandle
    }
}