sevenx_engine 0.2.11

Engine de jogos 2D/3D completa com suporte Android, física, áudio, partículas, tilemap, UI, eventos e sistema 3D avançado com PBR.
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
# 📖 API 2D Completa - SevenX Engine v0.2.9


## 🎯 Índice


1. [GameState Trait]#gamestate-trait
2. [Engine & Config]#engine--config
3. [Input (Teclado & Mouse)]#input
4. [Renderização 2D]#renderização-2d
5. [Sprites & Animação]#sprites--animação
6. [GameObject & Transform]#gameobject--transform
7. [Física 2D]#física-2d
8. [Colisão]#colisão
9. [Câmera 2D]#câmera-2d
10. [Partículas 2D]#partículas-2d
11. [Shaders 2D]#shaders-2d
12. [UI & Texto]#ui--texto
13. [Áudio]#áudio
14. [Tilemap]#tilemap
15. [Eventos]#eventos
16. [Diálogos]#diálogos
17. [Save/Load]#saveload
18. [Gamepad]#gamepad
19. [Networking]#networking
20. [Conquistas]#conquistas

---

## GameState Trait


### Estrutura Básica


```rust
use sevenx_engine::*;

struct MeuJogo {
    // Seus campos aqui
    player_x: f32,
    player_y: f32,
}

impl GameState for MeuJogo {
    fn new() -> Self {
        // Inicialização
        Self {
            player_x: 400.0,
            player_y: 300.0,
        }
    }
    
    fn update(&mut self, dt: f32, input: &InputHandler, world: &mut World) {
        // Lógica do jogo (60 FPS)
    }
    
    fn draw(&mut self, world: &World, pixels: &mut [u8]) {
        // Renderização customizada (opcional)
    }
}
```

### Parâmetros


- **dt**: Delta time (tempo desde o último frame em segundos)
- **input**: Gerenciador de input (teclado, mouse, gamepad)
- **world**: Mundo do jogo (objetos, física, etc)
- **pixels**: Buffer de pixels RGBA (width * height * 4)

---

## Engine & Config


### Criar Engine


```rust
// Engine padrão
let engine = Engine::new();

// Engine customizada
let config = EngineConfig::new()
    .with_title("Meu Jogo")
    .with_size(1280, 720)
    .with_gravity(980.0)
    .with_clear_color(20, 20, 40, 255);

let engine = Engine::with_config(config);
```

### Executar


```rust
fn main() {
    Engine::new().run::<MeuJogo>();
}
```

### EngineConfig


```rust
EngineConfig {
    window_title: String,      // Título da janela
    window_width: u32,          // Largura (padrão: 800)
    window_height: u32,         // Altura (padrão: 600)
    gravity: f32,               // Gravidade (padrão: 980.0)
    clear_color: [u8; 4],      // Cor de fundo RGBA
}
```

---

## Input


### Teclado


```rust
// Verificar se tecla está pressionada
if input.is_key_pressed(KeyCode::Space) {
    player_jump();
}

// Verificar se tecla foi pressionada neste frame
if input.is_key_just_pressed(KeyCode::Enter) {
    start_game();
}

// Verificar se tecla foi solta neste frame
if input.is_key_just_released(KeyCode::Escape) {
    pause_game();
}

// Verificar se alguma tecla está pressionada
if input.any_key_pressed() {
    wake_up();
}

// Obter todas as teclas pressionadas
let keys = input.get_pressed_keys();
```

### KeyCodes Comuns


```rust
// Setas
KeyCode::ArrowUp, ArrowDown, ArrowLeft, ArrowRight

// Letras
KeyCode::KeyA, KeyB, KeyC... KeyZ

// Números
KeyCode::Digit1, Digit2... Digit9, Digit0

// Especiais
KeyCode::Space
KeyCode::Enter
KeyCode::Escape
KeyCode::Tab
KeyCode::Backspace
KeyCode::Shift
KeyCode::Control
KeyCode::Alt
```

### Mouse


