Spaces:
Running
Running
File size: 16,891 Bytes
86f8e0b 5874da5 86f8e0b 5874da5 d75aeff 5874da5 86f8e0b 5874da5 86f8e0b 5874da5 86f8e0b 5874da5 3bd1e4b 86f8e0b 3bd1e4b 5874da5 86f8e0b 5874da5 86f8e0b 5874da5 86f8e0b 5874da5 86f8e0b 5874da5 86f8e0b 5874da5 86f8e0b 5874da5 3bd1e4b 5874da5 3bd1e4b 86f8e0b 3bd1e4b 86f8e0b 3bd1e4b 86f8e0b 5874da5 86f8e0b 5874da5 86f8e0b 5874da5 d75aeff 86f8e0b 5874da5 86f8e0b 3bd1e4b 86f8e0b 3bd1e4b 86f8e0b 5874da5 86f8e0b d75aeff 86f8e0b d75aeff 86f8e0b 5874da5 | 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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | """Isaac Sim (RTX) thumbnails for the Library: <out_dir>/dark/<asset>.webp and <out_dir>/light/<asset>.webp.
Renders each SimReady package with its own materials (MDL glass, liquids, OpenPBR), the
way it looks in sim, instead of the simplified preview GLB: a three-quarter view from the
front-right (the package's simready:assetFrame:forwardDirection when it has one, else -Y),
lit by Tyler's HDRI (Poly Haven small_hangar_02) as a dome that isn't visible in the image.
Path tracing with Tyler's settings: max bounces 4, specular/transmission bounces 6,
subsurface scattering on.
The asset stands on a floor that fills the whole frame, rendered twice, once per Library
theme (the app picks by theme):
dark: plain matte dark floor that ends up #1a1a1a, the dark theme's thumbnail
background (--thumb), with a fade to it over the outer 4% of the frame, so the
image melts into the card and only the asset and its soft shadow show.
light: NVIDIA-style grey studio: light grey floor with a faint grid (1-2-5 cm cells,
about a tenth of the asset's size) and soft reflections, balanced so the far
floor reads neutral grey (158,159,161).
Both get the same white balance for the warm HDRI (fixed gains), plus a small per-image
nudge that puts the far floor on its target colour.
Workaround, render only (the package is not changed): RTX draws a package's MaterialX
(OpenPBR) network, and an OpenPBR whose geometry_normal comes from an ND_normalmap node
that has a tangent input (the shared brushed and milled steel looks, normal map plus
material_tangent primvar) renders pure black there. Those geometry_normal links are cut
before rendering, so the steel shows with its colour, roughness and anisotropy, without
the fine normal-map detail.
Run on a GPU machine with Isaac Sim 6.x (pip install or /opt/IsaacSim/python.sh):
OMNI_KIT_ACCEPT_EULA=YES python isaac_thumbs.py <assets_dir> <out_dir> <hdri.exr> [asset ...]
<assets_dir>/<asset>/simready_usd/<asset>.usd for every asset (a download of
projectsim/simready-assets). Assets with both thumbnails already are skipped unless --force.
"""
import argparse
import math
import os
import sys
ap = argparse.ArgumentParser()
ap.add_argument("assets_dir")
ap.add_argument("out_dir")
ap.add_argument("hdri")
ap.add_argument("assets", nargs="*")
ap.add_argument("--variants", default="dark,light")
ap.add_argument("--size", type=int, default=640, help="output size in px")
ap.add_argument("--render-size", type=int, default=1024, help="rendered size before downscaling")
ap.add_argument("--spp", type=int, default=256, help="path-tracing samples per pixel")
ap.add_argument("--dome", type=float, default=1500.0, help="HDRI dome intensity")
ap.add_argument("--wb", default="1.63,2.14,2.93", help="white balance + exposure for the warm HDRI (linear RGB gains)")
ap.add_argument("--dark-floor", type=float, default=0.175, help="dark floor albedo (sRGB 0-1)")
ap.add_argument("--grid-grey", type=float, default=0.62, help="light (grid) floor albedo (sRGB 0-1)")
ap.add_argument("--fill", type=float, default=0.92, help="share of the frame the bounding box fills")
ap.add_argument("--azimuth", type=float, default=35.0, help="degrees right of the front")
ap.add_argument("--elevation", type=float, default=24.0)
ap.add_argument("--fov", type=float, default=22.0, help="vertical field of view, degrees")
ap.add_argument("--max-bounces", type=int, default=4)
ap.add_argument("--max-spec-bounces", type=int, default=6, help="max specular and transmission bounces")
ap.add_argument("--force", action="store_true")
args = ap.parse_intermixed_args() # asset names may follow the flags
sys.argv = sys.argv[:1] # keep our flags away from Kit's own argument parsing
VARIANTS = { # floor material, far-floor target (sRGB), fade the border to it
"dark": ("matte", (26, 26, 26), True),
"light": ("grid", (158, 159, 161), False),
}
variants = [v for v in args.variants.split(",") if v in VARIANTS]
from isaacsim import SimulationApp # noqa: E402
R = args.render_size
app = SimulationApp({"headless": True, "renderer": "PathTracing", "width": R, "height": R})
import carb # noqa: E402
import numpy as np # noqa: E402
import omni.replicator.core as rep # noqa: E402
import omni.usd # noqa: E402
from PIL import Image # noqa: E402
from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade # noqa: E402
settings = carb.settings.get_settings()
for key, value in {
"/rtx/pathtracing/totalSpp": args.spp,
"/rtx/pathtracing/spp": 16,
"/rtx/pathtracing/maxBounces": args.max_bounces, # Tyler's settings
"/rtx/pathtracing/maxSpecularAndTransmissionBounces": args.max_spec_bounces,
"/rtx/pathtracing/optixDenoiser/enabled": True,
# subsurface scattering (Tyler): frosted plastics, nylon, wax look flat without it
"/rtx/raytracing/subsurface/enabled": True,
"/rtx/raytracing/subsurface/transmission/enabled": True,
"/rtx/pathtracing/maxVolumeBounces": 15,
# load materials and textures before rendering, not in the background (otherwise the
# first image after a material change can show the previous floor)
"/rtx/materialDb/syncLoads": True,
"/rtx/hydra/materialSyncLoads": True,
"/rtx-transient/resourcemanager/texturestreaming/async": False,
"/omni.kit.plugin/syncUsdLoads": True,
}.items():
settings.set(key, value)
def to_lin(c):
c = np.asarray(c, np.float32)
return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
def to_srgb(c):
return np.where(c <= 0.0031308, c * 12.92, 1.055 * np.power(np.clip(c, 0, None), 1 / 2.4) - 0.055)
WB = np.array([float(v) for v in args.wb.split(",")], np.float32)
for v in variants:
os.makedirs(f"{args.out_dir}/{v}", exist_ok=True)
names = args.assets or sorted(n for n in os.listdir(args.assets_dir)
if os.path.isfile(f"{args.assets_dir}/{n}/simready_usd/{n}.usd"))
todo = [n for n in names if args.force or args.assets
or not all(os.path.exists(f"{args.out_dir}/{v}/{n}.webp") for v in variants)]
print(f"{len(todo)} assets to render ({', '.join(variants)})", flush=True)
ctx = omni.usd.get_context()
ctx.new_stage()
for _ in range(5):
app.update()
stage = ctx.get_stage()
UsdGeom.SetStageMetersPerUnit(stage, 1.0)
dome = UsdLux.DomeLight.Define(stage, "/World/Dome")
dome.CreateTextureFileAttr(os.path.abspath(args.hdri))
dome.CreateTextureFormatAttr("latlong")
dome.CreateIntensityAttr(args.dome)
dome.GetPrim().CreateAttribute("visibleInPrimaryRay", Sdf.ValueTypeNames.Bool).Set(False)
floor = UsdGeom.Mesh.Define(stage, "/World/Floor")
floor.CreatePointsAttr([(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0)])
floor.CreateFaceVertexCountsAttr([4])
floor.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
floor_st = UsdGeom.PrimvarsAPI(floor.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
floor_st.Set([(0, 0), (1, 0), (1, 1), (0, 1)])
floor_binding = UsdShade.MaterialBindingAPI.Apply(floor.GetPrim())
# dark: matte, no reflections, so it's one even colour up to the frame edges
matte = UsdShade.Material.Define(stage, "/World/Looks/Matte")
s1 = UsdShade.Shader.Define(stage, "/World/Looks/Matte/Surface")
s1.CreateIdAttr("UsdPreviewSurface")
s1.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(1.0)
s1.CreateInput("useSpecularWorkflow", Sdf.ValueTypeNames.Int).Set(1)
s1.CreateInput("specularColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(0, 0, 0))
g = float(to_lin(args.dark_floor))
s1.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(g, g, g))
matte.CreateSurfaceOutput().ConnectToSource(s1.ConnectableAPI(), "surface")
# light: grey studio floor with a faint grid, one texture tile = 8 x 8 cells
GRID = os.path.abspath(os.path.join(args.out_dir, "_studio_grid.png"))
tile = np.full((1024, 1024), args.grid_grey * 255, np.float32)
for k in range(0, 1024, 128):
tile[k:k + 2, :] *= 0.9
tile[:, k:k + 2] *= 0.9
tile[0:3, :] *= 0.93
tile[:, 0:3] *= 0.93
Image.fromarray(tile.clip(0, 255).astype(np.uint8), "L").convert("RGB").save(GRID)
grid = UsdShade.Material.Define(stage, "/World/Looks/Grid")
s2 = UsdShade.Shader.Define(stage, "/World/Looks/Grid/Surface")
s2.CreateIdAttr("UsdPreviewSurface")
s2.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.6)
s2.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
reader = UsdShade.Shader.Define(stage, "/World/Looks/Grid/St")
reader.CreateIdAttr("UsdPrimvarReader_float2")
reader.CreateInput("varname", Sdf.ValueTypeNames.String).Set("st")
tex = UsdShade.Shader.Define(stage, "/World/Looks/Grid/Texture")
tex.CreateIdAttr("UsdUVTexture")
tex.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(GRID)
tex.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat")
tex.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat")
tex.CreateInput("sourceColorSpace", Sdf.ValueTypeNames.Token).Set("sRGB")
tex.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(reader.ConnectableAPI(), "result")
s2.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(tex.ConnectableAPI(), "rgb")
grid.CreateSurfaceOutput().ConnectToSource(s2.ConnectableAPI(), "surface")
FLOORS = {"matte": matte, "grid": grid}
cam = UsdGeom.Camera.Define(stage, "/World/Cam")
APERTURE = 20.955
cam.CreateFocalLengthAttr(APERTURE / 2 / math.tan(math.radians(args.fov) / 2))
cam.CreateHorizontalApertureAttr(APERTURE)
cam.CreateVerticalApertureAttr(APERTURE)
cam_xf = cam.AddTransformOp()
rp = rep.create.render_product(str(cam.GetPath()), (R, R))
rgb = rep.AnnotatorRegistry.get_annotator("rgb")
rgb.attach(rp)
PURPOSES = [UsdGeom.Tokens.default_, UsdGeom.Tokens.render]
HALF = math.tan(math.radians(args.fov) / 2) * args.fill
SUBFRAMES = max(1, args.spp // 16)
edge = np.minimum(np.arange(R) + 0.5, R - np.arange(R) - 0.5) / (0.04 * R) # 0 at the edge, 1 at 4% in
edge = np.clip(edge, 0, 1)
edge = edge * edge * (3 - 2 * edge)
KEEP = np.minimum.outer(edge, edge)[..., None]
def basis(up_axis, forward):
"""Stage up vector, and the asset's front as a horizontal unit vector."""
up = Gf.Vec3d(0, 0, 1) if up_axis == "Z" else Gf.Vec3d(0, 1, 0)
f = Gf.Vec3d(*forward) if forward else (Gf.Vec3d(0, -1, 0) if up_axis == "Z" else Gf.Vec3d(0, 0, 1))
f = f - up * Gf.Dot(f, up)
if f.GetLength() < 1e-6:
f = Gf.Vec3d(0, -1, 0) if up_axis == "Z" else Gf.Vec3d(0, 0, 1)
return up, f.GetNormalized()
def fix_mtlx_normals(root):
"""Cut OpenPBR geometry_normal links that come from an ND_normalmap with a tangent input."""
n = 0
for p in Usd.PrimRange(root):
if not p.IsA(UsdShade.Shader) or UsdShade.Shader(p).GetIdAttr().Get() != "ND_open_pbr_surface_surfaceshader":
continue
inp = UsdShade.Shader(p).GetInput("geometry_normal")
srcs = inp.GetConnectedSources()[0] if inp else []
if not srcs:
continue
node = UsdShade.Shader(srcs[0].source.GetPrim())
tangent = node.GetInput("tangent")
if node.GetIdAttr().Get() == "ND_normalmap" and tangent and tangent.HasConnectedSource():
UsdShade.ConnectableAPI.DisconnectSource(inp) # blocks the link from the referenced layer
n += 1
return n
def render():
# Render without advancing time: a step that moves the timeline also steps physics, and
# the asset (a rigid body, with no collider under it) drops a millimetre or two into the
# floor, which swallows thin parts lying flat (angle brackets).
try:
rep.orchestrator.step(rt_subframes=SUBFRAMES, delta_time=0.0, pause_timeline=True)
except TypeError:
rep.orchestrator.step(rt_subframes=SUBFRAMES)
return np.asarray(rgb.get_data())
def finish(img, card, fade):
"""White balance, nudge the far floor onto its target colour, optionally fade the border to it."""
lin = to_lin(img[..., :3].astype(np.float32) / 255)
k = max(4, R // 10)
ref = np.concatenate([lin[:k, :k].reshape(-1, 3), lin[:k, -k:].reshape(-1, 3)])
target = to_lin(np.array(card, np.float32) / 255)
gain = WB * np.clip(target / np.maximum(np.median(ref, axis=0) * WB, 1e-5), 0.75, 1.25)
lin = lin * gain
if fade:
lin = lin * KEEP + target * (1 - KEEP)
out = Image.fromarray((np.clip(to_srgb(lin), 0, 1) * 255 + 0.5).astype(np.uint8), "RGB")
if args.size != R:
out = out.resize((args.size, args.size), Image.LANCZOS)
return out, gain, np.median(ref, axis=0)
# warm-up: compile both floor materials and load the grid texture before the first asset
for kind in ("grid", "matte"):
floor_binding.Bind(FLOORS[kind])
for _ in range(5):
app.update()
render()
for i, name in enumerate(todo, 1):
usd = f"{args.assets_dir}/{name}/simready_usd/{name}.usd"
try:
if stage.GetPrimAtPath("/World/Asset"):
stage.RemovePrim("/World/Asset")
app.update()
src = Usd.Stage.Open(usd, Usd.Stage.LoadNone)
up_axis = UsdGeom.GetStageUpAxis(src)
root = src.GetDefaultPrim()
fwd_attr = root.GetAttribute("simready:assetFrame:forwardDirection") if root else None
forward = fwd_attr.Get() if fwd_attr and fwd_attr.HasAuthoredValue() else None
if forward is not None and root.IsA(UsdGeom.Xformable): # authored in the prim's local frame
forward = UsdGeom.Xformable(root).GetLocalTransformation().TransformDir(Gf.Vec3d(*forward))
UsdGeom.SetStageUpAxis(stage, up_axis)
up, front = basis(up_axis, forward)
asset = stage.DefinePrim("/World/Asset", "Xform")
asset.GetReferences().AddReference(usd)
cut = fix_mtlx_normals(asset)
for _ in range(10):
app.update()
rng = UsdGeom.BBoxCache(Usd.TimeCode.Default(), PURPOSES).ComputeWorldBound(asset).ComputeAlignedRange()
if rng.IsEmpty():
print(f"THUMB_SKIP {name}: empty bounds", flush=True)
continue
centre = (rng.GetMin() + rng.GetMax()) / 2
size = max(rng.GetSize().GetLength(), 1e-3)
# view direction: front turned toward the right by the azimuth, raised by the elevation
a, e = math.radians(args.azimuth), math.radians(args.elevation)
right = Gf.Cross(front, up)
view = ((front * math.cos(a) + right * math.sin(a)) * math.cos(e) + up * math.sin(e)).GetNormalized()
# distance: smallest that keeps every bounding-box corner inside the frame
lo, hi = rng.GetMin(), rng.GetMax()
box = [Gf.Vec3d(x, y, z) for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]
def fits(d):
m = Gf.Matrix4d().SetLookAt(centre + view * d, centre, up)
for p in box:
q = m.Transform(p)
if -q[2] <= 1e-6 or max(abs(q[0]), abs(q[1])) / -q[2] > HALF:
return False
return True
lo_d, hi_d = size * 0.3, size * 20
for _ in range(40):
mid = (lo_d + hi_d) / 2
lo_d, hi_d = (lo_d, mid) if fits(mid) else (mid, hi_d)
cam_xf.Set(Gf.Matrix4d().SetLookAt(centre + view * hi_d, centre, up).GetInverse())
cam.CreateClippingRangeAttr(Gf.Vec2f(max(hi_d * 0.02, 1e-4), hi_d + size * 200))
# floor under the asset, reaching well past the top of the frame
base = lo[2] if up_axis == "Z" else lo[1]
w = size * 60
quad = ((-w, -w), (w, -w), (w, w), (-w, w))
floor.GetPointsAttr().Set([(centre[0] + x, centre[1] + y, base) for x, y in quad] if up_axis == "Z"
else [(centre[0] + x, base, centre[2] - y) for x, y in quad])
want = size / 10 # grid cells of 1-2-5 cm steps, about a tenth of the asset
mag = 10 ** math.floor(math.log10(want))
cell = min((m * mag for m in (1, 2, 5, 10)), key=lambda c: abs(math.log(c / want)))
reps = 2 * w / (8 * cell)
floor_st.Set([(0, 0), (reps, 0), (reps, reps), (0, reps)])
gains = []
for v in variants:
kind, card, fade = VARIANTS[v]
floor_binding.Bind(FLOORS[kind])
for _ in range(3):
app.update()
img = render()
if img.ndim != 3 or img.shape[2] < 3:
raise RuntimeError("no image")
out, gain, raw = finish(img, card, fade)
out.save(f"{args.out_dir}/{v}/{name}.webp", quality=90)
gains.append(f"{v}={round(float(gain[1] / WB[1]), 2)} raw={np.round(raw, 4).tolist()}")
print(f"THUMB_OK {name} {i}/{len(todo)} nudge {' '.join(gains)}" + (f" normal_links_cut={cut}" if cut else ""), flush=True)
except Exception as exc: # keep going; report at the end
print(f"THUMB_FAIL {name}: {exc}", flush=True)
rep.orchestrator.wait_until_complete()
print("THUMBS DONE", flush=True)
app.close()
|