CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,296 @@
|
||||
extends Node3D
|
||||
## Inicialização e orquestração da cena.
|
||||
##
|
||||
## Argumentos da aplicação (depois de `--` na linha de comando da Godot):
|
||||
## --config <arquivo.json> cena a montar (padrão: config/demo-street.json)
|
||||
## --validate-only só valida a configuração e sai (0 = ok, 2 = inválida)
|
||||
## --manifest <arquivo.json> no render, grava o resumo dos quadros produzidos
|
||||
## --debug-frame-index desenha índice do quadro e tempo de cena
|
||||
## --warmup-frames <n> no render, quadros descartáveis em t=0 antes da
|
||||
## cena (padrão 3). Na Godot 4.7.2 o 1º quadro sai
|
||||
## com sombras e luz do céu incompletas; o lançador
|
||||
## passa a codificar a partir do índice n.
|
||||
## Caminhos relativos são resolvidos a partir da RAIZ DO REPOSITÓRIO (a pasta
|
||||
## que contém godot/), nunca do diretório de execução.
|
||||
##
|
||||
## Modos:
|
||||
## render (Movie Maker ativo): t = quadro / fps. O delta do motor é ignorado
|
||||
## porque não é exatamente 1/fps nem com --fixed-fps.
|
||||
## preview (janela normal): o tempo de cena avança com o delta; Espaço pausa,
|
||||
## R reinicia, ←/→ andam um quadro pausado, L liga/desliga repetição.
|
||||
|
||||
const SceneConfig := preload("res://scripts/core/scene_config.gd")
|
||||
const StreetBuilder := preload("res://scripts/builders/street_builder.gd")
|
||||
const RiderBuilder := preload("res://scripts/builders/rider_builder.gd")
|
||||
const Timeline := preload("res://scripts/core/timeline_controller.gd")
|
||||
const CameraController := preload("res://scripts/view/camera_controller.gd")
|
||||
const OverlayController := preload("res://scripts/view/overlay_controller.gd")
|
||||
|
||||
const DEFAULT_CONFIG := "config/demo-street.json"
|
||||
const EXIT_INVALID_CONFIG := 2
|
||||
const EXIT_ENVIRONMENT := 3
|
||||
const EXIT_MANIFEST := 4
|
||||
const DEFAULT_WARMUP_FRAMES := 3
|
||||
const MAX_WARMUP_FRAMES := 30
|
||||
|
||||
var _cfg: Dictionary
|
||||
var _timeline: Timeline
|
||||
var _rider: Dictionary
|
||||
var _camera: Camera3D
|
||||
var _overlay: OverlayController
|
||||
var _render_mode := false
|
||||
var _frame := 0
|
||||
var _warmup_frames := DEFAULT_WARMUP_FRAMES
|
||||
var _warmup_done := 0
|
||||
var _total_frames := 0
|
||||
var _fps := 30
|
||||
var _preview_time := 0.0
|
||||
var _paused := false
|
||||
var _loop := false
|
||||
var _show_debug := false
|
||||
var _manifest_path := ""
|
||||
var _config_path := ""
|
||||
var _scene_stats := {}
|
||||
var _state_lines := PackedStringArray()
|
||||
var _started_msec := 0
|
||||
var _halted := false
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
_started_msec = Time.get_ticks_msec()
|
||||
var args := _parse_user_args(OS.get_cmdline_user_args())
|
||||
_config_path = _resolve_path(args.get("config", DEFAULT_CONFIG))
|
||||
_render_mode = Engine.get_write_movie_path() != ""
|
||||
_show_debug = args.has("debug-frame-index")
|
||||
_manifest_path = _resolve_path(args.manifest) if args.has("manifest") else ""
|
||||
if args.has("warmup-frames"):
|
||||
var value := str(args["warmup-frames"])
|
||||
if not value.is_valid_int() or int(value) < 0 or int(value) > MAX_WARMUP_FRAMES:
|
||||
printerr("ARGS_INVALID --warmup-frames precisa ser inteiro entre 0 e %d" % MAX_WARMUP_FRAMES)
|
||||
_halt(EXIT_INVALID_CONFIG)
|
||||
return
|
||||
_warmup_frames = int(value)
|
||||
|
||||
var result := SceneConfig.load_file(_config_path)
|
||||
if not result.ok:
|
||||
printerr("CONFIG_INVALID %s" % _config_path)
|
||||
for e in result.errors:
|
||||
printerr(" - " + e)
|
||||
_halt(EXIT_INVALID_CONFIG)
|
||||
return
|
||||
_cfg = result.config
|
||||
if args.has("validate-only"):
|
||||
print("CONFIG_OK %s (%s, %d quadros)" % [_cfg.id, _config_path, _cfg.video.total_frames])
|
||||
_halt(0)
|
||||
return
|
||||
|
||||
_fps = _cfg.video.fps
|
||||
_total_frames = _cfg.video.total_frames
|
||||
var viewport_size := get_viewport().get_visible_rect().size
|
||||
if _render_mode:
|
||||
# Caminho relativo em --write-movie é resolvido a partir de godot/, e
|
||||
# a Godot 4.7.2 sai com código 0 mesmo sem conseguir gravar os PNGs.
|
||||
var movie_dir := Engine.get_write_movie_path().get_base_dir()
|
||||
if movie_dir.is_relative_path():
|
||||
movie_dir = ProjectSettings.globalize_path("res://").path_join(movie_dir)
|
||||
if not DirAccess.dir_exists_absolute(movie_dir):
|
||||
printerr("RENDER_ENVIRONMENT pasta de saída do Movie Maker não existe: %s (use caminho absoluto e crie a pasta antes)" % movie_dir)
|
||||
_halt(EXIT_ENVIRONMENT)
|
||||
return
|
||||
var expected := Vector2(_cfg.video.width, _cfg.video.height)
|
||||
if viewport_size != expected:
|
||||
printerr("RENDER_ENVIRONMENT viewport %s difere da configuração %s. O Movie Maker fixa o tamanho na inicialização: use o lançador (gera override.cfg) ou ajuste display/window/size no projeto." % [viewport_size, expected])
|
||||
_halt(EXIT_ENVIRONMENT)
|
||||
return
|
||||
|
||||
_build_scene(viewport_size)
|
||||
_apply(0.0)
|
||||
print("SCENE_READY id=%s mode=%s frames=%d fps=%d viewport=%dx%d renderer=%s" % [
|
||||
_cfg.id, "render" if _render_mode else "preview", _total_frames, _fps,
|
||||
int(viewport_size.x), int(viewport_size.y), RenderingServer.get_current_rendering_method()])
|
||||
|
||||
|
||||
func _build_scene(viewport_size: Vector2) -> void:
|
||||
var world := Node3D.new()
|
||||
world.name = "World"
|
||||
add_child(world)
|
||||
_scene_stats = StreetBuilder.build(world, _cfg, ProjectSettings.globalize_path("res://assets/backgrounds"))
|
||||
|
||||
_rider = RiderBuilder.build(_cfg)
|
||||
add_child(_rider.root)
|
||||
|
||||
_camera = Camera3D.new()
|
||||
_camera.name = "Camera"
|
||||
_camera.near = 0.05
|
||||
_camera.far = 600.0
|
||||
_camera.keep_aspect = Camera3D.KEEP_HEIGHT
|
||||
add_child(_camera)
|
||||
_camera.current = true
|
||||
|
||||
_overlay = OverlayController.new()
|
||||
_overlay.name = "Overlay"
|
||||
add_child(_overlay)
|
||||
_overlay.setup(_cfg, viewport_size, _show_debug or not _render_mode)
|
||||
|
||||
_timeline = Timeline.new(_cfg, _rider.wheel_radius)
|
||||
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if _cfg.is_empty() or _halted:
|
||||
return
|
||||
if _render_mode:
|
||||
_process_render()
|
||||
else:
|
||||
_process_preview(delta)
|
||||
|
||||
|
||||
## Um quadro por iteração. Primeiro vêm os quadros de aquecimento (estado de
|
||||
## t=0, descartados na conversão); depois o quadro N da cena mostra o estado em
|
||||
## t = N / fps. A iteração em que chamamos quit() ainda é desenhada e gravada,
|
||||
## então o total de PNGs é exatamente warmup + total_frames (confirmado com a
|
||||
## Godot 4.7.2).
|
||||
func _process_render() -> void:
|
||||
if _warmup_done < _warmup_frames:
|
||||
_apply(0.0)
|
||||
_warmup_done += 1
|
||||
return
|
||||
var t := float(_frame) / float(_fps)
|
||||
var state := _apply(t)
|
||||
_state_lines.append(_state_line(state))
|
||||
_frame += 1
|
||||
if _frame >= _total_frames:
|
||||
_finish_render(state)
|
||||
|
||||
|
||||
func _process_preview(delta: float) -> void:
|
||||
if not _paused:
|
||||
_preview_time += delta
|
||||
var duration: float = _cfg.video.duration
|
||||
if _preview_time > duration:
|
||||
_preview_time = 0.0 if _loop else duration
|
||||
_apply(_preview_time)
|
||||
|
||||
|
||||
func _apply(t: float) -> Dictionary:
|
||||
var state := _timeline.evaluate_at_time(t)
|
||||
var root: Node3D = _rider.root
|
||||
root.position = state.rider_position
|
||||
var body: Node3D = _rider.body
|
||||
body.position = Vector3(0, state.body_bob, 0)
|
||||
body.rotation = Vector3(state.body_pitch, 0, 0)
|
||||
_rider.front_wheel.rotation = Vector3(state.wheel_angle, 0, 0)
|
||||
_rider.rear_wheel.rotation = Vector3(state.wheel_angle, 0, 0)
|
||||
CameraController.apply(_camera, state.camera)
|
||||
var debug_text := ""
|
||||
if _show_debug or not _render_mode:
|
||||
debug_text = "q=%03d t=%.3fs d=%.2fm v=%.2fm/s" % [int(round(t * _fps)), t, state.distance, state.speed]
|
||||
if not _render_mode:
|
||||
debug_text += "\n[Espaço] pausa [R] reinicia [←/→] quadro [L] repetir=%s" % ("sim" if _loop else "não")
|
||||
_overlay.apply(state.overlay, debug_text)
|
||||
return state
|
||||
|
||||
|
||||
func _unhandled_input(event: InputEvent) -> void:
|
||||
if _render_mode or _cfg.is_empty() or not (event is InputEventKey) or not event.pressed:
|
||||
return
|
||||
var step := 1.0 / float(_fps)
|
||||
match event.keycode:
|
||||
KEY_SPACE:
|
||||
_paused = not _paused
|
||||
KEY_R:
|
||||
_preview_time = 0.0
|
||||
KEY_L:
|
||||
_loop = not _loop
|
||||
KEY_RIGHT:
|
||||
_paused = true
|
||||
_preview_time = minf(_preview_time + step, _cfg.video.duration)
|
||||
KEY_LEFT:
|
||||
_paused = true
|
||||
_preview_time = maxf(_preview_time - step, 0.0)
|
||||
KEY_ESCAPE:
|
||||
get_tree().quit(0)
|
||||
|
||||
|
||||
func _state_line(state: Dictionary) -> String:
|
||||
var p: Vector3 = state.rider_position
|
||||
var c: Vector3 = state.camera.position
|
||||
return "%.4f|%.5f,%.5f,%.5f|%.5f|%.5f,%.5f,%.5f|%.3f" % [state.t, p.x, p.y, p.z, state.wheel_angle, c.x, c.y, c.z, state.overlay.title]
|
||||
|
||||
|
||||
func _finish_render(last_state: Dictionary) -> void:
|
||||
var final_position: Vector3 = last_state.rider_position
|
||||
var manifest := {
|
||||
"configId": _cfg.id,
|
||||
"configPath": _config_path,
|
||||
"fps": _fps,
|
||||
"durationSeconds": _cfg.video.duration,
|
||||
"framesRendered": _frame,
|
||||
"expectedFrames": _total_frames,
|
||||
"warmupFrames": _warmup_frames,
|
||||
"firstSceneFrameIndex": _warmup_frames,
|
||||
"pngFramesWritten": _warmup_frames + _frame,
|
||||
"firstFrameTime": 0.0,
|
||||
"lastFrameTime": float(_frame - 1) / float(_fps),
|
||||
"viewport": [int(get_viewport().get_visible_rect().size.x), int(get_viewport().get_visible_rect().size.y)],
|
||||
"renderer": {
|
||||
"method": RenderingServer.get_current_rendering_method(),
|
||||
"driver": RenderingServer.get_current_rendering_driver_name(),
|
||||
"adapter": RenderingServer.get_video_adapter_name(),
|
||||
"vendor": RenderingServer.get_video_adapter_vendor(),
|
||||
},
|
||||
"godotVersion": Engine.get_version_info().string,
|
||||
"finalDistanceMeters": last_state.distance,
|
||||
"travelMeters": _cfg.rider.travel,
|
||||
"finalPosition": [final_position.x, final_position.y, final_position.z],
|
||||
"cruiseSpeedMetersPerSecond": _timeline.cruise_speed(),
|
||||
"scene": _scene_stats,
|
||||
# Resumo do estado de todos os quadros: duas execuções da mesma
|
||||
# configuração precisam gerar o mesmo valor.
|
||||
"stateDigest": "\n".join(_state_lines).md5_text(),
|
||||
"wallClockSeconds": (Time.get_ticks_msec() - _started_msec) / 1000.0,
|
||||
}
|
||||
if _manifest_path != "":
|
||||
DirAccess.make_dir_recursive_absolute(_manifest_path.get_base_dir())
|
||||
var file := FileAccess.open(_manifest_path, FileAccess.WRITE)
|
||||
if file == null:
|
||||
printerr("MANIFEST_WRITE_FAILED %s (erro %d)" % [_manifest_path, FileAccess.get_open_error()])
|
||||
get_tree().quit(EXIT_MANIFEST)
|
||||
return
|
||||
file.store_string(JSON.stringify(manifest, " "))
|
||||
file.close()
|
||||
print("RENDER_DONE frames=%d warmup=%d fps=%d digest=%s" % [_frame, _warmup_frames, _fps, manifest.stateDigest])
|
||||
get_tree().quit(0)
|
||||
|
||||
|
||||
func _halt(code: int) -> void:
|
||||
_halted = true
|
||||
get_tree().quit(code)
|
||||
|
||||
|
||||
func _parse_user_args(raw: PackedStringArray) -> Dictionary:
|
||||
var out := {}
|
||||
var i := 0
|
||||
while i < raw.size():
|
||||
var arg := raw[i]
|
||||
if arg.begins_with("--"):
|
||||
var key := arg.substr(2)
|
||||
if key.contains("="):
|
||||
out[key.get_slice("=", 0)] = key.substr(key.find("=") + 1)
|
||||
elif i + 1 < raw.size() and not raw[i + 1].begins_with("--"):
|
||||
out[key] = raw[i + 1]
|
||||
i += 1
|
||||
else:
|
||||
out[key] = true
|
||||
i += 1
|
||||
return out
|
||||
|
||||
|
||||
static func repo_root() -> String:
|
||||
return ProjectSettings.globalize_path("res://").trim_suffix("/").get_base_dir()
|
||||
|
||||
|
||||
static func _resolve_path(path: String) -> String:
|
||||
var p := path.replace("\\", "/")
|
||||
if p.is_absolute_path():
|
||||
return p.simplify_path()
|
||||
return repo_root().path_join(p).simplify_path()
|
||||
@@ -0,0 +1 @@
|
||||
uid://cqmgnobpvhi0w
|
||||
@@ -0,0 +1,334 @@
|
||||
extends RefCounted
|
||||
## Leitura e validação do contrato de cena (schemaVersion 1).
|
||||
##
|
||||
## O JSON só descreve dados: números, textos curtos, cores e valores de listas
|
||||
## fechadas. Nenhum campo é interpretado como código ou comando. Campos
|
||||
## desconhecidos são rejeitados para o contrato não crescer por acidente.
|
||||
##
|
||||
## Saída: { "ok": bool, "errors": PackedStringArray, "config": Dictionary }
|
||||
## O dicionário "config" usa nomes internos em snake_case com tipos Godot
|
||||
## (Vector3, Color). Os nomes em camelCase pertencem ao contrato do JSON.
|
||||
|
||||
const SUPPORTED_SCHEMA_VERSION := 1
|
||||
const LIGHTING_PRESETS := ["warm_day", "golden_hour"]
|
||||
const BACKGROUND_MODES := ["cards", "none"]
|
||||
const CAMERA_PRESETS := ["third_person_follow"]
|
||||
const RIDER_ASSETS := ["placeholder-rider"]
|
||||
|
||||
## Velocidade de cruzeiro máxima aceita (m/s). Acima disso o plano deixa de ser
|
||||
## uma rua de bairro e a câmera não acompanha de forma legível.
|
||||
const MAX_CRUISE_SPEED := 20.0
|
||||
## A moto precisa parar a esta distância do fim da rua, para o fim do cenário
|
||||
## não aparecer em primeiro plano.
|
||||
const STREET_END_MARGIN := 15.0
|
||||
const MIN_CAMERA_HEIGHT := 0.5
|
||||
const DEFAULT_BOX_COLOR := "#1F8A70"
|
||||
|
||||
|
||||
static func load_file(path: String) -> Dictionary:
|
||||
if not FileAccess.file_exists(path):
|
||||
return _failure(["arquivo de configuração não encontrado: %s" % path])
|
||||
var text := FileAccess.get_file_as_string(path)
|
||||
if text.is_empty():
|
||||
var open_error := FileAccess.get_open_error()
|
||||
if open_error != OK:
|
||||
return _failure(["não foi possível ler %s (erro %d)" % [path, open_error]])
|
||||
return _failure(["arquivo de configuração vazio: %s" % path])
|
||||
return parse_text(text)
|
||||
|
||||
|
||||
static func parse_text(text: String) -> Dictionary:
|
||||
var json := JSON.new()
|
||||
var parse_error := json.parse(text)
|
||||
if parse_error != OK:
|
||||
return _failure(["JSON inválido na linha %d: %s" % [json.get_error_line(), json.get_error_message()]])
|
||||
if typeof(json.data) != TYPE_DICTIONARY:
|
||||
return _failure(["a raiz do JSON precisa ser um objeto"])
|
||||
return validate(json.data)
|
||||
|
||||
|
||||
static func validate(raw: Dictionary) -> Dictionary:
|
||||
var v := Validator.new()
|
||||
|
||||
v.check_keys(raw, ["schemaVersion", "id", "seed", "video", "world", "rider", "motion", "camera", "overlay", "audio"], "")
|
||||
var version = raw.get("schemaVersion")
|
||||
if not _is_number(version) or float(version) != SUPPORTED_SCHEMA_VERSION:
|
||||
# Sem versão conhecida não há como interpretar o resto com segurança.
|
||||
return _failure(["schemaVersion %s não suportada (esperado %d)" % [str(version), SUPPORTED_SCHEMA_VERSION]])
|
||||
|
||||
var cfg := {"schema_version": SUPPORTED_SCHEMA_VERSION}
|
||||
cfg.id = v.text(raw, "id", "id", 1, 64)
|
||||
if cfg.id != "" and not RegEx.create_from_string("^[a-z0-9][a-z0-9_-]*$").search(cfg.id):
|
||||
v.fail("id", "use apenas letras minúsculas, números, '-' e '_' (ex.: demo-street)")
|
||||
cfg.seed = v.integer(raw, "seed", "seed", 0, 2147483647)
|
||||
|
||||
# --- video ---
|
||||
var video := v.object(raw, "video", "video", ["width", "height", "fps", "durationSeconds"])
|
||||
cfg.video = {
|
||||
"width": v.integer(video, "width", "video.width", 128, 4096),
|
||||
"height": v.integer(video, "height", "video.height", 128, 4096),
|
||||
"fps": v.integer(video, "fps", "video.fps", 1, 120),
|
||||
"duration": v.number(video, "durationSeconds", "video.durationSeconds", 0.5, 120.0),
|
||||
}
|
||||
for key in ["width", "height"]:
|
||||
if cfg.video[key] % 2 != 0:
|
||||
v.fail("video." + key, "precisa ser par (H.264 com yuv420p exige dimensões pares)")
|
||||
var frames_exact: float = cfg.video.fps * cfg.video.duration
|
||||
cfg.video.total_frames = int(round(frames_exact))
|
||||
if v.ok() and absf(frames_exact - cfg.video.total_frames) > 1e-6:
|
||||
v.fail("video.durationSeconds", "fps × duração precisa dar um número inteiro de quadros (deu %.4f)" % frames_exact)
|
||||
|
||||
# --- world ---
|
||||
var world := v.object(raw, "world", "world", ["streetLengthMeters", "roadWidthMeters", "nearHousesPerSide", "backgroundMode", "lightingPreset"])
|
||||
cfg.world = {
|
||||
"street_length": v.number(world, "streetLengthMeters", "world.streetLengthMeters", 40.0, 1000.0),
|
||||
"road_width": v.number(world, "roadWidthMeters", "world.roadWidthMeters", 4.0, 20.0),
|
||||
"near_houses_per_side": v.integer(world, "nearHousesPerSide", "world.nearHousesPerSide", 0, 40),
|
||||
"background_mode": v.choice(world, "backgroundMode", "world.backgroundMode", BACKGROUND_MODES),
|
||||
"lighting_preset": v.choice(world, "lightingPreset", "world.lightingPreset", LIGHTING_PRESETS),
|
||||
}
|
||||
|
||||
# --- rider ---
|
||||
var rider := v.object(raw, "rider", "rider", ["assetId", "bikeColor", "boxColor", "startPosition", "travelMeters"])
|
||||
cfg.rider = {
|
||||
"asset_id": v.choice(rider, "assetId", "rider.assetId", RIDER_ASSETS),
|
||||
"bike_color": v.color(rider, "bikeColor", "rider.bikeColor"),
|
||||
"box_color": v.color(rider, "boxColor", "rider.boxColor", DEFAULT_BOX_COLOR),
|
||||
"start_position": v.vec3(rider, "startPosition", "rider.startPosition", 1000.0),
|
||||
"travel": v.number(rider, "travelMeters", "rider.travelMeters", 1.0, 900.0),
|
||||
}
|
||||
|
||||
# --- motion ---
|
||||
var motion := v.object(raw, "motion", "motion", ["startSeconds", "accelSeconds", "brakeStartSeconds", "stopSeconds"])
|
||||
cfg.motion = {
|
||||
"start": v.number(motion, "startSeconds", "motion.startSeconds", 0.0, 120.0),
|
||||
"brake_start": v.number(motion, "brakeStartSeconds", "motion.brakeStartSeconds", 0.0, 120.0),
|
||||
"stop": v.number(motion, "stopSeconds", "motion.stopSeconds", 0.0, 120.0),
|
||||
"accel_seconds": v.number(motion, "accelSeconds", "motion.accelSeconds", 0.05, 60.0, -1.0),
|
||||
}
|
||||
|
||||
# --- camera ---
|
||||
var camera := v.object(raw, "camera", "camera", ["preset", "offset", "lookAtOffset", "fovDegrees", "endOffset", "endLookAtOffset", "transitionStartSeconds", "transitionEndSeconds"])
|
||||
cfg.camera = {
|
||||
"preset": v.choice(camera, "preset", "camera.preset", CAMERA_PRESETS),
|
||||
"offset": v.vec3(camera, "offset", "camera.offset", 60.0),
|
||||
"look_at_offset": v.vec3(camera, "lookAtOffset", "camera.lookAtOffset", 60.0),
|
||||
"fov": v.number(camera, "fovDegrees", "camera.fovDegrees", 20.0, 100.0),
|
||||
}
|
||||
cfg.camera.end_offset = v.vec3(camera, "endOffset", "camera.endOffset", 60.0, cfg.camera.offset)
|
||||
cfg.camera.end_look_at_offset = v.vec3(camera, "endLookAtOffset", "camera.endLookAtOffset", 60.0, cfg.camera.look_at_offset)
|
||||
cfg.camera.transition_start = v.number(camera, "transitionStartSeconds", "camera.transitionStartSeconds", 0.0, 120.0, -1.0)
|
||||
cfg.camera.transition_end = v.number(camera, "transitionEndSeconds", "camera.transitionEndSeconds", 0.0, 120.0, -1.0)
|
||||
|
||||
# --- overlay ---
|
||||
var overlay := v.object(raw, "overlay", "overlay", ["startSeconds", "fadeSeconds", "title", "choiceA", "choiceB"])
|
||||
cfg.overlay = {
|
||||
"start": v.number(overlay, "startSeconds", "overlay.startSeconds", 0.0, 120.0),
|
||||
"fade_seconds": v.number(overlay, "fadeSeconds", "overlay.fadeSeconds", 0.0, 2.0, 0.4),
|
||||
"title": v.text(overlay, "title", "overlay.title", 1, 80),
|
||||
"choice_a": v.text(overlay, "choiceA", "overlay.choiceA", 1, 48),
|
||||
"choice_b": v.text(overlay, "choiceB", "overlay.choiceB", 1, 48),
|
||||
}
|
||||
|
||||
# --- audio ---
|
||||
var audio := v.object(raw, "audio", "audio", ["enabled", "file", "offsetSeconds"])
|
||||
cfg.audio = {
|
||||
"enabled": v.boolean(audio, "enabled", "audio.enabled"),
|
||||
"file": v.optional_text(audio, "file", "audio.file", 260),
|
||||
"offset": v.number(audio, "offsetSeconds", "audio.offsetSeconds", 0.0, 120.0, 0.0),
|
||||
}
|
||||
|
||||
if v.ok():
|
||||
_check_relations(cfg, v)
|
||||
return {"ok": v.ok(), "errors": v.errors, "config": cfg if v.ok() else {}}
|
||||
|
||||
|
||||
## Regras que envolvem mais de um campo. Só roda se os campos isolados passaram.
|
||||
static func _check_relations(cfg: Dictionary, v: Validator) -> void:
|
||||
var duration: float = cfg.video.duration
|
||||
var m: Dictionary = cfg.motion
|
||||
if not (m.start < m.brake_start and m.brake_start < m.stop and m.stop <= duration):
|
||||
v.fail("motion", "exige startSeconds < brakeStartSeconds < stopSeconds <= durationSeconds (recebido %s < %s < %s <= %s)" % [m.start, m.brake_start, m.stop, duration])
|
||||
return
|
||||
var free_run: float = m.brake_start - m.start
|
||||
if m.accel_seconds < 0.0:
|
||||
m.accel_seconds = minf(1.5, free_run * 0.5)
|
||||
elif m.accel_seconds > free_run:
|
||||
v.fail("motion.accelSeconds", "precisa caber entre startSeconds e brakeStartSeconds (máx. %.2f s)" % free_run)
|
||||
return
|
||||
|
||||
var w: Dictionary = cfg.world
|
||||
var r: Dictionary = cfg.rider
|
||||
if absf(r.start_position.x) > w.road_width * 0.5 - 0.5:
|
||||
v.fail("rider.startPosition", "x precisa ficar dentro da pista (|x| <= %.1f)" % (w.road_width * 0.5 - 0.5))
|
||||
if r.start_position.y < -0.5 or r.start_position.y > 5.0:
|
||||
v.fail("rider.startPosition", "y precisa estar entre -0.5 e 5")
|
||||
if r.start_position.z > 20.0:
|
||||
v.fail("rider.startPosition", "z precisa ser <= 20 (a rua começa logo atrás da câmera)")
|
||||
var end_z: float = r.start_position.z - r.travel
|
||||
if end_z < -w.street_length + STREET_END_MARGIN:
|
||||
v.fail("rider.travelMeters", "a moto pararia a menos de %d m do fim da rua (fim em z=%.1f, parada em z=%.1f); aumente streetLengthMeters ou reduza o percurso" % [int(STREET_END_MARGIN), -w.street_length, end_z])
|
||||
|
||||
var speed := cruise_speed(m, r.travel)
|
||||
if speed > MAX_CRUISE_SPEED:
|
||||
v.fail("rider.travelMeters", "percurso exige %.1f m/s de cruzeiro (máx. %.0f m/s); aumente o tempo de movimento ou reduza a distância" % [speed, MAX_CRUISE_SPEED])
|
||||
|
||||
var c: Dictionary = cfg.camera
|
||||
for key in ["offset", "end_offset"]:
|
||||
var off: Vector3 = c[key]
|
||||
if r.start_position.y + off.y < MIN_CAMERA_HEIGHT:
|
||||
v.fail("camera." + ("offset" if key == "offset" else "endOffset"), "câmera ficaria abaixo de %.1f m de altura" % MIN_CAMERA_HEIGHT)
|
||||
if off.length() < 1.5:
|
||||
v.fail("camera." + ("offset" if key == "offset" else "endOffset"), "câmera colada no personagem (distância < 1,5 m)")
|
||||
if c.transition_start < 0.0:
|
||||
c.transition_start = m.brake_start
|
||||
if c.transition_end < 0.0:
|
||||
c.transition_end = minf(duration, cfg.overlay.start + 0.6)
|
||||
if not (c.transition_start < c.transition_end and c.transition_end <= duration):
|
||||
v.fail("camera", "exige transitionStartSeconds < transitionEndSeconds <= durationSeconds")
|
||||
|
||||
if cfg.overlay.start >= duration:
|
||||
v.fail("overlay.startSeconds", "precisa ser menor que durationSeconds")
|
||||
|
||||
var a: Dictionary = cfg.audio
|
||||
if a.enabled and typeof(a.file) == TYPE_NIL:
|
||||
v.fail("audio.file", "obrigatório quando audio.enabled = true")
|
||||
if a.offset >= duration:
|
||||
v.fail("audio.offsetSeconds", "precisa ser menor que durationSeconds")
|
||||
|
||||
|
||||
## Velocidade de cruzeiro que faz o perfil (rampa suave, cruzeiro, frenagem
|
||||
## suave) cobrir exatamente `travel` metros. Cada rampa suave anda metade do que
|
||||
## andaria em velocidade plena no mesmo tempo.
|
||||
static func cruise_speed(motion: Dictionary, travel: float) -> float:
|
||||
var accel: float = motion.accel_seconds
|
||||
var cruise: float = motion.brake_start - motion.start - accel
|
||||
var brake: float = motion.stop - motion.brake_start
|
||||
return travel / (accel * 0.5 + cruise + brake * 0.5)
|
||||
|
||||
|
||||
static func _failure(errors: Array) -> Dictionary:
|
||||
return {"ok": false, "errors": PackedStringArray(errors), "config": {}}
|
||||
|
||||
|
||||
static func _is_number(value) -> bool:
|
||||
return (typeof(value) == TYPE_FLOAT or typeof(value) == TYPE_INT) and is_finite(float(value))
|
||||
|
||||
|
||||
## Acumula erros com o caminho do campo, para a mensagem final apontar o lugar exato.
|
||||
class Validator:
|
||||
var errors := PackedStringArray()
|
||||
|
||||
func ok() -> bool:
|
||||
return errors.is_empty()
|
||||
|
||||
func fail(path: String, message: String) -> void:
|
||||
errors.append("%s: %s" % [path, message] if path != "" else message)
|
||||
|
||||
func check_keys(obj: Dictionary, allowed: Array, path: String) -> void:
|
||||
for key in obj.keys():
|
||||
if not allowed.has(key):
|
||||
fail(path + ("." if path != "" else "") + str(key), "campo desconhecido (permitidos: %s)" % ", ".join(PackedStringArray(allowed)))
|
||||
|
||||
func object(parent: Dictionary, key: String, path: String, allowed: Array) -> Dictionary:
|
||||
var value = parent.get(key)
|
||||
if typeof(value) != TYPE_DICTIONARY:
|
||||
fail(path, "obrigatório e precisa ser um objeto")
|
||||
return {}
|
||||
check_keys(value, allowed, path)
|
||||
return value
|
||||
|
||||
## `fallback` diferente de null torna o campo opcional.
|
||||
func number(obj: Dictionary, key: String, path: String, min_value: float, max_value: float, fallback = null) -> float:
|
||||
if not obj.has(key) or (typeof(obj[key]) == TYPE_NIL and typeof(fallback) != TYPE_NIL):
|
||||
if typeof(fallback) == TYPE_NIL:
|
||||
fail(path, "obrigatório")
|
||||
return 0.0
|
||||
return fallback
|
||||
var value = obj[key]
|
||||
if not _is_number(value):
|
||||
fail(path, "precisa ser um número finito (recebido %s)" % _describe(value))
|
||||
return 0.0
|
||||
var f := float(value)
|
||||
if f < min_value or f > max_value:
|
||||
fail(path, "fora do intervalo [%s, %s] (recebido %s)" % [min_value, max_value, f])
|
||||
return f
|
||||
|
||||
func integer(obj: Dictionary, key: String, path: String, min_value: int, max_value: int) -> int:
|
||||
var f := number(obj, key, path, min_value, max_value)
|
||||
if obj.has(key) and _is_number(obj[key]) and f != floorf(f):
|
||||
fail(path, "precisa ser inteiro (recebido %s)" % f)
|
||||
return int(f)
|
||||
|
||||
func boolean(obj: Dictionary, key: String, path: String) -> bool:
|
||||
if typeof(obj.get(key)) != TYPE_BOOL:
|
||||
fail(path, "obrigatório e precisa ser true ou false")
|
||||
return false
|
||||
return obj[key]
|
||||
|
||||
func text(obj: Dictionary, key: String, path: String, min_len: int, max_len: int) -> String:
|
||||
var value = obj.get(key)
|
||||
if typeof(value) != TYPE_STRING:
|
||||
fail(path, "obrigatório e precisa ser texto")
|
||||
return ""
|
||||
return _check_text(value, path, min_len, max_len)
|
||||
|
||||
func optional_text(obj: Dictionary, key: String, path: String, max_len: int):
|
||||
var value = obj.get(key)
|
||||
if typeof(value) == TYPE_NIL:
|
||||
return null
|
||||
if typeof(value) != TYPE_STRING:
|
||||
fail(path, "precisa ser texto ou null")
|
||||
return null
|
||||
if value.strip_edges() == "":
|
||||
return null
|
||||
return _check_text(value, path, 1, max_len)
|
||||
|
||||
func choice(obj: Dictionary, key: String, path: String, options: Array) -> String:
|
||||
var value = obj.get(key)
|
||||
if typeof(value) != TYPE_STRING or not options.has(value):
|
||||
fail(path, "precisa ser um de: %s (recebido %s)" % [", ".join(PackedStringArray(options)), _describe(value)])
|
||||
return options[0]
|
||||
return value
|
||||
|
||||
func color(obj: Dictionary, key: String, path: String, fallback = null) -> Color:
|
||||
var value = obj.get(key, fallback)
|
||||
if typeof(value) == TYPE_NIL:
|
||||
value = fallback
|
||||
if typeof(value) != TYPE_STRING or not RegEx.create_from_string("^#[0-9A-Fa-f]{6}$").search(value):
|
||||
fail(path, "precisa ser uma cor no formato #RRGGBB (recebido %s)" % _describe(value))
|
||||
return Color.MAGENTA
|
||||
return Color.html(value)
|
||||
|
||||
func vec3(obj: Dictionary, key: String, path: String, max_abs: float, fallback = null) -> Vector3:
|
||||
if not obj.has(key) and typeof(fallback) != TYPE_NIL:
|
||||
return fallback
|
||||
var value = obj.get(key)
|
||||
if typeof(value) != TYPE_ARRAY or value.size() != 3:
|
||||
fail(path, "precisa ser uma lista [x, y, z] (recebido %s)" % _describe(value))
|
||||
return Vector3.ZERO
|
||||
for item in value:
|
||||
if not _is_number(item) or absf(float(item)) > max_abs:
|
||||
fail(path, "cada componente precisa ser número finito com |valor| <= %s" % max_abs)
|
||||
return Vector3.ZERO
|
||||
return Vector3(float(value[0]), float(value[1]), float(value[2]))
|
||||
|
||||
func _check_text(value: String, path: String, min_len: int, max_len: int) -> String:
|
||||
var trimmed := value.strip_edges()
|
||||
if trimmed.length() < min_len or trimmed.length() > max_len:
|
||||
fail(path, "precisa ter entre %d e %d caracteres (tem %d)" % [min_len, max_len, trimmed.length()])
|
||||
for i in trimmed.length():
|
||||
if trimmed.unicode_at(i) < 32 or trimmed.unicode_at(i) == 127:
|
||||
fail(path, "contém caractere de controle")
|
||||
break
|
||||
return trimmed
|
||||
|
||||
static func _is_number(value) -> bool:
|
||||
return (typeof(value) == TYPE_FLOAT or typeof(value) == TYPE_INT) and is_finite(float(value))
|
||||
|
||||
func _describe(value) -> String:
|
||||
if typeof(value) == TYPE_NIL:
|
||||
return "nada"
|
||||
var s := JSON.stringify(value)
|
||||
return s if s.length() <= 40 else s.substr(0, 37) + "..."
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
uid://duthxk5m2w3tx
|
||||
@@ -0,0 +1,126 @@
|
||||
extends RefCounted
|
||||
## Relógio da cena. Tudo que se move é função pura do tempo de cena `t` (s),
|
||||
## nunca do relógio do sistema: avaliar o mesmo `t` com a mesma configuração
|
||||
## devolve o mesmo estado, em qualquer execução.
|
||||
##
|
||||
## Perfil de velocidade (convenção da cena: a moto avança em -Z):
|
||||
## parada -> rampa suave (accelSeconds) -> cruzeiro -> frenagem suave -> parada
|
||||
## As rampas usam smoothstep na velocidade, então velocidade E aceleração são
|
||||
## contínuas: não há tranco nem salto de posição entre as fases. A distância
|
||||
## chega exatamente em travelMeters no instante stopSeconds e fica ali.
|
||||
|
||||
const SceneConfig := preload("res://scripts/core/scene_config.gd")
|
||||
const CameraController := preload("res://scripts/view/camera_controller.gd")
|
||||
const OverlayController := preload("res://scripts/view/overlay_controller.gd")
|
||||
|
||||
## Amplitude da vibração vertical da carroceria em velocidade de cruzeiro (m).
|
||||
const BOB_AMPLITUDE := 0.006
|
||||
## Frequência espacial da vibração (rad/m): depende da distância, não do tempo.
|
||||
const BOB_SPATIAL_FREQUENCY := 7.0
|
||||
## Mergulho de frente por m/s² de aceleração (rad), limitado a ±2°.
|
||||
const PITCH_PER_ACCEL := 0.004
|
||||
const MAX_PITCH := 0.035
|
||||
|
||||
var _cfg: Dictionary
|
||||
var _wheel_radius: float
|
||||
var _t_start: float
|
||||
var _accel_len: float
|
||||
var _t_cruise: float
|
||||
var _t_brake: float
|
||||
var _brake_len: float
|
||||
var _t_stop: float
|
||||
var _speed: float
|
||||
var _travel: float
|
||||
var _start_position: Vector3
|
||||
var _distance_at_brake: float
|
||||
|
||||
|
||||
func _init(cfg: Dictionary, wheel_radius: float) -> void:
|
||||
_cfg = cfg
|
||||
_wheel_radius = wheel_radius
|
||||
var m: Dictionary = cfg.motion
|
||||
_t_start = m.start
|
||||
_accel_len = m.accel_seconds
|
||||
_t_cruise = _t_start + _accel_len
|
||||
_t_brake = m.brake_start
|
||||
_t_stop = m.stop
|
||||
_brake_len = _t_stop - _t_brake
|
||||
_travel = cfg.rider.travel
|
||||
_start_position = cfg.rider.start_position
|
||||
_speed = SceneConfig.cruise_speed(m, _travel)
|
||||
_distance_at_brake = _speed * (_accel_len * 0.5 + (_t_brake - _t_cruise))
|
||||
|
||||
|
||||
func cruise_speed() -> float:
|
||||
return _speed
|
||||
|
||||
|
||||
func distance_at(t: float) -> float:
|
||||
if t <= _t_start:
|
||||
return 0.0
|
||||
if t < _t_cruise:
|
||||
return _speed * _accel_len * _ramp_integral((t - _t_start) / _accel_len)
|
||||
if t < _t_brake:
|
||||
return _speed * (_accel_len * 0.5 + (t - _t_cruise))
|
||||
if t < _t_stop:
|
||||
var u := t - _t_brake
|
||||
return _distance_at_brake + _speed * (u - _brake_len * _ramp_integral(u / _brake_len))
|
||||
return _travel
|
||||
|
||||
|
||||
func speed_at(t: float) -> float:
|
||||
if t <= _t_start or t >= _t_stop:
|
||||
return 0.0
|
||||
if t < _t_cruise:
|
||||
return _speed * _smoothstep((t - _t_start) / _accel_len)
|
||||
if t < _t_brake:
|
||||
return _speed
|
||||
return _speed * (1.0 - _smoothstep((t - _t_brake) / _brake_len))
|
||||
|
||||
|
||||
func acceleration_at(t: float) -> float:
|
||||
if t <= _t_start or t >= _t_stop:
|
||||
return 0.0
|
||||
if t < _t_cruise:
|
||||
return _speed * _smoothstep_derivative((t - _t_start) / _accel_len) / _accel_len
|
||||
if t < _t_brake:
|
||||
return 0.0
|
||||
return -_speed * _smoothstep_derivative((t - _t_brake) / _brake_len) / _brake_len
|
||||
|
||||
|
||||
## Estado visual completo no instante `t`. É a única fonte que a cena consulta.
|
||||
func evaluate_at_time(t: float) -> Dictionary:
|
||||
var distance := distance_at(t)
|
||||
var speed := speed_at(t)
|
||||
var acceleration := acceleration_at(t)
|
||||
var position := _start_position + Vector3(0.0, 0.0, -distance)
|
||||
var speed_ratio := clampf(speed / _speed, 0.0, 1.0) if _speed > 0.0 else 0.0
|
||||
return {
|
||||
"t": t,
|
||||
"distance": distance,
|
||||
"speed": speed,
|
||||
"acceleration": acceleration,
|
||||
"rider_position": position,
|
||||
# Rotação em torno de X. Negativa para o topo da roda ir para -Z (frente).
|
||||
"wheel_angle": -distance / _wheel_radius,
|
||||
"body_bob": BOB_AMPLITUDE * speed_ratio * sin(distance * BOB_SPATIAL_FREQUENCY),
|
||||
"body_pitch": clampf(acceleration * PITCH_PER_ACCEL, -MAX_PITCH, MAX_PITCH),
|
||||
"camera": CameraController.evaluate(_cfg, t, position),
|
||||
"overlay": OverlayController.evaluate(_cfg, t),
|
||||
}
|
||||
|
||||
|
||||
static func _smoothstep(p: float) -> float:
|
||||
p = clampf(p, 0.0, 1.0)
|
||||
return p * p * (3.0 - 2.0 * p)
|
||||
|
||||
|
||||
static func _smoothstep_derivative(p: float) -> float:
|
||||
p = clampf(p, 0.0, 1.0)
|
||||
return 6.0 * p * (1.0 - p)
|
||||
|
||||
|
||||
## Integral de smoothstep de 0 a p (vale 0,5 em p = 1).
|
||||
static func _ramp_integral(p: float) -> float:
|
||||
p = clampf(p, 0.0, 1.0)
|
||||
return p * p * p - 0.5 * p * p * p * p
|
||||
@@ -0,0 +1 @@
|
||||
uid://dditd5mb3m2te
|
||||
Reference in New Issue
Block a user