SDKs

Godot

valkyr_bridge.gd, uma bridge em GDScript puro que roda em um servidor headless do Godot 4 e conversa com o valkyr-server via HTTP.

bindings/godot/valkyr_bridge.gd é GDScript puro para um servidor dedicado do Godot 4 (um export headless). Ele conversa via HTTP com um valkyr-server rodando ao lado:

  • os eventos entram em uma fila e são enviados em lotes para POST /v1/matches/{match_id}/events;
  • as ações de punição são consultadas em GET /v1/actions e emitidas como o sinal action_received(player, action, reason);
  • end_match() encerra a partida.

Isso dispensa um build nativo por plataforma e mantém a detecção em um processo separado, que um servidor de jogo travando não consegue derrubar.

Não testado

O Godot não estava disponível onde a bridge foi escrita, então o script ainda não foi executado. Relatos e correções são bem-vindos.

Uso

  1. Rode o valkyr-server na mesma máquina com uma API key que tenha o papel ingest.
  2. Adicione o valkyr_bridge.gd a um nó da cena do servidor, ou como autoload, e defina server_url, api_key e match_id.
  3. Reporte os frames e reaja às ações:
server.gdGDScript
@onready var valkyr = $ValkyrBridge func _ready():    valkyr.action_received.connect(_on_valkyr_action) func _physics_process(_delta):    for p in players:  # your server side player nodes        valkyr.report_frame(p.peer_id, p.last_input_client_ms, p.global_position,            p.rotation.y, p.camera.rotation.x, p.is_on_floor(), p.jumped_this_tick) func _on_valkyr_action(player: int, action: String, reason: String):    if action == "kick":        multiplayer.multiplayer_peer.disconnect_peer(player)

Coordenadas

O Godot usa metros e Y para cima como o valkyr, mas um nó com rotation.y = 0 olha ao longo de -Z, enquanto o yaw 0 do valkyr olha ao longo de +Z. A bridge faz a conversão: o yaw do valkyr é rad_to_deg(rotation.y) + 180, ajustado para a faixa de -180 a 180, e o pitch é rad_to_deg(camera.rotation.x). As posições passam sem alteração.

A bridge