```rust
// Botões
if input.is_mouse_button_pressed(MouseBtn::Left) {
    shoot();
}

if input.is_mouse_button_just_pressed(MouseBtn::Right) {
    aim();
}

if input.is_mouse_button_just_released(MouseBtn::Middle) {
    stop_aim();
}

// Botões disponíveis
MouseBtn::Left
MouseBtn::Right
MouseBtn::Middle
MouseBtn::Back
MouseBtn::Forward
MouseBtn::Other(u16)

// Posição
let (x, y) = input.get_mouse_position();
let x = input.get_mouse_x();
let y = input.get_mouse_y();

// Delta (movimento desde último frame)
let (dx, dy) = input.get_mouse_delta();

// Scroll
let delta = input.get_mouse_wheel_delta();
if input.is_scrolling_up() {
    zoom_in();
}
if input.is_scrolling_down() {
    zoom_out();
}
```

### Atalhos


```rust
// Modificadores
if input.is_ctrl_pressed() { }
if input.is_shift_pressed() { }
if input.is_alt_pressed() { }

// Eixos (WASD/Setas)
let horizontal = input.get_axis_horizontal(); // -1.0 a 1.0
let vertical = input.get_axis_vertical();     // -1.0 a 1.0

// Vetor de movimento
let (x, y) = input.get_movement_vector();
player_x += x * speed * dt;
player_y += y * speed * dt;
```

---

## Renderização 2D


### Primitivas Básicas


```rust
use sevenx_engine::ui;

// Pixel
ui::render_pixel(x, y, [255, 0, 0, 255], pixels, width);

// Linha
ui::render_line(x1, y1, x2, y2, [255, 255, 255, 255], pixels, width);

// Linha grossa
ui::render_thick_line(x1, y1, x2, y2, thickness, color, pixels, width);

// Retângulo preenchido
ui::render_rect(x, y, w, h, [255, 0, 0, 255], pixels, width);

// Retângulo com borda
ui::render_rect_outline(x, y, w, h, thickness, color, pixels, width);

// Círculo preenchido
ui::render_circle(cx, cy, radius, color, pixels, width);

// Círculo com borda
ui::render_circle_outline(cx, cy, radius, thickness, color, pixels, width);

// Elipse
ui::render_ellipse(cx, cy, rx, ry, color, pixels, width);

// Triângulo
ui::render_triangle(x1, y1, x2, y2, x3, y3, color, pixels, width);

// Polígono
let points = vec![(x1, y1), (x2, y2), (x3, y3), (x4, y4)];
ui::render_polygon(&points, color, pixels, width);

// Arco
ui::render_arc(cx, cy, radius, start_angle, end_angle, color, pixels, width);
```

### Gradientes


```rust
// Gradiente horizontal
ui::render_gradient_horizontal(
    x, y, w, h,
    [255, 0, 0, 255],    // Cor inicial
    [0, 0, 255, 255],    // Cor final
    pixels, width
);

// Gradiente vertical
ui::render_gradient_vertical(x, y, w, h, color1, color2, pixels, width);

// Gradiente radial
ui::render_gradient_radial(cx, cy, radius, color1, color2, pixels, width);
```

### Preenchimento


```rust
// Flood fill (preencher área)
ui::flood_fill(x, y, new_color, pixels, width, height);
```

### Grade


```rust
// Desenhar grade
ui::render_grid(
    x, y,           // Posição
    cell_size,      // Tamanho da célula
    rows, cols,     // Linhas e colunas
    color,          // Cor das linhas
    pixels, width
);
```

---

## Sprites & Animação


### Carregar Sprite


```rust
use sevenx_engine::sprite::SpriteSheet;

// De arquivo
let sprite = SpriteSheet::load("assets/player.png", 32, 32)?;

// Placeholder (sem arquivo)
let sprite = SpriteSheet::create_placeholder();
```

### SpriteSheet


```rust
pub struct SpriteSheet {
    pub texture: Vec<u8>,      // Dados da textura RGBA
    pub width: u32,            // Largura total
    pub height: u32,           // Altura total
    pub frame_width: u32,      // Largura do frame
    pub frame_height: u32,     // Altura do frame
    pub frames: Vec<Frame>,    // Lista de frames
}

// Métodos
sprite.get_frame(index);
sprite.frame_count();
```

