File size: 6,003 Bytes
11c70d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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