1
0
forked from Mirrors/RGSX

correction du mappage des controles

This commit is contained in:
skymike03
2025-07-25 17:23:38 +02:00
parent 0ad13f3e10
commit 6b88731d8f
9 changed files with 611 additions and 511 deletions

View File

@@ -5,11 +5,12 @@ import logging
import config
from config import CONTROLS_CONFIG_PATH
from display import draw_gradient
import xml.etree.ElementTree as ET
logger = logging.getLogger(__name__)
# Chemin du fichier de configuration des contrôles
CONTROLS_CONFIG_PATH = "/userdata/saves/ports/rgsx/controls.json"
CONTROLS_CONFIG_PATH = os.path.join(config.SAVE_FOLDER, "controls.json")
# Actions internes de RGSX à mapper
ACTIONS = [
@@ -36,11 +37,11 @@ SDL_TO_PYGAME_KEY = {
1073741904: pygame.K_LEFT, # Flèche Gauche
1073741903: pygame.K_RIGHT, # Flèche Droite
1073742050: pygame.K_LALT, # Alt gauche
1073742051: pygame.K_RSHIFT, # Alt droit
1073742054: pygame.K_RALT, # Alt droit (AltGr)
1073742049: pygame.K_LCTRL, # Ctrl gauche
1073742053: pygame.K_RCTRL, # Ctrl droit
1073742048: pygame.K_LSHIFT, # Shift gauche
1073742054: pygame.K_RALT, # Shift droit
1073742052: pygame.K_RSHIFT, # Shift droit
}
# Noms lisibles pour les touches clavier
@@ -156,31 +157,100 @@ KEY_NAMES = {
pygame.K_SLASH: "/",
}
# Noms lisibles pour les boutons de manette
BUTTON_NAMES = {
0: "A",
1: "B",
2: "X",
3: "Y",
4: "LB",
5: "RB",
6: "LT",
7: "RT",
8: "Select",
9: "Start",
}
def get_controller_button_names():
"""Récupère les noms des boutons depuis es_input.cfg"""
es_input_path = "/usr/share/emulationstation/es_input.cfg"
button_names = {}
if not os.path.exists(es_input_path):
return {i: f"Bouton {i}" for i in range(16)}
try:
tree = ET.parse(es_input_path)
root = tree.getroot()
# Mapping des noms ES vers des noms lisibles
es_button_names = {
"a": "A", "b": "B", "x": "X", "y": "Y",
"leftshoulder": "LB", "rightshoulder": "RB",
"lefttrigger": "LT", "righttrigger": "RT",
"select": "Select", "start": "Start",
"leftstick": "L3", "rightstick": "R3"
}
for inputConfig in root.findall("inputConfig"):
if inputConfig.get("type") == "joystick":
for input_tag in inputConfig.findall("input"):
if input_tag.get("type") == "button":
es_name = input_tag.get("name")
button_id = int(input_tag.get("id"))
readable_name = es_button_names.get(es_name, es_name.upper())
button_names[button_id] = readable_name
break
except Exception as e:
logger.error(f"Erreur parsing es_input.cfg: {e}")
# Compléter avec des noms génériques
for i in range(16):
if i not in button_names:
button_names[i] = f"Bouton {i}"
return button_names
def get_controller_axis_names():
"""Récupère les noms des axes depuis es_input.cfg"""
es_input_path = "/usr/share/emulationstation/es_input.cfg"
axis_names = {}
if not os.path.exists(es_input_path):
return {(i, d): f"Axe {i}{'+' if d > 0 else '-'}" for i in range(8) for d in [-1, 1]}
try:
tree = ET.parse(es_input_path)
root = tree.getroot()
# Mapping des noms ES vers des noms lisibles
es_axis_names = {
"leftx": "Joy G", "lefty": "Joy G",
"rightx": "Joy D", "righty": "Joy D",
"lefttrigger": "LT", "righttrigger": "RT"
}
for inputConfig in root.findall("inputConfig"):
if inputConfig.get("type") == "joystick":
for input_tag in inputConfig.findall("input"):
if input_tag.get("type") == "axis":
es_name = input_tag.get("name")
axis_id = int(input_tag.get("id"))
value = int(input_tag.get("value", "1"))
direction = 1 if value > 0 else -1
if es_name in es_axis_names:
base_name = es_axis_names[es_name]
if "Joy" in base_name:
if "leftx" in es_name or "rightx" in es_name:
axis_names[(axis_id, direction)] = f"{base_name} {'Droite' if direction > 0 else 'Gauche'}"
else:
axis_names[(axis_id, direction)] = f"{base_name} {'Bas' if direction > 0 else 'Haut'}"
else:
axis_names[(axis_id, direction)] = base_name
break
except Exception as e:
logger.error(f"Erreur parsing es_input.cfg: {e}")
# Compléter avec des noms génériques
for i in range(8):
for d in [-1, 1]:
if (i, d) not in axis_names:
axis_names[(i, d)] = f"Axe {i}{'+' if d > 0 else '-'}"
return axis_names
# Charger les noms depuis es_input.cfg
BUTTON_NAMES = get_controller_button_names()
AXIS_NAMES = get_controller_axis_names()
# Noms pour les axes de joystick
AXIS_NAMES = {
(0, 1): "Joy G Haut",
(0, -1): "Joy G Bas",
(1, 1): "Joy G Gauche",
(1, -1): "Joy G Droite",
(2, 1): "Joy D Haut",
(2, -1): "Joy D Bas",
(3, 1): "Joy D Gauche",
(3, -1): "Joy D Droite",
}
# Noms pour la croix directionnelle
HAT_NAMES = {
@@ -227,7 +297,7 @@ def load_controls_config():
return {}
def save_controls_config(controls_config):
#Enregistre la configuration des contrôles dans controls.json
"""Enregistre la configuration des contrôles dans controls.json"""
try:
os.makedirs(os.path.dirname(CONTROLS_CONFIG_PATH), exist_ok=True)
with open(CONTROLS_CONFIG_PATH, "w") as f:
@@ -236,8 +306,41 @@ def save_controls_config(controls_config):
except Exception as e:
logger.error(f"Erreur lors de l'enregistrement de controls.json : {e}")
def validate_controls_config(controls_config):
"""Valide la structure de la configuration des contrôles"""
required_actions = ["confirm", "cancel", "up", "down", "left", "right"]
for action in required_actions:
if action not in controls_config:
logger.warning(f"Action {action} manquante dans la configuration")
return False
mapping = controls_config[action]
if "type" not in mapping:
logger.warning(f"Type manquant pour l'action {action}")
return False
input_type = mapping["type"]
if input_type == "key" and "key" not in mapping:
logger.warning(f"Clé 'key' manquante pour l'action {action}")
return False
elif input_type == "button" and "button" not in mapping:
logger.warning(f"Clé 'button' manquante pour l'action {action}")
return False
elif input_type == "axis" and ("axis" not in mapping or "direction" not in mapping):
logger.warning(f"Clés 'axis' ou 'direction' manquantes pour l'action {action}")
return False
elif input_type == "hat" and "value" not in mapping:
logger.warning(f"Clé 'value' manquante pour l'action {action}")
return False
elif input_type == "mouse" and "button" not in mapping:
logger.warning(f"Clé 'button' manquante pour l'action {action}")
return False
return True
def get_readable_input_name(event):
#Retourne un nom lisible pour une entrée (touche, bouton, axe, hat, ou souris)
"""Retourne un nom lisible pour une entrée (touche, bouton, axe, hat, ou souris)"""
if event.type == pygame.KEYDOWN:
key_value = SDL_TO_PYGAME_KEY.get(event.key, event.key)
return KEY_NAMES.get(key_value, pygame.key.name(key_value) or f"Touche {key_value}")
@@ -245,202 +348,208 @@ def get_readable_input_name(event):
return BUTTON_NAMES.get(event.button, f"Bouton {event.button}")
elif event.type == pygame.JOYAXISMOTION:
if abs(event.value) > 0.5: # Seuil pour détecter un mouvement significatif
return AXIS_NAMES.get((event.axis, 1 if event.value > 0 else -1), f"Axe {event.axis}")
return AXIS_NAMES.get((event.axis, 1 if event.value > 0 else -1), f"Axe {event.axis} {'Positif' if event.value > 0 else 'Négatif'}")
elif event.type == pygame.JOYHATMOTION:
return HAT_NAMES.get(event.value, f"D-Pad {event.value}")
if event.value != (0, 0): # Ignorer la position neutre
return HAT_NAMES.get(event.value, f"D-Pad {event.value}")
elif event.type == pygame.MOUSEBUTTONDOWN:
return MOUSE_BUTTON_NAMES.get(event.button, f"Souris Bouton {event.button}")
return "Inconnu"
def map_controls(screen):
mapping = True
current_action = 0
clock = pygame.time.Clock()
while mapping:
clock.tick(100) # 100 FPS
"""Interface de mappage des contrôles avec maintien de 3 secondes"""
controls_config = load_controls_config()
current_action_index = 0
current_input = None
input_held_time = 0
last_input_name = None
last_frame_time = pygame.time.get_ticks()
config.needs_redraw = True
last_joyhat_time = 0
# État des entrées maintenues
held_keys = set()
held_buttons = set()
held_axes = {}
held_hats = {}
held_mouse_buttons = set()
while current_action_index < len(ACTIONS):
if config.needs_redraw:
progress = min(input_held_time / HOLD_DURATION, 1.0) if current_input else 0.0
draw_controls_mapping(screen, ACTIONS[current_action_index], last_input_name, current_input is not None, progress)
pygame.display.flip()
config.needs_redraw = False
current_time = pygame.time.get_ticks()
delta_time = current_time - last_frame_time
last_frame_time = current_time
for event in pygame.event.get():
# Initialisation des variables de contrôle
controls_config = load_controls_config()
current_action_index = 0
current_input = None
input_held_time = 0
last_input_name = None
last_frame_time = pygame.time.get_ticks()
config.needs_redraw = True
last_joyhat_time = 0 # Pour le débouncing des événements JOYHATMOTION
# Initialiser l'état des boutons et axes pour suivre les relâchements
held_keys = set()
held_buttons = set()
held_axes = {} # {axis: direction}
held_hats = {} # {hat: value}
held_mouse_buttons = set()
while current_action_index < len(ACTIONS):
if config.needs_redraw:
progress = min(input_held_time / HOLD_DURATION, 1.0) if current_input else 0.0
draw_controls_mapping(screen, ACTIONS[current_action_index], last_input_name, current_input is not None, progress)
pygame.display.flip()
config.needs_redraw = False
current_time = pygame.time.get_ticks()
delta_time = current_time - last_frame_time
last_frame_time = current_time
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
return False
# Détecter les relâchements pour réinitialiser
if event.type == pygame.KEYUP:
if event.key in held_keys:
held_keys.remove(event.key)
if current_input and current_input["type"] == "key" and current_input["value"] == event.key:
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
logger.debug(f"Touche relâchée: {event.key}")
elif event.type == pygame.JOYBUTTONUP:
if event.button in held_buttons:
held_buttons.remove(event.button)
if current_input and current_input["type"] == "button" and current_input["value"] == event.button:
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
logger.debug(f"Bouton relâché: {event.button}")
elif event.type == pygame.MOUSEBUTTONUP:
if event.button in held_mouse_buttons:
held_mouse_buttons.remove(event.button)
if current_input and current_input["type"] == "mouse" and current_input["value"] == event.button:
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
logger.debug(f"Bouton souris relâché: {event.button}")
elif event.type == pygame.JOYAXISMOTION:
if abs(event.value) < 0.5: # Axe revenu à la position neutre
if event.axis in held_axes:
del held_axes[event.axis]
if current_input and current_input["type"] == "axis" and current_input["value"][0] == event.axis:
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
logger.debug(f"Axe relâché: {event.axis}")
elif event.type == pygame.JOYHATMOTION:
logger.debug(f"JOYHATMOTION détecté: hat={event.hat}, value={event.value}")
if event.value == (0, 0): # D-Pad revenu à la position neutre
if event.hat in held_hats:
del held_hats[event.hat]
if current_input and current_input["type"] == "hat" and current_input["value"] == event.value:
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
logger.debug(f"D-Pad relâché: {event.hat}")
continue # Ignorer les événements (0, 0) pour la détection des nouvelles entrées
# Détecter les nouvelles entrées
if event.type in (pygame.KEYDOWN, pygame.JOYBUTTONDOWN, pygame.JOYAXISMOTION, pygame.JOYHATMOTION, pygame.MOUSEBUTTONDOWN):
# Appliquer le débouncing pour JOYHATMOTION
if event.type == pygame.JOYHATMOTION and (current_time - last_joyhat_time) < JOYHAT_DEBOUNCE:
logger.debug(f"Événement JOYHATMOTION ignoré (debounce): hat={event.hat}, value={event.value}")
continue
if event.type == pygame.JOYHATMOTION:
last_joyhat_time = current_time
input_name = get_readable_input_name(event)
if input_name != "Inconnu":
input_type = {
pygame.KEYDOWN: "key",
pygame.JOYBUTTONDOWN: "button",
pygame.JOYAXISMOTION: "axis",
pygame.JOYHATMOTION: "hat",
pygame.MOUSEBUTTONDOWN: "mouse",
}[event.type]
input_value = (
SDL_TO_PYGAME_KEY.get(event.key, event.key) if event.type == pygame.KEYDOWN else
event.button if event.type == pygame.JOYBUTTONDOWN else
(event.axis, 1 if event.value > 0 else -1) if event.type == pygame.JOYAXISMOTION and abs(event.value) > 0.5 else
event.value if event.type == pygame.JOYHATMOTION else
event.button
)
# Vérifier si l'entrée est nouvelle ou différente
if (current_input is None or
(input_type == "key" and current_input["value"] != input_value) or
(input_type == "button" and current_input["value"] != input_value) or
(input_type == "axis" and current_input["value"] != input_value) or
(input_type == "hat" and current_input["value"] != input_value) or
(input_type == "mouse" and current_input["value"] != input_value)):
current_input = {"type": input_type, "value": input_value}
input_held_time = 0
last_input_name = input_name
config.needs_redraw = True
logger.debug(f"Nouvelle entrée détectée: {input_type}:{input_value} ({input_name})")
# Mettre à jour les entrées maintenues
if input_type == "key":
held_keys.add(input_value)
elif input_type == "button":
held_buttons.add(input_value)
elif input_type == "axis":
held_axes[input_value[0]] = input_value[1]
elif input_type == "hat":
held_hats[event.hat] = input_value
elif input_type == "mouse":
held_mouse_buttons.add(input_value)
# Désactivation du passage avec Échap
# Aucun code ici pour empêcher de sauter les actions avec Échap
# Mettre à jour le temps de maintien
if current_input:
input_held_time += delta_time
if input_held_time >= HOLD_DURATION:
action_name = ACTIONS[current_action_index]["name"]
logger.debug(f"Entrée validée pour {action_name}: {current_input['type']}:{current_input['value']} ({last_input_name})")
controls_config[action_name] = {
"type": current_input["type"],
"value": current_input["value"],
"display": last_input_name
}
current_action_index += 1
if event.type == pygame.QUIT:
return False
# Gestion des relâchements
if event.type == pygame.KEYUP and event.key in held_keys:
held_keys.remove(event.key)
if current_input and current_input["type"] == "key" and current_input["value"] == event.key:
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
elif event.type == pygame.JOYBUTTONUP and event.button in held_buttons:
held_buttons.remove(event.button)
if current_input and current_input["type"] == "button" and current_input["value"] == event.button:
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
elif event.type == pygame.JOYAXISMOTION and abs(event.value) < 0.5:
if event.axis in held_axes:
held_direction = held_axes[event.axis]
if current_input and current_input["type"] == "axis" and current_input["value"][0] == event.axis and current_input["value"][1] == held_direction:
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
# Réinitialiser les entrées maintenues pour éviter les interférences
held_keys.clear()
held_buttons.clear()
held_axes.clear()
held_hats.clear()
held_mouse_buttons.clear()
del held_axes[event.axis]
elif event.type == pygame.JOYHATMOTION and event.value == (0, 0):
if event.hat in held_hats:
del held_hats[event.hat]
if current_input and current_input["type"] == "hat":
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
continue
elif event.type == pygame.MOUSEBUTTONUP and event.button in held_mouse_buttons:
held_mouse_buttons.remove(event.button)
if current_input and current_input["type"] == "mouse" and current_input["value"] == event.button:
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
pygame.time.wait(10)
save_controls_config(controls_config)
config.controls_config = controls_config
return True
pass
def save_controls_config(config):
#Enregistre la configuration des contrôles dans un fichier JSON
try:
with open(CONTROLS_CONFIG_PATH, "w") as f:
json.dump(config, f, indent=4)
logger.debug("Configuration des contrôles enregistrée")
except Exception as e:
logger.error(f"Erreur lors de l'enregistrement de controls.json : {e}")
return False
# Détection des nouvelles entrées
if event.type in (pygame.KEYDOWN, pygame.JOYBUTTONDOWN, pygame.JOYAXISMOTION, pygame.JOYHATMOTION, pygame.MOUSEBUTTONDOWN):
if event.type == pygame.JOYHATMOTION:
if (current_time - last_joyhat_time) < JOYHAT_DEBOUNCE:
continue
last_joyhat_time = current_time
input_name = get_readable_input_name(event)
if input_name == "Inconnu":
continue
# Déterminer le type et la valeur
if event.type == pygame.KEYDOWN:
input_type = "key"
input_value = SDL_TO_PYGAME_KEY.get(event.key, event.key)
elif event.type == pygame.JOYBUTTONDOWN:
input_type = "button"
input_value = event.button
elif event.type == pygame.JOYAXISMOTION and abs(event.value) > 0.5:
input_type = "axis"
direction = 1 if event.value > 0 else -1
input_value = (event.axis, direction)
# Ignorer si c'est juste un changement de direction du même axe
if event.axis in held_axes and held_axes[event.axis] != direction:
continue
elif event.type == pygame.JOYHATMOTION:
input_type = "hat"
input_value = event.value
elif event.type == pygame.MOUSEBUTTONDOWN:
input_type = "mouse"
input_value = event.button
else:
continue
# Nouvelle entrée détectée
if (current_input is None or
current_input["type"] != input_type or
current_input["value"] != input_value):
current_input = {"type": input_type, "value": input_value}
input_held_time = 0
last_input_name = input_name
config.needs_redraw = True
# Mettre à jour les entrées maintenues
if input_type == "key":
held_keys.add(input_value)
elif input_type == "button":
held_buttons.add(input_value)
elif input_type == "axis":
held_axes[input_value[0]] = input_value[1]
elif input_type == "hat":
held_hats[event.hat] = input_value
elif input_type == "mouse":
held_mouse_buttons.add(input_value)
# Mise à jour du temps de maintien
if current_input:
input_held_time += delta_time
if input_held_time >= HOLD_DURATION:
action_name = ACTIONS[current_action_index]["name"]
# Sauvegarder avec la structure attendue par controls.py
if current_input["type"] == "key":
controls_config[action_name] = {
"type": "key",
"key": current_input["value"],
"display": last_input_name
}
elif current_input["type"] == "button":
controls_config[action_name] = {
"type": "button",
"button": current_input["value"],
"display": last_input_name
}
elif current_input["type"] == "axis":
axis, direction = current_input["value"]
controls_config[action_name] = {
"type": "axis",
"axis": axis,
"direction": direction,
"display": last_input_name
}
elif current_input["type"] == "hat":
controls_config[action_name] = {
"type": "hat",
"value": current_input["value"],
"display": last_input_name
}
elif current_input["type"] == "mouse":
controls_config[action_name] = {
"type": "mouse",
"button": current_input["value"],
"display": last_input_name
}
logger.debug(f"Contrôle mappé: {action_name} -> {controls_config[action_name]}")
current_action_index += 1
current_input = None
input_held_time = 0
last_input_name = None
config.needs_redraw = True
# Réinitialiser les entrées maintenues
held_keys.clear()
held_buttons.clear()
held_axes.clear()
held_hats.clear()
held_mouse_buttons.clear()
config.needs_redraw = True
pygame.time.wait(10)
save_controls_config(controls_config)
config.controls_config = controls_config
return True
def draw_controls_mapping(screen, action, last_input, waiting_for_input, hold_progress):
#Affiche l'interface de mappage des contrôles avec une barre de progression pour le maintien
draw_gradient(screen, (28, 37, 38), (47, 59, 61))