### Animação


```rust
use sevenx_engine::animation::Animation;

let mut animation = Animation::new(vec![0, 1, 2, 3], 0.1); // frames, duração
animation.update(dt);
let current_frame = animation.current_frame();

// Controles
animation.play();
animation.pause();
animation.stop();
animation.set_loop(true);
animation.set_speed(1.5);
```

---

## GameObject & Transform


### Criar GameObject


```rust
use sevenx_engine::game_object::{GameObject, ObjectType};

let mut player = GameObject::new(100.0, 100.0, ObjectType::Player);
player.active = true;

// Adicionar ao mundo
world.add_object(player);
```

### ObjectType


```rust
pub enum ObjectType {
    Player,
    Enemy,
    Projectile,
    Coin,
    Platform,
    Trigger,
    Custom(String),
}
```

### Transform


```rust
// Posição
obj.transform.position = (x, y);
obj.transform.translate(dx, dy);

// Rotação (radianos)
obj.transform.rotation = 1.57;  // 90 graus
obj.transform.rotate(0.1);
obj.transform.set_rotation_degrees(90.0);
let degrees = obj.transform.get_rotation_degrees();

// Escala
obj.transform.scale = (2.0, 2.0);

// Flip
obj.transform.flip_h = true;  // Horizontal
obj.transform.flip_v = true;  // Vertical

// Z-index (profundidade)
obj.transform.z_index = 10;
```

---

## Física 2D


### Adicionar Física


```rust
use sevenx_engine::Physics;

let player = GameObject::new(100.0, 100.0, ObjectType::Player)
    .with_physics(Physics::new()
        .with_gravity(1.0)
        .with_drag(0.1)
        .with_max_velocity(500.0, 1000.0));
```

### Physics


```rust
pub struct Physics {
    pub velocity: (f32, f32),        // Velocidade (x, y)
    pub acceleration: (f32, f32),    // Aceleração
    pub gravity_scale: f32,          // Escala da gravidade (0-1)
    pub drag: f32,                   // Arrasto/fricção
    pub max_velocity: (f32, f32),    // Velocidade máxima
    pub mass: f32,                   // Massa
}

// Métodos
physics.apply_force(fx, fy);
physics.apply_impulse(ix, iy);
physics.set_velocity(vx, vy);
```

### Exemplo de Pulo


```rust
if input.is_key_just_pressed(KeyCode::Space) {
    if let Some(physics) = &mut player.physics {
        physics.velocity.1 = -400.0;  // Força para cima
    }
}
```

---

## Colisão


### Adicionar Collider


```rust
use sevenx_engine::Collider;

let player = GameObject::new(100.0, 100.0, ObjectType::Player)
    .with_collider(Collider::new(32.0, 32.0));

// Trigger (não bloqueia movimento)
let coin = GameObject::new(200.0, 200.0, ObjectType::Coin)
    .with_collider(Collider::new(16.0, 16.0).as_trigger());
```

### Collider


```rust
pub struct Collider {
    pub width: f32,
    pub height: f32,
    pub offset: (f32, f32),
    pub is_trigger: bool,
}
```

### Verificar Colisão


```rust
use sevenx_engine::collision::Rect;

let rect1 = Rect::new(x1, y1, w1, h1);
let rect2 = Rect::new(x2, y2, w2, h2);

if rect1.intersects(&rect2) {
    // Colisão detectada
}

// Verificar ponto dentro do retângulo
if rect1.contains_point(x, y) {
    // Ponto dentro
}
```

---

## Câmera 2D


### Usar Câmera


```rust
use sevenx_engine::Camera;

// Obter câmera da engine
let camera = engine.get_camera_mut();

// Posição
camera.position = (x, y);
camera.move_to(x, y);
camera.translate(dx, dy);

// Zoom
camera.zoom = 2.0;  // 2x zoom

// Seguir alvo
camera.follow(target_x, target_y, smoothness);

// Limites
camera.set_bounds(min_x, min_y, max_x, max_y);

// Conversão de coordenadas
let (screen_x, screen_y) = camera.world_to_screen(world_x, world_y);
let (world_x, world_y) = camera.screen_to_world(screen_x, screen_y);
```

