PhysInOne / Utils /data_processing /camera /generate_static_cameras.py
vLAR's picture
Release data processing tools and UE render configs
11c70d1 verified
Raw History Blame Contribute Delete
6 kB
"""Generate managed static CineCamera actors around BP_CameraTrajectory.
Run this file with Unreal Engine's Python interpreter while the target level is
open in the editor. Only actors named ``CineCamera_<integer>`` are replaced.
Other CineCamera actors are never deleted.
"""
from __future__ import annotations
import argparse
import hashlib
import math
import random
import re
import unreal
CONFIG_ACTOR_LABEL = "BP_CameraTrajectory"
MANAGED_CAMERA_PATTERN = re.compile(r"^CineCamera_\d+$")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Generate PhysInOne static cameras.")
parser.add_argument("--focal", type=float, default=18.0, help="Focal length in mm.")
parser.add_argument("--aperture", type=float, default=10.0)
parser.add_argument("--radius", type=float, default=100.0, help="Base radius in cm.")
parser.add_argument("--min-latitude", type=float, default=30.0)
parser.add_argument("--max-latitude", type=float, default=60.0)
parser.add_argument(
"--deterministic",
action="store_true",
help="Disable the stable level-specific longitude offset.",
)
return parser.parse_known_args()[0]
def find_config_actor():
for actor in unreal.EditorLevelLibrary.get_all_level_actors():
if actor.get_actor_label() == CONFIG_ACTOR_LABEL:
return actor
return None
def validate_config(config_actor, minimum_latitude: float, maximum_latitude: float) -> None:
if not 0 <= minimum_latitude < maximum_latitude <= 90:
raise ValueError("Latitude limits must satisfy 0 <= min < max <= 90.")
scale = config_actor.get_actor_scale3d()
rotation = config_actor.get_actor_rotation()
tolerance = 1e-4
if max(abs(rotation.roll), abs(rotation.pitch), abs(rotation.yaw)) > tolerance:
raise ValueError("BP_CameraTrajectory rotation must be zero.")
if max(abs(scale.x - scale.y), abs(scale.x - scale.z)) > tolerance:
raise ValueError("BP_CameraTrajectory XYZ scale must be uniform.")
if min(scale.x, scale.y, scale.z) <= 0:
raise ValueError("BP_CameraTrajectory scale must be positive.")
def stable_seed(text: str) -> int:
return int.from_bytes(hashlib.sha256(text.encode("utf-8")).digest()[:8], "big")
def remove_managed_static_cameras() -> int:
removed = 0
for actor in unreal.EditorLevelLibrary.get_all_level_actors():
if isinstance(actor, unreal.CineCameraActor) and MANAGED_CAMERA_PATTERN.fullmatch(
actor.get_actor_label()
):
unreal.EditorLevelLibrary.destroy_actor(actor)
removed += 1
return removed
def configure_camera(camera_actor, focal: float, aperture: float) -> None:
component = camera_actor.get_cine_camera_component()
component.set_editor_property("current_focal_length", focal)
component.set_editor_property("current_aperture", aperture)
filmback = component.get_editor_property("filmback")
filmback.sensor_width = 23.76
filmback.sensor_height = 23.76
component.set_editor_property("filmback", filmback)
def generate(args: argparse.Namespace) -> int:
config_actor = find_config_actor()
if config_actor is None:
raise RuntimeError(f"Actor {CONFIG_ACTOR_LABEL!r} was not found in the current level.")
validate_config(config_actor, args.min_latitude, args.max_latitude)
count = int(config_actor.get_editor_property("Num"))
if count < 1:
raise ValueError("BP_CameraTrajectory.Num must be at least 1.")
world = unreal.EditorLevelLibrary.get_editor_world()
level_name = world.get_name()
rng = random.Random(stable_seed(level_name))
longitude_offset = 0.0 if args.deterministic else rng.uniform(0.0, 2.0 * math.pi)
random_hemisphere = bool(config_actor.get_editor_property("RandomHemisphere"))
upper_hemisphere = bool(config_actor.get_editor_property("UpperHemisphere"))
if random_hemisphere:
upper_hemisphere = rng.choice([True, False])
removed = remove_managed_static_cameras()
unreal.log(f"Removed {removed} managed static camera(s).")
center = config_actor.get_actor_location()
scale = config_actor.get_actor_scale3d()
editor = unreal.EditorLevelLibrary()
phi_min = math.radians(90.0 - args.max_latitude)
phi_max = math.radians(90.0 - args.min_latitude)
cos_min = math.cos(phi_min)
cos_max = math.cos(phi_max)
for index in range(count):
fraction = (index + 0.5) / count
phi = math.acos(cos_min + (cos_max - cos_min) * fraction)
theta = math.pi * (1.0 + math.sqrt(5.0)) * (index + 0.5) + longitude_offset
z_sign = 1.0 if upper_hemisphere else -1.0
x = args.radius * math.sin(phi) * math.cos(theta) * scale.x
y = args.radius * math.sin(phi) * math.sin(theta) * scale.y
z = z_sign * args.radius * math.cos(phi) * scale.z
location = unreal.Vector(center.x + x, center.y + y, center.z + z)
direction = center - location
rotation = unreal.MathLibrary.make_rot_from_x(unreal.MathLibrary.normal(direction))
rotation.roll = 0.0
camera = editor.spawn_actor_from_class(unreal.CineCameraActor, location, rotation)
camera.set_actor_label(f"CineCamera_{index}")
configure_camera(camera, args.focal, args.aperture)
camera.attach_to_actor(
config_actor,
socket_name=unreal.Name(""),
location_rule=unreal.AttachmentRule.KEEP_WORLD,
rotation_rule=unreal.AttachmentRule.KEEP_WORLD,
scale_rule=unreal.AttachmentRule.KEEP_WORLD,
weld_simulated_bodies=True,
)
unreal.log(
f"Generated {count} static camera(s) for {level_name}; "
f"hemisphere={'upper' if upper_hemisphere else 'lower'}."
)
return count
if __name__ == "__main__":
try:
generate(parse_args())
except Exception as exc:
unreal.log_error(f"Static camera generation failed: {exc}")
raise