-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1010 lines (813 loc) · 43.3 KB
/
Copy pathmain.py
File metadata and controls
1010 lines (813 loc) · 43.3 KB
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
PenguinTrack - Sistema de Rastreamento Facial para Jogos
Similar ao OpenTrack, detecta movimento da cabeça e converte em dados de controle de câmera
"""
import tkinter as tk
from tkinter import ttk, messagebox
import cv2
import numpy as np
from PIL import Image, ImageTk
import threading
import time
import json
import os
import sys
# Adiciona o diretório src ao path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from src.core.face_tracker import FaceTracker
from src.output.output_manager import OutputManager
from src.core.filters import FilterManager
from src.core.config_manager import ConfigManager
class PenguinTrackApp:
def __init__(self, root):
self.root = root
self.root.title("PenguinTrack - Rastreamento Facial v1.0")
self.root.geometry("1200x750")
# Define o ícone do programa
try:
# Tenta usar o ícone PNG
icon_path = os.path.join("assets", "img", "logo256.png")
if os.path.exists(icon_path):
# Para sistemas que suportam PNG como ícone
icon_image = Image.open(icon_path)
icon_photo = ImageTk.PhotoImage(icon_image)
self.root.iconphoto(True, icon_photo)
print("✅ Ícone do programa carregado:", icon_path)
else:
print("⚠️ Ícone não encontrado em:", icon_path)
except Exception as e:
print(f"⚠️ Erro ao carregar ícone: {e}")
# Managers
self.config_manager = ConfigManager()
self.face_tracker = FaceTracker(self.config_manager)
self.filter_manager = FilterManager(self.config_manager)
self.cube_filter_manager = FilterManager(self.config_manager) # Filtro separado para o avatar
self.output_manager = OutputManager(self.config_manager)
# Estado
self.tracking_active = False
self.camera_thread = None
self.current_frame = None
self.reset_frames_remaining = 0 # Contador para manter cubo resetado
# Avatar Logo (substitui cubo 3D)
self.avatar_image = None
self.avatar_photo = None
self.avatar_canvas = None
self.cube_visible = True
# Interface
self.setup_ui()
# Carrega configurações
self.load_settings()
def setup_ui(self):
"""Configura a interface do usuário"""
# Frame principal
main_frame = ttk.Frame(self.root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Frame esquerdo - Visualização (câmera + cubo + dados)
left_frame = ttk.LabelFrame(main_frame, text="Visualização e Dados")
left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
# Container para câmera e cubo (lado a lado)
video_container = ttk.Frame(left_frame)
video_container.pack(fill=tk.X, padx=5, pady=5)
# Frame da câmera
camera_frame = ttk.LabelFrame(video_container, text="Câmera")
camera_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 3))
# Canvas para vídeo (tamanho reduzido)
self.video_canvas = tk.Canvas(camera_frame, width=420, height=315, bg='black')
self.video_canvas.pack(padx=5, pady=5)
# Frame do avatar logo
avatar_frame = ttk.LabelFrame(video_container, text="Avatar")
avatar_frame.pack(side=tk.RIGHT, fill=tk.BOTH, padx=(3, 0))
# Canvas para avatar logo
self.avatar_canvas = tk.Canvas(avatar_frame, width=315, height=315, bg='#F8F8F8')
self.avatar_canvas.pack(padx=5, pady=5)
# Carrega e inicializa avatar logo
self.load_avatar_logo()
# Frame de dados de saída (MOVIDO para baixo da câmera)
output_frame = ttk.LabelFrame(left_frame, text="Dados de Saída em Tempo Real")
output_frame.pack(fill=tk.X, padx=5, pady=2)
# Labels para mostrar dados em formato compacto
data_container = ttk.Frame(output_frame)
data_container.pack(fill=tk.X, padx=5, pady=3)
# Primeira linha - Rotações
rotation_frame = ttk.Frame(data_container)
rotation_frame.pack(fill=tk.X, pady=1)
ttk.Label(rotation_frame, text="Rotação:", font=("Arial", 9, "bold")).pack(side=tk.LEFT)
self.yaw_label = ttk.Label(rotation_frame, text="Yaw: 0.0°", foreground="#44FF44",
font=("Arial", 8, "bold"))
self.yaw_label.pack(side=tk.LEFT, padx=10)
self.pitch_label = ttk.Label(rotation_frame, text="Pitch: 0.0°", foreground="#FF4444",
font=("Arial", 8, "bold"))
self.pitch_label.pack(side=tk.LEFT, padx=10)
self.roll_label = ttk.Label(rotation_frame, text="Roll: 0.0°", foreground="#4444FF",
font=("Arial", 8, "bold"))
self.roll_label.pack(side=tk.LEFT, padx=10)
# Segunda linha - Posições
position_frame = ttk.Frame(data_container)
position_frame.pack(fill=tk.X, pady=1)
ttk.Label(position_frame, text="Posição:", font=("Arial", 9, "bold")).pack(side=tk.LEFT)
self.x_label = ttk.Label(position_frame, text="X: 0.0mm", foreground="#FF44FF",
font=("Arial", 8))
self.x_label.pack(side=tk.LEFT, padx=10)
self.y_label = ttk.Label(position_frame, text="Y: 0.0mm", foreground="#FFAA44",
font=("Arial", 8))
self.y_label.pack(side=tk.LEFT, padx=10)
self.z_label = ttk.Label(position_frame, text="Z: 0.0mm", foreground="#44AAFF",
font=("Arial", 8))
self.z_label.pack(side=tk.LEFT, padx=10)
# ===== CONTROLES GERAIS (movidos da aba Rastreamento) =====
general_frame = ttk.LabelFrame(left_frame, text="Controles Gerais")
general_frame.pack(fill=tk.X, padx=5, pady=2)
# Container para os controles
general_container = ttk.Frame(general_frame)
general_container.pack(fill=tk.X, padx=5, pady=3)
# Botões de preset - em linha horizontal
preset_frame = ttk.Frame(general_container)
preset_frame.pack(fill=tk.X, pady=1)
ttk.Button(preset_frame, text="Reset",
command=self.reset_all_axes).pack(side=tk.LEFT, padx=2)
ttk.Button(preset_frame, text="Gaming",
command=self.apply_gaming_preset).pack(side=tk.LEFT, padx=2)
ttk.Button(preset_frame, text="Simulação",
command=self.apply_simulation_preset).pack(side=tk.LEFT, padx=2)
# Inversões - em linha horizontal
invert_frame = ttk.LabelFrame(general_container, text="Inversões")
invert_frame.pack(fill=tk.X, pady=2)
invert_controls = ttk.Frame(invert_frame)
invert_controls.pack(fill=tk.X, padx=5, pady=2)
self.invert_yaw = tk.BooleanVar()
ttk.Checkbutton(invert_controls, text="Yaw",
variable=self.invert_yaw,
command=self.on_invert_change).pack(side=tk.LEFT, padx=10)
self.invert_pitch = tk.BooleanVar()
ttk.Checkbutton(invert_controls, text="Pitch",
variable=self.invert_pitch,
command=self.on_invert_change).pack(side=tk.LEFT, padx=10)
self.invert_roll = tk.BooleanVar()
ttk.Checkbutton(invert_controls, text="Roll",
variable=self.invert_roll,
command=self.on_invert_change).pack(side=tk.LEFT, padx=10)
# Controles de rastreamento básicos
tracking_frame = ttk.Frame(left_frame)
tracking_frame.pack(fill=tk.X, padx=5, pady=2)
self.start_button = ttk.Button(tracking_frame, text="Iniciar Rastreamento",
command=self.toggle_tracking)
self.start_button.pack(side=tk.LEFT, padx=3)
self.reset_button = ttk.Button(tracking_frame, text="Reset Posição",
command=self.reset_tracking)
self.reset_button.pack(side=tk.LEFT, padx=3)
# Botão mostrar/ocultar avatar
self.cube_button = ttk.Button(tracking_frame, text="Ocultar Avatar",
command=self.toggle_cube)
self.cube_button.pack(side=tk.LEFT, padx=3)
# Status
self.status_label = ttk.Label(tracking_frame, text="Status: Parado")
self.status_label.pack(side=tk.RIGHT, padx=3)
# Frame direito - Configurações (simples, sem scroll externo)
right_frame = ttk.LabelFrame(main_frame, text="Configurações")
right_frame.pack(side=tk.RIGHT, fill=tk.Y, padx=(5, 0))
# Notebook para abas de configuração
self.notebook = ttk.Notebook(right_frame)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Aba Rastreamento
self.setup_tracking_tab()
# Aba Saída
self.setup_output_tab()
# Aba Filtros
self.setup_filters_tab()
# Aba Câmera
self.setup_camera_tab()
def load_avatar_logo(self):
"""Carrega e exibe o avatar logo com grid de fundo"""
try:
# Limpa o canvas
self.avatar_canvas.delete("all")
canvas_size = 315
center_x = canvas_size // 2
center_y = canvas_size // 2
# Desenha grid de fundo
grid_spacing = 20
grid_color = "#e0e0e0"
# Linhas verticais
for x in range(0, canvas_size, grid_spacing):
self.avatar_canvas.create_line(x, 0, x, canvas_size, fill=grid_color, width=1)
# Linhas horizontais
for y in range(0, canvas_size, grid_spacing):
self.avatar_canvas.create_line(0, y, canvas_size, y, fill=grid_color, width=1)
# Desenha eixos coloridos no centro
axis_length = 40
# Eixo X (vermelho) - horizontal
self.avatar_canvas.create_line(
center_x - axis_length, center_y,
center_x + axis_length, center_y,
fill="#FF4444", width=2, tags="axes"
)
# Eixo Y (verde) - vertical
self.avatar_canvas.create_line(
center_x, center_y - axis_length,
center_x, center_y + axis_length,
fill="#44FF44", width=2, tags="axes"
)
logo_path = os.path.join("assets", "img", "pingu.png")
if os.path.exists(logo_path):
# Carrega a imagem original
self.avatar_image = Image.open(logo_path)
# Redimensiona para tamanho menor (120x120 máximo)
max_size = 120
image_size = self.avatar_image.size
# Calcula novo tamanho mantendo proporção
if image_size[0] > image_size[1]: # Largura maior
new_width = max_size
new_height = int((image_size[1] * max_size) / image_size[0])
else: # Altura maior ou igual
new_height = max_size
new_width = int((image_size[0] * max_size) / image_size[1])
# Redimensiona a imagem base
self.avatar_image = self.avatar_image.resize((new_width, new_height), Image.Resampling.LANCZOS)
self.avatar_photo = ImageTk.PhotoImage(self.avatar_image)
# Centraliza a imagem no canvas
self.avatar_canvas.create_image(
center_x, center_y,
image=self.avatar_photo,
tags="avatar"
)
print("✅ Avatar logo carregado:", logo_path)
else:
# Se não encontrar o logo, exibe texto
self.avatar_canvas.create_text(
center_x, center_y,
text="PenguinTrack\nAvatar",
font=("Arial", 16, "bold"),
fill="#666666",
justify=tk.CENTER,
tags="avatar"
)
print("⚠️ Logo não encontrado, usando texto. Caminho:", logo_path)
except Exception as e:
print(f"⚠️ Erro ao carregar avatar logo: {e}")
# Fallback: texto simples
self.avatar_canvas.create_text(
157, 157,
text="PenguinTrack",
font=("Arial", 16, "bold"),
fill="#666666",
tags="avatar"
)
def update_avatar_rotation(self, yaw, pitch, roll):
"""Atualiza a rotação visual do avatar aplicando transformações 3D"""
if not self.avatar_image or not self.avatar_canvas:
return
try:
# Remove apenas o avatar anterior (mantém grid e eixos)
self.avatar_canvas.delete("avatar")
# Trabalha com uma cópia da imagem original
working_image = self.avatar_image.copy()
# Aplica rotação Z (roll) - rotação no plano da imagem
if abs(roll) > 0.5: # Só aplica se houver rotação significativa
working_image = working_image.rotate(-roll, expand=False, fillcolor=(248, 248, 248))
# Simula rotação 3D com transformações de perspectiva
# Para pitch (rotação X): escala vertical baseada no ângulo
if abs(pitch) > 0.5:
scale_factor = abs(np.cos(np.radians(pitch)))
scale_factor = max(0.4, scale_factor) # Mínimo de 40% para manter visível
# Redimensiona altura para simular perspectiva
original_size = working_image.size
new_height = int(original_size[1] * scale_factor)
new_size = (original_size[0], max(15, new_height)) # Altura mínima
working_image = working_image.resize(new_size, Image.Resampling.LANCZOS)
# Para yaw (rotação Y): escala horizontal baseada no ângulo
if abs(yaw) > 0.5:
scale_factor = abs(np.cos(np.radians(yaw)))
scale_factor = max(0.4, scale_factor) # Mínimo de 40% para manter visível
# Redimensiona largura para simular perspectiva
current_size = working_image.size
new_width = int(current_size[0] * scale_factor)
new_size = (max(15, new_width), current_size[1]) # Largura mínima
working_image = working_image.resize(new_size, Image.Resampling.LANCZOS)
# Converte para PhotoImage
self.avatar_photo = ImageTk.PhotoImage(working_image)
# Calcula posição com offset baseado nos movimentos (reduzido para o avatar menor)
canvas_center_x = 157 + int(yaw * 0.8) # Movimento horizontal mais suave
canvas_center_y = 157 + int(pitch * 0.8) # Movimento vertical mais suave
# Mantém dentro dos limites do canvas
canvas_center_x = max(60, min(255, canvas_center_x))
canvas_center_y = max(60, min(255, canvas_center_y))
# Desenha a imagem transformada
self.avatar_canvas.create_image(
canvas_center_x, canvas_center_y,
image=self.avatar_photo,
tags="avatar"
)
# Desenha eixos do avatar rotacionados
self.draw_avatar_axes(canvas_center_x, canvas_center_y, yaw, pitch, roll)
except Exception as e:
print(f"⚠️ Erro ao atualizar rotação do avatar: {e}")
# Em caso de erro, recarrega avatar estático
self.load_avatar_logo()
def draw_avatar_axes(self, center_x, center_y, yaw, pitch, roll):
"""Desenha os eixos do avatar com base na rotação atual"""
try:
# Remove eixos anteriores do avatar
self.avatar_canvas.delete("avatar_axes")
# Comprimento dos eixos do avatar
axis_length = 25
# Converte ângulos para radianos
yaw_rad = np.radians(yaw)
pitch_rad = np.radians(pitch)
roll_rad = np.radians(roll)
# Calcula as direções dos eixos rotacionados
# Eixo X (vermelho) - originalmente (1, 0)
x_dir_x = np.cos(yaw_rad) * np.cos(roll_rad) - np.sin(yaw_rad) * np.sin(roll_rad) * np.cos(pitch_rad)
x_dir_y = np.sin(roll_rad) * np.sin(pitch_rad)
# Eixo Y (verde) - originalmente (0, 1)
y_dir_x = -np.sin(yaw_rad) * np.cos(roll_rad) - np.cos(yaw_rad) * np.sin(roll_rad) * np.cos(pitch_rad)
y_dir_y = np.cos(roll_rad) * np.sin(pitch_rad)
# Eixo Z (azul) - representado como um círculo no centro (não visível em 2D diretamente)
z_scale = abs(np.cos(pitch_rad) * np.cos(yaw_rad)) # Escala baseada na rotação
# Desenha eixo X (vermelho)
end_x_x = center_x + x_dir_x * axis_length
end_x_y = center_y + x_dir_y * axis_length
self.avatar_canvas.create_line(
center_x, center_y, end_x_x, end_x_y,
fill="#FF4444", width=2, tags="avatar_axes"
)
# Seta do eixo X
self.avatar_canvas.create_oval(
end_x_x - 3, end_x_y - 3, end_x_x + 3, end_x_y + 3,
fill="#FF4444", outline="#FF4444", tags="avatar_axes"
)
# Desenha eixo Y (verde)
end_y_x = center_x + y_dir_x * axis_length
end_y_y = center_y + y_dir_y * axis_length
self.avatar_canvas.create_line(
center_x, center_y, end_y_x, end_y_y,
fill="#44FF44", width=2, tags="avatar_axes"
)
# Seta do eixo Y
self.avatar_canvas.create_oval(
end_y_x - 3, end_y_y - 3, end_y_x + 3, end_y_y + 3,
fill="#44FF44", outline="#44FF44", tags="avatar_axes"
)
# Desenha eixo Z (azul) como um círculo que muda de tamanho com a rotação
z_radius = max(3, int(8 * z_scale))
self.avatar_canvas.create_oval(
center_x - z_radius, center_y - z_radius,
center_x + z_radius, center_y + z_radius,
outline="#4444FF", width=2, fill="", tags="avatar_axes"
)
# Ponto central
self.avatar_canvas.create_oval(
center_x - 2, center_y - 2, center_x + 2, center_y + 2,
fill="#333333", outline="#333333", tags="avatar_axes"
)
except Exception as e:
pass # Ignora erros no desenho dos eixos
def setup_tracking_tab(self):
"""Configura a aba de rastreamento com controles individuais por eixo"""
tracking_tab = ttk.Frame(self.notebook)
self.notebook.add(tracking_tab, text="Rastreamento")
# Frame principal para os controles (sem scroll)
main_frame = ttk.Frame(tracking_tab)
main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# ===== SENSIBILIDADES POR EIXO =====
sens_frame = ttk.LabelFrame(main_frame, text="Sensibilidade por Eixo")
sens_frame.pack(fill=tk.X, padx=0, pady=2)
self.sensitivity_scales = {}
# Eixos de rotação
rotation_frame = ttk.LabelFrame(sens_frame, text="Rotação")
rotation_frame.pack(fill=tk.X, padx=2, pady=1)
for i, (axis, label, color) in enumerate([
('yaw', 'Yaw (Esq/Dir)', '#44FF44'),
('pitch', 'Pitch (Cima/Baixo)', '#FF4444'),
('roll', 'Roll (Inclinação)', '#4444FF')
]):
frame = ttk.Frame(rotation_frame)
frame.pack(fill=tk.X, padx=2, pady=1)
ttk.Label(frame, text=f"{label}:", foreground=color,
font=("Arial", 7, "bold"), width=15).pack(side=tk.LEFT)
scale = tk.Scale(frame, from_=0.0, to=3.0, resolution=0.1,
orient=tk.HORIZONTAL, font=("Arial", 6),
command=lambda val, ax=axis: self.on_sensitivity_change(ax, val))
scale.set(1.0)
scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(3, 0))
self.sensitivity_scales[axis] = scale
# Eixos de translação
translation_frame = ttk.LabelFrame(sens_frame, text="Posição")
translation_frame.pack(fill=tk.X, padx=2, pady=1)
for i, (axis, label, color) in enumerate([
('x', 'X (Horizontal)', '#FF44FF'),
('y', 'Y (Vertical)', '#FFAA44'),
('z', 'Z (Profundidade)', '#44AAFF')
]):
frame = ttk.Frame(translation_frame)
frame.pack(fill=tk.X, padx=2, pady=1)
ttk.Label(frame, text=f"{label}:", foreground=color,
font=("Arial", 7, "bold"), width=15).pack(side=tk.LEFT)
scale = tk.Scale(frame, from_=0.0, to=3.0, resolution=0.1,
orient=tk.HORIZONTAL, font=("Arial", 6),
command=lambda val, ax=axis: self.on_sensitivity_change(ax, val))
scale.set(1.0)
scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(3, 0))
self.sensitivity_scales[axis] = scale
# ===== ZONAS MORTAS POR EIXO =====
deadzone_frame = ttk.LabelFrame(main_frame, text="Zona Morta por Eixo")
deadzone_frame.pack(fill=tk.X, padx=0, pady=2)
self.deadzone_scales = {}
# Zona morta para rotação
rot_dead_frame = ttk.LabelFrame(deadzone_frame, text="Rotação")
rot_dead_frame.pack(fill=tk.X, padx=2, pady=1)
for axis, label, color in [
('yaw', 'Yaw', '#44FF44'),
('pitch', 'Pitch', '#FF4444'),
('roll', 'Roll', '#4444FF')
]:
frame = ttk.Frame(rot_dead_frame)
frame.pack(fill=tk.X, padx=2, pady=1)
ttk.Label(frame, text=f"{label}:", foreground=color,
font=("Arial", 7, "bold"), width=15).pack(side=tk.LEFT)
scale = tk.Scale(frame, from_=0.0, to=10.0, resolution=0.1,
orient=tk.HORIZONTAL, font=("Arial", 6),
command=lambda val, ax=axis: self.on_deadzone_change(ax, val))
scale.set(2.0)
scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(3, 0))
self.deadzone_scales[axis] = scale
# Zona morta para translação
trans_dead_frame = ttk.LabelFrame(deadzone_frame, text="Posição")
trans_dead_frame.pack(fill=tk.X, padx=2, pady=1)
for axis, label, color in [
('x', 'X', '#FF44FF'),
('y', 'Y', '#FFAA44'),
('z', 'Z', '#44AAFF')
]:
frame = ttk.Frame(trans_dead_frame)
frame.pack(fill=tk.X, padx=2, pady=1)
ttk.Label(frame, text=f"{label}:", foreground=color,
font=("Arial", 7, "bold"), width=15).pack(side=tk.LEFT)
scale = tk.Scale(frame, from_=0.0, to=10.0, resolution=0.1,
orient=tk.HORIZONTAL, font=("Arial", 6),
command=lambda val, ax=axis: self.on_deadzone_change(ax, val))
scale.set(2.0)
scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(3, 0))
self.deadzone_scales[axis] = scale
def reset_all_axes(self):
"""Reseta todos os eixos para valores padrão"""
for scale in self.sensitivity_scales.values():
scale.set(1.0)
for scale in self.deadzone_scales.values():
scale.set(2.0)
def apply_gaming_preset(self):
"""Aplica preset otimizado para jogos"""
gaming_sens = {'yaw': 1.8, 'pitch': 1.5, 'roll': 1.2, 'x': 0.8, 'y': 0.8, 'z': 1.0}
gaming_dead = {'yaw': 1.0, 'pitch': 1.0, 'roll': 1.5, 'x': 1.0, 'y': 1.0, 'z': 1.5}
for axis, value in gaming_sens.items():
if axis in self.sensitivity_scales:
self.sensitivity_scales[axis].set(value)
for axis, value in gaming_dead.items():
if axis in self.deadzone_scales:
self.deadzone_scales[axis].set(value)
def apply_simulation_preset(self):
"""Aplica preset otimizado para simulação"""
sim_sens = {'yaw': 0.9, 'pitch': 0.8, 'roll': 0.6, 'x': 0.7, 'y': 0.7, 'z': 0.8}
sim_dead = {'yaw': 0.5, 'pitch': 0.5, 'roll': 1.0, 'x': 0.5, 'y': 0.5, 'z': 1.0}
for axis, value in sim_sens.items():
if axis in self.sensitivity_scales:
self.sensitivity_scales[axis].set(value)
for axis, value in sim_dead.items():
if axis in self.deadzone_scales:
self.deadzone_scales[axis].set(value)
def on_sensitivity_change(self, axis, value):
"""Callback chamado quando a sensibilidade de um eixo muda"""
if self.tracking_active:
self.update_config()
def on_deadzone_change(self, axis, value):
"""Callback chamado quando a zona morta de um eixo muda"""
if self.tracking_active:
self.update_config()
def on_invert_change(self):
"""Callback chamado quando uma inversão muda"""
if self.tracking_active:
self.update_config()
def on_filter_change(self, value=None):
"""Callback chamado quando um filtro muda"""
if self.tracking_active:
self.update_config()
def on_fps_change(self, value=None):
"""Callback chamado quando FPS muda"""
if self.tracking_active:
self.update_config()
# Reconfigura filtros com nova taxa de amostragem
self.filter_manager.setup_filters()
self.cube_filter_manager.setup_filters()
def setup_output_tab(self):
"""Configura a aba de saída"""
output_tab = ttk.Frame(self.notebook)
self.notebook.add(output_tab, text="Saída")
# Protocolo de saída
ttk.Label(output_tab, text="Protocolo:").pack(pady=5)
self.output_protocol = tk.StringVar(value="freetrack")
protocols = ["freetrack", "mouse", "joystick", "udp"]
for protocol in protocols:
ttk.Radiobutton(output_tab, text=protocol.title(),
variable=self.output_protocol,
value=protocol).pack(anchor=tk.W, padx=10)
# Configurações UDP
udp_frame = ttk.LabelFrame(output_tab, text="Configuração UDP")
udp_frame.pack(fill=tk.X, padx=10, pady=10)
ttk.Label(udp_frame, text="IP:").grid(row=0, column=0, padx=5, pady=2)
self.udp_ip = tk.StringVar(value="127.0.0.1")
ttk.Entry(udp_frame, textvariable=self.udp_ip, width=15).grid(row=0, column=1, padx=5)
ttk.Label(udp_frame, text="Porta:").grid(row=1, column=0, padx=5, pady=2)
self.udp_port = tk.StringVar(value="4242")
ttk.Entry(udp_frame, textvariable=self.udp_port, width=15).grid(row=1, column=1, padx=5)
def setup_filters_tab(self):
"""Configura a aba de filtros"""
filters_tab = ttk.Frame(self.notebook)
self.notebook.add(filters_tab, text="Filtros")
# Filtro de suavização
ttk.Label(filters_tab, text="Suavização (0=sem filtro, 0.9=máximo):").pack(pady=5)
self.smoothing_scale = tk.Scale(filters_tab, from_=0.0, to=0.9,
resolution=0.01, orient=tk.HORIZONTAL,
command=self.on_filter_change)
self.smoothing_scale.set(0.3) # Valor padrão reduzido para permitir mais movimento
self.smoothing_scale.pack(fill=tk.X, padx=10)
# Filtro passa-baixa
ttk.Label(filters_tab, text="Filtro Passa-baixa").pack(pady=(10,0))
ttk.Label(filters_tab, text="Frequência de Corte (Hz):").pack(pady=(0,5))
self.cutoff_scale = tk.Scale(filters_tab, from_=1.0, to=30.0,
resolution=0.5, orient=tk.HORIZONTAL,
command=self.on_filter_change)
self.cutoff_scale.set(10.0)
self.cutoff_scale.pack(fill=tk.X, padx=10)
# Predição
self.enable_prediction = tk.BooleanVar()
ttk.Checkbutton(filters_tab, text="Habilitar Predição",
variable=self.enable_prediction,
command=self.on_filter_change).pack(anchor=tk.W, padx=10, pady=5)
def setup_camera_tab(self):
"""Configura a aba da câmera"""
camera_tab = ttk.Frame(self.notebook)
self.notebook.add(camera_tab, text="Câmera")
# Dispositivo de câmera
ttk.Label(camera_tab, text="Dispositivo:").pack(pady=5)
self.camera_device = tk.StringVar(value="0")
device_combo = ttk.Combobox(camera_tab, textvariable=self.camera_device,
values=["0", "1", "2"])
device_combo.pack(fill=tk.X, padx=10)
# Resolução
ttk.Label(camera_tab, text="Resolução:").pack(pady=5)
self.camera_resolution = tk.StringVar(value="640x480")
resolution_combo = ttk.Combobox(camera_tab, textvariable=self.camera_resolution,
values=["320x240", "640x480", "800x600", "1280x720"])
resolution_combo.pack(fill=tk.X, padx=10)
# FPS
ttk.Label(camera_tab, text="FPS:").pack(pady=5)
self.fps_scale = tk.Scale(camera_tab, from_=15, to=60,
orient=tk.HORIZONTAL,
command=self.on_fps_change)
self.fps_scale.set(30)
self.fps_scale.pack(fill=tk.X, padx=10)
# Espelhar imagem
self.mirror_image = tk.BooleanVar(value=True)
ttk.Checkbutton(camera_tab, text="Espelhar Imagem",
variable=self.mirror_image).pack(anchor=tk.W, padx=10, pady=5)
def toggle_tracking(self):
"""Liga/desliga o rastreamento"""
if not self.tracking_active:
self.start_tracking()
else:
self.stop_tracking()
def start_tracking(self):
"""Inicia o rastreamento"""
try:
# Atualiza configurações
self.update_config()
# Inicia a câmera
camera_id = int(self.camera_device.get())
if not self.face_tracker.start_camera(camera_id):
messagebox.showerror("Erro", "Não foi possível acessar a câmera")
return
# Inicia o output manager
self.output_manager.start()
self.tracking_active = True
self.start_button.config(text="Parar Rastreamento")
self.status_label.config(text="Status: Rastreando")
# Inicia thread de processamento
self.camera_thread = threading.Thread(target=self.camera_loop, daemon=True)
self.camera_thread.start()
except Exception as e:
messagebox.showerror("Erro", f"Erro ao iniciar rastreamento: {str(e)}")
def stop_tracking(self):
"""Para o rastreamento"""
self.tracking_active = False
self.face_tracker.stop_camera()
self.output_manager.stop()
self.start_button.config(text="Iniciar Rastreamento")
self.status_label.config(text="Status: Parado")
def reset_tracking(self):
"""Reseta a posição de referência"""
# Reseta todos os componentes
self.face_tracker.reset_reference()
self.filter_manager.reset()
self.cube_filter_manager.reset() # Reseta também o filtro do avatar
# Força o cubo a ficar resetado por alguns frames
self.reset_frames_remaining = 10 # 10 frames em posição zero
# Reseta avatar
if self.avatar_canvas:
self.load_avatar_logo() # Recarrega avatar na posição inicial
# Feedback visual
self.status_label.config(text="Status: Resetado - Posição atual = zero")
# Volta o status após 1 segundo
self.root.after(1000, lambda: self.status_label.config(
text="Status: Rastreando" if self.tracking_active else "Status: Parado"
))
def toggle_cube(self):
"""Mostra/oculta o avatar"""
if self.cube_visible:
self.avatar_canvas.pack_forget()
self.avatar_canvas.master.pack_forget()
self.cube_button.config(text="Mostrar Avatar")
self.cube_visible = False
else:
self.avatar_canvas.master.pack(side=tk.RIGHT, fill=tk.BOTH, padx=(5, 0))
self.avatar_canvas.pack(padx=5, pady=5)
self.cube_button.config(text="Ocultar Avatar")
self.cube_visible = True
def camera_loop(self):
"""Loop principal da câmera"""
while self.tracking_active:
frame = self.face_tracker.get_frame()
if frame is not None:
# Processa o frame
processed_data = self.face_tracker.process_frame(frame)
if processed_data:
absolute_pose, relative_pose = processed_data
# Aplica sensibilidade e inversões à pose absoluta para o cubo
cube_pose = absolute_pose.copy()
config = self.config_manager.get_config()
sensitivity_per_axis = config.get('sensitivity_per_axis', {})
# Aplica sensibilidade por eixo ao cubo
for axis in ['yaw', 'pitch', 'roll', 'x', 'y', 'z']:
if axis in sensitivity_per_axis:
cube_pose[axis] *= sensitivity_per_axis[axis]
# Aplica inversões ao cubo
if config.get('invert_yaw', False):
cube_pose['yaw'] *= -1
if config.get('invert_pitch', False):
cube_pose['pitch'] *= -1
if config.get('invert_roll', False):
cube_pose['roll'] *= -1
# Aplica filtros de suavização ao cubo para reduzir tremor
filtered_cube_pose = self.cube_filter_manager.apply_filters(cube_pose)
# Aplica sensibilidade, zona morta e inversões à pose relativa para o jogo
game_pose = relative_pose.copy()
deadzone_per_axis = config.get('deadzone_per_axis', {})
# Aplica sensibilidade por eixo
for axis in ['yaw', 'pitch', 'roll', 'x', 'y', 'z']:
if axis in sensitivity_per_axis:
game_pose[axis] *= sensitivity_per_axis[axis]
# Aplica zona morta por eixo
for axis in ['yaw', 'pitch', 'roll', 'x', 'y', 'z']:
deadzone = deadzone_per_axis.get(axis, 2.0)
if abs(game_pose[axis]) < deadzone:
game_pose[axis] = 0.0
# Aplica inversões aos dados do jogo
if config.get('invert_yaw', False):
game_pose['yaw'] *= -1
if config.get('invert_pitch', False):
game_pose['pitch'] *= -1
if config.get('invert_roll', False):
game_pose['roll'] *= -1
# Aplica filtros nos dados do jogo
filtered_data = self.filter_manager.apply_filters(game_pose)
# Envia dados filtrados para o jogo
self.output_manager.send_data(filtered_data)
# Atualiza a interface com os dados filtrados
self.root.after(0, self.update_display, filtered_data)
# Atualiza avatar com a pose filtrada (ou pose zero durante reset)
if self.avatar_canvas and self.cube_visible:
if self.reset_frames_remaining > 0:
# Durante reset, mantém avatar em posição zero
self.root.after(0, self.update_avatar_rotation, 0.0, 0.0, 0.0)
self.reset_frames_remaining -= 1
else:
# Operação normal
yaw = filtered_cube_pose.get('yaw', 0.0)
pitch = filtered_cube_pose.get('pitch', 0.0)
roll = filtered_cube_pose.get('roll', 0.0)
self.root.after(0, self.update_avatar_rotation, yaw, pitch, roll)
# Atualiza canvas de vídeo
self.root.after(0, self.update_video_canvas, frame)
# Usa FPS configurado pelo usuário ao invés de 60 fixo
config = self.config_manager.get_config()
target_fps = config.get('fps', 30)
time.sleep(1/target_fps)
def update_display(self, data):
"""Atualiza os labels de dados"""
self.yaw_label.config(text=f"Yaw: {data['yaw']:.1f}°")
self.pitch_label.config(text=f"Pitch: {data['pitch']:.1f}°")
self.roll_label.config(text=f"Roll: {data['roll']:.1f}°")
self.x_label.config(text=f"X: {data['x']:.1f}mm")
self.y_label.config(text=f"Y: {data['y']:.1f}mm")
self.z_label.config(text=f"Z: {data['z']:.1f}mm")
def update_video_canvas(self, frame):
"""Atualiza o canvas de vídeo"""
if frame is not None:
# Converte frame para PIL
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Redimensiona para caber no canvas
height, width = rgb_frame.shape[:2]
canvas_width = self.video_canvas.winfo_width()
canvas_height = self.video_canvas.winfo_height()
if canvas_width > 1 and canvas_height > 1:
scale = min(canvas_width/width, canvas_height/height)
new_width = int(width * scale)
new_height = int(height * scale)
rgb_frame = cv2.resize(rgb_frame, (new_width, new_height))
# Converte para ImageTk
image = Image.fromarray(rgb_frame)
photo = ImageTk.PhotoImage(image)
# Atualiza canvas
self.video_canvas.delete("all")
x = (canvas_width - new_width) // 2
y = (canvas_height - new_height) // 2
self.video_canvas.create_image(x, y, anchor=tk.NW, image=photo)
self.video_canvas.image = photo # Mantém referência
def update_config(self):
"""Atualiza as configurações nos managers"""
# Coleta sensibilidades por eixo
sensitivity_per_axis = {}
for axis, scale in self.sensitivity_scales.items():
sensitivity_per_axis[axis] = scale.get()
# Coleta zonas mortas por eixo
deadzone_per_axis = {}
for axis, scale in self.deadzone_scales.items():
deadzone_per_axis[axis] = scale.get()
config = {
'sensitivity': 1.0, # Mantém compatibilidade
'deadzone': 2.0, # Mantém compatibilidade
'sensitivity_per_axis': sensitivity_per_axis,
'deadzone_per_axis': deadzone_per_axis,
'invert_yaw': self.invert_yaw.get(),
'invert_pitch': self.invert_pitch.get(),
'invert_roll': self.invert_roll.get(),
'output_protocol': self.output_protocol.get(),
'udp_ip': self.udp_ip.get(),
'udp_port': int(self.udp_port.get()),
'smoothing': self.smoothing_scale.get(),
'cutoff_frequency': self.cutoff_scale.get(),
'enable_prediction': self.enable_prediction.get(),
'camera_resolution': self.camera_resolution.get(),
'fps': self.fps_scale.get(),
'mirror_image': self.mirror_image.get()
}
self.config_manager.update_config(config)
def load_settings(self):
"""Carrega configurações salvas"""
config = self.config_manager.load_config()
if config:
# Carrega sensibilidades por eixo
sensitivity_per_axis = config.get('sensitivity_per_axis', {
'yaw': 1.0, 'pitch': 1.0, 'roll': 1.0,
'x': 1.0, 'y': 1.0, 'z': 1.0
})
for axis, value in sensitivity_per_axis.items():
if axis in self.sensitivity_scales:
self.sensitivity_scales[axis].set(value)
# Carrega zonas mortas por eixo
deadzone_per_axis = config.get('deadzone_per_axis', {
'yaw': 2.0, 'pitch': 2.0, 'roll': 2.0,
'x': 2.0, 'y': 2.0, 'z': 2.0
})
for axis, value in deadzone_per_axis.items():
if axis in self.deadzone_scales:
self.deadzone_scales[axis].set(value)
# Carrega outras configurações
self.invert_yaw.set(config.get('invert_yaw', False))
self.invert_pitch.set(config.get('invert_pitch', False))
self.invert_roll.set(config.get('invert_roll', False))
self.output_protocol.set(config.get('output_protocol', 'freetrack'))
self.udp_ip.set(config.get('udp_ip', '127.0.0.1'))
self.udp_port.set(str(config.get('udp_port', 4242)))
self.smoothing_scale.set(config.get('smoothing', 0.3)) # Valor padrão reduzido
self.cutoff_scale.set(config.get('cutoff_frequency', 10.0))
self.enable_prediction.set(config.get('enable_prediction', False))
self.camera_resolution.set(config.get('camera_resolution', '640x480'))
self.fps_scale.set(config.get('fps', 30))
self.mirror_image.set(config.get('mirror_image', True))
def save_settings(self):
"""Salva as configurações"""
self.update_config()
self.config_manager.save_config()
def on_closing(self):
"""Chamado quando a janela é fechada"""
if self.tracking_active:
self.stop_tracking()
self.save_settings()
self.root.destroy()