---

## Partículas 2D


### Criar Sistema


```rust
use sevenx_engine::{ParticleSystem, ParticleConfig, BlendMode};

let mut particles = ParticleSystem::new(1000)
    .with_blend_mode(BlendMode::Additive)
    .with_drag(0.5);
```

### Emitir Partículas


```rust
// Burst (explosão)
let config = ParticleConfig::explosion();
particles.emit_burst(x, y, 50, config);

// Stream (contínuo)
let config = ParticleConfig::fire();
particles.emit_stream(x, y, 10.0, dt, config);
```

### Presets


```rust
ParticleConfig::explosion()  // Explosão
ParticleConfig::fire()       // Fogo
ParticleConfig::smoke()      // Fumaça
ParticleConfig::sparkle()    // Faíscas
ParticleConfig::magic()      // Magia
ParticleConfig::blood()      // Sangue
ParticleConfig::snow()       // Neve
ParticleConfig::rain()       // Chuva
```

### Partícula Customizada


```rust
use sevenx_engine::Particle;

let particle = Particle::new(x, y, vx, vy, lifetime, color, size)
    .with_turbulence(5.0)
    .with_color_shift([-100.0, 50.0, 100.0, 0.0])
    .with_acceleration(0.0, 50.0)
    .with_scale(1.0, -0.3)
    .with_rotation(0.0, 5.0)
    .with_fade(0.1, 0.2);

particles.emit(particle);
```

### Atualizar e Renderizar


```rust
// No update
particles.update(dt, gravity);

// No draw
particles.render(pixels, camera_x, camera_y, width, height);
```

---

## Shaders 2D


### Criar Shader Manager


```rust
use sevenx_engine::{Shader, ShaderManager, ShaderType};

let mut shader_manager = ShaderManager::new();
```

### Adicionar Shaders


```rust
// Bloom
shader_manager.add_shader(
    Shader::new(ShaderType::Bloom)
        .with_parameter("threshold", 200.0)
        .with_parameter("bloom_intensity", 1.5)
);

// Motion Blur
shader_manager.add_shader(
    Shader::new(ShaderType::MotionBlur)
        .with_parameter("direction", 0.0)
        .with_parameter("samples", 5.0)
);

// Hue Shift
shader_manager.add_shader(
    Shader::new(ShaderType::HueShift)
        .with_parameter("shift", 180.0)
);
```

### Tipos de Shader


```rust
// Básicos
ShaderType::Grayscale
ShaderType::Sepia
ShaderType::Invert
ShaderType::Blur
ShaderType::Pixelate

// Efeitos
ShaderType::ChromaticAberration
ShaderType::Vignette
ShaderType::Scanlines
ShaderType::CRT

// Avançados
ShaderType::Bloom
ShaderType::MotionBlur
ShaderType::GaussianBlur
ShaderType::EdgeDetect
ShaderType::Emboss
ShaderType::Sharpen

// Artísticos
ShaderType::OilPainting
ShaderType::Posterize

// Cor
ShaderType::HueShift
ShaderType::Saturation
ShaderType::Contrast
ShaderType::Brightness

// Especiais
ShaderType::Glitch
ShaderType::WaveDistortion
```

### Aplicar


```rust
// No draw
shader_manager.apply_all(pixels, width, height);
```

---

## UI & Texto


### Texto


```rust
use sevenx_engine::ui;

ui::render_text(
    "Hello World",
    x, y,
    [255, 255, 255, 255],  // Cor RGBA
    pixels,
    width
);

// Texto formatado
let score_text = format!("Score: {}", score);
ui::render_text(&score_text, 10, 10, [255, 255, 0, 255], pixels, width);
```

### Botões


```rust
use sevenx_engine::Button;

let mut button = Button::new(100, 100, 200, 50, "Click Me");

// No update
if button.update(input) {
    println!("Botão clicado!");
}

// No draw
button.render(pixels, width);
```

---

## Áudio


### Carregar e Tocar