valkyr_bridge.gdGDScript
# valkyr_bridge.gd - Godot 4 bridge from a headless (dedicated) Godot# server to a local valkyr-server over HTTP.## Untested example (Godot was not available where this was written).## Add this script to a Node in the server scene (or register it as an# autoload), set server_url, api_key (a key with the "ingest" role) and# match_id, then call the report_* functions from your server side game# code. Events are sent in batches; enforcement actions (kick and above)# are polled from /v1/actions and emitted as the action_received signal.## Coordinates: Godot is meters and Y up like valkyr, but a Godot node looks# along -Z with rotation.y = 0, while valkyr yaw 0 looks along +Z and 90# along +X. So valkyr yaw = rad_to_deg(rotation.y) + 180 (wrapped) and# valkyr pitch = rad_to_deg(camera rotation.x) (both positive up).extends Node signal action_received(player: int, action: String, reason: String) @export var server_url := "http://127.0.0.1:7420"@export var api_key := ""@export var match_id := "match-1"@export var batch_interval_sec := 0.25@export var poll_interval_sec := 1.0@export var max_batch := 2000 var _queue: Array = []var _sending := falsevar _polling := falsevar _cursor := 0var _send_timer := 0.0var _poll_timer := 0.0var _seq := {}var _events_http: HTTPRequestvar _actions_http: HTTPRequest  func _ready() -> void:	_events_http = HTTPRequest.new()	_actions_http = HTTPRequest.new()	add_child(_events_http)	add_child(_actions_http)	_events_http.request_completed.connect(_on_events_done)	_actions_http.request_completed.connect(_on_actions_done)  func _process(delta: float) -> void:	_send_timer += delta	_poll_timer += delta	if _send_timer >= batch_interval_sec:		_send_timer = 0.0		_flush()	if _poll_timer >= poll_interval_sec:		_poll_timer = 0.0		_poll()  static func now_ms() -> int:	return Time.get_ticks_msec()  static func valkyr_yaw(godot_rotation_y: float) -> float:	return wrapf(rad_to_deg(godot_rotation_y) + 180.0, -180.0, 180.0)  static func valkyr_pitch(godot_camera_rotation_x: float) -> float:	return rad_to_deg(godot_camera_rotation_x)  static func _vec(v: Vector3) -> Dictionary:	return {"x": v.x, "y": v.y, "z": v.z}  ## Per tick state of a player as the server sees it.## client_time_ms: the timestamp the client sent with its input.func report_frame(player: int, client_time_ms: int, feet: Vector3, body_rotation_y: float,		camera_rotation_x: float, on_ground: bool, jump: bool) -> void:	var seq: int = _seq.get(player, 0) + 1	_seq[player] = seq	_queue.append({		"type": "frame", "player": player, "seq": seq,		"client_time_ms": client_time_ms, "server_time_ms": now_ms(),		"position": _vec(feet), "yaw": valkyr_yaw(body_rotation_y),		"pitch": valkyr_pitch(camera_rotation_x),		"on_ground": on_ground, "jump": jump,	})  ## A shot the server accepted. target is -1 when nothing was hit; bone is## "head", "body", "limb" or "".func report_shot(player: int, client_time_ms: int, weapon: int, body_rotation_y: float,		camera_rotation_x: float, target: int = -1, bone: String = "", latency_ms: int = 0) -> void:	var ev := {		"type": "shot", "player": player, "client_time_ms": client_time_ms,		"server_time_ms": now_ms(), "weapon": weapon,		"yaw": valkyr_yaw(body_rotation_y), "pitch": valkyr_pitch(camera_rotation_x),		"latency_ms": latency_ms,	}	if target >= 0:		ev["target"] = target	if bone != "":		ev["bone"] = bone	_queue.append(ev)  ## Spawn or server authorized teleport (resets movement history).func report_spawn(player: int, feet: Vector3, team: int) -> void:	_queue.append({		"type": "spawn", "player": player, "server_time_ms": now_ms(),		"position": _vec(feet), "team": team,	})  func _headers() -> PackedStringArray:	return PackedStringArray([		"Content-Type: application/json",		"Authorization: Bearer %s" % api_key,	])  func _flush() -> void:	if _sending or _queue.is_empty():		return	var n := mini(_queue.size(), max_batch)	var batch := _queue.slice(0, n)	_queue = _queue.slice(n)	var url := "%s/v1/matches/%s/events" % [server_url, match_id.uri_encode()]	var body := JSON.stringify({"events": batch})	if _events_http.request(url, _headers(), HTTPClient.METHOD_POST, body) == OK:		_sending = true	else:		push_warning("valkyr: could not send %d events" % n)  func _on_events_done(result: int, code: int, _headers_in: PackedStringArray, body: PackedByteArray) -> void:	_sending = false	if result != HTTPRequest.RESULT_SUCCESS or code != 200:		push_warning("valkyr: events rejected (%d, %d): %s" % [result, code, body.get_string_from_utf8()])  func _poll() -> void:	if _polling:		return	var url := "%s/v1/actions?since=%d&limit=100" % [server_url, _cursor]	if _actions_http.request(url, _headers(), HTTPClient.METHOD_GET) == OK:		_polling = true  func _on_actions_done(result: int, code: int, _headers_in: PackedStringArray, body: PackedByteArray) -> void:	_polling = false	if result != HTTPRequest.RESULT_SUCCESS or code != 200:		return	var data = JSON.parse_string(body.get_string_from_utf8())	if typeof(data) != TYPE_DICTIONARY:		return	for a in data.get("actions", []):		# The queue is shared by every match on the valkyr server.		if str(a.get("match_id", match_id)) != match_id:			continue		action_received.emit(int(a.get("player", 0)), str(a.get("action", "")), str(a.get("reason", "")))	_cursor = int(data.get("cursor", _cursor))  ## Ends the match on the server. Call it after the last report and once the## queue is empty (the end request is not ordered with a batch in flight).func end_match() -> void:	var http := HTTPRequest.new()	add_child(http)	http.request_completed.connect(func(_r, _c, _h, _b): http.queue_free())	http.request("%s/v1/matches/%s/end" % [server_url, match_id.uri_encode()], _headers(),		HTTPClient.METHOD_POST, "{}")

Editar esta página no GitHub