```rust
use sevenx_engine::AudioSystem;

let mut audio = AudioSystem::new();

// Carregar som
audio.load_sound("shoot", "assets/shoot.wav")?;
audio.load_music("bgm", "assets/music.mp3")?;

// Tocar
audio.play_sound("shoot");
audio.play_music("bgm");

// Controles
audio.stop_music();
audio.pause_music();
audio.resume_music();

// Volume (0.0 a 1.0)
audio.set_sound_volume(0.8);
audio.set_music_volume(0.5);
```

---

## Tilemap


### Criar Tilemap


```rust
use sevenx_engine::{Tilemap, Tile};

let mut tilemap = Tilemap::new(20, 15, 32, 32);  // cols, rows, tile_w, tile_h

// Definir tile
tilemap.set_tile(x, y, Some(Tile::new(tile_id).with_solid(true)));

// Obter tile
if let Some(tile) = tilemap.get_tile(x, y) {
    if tile.solid {
        // Tile sólido
    }
}

// Renderizar
tilemap.render(pixels, camera_x, camera_y, width, height);
```

---

## Eventos


### Sistema de Eventos


```rust
use sevenx_engine::{EventSystem, EventData, EventType};

let mut events = EventSystem::new();

// Registrar listener
events.on(EventType::CoinCollected, |event| {
    println!("Moeda coletada!");
});

// Emitir evento
let event = EventData::new(EventType::CoinCollected)
    .with_data("points", "10");
events.emit(event);

// Processar eventos
events.process();
```

---

## Diálogos


### Criar Diálogo


```rust
use sevenx_engine::dialogue::{DialogueBuilder, DialogueSystem};

let mut dialogue_system = DialogueSystem::new();

let dialogue = DialogueBuilder::new("npc1", "Guarda")
    .add_node("Olá, viajante!")
    .add_node_with_choices(
        "O que deseja?",
        vec![
            ("Informações", 2),
            ("Tchau", 3),
        ],
    )
    .add_node("Aqui estão as informações...")
    .add_node("Até logo!")
    .build();

dialogue_system.add_dialogue(dialogue);

// Usar
dialogue_system.start_dialogue("npc1");
dialogue_system.advance();
dialogue_system.choose(0);
```

---

## Save/Load


### Salvar Jogo


```rust
use sevenx_engine::save_system::GameSave;

let mut save = GameSave::new();
save.player_data.level = 5;
save.game_progress.score = 1000;

// JSON
save.save_json("saves/save1.json")?;

// Binário
save.save_binary("saves/save1.dat")?;
```

### Carregar


```rust
let save = GameSave::load_json("saves/save1.json")?;
println!("Level: {}", save.player_data.level);
```

---

## Gamepad


### Usar Gamepad


```rust
use sevenx_engine::{GamepadManager, GamepadButton, GamepadAxis};

let gamepad = GamepadManager::new();

// Botões
if gamepad.is_button_pressed(GamepadButton::South) {
    jump();
}

// Eixos
let axis_x = gamepad.get_axis(GamepadAxis::LeftStickX);
let axis_y = gamepad.get_axis(GamepadAxis::LeftStickY);

player_x += axis_x * speed * dt;
player_y += axis_y * speed * dt;
```

---

## Networking


### Multiplayer


```rust
use sevenx_engine::NetworkManager;

// Host
let mut network = NetworkManager::create_host("player1", "Host");

// Cliente
let mut network = NetworkManager::connect_to_host(
    "player2",
    "Cliente",
    "127.0.0.1:8080"
);

// Enviar
network.update_player_position(x, y, 0.0);
network.send_chat("Olá!");

// Processar
network.process_messages();
```

---

## Conquistas


### Sistema de Conquistas


```rust
use sevenx_engine::{Achievement, AchievementSystem};

let mut achievements = AchievementSystem::new();

let achievement = Achievement::new(
    "first_kill",
    "Primeira Morte",
    "Derrote seu primeiro inimigo",
    10
);

achievements.add_achievement(achievement);

// Desbloquear
achievements.unlock("first_kill");

// Progresso
achievements.add_progress("coin_collector", 1);
```

---

**API 2D Completa! 🎮✨**