file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/mdl_usd.py | #*****************************************************************************
# Copyright 2022 NVIDIA Corporation. All rights reserved.
#*****************************************************************************
import sys
import os
import gc
import platform
import traceback
from enum import Enum
from pxr import Usd
from pxr import Plug
from pxr import Sdr
from pxr import Sdf
from pxr import Tf
from pxr import UsdShade
from pxr import Gf
from pxr import UsdGeom
from pxr import Kind
from pxr import UsdUI
import numpy # used to represent Vectors, Matrices, and Colors
import re # For command line args
from copy import deepcopy # Dictionary merging
import tempfile
# load the binding module
print("MDL python binding about to load ...")
####################
# Omniverse code
from omni.mdl import pymdlsdk
from omni.mdl import pymdl
import omni.client
async def copy_async(texture_path, dst_path):
result = await omni.client.copy_async(texture_path, dst_path)
return (result == omni.client.Result.OK)
# Omniverse code
####################
# TODO: loading fails for debug builds of the pymdlsdk.pyd (or pymdlsdk.so on unix) module
print("MDL python binding loaded")
def str2bool(v):
return str(v).lower() in ("true", "1")
def str2MDL_TO_USD_OUTPUT(v):
if v == '1': return OutputType.SHADER
if v == '2': return OutputType.MATERIAL
if v == '3': return OutputType.MATERIAL_AND_GEOMETRY
#--------------------------------------------------------------------------------------------------
# Command line arguments
#--------------------------------------------------------------------------------------------------
class Args: # pragma: no cover
display_usage = False
options = dict()
def __init__(self):
self.options["SEARCH_PATH"] = get_examples_search_path()
self.options["MODULE"] = "::nvidia::sdk_examples::tutorials"
self.options["PRIM"] = "/example_material" # Used for USD to MDL conversion
self.options["STAGE"] = "tutorials.usda"
self.options["OUT"] = "tutorials.usda"
# Set FOR_OV to False if a Material/Shader hierarchy is required in the output USD stage
# SHADER = 1
# MATERIAL = 2
# MATERIAL_AND_GEOMETRY = 3
self.options["MDL_TO_USD_OUTPUT"] = 1
self.options["NESTED_SHADERS"] = False # See mdl_to_usd_output_material_nested_shaders
self.options["MDL_TO_USD"] = True
for a in sys.argv:
if a == "-help" or a == "-h" or a == "-?":
self.display_usage = True
break
match = re.search("(.+)=(.+)", a)
if match:
self.options[match.group(1)] = match.group(2)
# Convert paths
self.options["SEARCH_PATH"] = os.path.abspath(self.options["SEARCH_PATH"])
self.options["OUT"] = os.path.abspath(self.options["OUT"])
# Convert string args to bool
self.options["MDL_TO_USD"] = str2bool(self.options["MDL_TO_USD"])
self.options["NESTED_SHADERS"] = str2bool(self.options["NESTED_SHADERS"])
# Convert string args to int
self.options["MDL_TO_USD_OUTPUT"] = str2MDL_TO_USD_OUTPUT(self.options["MDL_TO_USD_OUTPUT"])
def usage(self):
print("usage: " + os.path.basename(sys.argv[0]) + " [-help|-h|-?] [SEARCH_PATH=<path>] [MODULE=<string>] [PRIM=<string>] [STAGE=<string>] [OUT=<string>] [MDL_TO_USD_OUTPUT=<int>] [NESTED_SHADERS=<bool>] [MDL_TO_USD=<bool>]")
print("\n")
print(" -help|-h|-?:\t Display usage")
print(" SEARCH_PATH:\t Use this as MDL search path (default: {})".format(self.options["SEARCH_PATH"]))
print(" MODULE:\t Module to load (default: {})".format(self.options["MODULE"]))
print(" PRIM:\t\t USD prim to convert to MDL (default: {})".format(self.options["PRIM"]))
print(" STAGE:\t USD stage to load and convert (default: {})".format(self.options["STAGE"]))
print(" OUT:\t\t Output file (default: {})".format(self.options["OUT"]))
print(" MDL_TO_USD_OUTPUT:\t Output either a shader (1) or material (2) or material and geometry (3) (default: {})".format(self.options["MDL_TO_USD_OUTPUT"]))
print(" NESTED_SHADERS:\t Output nested shader tree, vs. flat shader tree (default: {})".format(self.options["NESTED_SHADERS"]))
print(" MDL_TO_USD:\t MDL to USD conversion ortherwise USD to MDL (default: {})".format(self.options["MDL_TO_USD"]))
#--------------------------------------------------------------------------------------------------
# USD and misc utilities
#--------------------------------------------------------------------------------------------------
MdlIValueKindToUSD = {
pymdlsdk.IValue.Kind.VK_BOOL: Sdf.ValueTypeNames.Bool,
pymdlsdk.IValue.Kind.VK_INT : Sdf.ValueTypeNames.Int,
pymdlsdk.IValue.Kind.VK_ENUM : Sdf.ValueTypeNames.Int,
pymdlsdk.IValue.Kind.VK_FLOAT : Sdf.ValueTypeNames.Float,
pymdlsdk.IValue.Kind.VK_DOUBLE : Sdf.ValueTypeNames.Double,
pymdlsdk.IValue.Kind.VK_STRING : Sdf.ValueTypeNames.String,
pymdlsdk.IValue.Kind.VK_COLOR : Sdf.ValueTypeNames.Color3f,
pymdlsdk.IValue.Kind.VK_STRUCT : Sdf.ValueTypeNames.Token,
pymdlsdk.IValue.Kind.VK_TEXTURE : Sdf.ValueTypeNames.Asset,
pymdlsdk.IValue.Kind.VK_LIGHT_PROFILE : Sdf.ValueTypeNames.Asset,
pymdlsdk.IValue.Kind.VK_BSDF_MEASUREMENT : Sdf.ValueTypeNames.Asset
}
MdlITypeKindToUSD = {
pymdlsdk.IType.Kind.TK_BOOL: Sdf.ValueTypeNames.Bool,
pymdlsdk.IType.Kind.TK_INT : Sdf.ValueTypeNames.Int,
pymdlsdk.IType.Kind.TK_ENUM : Sdf.ValueTypeNames.Int,
pymdlsdk.IType.Kind.TK_FLOAT : Sdf.ValueTypeNames.Float,
pymdlsdk.IType.Kind.TK_DOUBLE : Sdf.ValueTypeNames.Double,
pymdlsdk.IType.Kind.TK_STRING : Sdf.ValueTypeNames.String,
pymdlsdk.IType.Kind.TK_COLOR : Sdf.ValueTypeNames.Color3f,
pymdlsdk.IType.Kind.TK_STRUCT : Sdf.ValueTypeNames.Token,
pymdlsdk.IType.Kind.TK_TEXTURE : Sdf.ValueTypeNames.Asset,
pymdlsdk.IType.Kind.TK_LIGHT_PROFILE : Sdf.ValueTypeNames.Asset,
pymdlsdk.IType.Kind.TK_BSDF_MEASUREMENT : Sdf.ValueTypeNames.Asset
}
# TODO:
# mi::neuraylib::IType::TK_BSDF
# mi::neuraylib::IType::TK_EDF
# mi::neuraylib::IType::TK_VDF
def python_vector_to_usd_type(dtype, size):
if dtype == numpy.int32 or dtype == bool:
if size == 2:
return Sdf.ValueTypeNames.Int2
elif size == 3:
return Sdf.ValueTypeNames.Int3
elif size == 4:
return Sdf.ValueTypeNames.Int4
elif dtype == numpy.float32:
if size == 2:
return Sdf.ValueTypeNames.Float2
elif size == 3:
return Sdf.ValueTypeNames.Float3
elif size == 4:
return Sdf.ValueTypeNames.Float4
elif dtype == numpy.float64:
if size == 2:
return Sdf.ValueTypeNames.Double2
elif size == 3:
return Sdf.ValueTypeNames.Double3
elif size == 4:
return Sdf.ValueTypeNames.Double4
return None
def python_vector_to_usd_value(value):
dtype = value.dtype
size = value.size
out = None
if dtype == numpy.int32 or dtype == bool:
if size == 2:
out = Gf.Vec2i(0)
elif size == 3:
out = Gf.Vec3i(0)
elif size == 4:
out = Gf.Vec4i(0)
if out != None:
for i in range(size):
out[i] = int(value[i][0])
elif dtype == numpy.float32:
if size == 2:
out = Gf.Vec2f(0)
elif size == 3:
out = Gf.Vec3f(0)
elif size == 4:
out = Gf.Vec4f(0)
if out != None:
for i in range(size):
out[i] = float(value[i][0])
elif dtype == numpy.float64:
if size == 2:
out = Gf.Vec2d(0)
elif size == 3:
out = Gf.Vec3d(0)
elif size == 4:
out = Gf.Vec4d(0)
if out != None:
for i in range(size):
out[i] = numpy.float64(value[i][0])
return out
def custom_data_from_python_vector(value):
dtype = value.dtype
out = dict()
if dtype == bool:
size = value.size
out = dict({"mdl":{"type" : "bool{}".format(size)}})
return out
def python_matrix_to_usd_type(dtype, nrow, ncol):
# numpyType Column Row OutType
m = { 'float32' : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2d,
3 : Sdf.ValueTypeNames.Float3Array,
4 : Sdf.ValueTypeNames.Float4Array},
3 : { 2 : Sdf.ValueTypeNames.Float2Array,
3 : Sdf.ValueTypeNames.Matrix3d,
4 : Sdf.ValueTypeNames.Float4Array},
4 : { 2 : Sdf.ValueTypeNames.Float2Array,
3 : Sdf.ValueTypeNames.Float3Array,
4 : Sdf.ValueTypeNames.Matrix4d }},
'float64' : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2d,
3 : Sdf.ValueTypeNames.Double3Array,
4 : Sdf.ValueTypeNames.Double4Array},
3 : { 2 : Sdf.ValueTypeNames.Double2Array,
3 : Sdf.ValueTypeNames.Matrix3d,
4 : Sdf.ValueTypeNames.Double4Array},
4 : { 2 : Sdf.ValueTypeNames.Double2Array,
3 : Sdf.ValueTypeNames.Double3Array,
4 : Sdf.ValueTypeNames.Matrix4d }}}
return m[dtype.name][ncol][nrow]
def python_matrix_to_usd_value(value):
dtype = value.dtype
nrow = value.shape[0]
ncol = value.shape[1]
out = None
if dtype == numpy.float32:
if ncol == 2:
if nrow == 2:
out = Gf.Matrix2d(0)
out.SetColumn(0, Gf.Vec2d(float(value[0][0]), float(value[0][1])))
out.SetColumn(1, Gf.Vec2d(float(value[1][0]), float(value[1][1])))
elif nrow == 3:
out = [Gf.Vec3f(float(value[0][0]), float(value[1][0]), float(value[2][0])),
Gf.Vec3f(float(value[0][1]), float(value[1][1]), float(value[2][1]))]
elif nrow == 4:
out = [Gf.Vec4f(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])),
Gf.Vec4f(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1]))]
elif ncol == 3:
if nrow == 2:
out = [Gf.Vec2f(float(value[0][0]), float(value[1][0])),
Gf.Vec2f(float(value[0][1]), float(value[1][1])),
Gf.Vec2f(float(value[0][2]), float(value[1][2]))]
elif nrow == 3:
out = Gf.Matrix3d(0)
out.SetColumn(0, Gf.Vec3d(float(value[0][0]), float(value[0][1]), float(value[0][2])))
out.SetColumn(1, Gf.Vec3d(float(value[1][0]), float(value[1][1]), float(value[1][2])))
out.SetColumn(2, Gf.Vec3d(float(value[2][0]), float(value[2][1]), float(value[2][2])))
elif nrow == 4:
out = [Gf.Vec4f(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])),
Gf.Vec4f(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1])),
Gf.Vec4f(float(value[0][2]), float(value[1][2]), float(value[2][2]), float(value[3][2]))]
elif ncol == 4:
if nrow == 2:
out = [Gf.Vec2f(float(value[0][0]), float(value[1][0])),
Gf.Vec2f(float(value[0][1]), float(value[1][1])),
Gf.Vec2f(float(value[0][2]), float(value[1][2])),
Gf.Vec2f(float(value[0][3]), float(value[1][3]))]
elif nrow == 3:
out = [Gf.Vec3f(float(value[0][0]), float(value[1][0]), float(value[2][0])),
Gf.Vec3f(float(value[0][1]), float(value[1][1]), float(value[2][1])),
Gf.Vec3f(float(value[0][2]), float(value[1][2]), float(value[2][2])),
Gf.Vec3f(float(value[0][3]), float(value[1][3]), float(value[2][3]))]
elif nrow == 4:
out = Gf.Matrix4d(0)
out.SetColumn(0, Gf.Vec4d(float(value[0][0]), float(value[0][1]), float(value[0][2]), float(value[0][3])))
out.SetColumn(1, Gf.Vec4d(float(value[1][0]), float(value[1][1]), float(value[1][2]), float(value[1][3])))
out.SetColumn(2, Gf.Vec4d(float(value[2][0]), float(value[2][1]), float(value[2][2]), float(value[2][3])))
out.SetColumn(3, Gf.Vec4d(float(value[3][0]), float(value[3][1]), float(value[3][2]), float(value[3][3])))
elif dtype == numpy.float64:
if ncol == 2:
if nrow == 2:
out = Gf.Matrix2d(0)
out.SetColumn(0, Gf.Vec2d(float(value[0][0]), float(value[0][1])))
out.SetColumn(1, Gf.Vec2d(float(value[1][0]), float(value[1][1])))
elif nrow == 3:
out = [Gf.Vec3d(float(value[0][0]), float(value[1][0]), float(value[2][0])),
Gf.Vec3d(float(value[0][1]), float(value[1][1]), float(value[2][1]))]
elif nrow == 4:
out = [Gf.Vec4d(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])),
Gf.Vec4d(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1]))]
elif ncol == 3:
if nrow == 2:
out = [Gf.Vec2d(float(value[0][0]), float(value[1][0])),
Gf.Vec2d(float(value[0][1]), float(value[1][1])),
Gf.Vec2d(float(value[0][2]), float(value[1][2]))]
elif nrow == 3:
out = Gf.Matrix3d(0)
out.SetColumn(0, Gf.Vec3d(float(value[0][0]), float(value[0][1]), float(value[0][2])))
out.SetColumn(1, Gf.Vec3d(float(value[1][0]), float(value[1][1]), float(value[1][2])))
out.SetColumn(2, Gf.Vec3d(float(value[2][0]), float(value[2][1]), float(value[2][2])))
elif nrow == 4:
out = [Gf.Vec4d(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])),
Gf.Vec4d(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1])),
Gf.Vec4d(float(value[0][2]), float(value[1][2]), float(value[2][2]), float(value[3][2]))]
elif ncol == 4:
if nrow == 2:
out = [Gf.Vec2d(float(value[0][0]), float(value[1][0])),
Gf.Vec2d(float(value[0][1]), float(value[1][1])),
Gf.Vec2d(float(value[0][2]), float(value[1][2])),
Gf.Vec2d(float(value[0][3]), float(value[1][3]))]
elif nrow == 3:
out = [Gf.Vec3d(float(value[0][0]), float(value[1][0]), float(value[2][0])),
Gf.Vec3d(float(value[0][1]), float(value[1][1]), float(value[2][1])),
Gf.Vec3d(float(value[0][2]), float(value[1][2]), float(value[2][2])),
Gf.Vec3d(float(value[0][3]), float(value[1][3]), float(value[2][3]))]
elif nrow == 4:
out = Gf.Matrix4d(0)
out.SetColumn(0, Gf.Vec4d(float(value[0][0]), float(value[0][1]), float(value[0][2]), float(value[0][3])))
out.SetColumn(1, Gf.Vec4d(float(value[1][0]), float(value[1][1]), float(value[1][2]), float(value[1][3])))
out.SetColumn(2, Gf.Vec4d(float(value[2][0]), float(value[2][1]), float(value[2][2]), float(value[2][3])))
out.SetColumn(3, Gf.Vec4d(float(value[3][0]), float(value[3][1]), float(value[3][2]), float(value[3][3])))
return out
def python_array_to_usd_type(value):
array_simple_conversion = {
bool : Sdf.ValueTypeNames.BoolArray,
int : Sdf.ValueTypeNames.IntArray,
# TODO: enum?
# AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_ENUM, SdfValueTypeNames->IntArray);
float : Sdf.ValueTypeNames.FloatArray,
# TODO: double ?
# AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_DOUBLE, SdfValueTypeNames->DoubleArray);
str : Sdf.ValueTypeNames.StringArray,
pymdlsdk.IType.Kind.TK_COLOR : Sdf.ValueTypeNames.Color3fArray
# TODO: AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_STRUCT, SdfValueTypeNames->TokenArray);
# TODO: AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_TEXTURE, SdfValueTypeNames->AssetArray);
}
array_of_vector_conversion = {
numpy.bool_ : { 2 : Sdf.ValueTypeNames.Int2Array,
3 : Sdf.ValueTypeNames.Int3Array,
4 : Sdf.ValueTypeNames.Int4Array },
numpy.int32 : { 2 : Sdf.ValueTypeNames.Int2Array,
3 : Sdf.ValueTypeNames.Int3Array,
4 : Sdf.ValueTypeNames.Int4Array },
numpy.float32 : { 2 : Sdf.ValueTypeNames.Float2Array,
3 : Sdf.ValueTypeNames.Float3Array,
4 : Sdf.ValueTypeNames.Float4Array },
numpy.float64 : { 2 : Sdf.ValueTypeNames.Double2Array,
3 : Sdf.ValueTypeNames.Double3Array,
4 : Sdf.ValueTypeNames.Double4Array }
}
# // Array of matrix
# numpyType Column Row OutType
array_of_matrix = \
{ numpy.float32 : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2dArray,
3 : Sdf.ValueTypeNames.FloatArray,
4 : Sdf.ValueTypeNames.FloatArray},
3 : { 2 : Sdf.ValueTypeNames.FloatArray,
3 : Sdf.ValueTypeNames.Matrix3dArray,
4 : Sdf.ValueTypeNames.FloatArray},
4 : { 2 : Sdf.ValueTypeNames.FloatArray,
3 : Sdf.ValueTypeNames.FloatArray,
4 : Sdf.ValueTypeNames.Matrix4dArray }},
numpy.float64 : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2dArray,
3 : Sdf.ValueTypeNames.DoubleArray,
4 : Sdf.ValueTypeNames.DoubleArray},
3 : { 2 : Sdf.ValueTypeNames.DoubleArray,
3 : Sdf.ValueTypeNames.Matrix3dArray,
4 : Sdf.ValueTypeNames.DoubleArray},
4 : { 2 : Sdf.ValueTypeNames.DoubleArray,
3 : Sdf.ValueTypeNames.DoubleArray,
4 : Sdf.ValueTypeNames.Matrix4dArray }}}
dtype = type(value[0])
if dtype in array_simple_conversion:
return array_simple_conversion[dtype]
elif dtype == numpy.ndarray:
shape = value[0].shape
# Array
if len(shape) > 1 and shape[1] > 1:
# Array of matrices
elemtype = type(value[0][0][0])
if elemtype in array_of_matrix:
if shape[1] in array_of_matrix[elemtype]:
if shape[0] in array_of_matrix[elemtype][shape[1]]:
return array_of_matrix[elemtype][shape[1]][shape[0]]
elif type(value[0][0]) == numpy.ndarray:
# Array of vectors
etype = type(value[0][0][0])
size = len(value[0])
if etype in array_of_vector_conversion:
if size in array_of_vector_conversion[etype]:
return array_of_vector_conversion[etype][size]
else:
print("Array of vector type not supported for type/size: {}/{}".format(etype, size))
elif len(value[0]) == 3:
# Assume this is a color
return array_simple_conversion[pymdlsdk.IType.Kind.TK_COLOR]
else:
print("Array type not supported for type/shape: {}/{}".format(dtype, shape))
else:
print("Type not supported for type: {}".format(dtype))
def python_array_to_usd_value(value):
dtype = type(value[0])
out = None
if dtype == bool or \
dtype == int or \
dtype == float or \
dtype == str:
return value
elif dtype == numpy.ndarray:
# Array
shape = value[0].shape
if len(shape) > 1 and shape[1] > 1:
# Array of matrices
elemtype = type(value[0][0][0])
nrow = shape[0]
ncol = shape[1]
out = None
arraysize = len(value)
if ncol == nrow:
if ncol == 2:
mattype = Gf.Matrix2d
if ncol == 3:
mattype = Gf.Matrix3d
if ncol == 4:
mattype = Gf.Matrix4d
out = []
for i in range(arraysize):
mat = mattype(0)
for c in range(ncol):
row = []
for r in range(nrow):
row.append(float(value[i][c][r]))
mat.SetColumn(c, row)
out.append(mat)
else:
if elemtype == numpy.float32:
otype = float
elif elemtype == numpy.float64:
otype = numpy.float64
out = []
for i in range(arraysize):
for c in range(ncol):
for r in range(nrow):
out.append(otype(value[i][r][c]))
elif type(value[0][0]) == numpy.ndarray:
# Array of vectors
etype = type(value[0][0][0])
size = len(value)
out = []
if etype == numpy.bool_ or \
etype == numpy.int32:
otype = int
elif etype == numpy.float32:
otype = float
elif etype == numpy.float64:
otype = numpy.float64
itemsize = len(value[0])
for i in range(size):
ll = []
for j in range(itemsize):
ll.append(otype(value[i][j]))
out.append(ll)
elif len(value[0]) == 3:
# Assume this is a color
size = len(value)
out = []
for i in range(size):
out.append([value[0][0], value[0][1], value[0][2]])
return out
def custom_data_from_python_array(value):
# type = dict({"mdl":{"type" : "array of matrix"}})
out = dict()
dtype = type(value[0])
arraysize = len(value)
if dtype == numpy.ndarray:
# Array
shape = value[0].shape
if len(shape) > 1 and shape[1] > 1:
# Array of matrices
elemtype = type(value[0][0][0])
nrow = shape[0]
ncol = shape[1]
elemtype = type(value[0][0][0])
if ncol != nrow or elemtype == numpy.float32:
# Non square matrices
typename = ""
if elemtype == numpy.float32:
typename = "float"
elif elemtype == numpy.float64:
typename = "double"
out = dict({"mdl":{"type" : "{}{}x{}[{}]".format(typename, ncol, nrow, arraysize)}})
elif type(value[0][0]) == numpy.ndarray:
# Array of vectors
etype = type(value[0][0][0])
if etype == numpy.bool_:
itemsize = len(value[0])
out = dict({"mdl":{"type" : "bool{}[{}]".format(itemsize, arraysize)}})
return out
def mdl_type_to_usd_type(val : pymdl.ArgumentConstant):
if not val:
return None
kind = val.type.kind
if kind in MdlITypeKindToUSD:
return MdlITypeKindToUSD[kind]
else:
# A bit more work is required to derive the type
if kind == pymdlsdk.IType.Kind.TK_VECTOR:
return python_vector_to_usd_type(val.value.dtype, val.value.size)
elif kind == pymdlsdk.IType.Kind.TK_MATRIX:
return python_matrix_to_usd_type(val.value.dtype, val.value.shape[0], val.value.shape[1])
elif kind == pymdlsdk.IType.Kind.TK_ARRAY:
return python_array_to_usd_type(val.value)
return None
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def top(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
# When converting from MDL to USD user can choose the USD output format
# SHADER: A single shader is output at the root of the USD Stage
# MATERIAL: A single material is output at the root of the USD Stage
# MATERIAL_AND_GEOMETRY: Geometry and Material (bound to the geometry) are output in the USD Stage
class OutputType(Enum):
SHADER = 1
MATERIAL = 2
MATERIAL_AND_GEOMETRY = 3
class ConverterContext():
def __init__(self):
self.neuray = None
self.transaction = None
self.stage = None
self.modules = Stack()
self.usd_materials = Stack()
self.parameter_names = Stack()
self.usd_shaders = Stack()
self.custom_data = Stack()
self.type_annotation = True
self.mdl_to_usd_output = OutputType.SHADER
self.mdl_to_usd_output_material_nested_shaders = False # Nested/deep or flat shader tree
self.ov_neuray = None
GetUniqueNameInStage.s_uniqueID = 0 # Reset the unique name counter to get same output between 2 runs
def enable_type_annotation(self):
self.type_annotation = True
def disable_type_annotation(self):
self.type_annotation = False
def is_type_annotation_enabled(self):
return self.type_annotation == True
def set_neuray(self, neuray):
self.neuray = neuray
def set_transaction(self, transaction):
self.transaction = transaction
def set_stage(self, stage):
self.stage = stage
def push_module(self, module):
self.modules.push(module)
def pop_module(self):
return self.modules.pop()
def current_module(self):
return self.modules.top()
def push_usd_material(self, material):
self.usd_materials.push(material)
def pop_usd_material(self):
return self.usd_materials.pop()
def current_usd_material(self):
return self.usd_materials.top()
def push_parameter_name(self, parm):
self.parameter_names.push(parm)
def pop_parameter_name(self):
return self.parameter_names.pop()
def current_parameter_name(self):
return self.parameter_names.top()
def push_usd_shader(self, shader):
self.usd_shaders.push(shader)
def pop_usd_shader(self):
return self.usd_shaders.pop()
def current_usd_shader(self):
return self.usd_shaders.top()
def push_custom_data(self, custom_data):
self.custom_data.push(custom_data)
def pop_custom_data(self):
return self.custom_data.pop()
def current_custom_data(self):
return self.custom_data.top()
# Example: 'mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase'
# Return: 'OmniSurface/OmniSurfaceBase.mdl'
def prototype_to_source_asset(prototype):
source_asset = prototype
if source_asset[:5] == "mdl::":
source_asset = source_asset[3:] # Remove leading "mdl"
if source_asset[:2] == "::":
source_asset = source_asset[2:] # Remove leading "::"
ll = source_asset.split("::")
source_asset = '/'.join(ll[0:-1]) # Drop last part which is material name
source_asset = source_asset + ".mdl" # Append ".mdl" extension
return source_asset
def module_mdl_name_to_source_asset(context, module_mdl_name):
# Hack to convert builtin module functions
if module_mdl_name == '::scene' or module_mdl_name == '::state':
return 'nvidia/support_definitions.mdl'
unmangle_helper = UnmangleAndFixMDLSearchPath(context)
(isMangled, wasSuccess, newmodule_mdl_name) = unmangle_helper.unmangle_mdl_module(module_mdl_name)
if wasSuccess and newmodule_mdl_name != module_mdl_name:
return newmodule_mdl_name + '.mdl'
if isMangled and not wasSuccess:
# Better return empty asset than garbage asset
return ''
source_asset = module_mdl_name
if source_asset[:5] == "mdl::":
source_asset = source_asset[3:] # Remove leading "mdl"
if source_asset[:2] == "::":
source_asset = source_asset[2:] # Remove leading "::"
source_asset = source_asset.replace("::", "/") # Replace "::" with "/"
source_asset = source_asset + ".mdl" # Append ".mdl" extension
return source_asset
def source_asset_to_module_name(source_asset, context):
module_name = source_asset
module_name = os.path.normpath(module_name)
if os.path.isabs(module_name):
# Absolute path, try to find a mathing search path and remove it
with context.neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg:
if cfg.is_valid_interface():
for i in range(cfg.get_mdl_paths_length()):
sp = cfg.get_mdl_path(i)
sp = os.path.normpath(sp.get_c_str())
if module_name.find(sp) == 0:
module_name = module_name[len(sp):]
break
# Split path
ll = module_name.split(os.sep)
# Concat path using '::' separator
module_name = "::".join(ll)
if not module_name[0:2] == "::":
# Prepend '::'
module_name = "::" + module_name
if module_name[-4:] == ".mdl":
# Remove '.mdl' extension
module_name = module_name[0:-4]
return module_name
def db_name_to_prim_name(dbname):
name = dbname
name = name.split("(")[0] # Remove arguments
name = name.split("::")[-1] # Remove package, module
name = name.replace(".", "_") # Replace '.'
return name
def mdl_name_to_sub_identifier(mdl_name, fct_call=False):
sub_id = mdl_name
if sub_id[:5] == "mdl::":
sub_id = sub_id[3:] # Remove leading "mdl"
# split the identifier from the arguments
names = sub_id.split("(")
# keep only the last name from the identifier
sub_id = names[0].split("::")[-1]
if fct_call:
# concat with args
if len(names) > 1:
sub_id = sub_id + "(" + names[1]
return sub_id
# Return a unique SdfPath for the current stage
class GetUniqueNameInStage:
s_uniqueID = 0
@staticmethod
def get(stage, path):
unique_path = path
while stage.GetPrimAtPath(unique_path).IsValid():
unique_path = Sdf.Path(str(path) + str(GetUniqueNameInStage.s_uniqueID))
GetUniqueNameInStage.s_uniqueID += 1
return unique_path
class GetUniqueName:
s_uniqueID = 0
@staticmethod
def get(transaction, prefix_in):
prefix = prefix_in
if len(prefix)==0:
prefix = "elt"
if not transaction.access_as(pymdlsdk.IInterface, prefix).is_valid_interface():
return prefix
while True:
prefix = prefix_in + "_" + str(GetUniqueName.s_uniqueID)
GetUniqueName.s_uniqueID += 1
if not transaction.access_as(pymdlsdk.IInterface, prefix).is_valid_interface():
return prefix
def create_stage(args):
stageName = args.options["OUT"]
stage = Usd.Stage.CreateNew(stageName)
stage.SetMetadata('comment', 'MDL to USD conversion')
return stage
def load_stage(stageName):
stage = None
try:
stage = Usd.Stage.Open(stageName)
except:
print("Error:\tFailed to load stage: {}".format(stageName))
return stage
def save_stage(stage):
stage.GetRootLayer().Save()
def export_stage(stage, filename):
stage.GetRootLayer().Export(filename)
def material_to_stage_output_material(context, function: pymdl.FunctionDefinition):
return material_to_stage_output_material_and_geo(context, function, want_geometry = False)
def material_to_stage_output_material_and_geo(context, function: pymdl.FunctionDefinition, want_geometry = True):
neuray = context.neuray
transaction = context.transaction
stage = context.stage
db_name = function.dbName
materialName = db_name_to_prim_name(db_name)
# Start at root
rootPath = Sdf.Path('/')
spherePrim = None
if want_geometry:
xform = UsdGeom.Xform.Define(stage,"/World")
# Add geometry
spherePrim = UsdGeom.Sphere.Define(stage, xform.GetPath().AppendChild('Geom'))
model = Usd.ModelAPI(xform)
model.SetKind(Kind.Tokens.component)
# Create Looks scope
# Scope is the simplest grouping primitive...
scope = UsdGeom.Scope.Define(stage, xform.GetPath().AppendChild('Looks'))
rootPath = scope.GetPath()
model = Usd.ModelAPI(scope)
model.SetKind(Kind.Tokens.model)
material = None
# Create material
material = UsdShade.Material.Define(stage, rootPath.AppendChild(materialName))
if spherePrim != None:
# Bind material to geometry
UsdShade.MaterialBindingAPI(spherePrim).Bind(material)
# Create surface shader
surfaceShader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("Shader"))
# Create surface shader output port
outPort = surfaceShader.CreateOutput('out', Sdf.ValueTypeNames.Token)
# Create material output port
terminal = material.CreateOutput('mdl:surface', Sdf.ValueTypeNames.Token)
# Connect material output to shader output
terminal.ConnectToSource(outPort)
terminal = material.CreateOutput('mdl:volume', Sdf.ValueTypeNames.Token)
terminal.ConnectToSource(outPort)
terminal = material.CreateOutput('mdl:displacement', Sdf.ValueTypeNames.Token)
terminal.ConnectToSource(outPort)
# Determine module asset
module_interface : pymdl.Module
module_interface = context.current_module()
module = module_interface.mdlName
source_asset = module_mdl_name_to_source_asset(context, module)
# Example:
# uniform token info:implementationSource = "sourceAsset"
# uniform asset info:mdl:sourceAsset = @nvidia/core_definitions.mdl@
# uniform token info:mdl:sourceAsset:subIdentifier = "::nvidia::core_definitions::flex_material"
surfaceShader.GetImplementationSourceAttr().Set("sourceAsset")
surfaceShader.SetSourceAsset(Sdf.AssetPath(source_asset), "mdl")
node_identifier = mdl_name_to_sub_identifier(db_name)
surfaceShader.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier)
context.stage.SetDefaultPrim(material.GetPrim())
context.push_usd_material(material)
context.push_usd_shader(surfaceShader)
context.push_custom_data(dict())
definition_to_stage(context, function)
# Annotations
anno_dict = get_annotations_dict(context, function)
add_annotations_to_prim(surfaceShader.GetPrim(), anno_dict)
add_annotations_to_node(surfaceShader, anno_dict)
context.pop_custom_data()
context.pop_usd_shader()
context.pop_usd_material()
def material_to_stage_output_shader(context, function: pymdl.FunctionDefinition):
neuray = context.neuray
transaction = context.transaction
stage = context.stage
db_name = function.dbName
materialName = db_name_to_prim_name(db_name)
# Start at root
rootPath = Sdf.Path('/')
material = UsdShade.Shader.Define(stage, rootPath.AppendChild(materialName))
# Create output port
outPort = material.CreateOutput('out', Sdf.ValueTypeNames.Token).SetRenderType("material")
# Determine module asset
module_interface : pymdl.Module
module_interface = context.current_module()
module = module_interface.mdlName
source_asset = module_mdl_name_to_source_asset(context, module)
# Example:
# uniform token info:implementationSource = "sourceAsset"
# uniform asset info:mdl:sourceAsset = @nvidia/core_definitions.mdl@
# uniform token info:mdl:sourceAsset:subIdentifier = "::nvidia::core_definitions::flex_material"
material.GetImplementationSourceAttr().Set("sourceAsset")
material.SetSourceAsset(Sdf.AssetPath(source_asset), "mdl")
node_identifier = mdl_name_to_sub_identifier(db_name)
material.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier)
context.stage.SetDefaultPrim(material.GetPrim())
context.push_usd_material(material)
context.push_usd_shader(material)
context.push_custom_data(dict())
definition_to_stage(context, function)
# Annotations
anno_dict = get_annotations_dict(context, function)
add_annotations_to_prim(material.GetPrim(), anno_dict)
add_annotations_to_node(material, anno_dict)
context.pop_custom_data()
context.pop_usd_shader()
context.pop_usd_material()
def material_to_stage(context, function: pymdl.FunctionDefinition):
if context.mdl_to_usd_output == OutputType.SHADER:
return material_to_stage_output_shader(context, function)
elif context.mdl_to_usd_output == OutputType.MATERIAL:
return material_to_stage_output_material(context, function)
elif context.mdl_to_usd_output == OutputType.MATERIAL_AND_GEOMETRY:
return material_to_stage_output_material_and_geo(context, function)
def module_to_stage(context, module: pymdl.Module):
context.push_module(module)
for simple_name, overloads in module.functions.items():
f: pymdl.FunctionDefinition
for f in overloads:
material_to_stage(context, f)
anno_dict = get_annotations_dict(context, module)
add_annotations_to_stage(context, context.stage, anno_dict)
context.pop_module()
def mdl_prim_to_usd(context : ConverterContext, stage: Usd.Stage, prim: Usd.Prim, createNewMaterial: bool = False):
inst_name = None
mdl_entity = None
mdl_entity_snapshot = None
if context.ov_neuray == None:
return
# Get the shader prim from Material
shader_prim = get_shader_prim(context.stage, prim.GetPath())
mdl_entity = context.ov_neuray.createMdlEntity(shader_prim.GetPath().pathString)
mdl_entity_snapshot = None
if not mdl_entity.getMdlModule() == None:
mdl_entity_snapshot = context.ov_neuray.createMdlEntitySnapshot(mdl_entity)
inst_name = mdl_entity_snapshot.dbName
source_asset = Sdf.AssetPath("")
shader = UsdShade.Shader(shader_prim)
if shader:
imp_source = shader.GetImplementationSourceAttr().Get()
if imp_source == "sourceAsset":
# Retrieve module name
source_asset = shader.GetSourceAsset("mdl")
material = UsdShade.Material(prim)
if createNewMaterial:
rootPath = Sdf.Path(prim.GetPath().GetParentPath())
# Create material
materialName = prim.GetName() + "_converted"
# Find unique name
materialName = GetUniqueNameInStage.get(stage, rootPath.AppendChild(materialName))
material = UsdShade.Material.Define(stage, materialName)
# Create surface shader
surfaceShader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild(shader_prim.GetName()))
# Create output port
outPort = surfaceShader.CreateOutput('out', Sdf.ValueTypeNames.Token)
# Create material output port
terminal = material.CreateOutput('mdl:surface', Sdf.ValueTypeNames.Token)
# Connect material output to shader output
terminal.ConnectToSource(outPort)
terminal = material.CreateOutput('mdl:volume', Sdf.ValueTypeNames.Token)
terminal.ConnectToSource(outPort)
terminal = material.CreateOutput('mdl:displacement', Sdf.ValueTypeNames.Token)
terminal.ConnectToSource(outPort)
context.push_usd_material(material)
context.push_usd_shader(surfaceShader)
context.push_custom_data(dict())
fctCall = pymdl.FunctionCall._fetchFromDb(context.transaction, inst_name)
handle_function_call(context, fctCall)
context.pop_usd_material()
context.pop_usd_shader()
context.pop_custom_data()
if not mdl_entity_snapshot == None:
context.ov_neuray.destroyMdlEntitySnapshot(mdl_entity_snapshot)
if not mdl_entity == None:
context.ov_neuray.destroyMdlEntity(mdl_entity)
#--------------------------------------------------------------------------------------------------
# Utilities
#--------------------------------------------------------------------------------------------------
def get_examples_search_path():
"""Try to get the example search path or returns 'mdl' sub folder of the current directory if it failed."""
# get the environment variable that is used in all MDL SDK examples
example_sp = os.getenv('MDL_SAMPLES_ROOT')
# fall back to a path relative to this script file
if example_sp == None or not os.path.exists(example_sp):
example_sp = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..')
# go down into the mdl folder
example_sp = os.path.join(example_sp, 'mdl')
# fall back to the current folder
if not os.path.exists(example_sp):
example_sp = './mdl'
return os.path.abspath(example_sp)
#--------------------------------------------------------------------------------------------------
# MDL Python Example
#--------------------------------------------------------------------------------------------------
# return usd_value, connection, usd_type
def get_usd_value_and_type(context, val : pymdl.ArgumentConstant):
if not val:
return (None, None, None)
kind = val.type.kind
usd_type = mdl_type_to_usd_type(val)
if usd_type == None:
return (None, None, None)
usd_val = None
connection = None
# -------------------------------- Atomic ---------------------------------
if kind == pymdlsdk.IType.Kind.TK_BOOL or \
kind == pymdlsdk.IType.Kind.TK_INT or \
kind == pymdlsdk.IType.Kind.TK_FLOAT or \
kind == pymdlsdk.IType.Kind.TK_DOUBLE or \
kind == pymdlsdk.IType.Kind.TK_STRING:
usd_val = val.value
elif kind == pymdlsdk.IType.Kind.TK_ENUM:
usd_val = val.value[1]
# -------------------------------- Compound ---------------------------------
elif kind == pymdlsdk.IType.Kind.TK_VECTOR:
usd_val = python_vector_to_usd_value(val.value)
if context.is_type_annotation_enabled():
custom_data = custom_data_from_python_vector(val.value)
context.current_custom_data().update(custom_data)
elif kind == pymdlsdk.IType.Kind.TK_MATRIX:
usd_val = python_matrix_to_usd_value(val.value)
elif kind == pymdlsdk.IType.Kind.TK_COLOR:
usd_val = Gf.Vec3f(val.value[0], val.value[1], val.value[2])
elif kind == pymdlsdk.IType.Kind.TK_ARRAY:
usd_val = python_array_to_usd_value(val.value)
if context.is_type_annotation_enabled():
custom_data = custom_data_from_python_array(val.value)
context.current_custom_data().update(custom_data)
elif kind == pymdlsdk.IType.Kind.TK_STRUCT:
parm_name = context.current_parameter_name()
shader = context.current_usd_shader()
usd_mat = context.current_usd_shader()
new_shader = UsdShade.Shader.Define(context.stage,
GetUniqueNameInStage.get(context.stage, usd_mat.GetPath().AppendChild("ShaderAttachement_" + parm_name)))
connection = new_shader.CreateOutput('out', Sdf.ValueTypeNames.Token)
context.push_usd_shader(new_shader)
for item in val.value:
field_name = item
context.push_parameter_name(field_name)
context.push_custom_data(dict())
v = val.value[item]
handle_value(context, v)
context.pop_custom_data()
context.pop_parameter_name()
context.pop_usd_shader()
# -------------------------------- Resource ---------------------------------
elif kind == pymdlsdk.IType.Kind.TK_TEXTURE:
ftex = val.value[0]
gamma = val.value[1]
with context.transaction.access_as(pymdlsdk.ITexture, ftex) as text:
if text.is_valid_interface():
with context.transaction.access_as(pymdlsdk.IImage, text.get_image()) as image:
if image.is_valid_interface():
usd_val = image.get_filename(0,0)
elif kind == pymdlsdk.IType.Kind.TK_LIGHT_PROFILE:
v = val.value
with context.transaction.access_as(pymdlsdk.ILightprofile, v) as obj:
if obj.is_valid_interface():
usd_val = obj.get_filename()
elif kind == pymdlsdk.IType.Kind.TK_BSDF_MEASUREMENT:
v = val.value
with context.transaction.access_as(pymdlsdk.IBsdf_measurement, v) as obj:
if obj.is_valid_interface():
usd_val = obj.get_filename()
else:
print("Error: Unknown IValue Kind for parm/kind: {}/{}".format(context.current_parameter_name(), kind))
return (usd_val, connection, usd_type)
def dict_of_dicts_merge(x, y):
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
z[key] = dict_of_dicts_merge(x[key], y[key])
for key in x.keys() - overlapping_keys:
z[key] = deepcopy(x[key])
for key in y.keys() - overlapping_keys:
z[key] = deepcopy(y[key])
return z
# Return a dictionary of pair [string, value]
#
def get_annotations_dict(context, val):
main_dict = dict()
# We do not want to collect type annotations during conversion of annotation expressions
# Otherwise the type for the annotations is mized with the parameter annotations
context.disable_type_annotation()
try:
# Handle annotations
if val.annotations:
anno_dict = dict()
# print(f" Annotations:")
anno: pymdl.Annotation
for anno in val.annotations:
# print(f" - Simple Name: {anno.simpleName}")
# print(f" Qualified Name: {anno.name}")
# // Special case of annotations without expressions, e.g. ::anno::hidden()
# // We create a boolean VtValue and set it to true
# // Annotation:
# // ::anno::hidden()
# // becomes:
# // bool "::anno::hidden()" = 1
if len(anno.arguments.items()) == 0:
usd_value = True
usd_type = bool
anno_dict[anno.name] = usd_value
arg: pymdl.val
for arg_name, arg in anno.arguments.items():
# print(f" ({arg.type.kind}) {arg_name}: {arg.value}")
(usd_value, connection, usd_type) = get_usd_value_and_type(context, arg)
# print(f" ({usd_value}) {connection}: {usd_type}")
if usd_value != None and usd_type != None:
anno_dict[anno.name+"::"+arg_name] = usd_value
if len(anno_dict) > 0:
main_dict.update(dict({"mdl" : {"annotations": anno_dict}}))
# Handle special values, concat (possibly empty) context dictionary
main_dict = dict_of_dicts_merge(main_dict, context.current_custom_data())
except Exception as e:
print("Error while retrieving annotations")
finally:
context.enable_type_annotation()
return main_dict
def add_annotations_to_stage(context, stage, anno_dict):
try:
if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]:
stage.SetMetadata('comment', 'Conversion from MDL module: ' + anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"])
else:
if context.current_module() != None:
stage.SetMetadata('comment', 'Conversion from MDL module: ' + context.current_module().mdlName)
# TODO: Add more annotations to Stage as Metadata: version, ...
except:
pass
def add_annotations_to_node(node, anno_dict):
# display name, group and description
#
# sdrMetadata = {
# dictionary ui = {
# string displayGroup = "float2_parm group"
# }
# }
#
if "mdl" in anno_dict and "annotations" in anno_dict["mdl"]:
for anno, key in ( \
("::anno::display_name(string)::name", "ui:displayName"), \
("::anno::in_group(string)::group", "ui:displayGroup"), \
("::anno::in_group(string,string)::group", "ui:displayGroup"), \
("::anno::in_group(string,string,string)::group", "ui:displayGroup"), \
("::anno::description(string)::description", "ui:description")):
if anno in anno_dict["mdl"]["annotations"]:
node.SetSdrMetadataByKey( key, anno_dict["mdl"]["annotations"][anno])
#
# See Also:
#
# ui = Usd.SceneGraphPrimAPI(minput.GetAttr())
# a = ui.CreateDisplayNameAttr()
#
# TODO: Could also use?
#
# minput.GetAttr().SetDisplayName("FOOBAR")
# minput.GetAttr().SetDisplayGroup("GROUP")
try:
if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]:
node.GetAttr().SetDisplayName(anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"])
for anno in ( \
"::anno::in_group(string)::group", \
"::anno::in_group(string,string)::group", \
"::anno::in_group(string,string,string)::group" \
):
if anno in anno_dict["mdl"]["annotations"]:
node.GetAttr().SetDisplayGroup(anno_dict["mdl"]["annotations"][anno])
except:
pass
def add_annotations_to_prim(usd_prim, anno_dict):
if len(anno_dict) > 0:
cd = usd_prim.GetCustomData()
cd.update(anno_dict)
usd_prim.SetCustomData(cd)
try:
ui = UsdUI.UsdUIBackdrop(usd_prim)
if "::anno::description(string)::description" in anno_dict["mdl"]["annotations"]:
ui.CreateDescriptionAttr(anno_dict["mdl"]["annotations"]["::anno::description(string)::description"])
except:
pass
try:
ui = UsdUI.SceneGraphPrimAPI(usd_prim)
if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]:
ui.CreateDisplayNameAttr(anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"])
for anno in ( \
"::anno::in_group(string)::group", \
"::anno::in_group(string,string)::group", \
"::anno::in_group(string,string,string)::group" \
):
if anno in anno_dict["mdl"]["annotations"]:
ui.CreateDisplayGroupAttr(anno_dict["mdl"]["annotations"][anno])
except:
pass
# Hidden
if "mdl" in anno_dict and "annotations" in anno_dict["mdl"]:
if "::anno::hidden()" in anno_dict["mdl"]["annotations"]:
if anno_dict["mdl"]["annotations"]["::anno::hidden()"]:
usd_prim.SetHidden(True)
def handle_value(context, val : pymdl.ArgumentConstant):
if not val:
return
(usd_value, connection, usd_type) = get_usd_value_and_type(context, val)
if (usd_value == None and connection == None) or usd_type == None:
return
parm_name = context.current_parameter_name()
shader = context.current_usd_shader()
minput = shader.CreateInput(parm_name, usd_type)
if usd_value != None:
minput.Set(usd_value)
else:
minput.ConnectToSource(connection)
anno_dict = get_annotations_dict(context, val)
add_annotations_to_prim(minput.GetAttr(), anno_dict)
add_annotations_to_node(minput, anno_dict)
if val.type.kind == pymdlsdk.IType.Kind.TK_ENUM:
minput.SetRenderType(val.type.symbol)
def handle_expression_constant(context, expression_constant : pymdl.ArgumentConstant):
if not expression_constant:
return
handle_value(context, expression_constant)
def handle_function_call(context, function_call : pymdl.FunctionCall):
if not function_call:
return
# print("* Function definition: {}".format(function_call.functionDefinition))
# print("* MDL function definition: {}".format(function_call.mdlFunctionDefinition))
# print("* Parameter count: {}".format(len(function_call.parameters)))
fdef_db_name = function_call.functionDefinition
function_def = pymdl.FunctionDefinition._fetchFromDb(context.transaction, fdef_db_name)
if not function_def:
return
sourceAsset = module_mdl_name_to_source_asset(context, function_def.mdlModuleName)
node_identifier = mdl_name_to_sub_identifier( function_def.mdlName, True )
# Determine if function definition is variant
fctdef = context.transaction.access_as(pymdlsdk.IFunction_definition, function_def.dbName)
prototype = fctdef.get_prototype()
if prototype:
node_identifier = mdl_name_to_sub_identifier(prototype)
sourceAsset = prototype_to_source_asset(prototype)
shader = context.current_usd_shader()
shader.GetImplementationSourceAttr().Set("sourceAsset")
shader.SetSourceAsset(Sdf.AssetPath(sourceAsset), "mdl")
shader.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier)
for name, argument in function_call.parameters.items():
# print(f"* Name: {name}")
# print(f" Type: {argument.type.kind}")
# if argument.type.symbol:
# print(f" Type Symbol: {argument.type.symbol}")
# print(f" Value: {argument.value}")
# print(f" Value is Constant: {isinstance(argument, pymdl.ArgumentConstant)}")
# print(f" Value is Attachment: {isinstance(argument, pymdl.ArgumentCall)}")
context.push_parameter_name(name)
context.push_custom_data(dict())
handle_expression(context, argument)
context.pop_custom_data()
context.pop_parameter_name()
def handle_material_instance(context, minst):
if not minst.is_valid_interface():
return
pass
def handle_expression_call(context, expression_call : pymdl.ArgumentCall):
if not expression_call:
return
neuray = context.neuray
transaction = context.transaction
# NEW
fcall : pymdl.FunctionCall
fcall = pymdl.FunctionCall._fetchFromDb(transaction, expression_call.value)
if fcall:
handle_function_call(context, fcall)
return
# TODO?
# minst = transaction.access_as(pymdlsdk.IFunction_call, expression_call.get_call())
# if minst.is_valid_interface():
# handle_material_instance(context, minst)
def handle_expression_parameter(context, expression_parameter):
if not expression_parameter.is_valid_interface():
return
pass
def handle_expression_direct_call(context, expression_direct_call):
if not expression_direct_call.is_valid_interface():
return
pass
def handle_expression_temporary(context, expression_temporary):
if not expression_temporary.is_valid_interface():
return
pass
def handle_expression(context, argument : pymdl.Argument):
if not argument:
return
if isinstance(argument, pymdl.ArgumentConstant):
# A constant expression. See #mi::neuraylib::IExpression_constant.
# argument_cst = pymdl.ArgumentConstant(argument) # FAILS
argument_cst : pymdl.ArgumentConstant
argument_cst = argument
handle_expression_constant(context, argument_cst)
elif isinstance(argument, pymdl.ArgumentCall):
# Need to:
# - create a parameter of the given type
# - create a new shader in the current material
# - Connect the parameter to the new shader
# - Evaluate the expression
expression_kind = argument.type.kind
# If the exact return type can not be determined (e.g. vectors, where to get the size?) set the parm type to Token by default
parm_type = Sdf.ValueTypeNames.Token
parm_name = context.current_parameter_name()
if expression_kind in MdlITypeKindToUSD:
parm_type = MdlITypeKindToUSD[expression_kind]
else:
print("Warning: Indirect call expression parm/kind : {}/{}".format(parm_name,argument.type.kind))
# - create a parameter of the given type
usd_shader = context.current_usd_shader()
minput = usd_shader.CreateInput(parm_name, parm_type)
# By default shaders are not nested, they are created immediately under the material
usd_mat = context.current_usd_material()
if context.mdl_to_usd_output_material_nested_shaders == True:
# Nested shaders case, create under current shader
usd_mat = context.current_usd_shader()
# - create a new shader in thecurrent material (or current shader in the nested case)
shName = GetUniqueNameInStage.get(context.stage, usd_mat.GetPath().AppendChild(parm_name))
shader = UsdShade.Shader.Define(context.stage, shName)
outPort = shader.CreateOutput('out', Sdf.ValueTypeNames.Token)
# - Connect the parameter to the new shader
minput.ConnectToSource(outPort)
context.push_usd_shader(shader)
# - Evaluate the expression
argument_call : pymdl.ArgumentCall
argument_call = argument
handle_expression_call(context, argument_call)
# Annotations
anno_dict = get_annotations_dict(context, argument_call)
add_annotations_to_prim(minput.GetAttr(), anno_dict)
add_annotations_to_node(minput, anno_dict)
context.pop_usd_shader()
# TODO
# elif kind == pymdlsdk.IExpression.Kind.EK_PARAMETER:
# # A parameter reference expression. See #mi::neuraylib::IExpression_parameter.
# # handle_expression_parameter(context, expression.get_interface(pymdlsdk.IExpression_parameter))
# pass
# elif kind == pymdlsdk.IExpression.Kind.EK_DIRECT_CALL:
# # A direct call expression. See #mi::neuraylib::IExpression_direct_call.
# # handle_expression_direct_call(context, expression.get_interface(pymdlsdk.IExpression_direct_call))
# pass
# elif kind == pymdlsdk.IExpression.Kind.EK_TEMPORARY:
# # A temporary reference expression. See #mi::neuraylib::IExpression_temporary.
# # handle_expression_temporary(context, expression.get_interface(pymdlsdk.IExpression_temporary))
# pass
def definition_to_stage(context, function: pymdl.FunctionDefinition):
neuray = context.neuray
transaction = context.transaction
argument: pymdl.Argument
for name, argument in function.parameters.items():
# print(f"* Name: {name}")
# print(f" Type: {argument.type.kind}")
# if argument.type.symbol:
# print(f" Type Symbol: {argument.type.symbol}")
# print(f" Value: {argument.value}")
# print(f" Value is Constant: {isinstance(argument, pymdl.ArgumentConstant)}")
# print(f" Value is Attachment: {isinstance(argument, pymdl.ArgumentCall)}")
context.push_parameter_name(name)
context.push_custom_data(dict())
handle_expression(context, argument)
context.pop_custom_data()
context.pop_parameter_name()
def get_db_module_name(neuray, module_mdl_name):
"""Return the db name of the given module."""
module_db_name = None
# When the module is loaded we can access it and all its definitions by accessing the DB
# for that we need to get a the database name of the module using the factory
with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory:
with factory.get_db_module_name(module_mdl_name) as istring:
if istring.is_valid_interface():
module_db_name = istring.get_c_str() # note, even though this name simple and could
# be constructed by string operations, use the
# factory to be save in case of unicode encodings
# and potential upcoming changes in the future
# # shortcut for the function above
# # this chaining is a bit special. In the C++ interface it's not possible without
# # leaking memory. Here we create the smart pointer automatically. However, the IString
# # which is created temporay here is released at the end the `load_module` function, right?
# # This might be unexpected, especially when we rely on the RAII pattern and that
# # objects are disposed at certain points in time (usually before committing a transaction)
# module_db_name_2 = factory.get_db_module_name(module_mdl_name).get_c_str()
# # note, we plan to map compatible types to python. E.g. the IString class may disappear
# return module_db_name_2
return module_db_name
#--------------------------------------------------------------------------------------------------
def get_db_definition_name(neuray, function_mdl_name):
"""Return the db name of the given function definition."""
with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory:
with factory.get_db_definition_name(function_mdl_name) as istring:
if istring.is_valid_interface():
return istring.get_c_str()
return None
#--------------------------------------------------------------------------------------------------
def load_module(context, source_asset):
success = False
module_db_name = ""
if not context.ov_neuray == None:
# We are in OV
if context.transaction:
context.transaction.commit()
context.transaction = None
module_db_name = load_module_from_ov(context.ov_neuray, source_asset.path)
dbScopeName = "rtx_scope"
rtxTransactionReadHandle = context.ov_neuray.createReadingTransaction(dbScopeName)
context.transaction: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(rtxTransactionReadHandle)
module = pymdl.Module._fetchFromDb(context.transaction, module_db_name)
success = (not module == None)
else:
module_mdl_name = source_asset_to_module_name(source_asset.path, context)
success = load_module_from_neuray(context.neuray, context.transaction, module_mdl_name)
if success:
module_db_name = get_db_module_name(context.neuray, module_mdl_name)
module = pymdl.Module._fetchFromDb(context.transaction, module_db_name)
print(f'Loaded module (from omni.mdl.neuraylib={context.ov_neuray} / source asset={source_asset}): {module.filename}')
return (success, module_db_name)
#--------------------------------------------------------------------------------------------------
def load_module_from_neuray(neuray, transaction, module_mdl_name):
"""Load the module given its name.
Returns true if the module is loaded to database"""
with neuray.get_api_component(pymdlsdk.IMdl_impexp_api) as imp_exp:
with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory:
# for illustation, we don't use a `with` block for the `context`, instead we release manually
context = factory.create_execution_context()
res = imp_exp.load_module(transaction, module_mdl_name, context)
context.release()
return res >= 0
#--------------------------------------------------------------------------------------------------
def load_module_from_ov(rtxneuray, module_path):
"""Load the module given its name.
Returns rtxModule.dbName if the module is loaded to database, otherwise return empty string """
rtxModule = None
try:
rtxModule = rtxneuray.createMdlModule(module_path)
except:
return ""
return rtxModule.dbName
#--------------------------------------------------------------------------------------------------
class ConvertVectorAndArray:
def create_type_or_value(self, usd_type, factory):
if usd_type in (\
Sdf.ValueTypeNames.Float2,\
Sdf.ValueTypeNames.Float2Array,\
Sdf.ValueTypeNames.Float3,\
Sdf.ValueTypeNames.Float3Array,\
Sdf.ValueTypeNames.Float4,\
Sdf.ValueTypeNames.Float4Array,\
Sdf.ValueTypeNames.FloatArray):
return factory.create_float()
elif usd_type in (\
Sdf.ValueTypeNames.Int2,\
Sdf.ValueTypeNames.Int2Array,\
Sdf.ValueTypeNames.Int3,\
Sdf.ValueTypeNames.Int3Array,\
Sdf.ValueTypeNames.Int4,\
Sdf.ValueTypeNames.Int4Array,\
Sdf.ValueTypeNames.IntArray):
return factory.create_int()
elif usd_type in (\
Sdf.ValueTypeNames.Double2,\
Sdf.ValueTypeNames.Double2Array,\
Sdf.ValueTypeNames.Double3,\
Sdf.ValueTypeNames.Double3Array,\
Sdf.ValueTypeNames.Double4,\
Sdf.ValueTypeNames.Double4Array,\
Sdf.ValueTypeNames.DoubleArray,\
Sdf.ValueTypeNames.Matrix2d,\
Sdf.ValueTypeNames.Matrix3d,\
Sdf.ValueTypeNames.Matrix4d):
return factory.create_double()
elif usd_type == Sdf.ValueTypeNames.BoolArray:
return factory.create_bool()
elif usd_type == Sdf.ValueTypeNames.StringArray:
return factory.create_string()
return None
def convert(self, input, usd_type, type_factory, value_factory, expression_factory):
value = input.Get()
if value == None:
return None
if usd_type == Sdf.ValueTypeNames.Color3fArray:
value = input.Get()
array_size = len(value)
vector_size = len(value[0])
assert(vector_size == 3)
atomic_type = type_factory.create_color()
if not atomic_type.is_valid_interface():
return None
array_type = type_factory.create_immediate_sized_array(atomic_type, array_size)
mdl_value_array = value_factory.create_array(array_type)
mdl_value_array.set_size(array_size)
for index in range(array_size):
usd_value = value[index]
atomic_value = value_factory.create_color(usd_value[0],usd_value[1],usd_value[2])
mdl_value_array.set_value(index, atomic_value)
expression = expression_factory.create_constant(mdl_value_array)
return expression
elif usd_type == Sdf.ValueTypeNames.StringArray:
value = input.Get()
array_size = len(value)
atomic_type = type_factory.create_string()
if not atomic_type.is_valid_interface():
return None
array_type = type_factory.create_immediate_sized_array(atomic_type, array_size)
mdl_value_array = value_factory.create_array(array_type)
mdl_value_array.set_size(array_size)
for index in range(array_size):
usd_value = value[index]
atomic_value = value_factory.create_string()
atomic_value.set_value(usd_value)
mdl_value_array.set_value(index, atomic_value)
expression = expression_factory.create_constant(mdl_value_array)
return expression
elif numpy.isscalar(value[0]):
# Vector
vector_size = len(value)
type = self.create_type_or_value(usd_type, type_factory)
if not type.is_valid_interface():
return None
vector_type = type_factory.create_vector(type, vector_size)
if not vector_type.is_valid_interface():
return None
mdl_value_vector = value_factory.create_vector(vector_type)
for index in range(vector_size):
usd_value = value[index]
atomic_value = self.create_type_or_value(usd_type, value_factory)
atomic_value.set_value(usd_value)
mdl_value_vector.set_value(index, atomic_value)
expression = expression_factory.create_constant(mdl_value_vector)
return expression
else:
# Array
value = input.Get()
array_size = len(value)
vector_size = len(value[0])
type = self.create_type_or_value(usd_type, type_factory)
if not type.is_valid_interface():
return None
vector_type = type_factory.create_vector(type, vector_size)
if not vector_type.is_valid_interface():
return None
array_type = type_factory.create_immediate_sized_array(vector_type, array_size)
mdl_value_array = value_factory.create_array(array_type)
mdl_value_array.set_size(array_size)
for index in range(array_size):
mdl_value_vector = value_factory.create_vector(vector_type)
usd_value = value[index]
for index2 in range(vector_size):
atomic_value = self.create_type_or_value(usd_type, value_factory)
atomic_value.set_value(usd_value[index2])
mdl_value_vector.set_value(index2, atomic_value)
mdl_value_array.set_value(index, mdl_value_vector)
expression = expression_factory.create_constant(mdl_value_array)
return expression
#--------------------------------------------------------------------------------------------------
def convert_value(context, input, mdl_type):
neuray = context.neuray
transaction = context.transaction
factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
expression_factory = factory.create_expression_factory(transaction)
value_factory = factory.create_value_factory(transaction)
type_factory = factory.create_type_factory(transaction)
name = input.GetBaseName()
type = input.GetTypeName()
# Try to follow the connection
# TODO: not sure this is properly implemented, need further tests
expression = None
if input.HasConnectedSource():
(source, sourceName, sourceType) = input.GetConnectedSource()
if UsdShade.Shader(source):
prim = source.GetPrim()
inst_name = create_material_instance(context, prim.GetPath(), None) # TODO Test None expression_list
if not inst_name == None:
expression = expression_factory.create_call(inst_name)
else:
expression = convert_value(context, UsdShade.Input(input.GetValueProducingAttribute()[0]), mdl_type)
if expression == None:
# No connections
mdlvalue = None
if type == Sdf.ValueTypeNames.Int:
if not input.GetRenderType() == None:
# Handle Enum
tf = factory.create_type_factory(transaction)
if tf and tf.is_valid_interface():
et = tf.create_enum(input.GetRenderType())
if et and et.is_valid_interface():
mdlvalue = value_factory.create_enum(et)
if mdlvalue == None:
# Fallback
mdlvalue = value_factory.create_int()
elif type == Sdf.ValueTypeNames.Float:
mdlvalue = value_factory.create_float()
elif type == Sdf.ValueTypeNames.Bool:
mdlvalue = value_factory.create_bool()
elif type == Sdf.ValueTypeNames.Double:
mdlvalue = value_factory.create_double()
elif type == Sdf.ValueTypeNames.String:
mdlvalue = value_factory.create_string()
elif type == Sdf.ValueTypeNames.Color3f:
value = input.Get()
if value:
mdlvalue = value_factory.create_color(value[0], value[1], value[2])
else:
mdlvalue = value_factory.create_color(0, 0, 0)
expression = expression_factory.create_constant(mdlvalue)
return expression
elif type == Sdf.ValueTypeNames.Asset:
is_texture = mdl_type.get_kind() == pymdlsdk.IType.Kind.TK_TEXTURE
if not is_texture and mdl_type.get_kind() == pymdlsdk.IType.Kind.TK_ALIAS:
type_alias = mdl_type.get_interface(pymdlsdk.IType_alias)
aliased_type = type_alias.get_aliased_type()
is_texture = aliased_type.get_kind() == pymdlsdk.IType.Kind.TK_TEXTURE
if is_texture:
# Shape
# TS_2D = 0,
# TS_3D = 1,
# TS_CUBE = 2,
# TS_PTEX = 3,
# TS_BSDF_DATA = 4,
tt = aliased_type.get_interface(pymdlsdk.IType_texture)
shape = tt.get_shape()
texture_name = GetUniqueName.get(transaction, "texture")
# TODO_PA: Has to specify argc and argv otherwise failure
tex = transaction.create("Texture", 0, None)
transaction.store(tex, texture_name)
value = input.Get()
if value:
texture = transaction.edit_as(pymdlsdk.ITexture, texture_name)
texture.set_image(value.path)
tex_type = type_factory.create_texture(shape)
mdlvalue = value_factory.create_texture(tex_type, texture_name)
if mdlvalue:
expression = expression_factory.create_constant(mdlvalue)
return expression
elif type in (
Sdf.ValueTypeNames.Float2,\
Sdf.ValueTypeNames.Float2Array,\
Sdf.ValueTypeNames.Float3,\
Sdf.ValueTypeNames.Float3Array,\
Sdf.ValueTypeNames.Float4,\
Sdf.ValueTypeNames.Float4Array,\
Sdf.ValueTypeNames.Int2,\
Sdf.ValueTypeNames.Int2Array,\
Sdf.ValueTypeNames.Int3,\
Sdf.ValueTypeNames.Int3Array,\
Sdf.ValueTypeNames.Int4,\
Sdf.ValueTypeNames.Int4Array,\
Sdf.ValueTypeNames.Double2,\
Sdf.ValueTypeNames.Double2Array,\
Sdf.ValueTypeNames.Double3,\
Sdf.ValueTypeNames.Double3Array,\
Sdf.ValueTypeNames.Double4,\
Sdf.ValueTypeNames.Double4Array,\
Sdf.ValueTypeNames.BoolArray,\
Sdf.ValueTypeNames.IntArray,\
Sdf.ValueTypeNames.FloatArray,\
Sdf.ValueTypeNames.DoubleArray,\
Sdf.ValueTypeNames.Color3fArray,\
Sdf.ValueTypeNames.StringArray,\
Sdf.ValueTypeNames.Matrix2d,\
Sdf.ValueTypeNames.Matrix3d,\
Sdf.ValueTypeNames.Matrix4d\
):
converter = ConvertVectorAndArray()
return converter.convert(input, type, type_factory, value_factory, expression_factory)
# TODO Convert structures
# elif type == Sdf.ValueTypeNames.Token:
# pass
else:
print("Error: Unsupported input (parm/type): {}/{}".format(name, type))
if mdlvalue:
value = input.Get()
rtn = 0
if not value == None:
rtn = mdlvalue.set_value(value)
if rtn and not rtn == 0:
print("set_value() error ({}) for (parm/type/value): {}/{}/{}".format(rtn, name, type, value))
expression = expression_factory.create_constant(mdlvalue)
return expression
return expression
#--------------------------------------------------------------------------------------------------
def set_default_value(context, parm_name, definition):
defaults = definition.get_defaults()
i = defaults.get_index(parm_name)
if i != -1:
return defaults.get_expression(i)
return None
#--------------------------------------------------------------------------------------------------
def convert_parameter(context, definition, input):
name = input.GetBaseName()
index = definition.get_parameter_index(name)
if index >= 0:
types = definition.get_parameter_types()
if types:
type = types.get_type(index)
if type:
expression = convert_value(context, input, type)
if expression and expression.is_valid_interface():
return expression
else:
print("Error: Invalid expression for parameter: {}".format(name))
return None
#--------------------------------------------------------------------------------------------------
def edit_instance(transaction, inst_name):
return transaction.edit_as(pymdlsdk.IFunction_call, inst_name)
#--------------------------------------------------------------------------------------------------
def dump_expression_list(expression_list):
print("===== Dump expression list =====")
for index in range(expression_list.get_size()):
name = expression_list.get_name(index)
expr = expression_list.get_expression(index)
print("Expression name/kind/type kind: {} / {} / {}".format(name, expr.get_kind(), expr.get_type().get_kind()))
print("===== End dump expression list =====")
#--------------------------------------------------------------------------------------------------
def dump_parameter_types(fctdef, neuray, transaction):
print("===== Dump parameter types =====")
name = fctdef.get_mdl_simple_name()
print("Function name: {}".format(name))
pt = fctdef.get_parameter_types()
factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
type_factory = factory.create_type_factory(transaction)
print(type_factory.dump(pt).get_c_str())
# for i in range(pt.get_size()):
# t = pt.get_type(i)
# k = t.get_kind()
# if k == pymdlsdk.IType.Kind.TK_ALIAS:
# a = t.get_interface(pymdlsdk.IType_alias)
# k = a.get_aliased_type().get_kind()
# pn = fctdef.get_parameter_name(i)
# print("Parameter name/kind: {} / {}".format(pn, k))
print("===== End dump parameter types =====")
#--------------------------------------------------------------------------------------------------
def convert_parameters(context, prim_path):
definition = get_definition(context, prim_path)
if not definition:
return None
stage = context.stage
prim = get_shader_prim(stage, prim_path)
# expression_list = definition.get_defaults()
# expression_list = pymdlsdk.IExpression_list()
neuray = context.neuray
factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
transaction = context.transaction
expression_factory = factory.create_expression_factory(transaction)
expression_list = expression_factory.create_expression_list()
if prim:
shader = UsdShade.Shader(prim)
if shader:
inputs = shader.GetInputs()
for input in inputs:
name = input.GetBaseName()
expression = convert_parameter(context, definition, input)
if expression:
rtn = expression_list.add_expression(name, expression)
if rtn != 0:
print("Error")
# dump_expression_list(expression_list)
# Handle parameters which are not set
defaults = definition.get_defaults()
parameter_types = definition.get_parameter_types()
value_factory = factory.create_value_factory(transaction)
for i in range(definition.get_parameter_count()):
name = definition.get_parameter_name(i)
if expression_list.get_index(name) == -1:
type = parameter_types.get_type(i)
value = value_factory.create(type)
expr = expression_factory.create_constant(value)
expression_list.add_expression(name, expr)
return expression_list
#--------------------------------------------------------------------------------------------------
def dump_material_instance(context, inst_name):
transaction = context.transaction
inst = edit_instance(transaction, inst_name)
if not inst.is_valid_interface():
return
print("============ MDL Dump =============")
print(inst_name)
print("")
neuray = context.neuray
factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
expression_factory = factory.create_expression_factory(transaction)
count = inst.get_parameter_count()
arguments = inst.get_arguments()
for index in range(count):
argument = arguments.get_expression(index)
name = inst.get_parameter_name(index)
argument_text = expression_factory.dump(argument, name, 1)
print(argument_text.get_c_str())
print("============ MDL Dump =============")
#--------------------------------------------------------------------------------------------------
# Return a shader prim corresponding to the input prim_path.
# If prim_path is a shader, return the corresponding prim.
# If prim_path is a material, return the first shader found in the list of children.
def get_shader_prim(stage, prim_path):
prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
if UsdShade.Shader(prim):
return prim
if UsdShade.Material(prim):
mat = UsdShade.Material(prim)
if mat.GetOutput("mdl:surface") and mat.GetOutput("mdl:surface").HasConnectedSource():
(src, name, t) = mat.GetOutput("mdl:surface").GetConnectedSource()
if UsdShade.Shader(src):
return src.GetPrim()
for prim in prim.GetChildren():
if UsdShade.Shader(prim):
return prim
if UsdShade.NodeGraph(prim):
ng = UsdShade.NodeGraph(prim)
if ng.GetOutput("out") and ng.GetOutput("out").HasConnectedSource():
(src, name, t) = ng.GetOutput("out").GetConnectedSource()
if UsdShade.Shader(src):
return src.GetPrim()
for prim in prim.GetChildren():
if UsdShade.Shader(prim):
return prim
return None
#--------------------------------------------------------------------------------------------------
def get_sub_identifier_from_prim(prim):
sub_id = prim.GetAttribute("info:mdl:sourceAsset:subIdentifier").Get()
if not sub_id:
sub_id = prim.GetAttribute("info:sourceAsset:subIdentifier").Get()
return sub_id
#--------------------------------------------------------------------------------------------------
def get_definition(context, prim_path):
stage = context.stage
prim = get_shader_prim(stage, prim_path)
if not prim:
print("Error:\tCould not find any shader in prim '{}' from stage '{}'".format(prim_path, stage.GetRootLayer().GetDisplayName()))
else:
shader = UsdShade.Shader(prim)
if shader:
imp_source = shader.GetImplementationSourceAttr().Get()
if imp_source == "sourceAsset":
# Retrieve module name
source_asset = shader.GetSourceAsset("mdl")
neuray = context.neuray
(success, module_db_name) = load_module(context, source_asset)
if not success:
print("Error: Failed to load module: {}".format(source_asset))
else:
sub_id = get_sub_identifier_from_prim(prim)
if sub_id:
transaction = context.transaction
module = pymdl.Module._fetchFromDb(transaction, module_db_name)
if module:
fct = find_function(module, sub_id)
if fct:
fctdef = transaction.access_as(pymdlsdk.IFunction_definition, fct.dbName)
if fctdef.is_valid_interface():
return fctdef
return None
#--------------------------------------------------------------------------------------------------
def list_functions(module: pymdl.Module):
for k in module.functions.keys():
for index in range(len(module.functions[k])):
print(module.functions[k][index].mdlName.split("::")[-1])
#--------------------------------------------------------------------------------------------------
# return (module_name, simple_name, parameters)
# module_name without trailing '::'
# e.g. if sub_id = '::nvidia::foo::bar(float,color)'
# module_name = '::nvidia::foo'
# simple_name = 'bar'
# parameters = 'float,color'
def split_function_name(sub_id: str):
module_name = ""
simple_name = ""
parameters = ""
lf = sub_id.split('(')
name_and_module = lf[0]
lm = name_and_module.split('::')
if len(lm) > 1:
module_name = '::'.join(lm[0:-1])
simple_name = lm[-1]
if len(lf) > 1:
parameters = lf[1].split(')')[0]
return (module_name, simple_name, parameters)
#--------------------------------------------------------------------------------------------------
def find_function(module: pymdl.Module, sub_id: str):
(module_name, simple_name, parameters) = split_function_name(sub_id)
if simple_name in module.functions:
if sub_id == simple_name:
# Exact match, no overload, return the function
return module.functions[simple_name][0]
# Access the function definition, enumerate the overloads
for index in range(len(module.functions[simple_name])):
fct = module.functions[simple_name][index]
(candidate_module_name, candidate_simple_name, candidate_parameters) = split_function_name(fct.mdlName)
if parameters == candidate_parameters:
return module.functions[simple_name][index]
print("Error: Function not found in module (function/module): {} / {}".format(sub_id, module.filename))
# list_functions(module)
return None
#--------------------------------------------------------------------------------------------------
def create_material_instance(context, prim_path, expression_list):
stage = context.stage
prim = get_shader_prim(stage, prim_path)
if prim:
shader = UsdShade.Shader(prim)
if shader:
imp_source = shader.GetImplementationSourceAttr().Get()
if imp_source == "sourceAsset":
# Retrieve module name
source_asset = shader.GetSourceAsset("mdl")
neuray = context.neuray
(success, module_db_name) = load_module(context, source_asset)
if success:
sub_id = get_sub_identifier_from_prim(prim)
if sub_id:
transaction = context.transaction
module = pymdl.Module._fetchFromDb(transaction, module_db_name)
if module:
fct = find_function(module, sub_id)
if fct:
with transaction.access_as(pymdlsdk.IFunction_definition, fct.dbName) as fctdef:
inst = None
if fctdef.is_valid_interface():
if expression_list == None:
expression_list = convert_parameters(context, prim_path)
# dump_parameter_types(fctdef, context.neuray, context.transaction)
(inst, ret) = fctdef.create_function_call_with_ret(expression_list)
fname = "create_material_instance()"
error = {0: "Success.",
-1: "An argument for a non-existing parameter was provided in 'arguments'.",
-2: "The type of an argument in 'arguments' does not have the correct type, see #get_parameter_types().",
-3: "A parameter that has no default was not provided with an argument value.",
-4: "The definition can not be instantiated because it is not exported.",
-5: "A parameter type is uniform, but the corresponding argument has a varying return type.",
-6: "An argument expression is not a constant nor a call.",
-8: "One of the parameter types is uniform, but the corresponding argument or default is a \
call expression and the return type of the called function definition is effectively varying since the \
function definition itself is varying.",
-9: "The function definition is invalid due to a module reload, see #is_valid() for diagnostics."}
if inst:
if inst.is_valid_interface():
(module_name, simple_name, parameters) = split_function_name(fct.dbName)
inst_name = module_name + "::" + simple_name + "::converted"
inst_name = GetUniqueName.get(transaction, inst_name)
transaction.store(inst, inst_name)
return inst_name
else:
print("Error: Invalid instance for function: {}".format(fct.mdlSimpleName))
print("{} error {}: {}".format(fname, ret, error[ret]))
if ret == -2:
dump_parameter_types(fctdef, context.neuray, context.transaction)
return None
#--------------------------------------------------------------------------------------------------
async def convert_usd_to_mdl(context, prim_path, output_filename):
inst_name = None
mdl_entity = None
mdl_entity_snapshot = None
if not context.ov_neuray == None:
# We are in OV
# Get the shader prim from Material
shader_prim_path = get_shader_prim(context.stage, prim_path)
if shader_prim_path == None:
print(f"Error: can not access prim: '{prim_path}'")
return None
mdl_entity = context.ov_neuray.createMdlEntity(shader_prim_path.GetPath().pathString)
mdl_entity_snapshot = None
if not mdl_entity.getMdlModule() == None:
mdl_entity_snapshot = context.ov_neuray.createMdlEntitySnapshot(mdl_entity)
inst_name = mdl_entity_snapshot.dbName
else:
print(f"Error: can not access entity: '{prim_path}'")
else:
# Outside of OV, conversion is done here
expression_list = convert_parameters(context, prim_path)
inst_name = create_material_instance(context, prim_path, expression_list)
if inst_name is not None:
dump_material_instance(context, inst_name)
if output_filename:
# we use a temporary folder for resources from the server
with tempfile.TemporaryDirectory() as temp_dir:
success = await save_instance_to_module(context, inst_name, prim_path, temp_dir, output_filename)
if not success:
inst_name = None
if not context.ov_neuray == None:
# We are in OV
if not mdl_entity_snapshot == None:
context.ov_neuray.destroyMdlEntitySnapshot(mdl_entity_snapshot)
if not mdl_entity == None:
context.ov_neuray.destroyMdlEntity(mdl_entity)
return inst_name
#--------------------------------------------------------------------------------------------------
# Split the input string or list of strings using given the split char
# Return a list of strings
def split_list(list_of_strings, split_char):
res = []
if type(list_of_strings) == list:
for s in list_of_strings:
res += s.split(split_char)
else:
res = list_of_strings.split(split_char)
return res
#--------------------------------------------------------------------------------------------------
# Remove all occurences of element from the list
def remove_all_occurences_of_element_from_list(element, alist):
try:
while True:
alist.remove(element)
except:
pass
finally:
return alist
#--------------------------------------------------------------------------------------------------
# Split the input string or list of strings using all the input split chars
def multi_split_list(list_of_strings, list_of_splits):
res = list_of_strings
for split in list_of_splits:
res = split_list(res, split)
return res
#--------------------------------------------------------------------------------------------------
# Identify a line containing an MD import declaration
# From the MDL 1.7 specs:
# import : import qualified_import {, qualified_import} ;
# | [export] using import_path
# import ( * | simple_name {, simple_name} ) ;
def is_import_line(token_list):
if 'import' in token_list:
if token_list[0] == 'import' or token_list[0] == 'export' or token_list[0] == 'using':
return True
return False
#--------------------------------------------------------------------------------------------------
# Construct a set or strings found in an MDL module
# Split the input strings using several separators (' ',';','(', ')')
# if filter_import_lines is set to True, then only process lines beginning with 'import'
def find_tokens(lines, filter_import_lines = False):
all_ids = set()
input_list = lines
if not type(lines) == list:
input_list = [lines]
for l in input_list:
ids = multi_split_list(l, [' ',';','(', ')'])
remove_all_occurences_of_element_from_list('', ids)
if filter_import_lines:
if not is_import_line(ids):
continue
for id in ids:
if not id.find('::') == -1:
tokens = id.split('::')
for t in tokens:
if len(t) > 0:
all_ids.add(t)
return all_ids
#--------------------------------------------------------------------------------------------------
# Find MDL identifier in this line of text if text is an import statement
def find_import(line):
ids = multi_split_list(line, [' ',';','(', ')'])
remove_all_occurences_of_element_from_list('', ids)
if is_import_line(ids):
for id in ids:
if not id.find('::') == -1:
return id
return ''
#--------------------------------------------------------------------------------------------------
# Find MDL identifier in this line of text
def find_identifiers(line):
rtn_identifiers = set()
ids = multi_split_list(line, [' ', ';', '(', ')', ',', '\n'])
remove_all_occurences_of_element_from_list('', ids)
for id in ids:
if not id.find('::') == -1:
rtn_identifiers.add(id)
return rtn_identifiers
#--------------------------------------------------------------------------------------------------
# Substitute source strings with target strings found in the input table in the input lines
# Input lines is a string or list of strings
def replace_tokens(lines, table):
if type(lines) == list:
for i in range(len(lines)):
for k in table.keys():
lines[i] = lines[i].replace(k, table[k])
return lines
else:
for k in table.keys():
lines = lines.replace(k, table[k])
return lines
#--------------------------------------------------------------------------------------------------
# Helper to perfom unmangling on MDL module files and MDL identifiers
# Un-mangling is only done in the framework of OV if an un-mangling routine exists
class Unmangle:
unmangle_routine = None
def __init__(self, context):
if context.ov_neuray != None:
if "_unmangleMdlModulePath" in dir(context.ov_neuray):
self.unmangle_routine = context.ov_neuray._unmangleMdlModulePath
# Un-mangle a single token
# token should not contain any '::'
def _unmangle_token(self, token):
assert(token.find("::") == -1)
# Un-mangle the input token
# Add prefix otherwise unmangling has not effect
unmangled_token = self.unmangle_routine("::" + token)
# Remove any '.mdl' extension from unmangled token
if len(unmangled_token) > 4 and unmangled_token[-4:] == '.mdl':
unmangled_token = unmangled_token[:-4]
unmangled = (unmangled_token != token)
return (unmangled, unmangled_token)
# Build an un-mangling mapping table from the input list of tokens
def build_mapping_table(self, token_list):
table = dict()
for token in token_list:
(unmangled_flag, unmangled_token) = self._unmangle_token(token)
if unmangled_flag:
table[token] = unmangled_token
return table
# Un-mangled an MDL identifier
# Return a tuple (True if unmagling was done, unmangled value)
def unmangle_mdl_identifier(self, source):
if self.unmangle_routine == None:
return (False, source)
token_list = find_tokens(source)
table = self.build_mapping_table(token_list)
unmangled_str = replace_tokens(source, table)
return (unmangled_str != source, unmangled_str)
# Un-mangle an MDL file and create a new un-mangled output file
def unmangle_mdl_file(self, infile, outfile):
if self.unmangle_routine == None:
return
# Only consider 'import' statements
filter_import_lines = True
with open(infile, 'r') as f_in:
lines = f_in.readlines()
token_list = find_tokens(lines, filter_import_lines)
mapping = self.build_mapping_table(token_list)
lines = replace_tokens(lines, mapping)
with open(outfile, 'w') as f_out:
f_out.writelines(lines)
#--------------------------------------------------------------------------------------------------
def parse_alias(pattern, line):
match = pattern.match(line)
if match == None:
return(False, '', '')
alias = match.group("alias")
path_segment = match.group("value")
# print(f"alias: '{alias}' path_segment: '{path_segment}'")
return(True, alias, path_segment)
#--------------------------------------------------------------------------------------------------
# This unmangling class uses MDL search path to trim down MDL identifiers
# It uses also MDL aliases to perform substitutions in the MDL identifier
class UnmangleAndFixMDLSearchPath(Unmangle):
alias_pattern = None
def __init__(self, context):
# compile pattern only once as it is constant
self.alias_pattern = re.compile(r"""\s*using\s* # whitespace, using, whitespace
(?P<alias>.*?) # alias name
\s*=\s* # whitespace, equal, whitespace
\"(?P<value>.*?)\" # value in quotes,
\s*;""", re.VERBOSE) # semicolon, whitespace
# Build MDL search path list
self.mdl_search_paths = list()
with context.neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg:
if cfg.is_valid_interface():
for i in range(cfg.get_mdl_paths_length()):
sp = cfg.get_mdl_path(i)
sp = os.path.normpath(sp.get_c_str())
self.mdl_search_paths.append(sp)
super(UnmangleAndFixMDLSearchPath, self).__init__(context)
# Determine if this line is defining an alias
def __is_alias(self, line):
(is_alias, alias, path_segment) = parse_alias(self.alias_pattern, line)
if is_alias:
return (True, path_segment, alias)
return (False, '', '')
# Determine if this identifier is mangled
def __is_mangled_identifier(self, id):
token_list = id.split("::")
remove_all_occurences_of_element_from_list('', token_list)
for token in token_list:
(unmangled_flag, unmangled_token) = self._unmangle_token(token)
if unmangled_flag:
return unmangled_flag
return False
# Determine if this string contains a mangled identifier
def __get_mangled_identifiers(self, line):
identifiers = find_identifiers(line)
rtn_identifiers = set()
for id in identifiers:
if len(id) > 0:
if self.__is_mangled_identifier(id):
rtn_identifiers.add(id)
return rtn_identifiers
# Build mapping table for a given mangled identifier
# Using the stored MDL search paths and the MDL aliases
def __build_table_from_mangled_id(self, id, aliases, makeRelativeIfFailure: bool = False):
key = ''
value = ''
# unmangle using _unmangleMdlModulePath
if not id.find('::') == 0:
unmangled_id = self.unmangle_routine("::" + id)
else:
unmangled_id = self.unmangle_routine(id)
unmangled_id = re.sub('^file:/', '', unmangled_id)
# Replace aliases
for alias in aliases.keys():
unmangled_id = unmangled_id.replace(aliases[alias], alias)
unmangled_id = os.path.normpath(unmangled_id)
# Remove MDL seach path
search_path_removed = False
mapping_table = dict()
for sp in self.mdl_search_paths:
temp_id = unmangled_id
temp_sp = sp
if platform.system() == 'Windows':
temp_id = unmangled_id.lower()
temp_sp = sp.lower()
# Remove the search path only when the path is found at the head of id
if temp_id.startswith(temp_sp):
unmangled_id = unmangled_id[len(sp):]
search_path_removed = True
break
# Conversion is done only if we did find search path prefix in the identifier
if search_path_removed:
replaced = unmangled_id
replaced = replaced.replace('\\', '::')
replaced = replaced.replace('.mdl::', '::')
what_to_replace = id
mapping_table[what_to_replace] = replaced
return (True, mapping_table)
else:
if makeRelativeIfFailure:
# Turn absolute path to relative
unmangled_id = os.path.basename(unmangled_id)
replaced = unmangled_id
replaced = replaced.replace('.mdl::', '::')
what_to_replace = id
mapping_table[what_to_replace] = replaced
return (True, mapping_table)
return (False, mapping_table)
# Un-mangle an MDL file and create a new un-mangled output file
def unmangle_mdl_file(self, infile, outfile):
if self.unmangle_routine == None:
return
# Read file
mapping_table = dict()
with open(infile, 'r') as f_in:
input_lines = f_in.readlines()
if not type(input_lines) == list:
# handle single line
input_lines = [input_lines]
# aliases mapping table
aliases = dict()
for line in input_lines:
(alias, key, value) = self.__is_alias(line)
if alias:
aliases[key] = value
continue
ids = self.__get_mangled_identifiers(line)
for id in ids:
(success, new_mapping_table) = self.__build_table_from_mangled_id(id, aliases)
if success:
# Mege new mapping in
mapping_table.update(new_mapping_table)
# Replace in file and write out result
with open(infile, 'r') as f_in:
lines = f_in.readlines()
lines = replace_tokens(lines, mapping_table)
with open(outfile, 'w') as f_out:
f_out.writelines(lines)
# Un-mangle an MDL file and create a new un-mangled output file
# Return (is identifier mangled, demangling and removing search path succeeded, un-mangled module name)
def unmangle_mdl_module(self, module):
if self.unmangle_routine == None:
return (False, True, module)
rtn = module
isMangled = self.__is_mangled_identifier(module)
(success, mapping_table) = self.__build_table_from_mangled_id(module, dict(), makeRelativeIfFailure = True)
if success:
rtn = mapping_table[module]
if rtn.find('::') == 0:
rtn = rtn[2:]
rtn = rtn.replace("::", "/")
return (isMangled, success, rtn)
#--------------------------------------------------------------------------------------------------
def is_reserved_word(name : str):
# there will be an API function for this soon
reserved_words = ['annotation', 'auto', 'bool', 'bool2', 'bool3', 'bool4', 'break', 'bsdf', 'bsdf_measurement',
'case', 'cast', 'color', 'const', 'continue', 'default', 'do', 'double', 'double2', 'double2x2',
'double2x3', 'double3', 'double3x2', 'double3x3', 'double3x4', 'double4', 'double4x3', 'double4x4',
'double4x2', 'double2x4', 'edf', 'else', 'enum', 'export', 'false', 'float', 'float2', 'float2x2',
'float2x3', 'float3', 'float3x2', 'float3x3', 'float3x4', 'float4', 'float4x3', 'float4x4',
'float4x2', 'float2x4', 'for', 'hair_bsdf', 'if', 'import', 'in', 'int', 'int2', 'int3', 'int4',
'intensity_mode', 'intensity_power', 'intensity_radiant_exitance', 'let', 'light_profile', 'material',
'material_emission', 'material_geometry', 'material_surface', 'material_volume', 'mdl', 'module',
'package', 'return', 'string', 'struct', 'switch', 'texture_2d', 'texture_3d', 'texture_cube',
'texture_ptex', 'true', 'typedef', 'uniform', 'using', 'varying', 'vdf', 'while', 'catch', 'char',
'class', 'const_cast', 'delete', 'dynamic_cast', 'explicit', 'extern', 'external', 'foreach',
'friend', 'goto', 'graph', 'half', 'half2', 'half2x2', 'half2x3', 'half3', 'half3x2', 'half3x3',
'half3x4', 'half4', 'half4x3', 'half4x4', 'half4x2', 'half2x4', 'inline', 'inout', 'lambda',
'long', 'mutable', 'namespace', 'native', 'new', 'operator', 'out', 'phenomenon', 'private',
'protected', 'public', 'reinterpret_cast', 'sampler', 'shader', 'short', 'signed', 'sizeof',
'static', 'static_cast', 'technique', 'template', 'this', 'throw', 'try', 'typeid', 'typename',
'union', 'unsigned', 'virtual', 'void', 'volatile', 'wchar_t']
return name in reserved_words
#--------------------------------------------------------------------------------------------------
# the db name of a texture is constructed here:
# rendering\include\rtx\neuraylib\NeurayLibUtils.h
# computeSceneIdentifierTexture
def parse_ov_resource_name(texture_db_name : str):
# drop the db prefix
texture_db_name = texture_db_name[5:]
undescore = texture_db_name.rfind('_')
texture_db_name = texture_db_name[:undescore]
undescore = texture_db_name.rfind('_')
return texture_db_name[:undescore]
async def prepare_resources_for_export(transaction : pymdlsdk.ITransaction, inst_name, temp_dir):
functionCall = pymdl.FunctionCall._fetchFromDb(transaction, inst_name)
for name, param in functionCall.parameters.items():
# name
if param.type.kind == pymdlsdk.IType.Kind.TK_TEXTURE and param.value[0] != None:
# print(f"* Name: {name}")
# print(f" Type Kind: {param.type.kind}")
texture_path = parse_ov_resource_name(param.value[0])
# print(f" texture_path: {texture_path}")
# print(f" db_name: {param.value[0]}")
# print(f" gamma: {param.value[1]}")
# special handling for resources on the server
if texture_path.startswith("omniverse:") or \
texture_path.startswith("file:") or \
texture_path.startswith("ftp:") or \
texture_path.startswith("http:") or \
texture_path.startswith("https:"):
basename = os.path.basename(texture_path)
filename, fileext = os.path.splitext(basename)
id = 0
dst_path = os.path.join(temp_dir, basename)
while (os.path.exists(dst_path)):
dst_path = os.path.join(temp_dir, f"{filename}_{id}{fileext}")
id = id + 1
result = await copy_async(texture_path, dst_path)
if not result:
print(f"Cannot copy from {texture_path} to {dst_path}, error code: {result}.")
continue
else:
print(f"Downloaded resource from {texture_path} to {dst_path}. Will be deleted after export.")
# use the resource in the temp folder
texture_path = dst_path
# create a new image
new_image_db_name = "mdlexp::" + texture_path
with transaction.create("Image", 0, None) as new_interface:
with new_interface.get_interface(pymdlsdk.IImage) as new_image:
new_image.reset_file(texture_path)
transaction.store(new_image, new_image_db_name)
transaction.remove(new_image_db_name) # drop after transaction is closed
# assign the image to the texture
# todo make sure the transaction is aborted, we don't want this change visible to other components
with transaction.edit_as(pymdlsdk.ITexture, param.value[0]) as itexture:
itexture.set_image(new_image_db_name)
itexture.set_gamma(param.value[1]) # TODO check if srgb and linear work with floating precission here
if isinstance(param, pymdl.ArgumentCall):
# print(f"* Name: {name}")
# print(f" Type Kind: {param.type.kind}")
# print(f" dbName: {param.value}")
await prepare_resources_for_export(transaction, param.value, temp_dir)
# ExportHelper: Helps to save files to Nucleus server.
# If we want to export a file to Nucleus, this helper:
# 1- creates a temp folder,
# 2- substitutes the original Nucleus folder with the temp folder,
# 3- files are saved/exported to the temp folder,
# 4- when finalize() is called, the content of the temp folder is saved to Nucleus server
# and temp folder is deleted
class ExportHelper:
def __init__(self, out_filename):
self.original_filename = out_filename
self.out_filename = out_filename
self.temp_dir = None
# If out_filename is on Nucleus, then change it to temp filename
if out_filename.startswith("omniverse:") or \
out_filename.startswith("file:") or \
out_filename.startswith("ftp:"):
# create a temp folder
self.temp_dir = tempfile.TemporaryDirectory()
# substitutes the original Nucleus folder with the temp folder
self.out_filename = os.path.join(self.temp_dir.name, os.path.basename(out_filename))
async def finalize(self, copy_files: bool = True):
# If out_filename is different from the original one, copy all files
# from the temp folder to the Nucleus server
if self.temp_dir != None:
if copy_files:
from_dir = os.path.dirname(self.out_filename)
to_dir = os.path.dirname(self.original_filename)
for ld in os.listdir(from_dir):
f = os.path.basename(ld)
result = await copy_async(os.path.join(from_dir, f), to_dir + '/' + f)
if not result:
print(f"Cannot copy from {f} to {to_dir}, error code: {result}.")
else:
print(f"Copied resource {f} to {to_dir}.")
# Delete temp folder
self.temp_dir.cleanup()
async def save_instance_to_module(context, inst_name, usd_prim, temp_dir, out_filename):
print("============ MDL Save Instance to Module =============")
neuray = context.neuray
transaction = context.transaction
stage = context.stage
# access shader prim
prim = get_shader_prim(stage, usd_prim)
prim_name = usd_prim.pathString.split('/')[-1]
if out_filename == None or os.path.isdir(out_filename) or os.path.splitext(out_filename)[1] != '.mdl':
print(f"Error: output filename is invalid, expected an .mdl file: '{out_filename}'")
return False
# Handle Nucleus: OM-46539 Graph to MDL fails to copy Nucleus textures to local filesystem when exporting
export_helper = ExportHelper(out_filename)
out_filename = export_helper.out_filename
# Sanity checks
with transaction.access_as(pymdlsdk.IFunction_call, inst_name) as inst:
if inst == None or not inst.is_valid_interface():
print("Error: Invalid instance name (IFunction_call): {}".format(inst_name))
return False
with transaction.access_as(pymdlsdk.IFunction_definition, inst.get_function_definition()) as fd:
if fd == None or not fd.is_valid_interface():
print("Error: Invalid IFunction_definition: {}".format(inst.get_function_definition()))
return False
module = pymdl.Module._fetchFromDb(transaction, fd.get_module())
if module == None:
print("Error: Invalid Module: {}".format(fd.get_module()))
return False
# since resourcse are handled by the renderer we need to pass them to neuray before exporting
await prepare_resources_for_export(transaction, inst_name, temp_dir)
factory: pymdlsdk.IMdl_factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
execution_context = factory.create_execution_context()
# Create the module builder.
module_name = "mdl::new_module_28f8c871b7034e55a0541be81655ffb1"
module_builder = factory.create_module_builder(
transaction,
module_name,
pymdlsdk.MDL_VERSION_1_6, # In order to use aliases
pymdlsdk.MDL_VERSION_LATEST,
execution_context)
if not module_builder.is_valid_interface():
print("Error: Failed to create module builder")
return False
module_builder.clear_module(execution_context)
# Create a variant
success = False
with transaction.access_as(pymdlsdk.IFunction_call, inst_name) as inst, \
factory.create_expression_factory(transaction) as ef, \
ef.create_annotation_block() as empty_anno_block:
if inst.is_valid_interface():
if is_reserved_word(prim_name):
variant_name = "Main"
else:
variant_name = prim_name
result = module_builder.add_variant(
variant_name,
inst.get_function_definition(),
inst.get_arguments(),
empty_anno_block,
empty_anno_block,
True,
execution_context)
if result != 0:
print("Error: Failed to add variant to module builder:\n\t'{}'\n\t'{}'\n\t'{}'".format(prim.GetName(), inst.get_function_definition(), inst.get_arguments()))
for i in range(execution_context.get_messages_count()):
print(execution_context.get_message(i).get_string())
if result == 0:
with neuray.get_api_component(pymdlsdk.IMdl_impexp_api) as imp_exp:
rtn = -1
execution_context.set_option("bundle_resources", True)
rtn = imp_exp.export_module(transaction, module_name, out_filename, execution_context)
if rtn >= 0:
unmangle_helper = UnmangleAndFixMDLSearchPath(context)
unmangle_helper.unmangle_mdl_file(out_filename, out_filename)
print(f"Success: Material '{prim_name}' exported to module '{out_filename}'")
# Copy files to Nucleus if needed
await export_helper.finalize()
success = True
else:
print(f"Failure: Could not export Material '{prim_name}' to module '{out_filename}'")
await export_helper.finalize(copy_files = False)
module_builder.clear_module(execution_context)
return success
| 117,950 | Python | 43.695339 | 232 | 0.568249 |
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/test_usd_converter.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import omni.mdl.usd_converter
import omni.usd
import shutil
import pathlib
import os
import carb
import carb.settings
# Having a test class derived from omni.kit.test.AsyncTestCase declared on the root of module
# will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCaseFailOnLogError):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._test_data = str(pathlib.Path(__file__).parent.joinpath("data"))
self._test_data_usd = str(pathlib.Path(self._test_data).joinpath("usd"))
self._test_data_mdl = str(pathlib.Path(self._test_data).joinpath("mdl"))
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_mdl_to_usd(self):
# Disable standard path to ensure reproducible results locally and in TC
NO_STD_PATH = "/app/mdl/nostdpath"
settings = carb.settings.get_settings()
settings.set_bool(NO_STD_PATH, True)
filter_import = False
tokens = omni.mdl.usd_converter.find_tokens('mdl::ZA0OmniGlass_2Emdl::OmniGlass::converted_27', filter_import)
result = (tokens == {'ZA0OmniGlass_2Emdl', 'converted_27', 'mdl', 'OmniGlass'})
self.assertEqual(result, True)
filter_import = True
tokens = omni.mdl.usd_converter.find_tokens('import ::state::normal;\n', filter_import)
result = (tokens == {'state', 'normal'})
self.assertEqual(result, True)
filter_import = False
tokens = omni.mdl.usd_converter.find_tokens(' anno::author("NVIDIA CORPORATION"),\n', filter_import)
result = (tokens == {'anno', 'author'})
self.assertEqual(result, True)
filter_import = True
tokens = omni.mdl.usd_converter.find_tokens(' anno::author("NVIDIA CORPORATION"),\n', filter_import)
result = (len(tokens) == 0)
self.assertEqual(result, True)
with omni.mdl.usd_converter.TemporaryDirectory() as temp_dir:
test_search_path = self._test_data_mdl
fn = "core_definitions.usda"
ADD_MDL_PATH = "/app/mdl/additionalUserPaths"
settings = carb.settings.get_settings()
mdl_custom_paths: List[str] = settings.get(ADD_MDL_PATH) or []
mdl_custom_paths.append(test_search_path)
mdl_custom_paths.append(temp_dir)
mdl_custom_paths = list(set(mdl_custom_paths))
settings.set_string_array(ADD_MDL_PATH, mdl_custom_paths)
result = omni.mdl.usd_converter.mdl_to_usd(
moduleName="nvidia/core_definitions.mdl",
targetFolder=temp_dir,
targetFilename=fn,
output=omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY)
self.assertEqual(result, True)
# fn = "tutorials.usda"
# # WORKAROUND: Copy test file to temp folder, NeurayLib does not handle folder containing '*.mdl.*' in their name
# source_file = str(pathlib.Path(self._test_data_mdl).joinpath('nvidia/sdk_examples/tutorials.mdl'))
# shutil.copy2(source_file, temp_dir)
# module = str(pathlib.Path(temp_dir).joinpath("tutorials.mdl"))
# if os.path.exists(module):
# result = omni.mdl.usd_converter.mdl_to_usd(
# moduleName=module,
# targetFolder=temp_dir,
# targetFilename=fn,
# searchPath=test_search_path)
# self.assertEqual(result, True)
# fn = "test_types.usda"
# WORKAROUND: Copy test file to temp folder, NeurayLib does not handle folder containing '*.mdl.*' in their name
# source_file = str(pathlib.Path(self._test_data_mdl).joinpath('test/test_types.mdl'))
# shutil.copy2(source_file, temp_dir)
# module = str(pathlib.Path(temp_dir).joinpath("test_types.mdl"))
# if os.path.exists(module):
# result = omni.mdl.usd_converter.mdl_to_usd(
# moduleName=module,
# targetFolder=temp_dir,
# targetFilename=fn,
# searchPath=test_search_path)
# self.assertEqual(result, True)
tutorial_scene = str(pathlib.Path(self._test_data_usd).joinpath("tutorials.usda"))
if os.path.exists(tutorial_scene):
result = await omni.mdl.usd_converter.usd_prim_to_mdl(
tutorial_scene,
"/example_material",
test_search_path,
forceNotOV=True)
self.assertEqual(result, True)
result = await omni.mdl.usd_converter.usd_prim_to_mdl(
tutorial_scene,
"/example_modulemdl_material_examples",
test_search_path,
forceNotOV=True)
self.assertEqual(result, True)
result = await omni.mdl.usd_converter.usd_prim_to_mdl(
tutorial_scene,
"/wave_gradient",
test_search_path,
forceNotOV=True)
self.assertEqual(result, True)
omni.mdl.usd_converter.test_mdl_prim_to_usd('/root')
simple_scene = str(pathlib.Path(self._test_data_usd).joinpath("scene.usda"))
if os.path.exists(simple_scene):
test_prim = '/World/Looks/Material'
stage = omni.mdl.usd_converter.mdl_usd.Usd.Stage.Open(simple_scene)
prim = stage.GetPrimAtPath(test_prim)
omni.mdl.usd_converter.mdl_prim_to_usd(stage, prim)
omni.mdl.usd_converter.mdl_usd.get_examples_search_path()
mdl_tmpfile = str(pathlib.Path(temp_dir).joinpath("tmpout.mdl"))
result = await omni.mdl.usd_converter.export_to_mdl(mdl_tmpfile, prim, forceNotOV=True)
self.assertEqual(result, True)
# Example: 'mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase'
# Return: 'OmniSurface/OmniSurfaceBase.mdl'
omni.mdl.usd_converter.mdl_usd.prototype_to_source_asset('mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase')
omni.mdl.usd_converter.mdl_usd.parse_ov_resource_name('mdl::resolvedPath_texture_raw')
| 6,881 | Python | 44.576159 | 126 | 0.600203 |
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/__init__.py | from .test_usd_converter import *
| 34 | Python | 16.499992 | 33 | 0.764706 |
omniverse-code/kit/exts/omni.mdl.usd_converter/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.mdl.usd_converter`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`_.
## [1.0.1] - 2021-09-20
### Changed
- Added interface for USD to MDL conversion
## [1.0.0] - 2021-05-12
### Added
- Initial extensions 2.0
| 309 | Markdown | 19.666665 | 82 | 0.695793 |
omniverse-code/kit/exts/omni.mdl.usd_converter/docs/README.md | # Python Extension for MDL <--> USD conversions [omni.mdl.usd_converter]
This is an extension for MDL to USD and for USD to MDL conversions.
## Interfaces
### mdl_to_usd(moduleName: str, searchPath: str = None, targetFolder: str = MDL_AUTOGEN_PATH, targetFilename: str = None, output: mdl_usd.OutputType = mdl_usd.OutputType.SHADER, nestedShaders: bool = False)
- moduleName: Module to convert (example: `nvidia/core_definitions.mdl`)
- searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set)
- targetFolder: Destination folder for USD stage (default = `${data}/shadergraphs/mdl_usd`)
- targetFilename: Destination stage filename, extension `.usd` or `.usda` can be omitted (default is module name, example: `core_definitions.usda`)
- output: What to output:
a shader: omni.mdl.usd_converter.mdl_usd.OutputType.SHADER
a material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL
material and geometry: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY
- nestedShaders: Do we want nested shaders or flat (default = False)
### usd_prim_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None, forceNotOV: bool = False)
- usdStage: Input stage containing the prim to convert
- usdPrim: Prim path to convert (default = not set, use stage default prim)
- searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set)
- forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False)
### export_to_mdl(path: str, prim: mdl_usd.Usd.Prim, forceNotOV: bool = False)
- path: Output filename to save the new module to (need to end with .mdl, example: "c:/temp/new_module.mdl")
- prim: The Usd.Prim to convert
- forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False)
## Examples
### MDL -> USD conversion
```
omni.mdl.usd_converter.mdl_to_usd("nvidia/core_definitions.mdl")
```
Convert core_definitions module to USD. Save the result of the conversion in the folder `${data}/shadergraphs/mdl_usd`.
```
omni.mdl.usd_converter.mdl_to_usd(
moduleName = "nvidia/core_definitions.mdl",
targetFolder = "C:/ProgramData/NVIDIA Corporation/mdl")
```
Convert core_definitions module to USD. Save the result of the conversion in the folder `C:/ProgramData/NVIDIA Corporation/mdl`.
```
omni.mdl.usd_converter.mdl_to_usd(
moduleName = "nvidia/core_definitions.mdl",
targetFolder = "C:/ProgramData/NVIDIA Corporation/mdl",
targetFilename = "stage.usda")
```
Convert core_definitions module to USD. Save the result of the conversion in the folder `C:/ProgramData/NVIDIA Corporation/mdl` under the name `stage.usda`.
### USD -> MDL conversion
```
import asyncio
asyncio.ensure_future(omni.mdl.usd_converter.usd_prim_to_mdl(
"C:/temp/tutorials.usda",
"/example_material",
"C:/ProgramData/NVIDIA Corporation/mdl",
forceNotOV = True))
```
Convert the USD Prim `/example_material` found in the stage `C:/temp/tutorials.usda`.
Assuming `/example_material` is a valid prim in the stage `C:/temp/tutorials.usda`, and that MDL material module `tutorials.mdl` is under `C:/ProgramData/NVIDIA Corporation/mdl/nvidia/sdk_examples`, convert the prim to MDL in memory.
Here is the shader prim:
```
def Shader "example_material"
{
uniform token info:implementationSource = "sourceAsset"
uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@
uniform token info:mdl:sourceAsset:subIdentifier = "example_material"
float inputs:roughness = 0
color3f inputs:tint = (1, 1, 1)
token outputs:out (
renderType = "material"
)
}
```
| 3,657 | Markdown | 39.644444 | 233 | 0.744053 |
omniverse-code/kit/exts/omni.mdl.usd_converter/docs/index.rst | omni.mdl.usd_converter
###########################
.. toctree::
:maxdepth: 1
CHANGELOG | 94 | reStructuredText | 12.571427 | 27 | 0.468085 |
omniverse-code/kit/exts/omni.kit.menu.file/PACKAGE-LICENSES/omni.kit.menu.file-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.menu.file/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.1.4"
category = "Internal"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "File Menu"
description="Implementation of File Menu. New, Open, Save, Exit etc."
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "ui", "menu"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog = "docs/CHANGELOG.md"
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
[settings]
persistent.app.file.recentFiles = []
[dependencies]
"omni.usd" = {}
"omni.kit.menu.utils" = {}
"omni.kit.window.file" = {}
"omni.client" = {}
[[python.module]]
name = "omni.kit.menu.file"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/file/ignoreUnsavedStage=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window",
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.window.preferences",
"omni.kit.property.usd",
"omni.kit.material.library",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers"
]
stdoutFailPatterns.exclude = [
"*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop
"*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available
]
unreliable = true # OM-55408
| 2,025 | TOML | 27.942857 | 122 | 0.694321 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/__init__.py | from .scripts import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/__init__.py | from .file import *
| 20 | Python | 9.499995 | 19 | 0.7 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/file_actions.py | import carb
import omni.usd
import omni.kit.window.file
import omni.kit.actions.core
def post_notification(message: str, info: bool = False, duration: int = 3):
try:
import omni.kit.notification_manager as nm
if info:
type = nm.NotificationStatus.INFO
else:
type = nm.NotificationStatus.WARNING
nm.post_notification(message, status=type, duration=duration)
except ModuleNotFoundError:
carb.log_warn(message)
def quit(fast: bool = False):
if fast:
carb.settings.get_settings().set("/app/fastShutdown", True)
omni.kit.app.get_app().post_quit()
def open_stage_with_new_edit_layer():
stage = omni.usd.get_context().get_stage()
if not stage:
post_notification(f"Cannot Re-open with New Edit Layer. No valid stage")
return
omni.kit.window.file.open_with_new_edit_layer(stage.GetRootLayer().identifier)
def register_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "File Actions"
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"quit",
lambda: quit(fast=False),
display_name="File->Exit",
description="Exit",
tag=actions_tag,
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"quit_fast",
lambda: quit(fast=True),
display_name="File->Exit Fast",
description="Exit Fast",
tag=actions_tag,
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"open_stage_with_new_edit_layer",
open_stage_with_new_edit_layer,
display_name="File->Open Current Stage With New Edit Layer",
description="Open Stage With New Edit Layer",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 2,035 | Python | 28.507246 | 82 | 0.653071 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/file.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import urllib.parse
import carb.input
import omni.client
import omni.ext
import omni.kit.menu.utils
import omni.kit.ui
import omni.usd
from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types, FILE_EVENT_QUEUE_UPDATED
from omni.kit.menu.utils import MenuItemDescription
from .file_actions import register_actions, deregister_actions
from omni.ui import color as cl
from pathlib import Path
_extension_instance = None
_extension_path = None
INTERACTIVE_TEXT = cl.shade(cl("#1A91C5"))
SHARE_ICON_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)).joinpath("data/icons/share.svg")
class FileMenuExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
omni.kit.menu.utils.set_default_menu_proirity("File", -10)
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
global _extension_path
_extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name)
settings = carb.settings.get_settings()
self._max_recent_files = settings.get("exts/omni.kit.menu.file/maxRecentFiles") or 10
self._file_menu_list = None
self._recent_menu_list = None
self._build_file_menu()
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._event_sub = event_stream.create_subscription_to_pop_by_type(FILE_EVENT_QUEUE_UPDATED, lambda _: self._build_recent_menu())
events = omni.usd.get_context().get_stage_event_stream()
self._stage_event_subscription = events.create_subscription_to_pop(self._on_stage_event, name="omni.kit.menu.file stage watcher")
def on_shutdown(self):
global _extension_instance
deregister_actions(self._ext_name)
_extension_instance = None
self._stage_sub = None
omni.kit.menu.utils.remove_menu_items(self._recent_menu_list, "File")
omni.kit.menu.utils.remove_menu_items(self._file_menu_list, "File")
self._recent_menu_list = None
self._file_menu_list = None
self._event_sub = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.CLOSED):
self._build_file_menu()
def _build_file_menu(self):
# setup menu
self._file_menu_list = [
MenuItemDescription(
name="New",
glyph="file.svg",
onclick_action=("omni.kit.window.file", "new"),
hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.N),
),
MenuItemDescription(
name="Open",
glyph="folder_open.svg",
onclick_action=("omni.kit.window.file", "open"),
hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.O),
),
MenuItemDescription(),
MenuItemDescription(
name="Re-open with New Edit Layer",
glyph="external_link.svg",
# enable_fn=lambda: not FileMenuExtension.is_new_stage(),
onclick_action=("omni.kit.menu.file", "open_stage_with_new_edit_layer")
),
MenuItemDescription(),
MenuItemDescription(
name="Share",
glyph=str(SHARE_ICON_PATH),
enable_fn=FileMenuExtension.can_share,
onclick_action=("omni.kit.window.file", "share")
),
MenuItemDescription(),
MenuItemDescription(
name="Save",
glyph="save.svg",
# enable_fn=FileMenuExtension.can_close,
onclick_action=("omni.kit.window.file", "save"),
hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.S),
),
MenuItemDescription(
name="Save With Options",
glyph="save.svg",
# enable_fn=FileMenuExtension.can_close,
onclick_action=("omni.kit.window.file", "save_with_options"),
hotkey=(
carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL | carb.input.KEYBOARD_MODIFIER_FLAG_ALT,
carb.input.KeyboardInput.S,
),
),
MenuItemDescription(
name="Save As...",
glyph="none.svg",
# enable_fn=FileMenuExtension.can_close,
onclick_action=("omni.kit.window.file", "save_as"),
hotkey=(
carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL | carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT,
carb.input.KeyboardInput.S,
),
),
MenuItemDescription(
name="Save Flattened As...",
glyph="none.svg",
# enable_fn=FileMenuExtension.can_close,
onclick_action=("omni.kit.window.file", "save_as_flattened"),
),
MenuItemDescription(),
MenuItemDescription(
name="Add Reference",
glyph="none.svg",
onclick_action=("omni.kit.window.file", "add_reference"),
),
MenuItemDescription(
name="Add Payload",
glyph="none.svg",
onclick_action=("omni.kit.window.file", "add_payload")
),
MenuItemDescription(),
MenuItemDescription(name="Exit", glyph="none.svg", onclick_action=("omni.kit.menu.file", "quit")),
]
if not carb.settings.get_settings().get("/app/fastShutdown"):
self._file_menu_list.append(MenuItemDescription(name="Exit Fast (Experimental)", glyph="none.svg", onclick_action=("omni.kit.menu.file", "quit_fast")))
self._build_recent_menu()
omni.kit.menu.utils.add_menu_items(self._file_menu_list, "File", -10)
def _build_recent_menu(self):
if self._recent_menu_list:
omni.kit.menu.utils.remove_menu_items(self._recent_menu_list, "File", rebuild_menus=False)
recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD)
sub_menu = []
# add reopen
stage = omni.usd.get_context().get_stage()
is_anonymous = stage.GetRootLayer().anonymous if stage else False
filename_url = ""
if not is_anonymous:
filename_url = stage.GetRootLayer().identifier if stage else ""
if filename_url:
sub_menu.append(
MenuItemDescription(
name=f"Current stage: {filename_url}",
onclick_action=("omni.kit.window.file", "reopen"),
user={"user_style": {"color": INTERACTIVE_TEXT}}
)
)
elif not recent_files:
sub_menu.append(MenuItemDescription(name="None", enabled=False))
if recent_files:
for recent_file in recent_files:
# NOTE: not compatible with hotkeys as passing URL to open_stage
sub_menu.append(
MenuItemDescription(
name=urllib.parse.unquote(recent_file),
onclick_action=("omni.kit.window.file", "open_stage", recent_file),
)
)
self._recent_menu_list = [
MenuItemDescription(name="Open Recent", glyph="none.svg", appear_after="Open", sub_menu=sub_menu)
]
omni.kit.menu.utils.add_menu_items(self._recent_menu_list, "File")
def is_new_stage():
return omni.usd.get_context().is_new_stage()
def can_open():
stage_state = omni.usd.get_context().get_stage_state()
return stage_state == omni.usd.StageState.OPENED or stage_state == omni.usd.StageState.CLOSED
def can_save():
return (
omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED
and not FileMenuExtension.is_new_stage()
and omni.usd.get_context().is_writable()
)
def can_close():
return omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED
def can_close_and_not_is_new_stage():
return FileMenuExtension.can_close() and not FileMenuExtension.is_new_stage()
def can_share():
return (
omni.usd.get_context() is not None
and omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED
and omni.usd.get_context().get_stage_url().startswith("omniverse://")
)
def get_extension_path(sub_directory):
global _extension_path
path = _extension_path
if sub_directory:
path = os.path.normpath(os.path.join(path, sub_directory))
return path
def get_instance():
global _extension_instance
return _extension_instance
| 9,504 | Python | 39.619658 | 163 | 0.592277 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_recent_menu.py | import carb
import omni.kit.test
import omni.kit.helper.file_utils as file_utils
from omni.kit import ui_test
from .. import get_instance
from omni.kit.window.file_importer.test_helper import FileImporterTestHelper
class TestMenuFileRecents(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await omni.usd.get_context().new_stage_async()
file_utils.reset_file_event_queue()
# After running each test
async def tearDown(self):
await omni.usd.get_context().new_stage_async()
file_utils.reset_file_event_queue()
async def _mock_open_stage_async(self, url: str):
# Doesn't actually open a stage but pushes an opened event like that action would. This
# should cause the file event queue to update.
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(file_utils.FILE_OPENED_EVENT, payload=file_utils.FileEventModel(url=url).dict())
await ui_test.human_delay(4)
async def test_file_recent_menu(self):
test_files = [
"omniverse://ov-test/first.usda",
"c:/users/me/second.usda",
"omniverse://ov-test/third.usda",
]
under_test = get_instance()
get_recent_list = lambda: under_test._recent_menu_list[0].sub_menu
# load first.usda file... rebuild_menu == 1
await self._mock_open_stage_async(test_files[0])
recent_list = get_recent_list()
self.assertEqual(len(recent_list), 1)
self.assertEqual(recent_list[0].name, test_files[0])
# load second.usda file... rebuild_menu == 2
await self._mock_open_stage_async(test_files[1])
recent_list = get_recent_list()
self.assertEqual(len(recent_list), 2)
self.assertEqual(recent_list[0].name, test_files[1])
# load second.usda file again... rebuild_menu still == 2
await self._mock_open_stage_async(test_files[1])
recent_list = get_recent_list()
self.assertEqual(len(recent_list), 2)
self.assertEqual(recent_list[0].name, test_files[1])
# load third.usda ... rebuild_menu == 3
await self._mock_open_stage_async(test_files[2])
recent_list = get_recent_list()
self.assertEqual(len(recent_list), 3)
self.assertEqual(recent_list[0].name, test_files[2])
# confirm list order is as expected
expected = test_files[::-1]
self.assertEqual([i.name for i in recent_list], expected)
async def test_file_recent_menu_current_stage(tester, _):
under_test = get_instance()
get_recent_list = lambda: under_test._recent_menu_list[0].sub_menu
# verify recent == "None"
recent_list = get_recent_list()
tester.assertEqual(len(recent_list), 1)
tester.assertTrue(recent_list[0].name.startswith("None"))
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open").click()
await ui_test.human_delay(5)
async with FileImporterTestHelper() as file_import_helper:
dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")
await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda")
await tester.wait_for_stage_event()
await ui_test.human_delay(5)
# verify name of stage
stage = omni.usd.get_context().get_stage()
tester.assertTrue(stage.GetRootLayer().identifier.replace("\\", "/").endswith("data/tests/4Lights.usda"))
# verify recent == "Current stage:" and "4Lights.usda"
recent_list = get_recent_list()
tester.assertEqual(len(recent_list), 2)
tester.assertTrue(recent_list[0].name.startswith("Current stage:"))
tester.assertTrue(recent_list[0].name.endswith("data/tests/4Lights.usda"))
tester.assertFalse(recent_list[1].name.startswith("Current stage:"))
tester.assertTrue(recent_list[1].name.endswith("data/tests/4Lights.usda"))
await omni.usd.get_context().new_stage_async()
await ui_test.human_delay(5)
# verify recent == "4Lights.usda"
recent_list = get_recent_list()
tester.assertEqual(len(recent_list), 1)
tester.assertFalse(recent_list[0].name.startswith("Current stage:"))
tester.assertTrue(recent_list[0].name.endswith("data/tests/4Lights.usda"))
| 4,420 | Python | 40.317757 | 109 | 0.666968 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/__init__.py | from .file_tests import *
from .test_recent_menu import *
| 58 | Python | 18.66666 | 31 | 0.741379 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_templates.py | import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
async def file_test_func_file_new_from_stage_template_empty(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select empty and wait for stage open
await menu_widget.find_menu("Empty").click()
await tester.wait_for_stage_event()
# verify Empty stage
stage = omni.usd.get_context().get_stage()
tester.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertTrue(prim_list == ['/World'])
async def file_test_func_file_new_from_stage_template_sunlight(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select Sunlight and wait for stage open
await menu_widget.find_menu("Sunlight").click()
await tester.wait_for_stage_event()
# verify Sunlight stage
stage = omni.usd.get_context().get_stage()
tester.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertTrue(prim_list == ['/World', '/Environment', '/Environment/defaultLight'])
async def file_test_func_file_new_from_stage_template_default_stage(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select Default Stage and wait for stage open
await menu_widget.find_menu("Default Stage").click()
await tester.wait_for_stage_event()
# verify Default Stage
stage = omni.usd.get_context().get_stage()
tester.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertEqual(set(prim_list), set([
'/World', '/Environment', '/Environment/Sky',
'/Environment/DistantLight', '/Environment/Looks',
'/Environment/Looks/Grid', '/Environment/Looks/Grid/Shader',
'/Environment/ground', '/Environment/groundCollider']))
| 3,018 | Python | 42.128571 | 108 | 0.710073 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_media.py | import os
import shutil
import tempfile
import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
from omni.kit.window.file_importer.test_helper import FileImporterTestHelper
from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper
async def file_test_func_file_new(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New").click()
await tester.wait_for_stage_event()
# verify its a new layer
tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier == layer_name)
async def file_test_func_file_open(tester, menu_item: MenuItemDescription):
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open").click()
await ui_test.human_delay(5)
async with FileImporterTestHelper() as file_import_helper:
dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")
await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda")
await tester.wait_for_stage_event()
# verify name of stage
stage = omni.usd.get_context().get_stage()
tester.assertTrue(stage.GetRootLayer().identifier.replace("\\", "/").endswith("data/tests/4Lights.usda"))
async def file_test_func_file_reopen(tester, menu_item: MenuItemDescription):
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open Recent").click()
await menu_widget.find_menu(tester._light_path, ignore_case=True).click()
await tester.wait_for_stage_event()
# verify its a unmodified stage
tester.assertFalse(omni.kit.undo.can_undo())
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# verify its a modified stage
tester.assertTrue(omni.kit.undo.can_undo())
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open Recent").click()
await menu_widget.find_menu("Current stage:", contains_path=True).click()
await tester.wait_for_stage_event()
# verify its a unmodified stage
tester.assertFalse(omni.kit.undo.can_undo())
async def file_test_func_file_re_open_with_new_edit_layer(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await file_test_func_file_open(tester, {})
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Re-open with New Edit Layer").click()
await ui_test.human_delay(50)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights_layer.usda")
await tester.wait_for_stage_event()
# verify its not saved to tmpdir
layer = omni.usd.get_context().get_stage().GetRootLayer()
expected_name = f"{tmpdir}/4Lights_layer.usd".replace("\\", "/")
tester.assertTrue(layer.anonymous)
tester.assertTrue(len(layer.subLayerPaths) == 2)
tester.assertTrue(layer.subLayerPaths[0] == expected_name)
tester.assertTrue(layer.subLayerPaths[1].endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda"))
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_save(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save").click()
await ui_test.human_delay(50)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
expected_size = os.path.getsize(expected_name)
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# save again, it should not show dialog....
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save").click()
await ui_test.human_delay()
# handle dialog....
save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'")
await save_widget.click()
await ui_test.human_delay()
await tester.wait_for_stage_event()
# verify file was saved
tester.assertFalse(os.path.getsize(expected_name) == expected_size)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_save_with_options(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save With Options").click()
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
expected_size = os.path.getsize(expected_name)
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# save again, it should not show dialog....
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save").click()
await ui_test.human_delay()
# handle dialog....
save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'")
await save_widget.click()
await ui_test.human_delay()
await tester.wait_for_stage_event()
# verify file was saved
tester.assertFalse(os.path.getsize(expected_name) == expected_size)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_save_as(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await file_test_func_file_open(tester, {})
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save As...").click()
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_save_flattened_as(tester, menu_item: MenuItemDescription):
# save flattened doesn't send any stage events as it exports not saves
tmpdir = tempfile.mkdtemp()
await file_test_func_file_open(tester, {})
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier.replace("\\", "/") if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save Flattened As...").click()
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda")
await ui_test.human_delay(20)
# verify its exported to tmpdir & hasn't changed stage path
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == layer_name)
tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_open_recent_exts_omni_kit_menu_file_data_tests_4lights_usda(tester, menu_item: MenuItemDescription):
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open Recent").click()
await menu_widget.find_menu(tester._light_path, ignore_case=True).click()
await tester.wait_for_stage_event()
# verify its 4lights
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/").endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda"))
async def file_test_func_file_exit(tester, menu_item: MenuItemDescription):
# not sure how to test this without kit exiting...
pass
async def file_test_func_file_exit_fast__experimental(tester, menu_item: MenuItemDescription):
# not sure how to test this without kit exiting...
pass
async def file_test_hotkey_func_file_new(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
# emulate hotkey
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await tester.wait_for_stage_event()
# verify its a new layer
tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier == layer_name)
async def file_test_hotkey_func_file_open(tester, menu_item: MenuItemDescription):
# emulate hotkey
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(5)
async with FileImporterTestHelper() as file_import_helper:
dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")
await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda")
await tester.wait_for_stage_event()
# verify its 4lights
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/").endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda"))
async def file_test_hotkey_func_file_save(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
# emulate hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
expected_size = os.path.getsize(expected_name)
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await ui_test.human_delay()
# save again, it should not show dialog....
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.S, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
# handle dialog....
save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'")
if save_widget:
await save_widget.click()
await ui_test.human_delay()
await tester.wait_for_stage_event()
# verify file was saved
tester.assertFalse(os.path.getsize(expected_name) == expected_size)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_hotkey_func_file_save_with_options(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
# emulate hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
expected_size = os.path.getsize(expected_name)
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await ui_test.human_delay()
# save again, it should not show dialog....
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
# emulate hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
# handle dialog....
save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'")
await save_widget.click()
await ui_test.human_delay()
await tester.wait_for_stage_event()
# verify file was saved
tester.assertFalse(os.path.getsize(expected_name) == expected_size)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_hotkey_func_file_save_as(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await file_test_func_file_open(tester, {})
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
# emulate hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_share(tester, menu_item: MenuItemDescription):
# File->Share will only work on omniverse:// files. Currently there is no way to mock this scenario.
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Share").click()
pass
| 15,830 | Python | 40.012953 | 162 | 0.704991 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_payload.py | import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
async def file_test_func_file_add_reference(tester, menu_item: MenuItemDescription):
from carb.input import KeyboardInput
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Add Reference").click()
await ui_test.human_delay()
dir_widget = ui_test.find("Select File//Frame/**/StringField[*].identifier=='filepicker_directory_path'")
await ui_test.human_delay()
await dir_widget.input(carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests"))
await ui_test.human_delay()
await tester.find_content_file("Select File", "sphere.usda").click(double=True)
await ui_test.human_delay(20)
# verify reference was added...
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertTrue(len(prim_list) > 0)
async def file_test_func_file_add_payload(tester, menu_item: MenuItemDescription):
from carb.input import KeyboardInput
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Add Payload").click()
await ui_test.human_delay()
dir_widget = ui_test.find("Select File//Frame/**/StringField[*].identifier=='filepicker_directory_path'")
await ui_test.human_delay()
await dir_widget.input(carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests"))
await ui_test.human_delay()
await tester.find_content_file("Select File", "sphere.usda").click(double=True)
await ui_test.human_delay(20)
# verify payload was added...
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertTrue(len(prim_list) > 0)
| 1,999 | Python | 36.735848 | 119 | 0.710355 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/file_tests.py | import sys
import re
import asyncio
import carb
import omni.kit.test
import omni.kit.helper.file_utils as file_utils
from .test_func_media import *
from .test_func_payload import *
from .test_func_templates import *
from .test_recent_menu import test_file_recent_menu_current_stage
class TestMenuFile(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._light_path = carb.tokens.get_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests/4Lights.usda")
# load stage so menu shows reopen
await omni.usd.get_context().open_stage_async(self._light_path)
async def tearDown(self):
pass
async def test_file_menus(self):
import omni.kit.material.library
# wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
await omni.kit.material.library.get_mdl_list_async()
await ui_test.human_delay()
menus = omni.kit.menu.utils.get_merged_menus()
prefix = "file_test"
to_test = []
this_module = sys.modules[__name__]
for key in menus.keys():
if key.startswith("File"):
for item in menus[key]['items']:
if item.name != "" and item.has_action():
key_name = re.sub('\W|^(?=\d)','_', key.lower())
func_name = re.sub('\W|^(?=\d)','_', item.name.replace("${kit}/", "").lower())
while key_name and key_name[-1] == "_":
key_name = key_name[:-1]
while func_name and func_name[-1] == "_":
func_name = func_name[:-1]
test_fn = f"{prefix}_func_{key_name}_{func_name}"
if test_fn.startswith("file_test_func_file_open_recent_reopen_current_stage"):
test_fn = "file_test_func_file_reopen"
elif test_fn.startswith("file_test_func_file_open_recent"):
continue
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item))
except AttributeError:
carb.log_error(f"test function \"{test_fn}\" not found")
if item.original_menu_item and item.original_menu_item.hotkey:
test_fn = f"{prefix}_hotkey_func_{key_name}_{func_name}"
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item.original_menu_item))
except AttributeError:
carb.log_error(f"test function \"{test_fn}\" not found")
self._future_test = None
self._required_stage_event = -1
self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.menu.file")
# add in any additional tests
test_fn = "test_file_recent_menu_current_stage"
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, None))
for to_call, test_fn, menu_item in to_test:
file_utils.reset_file_event_queue()
carb.settings.get_settings().set("/persistent/app/omniverse/lastOpenDirectory", "")
carb.settings.get_settings().set("/persistent/app/file_exporter/directory", "")
carb.settings.get_settings().set("/persistent/app/file_exporter/filename", "")
carb.settings.get_settings().set("/persistent/app/file_exporter/file_extension", "")
await self.wait_stage_loading()
await omni.usd.get_context().new_stage_async()
await ui_test.human_delay()
print(f"Running test {test_fn}")
await to_call(self, menu_item)
self._stage_event_sub = None
def find_content_file(self, window_name, filename):
for widget in ui_test.find_all(f"{window_name}//Frame/**/TreeView[*]"):
for file_widget in widget.find_all(f"**/Label[*]"):
if file_widget.widget.text==filename:
return file_widget
return None
def _on_stage_event(self, event):
if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done():
self._future_test.set_result(event.type)
async def reset_stage_event(self, stage_event):
self._required_stage_event = stage_event
self._future_test = asyncio.Future()
async def wait_for_stage_event(self):
async def wait_for_event():
await self._future_test
try:
await asyncio.wait_for(wait_for_event(), timeout=30.0)
except asyncio.TimeoutError:
carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}")
self._future_test = None
self._required_stage_event = -1
async def wait_stage_loading(self):
while True:
_, files_loaded, total_files = omni.usd.get_context().get_stage_loading_status()
if files_loaded or total_files:
await ui_test.human_delay()
continue
break
await ui_test.human_delay()
| 5,421 | Python | 42.725806 | 155 | 0.561336 |
omniverse-code/kit/exts/omni.kit.menu.file/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.1.4] - 2023-01-18
### Changes
- Cancel update task after stage closing.
## [1.1.3] - 2022-11-01
### Changes
- Restored failing test & fixed
## [1.1.2] - 2022-11-01
### Changes
- Remove failing test
## [1.1.1] - 2022-07-19
### Changes
- Disabled contextual greying of menu items
## [1.1.0] - 2022-06-08
### Changes
- Updated menu to use actions
## [1.0.9] - 2022-06-15
### Changes
- Updated unittests.
## [1.0.8] - 2022-05-19
### Changes
- Optimized recents menu rebuilding
## [1.0.7] - 2022-02-23
### Changes
- Removed "Open With Payloads Disabled" from file menu.
## [1.0.6] - 2021-11-25
### Changes
- Only rebuild recent list on stage save/load/open/close events
## [1.0.5] - 2021-08-23
### Changes
- Set menus default order
## [1.0.4] - 2021-07-13
### Changes
- Added "Open With Payloads Disabled"
- Added "Add Payload"
## [1.0.3] - 2021-06-21
### Changes
- Moved recents from USDContext
## [1.0.2] - 2021-05-05
### Changes
- Added "Save With Options"
## [1.0.1] - 2020-12-03
### Changes
- Added "Add Reference"
## [1.0.0] - 2020-08-17
### Changes
- Created
| 1,176 | Markdown | 17.107692 | 80 | 0.633503 |
omniverse-code/kit/exts/omni.kit.menu.file/docs/index.rst | omni.kit.menu.file
###########################
File Menu
.. toctree::
:maxdepth: 1
CHANGELOG
| 107 | reStructuredText | 6.2 | 27 | 0.448598 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/PACKAGE-LICENSES/omni.kit.stage.mdl_converter-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/config/extension.toml | [package]
version = "1.0.1"
authors = ["NVIDIA"]
title = "USD Material MDL Export"
description="The ability to export USD Material to MDL"
readme = "docs/README.md"
repository = ""
category = "USD"
feature = true
keywords = ["usd", "mdl", "export", "stage"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
# icon = "data/icon.png"
[dependencies]
"omni.appwindow" = {}
"omni.kit.commands" = {}
"omni.kit.context_menu" = {}
"omni.kit.pip_archive" = {}
"omni.usd" = {}
"omni.mdl.usd_converter" = {}
"omni.kit.window.filepicker" = {}
"omni.kit.widget.filebrowser" = {}
[[python.module]]
name = "omni.kit.stage.mdl_converter"
[[test]]
args = []
dependencies = []
stdoutFailPatterns.include = []
stdoutFailPatterns.exclude = []
| 744 | TOML | 20.911764 | 55 | 0.669355 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/stage_mdl_converter_extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageMdlConverterExtension"]
from pxr import Sdf
import omni.ext
import omni.usd
import omni.kit.context_menu
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.window.popup_dialog.message_dialog import MessageDialog
import os
import omni.ui as ui
import asyncio
import carb
class AskForOverrideDialog(MessageDialog):
WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE
WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP
WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# self._style = self._style.copy()
# self._style["Background"]["background_color"] = ui.color("#00000000")
# self._style["Background"]["border_color"] = ui.color("#00000000")
class WarningDialog(MessageDialog):
WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE
WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP
WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class StageMdlConverterExtension(omni.ext.IExt):
def on_startup(self, ext_id):
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
self._stage_menu = ext_manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_stage_menu(),
on_disable_fn=lambda _: self._unregister_stage_menu(),
ext_name="omni.kit.widget.stage",
hook_name="omni.kit.stage.mdl_converter",
)
self._pick_export_path_dialog = None
self._override_dialog = None
self._warning_dialog = None
self._selected_prim = None
self._current_dir = None
self._current_export_path = None
def on_shutdown(self):
self._unregister_stage_menu()
self._stage_menu = None
self._stage_context_menu_export = None
@staticmethod
def __on_filter_mdl_files(item: FileBrowserItem) -> bool:
"""Used by pick folder dialog to hide all the files"""
if item and not item.is_folder:
_, ext = os.path.splitext(item.path)
return (ext in [".mdl"])
return True
def __run_export(self):
"""Do the actual export after we have a filename to export to"""
carb.log_info(f"Picked output filename: {self._current_export_path}")
asyncio.ensure_future(omni.mdl.usd_converter.usd_to_mdl(self._current_export_path, self._selected_prim))
def __on_ok_override(self, popup):
"""Called when the the user confirmed to override"""
carb.log_info(f"Confirmed to override selected filename: {self._current_export_path}")
popup.hide()
self.__run_export()
def __on_cancel_override(self, popup):
"""Called when the the user rejected to override"""
carb.log_info(f"Rejected to override selected filename: {self._current_export_path}")
popup.hide()
self._pick_export_path_dialog.refresh_current_directory()
self._pick_export_path_dialog.show(path=self._current_export_path)
def __on_ok_warning(self, popup):
"""Called when the the user closes warning dialog"""
popup.hide()
def __on_apply_filename(self, filename: str, dir: str):
"""Called when the user press "Export" in the pick filename dialog"""
# don't accept as long as no filename is selected
if not filename or not dir:
return
# add the file extension if missing
if len(filename) < 5 or filename[-4:] != '.mdl':
filename = filename + '.mdl'
self._current_dir = dir
# add a trailing slash for the client library
if(dir[-1] != os.sep):
dir = dir + os.sep
self._current_export_path = omni.client.combine_urls(dir, filename)
self._pick_export_path_dialog.hide()
# ask for override or run export directly
if os.path.exists(self._current_export_path):
carb.log_info(f"WARNING: selected filename already exists: {self._current_export_path}")
if self._override_dialog != None:
self._override_dialog.destroy()
self._override_dialog = AskForOverrideDialog(
title = "Confirm override...",
message = "The selected file already exists. Do you want to replace it?",
ok_label = "Yes",
cancel_label = "No",
ok_handler = self.__on_ok_override,
cancel_handler = self.__on_cancel_override
)
# self._override_dialog.build_ui()
self._override_dialog.show()
else:
self.__run_export()
def _register_stage_menu(self):
"""Called when "omni.kit.widget.stage" is loaded"""
def on_export(objects: dict):
"""Called from the context menu"""
# keep the selected prim
prims = objects.get("prim_list", None)
if not prims or len(prims) > 1:
return
if len(prims) == 1:
theprim = prims[0]
stage = theprim.GetStage()
(status, message) = omni.mdl.usd_converter.is_shader_resolved(stage, theprim)
if not status:
carb.log_warn(message)
if self._warning_dialog != None:
self._warning_dialog.destroy()
self._warning_dialog = WarningDialog(
title = "Convert Material to MDL",
message = "WARNING: " + message,
disable_cancel_button=True,
ok_handler = self.__on_ok_warning,
)
self._warning_dialog.show()
return
if not omni.mdl.usd_converter.is_material_bound_to_prim(stage, theprim):
# Material not bound, display warning dialog and do not proceed
carb.log_warn(f"Material is not bound to any prim, can not convert")
if self._warning_dialog != None:
self._warning_dialog.destroy()
self._warning_dialog = WarningDialog(
title = "Convert Material to MDL",
message = "WARNING: Material is not bound to any prim, can not convert",
disable_cancel_button=True,
ok_handler = self.__on_ok_warning,
)
self._warning_dialog.show()
return
self._selected_prim = prims[0]
"""Open Pick Folder dialog to add compounds"""
if self._pick_export_path_dialog is None:
self._pick_export_path_dialog = FilePickerDialog(
"Convert Material to MDL and Export As...",
allow_multi_selection=False,
apply_button_label="Export",
click_apply_handler=self.__on_apply_filename,
item_filter_options=["MDL Files (*.mdl)"],
item_filter_fn=self.__on_filter_mdl_files,
# OM-61553: Use the selected material prim name as the default filename
current_filename=self._selected_prim.GetName(),
current_directory=self._current_dir
)
if self._pick_export_path_dialog is not None:
self._pick_export_path_dialog.refresh_current_directory()
self._pick_export_path_dialog.set_filename(self._selected_prim.GetName())
self._pick_export_path_dialog.show(path=self._current_export_path)
# Add context menu to omni.kit.widget.stage
context_menu = omni.kit.context_menu.get_instance()
if context_menu:
menu = {
"name": "Export to MDL",
"glyph": "menu_save.svg",
"show_fn": [context_menu.is_material, context_menu.is_one_prim_selected],
"onclick_fn": on_export,
"appear_after": "Save Selected",
}
self._stage_context_menu_export = omni.kit.context_menu.add_menu(menu, "MENU", "omni.kit.widget.stage")
def _unregister_stage_menu(self):
"""Called when "omni.kit.widget.stage" is unloaded"""
if self._pick_export_path_dialog:
self._pick_export_path_dialog.destroy()
self._pick_export_path_dialog = None
if self._override_dialog:
self._override_dialog.destroy()
self._override_dialog = None
if self._warning_dialog:
self._warning_dialog.destroy()
self._warning_dialog = None
self._stage_context_menu_export = None
| 9,267 | Python | 40.375 | 115 | 0.584116 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/__init__.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .stage_mdl_converter_extension import *
| 473 | Python | 46.399995 | 76 | 0.807611 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/tests/__init__.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .test_mdl_converter import *
| 462 | Python | 45.299995 | 76 | 0.805195 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/tests/test_mdl_converter.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.kit.stage.mdl_converter import *
from pxr import Sdf
from pxr import Usd
from pxr import UsdGeom
import omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
async def test_mdl_converter(self):
"""Testing omni.kit.stage.mdl_converter"""
self.assertEqual(True, True)
| 726 | Python | 37.263156 | 76 | 0.77686 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/docs/CHANGELOG.md | # CHANGELOG
The ability to export USD Material to MDL.
## [1.0.1] - 2022-05-31
- Changed "Export Selected" to "Save Selected"
## [1.0.0] - 2022-02-10
### Added
| 165 | Markdown | 14.090908 | 47 | 0.636364 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/docs/README.md | # USD Material MDL Export.
This extension adds a context menu item "Export to MDL" to the stage window. It shows when right-clicking a (single) selected material node. When the new menu item is chosen, the user is prompted for a destination MDL filename. The selected USD material is then converted to an MDL material and saved to the selected destination in a new MDL module.
## Issues and limitation
- The USD material needs to be bound to geometry in order to be fully available to the renderer and ready for export.
- Resources that are exported with the material are not overridden if files with the name exists already. Instead, new filenames are generated for those resources. This also applies when exporting a USD material to the same MDL file multiple times.
## Screenshot
| 787 | Markdown | 70.636357 | 349 | 0.792884 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/docs/index.rst | omni.kit.stage.mdl_converter
############################
.. toctree::
:maxdepth: 1
CHANGELOG
| 104 | reStructuredText | 9.499999 | 28 | 0.471154 |
omniverse-code/kit/exts/omni.kit.capture/PACKAGE-LICENSES/omni.kit.capture-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.capture/config/extension.toml | [package]
category = "Rendering"
changelog = "docs/CHANGELOG.md"
description = "An extension to capture Kit viewport into images and videos."
icon = "data/icon.svg"
preview_image = "data/preview.png"
readme = "docs/README.md"
title = "Kit Image and Video Capture"
version = "0.5.1"
[dependencies]
"omni.usd" = {}
"omni.timeline" = {}
"omni.ui" = {}
"omni.videoencoding" = {}
"omni.kit.viewport.utility" = {}
"omni.kit.renderer.capture" = { optional=true }
[[python.module]]
name = "omni.kit.capture"
[[test]]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.window.viewport",
]
waiver = "extension is being deprecated"
unreliable = true
| 656 | TOML | 20.899999 | 76 | 0.6875 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/capture_progress.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from enum import Enum, IntEnum
import datetime
import subprocess
import carb
import omni.ui as ui
import omni.kit.app
class CaptureStatus(IntEnum):
NONE = 0
CAPTURING = 1
PAUSED = 2
FINISHING = 3
TO_START_ENCODING = 4
ENCODING = 5
CANCELLED = 6
class CaptureProgress:
def __init__(self):
self._init_internal()
def _init_internal(self, time_length=0, time_rate=24):
self._time_length = time_length
self._time_rate = time_rate
self._total_frames = int(self._time_length / self._time_rate)
# at least to capture 1 frame
if self._total_frames < 1:
self._total_frames = 1
self._capture_status = CaptureStatus.NONE
self._elapsed_time = 0.0
self._estimated_time_remaining = 0.0
self._current_frame_time = 0.0
self._average_time_per_frame = 0.0
self._encoding_time = 0.0
self._current_frame = 0
self._first_frame_num = 0
self._got_first_frame = False
self._progress = 0.0
self._current_subframe = -1
self._total_subframes = 1
self._subframe_time = 0.0
self._total_frame_time = 0.0
self._average_time_per_subframe = 0.0
self._total_preroll_frames = 0
self._prerolled_frames = 0
self._path_trace_iteration_num = 0
self._path_trace_subframe_num = 0
@property
def capture_status(self):
return self._capture_status
@capture_status.setter
def capture_status(self, value):
self._capture_status = value
@property
def elapsed_time(self):
return self._get_time_string(self._elapsed_time)
@property
def estimated_time_remaining(self):
return self._get_time_string(self._estimated_time_remaining)
@property
def current_frame_time(self):
return self._get_time_string(self._current_frame_time)
@property
def average_frame_time(self):
return self._get_time_string(self._average_time_per_frame)
@property
def encoding_time(self):
return self._get_time_string(self._encoding_time)
@property
def progress(self):
return self._progress
@property
def current_subframe(self):
return self._current_subframe
@property
def total_subframes(self):
return self._total_subframes
@property
def subframe_time(self):
return self._get_time_string(self._subframe_time)
@property
def average_time_per_subframe(self):
return self._get_time_string(self._average_time_per_subframe)
@property
def total_preroll_frames(self):
return self._total_preroll_frames
@total_preroll_frames.setter
def total_preroll_frames(self, value):
self._total_preroll_frames = value
@property
def prerolled_frames(self):
return self._prerolled_frames
@prerolled_frames.setter
def prerolled_frames(self, value):
self._prerolled_frames = value
@property
def path_trace_iteration_num(self):
return self._path_trace_iteration_num
@path_trace_iteration_num.setter
def path_trace_iteration_num(self, value):
self._path_trace_iteration_num = value
@property
def path_trace_subframe_num(self):
return self._path_trace_subframe_num
@path_trace_subframe_num.setter
def path_trace_subframe_num(self, value):
self._path_trace_subframe_num = value
def start_capturing(self, time_length, time_rate, preroll_frames=0):
self._init_internal(time_length, time_rate)
self._total_preroll_frames = preroll_frames
self._capture_status = CaptureStatus.CAPTURING
def finish_capturing(self):
self._init_internal()
def is_prerolling(self):
return (
(self._capture_status == CaptureStatus.CAPTURING or self._capture_status == CaptureStatus.PAUSED)
and self._total_preroll_frames > 0
and self._total_preroll_frames > self._prerolled_frames
)
def add_encoding_time(self, time):
if self._estimated_time_remaining > 0.0:
self._elapsed_time += self._estimated_time_remaining
self._estimated_time_remaining = 0.0
self._encoding_time += time
def add_frame_time(self, frame, time, pt_subframe_num=0, pt_iteration_num=0):
if not self._got_first_frame:
self._got_first_frame = True
self._first_frame_num = frame
self._current_frame = frame
self._path_trace_subframe_num = pt_subframe_num
self._path_trace_iteration_num = pt_iteration_num
self._elapsed_time += time
if self._current_frame != frame:
frames_captured = self._current_frame - self._first_frame_num + 1
self._average_time_per_frame = self._elapsed_time / frames_captured
self._current_frame = frame
self._current_frame_time = time
else:
self._current_frame_time += time
if frame == self._first_frame_num:
self._estimated_time_remaining = 0.0
self._progress = 0.0
else:
total_frame_time = self._average_time_per_frame * self._total_frames
# if users pause for long times, it's possible that elapsed time will be greater than estimated total time
# if this happens, estimate it again
if self._elapsed_time >= total_frame_time:
total_frame_time += time + self._average_time_per_frame
self._estimated_time_remaining = total_frame_time - self._elapsed_time
self._progress = self._elapsed_time / total_frame_time
def add_single_frame_capture_time(self, subframe, total_subframes, time):
self._total_subframes = total_subframes
self._elapsed_time += time
if self._current_subframe != subframe:
self._subframe_time = time
if self._current_subframe == -1:
self._average_time_per_subframe = self._elapsed_time
else:
self._average_time_per_subframe = self._elapsed_time / subframe
self._total_frame_time = self._average_time_per_subframe * total_subframes
else:
self._subframe_time += time
self._current_subframe = subframe
if self._current_subframe == 0:
self._estimated_time_remaining = 0.0
self._progress = 0.0
else:
if self._elapsed_time >= self._total_frame_time:
self._total_frame_time += time + self._average_time_per_subframe
self._estimated_time_remaining = self._total_frame_time - self._elapsed_time
self._progress = self._elapsed_time / self._total_frame_time
def _get_time_string(self, time_seconds):
hours = int(time_seconds / 3600)
minutes = int((time_seconds - hours*3600) / 60)
seconds = time_seconds - hours*3600 - minutes*60
time_string = ""
if hours > 0:
time_string += '{:d}h '.format(hours)
if minutes > 0:
time_string += '{:d}m '.format(minutes)
else:
if hours > 0:
time_string += "0m "
time_string += '{:.2f}s'.format(seconds)
return time_string
PROGRESS_WINDOW_WIDTH = 360
PROGRESS_WINDOW_HEIGHT = 260
PROGRESS_BAR_WIDTH = 216
PROGRESS_BAR_HEIGHT = 20
PROGRESS_BAR_HALF_HEIGHT = PROGRESS_BAR_HEIGHT / 2
TRIANGLE_WIDTH = 6
TRIANGLE_HEIGHT = 10
TRIANGLE_OFFSET_Y = 10
PROGRESS_WIN_DARK_STYLE = {
"Triangle::progress_marker": {"background_color": 0xFFD1981D},
"Rectangle::progress_bar_background": {
"border_width": 0.5,
"border_radius": PROGRESS_BAR_HALF_HEIGHT,
"background_color": 0xFF888888,
},
"Rectangle::progress_bar_full": {
"border_width": 0.5,
"border_radius": PROGRESS_BAR_HALF_HEIGHT,
"background_color": 0xFFD1981D,
},
"Rectangle::progress_bar": {
"background_color": 0xFFD1981D,
"border_radius": PROGRESS_BAR_HALF_HEIGHT,
"corner_flag": ui.CornerFlag.LEFT,
"alignment": ui.Alignment.LEFT,
},
}
PAUSE_BUTTON_STYLE = {
"NvidiaLight": {
"Button.Label::pause": {"color": 0xFF333333},
"Button.Label::pause:disabled": {"color": 0xFF666666},
},
"NvidiaDark": {
"Button.Label::pause": {"color": 0xFFCCCCCC},
"Button.Label::pause:disabled": {"color": 0xFF666666},
},
}
class CaptureProgressWindow:
def __init__(self):
self._app = omni.kit.app.get_app_interface()
self._update_sub = None
self._window_caption = "Capture Progress"
self._window = None
self._progress = None
self._progress_bar_len = PROGRESS_BAR_HALF_HEIGHT
self._progress_step = 0.5
self._is_single_frame_mode = False
self._show_pt_subframes = False
self._show_pt_iterations = False
self._support_pausing = True
def show(
self,
progress,
single_frame_mode: bool = False,
show_pt_subframes: bool = False,
show_pt_iterations: bool = False,
support_pausing: bool = True,
) -> None:
self._progress = progress
self._is_single_frame_mode = single_frame_mode
self._show_pt_subframes = show_pt_subframes
self._show_pt_iterations = show_pt_iterations
self._support_pausing = support_pausing
self._build_ui()
self._update_sub = self._app.get_update_event_stream().create_subscription_to_pop(
self._on_update, name="omni.kit.capure progress"
)
def close(self):
self._window = None
self._update_sub = None
def _build_progress_bar(self):
self._progress_bar_area.clear()
self._progress_bar_area.set_style(PROGRESS_WIN_DARK_STYLE)
with self._progress_bar_area:
with ui.Placer(offset_x=self._progress_bar_len - TRIANGLE_WIDTH / 2, offset_y=TRIANGLE_OFFSET_Y):
ui.Triangle(
name="progress_marker",
width=TRIANGLE_WIDTH,
height=TRIANGLE_HEIGHT,
alignment=ui.Alignment.CENTER_BOTTOM,
)
with ui.ZStack():
ui.Rectangle(name="progress_bar_background", width=PROGRESS_BAR_WIDTH, height=PROGRESS_BAR_HEIGHT)
ui.Rectangle(name="progress_bar", width=self._progress_bar_len, height=PROGRESS_BAR_HEIGHT)
def _build_ui_timer(self, text, init_value):
with ui.HStack():
with ui.HStack(width=ui.Percent(50)):
ui.Spacer()
ui.Label(text, width=0)
with ui.HStack(width=ui.Percent(50)):
ui.Spacer(width=15)
timer_label = ui.Label(init_value)
ui.Spacer()
return timer_label
def _build_multi_frames_capture_timers(self):
self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time)
self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining)
self._ui_current_frame_time = self._build_ui_timer("Current frame time", self._progress.current_frame_time)
if self._show_pt_subframes:
subframes_str = f"{self._progress.path_trace_subframe_num}"
self._ui_pt_subframes = self._build_ui_timer("Subframes", subframes_str)
if self._show_pt_iterations:
iter_str = f"{self._progress.path_trace_iteration_num}"
self._ui_pt_iterations = self._build_ui_timer("Iterations", iter_str)
self._ui_ave_frame_time = self._build_ui_timer("Average time per frame", self._progress.average_frame_time)
self._ui_encoding_time = self._build_ui_timer("Encoding", self._progress.encoding_time)
def _build_single_frame_capture_timers(self):
self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time)
self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining)
subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}"
self._ui_subframe_count = self._build_ui_timer("Subframe/Total frames", subframe_count)
self._ui_current_frame_time = self._build_ui_timer("Current subframe time", self._progress.subframe_time)
self._ui_ave_frame_time = self._build_ui_timer("Average time per subframe", self._progress.average_frame_time)
def _build_preroll_notification(self):
with ui.HStack():
ui.Spacer(width=ui.Percent(20))
self._preroll_frames_notification = ui.Label("Running preroll frames, please wait...")
ui.Spacer(width=ui.Percent(10))
def _build_ui(self):
if self._window is None:
style_settings = carb.settings.get_settings().get("/persistent/app/window/uiStyle")
if not style_settings:
style_settings = "NvidiaDark"
self._window = ui.Window(
self._window_caption,
width=PROGRESS_WINDOW_WIDTH,
height=PROGRESS_WINDOW_HEIGHT,
style=PROGRESS_WIN_DARK_STYLE,
)
with self._window.frame:
with ui.VStack():
with ui.HStack():
ui.Spacer(width=ui.Percent(20))
self._progress_bar_area = ui.VStack()
self._build_progress_bar()
ui.Spacer(width=ui.Percent(20))
ui.Spacer(height=5)
if self._is_single_frame_mode:
self._build_single_frame_capture_timers()
else:
self._build_multi_frames_capture_timers()
self._build_preroll_notification()
with ui.HStack():
with ui.HStack(width=ui.Percent(50)):
ui.Spacer()
self._ui_pause_button = ui.Button(
"Pause",
height=0,
clicked_fn=self._on_pause_clicked,
enabled=self._support_pausing,
style=PAUSE_BUTTON_STYLE[style_settings],
name="pause",
)
with ui.HStack(width=ui.Percent(50)):
ui.Spacer(width=15)
ui.Button("Cancel", height=0, clicked_fn=self._on_cancel_clicked)
ui.Spacer()
ui.Spacer()
self._window.visible = True
self._update_timers()
def _on_pause_clicked(self):
if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause":
self._progress.capture_status = CaptureStatus.PAUSED
self._ui_pause_button.text = "Resume"
elif self._progress.capture_status == CaptureStatus.PAUSED:
self._progress.capture_status = CaptureStatus.CAPTURING
self._ui_pause_button.text = "Pause"
def _on_cancel_clicked(self):
if (
self._progress.capture_status == CaptureStatus.CAPTURING
or self._progress.capture_status == CaptureStatus.PAUSED
):
self._progress.capture_status = CaptureStatus.CANCELLED
def _update_timers(self):
if self._is_single_frame_mode:
self._ui_elapsed_time.text = self._progress.elapsed_time
self._ui_remaining_time.text = self._progress.estimated_time_remaining
subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}"
self._ui_subframe_count.text = subframe_count
self._ui_current_frame_time.text = self._progress.subframe_time
self._ui_ave_frame_time.text = self._progress.average_time_per_subframe
else:
self._ui_elapsed_time.text = self._progress.elapsed_time
self._ui_remaining_time.text = self._progress.estimated_time_remaining
self._ui_current_frame_time.text = self._progress.current_frame_time
if self._show_pt_subframes:
subframes_str = f"{self._progress.path_trace_subframe_num}"
self._ui_pt_subframes.text = subframes_str
if self._show_pt_iterations:
iter_str = f"{self._progress.path_trace_iteration_num}"
self._ui_pt_iterations.text = iter_str
self._ui_ave_frame_time.text = self._progress.average_frame_time
self._ui_encoding_time.text = self._progress.encoding_time
def _update_preroll_frames(self):
if self._progress.is_prerolling():
msg = 'Running preroll frames {}/{}, please wait...'.format(
self._progress.prerolled_frames,
self._progress.total_preroll_frames
)
self._preroll_frames_notification.text = msg
else:
self._preroll_frames_notification.visible = False
def _on_update(self, event):
self._update_preroll_frames()
self._update_timers()
self._progress_bar_len = (
PROGRESS_BAR_WIDTH - PROGRESS_BAR_HEIGHT
) * self._progress.progress + PROGRESS_BAR_HALF_HEIGHT
self._build_progress_bar()
| 17,963 | Python | 38.052174 | 123 | 0.597228 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import math
import time
import datetime
import omni.ext
import carb
import omni.kit.app
import omni.timeline
import omni.usd
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file
from .capture_options import *
from .capture_progress import *
from .video_generation import VideoGenerationHelper
from .helper import get_num_pattern_file_path
VIDEO_FRAMES_DIR_NAME = "frames"
DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO = ".png"
capture_instance = None
class CaptureExtension(omni.ext.IExt):
def on_startup(self):
global capture_instance
capture_instance = self
self._options = CaptureOptions()
self._progress = CaptureProgress()
self._progress_window = CaptureProgressWindow()
self._renderer = None
import omni.renderer_capture
self._renderer = omni.renderer_capture.acquire_renderer_capture_interface()
self._viewport_api = None
self._app = omni.kit.app.get_app_interface()
self._timeline = omni.timeline.get_timeline_interface()
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._settings = carb.settings.get_settings()
self._show_default_progress_window = True
self._progress_update_fn = None
self._forward_one_frame_fn = None
self._capture_finished_fn = None
carb.log_warn("Deprecated notice: Please be noted that omni.kit.capture has been replaced with omni.kit.capture.viewport and will be removed in future releases. " \
"Please update the use of this extension to the new one.")
def on_shutdown(self):
self._progress = None
self._progress_window = None
global capture_instance
capture_instance = None
@property
def options(self):
return self._options
@options.setter
def options(self, value):
self._options = value
@property
def progress(self):
return self._progress
@property
def show_default_progress_window(self):
return self._show_default_progress_window
@show_default_progress_window.setter
def show_default_progress_window(self, value):
self._show_default_progress_window = value
@property
def progress_update_fn(self):
return self._progress_update_fn
@progress_update_fn.setter
def progress_update_fn(self, value):
self._progress_update_fn = value
@property
def forward_one_frame_fn(self):
return self._forward_one_frame_fn
@forward_one_frame_fn.setter
def forward_one_frame_fn(self, value):
self._forward_one_frame_fn = value
@property
def capture_finished_fn(self):
return self._capture_finished_fn
@capture_finished_fn.setter
def capture_finished_fn(self, value):
self._capture_finished_fn = value
def start(self):
self._prepare_folder_and_counters()
self._prepare_viewport()
self._start_internal()
def pause(self):
if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause":
self._progress.capture_status = CaptureStatus.PAUSED
def resume(self):
if self._progress.capture_status == CaptureStatus.PAUSED:
self._progress.capture_status = CaptureStatus.CAPTURING
def cancel(self):
if (
self._progress.capture_status == CaptureStatus.CAPTURING
or self._progress.capture_status == CaptureStatus.PAUSED
):
self._progress.capture_status = CaptureStatus.CANCELLED
def _update_progress_hook(self):
if self._progress_update_fn is not None:
self._progress_update_fn(
self._progress.capture_status,
self._progress.progress,
self._progress.elapsed_time,
self._progress.estimated_time_remaining,
self._progress.current_frame_time,
self._progress.average_frame_time,
self._progress.encoding_time,
self._frame_counter,
self._total_frame_count,
)
def _get_index_for_image(self, dir, file_name, image_suffix):
def is_int(string_val):
try:
v = int(string_val)
return True
except:
return False
images = os.listdir(dir)
name_len = len(file_name)
suffix_len = len(image_suffix)
max_index = 0
for item in images:
if item.startswith(file_name) and item.endswith(image_suffix):
num_part = item[name_len : (len(item) - suffix_len)]
if is_int(num_part):
num = int(num_part)
if max_index < num:
max_index = num
return max_index + 1
def _float_to_time(self, ft):
hour = int(ft)
ft = (ft - hour) * 60
minute = int(ft)
ft = (ft - minute) * 60
second = int(ft)
ft = (ft - second) * 1000000
microsecond = int(ft)
return datetime.time(hour, minute, second, microsecond)
def _is_environment_sunstudy_player(self):
if self._options.sunstudy_player is not None:
return type(self._options.sunstudy_player).__module__ == "omni.kit.environment.core.sunstudy_player.player"
else:
carb.log_warn("Sunstudy player type check is valid only when the player is available.")
return False
def _update_sunstudy_player_time(self):
if self._is_environment_sunstudy_player():
self._options.sunstudy_player.current_time = self._sunstudy_current_time
else:
self._options.sunstudy_player.update_time(self._sunstudy_current_time)
def _set_sunstudy_player_time(self, current_time):
if self._is_environment_sunstudy_player():
self._options.sunstudy_player.current_time = current_time
else:
date_time = self._options.sunstudy_player.get_date_time()
time_to_set = self._float_to_time(current_time)
new_date_time = datetime.datetime(
date_time.year, date_time.month, date_time.day,
time_to_set.hour, time_to_set.minute, time_to_set.second
)
self._options.sunstudy_player.set_date_time(new_date_time)
def _prepare_sunstudy_counters(self):
self._total_frame_count = self._options.fps * self._options.sunstudy_movie_length_in_seconds
duration = self._options.sunstudy_end_time - self._options.sunstudy_start_time
self._sunstudy_iterations_per_frame = self._options.ptmb_subframes_per_frame
self._sunstudy_delta_time_per_iteration = duration / float(self._total_frame_count * self._sunstudy_iterations_per_frame)
self._sunstudy_current_time = self._options.sunstudy_start_time
self._set_sunstudy_player_time(self._sunstudy_current_time)
def _prepare_folder_and_counters(self):
self._workset_dir = self._options.output_folder
if not self._make_sure_directory_existed(self._workset_dir):
carb.log_warn(f"Capture failed due to unable to create folder {self._workset_dir}")
self._finish()
return
if self._options.is_capturing_nth_frames():
if self._options.capture_every_Nth_frames == 1:
frames_folder = self._options.file_name + "_frames"
else:
frames_folder = self._options.file_name + "_" + str(self._options.capture_every_Nth_frames) + "th_frames"
self._nth_frames_dir = os.path.join(self._workset_dir, frames_folder)
if not self._make_sure_directory_existed(self._nth_frames_dir):
carb.log_warn(f"Capture failed due to unable to create folder {self._nth_frames_dir}")
self._finish()
return
if self._options.is_video():
self._frames_dir = os.path.join(self._workset_dir, self._options.file_name + "_" + VIDEO_FRAMES_DIR_NAME)
if not self._make_sure_directory_existed(self._frames_dir):
carb.log_warn(
f"Capture failed due to unable to create folder {self._workset_dir} to save frames of the video."
)
self._finish()
return
self._video_name = self._options.get_full_path()
self._frame_pattern_prefix = os.path.join(self._frames_dir, self._options.file_name)
if self._options.is_capturing_frame():
self._start_time = float(self._options.start_frame) / self._options.fps
self._end_time = float(self._options.end_frame + 1) / self._options.fps
self._time = self._start_time
self._frame = self._options.start_frame
self._start_number = self._frame
self._total_frame_count = round((self._end_time - self._start_time) * self._options.fps)
else:
self._start_time = self._options.start_time
self._end_time = self._options.end_time
self._time = self._options.start_time
self._frame = int(self._options.start_time * self._options.fps)
self._start_number = self._frame
self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._options.fps)
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._prepare_sunstudy_counters()
else:
if self._options.is_capturing_nth_frames():
self._frame_pattern_prefix = self._nth_frames_dir
if self._options.is_capturing_frame():
self._start_time = float(self._options.start_frame) / self._options.fps
self._end_time = float(self._options.end_frame + 1) / self._options.fps
self._time = self._start_time
self._frame = self._options.start_frame
self._start_number = self._frame
self._total_frame_count = round((self._end_time - self._start_time) * self._options.fps)
else:
self._start_time = self._options.start_time
self._end_time = self._options.end_time
self._time = self._options.start_time
self._frame = int(self._options.start_time * self._options.fps)
self._start_number = self._frame
self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._options.fps)
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._prepare_sunstudy_counters()
else:
index = self._get_index_for_image(self._workset_dir, self._options.file_name, self._options.file_type)
self._frame_pattern_prefix = os.path.join(self._workset_dir, self._options.file_name + str(index))
self._start_time = self._timeline.get_current_time()
self._end_time = self._timeline.get_current_time()
self._time = self._timeline.get_current_time()
self._frame = 1
self._start_number = self._frame
self._total_frame_count = 1
self._subframe = 0
self._sample_count = 0
self._frame_counter = 0
self._real_time_settle_latency_frames_done = 0
self._last_skipped_frame_path = ""
self._path_trace_iterations = 0
self._time_rate = 1.0 / self._options.fps
self._time_subframe_rate = (
self._time_rate * (self._options.ptmb_fsc - self._options.ptmb_fso) / self._options.ptmb_subframes_per_frame
)
def _prepare_viewport(self):
viewport_api = get_active_viewport()
if viewport_api is None:
return False
self._record_current_window_status(viewport_api)
viewport_api.camera_path = self._options.camera
viewport_api.resolution = (self._options.res_width, self._options.res_height)
self._settings.set_bool("/persistent/app/captureFrame/viewport", True)
self._settings.set_bool("/app/captureFrame/setAlphaTo1", not self._options.save_alpha)
if self._options.file_type == ".exr":
self._settings.set_bool("/app/captureFrame/hdr", self._options.hdr_output)
else:
self._settings.set_bool("/app/captureFrame/hdr", False)
if self._options.save_alpha:
self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", True)
self._settings.set_bool("/rtx/post/backgroundZeroAlpha/backgroundComposite", False)
self._selection.clear_selected_prim_paths()
if self._options.render_preset == CaptureRenderPreset.RAY_TRACE:
self._switch_renderer = not (self._saved_active_render == "rtx" and self._saved_render_mode == "RaytracedLighting")
if self._switch_renderer:
viewport_api.set_hd_engine("rtx", "RaytracedLighting")
carb.log_info("Switching to RayTracing Mode")
elif self._options.render_preset == CaptureRenderPreset.PATH_TRACE:
self._switch_renderer = not (self._saved_active_render == "rtx" and self._saved_render_mode == "PathTracing")
if self._switch_renderer:
viewport_api.set_hd_engine("rtx", "PathTracing")
carb.log_info("Switching to PathTracing Mode")
elif self._options.render_preset == CaptureRenderPreset.IRAY:
self._switch_renderer = not (self._saved_active_render == "iray" and self._saved_render_mode == "iray")
if self._switch_renderer:
viewport_api.set_hd_engine("iray", "iray")
carb.log_info("Switching to IRay Mode")
else:
self._switch_renderer = False
carb.log_info("Keeping current Render Mode")
if self._options.debug_material_type == CaptureDebugMaterialType.SHADED:
self._settings.set_int("/rtx/debugMaterialType", -1)
elif self._options.debug_material_type == CaptureDebugMaterialType.WHITE:
self._settings.set_int("/rtx/debugMaterialType", 0)
else:
carb.log_info("Keeping current debug mateiral type")
# set it to 0 to ensure we accumulate as many samples as requested even across subframes (for motion blur)
self._settings.set_int("/rtx/pathtracing/totalSpp", 0)
# don't show light and grid during capturing
self._settings.set_int("/persistent/app/viewport/displayOptions", 0)
# disable async rendering for capture, otherwise it won't capture images correctly
self._settings.set_bool("/app/asyncRendering", False)
self._settings.set_bool("/app/asyncRenderingLowLatency", False)
# Rendering to some image buffers additionally require explicitly setting `set_capture_sync(True)`, on top of
# disabling the `/app/asyncRendering` setting. This can otherwise cause images to hold corrupted buffer
# information by erroneously assuming a complete image buffer is available when only a first partial subframe
# has been renderer (as in the case of EXR):
self._renderer.set_capture_sync( self._options.file_type == ".exr" )
# frames to wait for the async settings above to be ready, they will need to be detected by viewport, and
# then viewport will notify the renderer not to do async rendering
self._frames_to_disable_async_rendering = 2
# Normally avoid using a high /rtx/pathtracing/spp setting since it causes GPU
# timeouts for large sample counts. But a value larger than 1 can be useful in Multi-GPU setups
self._settings.set_int(
"/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp)
)
# Setting resetPtAccumOnlyWhenExternalFrameCounterChanges ensures we control accumulation explicitly
# by simpling changing the /rtx/externalFrameCounter value
self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", True)
if self._options.render_preset == CaptureRenderPreset.IRAY:
self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._options.path_trace_spp)
# Enable syncLoads in materialDB and Hydra. This is needed to make sure texture updates finish before we start the rendering
self._settings.set("/rtx/materialDb/syncLoads", True)
self._settings.set("/rtx/hydra/materialSyncLoads", True)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", False)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", 0)
return True
def _show_progress_window(self):
return (
self._options.is_video() or self._options.is_capturing_nth_frames() or (self._options.show_single_frame_progress and self._options.is_capturing_pathtracing_single_frame())
) and self.show_default_progress_window
def _start_internal(self):
# If texture streaming is enabled, set the preroll to at least 1 frame
if self._settings.get("/rtx-transient/resourcemanager/enableTextureStreaming"):
self._options.preroll_frames = max(self._options.preroll_frames, 1)
# set usd time code second to target frame rate
self._saved_timecodes_per_second = self._timeline.get_time_codes_per_seconds()
self._timeline.set_time_codes_per_second(self._options.fps)
# if we want preroll, then set timeline's current time back with the preroll frames' time,
# and rely on timeline to do the preroll using the give timecode
if self._options.preroll_frames > 0:
self._timeline.set_current_time(self._start_time - self._options.preroll_frames / self._options.fps)
self._settings.set("/iray/current_frame_time", self._start_time - self._options.preroll_frames / self._options.fps)
else:
self._timeline.set_current_time(self._start_time)
self._settings.set("/iray/current_frame_time", self._start_time)
# change timeline to be in play state
self._timeline.play()
# disable automatic time update in timeline so that movie capture tool can control time step
self._timeline.set_auto_update(False)
self._update_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update, order=1000000)
)
self._progress.start_capturing(self._end_time - self._start_time, self._time_rate, self._options.preroll_frames)
# always show single frame capture progress for PT mode
self._options.show_single_frame_progress = True
if self._show_progress_window():
self._progress_window.show(
self._progress,
self._options.is_capturing_pathtracing_single_frame(),
show_pt_subframes=self._options.render_preset == CaptureRenderPreset.PATH_TRACE,
show_pt_iterations=self._options.render_preset == CaptureRenderPreset.IRAY
)
def _record_current_window_status(self, viewport_api):
assert viewport_api is not None, "No viewport to record to"
self._viewport_api = viewport_api
self._saved_camera = viewport_api.camera_path
self._saved_hydra_engine = viewport_api.hydra_engine
self._saved_render_mode = viewport_api.render_mode
resolution = viewport_api.resolution
self._saved_resolution_width = int(resolution[0])
self._saved_resolution_height = int(resolution[1])
self._saved_capture_frame_viewport = self._settings.get("/persistent/app/captureFrame/viewport")
self._saved_active_render = self._settings.get("/renderer/active")
self._saved_debug_material_type = self._settings.get("/rtx/debugMaterialType")
self._saved_total_spp = int(self._settings.get("/rtx/pathtracing/totalSpp"))
self._saved_spp = int(self._settings.get("/rtx/pathtracing/spp"))
self._saved_reset_pt_accum_only = self._settings.get("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges")
self._saved_display_options = self._settings.get("/persistent/app/viewport/displayOptions")
self._saved_async_rendering = self._settings.get("/app/asyncRendering")
self._saved_async_renderingLatency = self._settings.get("/app/asyncRenderingLowLatency")
self._saved_background_zero_alpha = self._settings.get("/rtx/post/backgroundZeroAlpha/enabled")
self._saved_background_zero_alpha_comp = self._settings.get("/rtx/post/backgroundZeroAlpha/backgroundComposite")
if self._options.render_preset == CaptureRenderPreset.IRAY:
self._saved_iray_sample_limit = int(self._settings.get("/rtx/iray/progressive_rendering_max_samples"))
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._saved_sunstudy_current_time = self._options.sunstudy_current_time
self._saved_timeline_current_time = self._timeline.get_current_time()
self._saved_rtx_sync_load_setting = self._settings.get("/rtx/materialDb/syncLoads")
self._saved_hydra_sync_load_setting = self._settings.get("/rtx/hydra/materialSyncLoads")
self._saved_async_texture_streaming = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/async")
self._saved_texture_streaming_budget = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB")
def _restore_window_status(self):
viewport_api, self._viewport_api = self._viewport_api, None
assert viewport_api is not None, "No viewport to restore to"
viewport_api.camera_path = self._saved_camera
viewport_api.resolution = (self._saved_resolution_width, self._saved_resolution_height)
if self._switch_renderer:
viewport_api.set_hd_engine(self._saved_hydra_engine, self._saved_render_mode)
self._settings.set_bool("/persistent/app/captureFrame/viewport", self._saved_capture_frame_viewport)
self._settings.set_int("/rtx/debugMaterialType", self._saved_debug_material_type)
self._settings.set_int("/rtx/pathtracing/totalSpp", self._saved_total_spp)
self._settings.set_int("/rtx/pathtracing/spp", self._saved_spp)
self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", self._saved_reset_pt_accum_only)
self._settings.set_int("/persistent/app/viewport/displayOptions", self._saved_display_options)
self._settings.set_bool("/app/asyncRendering", self._saved_async_rendering)
self._settings.set_bool("/app/asyncRenderingLowLatency", self._saved_async_renderingLatency)
self._renderer.set_capture_sync(not self._saved_async_rendering)
self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", self._saved_background_zero_alpha)
self._settings.set_bool(
"/rtx/post/backgroundZeroAlpha/backgroundComposite", self._saved_background_zero_alpha_comp
)
if self._options.render_preset == CaptureRenderPreset.IRAY:
self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._saved_iray_sample_limit)
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._set_sunstudy_player_time(self._saved_sunstudy_current_time)
self._settings.set("/rtx/materialDb/syncLoads", self._saved_rtx_sync_load_setting)
self._settings.set("/rtx/hydra/materialSyncLoads", self._saved_hydra_sync_load_setting)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", self._saved_async_texture_streaming)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", self._saved_texture_streaming_budget)
self._settings.set("/app/captureFrame/hdr", False)
def _clean_pngs_in_directory(self, directory):
self._clean_files_in_directory(directory, ".png")
def _clean_files_in_directory(self, directory, suffix):
images = os.listdir(directory)
for item in images:
if item.endswith(suffix):
os.remove(os.path.join(directory, item))
def _make_sure_directory_existed(self, directory):
if not os.path.exists(directory):
try:
os.makedirs(directory, exist_ok=True)
except OSError as error:
carb.log_warn(f"Directory cannot be created: {dir}")
return False
return True
def _finish(self):
if (
self._progress.capture_status == CaptureStatus.FINISHING
or self._progress.capture_status == CaptureStatus.CANCELLED
):
self._update_sub = None
self._restore_window_status()
self._sample_count = 0
self._start_number = 0
self._frame_counter = 0
self._path_trace_iterations = 0
self._progress.capture_status = CaptureStatus.NONE
# restore timeline settings
# stop timeline, but re-enable auto update
timeline = self._timeline
timeline.set_auto_update(True)
timeline.stop()
timeline.set_time_codes_per_second(self._saved_timecodes_per_second)
self._timeline.set_current_time(self._saved_timeline_current_time)
self._settings.set("/iray/current_frame_time", self._saved_timeline_current_time)
if self._show_progress_window():
self._progress_window.close()
if self._capture_finished_fn is not None:
self._capture_finished_fn()
def _wait_for_image_writing(self):
# wait for the last frame is written to disk
# my tests of scenes of different complexity show a range of 0.2 to 1 seconds wait time
# so 5 second max time should be enough and we can early quit by checking the last
# frame every 0.1 seconds.
SECONDS_TO_WAIT = 5
SECONDS_EACH_TIME = 0.1
seconds_tried = 0.0
carb.log_info("Waiting for frames to be ready for encoding.")
while seconds_tried < SECONDS_TO_WAIT:
if os.path.isfile(self._frame_path) and os.access(self._frame_path, os.R_OK):
break
else:
time.sleep(SECONDS_EACH_TIME)
seconds_tried += SECONDS_EACH_TIME
if seconds_tried >= SECONDS_TO_WAIT:
carb.log_warn(f"Wait time out. To start encoding with images already have.")
def _capture_viewport(self, frame_path: str):
capture_viewport_to_file(self._viewport_api, file_path=frame_path)
carb.log_info(f"Capturing {frame_path}")
def _get_current_frame_output_path(self):
frame_path = ""
if self._options.is_video():
frame_path = get_num_pattern_file_path(
self._frames_dir,
self._options.file_name,
self._options.file_name_num_pattern,
self._frame,
DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO,
self._options.renumber_negative_frame_number_from_0,
abs(self._start_number)
)
else:
if self._options.is_capturing_nth_frames():
if self._frame_counter % self._options.capture_every_Nth_frames == 0:
frame_path = get_num_pattern_file_path(
self._frame_pattern_prefix,
self._options.file_name,
self._options.file_name_num_pattern,
self._frame,
self._options.file_type,
self._options.renumber_negative_frame_number_from_0,
abs(self._start_number)
)
else:
frame_path = self._frame_pattern_prefix + self._options.file_type
return frame_path
def _handle_skipping_frame(self, dt):
if not self._options.overwrite_existing_frames:
if os.path.exists(self._frame_path):
carb.log_warn(f"Frame {self._frame_path} exists, skip it...")
self._settings.set_int("/rtx/pathtracing/spp", 1)
self._subframe = 0
self._sample_count = 0
self._path_trace_iterations = 0
can_continue = True
if self._forward_one_frame_fn is not None:
can_continue = self._forward_one_frame_fn(dt)
elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \
(self._options.is_video() or self._options.is_capturing_nth_frames()):
self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration * self._sunstudy_iterations_per_frame
self._update_sunstudy_player_time()
else: # movie type is SEQUENCE
self._time = self._start_time + (self._frame - self._start_number) * self._time_rate
self._timeline.set_current_time(self._time)
self._settings.set("/iray/current_frame_time", self._time)
self._frame += 1
self._frame_counter += 1
# check if capture ends
if self._forward_one_frame_fn is not None:
if can_continue is False:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
else:
if self._time >= self._end_time or self._frame_counter >= self._total_frame_count:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
return True
else:
if os.path.exists(self._frame_path) and self._last_skipped_frame_path != self._frame_path:
carb.log_warn(f"Frame {self._frame_path} will be overwritten.")
self._last_skipped_frame_path = self._frame_path
return False
def _handle_real_time_capture_settle_latency(self):
if (self._options.render_preset == CaptureRenderPreset.RAY_TRACE
and self._options.real_time_settle_latency_frames > 0):
self._real_time_settle_latency_frames_done += 1
if self._real_time_settle_latency_frames_done > self._options.real_time_settle_latency_frames:
self._real_time_settle_latency_frames_done = 0
return False
else:
self._subframe = 0
self._sample_count = 0
return True
return False
def _on_update(self, e):
dt = e.payload["dt"]
if self._progress.capture_status == CaptureStatus.FINISHING:
self._finish()
self._update_progress_hook()
elif self._progress.capture_status == CaptureStatus.CANCELLED:
# carb.log_warn("video recording cancelled")
self._update_progress_hook()
self._finish()
elif self._progress.capture_status == CaptureStatus.ENCODING:
if VideoGenerationHelper().encoding_done:
self._progress.capture_status = CaptureStatus.FINISHING
self._update_progress_hook()
self._progress.add_encoding_time(dt)
elif self._progress.capture_status == CaptureStatus.TO_START_ENCODING:
if VideoGenerationHelper().is_encoding is False:
self._wait_for_image_writing()
if self._options.renumber_negative_frame_number_from_0 is True and self._start_number < 0:
video_frame_start_num = 0
else:
video_frame_start_num = self._start_number
started = VideoGenerationHelper().generating_video(
self._video_name,
self._frames_dir,
self._options.file_name,
self._options.file_name_num_pattern,
video_frame_start_num,
self._total_frame_count,
self._options.fps,
)
if started:
self._progress.capture_status = CaptureStatus.ENCODING
self._update_progress_hook()
self._progress.add_encoding_time(dt)
else:
carb.log_warn("Movie capture failed to encode the capture images.")
self._progress.capture_status = CaptureStatus.FINISHING
elif self._progress.capture_status == CaptureStatus.CAPTURING:
if self._frames_to_disable_async_rendering >= 0:
self._frames_to_disable_async_rendering -= 1
return
if self._progress.is_prerolling():
self._progress.prerolled_frames += 1
self._settings.set_int("/rtx/pathtracing/spp", 1)
left_preroll_frames = self._options.preroll_frames - self._progress.prerolled_frames
self._timeline.set_current_time(self._start_time - left_preroll_frames / self._options.fps)
self._settings.set("/iray/current_frame_time", self._start_time - left_preroll_frames / self._options.fps)
return
self._frame_path = self._get_current_frame_output_path()
if self._handle_skipping_frame(dt):
return
self._settings.set_int(
"/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp)
)
if self._options.render_preset == CaptureRenderPreset.IRAY:
iterations_done = int(self._settings.get("/iray/progression"))
self._path_trace_iterations = iterations_done
self._sample_count = iterations_done
else:
self._sample_count += self._options.spp_per_iteration
self._timeline.set_prerolling(False)
self._settings.set_int("/rtx/externalFrameCounter", self._frame)
# update progress timers
if self._options.is_capturing_pathtracing_single_frame():
self._progress.add_single_frame_capture_time(self._subframe, self._options.ptmb_subframes_per_frame, dt)
else:
self._progress.add_frame_time(self._frame, dt, self._subframe + 1, self._path_trace_iterations)
self._update_progress_hook()
# capture frame when we reach the sample count for this frame and are rendering the last subframe
# Note _sample_count can go over _samples_per_pixel when 'spp_per_iteration > 1'
if (self._sample_count >= self._options.path_trace_spp) and (
self._subframe == self._options.ptmb_subframes_per_frame - 1
):
if self._handle_real_time_capture_settle_latency():
return
if self._options.is_video():
self._capture_viewport(self._frame_path)
else:
if self._options.is_capturing_nth_frames():
if self._frame_counter % self._options.capture_every_Nth_frames == 0:
self._capture_viewport(self._frame_path)
else:
self._progress.capture_status = CaptureStatus.FINISHING
self._capture_viewport(self._frame_path)
# reset time the *next frame* (since otherwise we capture the first sample)
if self._sample_count >= self._options.path_trace_spp:
self._sample_count = 0
self._path_trace_iterations = 0
self._subframe += 1
if self._subframe == self._options.ptmb_subframes_per_frame:
self._subframe = 0
self._frame += 1
self._frame_counter += 1
self._time = self._start_time + (self._frame - self._start_number) * self._time_rate
can_continue = False
if self._forward_one_frame_fn is not None:
can_continue = self._forward_one_frame_fn(dt)
elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \
(self._options.is_video() or self._options.is_capturing_nth_frames()):
self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration
self._update_sunstudy_player_time()
else:
cur_time = (
self._time + (self._options.ptmb_fso * self._time_rate) + self._time_subframe_rate * self._subframe
)
self._timeline.set_current_time(cur_time)
self._settings.set("/iray/current_frame_time", cur_time)
if self._forward_one_frame_fn is not None:
if can_continue == False:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
else:
if self._time >= self._end_time or self._frame_counter >= self._total_frame_count:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
@staticmethod
def get_instance():
global capture_instance
return capture_instance
| 38,884 | Python | 48.91656 | 183 | 0.610045 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/video_generation.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import threading
import carb
from video_encoding import get_video_encoding_interface
from .singleton import Singleton
from .helper import get_num_pattern_file_path
g_video_encoding_api = get_video_encoding_interface()
@Singleton
class VideoGenerationHelper:
def __init__(self):
self._init_internal()
@property
def is_encoding(self):
return self._is_encoding
@property
def encoding_done(self):
return self._is_encoding == False and self._encoding_done == True
def generating_video(
self, video_name, frames_dir, filename_prefix, filename_num_pattern,
start_number, total_frames, frame_rate, image_type=".png"
):
carb.log_warn(f"Using videoencoding plugin to encode video ({video_name})")
global g_video_encoding_api
self._encoding_finished = False
if g_video_encoding_api is None:
carb.log_warn("Video encoding api not available; cannot encode video.")
return False
# acquire list of available frame image files, based on start_number and filename_pattern
next_frame = start_number
frame_count = 0
self._frame_filenames = []
while True:
frame_path = get_num_pattern_file_path(
frames_dir,
filename_prefix,
filename_num_pattern,
next_frame,
image_type
)
if os.path.isfile(frame_path) and os.access(frame_path, os.R_OK):
self._frame_filenames.append(frame_path)
next_frame += 1
frame_count += 1
if frame_count == total_frames:
break
else:
break
carb.log_warn(f"Found {len(self._frame_filenames)} frames to encode.")
if len(self._frame_filenames) == 0:
carb.log_warn(f"No frames to encode.")
return False
if not g_video_encoding_api.start_encoding(video_name, frame_rate, len(self._frame_filenames), True):
carb.log_warn(f"videoencoding plug failed to start encoding.")
return False
if self._encoding_thread == None:
self._encoding_thread = threading.Thread(target=self._encode_image_file_sequence, args=())
self._is_encoding = True
self._encoding_thread.start()
return True
def _init_internal(self):
self._video_generation_done_fn = None
self._frame_filenames = []
self._encoding_thread = None
self._is_encoding = False
self._encoding_done = False
def _encode_image_file_sequence(self):
global g_video_encoding_api
try:
for frame_filename in self._frame_filenames:
g_video_encoding_api.encode_next_frame_from_file(frame_filename)
except:
import traceback
carb.log_warn(traceback.format_exc())
finally:
g_video_encoding_api.finalize_encoding()
self._init_internal()
self._encoding_done = True
| 3,529 | Python | 34.656565 | 109 | 0.620572 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import CaptureExtension
from .capture_options import *
from .capture_progress import *
| 537 | Python | 40.384612 | 76 | 0.808194 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/capture_options.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from enum import Enum, IntEnum
class CaptureMovieType(IntEnum):
SEQUENCE = 0
SUNSTUDY = 1
PLAYLIST = 2
class CaptureRangeType(IntEnum):
FRAMES = 0
SECONDS = 1
class CaptureRenderPreset(IntEnum):
PATH_TRACE = 0
RAY_TRACE = 1
IRAY = 2
class CaptureDebugMaterialType(IntEnum):
SHADED = 0
WHITE = 1
class CaptureOptions:
""" All Capture options that will be used when capturing.
Note: When adding an attribute make sure it is exposed via the constructor.
Not doing this will cause erorrs when serializing and deserializing this object.
"""
def __init__(
self,
camera="camera",
range_type=CaptureRangeType.FRAMES,
capture_every_nth_frames=-1,
fps="24",
start_frame=1,
end_frame=40,
start_time=0,
end_time=10,
res_width=1920,
res_height=1080,
render_preset=CaptureRenderPreset.PATH_TRACE,
debug_material_type=CaptureDebugMaterialType.SHADED,
spp_per_iteration=1,
path_trace_spp=1,
ptmb_subframes_per_frame=1,
ptmb_fso=0.0,
ptmb_fsc=1.0,
output_folder="",
file_name="Capture",
file_name_num_pattern=".####",
file_type=".tga",
save_alpha=False,
hdr_output=False,
show_pathtracing_single_frame_progress=False,
preroll_frames=0,
overwrite_existing_frames=False,
movie_type=CaptureMovieType.SEQUENCE,
sunstudy_start_time=0.0,
sunstudy_current_time=0.0,
sunstudy_end_time=0.0,
sunstudy_movie_length_in_seconds=0,
sunstudy_player=None,
real_time_settle_latency_frames=0,
renumber_negative_frame_number_from_0=False
):
self._camera = camera
self._range_type = range_type
self._capture_every_nth_frames = capture_every_nth_frames
self._fps = fps
self._start_frame = start_frame
self._end_frame = end_frame
self._start_time = start_time
self._end_time = end_time
self._res_width = res_width
self._res_height = res_height
self._render_preset = render_preset
self._debug_material_type = debug_material_type
self._spp_per_iteration = spp_per_iteration
self._path_trace_spp = path_trace_spp
self._ptmb_subframes_per_frame = ptmb_subframes_per_frame
self._ptmb_fso = ptmb_fso
self._ptmb_fsc = ptmb_fsc
self._output_folder = output_folder
self._file_name = file_name
self._file_name_num_pattern = file_name_num_pattern
self._file_type = file_type
self._save_alpha = save_alpha
self._hdr_output = hdr_output
self._show_pathtracing_single_frame_progress = show_pathtracing_single_frame_progress
self._preroll_frames = preroll_frames
self._overwrite_existing_frames = overwrite_existing_frames
self._movie_type = movie_type
self._sunstudy_start_time = sunstudy_start_time
self._sunstudy_current_time = sunstudy_current_time
self._sunstudy_end_time = sunstudy_end_time
self._sunstudy_movie_length_in_seconds = sunstudy_movie_length_in_seconds
self._sunstudy_player = sunstudy_player
self._real_time_settle_latency_frames = real_time_settle_latency_frames
self._renumber_negative_frame_number_from_0 = renumber_negative_frame_number_from_0
def to_dict(self):
data = vars(self)
return {key.lstrip("_"): value for key, value in data.items()}
@classmethod
def from_dict(cls, options):
return cls(**options)
@property
def camera(self):
return self._camera
@camera.setter
def camera(self, value):
self._camera = value
@property
def range_type(self):
return self._range_type
@range_type.setter
def range_type(self, value):
self._range_type = value
@property
def capture_every_Nth_frames(self):
return self._capture_every_nth_frames
@capture_every_Nth_frames.setter
def capture_every_Nth_frames(self, value):
self._capture_every_nth_frames = value
@property
def fps(self):
return self._fps
@fps.setter
def fps(self, value):
self._fps = value
@property
def start_frame(self):
return self._start_frame
@start_frame.setter
def start_frame(self, value):
self._start_frame = value
@property
def end_frame(self):
return self._end_frame
@end_frame.setter
def end_frame(self, value):
self._end_frame = value
@property
def start_time(self):
return self._start_time
@start_time.setter
def start_time(self, value):
self._start_time = value
@property
def end_time(self):
return self._end_time
@end_time.setter
def end_time(self, value):
self._end_time = value
@property
def res_width(self):
return self._res_width
@res_width.setter
def res_width(self, value):
self._res_width = value
@property
def res_height(self):
return self._res_height
@res_height.setter
def res_height(self, value):
self._res_height = value
@property
def render_preset(self):
return self._render_preset
@render_preset.setter
def render_preset(self, value):
self._render_preset = value
@property
def debug_material_type(self):
return self._debug_material_type
@debug_material_type.setter
def debug_material_type(self, value):
self._debug_material_type = value
@property
def spp_per_iteration(self):
return self._spp_per_iteration
@spp_per_iteration.setter
def spp_per_iteration(self, value):
self._spp_per_iteration = value
@property
def path_trace_spp(self):
return self._path_trace_spp
@path_trace_spp.setter
def path_trace_spp(self, value):
self._path_trace_spp = value
@property
def ptmb_subframes_per_frame(self):
return self._ptmb_subframes_per_frame
@ptmb_subframes_per_frame.setter
def ptmb_subframes_per_frame(self, value):
self._ptmb_subframes_per_frame = value
@property
def ptmb_fso(self):
return self._ptmb_fso
@ptmb_fso.setter
def ptmb_fso(self, value):
self._ptmb_fso = value
@property
def ptmb_fsc(self):
return self._ptmb_fsc
@ptmb_fsc.setter
def ptmb_fsc(self, value):
self._ptmb_fsc = value
@property
def output_folder(self):
return self._output_folder
@output_folder.setter
def output_folder(self, value):
self._output_folder = value
@property
def file_name(self):
return self._file_name
@file_name.setter
def file_name(self, value):
self._file_name = value
@property
def file_name_num_pattern(self):
return self._file_name_num_pattern
@file_name_num_pattern.setter
def file_name_num_pattern(self, value):
self._file_name_num_pattern = value
@property
def file_type(self):
return self._file_type
@file_type.setter
def file_type(self, value):
self._file_type = value
@property
def save_alpha(self):
return self._save_alpha
@save_alpha.setter
def save_alpha(self, value):
self._save_alpha = value
@property
def hdr_output(self):
return self._hdr_output
@hdr_output.setter
def hdr_output(self, value):
self._hdr_output = value
@property
def show_pathtracing_single_frame_progress(self):
return self._show_pathtracing_single_frame_progress
@show_pathtracing_single_frame_progress.setter
def show_pathtracing_single_frame_progress(self, value):
self._show_pathtracing_single_frame_progress = value
@property
def preroll_frames(self):
return self._preroll_frames
@preroll_frames.setter
def preroll_frames(self, value):
self._preroll_frames = value
@property
def overwrite_existing_frames(self):
return self._overwrite_existing_frames
@overwrite_existing_frames.setter
def overwrite_existing_frames(self, value):
self._overwrite_existing_frames = value
@property
def movie_type(self):
return self._movie_type
@movie_type.setter
def movie_type(self, value):
self._movie_type = value
@property
def sunstudy_start_time(self):
return self._sunstudy_start_time
@sunstudy_start_time.setter
def sunstudy_start_time(self, value):
self._sunstudy_start_time = value
@property
def sunstudy_current_time(self):
return self._sunstudy_current_time
@sunstudy_current_time.setter
def sunstudy_current_time(self, value):
self._sunstudy_current_time = value
@property
def sunstudy_end_time(self):
return self._sunstudy_end_time
@sunstudy_end_time.setter
def sunstudy_end_time(self, value):
self._sunstudy_end_time = value
@property
def sunstudy_movie_length_in_seconds(self):
return self._sunstudy_movie_length_in_seconds
@sunstudy_movie_length_in_seconds.setter
def sunstudy_movie_length_in_seconds(self, value):
self._sunstudy_movie_length_in_seconds = value
@property
def sunstudy_player(self):
return self._sunstudy_player
@sunstudy_player.setter
def sunstudy_player(self, value):
self._sunstudy_player = value
@property
def real_time_settle_latency_frames(self):
return self._real_time_settle_latency_frames
@real_time_settle_latency_frames.setter
def real_time_settle_latency_frames(self, value):
self._real_time_settle_latency_frames = value
@property
def renumber_negative_frame_number_from_0(self):
return self._renumber_negative_frame_number_from_0
@renumber_negative_frame_number_from_0.setter
def renumber_negative_frame_number_from_0(self, value):
self._renumber_negative_frame_number_from_0 = value
def is_video(self):
return self.file_type == ".mp4"
def is_capturing_nth_frames(self):
return self._capture_every_nth_frames > 0
def is_capturing_pathtracing_single_frame(self):
return self.is_video() is False and self.is_capturing_nth_frames() is False and self.render_preset == CaptureRenderPreset.PATH_TRACE
def is_capturing_frame(self):
return self._range_type == CaptureRangeType.FRAMES
def get_full_path(self):
return os.path.join(self._output_folder, self._file_name + self._file_type)
| 11,163 | Python | 26.429975 | 140 | 0.642659 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/helper.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
def get_num_pattern_file_path(frames_dir, file_name, num_pattern, frame_num, file_type, renumber_frames=False, renumber_offset=0):
if renumber_frames:
renumbered_frames = frame_num + renumber_offset
else:
renumbered_frames = frame_num
abs_frame_num = abs(renumbered_frames)
padding_length = len(num_pattern.strip(".")[len(str(abs_frame_num)) :])
if renumbered_frames >= 0:
padded_string = "0" * padding_length + str(renumbered_frames)
else:
padded_string = "-" + "0" * padding_length + str(abs_frame_num)
filename = ".".join((file_name, padded_string, file_type.strip(".")))
frame_path = os.path.join(frames_dir, filename)
return frame_path
| 1,154 | Python | 43.423075 | 130 | 0.713172 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/singleton.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
def Singleton(class_):
"""A singleton decorator"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
| 697 | Python | 32.238094 | 76 | 0.725968 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/tests/__init__.py | from .test_capture_options import TestCaptureOptions
# from .test_capture_hdr import TestCaptureHdr
| 100 | Python | 32.666656 | 52 | 0.84 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/tests/test_capture_hdr.py | from typing import Type
import os.path
import omni.kit.test
import carb
import carb.settings
import carb.tokens
import pathlib
import omni.kit.capture.capture_options as _capture_options
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file, create_viewport_window
OUTPUTS_DIR = omni.kit.test.get_test_output_path()
class TestCaptureHdr(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
settings = carb.settings.get_settings()
settings.set("/app/asyncRendering", False)
settings.set("/app/asyncRenderingLowLatency", False)
settings.set("/app/captureFrame/hdr", True)
# Setup viewport
self._usd_context = ''
await omni.usd.get_context(self._usd_context).new_stage_async()
async def test_hdr_capture(self):
viewport_api = get_active_viewport(self._usd_context)
if viewport_api is None:
return
# Wait until the viewport has valid resources
await viewport_api.wait_for_rendered_frames()
capture_filename = "capture.hdr_test.exr"
filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename)
capture_viewport_to_file(viewport_api, str(filePath))
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
assert os.path.isfile(str(filePath))
# Make sure we do not crash in the unsupported multi-view case
async def do_test_hdr_multiview_capture(self, test_legacy: bool):
viewport_api = get_active_viewport(self._usd_context)
if viewport_api is None:
return
# Wait until the viewport has valid resources
await viewport_api.wait_for_rendered_frames()
second_vp_window = create_viewport_window('Viewport 2', width=256, height=256)
await second_vp_window.viewport_api.wait_for_rendered_frames()
capture_filename = "capture.hdr_test.multiview.exr"
filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename)
# Multiview HDR output is not yet fully supported, confirm this exits gracefully
capture_viewport_to_file(viewport_api, str(filePath))
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
assert os.path.isfile(str(filePath))
second_vp_window.destroy()
del second_vp_window
async def test_hdr_multiview_capture_legacy(self):
await self.do_test_hdr_multiview_capture(True)
async def test_hdr_multiview_capture(self):
await self.do_test_hdr_multiview_capture(False)
| 2,828 | Python | 36.223684 | 107 | 0.688826 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/tests/test_capture_options.py | from typing import Type
import omni.kit.test
import omni.kit.capture.capture_options as _capture_options
class TestCaptureOptions(omni.kit.test.AsyncTestCase):
async def test_capture_options_serialisation(self):
options = _capture_options.CaptureOptions()
data_dict = options.to_dict()
self.assertIsInstance(data_dict, dict)
async def test_capture_options_deserialisation(self):
options = _capture_options.CaptureOptions()
data_dict = options.to_dict()
regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict)
self.assertIsInstance(regenerated_options, _capture_options.CaptureOptions)
async def test_capture_options_values_persisted(self):
options = _capture_options.CaptureOptions(camera="my_camera")
data_dict = options.to_dict()
regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict)
self.assertEqual(regenerated_options.camera, "my_camera")
async def test_adding_random_attribute_fails(self):
""" Test that adding new attributes without making them configurable via the __init__ will raise an exception
"""
options = _capture_options.CaptureOptions()
options._my_new_value = "foo"
data_dict = options.to_dict()
with self.assertRaises(TypeError, msg="__init__() got an unexpected keyword argument 'my_new_value'"):
regnerated = _capture_options.CaptureOptions.from_dict(data_dict) | 1,496 | Python | 40.583332 | 117 | 0.703209 |
omniverse-code/kit/exts/omni.kit.capture/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.5.1] - 2022-06-22
### Changed
- Add declaration of deprecation: this extension has been replaced with omni.kit.capture.viewport will be removed in future releases.
## [0.5.0] - 2022-05-23
### Changes
- Support legacy and new Viewport API
- Add dependency on omni.kit.viewport.utility
## [0.4.9] - 2021-11-27
### Changed
- Changed the way sunstudy updates its player by supporting the new player in environment.sunstudy
## [0.4.8] - 2021-09-08
### Changed
- Merge fixes from the release/102 branch; fixes includes:
- Fix the iray capture produces duplicated images issue
- Fix corrupted EXR image capture under certain circumstances, due to the rendering not behaving according to the value of the `asyncRendering` setting
- Backport required features of the plugin related to validation of frame counts and erroneous selection of Hydra engine when switching between RTX and Iray
- Add current frame index and total frame count to the notification system during frame capture
## [0.4.4] - 2021-07-05
### Added
- Added current frame index and total frame count to the notification system during frame capture.
## [0.4.3] - 2021-07-04
### Fixed
- Fixed the issue that can't switch to iray mode to capture images
## [0.4.2] - 2021-06-14
### Added
- Added support to renumber negative frame numbers from zero
### Changed
- Negative frame number format changed from ".00-x.png" to ".-000x.png"
## [0.4.1] - 2021-06-09
### Added
- Added the handling of path tracing iterations for capturing in Iray mode, also added a new entry to show number of iterations done on the progress window for Iray capturing
## [0.4.0] - 2021-05-25
### Fixed
- Fixed the issue that animation timeline's current time reset to zero after capture, now it's restored to the time before capture
## [0.3.9] - 2021-05-20
### Added
- Added a settle latency for capture in RTX real time mode to set the number of frames to be settled to improve image quality for each frame captured
## [0.3.8] - 2021-05-11
### Added
- Added support to the overwrite existing frame option; now if the frame path exists already, will warn either it will be skipped or it will be overwritten
- Added capture end callback in case users want it
### Fixed
- Fixed the issue that capture doesn't end in time if there are skipped frames
- Fixed the issue that all frames with number greater than start frame number in the output folder will be encoded into the final mp4 file, now only captured frames will be added.
## [0.3.7] - 2021-04-29
### Added
- Add support to new movie type sunstudy
## [0.3.6] - 2021-04-15
### Changed
- Change the name pattern of images of mp4 to be the same to capture Nth frames name pattern
## [0.3.5] - 2021-04-10
### Added
- Add support to skip existing frames at capturing sequence
## [0.3.4] - 2021-04-02
### Added
- Add preroll frames support so that it can run given frames before starting actual capturing. To save performance
for the preroll frames, "/rtx/pathtracing/spp" for path tracing will be set to 1
## [0.3.3] - 2021-03-01
### Added
- Add progress report of single frame capture in PT mode
- Update progress timers for video captures per iteration instead of per frame
## [0.3.2] - 2021-02-03
### Fixed
- Fix the time precision is a bit much issue
## [0.3.1] - 2021-02-03
### Fixed
- Fixed the PhysX and Flow simulation speed is much faster than normal in the captured movie issue
- Fixed the path tracing options are wrongly taken in the ray tracing mode during capture issue
## [0.3.0] - 2020-12-03
### Added
- Add support to capture in IRay mode
## [0.2.1] - 2020-11-30
### Removed
- Removed verbose warning during startup
## [0.2.0] - 2020-11-19
### Added
- Added functionality to capture with Kit Next
## [0.1.7] - 2020-10-19
### Fixed
- Hide lights and grid during capturing
## [0.1.6] - 2020-10-08
### Fixed
- Correct the update of motion blur subframe time
- Make sure frame count is right with when motion blur frame shutter open and close difference is not 1
## [0.1.5] - 2020-10-07
### Fixed
- Pass through the right file name
- Make sure padding is applied for files
| 4,191 | Markdown | 35.137931 | 179 | 0.730375 |
omniverse-code/kit/exts/omni.kit.capture/docs/README.md | # Omniverse Kit Image and Video Capture
Extension to handle the capturing and recording of the viewport | 104 | Markdown | 33.999989 | 63 | 0.826923 |
omniverse-code/kit/exts/omni.kit.window.splash_close_example/PACKAGE-LICENSES/omni.kit.window.splash_close_example-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.window.splash_close_example/config/extension.toml | [package]
version = "0.2.0"
category = "Internal"
[core]
# Load as late as possible
order = 10000
[dependencies]
"omni.kit.window.splash" = { optional = true }
[[python.module]]
name = "omni.kit.window.splash_close_example"
[[test]]
waiver = "Simple example extension" # OM-48132
| 285 | TOML | 14.888888 | 46 | 0.687719 |
omniverse-code/kit/exts/omni.kit.window.splash_close_example/omni/kit/window/splash_close_example/extension.py | import carb
import omni.ext
class SplashCloseExtension(omni.ext.IExt):
def on_startup(self):
try:
import omni.splash
splash_iface = omni.splash.acquire_splash_screen_interface()
except (ImportError, ModuleNotFoundError):
splash_iface = None
if not splash_iface:
return
splash_iface.close_all()
def on_shutdown(self):
pass
| 424 | Python | 19.238094 | 72 | 0.603774 |
omniverse-code/kit/exts/omni.kit.window.splash_close_example/omni/kit/window/splash_close_example/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
omniverse-code/kit/exts/omni.kit.window.splash_close_example/docs/index.rst | omni.kit.window.splash_close_example: omni.kit.window.stats
############################################################
Window to display omni.stats
| 152 | reStructuredText | 24.499996 | 60 | 0.480263 |
omniverse-code/kit/exts/omni.kit.property.light/PACKAGE-LICENSES/omni.kit.property.light-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.property.light/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.6"
category = "Internal"
feature = true
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "Light Property Widget"
description="View and Edit Light Property Values"
# URL of the extension source repository.
repository = ""
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Keywords for the extension
keywords = ["kit", "usd", "property", "light"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
[dependencies]
"omni.usd" = {}
"omni.ui" = {}
"omni.kit.window.property" = {}
"omni.kit.property.usd" = {}
[[python.module]]
name = "omni.kit.property.light"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/app/file/ignoreUnsavedOnExit=true",
"--/persistent/app/stage/dragDropImport='reference'",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=false",
"--no-window"
]
dependencies = [
"omni.usd",
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.material.library", # for omni_pbr...
"omni.kit.window.content_browser",
"omni.kit.window.stage",
"omni.kit.property.material",
"omni.kit.window.status_bar",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers",
"omni.kit.window.file",
"omni.hydra.pxr",
"omni.kit.window.viewport",
"omni.kit.window.content_browser"
]
stdoutFailPatterns.exclude = [
"*Failed to acquire interface*while unloading all plugins*"
]
| 2,357 | TOML | 28.848101 | 94 | 0.693678 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/__init__.py | from .scripts import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/scripts/light_properties.py | import os
import carb
import omni.ext
from pathlib import Path
from pxr import Sdf, UsdLux, Usd
TEST_DATA_PATH = ""
class LightPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from .prim_light_widget import LightSchemaAttributesWidget
w = p.get_window()
if w:
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
w.register_widget(
"prim",
"light",
LightSchemaAttributesWidget(
"Light",
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
UsdLux.LightAPI if hasattr(UsdLux, 'LightAPI') else UsdLux.Light,
[
UsdLux.CylinderLight,
UsdLux.DiskLight,
UsdLux.DistantLight,
UsdLux.DomeLight,
UsdLux.GeometryLight,
UsdLux.RectLight,
UsdLux.SphereLight,
UsdLux.ShapingAPI,
UsdLux.ShadowAPI,
UsdLux.LightFilter,
# https://github.com/PixarAnimationStudios/USD/commit/9eda37ec9e1692dd290efd9a26526e0d2c21bb03
UsdLux.PortalLight if hasattr(UsdLux, 'PortalLight') else UsdLux.LightPortal,
UsdLux.ListAPI,
],
[
"color",
"enableColorTemperature",
"colorTemperature",
"intensity",
"exposure",
"normalize",
"angle",
"radius",
"height",
"width",
"radius",
"length",
"texture:file",
"texture:format",
"diffuse",
"specular",
"shaping:focus",
"shaping:focusTint",
"shaping:cone:angle",
"shaping:cone:softness",
"shaping:ies:file",
"shaping:ies:angleScale",
"shaping:ies:normalize",
"collection:shadowLink:expansionRule",
"collection:shadowLink:excludes",
"collection:shadowLink:includes",
"collection:lightLink:expansionRule",
"collection:lightLink:excludes",
"collection:lightLink:includes",
"light:enableCaustics",
"visibleInPrimaryRay",
"disableFogInteraction",
"isProjector",
] \
# https://github.com/PixarAnimationStudios/USD/commit/c8cd344af6be342911e50d2350c228ed329be6b2
# USD v22.08 adds this to LightAPI as an API schema override of CollectionAPI
+ (["collection:lightLink:includeRoot"] if Usd.GetVersion() >= (0,22,8) else []),
[],
),
)
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "light")
self._registered = False
| 4,274 | Python | 37.863636 | 118 | 0.477305 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/scripts/__init__.py | from .light_properties import *
| 32 | Python | 15.499992 | 31 | 0.78125 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/scripts/prim_light_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Set
import omni.ui as ui
import omni.usd
from omni.kit.property.usd.usd_property_widget import MultiSchemaPropertiesWidget, UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import create_primspec_bool
from pxr import Kind, Sdf, Usd, UsdLux
import carb
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class LightSchemaAttributesWidget(MultiSchemaPropertiesWidget):
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
self._settings = carb.settings.get_settings()
self._setting_path = PERSISTENT_SETTINGS_PREFIX + "/app/usd/usdLuxUnprefixedCompat"
self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change)
self.lux_attributes: Set[str] = set(['inputs:angle', 'inputs:color', 'inputs:temperature', 'inputs:diffuse', 'inputs:specular', 'inputs:enableColorTemperature',
'inputs:exposure', 'inputs:height', 'inputs:width', 'inputs:intensity', 'inputs:length',
'inputs:normalize', 'inputs:radius', 'inputs:shadow:color', 'inputs:shadow:distance', 'inputs:shadow:enable', 'inputs:shadow:falloff',
'inputs:shadow:falloffGamma', 'inputs:shaping:cone:angle', 'inputs:shaping:cone:softness', 'inputs:shaping:focus',
'inputs:shaping:focusTint', 'inputs:shaping:ies:angleScale', 'inputs:shaping:ies:file', 'inputs:shaping:ies:normalize', 'inputs:texture:format'])
# custom attributes
def is_prim_light_primary_visible_supported(prim):
return (
prim.IsA(UsdLux.DomeLight)
or prim.IsA(UsdLux.DiskLight)
or prim.IsA(UsdLux.RectLight)
or prim.IsA(UsdLux.SphereLight)
or prim.IsA(UsdLux.CylinderLight)
or prim.IsA(UsdLux.DistantLight)
)
def is_prim_light_disable_fog_interaction_supported(prim):
return (
prim.IsA(UsdLux.DomeLight)
or prim.IsA(UsdLux.DiskLight)
or prim.IsA(UsdLux.RectLight)
or prim.IsA(UsdLux.SphereLight)
or prim.IsA(UsdLux.CylinderLight)
or prim.IsA(UsdLux.DistantLight)
)
def is_prim_light_caustics_supported(prim):
return prim.IsA(UsdLux.DiskLight) or prim.IsA(UsdLux.RectLight) or prim.IsA(UsdLux.SphereLight)
def is_prim_light_is_projector_supported(prim):
return prim.IsA(UsdLux.RectLight)
def add_vipr(attribute_name, value_dict):
anchor_prim = self._get_prim(self._payload[-1])
if anchor_prim and (anchor_prim.IsA(UsdLux.DomeLight) or anchor_prim.IsA(UsdLux.DistantLight)):
return UsdPropertyUiEntry("visibleInPrimaryRay", "", create_primspec_bool(True), Usd.Attribute)
else:
return UsdPropertyUiEntry("visibleInPrimaryRay", "", create_primspec_bool(False), Usd.Attribute)
self.add_custom_schema_attribute("visibleInPrimaryRay", is_prim_light_primary_visible_supported, add_vipr, "", {})
self.add_custom_schema_attribute("disableFogInteraction", is_prim_light_disable_fog_interaction_supported, None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("light:enableCaustics", is_prim_light_caustics_supported, None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("isProjector", is_prim_light_is_projector_supported, None, "", create_primspec_bool(False))
def _on_change(self, item, event_type):
self.request_rebuild()
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
if self._schema().IsTyped() and not prim.IsA(self._schema):
return False
if self._schema().IsAPISchema() and not prim.HasAPI(self._schema):
return False
used += [attr for attr in prim.GetAttributes() if attr.GetName() in self._schema_attr_names and not attr.IsHidden()]
if self.is_custom_schema_attribute_used(prim):
used.append(None)
return used
def has_authored_inputs_attr(self, prim):
attrs = set([a.GetName() for a in prim.GetAuthoredAttributes()])
any_authored = attrs.intersection(self.lux_attributes)
return any_authored
def _customize_props_layout(self, attrs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.window.property.templates import (
SimplePropertyWidget,
LABEL_WIDTH,
LABEL_HEIGHT,
HORIZONTAL_SPACING,
)
self.add_custom_schema_attributes_to_props(attrs)
frame = CustomLayoutFrame(hide_extra=False)
anchor_prim = self._get_prim(self._payload[-1])
# TODO -
# add shadow values (Shadow Enable, Shadow Include, Shadow Exclude, Shadow Color, Shadow Distance, Shadow Falloff, Shadow Falloff Gamma)
# add UsdLux.DomeLight portals (see UsdLux.DomeLight GetPortalsRel)
# add filters (see UsdLux.Light / UsdLux.LightAPI GetFiltersRel)
self.usdLuxUnprefixedCompat = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/usd/usdLuxUnprefixedCompat")
has_authored_inputs = self.has_authored_inputs_attr(anchor_prim)
with frame:
with CustomLayoutGroup("Main"):
self._create_property("color", "Color", anchor_prim, has_authored_inputs)
self._create_property("enableColorTemperature", "Enable Color Temperature", anchor_prim, has_authored_inputs)
self._create_property("colorTemperature", "Color Temperature", anchor_prim, has_authored_inputs)
self._create_property("intensity", "Intensity", anchor_prim, has_authored_inputs)
self._create_property("exposure", "Exposure", anchor_prim, has_authored_inputs)
self._create_property("normalize", "Normalize Power", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.DistantLight):
self._create_property("angle", "Angle", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.DiskLight):
self._create_property("radius", "Radius", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.RectLight):
self._create_property("height", "Height", anchor_prim, has_authored_inputs)
self._create_property("width", "Width", anchor_prim, has_authored_inputs)
self._create_property("texture:file", "Texture File", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.SphereLight):
self._create_property("radius", "Radius", anchor_prim, has_authored_inputs)
CustomLayoutProperty("treatAsPoint", "Treat As Point")
if anchor_prim and anchor_prim.IsA(UsdLux.CylinderLight):
self._create_property("length", "Length", anchor_prim, has_authored_inputs)
self._create_property("radius", "Radius", anchor_prim, has_authored_inputs)
CustomLayoutProperty("treatAsLine", "Treat As Line")
if anchor_prim and anchor_prim.IsA(UsdLux.DomeLight):
self._create_property("texture:file", "Texture File", anchor_prim, has_authored_inputs)
self._create_property("texture:format", "Texture Format", anchor_prim, has_authored_inputs)
self._create_property("diffuse", "Diffuse Multiplier", anchor_prim, has_authored_inputs)
self._create_property("specular", "Specular Multiplier", anchor_prim, has_authored_inputs)
CustomLayoutProperty("visibleInPrimaryRay", "Visible In Primary Ray")
CustomLayoutProperty("disableFogInteraction", "Disable Fog Interaction")
CustomLayoutProperty("light:enableCaustics", "Enable Caustics")
CustomLayoutProperty("isProjector", "Projector light type")
with CustomLayoutGroup("Shaping", collapsed=True):
self._create_property("shaping:focus", "Focus", anchor_prim, has_authored_inputs)
self._create_property("shaping:focusTint", "Focus Tint", anchor_prim, has_authored_inputs)
self._create_property("shaping:cone:angle", "Cone Angle", anchor_prim, has_authored_inputs)
self._create_property("shaping:cone:softness", "Cone Softness", anchor_prim, has_authored_inputs)
self._create_property("shaping:ies:file", "File", anchor_prim, has_authored_inputs)
self._create_property("shaping:ies:angleScale", "AngleScale", anchor_prim, has_authored_inputs)
self._create_property("shaping:ies:normalize", "Normalize", anchor_prim, has_authored_inputs)
with CustomLayoutGroup("Light Link"):
CustomLayoutProperty("collection:lightLink:includeRoot", "Light Link Include Root")
CustomLayoutProperty("collection:lightLink:expansionRule", "Light Link Expansion Rule")
CustomLayoutProperty("collection:lightLink:includes", "Light Link Includes")
CustomLayoutProperty("collection:lightLink:excludes", "Light Link Excludes")
with CustomLayoutGroup("Shadow Link"):
CustomLayoutProperty("collection:shadowLink:includeRoot", "Shadow Link Include Root")
CustomLayoutProperty("collection:shadowLink:expansionRule", "Shadow Link Expansion Rule")
CustomLayoutProperty("collection:shadowLink:includes", "Shadow Link Includes")
CustomLayoutProperty("collection:shadowLink:excludes", "Shadow Link Excludes")
return frame.apply(attrs)
def _create_property(self, name: str, display_name: str, prim, has_authored_inputs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutProperty
)
if has_authored_inputs or not self.usdLuxUnprefixedCompat or not prim.HasAttribute(name):
prefixed_name = "inputs:" + name
return CustomLayoutProperty(prefixed_name, display_name)
return CustomLayoutProperty(name, display_name)
| 11,860 | Python | 54.167442 | 168 | 0.649494 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/tests/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .test_light import *
from .test_drag_drop_HDRI_property import *
| 503 | Python | 44.818178 | 76 | 0.801193 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/tests/test_light.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import pathlib
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading
from pxr import Kind, Sdf, Gf
class TestLightWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
usd_path = pathlib.Path(get_test_data_path(__name__))
self._golden_img_dir = usd_path.absolute().joinpath("golden_img").absolute()
self._usd_path = usd_path.absolute()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
await super().tearDown()
await wait_stage_loading()
# Test(s)
async def test_light_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=650,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("light_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await wait_stage_loading()
# NOTE: cannot do DomeLight as it contains a file path which is build specific
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/DistantLight"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_light_ui.png")
| 2,320 | Python | 36.435483 | 106 | 0.6875 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/tests/test_drag_drop_HDRI_property.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
build_sdf_asset_frame_dictonary,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropHDRIProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "dome_light.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_drag_drop_HDRI_property(self):
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ["/World/DomeLight"]
# select prim
await select_prims(to_select)
# wait for material to load & UI to refresh
await wait_stage_loading()
# open all CollapsableFrames
for frame in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if frame.widget.title != "Raw USD Properties":
frame.widget.scroll_here_y(0.5)
frame.widget.collapsed = False
await ui_test.human_delay()
# prep content window for drag/drop
texture_path = get_test_data_path(__name__, "textures/sunflowers.hdr")
# NOTE: cannot keep using widget as they become stale as window refreshes due to set_value
# do tests
widget_table = await build_sdf_asset_frame_dictonary()
for frame_name in widget_table.keys():
if frame_name in ["Raw USD Properties", "Extra Properties"]:
continue
for field_name in widget_table[frame_name].keys():
# NOTE: sdf_asset_ could be used more than once, if so skip
if widget_table[frame_name][field_name] == 1:
def get_widget():
return ui_test.find(f"Property//Frame/**/CollapsableFrame[*].title=='{frame_name}'").find(f"**/StringField[*].identifier=='{field_name}'")
# scroll to widget
get_widget().widget.scroll_here_y(0.5)
await ui_test.human_delay()
# reset for test
get_widget().model.set_value("")
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.drag_and_drop_tree_view(texture_path, drag_target=get_widget().center)
# verify dragged item(s)
for prim_path in to_select:
prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
self.assertTrue(prim.IsValid())
attr = prim.GetAttribute(field_name[10:])
self.assertTrue(attr.IsValid())
asset_path = attr.Get()
self.assertTrue(asset_path != None)
self.assertTrue(asset_path.resolvedPath.replace("\\", "/").lower() == texture_path.replace("\\", "/").lower())
# reset for next test
get_widget().model.set_value("")
| 3,916 | Python | 39.802083 | 162 | 0.599081 |
omniverse-code/kit/exts/omni.kit.property.light/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.6] - 2022-07-25
### Changes
- Refactored unittests to make use of content_browser test helpers
## [1.0.5] - 2022-01-10
### Changes
- Updated Shadow Link & Light Link. Now has include/exclude
## [1.0.4] - 2021-02-19
### Changes
- Added UI test
## [1.0.3] - 2021-01-11
### Changes
- visibleInPrimaryRay default value changed to True
## [1.0.2] - 2020-12-09
### Changes
- Added extension icon
- Added readme
- Updated preview image
## [1.0.1] - 2020-10-22
### Changes
- Improved layout
## [1.0.0] - 2020-09-17
### Changes
- Created
| 638 | Markdown | 17.794117 | 80 | 0.65674 |
omniverse-code/kit/exts/omni.kit.property.light/docs/README.md | # omni.kit.property.light
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension supports editing of these Usd Types;
- UsdLux.CylinderLight
- UsdLux.DiskLight
- UsdLux.DistantLight
- UsdLux.DomeLight
- UsdLux.GeometryLight
- UsdLux.RectLight
- UsdLux.SphereLight
- UsdLux.ShapingAPI
- UsdLux.ShadowAPI
- UsdLux.LightFilter
- UsdLux.LightPortal
### and supports editing of these Usd APIs;
- UsdLux.ListAPI
| 467 | Markdown | 17.719999 | 74 | 0.785867 |
omniverse-code/kit/exts/omni.kit.property.light/docs/index.rst | omni.kit.property.light
###########################
Property Light Values
.. toctree::
:maxdepth: 1
CHANGELOG
| 121 | reStructuredText | 9.166666 | 27 | 0.528926 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/PACKAGE-LICENSES/omni.kit.audiodeviceenum-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/config/extension.toml | [package]
title = "Kit Audio Device Enumerator"
category = "Audio"
feature = true
version = "1.0.0"
description = "An audio device enumeration API which is available from python and C++"
authors = ["NVIDIA"]
keywords = ["audio", "device"]
[dependencies]
"carb.audio" = {}
[[native.plugin]]
path = "bin/*.plugin"
[[python.module]]
name = "omni.kit.audiodeviceenum"
| 368 | TOML | 18.421052 | 86 | 0.690217 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/__init__.py | """
This module contains bindings to the C++ omni::audio::IAudioDeviceEnum
interface. This provides functionality for enumerating available audio devices
and collecting some basic information on each one.
Sound devices attached to the system may change at any point due to user
activity (ie: connecting or unplugging a USB audio device). When enumerating
devices, it is important to collect all device information directly instead
of caching it.
The device information is suitable to be used to display to a user in a menu
to allow them to choose a device to use by name.
"""
from ._audiodeviceenum import *
# Cached audio device enumerator instance pointer
def get_audio_device_enum_interface() -> IAudioDeviceEnum:
"""
helper method to retrieve a cached version of the IAudioDeviceEnum interface.
Returns:
The cached :class:`omni.kit.audiodeviceenum.IAudioDeviceEnum` interface. This will
only be retrieved on the first call. All subsequent calls will return the cached
interface object.
"""
if not hasattr(get_audio_device_enum_interface, "audio_device_enum"):
get_audio_device_enum_interface.audio_device_enum = acquire_audio_device_enum_interface()
return get_audio_device_enum_interface.audio_device_enum
| 1,351 | Python | 39.969696 | 97 | 0.720207 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/_audio.pyi | """
This module contains bindings to the C++ omni::audio::IAudioDeviceEnum
interface. This provides functionality for enumerating available audio
devices and collecting some basic information on each one.
Sound devices attached to the system may change at any point due to user
activity (ie: connecting or unplugging a USB audio device). When enumerating
devices, it is important to collect all device information directly instead
of caching it.
The device information is suitable to be used to display to a user in a menu
to allow them to choose a device to use by name.
"""
import omni.kit.audiodeviceenum._audio
import typing
__all__ = [
"Direction",
"IAudioDeviceEnum",
"SampleType",
"acquire_audio_device_enum_interface"
]
class Direction():
"""
Members:
PLAYBACK : audio playback devices only.
CAPTURE : audio capture devices only.
"""
def __init__(self, arg0: int) -> None: ...
def __int__(self) -> int: ...
@property
def name(self) -> str:
"""
(self: handle) -> str
:type: str
"""
CAPTURE: omni.kit.audiodeviceenum._audio.Direction # value = Direction.CAPTURE
PLAYBACK: omni.kit.audiodeviceenum._audio.Direction # value = Direction.PLAYBACK
__members__: dict # value = {'PLAYBACK': Direction.PLAYBACK, 'CAPTURE': Direction.CAPTURE}
pass
class IAudioDeviceEnum():
"""
This interface contains functions for audio device enumeration. This is able to
enumerate all audio devices attached to the system at any given point and collect the
information for each device. This is only intended to collect the device information
needed to display to the user for device selection purposes. If a device is to be
chosen based on certain needs (ie: channel count, frame rate, etc), it should be done
directly through the audio playback or capture context during creation. This is able
to collect information for both playback and capture devices.
All the function in this interface are in omni.kit.audio.IAudioDeviceEnum class.
To retrieve this object, use get_audio_device_enum_interface() method:
>>> import omni.kit.audio
>>> dev = omni.kit.audio.get_audio_device_enum_interface()
>>> count = dev.get_device_count(PLAYBACK)
>>> desc = dev.get_device_description(PLAYBACK, 0)
"""
def get_device_channel_count(self, dir: Direction, index: int) -> int:
"""
Retrieves the maximum channel count for a requested device.
This retrieves the maximum channel count for a requested device. This count
is the maximum number of channels that the device can natively handle without
having to trim or reprocess the data. Using a device with a different channel
count than its maximum is allowed but will result in extra processing time to
upmix or downmix channels in the stream. Note that downmixing channel counts
(ie: 7.1 to stereo) will often result in multiple channels being blended
together and can result in an unexpected final signal in certain cases.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the maximum channel count for.
index: the index of the device to retrieve the channel count for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the maximum channel count of the requested device.
If the requested device is out of range of those connected to the system, 0
is returned.
"""
def get_device_count(self, dir: Direction) -> int:
"""
Retrieves the total number of devices attached to the system of a requested type.
Args:
dir: the audio direction to get the device count for.
Returns:
If successful, this returns the total number of connected audio devices of the
requested type.
If there are no devices of the requested type connected to the system, 0 is
returned.
"""
def get_device_description(self, dir: Direction, index: int) -> object:
"""
Retrieves a descriptive string for a requested audio device.
This retrieves a descriptive string for the requested device. This string is
suitable for display to a user in a menu or selection list.
Args:
dir: the audio direction to get the description string for.
index: the index of the device to retrieve the description for. This should be
between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns a python string describing the requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_frame_rate(self, dir: Direction, index: int) -> int:
"""
Retrieves the preferred frame rate of a requested device.
This retrieves the preferred frame rate of a requested device. The preferred
frame rate is the rate at which the device natively wants to process audio data.
Using the device at other frame rates may be possible but would require extra
processing time. Using a device at a different frame rate than its preferred
one may also result in degraded quality depending on what the processing versus
preferred frame rate is.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the preferred frame rate for.
index: the index of the device to retrieve the frame rate for. This should
be between 0 and one less than the most recent return value of
getDeviceCount().
Returns:
If successful, this returns the preferred frame rate of the requested device.
If the requested device was out of range of those connected to the system, 0
is returned.
"""
def get_device_id(self, dir: Direction, index: int) -> object:
"""
Retrieves the unique identifier for the requested device.
Args:
dir: the audio direction to get the device name for.
index: the index of the device to retrieve the identifier for. This
should be between 0 and one less than the most recent return
value of getDeviceCount().
Returns:
If successful, this returns a python string containing the unique identifier
of the requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_name(self, dir: Direction, index: int) -> object:
"""
Retrieves the friendly name of a requested device.
Args:
dir: the audio direction to get the device name for.
index: the index of the device to retrieve the name for. This should be between
0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns a python string containing the friendly name of the
requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_sample_size(self, dir: Direction, index: int) -> int:
"""
Retrieves the native sample size for a requested device.
This retrieves the bits per sample that a requested device prefers to process
its data at. It may be possible to use the device at a different sample size,
but that would likely result in extra processing time. Using a device at a
different sample rate than its native could degrade the quality of the final
signal.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the native sample size for.
index: the index of the device to retrieve the sample size for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the native sample size in bits per sample of the
requested device.
If the requested device is out of range of those connected to the system, 0
is returned.
"""
def get_device_sample_type(self, dir: Direction, index: int) -> SampleType:
"""
Retrieves the native sample data type for a requested device.
This retrieves the sample data type that a requested device prefers to process
its data in. It may be possible to use the device with a different data type,
but that would likely result in extra processing time. Using a device with a
different sample data type than its native could degrade the quality of the
final signal.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the native sample data type for.
index: the index of the device to retrieve the sample data type for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the native sample data type of the requested device.
If the requested device is out of range of those connected to the system,
UNKNOWN is returned.
"""
def is_direct_hardware_backend(self) -> bool:
"""
/** Check if the audio device backend uses direct hardware access.
*
* A direct hardware audio backend is capable of exclusively locking audio
* devices, so devices are not guaranteed to open successfully and opening
* devices to test their format may be disruptive to the system.
*
* ALSA is the only 'direct hardware' backend that's currently supported.
* Some devices under ALSA will exclusively lock the audio device; these
* may fail to open because they're busy.
* Additionally, some devices under ALSA can fail to open because they're
* misconfigured (Ubuntu's default ALSA configuration can contain
* misconfigured devices).
* In addition to this, opening some devices under ALSA can take a
* substantial amount of time (over 100ms).
* For these reasons, it is important to verify that you are not using a
* 'direct hardware' backend if you are going to call certain functions in
* this interface.
*
* Args:
* No arguments.
*
* Returns:
* This returns `True` if this backend has direct hardware access.
* This will be returned when ALSA is in use.
* This returns `False` if the backend is an audio mixing server.
* This will be returned when Pulse Audio or Window Audio Services
* are in use.
"""
pass
class SampleType():
"""
Members:
UNKNOWN : could not determine the same type or an invalid device index.
PCM_SIGNED_INTEGER : signed integer PCM samples.
PCM_UNSIGNED_INTEGER : unsigned integer PCM samples.
PCM_FLOAT : single precision floating point PCM samples.
COMPRESSED : a compressed sample format.
"""
def __init__(self, arg0: int) -> None: ...
def __int__(self) -> int: ...
@property
def name(self) -> str:
"""
(self: handle) -> str
:type: str
"""
COMPRESSED: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.COMPRESSED
PCM_FLOAT: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.PCM_FLOAT
PCM_SIGNED_INTEGER: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.PCM_SIGNED_INTEGER
PCM_UNSIGNED_INTEGER: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.PCM_UNSIGNED_INTEGER
UNKNOWN: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.UNKNOWN
__members__: dict # value = {'UNKNOWN': SampleType.UNKNOWN, 'PCM_SIGNED_INTEGER': SampleType.PCM_SIGNED_INTEGER, 'PCM_UNSIGNED_INTEGER': SampleType.PCM_UNSIGNED_INTEGER, 'PCM_FLOAT': SampleType.PCM_FLOAT, 'COMPRESSED': SampleType.COMPRESSED}
pass
def acquire_audio_device_enum_interface(plugin_name: str = None, library_path: str = None) -> IAudioDeviceEnum:
pass
| 14,603 | unknown | 46.570032 | 245 | 0.60241 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/_audiodeviceenum.pyi | """
This module contains bindings to the C++ omni::audio::IAudioDeviceEnum
interface. This provides functionality for enumerating available audio
devices and collecting some basic information on each one.
Sound devices attached to the system may change at any point due to user
activity (ie: connecting or unplugging a USB audio device). When enumerating
devices, it is important to collect all device information directly instead
of caching it.
The device information is suitable to be used to display to a user in a menu
to allow them to choose a device to use by name.
"""
from __future__ import annotations
import omni.kit.audiodeviceenum._audiodeviceenum
import typing
__all__ = [
"Direction",
"IAudioDeviceEnum",
"SampleType",
"acquire_audio_device_enum_interface"
]
class Direction():
"""
Members:
PLAYBACK : audio playback devices only.
CAPTURE : audio capture devices only.
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
CAPTURE: omni.kit.audiodeviceenum._audiodeviceenum.Direction # value = <Direction.CAPTURE: 1>
PLAYBACK: omni.kit.audiodeviceenum._audiodeviceenum.Direction # value = <Direction.PLAYBACK: 0>
__members__: dict # value = {'PLAYBACK': <Direction.PLAYBACK: 0>, 'CAPTURE': <Direction.CAPTURE: 1>}
pass
class IAudioDeviceEnum():
"""
This interface contains functions for audio device enumeration. This is able to
enumerate all audio devices attached to the system at any given point and collect the
information for each device. This is only intended to collect the device information
needed to display to the user for device selection purposes. If a device is to be
chosen based on certain needs (ie: channel count, frame rate, etc), it should be done
directly through the audio playback or capture context during creation. This is able
to collect information for both playback and capture devices.
All the function in this interface are in omni.kit.audio.IAudioDeviceEnum class.
To retrieve this object, use get_audio_device_enum_interface() method:
>>> import omni.kit.audio
>>> dev = omni.kit.audio.get_audio_device_enum_interface()
>>> count = dev.get_device_count(PLAYBACK)
>>> desc = dev.get_device_description(PLAYBACK, 0)
"""
def get_device_channel_count(self, dir: Direction, index: int) -> int:
"""
Retrieves the maximum channel count for a requested device.
This retrieves the maximum channel count for a requested device. This count
is the maximum number of channels that the device can natively handle without
having to trim or reprocess the data. Using a device with a different channel
count than its maximum is allowed but will result in extra processing time to
upmix or downmix channels in the stream. Note that downmixing channel counts
(ie: 7.1 to stereo) will often result in multiple channels being blended
together and can result in an unexpected final signal in certain cases.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the maximum channel count for.
index: the index of the device to retrieve the channel count for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the maximum channel count of the requested device.
If the requested device is out of range of those connected to the system, 0
is returned.
"""
def get_device_count(self, dir: Direction) -> int:
"""
Retrieves the total number of devices attached to the system of a requested type.
Args:
dir: the audio direction to get the device count for.
Returns:
If successful, this returns the total number of connected audio devices of the
requested type.
If there are no devices of the requested type connected to the system, 0 is
returned.
"""
def get_device_description(self, dir: Direction, index: int) -> object:
"""
Retrieves a descriptive string for a requested audio device.
This retrieves a descriptive string for the requested device. This string is
suitable for display to a user in a menu or selection list.
Args:
dir: the audio direction to get the description string for.
index: the index of the device to retrieve the description for. This should be
between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns a python string describing the requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_frame_rate(self, dir: Direction, index: int) -> int:
"""
Retrieves the preferred frame rate of a requested device.
This retrieves the preferred frame rate of a requested device. The preferred
frame rate is the rate at which the device natively wants to process audio data.
Using the device at other frame rates may be possible but would require extra
processing time. Using a device at a different frame rate than its preferred
one may also result in degraded quality depending on what the processing versus
preferred frame rate is.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the preferred frame rate for.
index: the index of the device to retrieve the frame rate for. This should
be between 0 and one less than the most recent return value of
getDeviceCount().
Returns:
If successful, this returns the preferred frame rate of the requested device.
If the requested device was out of range of those connected to the system, 0
is returned.
"""
def get_device_id(self, dir: Direction, index: int) -> object:
"""
Retrieves the unique identifier for the requested device.
Args:
dir: the audio direction to get the device name for.
index: the index of the device to retrieve the identifier for. This
should be between 0 and one less than the most recent return
value of getDeviceCount().
Returns:
If successful, this returns a python string containing the unique identifier
of the requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_name(self, dir: Direction, index: int) -> object:
"""
Retrieves the friendly name of a requested device.
Args:
dir: the audio direction to get the device name for.
index: the index of the device to retrieve the name for. This should be between
0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns a python string containing the friendly name of the
requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_sample_size(self, dir: Direction, index: int) -> int:
"""
Retrieves the native sample size for a requested device.
This retrieves the bits per sample that a requested device prefers to process
its data at. It may be possible to use the device at a different sample size,
but that would likely result in extra processing time. Using a device at a
different sample rate than its native could degrade the quality of the final
signal.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the native sample size for.
index: the index of the device to retrieve the sample size for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the native sample size in bits per sample of the
requested device.
If the requested device is out of range of those connected to the system, 0
is returned.
"""
def get_device_sample_type(self, dir: Direction, index: int) -> SampleType:
"""
Retrieves the native sample data type for a requested device.
This retrieves the sample data type that a requested device prefers to process
its data in. It may be possible to use the device with a different data type,
but that would likely result in extra processing time. Using a device with a
different sample data type than its native could degrade the quality of the
final signal.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the native sample data type for.
index: the index of the device to retrieve the sample data type for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the native sample data type of the requested device.
If the requested device is out of range of those connected to the system,
UNKNOWN is returned.
"""
def is_direct_hardware_backend(self) -> bool:
"""
/** Check if the audio device backend uses direct hardware access.
*
* A direct hardware audio backend is capable of exclusively locking audio
* devices, so devices are not guaranteed to open successfully and opening
* devices to test their format may be disruptive to the system.
*
* ALSA is the only 'direct hardware' backend that's currently supported.
* Some devices under ALSA will exclusively lock the audio device; these
* may fail to open because they're busy.
* Additionally, some devices under ALSA can fail to open because they're
* misconfigured (Ubuntu's default ALSA configuration can contain
* misconfigured devices).
* In addition to this, opening some devices under ALSA can take a
* substantial amount of time (over 100ms).
* For these reasons, it is important to verify that you are not using a
* 'direct hardware' backend if you are going to call certain functions in
* this interface.
*
* Args:
* No arguments.
*
* Returns:
* This returns `True` if this backend has direct hardware access.
* This will be returned when ALSA is in use.
* This returns `False` if the backend is an audio mixing server.
* This will be returned when Pulse Audio or Window Audio Services
* are in use.
"""
pass
class SampleType():
"""
Members:
UNKNOWN : could not determine the same type or an invalid device index.
PCM_SIGNED_INTEGER : signed integer PCM samples.
PCM_UNSIGNED_INTEGER : unsigned integer PCM samples.
PCM_FLOAT : single precision floating point PCM samples.
COMPRESSED : a compressed sample format.
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
COMPRESSED: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.COMPRESSED: 4>
PCM_FLOAT: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.PCM_FLOAT: 3>
PCM_SIGNED_INTEGER: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.PCM_SIGNED_INTEGER: 1>
PCM_UNSIGNED_INTEGER: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.PCM_UNSIGNED_INTEGER: 2>
UNKNOWN: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.UNKNOWN: 0>
__members__: dict # value = {'UNKNOWN': <SampleType.UNKNOWN: 0>, 'PCM_SIGNED_INTEGER': <SampleType.PCM_SIGNED_INTEGER: 1>, 'PCM_UNSIGNED_INTEGER': <SampleType.PCM_UNSIGNED_INTEGER: 2>, 'PCM_FLOAT': <SampleType.PCM_FLOAT: 3>, 'COMPRESSED': <SampleType.COMPRESSED: 4>}
pass
def acquire_audio_device_enum_interface(plugin_name: str = None, library_path: str = None) -> IAudioDeviceEnum:
pass
| 14,246 | unknown | 43.801887 | 270 | 0.64762 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/tests/test_device.py | import omni.kit.test
import omni.kit.audiodeviceenum
def get_name_from_sample_type(sample_type): # pragma: no cover
if sample_type == omni.kit.audiodeviceenum.SampleType.UNKNOWN:
return "UNKNOWN"
if sample_type == omni.kit.audiodeviceenum.SampleType.PCM_SIGNED_INTEGER:
return "INT PCM"
if sample_type == omni.kit.audiodeviceenum.SampleType.PCM_UNSIGNED_INTEGER:
return "UINT PCM"
if sample_type == omni.kit.audiodeviceenum.SampleType.PCM_FLOAT:
return "FLOAT PCM"
if sample_type == omni.kit.audiodeviceenum.SampleType.COMPRESSED:
return "COMPRESSED"
class TestAudio(omni.kit.test.AsyncTestCase): # pragma: no cover
async def test_audio_device(self):
audio = omni.kit.audiodeviceenum.get_audio_device_enum_interface()
self.assertIsNotNone(audio)
count = audio.get_device_count(omni.kit.audiodeviceenum.Direction.PLAYBACK)
self.assertGreaterEqual(count, 0)
printDevices = 0
if printDevices != 0:
print("Found ", count, " Available Playback Devices:")
if count > 0:
for i in range(0, count):
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertIsNotNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertIsNotNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertIsNotNone(uniqueId)
if not audio.is_direct_hardware_backend():
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertGreater(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertGreater(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertGreater(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
if printDevices != 0:
str_desc = " found the device '" + name + "' "
str_desc += "{" + str(channel_count) + " channels "
str_desc += "@ " + str(frame_rate) + "Hz "
str_desc += str(sample_size) + "-bit " + get_name_from_sample_type(sample_type)
print(str_desc)
print(" " + desc)
else:
if printDevices != 0:
print(" found the device '" + name + "' ")
print(" " + desc)
# make sure out of range values fail.
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertIsNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertIsNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertIsNone(uniqueId)
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(sample_type, omni.kit.audiodeviceenum.SampleType.UNKNOWN)
count = audio.get_device_count(omni.kit.audiodeviceenum.Direction.CAPTURE)
self.assertGreaterEqual(count, 0)
if printDevices != 0:
print("\nFound ", count, " Available Capture Devices:")
if count > 0:
for i in range(0, count):
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertIsNotNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertIsNotNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertIsNotNone(uniqueId)
if not audio.is_direct_hardware_backend():
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertGreater(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertGreater(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertGreater(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
if printDevices != 0:
str_desc = " found the device '" + name + "' "
str_desc += "{" + str(channel_count) + " channels "
str_desc += "@ " + str(frame_rate) + "Hz "
str_desc += str(sample_size) + "-bit " + get_name_from_sample_type(sample_type)
print(str_desc)
print(" " + desc)
else:
if printDevices != 0:
print(" found the device '" + name + "' ")
print(" " + desc)
# make sure out of range values fail.
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertIsNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertIsNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertIsNone(uniqueId)
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(sample_type, omni.kit.audiodeviceenum.SampleType.UNKNOWN)
| 6,979 | Python | 47.137931 | 114 | 0.60854 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/tests/__init__.py | from .test_device import * # pragma: no cover
| 48 | Python | 15.333328 | 46 | 0.6875 |
omniverse-code/kit/exts/omni.kit.window.cursor/PACKAGE-LICENSES/omni.kit.window.cursor-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.window.cursor/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.1.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "Window Cursor Extension"
description="Extension to manage main window cursor."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Internal"
# Keywords for the extension
keywords = ["kit", "cursor"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
"omni.appwindow" = {}
"omni.ui" = {}
# Main python module this extension provides, it will be publicly available as "import omni.example.hello".
[[python.module]]
name = "omni.kit.window.cursor"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
]
dependencies = [
"omni.kit.mainwindow"
]
| 1,656 | TOML | 30.26415 | 118 | 0.735507 |
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/cursor.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
from carb import windowing, log_warn
import omni.ext
import weakref
EXTEND_CURSOR_GRAB_OPEN = "Grab_open"
EXTEND_CURSOR_GRAB_CLOSE = "Grab_close"
EXTEND_CURSOR_PAN_FILE = "cursorPan.png"
EXTEND_CURSOR_PAN_CLOSE_FILE = "cursorPanClosed.png"
main_window_cursor = None
def get_main_window_cursor():
return main_window_cursor
def get_icon_path(path: str):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
icon_path = Path(extension_path).joinpath("data").joinpath("icons").joinpath(path)
return str(icon_path)
class WindowCursor(omni.ext.IExt):
def __init__(self):
self._imgui_renderer = None
self._app_window = None
super().__init__()
def on_startup(self, ext_id):
global main_window_cursor
main_window_cursor = weakref.proxy(self)
try:
import omni.kit.imgui_renderer
import omni.appwindow
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
self._app_window = omni.appwindow.get_default_app_window()
except Exception:
# Currently need both of these for further API usage, which can't happen now; so clear them both out
self._imgui_renderer, self._app_window = None, None
log_warn("omni.kit.window.cursor failed to initialize properly, changing cursor with it will not work")
import traceback
log_warn(f"{traceback.format_exc()}")
self._app_ready_sub = omni.kit.app.get_app().get_startup_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY,
self._on_app_ready,
)
def on_shutdown(self):
if self._imgui_renderer:
self._imgui_renderer.unregister_cursor_shape_extend(EXTEND_CURSOR_GRAB_OPEN)
self._imgui_renderer.unregister_cursor_shape_extend(EXTEND_CURSOR_GRAB_CLOSE)
global main_window_cursor
main_window_cursor = None
self._imgui_renderer = None
self._app_window = None
self._app_ready_sub = None
def _on_app_ready(self, event):
if self._imgui_renderer:
self._imgui_renderer.register_cursor_shape_extend(EXTEND_CURSOR_GRAB_OPEN, get_icon_path(EXTEND_CURSOR_PAN_FILE))
self._imgui_renderer.register_cursor_shape_extend(EXTEND_CURSOR_GRAB_CLOSE, get_icon_path(EXTEND_CURSOR_PAN_CLOSE_FILE))
def override_cursor_shape_extend(self, shape_name: str):
if self._app_window and self._imgui_renderer:
self._imgui_renderer.set_cursor_shape_override_extend(self._app_window, shape_name)
return True
return False
def override_cursor_shape(self, shape: windowing.CursorStandardShape):
if self._app_window and self._imgui_renderer:
self._imgui_renderer.set_cursor_shape_override(self._app_window, shape)
return True
return False
def clear_overridden_cursor_shape(self):
if self._app_window and self._imgui_renderer:
self._imgui_renderer.clear_cursor_shape_override(self._app_window)
return True
return False
def get_cursor_shape_override_extend(self):
if self._app_window and self._imgui_renderer:
return self._imgui_renderer.get_cursor_shape_override_extend(self._app_window)
return None
def get_cursor_shape_override(self):
if self._app_window and self._imgui_renderer:
return self._imgui_renderer.get_cursor_shape_override(self._app_window)
return None
| 4,062 | Python | 37.695238 | 132 | 0.674545 |
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/__init__.py | from .cursor import *
| 22 | Python | 10.499995 | 21 | 0.727273 |
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/tests/tests.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.imgui
import carb.input
import carb.windowing
import omni.appwindow
import omni.kit.app
import omni.kit.test
import omni.kit.window.cursor
import omni.kit.imgui_renderer
import omni.ui as ui
class TestCursorShape(omni.kit.test.AsyncTestCase):
async def setUp(self):
app_window = omni.appwindow.get_default_app_window()
self._mouse = app_window.get_mouse()
self._app = omni.kit.app.get_app()
self._cursor = omni.kit.window.cursor.get_main_window_cursor()
self._input_provider = carb.input.acquire_input_provider()
self._imgui = carb.imgui.acquire_imgui()
self._windowing = carb.windowing.acquire_windowing_interface()
self._os_window = app_window.get_window()
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
await self._build_test_windows()
async def tearDown(self):
self._os_window = None
self._windowing = None
self._imgui = None
self._window = None
self._dock_window_1 = None
self._dock_window_2 = None
self._imgui_renderer = None
async def test_cursor_shape(self):
main_dockspace = ui.Workspace.get_window("DockSpace")
width = main_dockspace.width
height = main_dockspace.height
await self._wait()
await self._move_and_test_cursor_shape((width / 2, 1), carb.imgui.MouseCursor.ARROW)
# Put on StringField and test IBeam shape
await self._move_and_test_cursor_shape((width / 2, height / 4), carb.imgui.MouseCursor.TEXT_INPUT)
# Put on vertical split and test HORIZONTAL_RESIZE
await self._move_and_test_cursor_shape(
(width / 2 + 1, height * 3 / 4),
carb.imgui.MouseCursor.RESIZE_EW,
)
# Put on horizontal split and test VERTICAL_RESIZE
await self._move_and_test_cursor_shape(
(width * 3 / 4, height / 2 + 1),
carb.imgui.MouseCursor.RESIZE_NS,
)
await self._wait()
# test override_cursor_shape_extend and get_cursor_shape_override_extend
test_extend_shapes = [
"IBeam",
"Grab_close",
"Crosshair",
"Grab_open",
]
for cursor_shape in test_extend_shapes:
self._cursor.override_cursor_shape_extend(cursor_shape)
await self._wait(100)
cur_cursor = self._cursor.get_cursor_shape_override_extend()
self.assertEqual(cur_cursor, cursor_shape)
# test override_cursor_shape and get_cursor_shape_override
test_shapes = [
carb.windowing.CursorStandardShape.CROSSHAIR,
carb.windowing.CursorStandardShape.IBEAM,
]
for cursor_shape in test_shapes:
self._cursor.override_cursor_shape(cursor_shape)
await self._wait(100)
cur_cursor = self._cursor.get_cursor_shape_override()
self.assertEqual(cur_cursor, cursor_shape)
all_shapes = self._imgui_renderer.get_all_cursor_shape_names()
print(all_shapes)
self._cursor.clear_overridden_cursor_shape()
await self._wait()
async def _move_and_test_cursor_shape(self, pos, cursor: carb.imgui.MouseCursor):
# Available options:
# carb.imgui.MouseCursor.ARROW: carb.windowing.CursorStandardShape.ARROW,
# carb.imgui.MouseCursor.TEXT_INPUT: carb.windowing.CursorStandardShape.IBEAM,
# carb.imgui.MouseCursor.RESIZE_NS: carb.windowing.CursorStandardShape.VERTICAL_RESIZE,
# carb.imgui.MouseCursor.RESIZE_EW: carb.windowing.CursorStandardShape.HORIZONTAL_RESIZE,
# carb.imgui.MouseCursor.HAND: carb.windowing.CursorStandardShape.HAND,
# carb.imgui.MouseCursor.CROSSHAIR: carb.windowing.CursorStandardShape.CROSSHAIR,
self._input_provider.buffer_mouse_event(self._mouse, carb.input.MouseEventType.MOVE, pos, 0, pos)
self._windowing.set_cursor_position(self._os_window, carb.Int2(*[int(p) for p in pos]))
await self._wait()
imgui_cursor = self._imgui.get_mouse_cursor()
self.assertEqual(cursor, imgui_cursor, f"Expect {cursor} but got {imgui_cursor}")
# build a dockspace with windows/widgets to test various cursor shape from imgui
async def _build_test_windows(self):
import omni.ui as ui
self._window = ui.Window("CursorShapeTest")
with self._window.frame:
with ui.ZStack():
with ui.Placer(offset_x=0, offset_y=10):
ui.StringField()
self._dock_window_1 = ui.Window("DockWindow1")
self._dock_window_2 = ui.Window("DockWindow2")
await self._app.next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window_handle = ui.Workspace.get_window("CursorShapeTest")
dock_window_handle1 = ui.Workspace.get_window("DockWindow1")
dock_window_handle2 = ui.Workspace.get_window("DockWindow2")
window_handle.dock_in(main_dockspace, ui.DockPosition.SAME)
dock_window_handle1.dock_in(window_handle, ui.DockPosition.BOTTOM, 0.5)
dock_window_handle2.dock_in(dock_window_handle1, ui.DockPosition.RIGHT, 0.5)
async def _wait(self, num=8):
for i in range(num):
await self._app.next_update_async() | 5,770 | Python | 38.8 | 106 | 0.656672 |
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/tests/__init__.py | from .tests import *
| 21 | Python | 9.999995 | 20 | 0.714286 |
omniverse-code/kit/exts/omni.kit.window.cursor/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.kit.window.cursor`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`.
## [1.1.1] - 2022-09-26
### Changed
- Store weakly referenced proxy to extension object.
- Handle possiblity of lower level API failure better.
- Return value of success for changing / restoring the cursor.
## [1.1.0] - 2022-05-06
### Changed
- Using `IImGuiRenderer` to override the mouse cursor
## [1.0.1] - 2021-03-01
### Added
- Added tests.
## [1.0.0] - 2020-11-06
### Added
- Initial extensions.
| 575 | Markdown | 20.333333 | 82 | 0.697391 |
omniverse-code/kit/exts/omni.kit.window.cursor/docs/README.md | # Cursor Extension [omni.kit.window.cursor]
This is an extension to manager cursor shape.
| 92 | Markdown | 17.599996 | 45 | 0.771739 |
omniverse-code/kit/exts/omni.kit.window.cursor/docs/index.rst | omni.kit.window.cursor
###########################
.. toctree::
:maxdepth: 1
CHANGELOG
| 97 | reStructuredText | 8.799999 | 27 | 0.453608 |
omniverse-code/kit/exts/omni.kit.widget.live/PACKAGE-LICENSES/omni.kit.widget.live-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.widget.live/config/extension.toml | [package]
version = "2.0.3"
title = "Kit Live Mode Control Widget"
category = "Internal"
changelog = "docs/CHANGELOG.md"
feature = true
keywords = ["live", "session"]
authors = ["NVIDIA"]
repository = ""
[dependencies]
"omni.usd" = {}
"omni.client" = {}
"omni.ui" = {}
"omni.kit.usd.layers" = {}
"omni.kit.menu.utils" = {}
"omni.kit.widget.live_session_management" = {}
[[python.module]]
name = "omni.kit.widget.live"
[settings]
exts."omni.kit.widget.live".enable_server_tests = false
[[test]]
args = [
"--/app/asyncRendering=false",
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/app/file/ignoreUnsavedOnExit=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=false",
"--no-window"
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.commands",
"omni.kit.selection",
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers"
]
stdoutFailPatterns.include = []
stdoutFailPatterns.exclude = [] | 1,101 | TOML | 21.958333 | 77 | 0.654859 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/cache_state_menu.py | import asyncio
import aiohttp
import carb
import os
import toml
import time
import omni.client
import webbrowser
from omni.kit.menu.utils import MenuItemDescription, MenuAlignment
from omni import ui
from typing import Union
from .style import Styles
class CacheStateDelegate(ui.MenuDelegate):
def __init__(self, cache_enabled, **kwargs):
super().__init__(**kwargs)
self._cache_enabled = cache_enabled
self._cache_widget = None
def destroy(self):
self._cache_widget = None
def build_item(self, item: ui.MenuHelper):
with ui.HStack(width=0, style={"margin" : 0}):
ui.Spacer(width=5)
self._cache_widget = ui.HStack(content_clipping=1, width=0, style=Styles.CACHE_STATE_ITEM_STYLE)
ui.Spacer(width=10)
self.update_live_state(self._cache_enabled)
def get_menu_alignment(self):
return MenuAlignment.RIGHT
def update_menu_item(self, menu_item: Union[ui.Menu, ui.MenuItem], menu_refresh: bool):
if isinstance(menu_item, ui.MenuItem):
menu_item.visible = False
def update_live_state(self, cache_enabled):
if not self._cache_widget:
return
margin = 2
self._cache_enabled = cache_enabled
self._cache_widget.clear()
with self._cache_widget:
ui.Label("CACHE: ")
if cache_enabled:
ui.Label("ON", style={"color": 0xff00b86b})
else:
with ui.VStack():
ui.Spacer(height=margin)
with ui.ZStack(width=0):
with ui.HStack(width=20):
ui.Spacer()
ui.Label("OFF", name="offline", width=0)
ui.Spacer(width=margin)
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=14, height=14, name="doc")
ui.Spacer()
ui.Spacer()
button = ui.InvisibleButton(width=20)
button.set_clicked_fn(lambda: webbrowser.open('https://docs.omniverse.nvidia.com/nucleus/cache_troubleshoot.html', new=2))
ui.Spacer(height=margin)
class CacheStateMenu:
def __init__(self):
self._live_menu_name = "Cache State Widget"
self._menu_list = [MenuItemDescription(name="placeholder", show_fn=lambda: False)]
global_config_path = carb.tokens.get_tokens_interface().resolve("${omni_global_config}")
self._omniverse_config_path = os.path.join(global_config_path, "omniverse.toml").replace("\\", "/")
self._all_cache_apis = []
self._cache_enabled = False
self._last_time_check = 0
self._ping_cache_future = None
self._update_subscription = None
def _initialize(self):
if os.path.exists(self._omniverse_config_path):
try:
contents = toml.load(self._omniverse_config_path)
except Exception as e:
carb.log_error(f"Unable to parse {self._omniverse_config_path}. File corrupted?")
contents = None
if contents:
self._all_cache_apis = self._load_all_cache_server_apis(contents)
if self._all_cache_apis:
self._cache_enabled = True
self._update_subscription = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(
self._on_update, name="omni.kit.widget.live update"
)
else:
carb.log_warn("Unable to detect Omniverse Cache Server. Consider installing it for better IO performance.")
self._cache_enabled = False
else:
carb.log_warn(f"Unable to detect Omniverse Cache Server. File {self._omniverse_config_path} is not found."
f" Consider installing it for better IO performance.")
def register_menu_widgets(self):
self._initialize()
self._cache_state_delegate = CacheStateDelegate(self._cache_enabled)
omni.kit.menu.utils.add_menu_items(self._menu_list, name=self._live_menu_name, delegate=self._cache_state_delegate)
def unregister_menu_widgets(self):
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._live_menu_name)
if self._cache_state_delegate:
self._cache_state_delegate.destroy()
self._cache_state_delegate = None
self._menu_list = None
self._update_subscription = None
self._all_cache_apis = []
try:
if self._ping_cache_future and not self._ping_cache_future.done():
self._ping_cache_future.cancel()
self._ping_cache_future = None
except Exception:
self._ping_cache_future = None
def _on_update(self, dt):
if not self._cache_state_delegate or not self._all_cache_apis:
return
if not self._ping_cache_future or self._ping_cache_future.done():
now = time.time()
duration = now - self._last_time_check
# 30s
if duration < 30:
return
self._last_time_check = now
async def _ping_cache():
session = aiohttp.ClientSession()
cache_enabled = None
for cache_api in self._all_cache_apis:
try:
async with session.head(cache_api):
''' If we're here the service port is alive '''
cache_enabled = True
except Exception as e:
cache_enabled = False
break
await session.close()
if cache_enabled is not None and self._cache_enabled != cache_enabled:
self._cache_enabled = cache_enabled
if self._cache_state_delegate:
self._cache_state_delegate.update_live_state(self._cache_enabled)
self._ping_cache_future = asyncio.ensure_future(_ping_cache())
def _load_all_cache_server_apis(self, config_contents):
mapping = os.environ.get("OMNI_CONN_CACHE", None)
if mapping:
mapping = f"*#{mapping},f"
else:
mapping = os.environ.get("OMNI_CONN_REDIRECTION_DICT", None)
if not mapping:
mapping = os.environ.get("OM_REDIRECTION_DICT", None)
if not mapping:
connection_library_dict = config_contents.get("connection_library", None)
if connection_library_dict:
mapping = connection_library_dict.get("proxy_dict", None)
all_proxy_apis = set([])
if mapping:
mapping = mapping.lstrip("\"")
mapping = mapping.rstrip("\"")
mapping = mapping.lstrip("'")
mapping = mapping.rstrip("'")
redirections = mapping.split(";")
for redirection in redirections:
parts = redirection.split("#")
if not parts or len(parts) < 2:
continue
source, target = parts[0], parts[1]
targets = target.split(",")
if not targets:
continue
if len(targets) > 1:
proxy_address = targets[0]
else:
proxy_address = target
if not proxy_address.startswith("http://") and not proxy_address.startswith("https://"):
proxy_address_api = f"http://{proxy_address}/ping"
else:
if proxy_address.endswith("/"):
proxy_address_api = f"{proxy_address}ping"
else:
proxy_address_api = f"{proxy_address}/ping"
all_proxy_apis.add(proxy_address_api)
return all_proxy_apis
| 8,210 | Python | 37.731132 | 146 | 0.5324 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/style.py | from .icons import Icons
class Styles:
CACHE_STATE_ITEM_STYLE = None
LIVE_STATE_ITEM_STYLE = None
@staticmethod
def on_startup():
# It needs to delay initialization of style as icons need to be initialized firstly.
Styles.CACHE_STATE_ITEM_STYLE = {
"Image::doc": {"image_url": Icons.get("docs"), "color": 0xB04B4BFF},
"Label::offline": {"color": 0xB04B4BFF},
"Rectangle::offline": {"border_radius": 2.0},
"Rectangle::offline": {"background_color": 0xff808080},
"Rectangle::offline:hovered": {"background_color": 0xFF9E9E9E},
}
Styles.LIVE_STATE_ITEM_STYLE = {
"Label": {"color": 0xffffffff},
"Image::lightning": {"image_url": Icons.get("lightning")},
"Image::arrow_down": {"image_url": Icons.get("arrow_down"), "color": 0xffffffff},
"Rectangle": {"border_radius": 2.0},
"Rectangle:hovered": {"background_color": 0xFF9E9E9E},
"Rectangle::offline": {"background_color": 0xff808080},
"Rectangle::live": {"background_color": 0xff00b86b}
}
| 1,139 | Python | 39.714284 | 93 | 0.581212 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.usd
import omni.ext
import omni.kit.app
from .live_state_menu import LiveStateMenu
from .icons import Icons
from .style import Styles
class OmniLiveWidgetExtension(omni.ext.IExt):
def on_startup(self, ext_id):
extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
Icons.on_startup(extension_path)
Styles.on_startup()
usd_context = omni.usd.get_context()
self._live_state_menu = LiveStateMenu(usd_context)
self._live_state_menu.register_menu_widgets()
def on_shutdown(self):
self._live_state_menu.unregister_menu_widgets()
Icons.on_shutdown()
| 1,112 | Python | 33.781249 | 108 | 0.739209 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/live_state_menu.py | import carb
import omni.usd
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.widget.live_session_management as lsm
from functools import partial
from omni.kit.menu.utils import MenuItemDescription, MenuAlignment
from omni.ui import color as cl
from typing import Union
from .style import Styles
class LiveStateDelegate(ui.MenuDelegate):
def __init__(self, layers_interface, **kwargs):
super().__init__(**kwargs)
self._layers = layers_interface
self._live_syncing = layers_interface.get_live_syncing()
self._usd_context = self._live_syncing.usd_context
self._live_background = None
self._drop_down_background = None
self._live_button = None
self._drop_down_button = None
self._live_session_user_list_widget = None
self._layers_event_subs = []
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
]:
layers_event_sub = self._layers.get_event_stream().create_subscription_to_pop_by_type(
event, self._on_layer_event, name=f"omni.kit.widget.live {str(event)}"
)
self._layers_event_subs.append(layers_event_sub)
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="omni.kit.widget.live stage event"
)
def destroy(self):
if self._live_button:
self._live_button.set_clicked_fn(None)
self._live_button = None
if self._drop_down_button:
self._drop_down_button.set_clicked_fn(None)
self._drop_down_button = None
if self._live_session_user_list_widget:
self._live_session_user_list_widget.destroy()
self._live_session_user_list_widget = None
self._live_syncing = None
self._layers_event_subs = []
self._stage_event_sub = None
def _on_layer_event(self, event: carb.events.IEvent):
payload = layers.get_layer_event_payload(event)
if not payload:
return
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self._usd_context.get_stage_url()):
return
self.__update_live_state()
elif (
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED or
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT
):
if not payload.is_layer_influenced(self._usd_context.get_stage_url()):
return
self.__update_live_tooltip()
def _on_stage_event(self, event: carb.events.IEvent):
if event.type == int(omni.usd.StageEventType.OPENED):
if self._live_session_user_list_widget:
self._live_session_user_list_widget.track_layer(self._usd_context.get_stage_url())
def _on_live_widget_button_clicked(self, button, show_options):
menu_widget = lsm.stop_or_show_live_session_widget(
self._live_syncing.usd_context,
not show_options,
False,
show_options
)
if not menu_widget:
return
# Try to align it with the button.
drop_down_x = button.screen_position_x
drop_down_y = button.screen_position_y
drop_down_height = button.computed_height
# FIXME: The width of context menu cannot be got. Using fixed width here.
menu_widget.show_at(
drop_down_x - 94,
drop_down_y + drop_down_height + 2
)
def build_item(self, item: ui.MenuHelper):
margin = 2
with ui.HStack(width=0, style={"margin" : 0}):
with ui.HStack(content_clipping=1, width=0, style=Styles.LIVE_STATE_ITEM_STYLE):
with ui.VStack():
ui.Spacer(height=margin)
self.__build_user_list()
ui.Spacer(height=margin)
ui.Spacer(width=2 * margin)
with ui.VStack():
ui.Spacer(height=margin)
with ui.ZStack(width=0):
self._live_background = ui.Rectangle(width=50, name="offline")
with ui.HStack(width=50):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=14, height=14, name="lightning")
ui.Spacer()
ui.Spacer(width=margin)
ui.Label("LIVE", width=0)
ui.Spacer()
self._live_button = ui.InvisibleButton(width=50, identifier="live_button")
self._live_button.set_clicked_fn(
partial(self._on_live_widget_button_clicked, self._live_button, False)
)
ui.Spacer(height=margin)
ui.Spacer(width=margin)
with ui.VStack():
ui.Spacer(height=margin)
with ui.ZStack(width=0):
self._drop_down_background = ui.Rectangle(width=16, name="offline")
with ui.HStack(width=16):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=14, height=14, name="arrow_down")
ui.Spacer()
ui.Spacer()
self._drop_down_button = ui.InvisibleButton(width=16, identifier="drop_down_button")
self._drop_down_button.set_clicked_fn(
partial(self._on_live_widget_button_clicked, self._drop_down_button, True)
)
ui.Spacer(height=margin)
ui.Spacer(width=8)
self.__update_live_state()
def get_menu_alignment(self):
return MenuAlignment.RIGHT
def update_menu_item(self, menu_item: Union[ui.Menu, ui.MenuItem], menu_refresh: bool):
if isinstance(menu_item, ui.MenuItem):
menu_item.visible = False
def __update_live_tooltip(self):
current_session = self._live_syncing.get_current_live_session()
if current_session:
peer_users_count = len(current_session.peer_users)
if peer_users_count > 0:
self._live_background.set_tooltip(
f"Leave Session {current_session.name}\n{peer_users_count + 1} Total Users in Session"
)
else:
self._live_background.set_tooltip(
f"Leave Session {current_session.name}"
)
def __update_live_state(self):
if self._live_background:
current_session = self._live_syncing.get_current_live_session()
if current_session:
self._live_background.name = "live"
self.__update_live_tooltip()
self._drop_down_background.name = "live"
else:
self._live_background.name = "offline"
self._live_background.set_tooltip("Start Session")
self._drop_down_background.name = "offline"
def __build_user_list(self):
def is_follow_enabled():
settings = carb.settings.get_settings()
enabled = settings.get(f"/app/liveSession/enableMenuFollowUser")
if enabled == True or enabled == False:
return enabled
return True
stage_url = self._usd_context.get_stage_url()
self._live_session_user_list_widget = lsm.LiveSessionUserList(
self._usd_context, stage_url,
follow_user_with_double_click=is_follow_enabled(),
allow_timeline_settings=True,
maximum_users=10
)
class LiveStateMenu:
def __init__(self, usd_context):
self._live_menu_name = "Live State Widget"
self._menu_list = [MenuItemDescription(name="placeholder", show_fn=lambda: False)]
self._usd_context = usd_context
self._layers = layers.get_layers(self._usd_context)
self._layer_state_delegate = None
def register_menu_widgets(self):
self._layer_state_delegate = LiveStateDelegate(self._layers)
omni.kit.menu.utils.add_menu_items(self._menu_list, name=self._live_menu_name, delegate=self._layer_state_delegate)
def unregister_menu_widgets(self):
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._live_menu_name)
self._menu_list = None
if self._layer_state_delegate:
self._layer_state_delegate.destroy()
self._layer_state_delegate = None
self._layers = None
self._usd_context = None
| 9,094 | Python | 39.066079 | 123 | 0.55905 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/__init__.py | from .extension import OmniLiveWidgetExtension | 46 | Python | 45.999954 | 46 | 0.913043 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/icons.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
class Icons:
"""A singleton that scans the icon folder and returns the icon depending on the type"""
_icons = {}
@staticmethod
def on_startup(extension_path):
current_path = Path(extension_path)
icon_path = current_path.joinpath("icons")
# Read all the svg files in the directory
Icons._icons = {icon.stem: icon for icon in icon_path.glob("*.svg")}
@staticmethod
def on_shutdown():
Icons._icons = None
@staticmethod
def get(name, default=None):
"""Checks the icon cache and returns the icon if exists"""
found = Icons._icons.get(name)
if not found and default:
found = Icons._icons.get(default)
if found:
return str(found)
return None
| 1,248 | Python | 31.86842 | 91 | 0.673878 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/tests/base.py | import carb
def enable_server_tests():
settings = carb.settings.get_settings()
return settings.get_as_bool("/exts/omni.kit.widget.live/enable_server_tests")
| 168 | Python | 20.124997 | 81 | 0.72619 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/tests/test_live_widget.py | import omni.kit.test
from pathlib import Path
import omni.usd
import omni.client
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.kit.clipboard
from omni.ui.tests.test_base import OmniUiTest
from pxr import Usd, Sdf
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi, join_new_simulated_user, quit_simulated_user
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data")
class TestLiveWidget(OmniUiTest):
# Before running each test
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self.app = omni.kit.app.get_app()
self.usd_context = omni.usd.get_context()
self.layers = layers.get_layers(self.usd_context)
self.live_syncing = self.layers.get_live_syncing()
await omni.usd.get_context().new_stage_async()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self.simulated_user_names = []
self.simulated_user_ids = []
self.test_session_name = "test"
self.stage_url = "omniverse://__faked_omniverse_server__/test/live_session.usd"
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def wait(self, frames=10):
for i in range(frames):
await self.app.next_update_async()
async def __create_simulated_users(self, count=2):
for i in range(count):
user_name = f"test{i}"
user_id = user_name
self.simulated_user_names.append(user_name)
self.simulated_user_ids.append(user_id)
join_new_simulated_user(user_name, user_id)
await self.wait(2)
async def test_menu_setup(self):
import omni.kit.ui_test as ui_test
await self.usd_context.new_stage_async()
menu_widget = ui_test.get_menubar()
menu = menu_widget.find_menu("Live State Widget")
self.assertTrue(menu)
async def __create_fake_stage(self, join_test_session=True):
format = Sdf.FileFormat.FindByExtension(".usd")
# Sdf.Layer.New will not save layer so it won't fail.
# This can be used to test layer identifier with omniverse sheme without
# touching real server.
layer = Sdf.Layer.New(format, self.stage_url)
stage = Usd.Stage.Open(layer.identifier)
session = self.live_syncing.create_live_session(self.test_session_name, layer_identifier=layer.identifier)
self.assertTrue(session)
if join_test_session:
await self.usd_context.attach_stage_async(stage)
self.live_syncing.join_live_session(session)
return stage, layer
@MockLiveSyncingApi
async def test_open_stage_with_live_session(self):
import omni.kit.ui_test as ui_test
await self.usd_context.new_stage_async()
_, layer = await self.__create_fake_stage(False)
menu_widget = ui_test.get_menubar()
menu = menu_widget.find_menu("Live State Widget")
self.assertTrue(menu)
await menu.bring_to_front()
await menu.click(menu.center + ui_test.Vec2(50, 0), False, 10)
# hard code the position of click point, as the menu positon changes after running test_join_live_session_users
# don't know why the menu positon changes after running test_join_live_session_users
# await menu.click(ui_test.Vec2(1426, 5), False, 10)
await ui_test.human_delay(100)
await ui_test.select_context_menu("Join With Session Link")
stage_url_with_session = f"{layer.identifier}?live_session_name=test"
omni.kit.clipboard.copy(stage_url_with_session)
window = ui_test.find("JOIN LIVE SESSION WITH LINK")
self.assertTrue(window is not None)
input_field = window.find("**/StringField[*].name=='new_session_link_field'")
self.assertTrue(input_field)
confirm_button = window.find("**/Button[*].name=='confirm_button'")
self.assertTrue(confirm_button)
cancel_button = window.find("**/Button[*].name=='cancel_button'")
self.assertTrue(cancel_button)
# Invalid session name will fail to join
await ui_test.human_delay(100)
input_field.model.set_value("111111")
await confirm_button.click()
await ui_test.human_delay(100)
self.assertFalse(self.live_syncing.is_stage_in_live_session())
self.assertTrue(window.window.visible)
input_field.model.set_value("")
await confirm_button.click()
await ui_test.human_delay(100)
self.assertFalse(self.live_syncing.is_stage_in_live_session())
self.assertTrue(window.window.visible)
await cancel_button.click()
self.assertFalse(self.live_syncing.is_stage_in_live_session())
self.assertFalse(window.window.visible)
window.window.visible = True
await self.wait()
# Valid session link
paste_button = window.find("**/ToolButton[*].name=='paste_button'")
self.assertTrue(paste_button)
await paste_button.click()
self.assertEqual(input_field.model.get_value_as_string(), stage_url_with_session)
await confirm_button.click()
self.assertFalse(window.window.visible)
await ui_test.human_delay(300)
self.assertTrue(self.live_syncing.is_stage_in_live_session())
await menu.click(menu.center + ui_test.Vec2(70, 0), False, 10)
await ui_test.human_delay(100)
# Copy session link
omni.kit.clipboard.copy("unkonwn")
await ui_test.select_context_menu("Share Session Link")
window = ui_test.find("SHARE LIVE SESSION LINK")
self.assertTrue(window is not None)
confirm_button = window.find("**/InvisibleButton[*].name=='confirm_button'")
self.assertTrue(confirm_button)
await confirm_button.click()
stage_url_with_session = f"{layer.identifier}?live_session_name=test"
live_session_link = omni.kit.clipboard.paste()
self.assertTrue(live_session_link, stage_url_with_session)
self.assertFalse(window.window.visible)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_join_live_session_users(self):
await self.__create_fake_stage(join_test_session=True)
await self.wait()
await self.__create_simulated_users()
await self.wait()
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
hide_menu_bar = False,
threshold=1e-4
)
self.live_syncing.stop_all_live_sessions()
await self.wait()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_leave_live_session_users(self):
await self.__create_fake_stage(join_test_session=True)
await self.wait()
await self.__create_simulated_users()
await self.wait()
quit_simulated_user(self.simulated_user_ids[0])
await self.wait()
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
hide_menu_bar=False,
threshold=1e-4
)
self.live_syncing.stop_all_live_sessions()
await self.wait()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_join_live_session_over_max_users(self):
await self.__create_fake_stage(join_test_session=True)
await self.wait()
await self.__create_simulated_users(26)
await self.wait()
await self.finalize_test(golden_img_dir=self._golden_img_dir, hide_menu_bar=False)
self.live_syncing.stop_all_live_sessions()
await self.wait()
| 7,798 | Python | 36.676328 | 119 | 0.645037 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/tests/__init__.py | from .test_live_widget import TestLiveWidget | 44 | Python | 43.999956 | 44 | 0.863636 |
omniverse-code/kit/exts/omni.kit.widget.live/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [2.0.3] - 2022-09-29
- Use new omni.kit.usd.layers interfaces.
## [2.0.2] - 2022-08-30
### Changes
- Show menu options for join.
## [2.0.1] - 2022-07-19
### Changes
- Show app name for user in the live session.
## [2.0.0] - 2022-06-29
### Changes
- Refactoring live widget to move all code into python.
## [1.0.0] - 2022-06-13
### Changes
- Initialize live widget changelog. | 476 | Markdown | 20.681817 | 80 | 0.655462 |
omniverse-code/kit/exts/omni.kit.widget.live/docs/index.rst | omni.kit.widget.live
####################
Omniverse Kit Live Mode Control Widget
| 82 | reStructuredText | 15.599997 | 38 | 0.609756 |
omniverse-code/kit/exts/omni.kit.viewport.ready/PACKAGE-LICENSES/omni.kit.viewport.ready-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.viewport.ready/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.2"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "Viewport Ready"
description="Extension to inject a omni.ui element into the Viewport until rendering has begun"
# Keywords for the extension
keywords = ["kit", "viewport", "utility", "ready"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
category = "Viewport"
[dependencies]
"omni.ui" = {}
"omni.usd" = {}
"omni.kit.window.viewport" = {optional = true} # Load after legacy omni.kit.window.viewport, but don't require it
"omni.kit.viewport.window" = {optional = true} # Load after new omni.kit.viewport.window, but don't require it
# Main python module this extension provides, it will be publicly available as "import omni.kit.viewport.registry".
[[python.module]]
name = "omni.kit.viewport.ready"
[settings]
exts."omni.kit.viewport.ready".startup.enabled = true
exts."omni.kit.viewport.ready".startup.viewport = "Viewport"
exts."omni.kit.viewport.ready".startup.show_once = true
exts."omni.kit.viewport.ready".message = "RTX Loading"
exts."omni.kit.viewport.ready".font_size = 72
exts."omni.kit.viewport.ready".background_color = 0
[[test]]
args = [
"--/app/window/width=512",
"--/app/window/height=512",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture"
]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 1,990 | TOML | 30.603174 | 115 | 0.720603 |
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ext
import omni.kit.app
import carb
class ViewportReadyExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self.__vp_ready = None
self.__vp_extension_hooks = None
# Create a default ready-delegate when exts/omni.kit.viewport.ready/startup/enabled is set
if carb.settings.get_settings().get("exts/omni.kit.viewport.ready/startup/enabled"):
manager = omni.kit.app.get_app().get_extension_manager()
self.__vp_extension_hooks = (
manager.subscribe_to_extension_enable(
self._create_viewport_ready,
self._remove_viewport_ready,
ext_name="omni.kit.window.viewport",
hook_name="omni.kit.viewport.ready.LoadListener-1",
),
manager.subscribe_to_extension_enable(
self._create_viewport_ready,
self._remove_viewport_ready,
ext_name="omni.kit.viewport.window",
hook_name="omni.kit.viewport.ready.LoadListener-2",
)
)
def on_shutdown(self):
self._remove_viewport_ready()
def _create_viewport_ready(self, *args):
async def viewport_ready_ui():
# Honor setting to force this message to only ever show once in a session if requested.
# This needs to happen in the async loop as subscribe_to_extension_enable can call _create_viewport_ready
# before it has returned and assigend hooks to self.__vp_extension_hooks
settings = carb.settings.get_settings()
show_once = bool(settings.get("exts/omni.kit.viewport.ready/startup/show_once"))
if show_once:
self.__vp_extension_hooks = None
import omni.ui
from .viewport_ready import ViewportReady, ViewportReadyDelegate
max_wait = 100
viewport_name = settings.get("exts/omni.kit.viewport.ready/startup/viewport") or "Viewport"
viewport_window = omni.ui.Workspace.get_window(viewport_name)
while viewport_window is None and max_wait:
await omni.kit.app.get_app().next_update_async()
viewport_window = omni.ui.Workspace.get_window(viewport_name)
max_wait = max_wait - 1
# Create a simple delegate that responds to on_complete and clears the objects created
class DefaultDelegate(ViewportReadyDelegate):
def on_complete(delegate_self):
# self is ViewportReadyExtension instance
self.__vp_ready = None
super().on_complete()
self.__vp_ready = ViewportReady(DefaultDelegate())
import asyncio
asyncio.ensure_future(viewport_ready_ui())
def _remove_viewport_ready(self, *args):
self.__vp_ready = None
self.__vp_extension_hooks = None
| 3,381 | Python | 44.093333 | 117 | 0.623188 |
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/__init__.py | from .extension import ViewportReadyExtension
| 46 | Python | 22.499989 | 45 | 0.891304 |
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/viewport_ready.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ['ViewportReadyProgressDelegate', 'ViewportReadyDelegate', 'ViewportReady']
import omni.ui
import omni.usd
import carb
class ViewportReadyProgressDelegate:
def __init__(self, settings: carb.settings.ISettings):
self.__progress = None
self.__label = None
self.__shader_count = None
self.__enabled_mask_id = None
self.setup_updates(settings)
def __del__(self):
self.destroy()
def setup_updates(self, settings: carb.settings.ISettings):
"""Setup the ViewportReadyProgressDelegate to get progress updates"""
try:
import re
import omni.activity.core
import omni.activity.profiler
self.__re_matcher = re.compile("^.*\.hlsl \(UID: [0-9]+\)")
persisted_shader_count = settings.get("/persistent/exts/omni.kit.viewport.ready/shader_count")
# Guard against divide by 0 error in activity_event which shouldn't happen but did once somehow.
self.__shader_count = (0, persisted_shader_count if persisted_shader_count else 1)
profiler = omni.activity.profiler.get_activity_profiler()
if profiler:
self.__enabled_mask_id = profiler.enable_capture_mask(omni.activity.profiler.CAPTURE_MASK_STARTUP)
activity = omni.activity.core.get_instance()
self.__activity = (activity, activity.create_callback_to_pop(self.activity_event))
except (ImportError, RuntimeError):
required_exts = "omni.activity.profiler and omni.activity.pump"
carb.log_error(f"{required_exts} must be enabled with /exts/omni.kit.viewport.ready/activity_progress=true")
def destroy(self):
self.__activity = None
progress, self.__progress = self.__progress, None
if progress:
progress.destroy()
label, self.__label = self.__label, None
if label:
label.destroy()
# Save the total number of shaders processed as the progress max hint for the next launch
if self.__shader_count:
carb.settings.get_settings().set("/persistent/exts/omni.kit.viewport.ready/shader_count", self.__shader_count[0])
# Restore the profile mask to whatever it was before
enabled_mask_id, self.__enabled_mask_id = self.__enabled_mask_id, None
if enabled_mask_id is not None:
profiler = omni.activity.profiler.get_activity_profiler()
profiler.disable_capture_mask(enabled_mask_id)
def activity_event(self, node, root_node: bool = True):
"""Event handler for omni.activity messages"""
# This is a rather delicate method relying on strings being constant to filter properly
node_name = node.name or ""
if not root_node:
if self.__re_matcher.search(node_name) is not None:
self.__shader_count = self.__shader_count[0] + 1, self.__shader_count[1]
self.set_progress(self.__shader_count[0] / self.__shader_count[1], f"Compiling: {node_name}")
elif node_name == "Ray Tracing Pipeline":
for node_id in range(node.child_count):
self.activity_event(node.get_child(node_id), False)
def set_progress(self, amount: float, message: str):
if self.__progress:
self.__progress.model.set_value(amount)
if self.__label:
self.__label.text = message
def build_ui(self, settings: carb.settings.ISettings, font_size: float, color: omni.ui.color):
"""Build the progress ui with font and color style hints"""
margin = settings.get("/exts/omni.kit.viewport.ready/activity_progress/margin")
margin = omni.ui.Percent(20 if margin is None else margin)
omni.ui.Spacer(width=margin)
with omni.ui.VStack():
omni.ui.Spacer(height=5)
self.__progress = omni.ui.ProgressBar(height=5,
alignment=omni.ui.Alignment.CENTER_BOTTOM,
style={"border_width": 2, "border_radius": 5,
"color": color})
omni.ui.Spacer(height=5)
self.__label = omni.ui.Label("", alignment=omni.ui.Alignment.CENTER_TOP, style={"font_size": font_size})
omni.ui.Spacer(width=margin)
class ViewportReadyDelegate:
def __init__(self, viewport_name: str = 'Viewport', usd_context_name: str = '', viewport_handle: int = None):
self.__viewport_name = viewport_name
self.__usd_context_name = usd_context_name
self.__viewport_handle = viewport_handle
self.__frame = None
# The signal RTX sends that first frame is ready could actually come before omni.ui has called the ui build fn
self.__destroyed = False
# Fill in some default based on carb.settings
settings = carb.settings.get_settings()
self.__message = settings.get("/exts/omni.kit.viewport.ready/message") or "RTX Loading"
self.__font_size = settings.get("/exts/omni.kit.viewport.ready/font_size") or 72
if settings.get("/exts/omni.kit.viewport.ready/activity_progress/enabled"):
self.__progress = ViewportReadyProgressDelegate(settings)
else:
self.__progress = None
@property
def message(self) -> str:
'''Return the string for the default omni.ui.Label.'''
if self.__message == "RTX Loading":
active = {
"rtx": "RTX",
"iray": "Iray",
"pxr": "Storm",
"index": "Index"
}.get(carb.settings.get_settings().get("/renderer/active"), None)
if active:
return f"{active} Loading"
return self.__message
@property
def font_size(self) -> float:
'''Return the font-size for the default omni.ui.Label.'''
return self.__font_size
@property
def usd_context_name(self) -> str:
'''Return the omni.usd.UsdContext name this delegate is waiting for completion on.'''
return self.__usd_context_name
@property
def viewport_name(self) -> str:
'''Return the name of the omni.ui.Window this delegate is waiting for completion on.'''
return self.__viewport_name
@property
def viewport_handle(self) -> int:
'''Return the ViewportHandle this delegate is waiting for completion on or None for any Viewport.'''
return self.__viewport_handle
def on_complete(self):
'''Callback function invoked when first rendered frame is delivered'''
# Make sure to always call destroy if any exception is thrown during log_complete
try:
self.log_complete()
finally:
self.destroy()
def log_complete(self, msg: str = None, prefix_time_since_start: bool = True):
'''Callback function that will log to info (and stdout if /app/enableStdoutOutput is enabled)'''
if msg is None:
msg = 'RTX ready'
if prefix_time_since_start:
import omni.kit.app
seconds = omni.kit.app.get_app().get_time_since_start_s()
msg = "[{0:.3f}s] ".format(seconds) + msg
if carb.settings.get_settings().get('/app/enableStdoutOutput'):
# Going to sys.stdout directly is cleaner when launched with -info
import sys
sys.stdout.write(msg + '\n')
else:
carb.log_info(msg)
def build_label(self) -> omni.ui.Widget:
'''Simple method to override the basic label showing progress.'''
return omni.ui.Label(self.message, alignment=omni.ui.Alignment.CENTER, style={"font_size": self.font_size})
def build_progress(self) -> None:
settings = carb.settings.get_settings()
color = settings.get("/exts/omni.kit.viewport.ready/activity_progress/color")
color = omni.ui.color("#76b900" if color is None else color)
font_size = settings.get("/exts/omni.kit.viewport.ready/activity_progress/font_size")
if font_size is None:
font_size = self.__font_size / 6
omni.ui.Spacer(height=5)
with omni.ui.HStack():
self.__progress.build_ui(settings, font_size, color)
def build_frame(self) -> None:
'''Method to override the basic frame showing progress.'''
# If RTX is ready before omni.ui is calling the build function, then do nothing
if self.__destroyed:
return
self.__frame = omni.ui.ZStack()
with self.__frame:
bg_color = carb.settings.get_settings().get('/exts/omni.kit.viewport.ready/background_color')
if bg_color:
omni.ui.Rectangle(style={"background_color": bg_color})
with omni.ui.VStack():
kwargs = {}
if self.__progress:
kwargs = {"height": omni.ui.Percent(35)}
omni.ui.Spacer(**kwargs)
self.build_label()
if self.__progress:
self.build_progress()
omni.ui.Spacer()
def build_ui(self) -> None:
'''Method to build the progress/info state in the Viewport window.'''
# If RTX is ready before build_ui is called then do nothing
if self.__destroyed:
return
if self.__frame is None:
viewport_window = omni.ui.Workspace.get_window(self.viewport_name)
if viewport_window:
frame = None
if hasattr(viewport_window, 'get_frame'):
frame = viewport_window.get_frame('omni.kit.viewport.ready.ViewportReadyDelegate')
else:
# TODO: Use omni.kit.viewport.utility get_viewport_window to manage omni.ui Wrapper on legacy viewport
if hasattr(viewport_window, 'frame'):
frame = viewport_window.frame
if frame:
frame.set_build_fn(self.build_frame)
def __del__(self):
self.destroy()
def destroy(self):
self.__destroyed = True
progress, self.__progress = self.__progress, None
if progress:
progress.destroy()
if self.__frame:
self.__frame.visible = False
if hasattr(self.__frame, 'clear'):
self.__frame.clear()
self.__frame.destroy()
self.__frame = None
class ViewportReady:
def __init__(self, viewport_ready: ViewportReadyDelegate = None):
self.__viewport_ready = viewport_ready if viewport_ready else ViewportReadyDelegate()
usd_context_name = self.__viewport_ready.usd_context_name
usd_context = omni.usd.get_context(usd_context_name)
if usd_context:
# Build the UI objects now
self.__viewport_ready.build_ui()
# Subscribe to the eent to wait for frame delivery
self.__new_frame_sub = usd_context.get_rendering_event_stream().create_subscription_to_push_by_type(
int(omni.usd.StageRenderingEventType.NEW_FRAME),
self.__on_event,
name=f"omni.kit.viewport.ready.ViewportReady"
)
else:
raise RuntimeError(f'No omni.usd.UsdContext found with name "{usd_context_name}"')
def __del__(self):
self.destroy()
def destroy(self):
self.__new_frame_sub = None
self.__viewport_ready = None
def __on_event(self, e: carb.events.IEvent):
waiting_for = self.__viewport_ready.viewport_handle
if (waiting_for is None) or (waiting_for == e.payload["viewport_handle"]):
if self.__viewport_complete():
# Avoid wrapping callback in try/catch by storing it first, destroying, then calling it
viewport_ready, self.__viewport_ready = self.__viewport_ready, None
self.destroy()
viewport_ready.on_complete()
del viewport_ready
def __viewport_complete(self):
usd_context_name = self.__viewport_ready.usd_context_name
window_name = self.__viewport_ready.viewport_name
try:
from omni.kit.viewport.window import get_viewport_window_instances
# Get every ViewportWindow, regardless of UsdContext it is attached to
for window in get_viewport_window_instances(usd_context_name):
if window.title == window_name:
return window.viewport_api.frame_info.get('viewport_handle', None) is not None
except ImportError:
pass
try:
import omni.kit.viewport_legacy as vp_legacy
vp_iface = vp_legacy.get_viewport_interface()
viewport_handle = vp_iface.get_instance(window_name)
if viewport_handle:
vp_window = vp_iface.get_viewport_window(viewport_handle)
if vp_window:
return bool(vp_window.get_drawable_ldr_resource() or vp_window.get_drawable_hdr_resource())
except ImportError:
pass
return False
| 13,578 | Python | 42.107936 | 125 | 0.602887 |
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/tests/__init__.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestViewportReady']
import omni.kit.test
from ..viewport_ready import ViewportReadyDelegate, ViewportReady
import omni.usd
import omni.ui
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
EXTENSION_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.ready}")).resolve().absolute()
TEST_PATH = EXTENSION_PATH.joinpath("data", "tests")
WIDTH, HEIGHT = 512, 512
class TestViewportReady(OmniUiTest):
async def setUp(self):
await super().setUp()
async def tearDown(self):
await super().tearDown()
@staticmethod
def __test_image_name(base_name: str):
settings = carb.settings.get_settings()
if settings.get("/exts/omni.kit.viewport.ready/activity_progress/enabled"):
base_name += "_progress"
if settings.get("/exts/omni.kit.viewport.window/startup/windowName"):
base_name += "_viewport"
return base_name + ".png"
async def test_ready_delegate_begin(self):
'''Test the Viewport readys status message is placed inside a ui.Window named Viewport'''
await self.create_test_area(WIDTH, HEIGHT)
test_window = omni.ui.Window(
"Viewport",
dockPreference=omni.ui.DockPreference.DISABLED,
flags=omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE,
width=WIDTH,
height=HEIGHT
)
await self.wait_n_updates()
delegate = ViewportReadyDelegate()
delegate.build_ui()
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_begin"))
async def test_ready_delegate_end(self):
'''Test the Viewport readys status message is removed from the Viewport'''
await self.create_test_area(WIDTH, HEIGHT)
test_window = omni.ui.Window(
"Viewport",
dockPreference=omni.ui.DockPreference.DISABLED,
flags=omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE,
width=WIDTH,
height=HEIGHT
)
await self.wait_n_updates()
delegate = ViewportReadyDelegate()
delegate.build_ui()
await self.wait_n_updates()
delegate.on_complete()
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_end"))
async def test_settings(self):
'''Test carb.settings usage for default delegate'''
# Make sure the values being set aren't the defaults!
delegate = ViewportReadyDelegate()
self.assertNotEqual(delegate.message, 'TEST MESSAGE')
self.assertNotEqual(delegate.font_size, 128)
import carb
settings = carb.settings.get_settings()
# Save all the defaults for restoration for later tests
preferences = [
'/exts/omni.kit.viewport.ready/message',
'/exts/omni.kit.viewport.ready/font_size',
]
defaults = {k: settings.get(k) for k in preferences}
try:
settings.set('/exts/omni.kit.viewport.ready/message', 'TEST MESSAGE')
settings.set('/exts/omni.kit.viewport.ready/font_size', 128)
delegate = ViewportReadyDelegate(viewport_name='Not a Viewport', usd_context_name='Not a UsdContext')
self.assertEqual(delegate.message, 'TEST MESSAGE')
self.assertEqual(delegate.font_size, 128)
self.assertEqual(delegate.viewport_name, 'Not a Viewport')
self.assertEqual(delegate.usd_context_name, 'Not a UsdContext')
except Exception as e:
raise e
finally:
# Restore the defaults
for k, v in defaults.items():
settings.set(k, v)
async def test_throw_in_log_message(self):
'''Test the Viewport readys status message is removed from the Viewport when log_message throws an Exception'''
await self.create_test_area(WIDTH, HEIGHT)
test_window = omni.ui.Window(
"Viewport",
dockPreference=omni.ui.DockPreference.DISABLED,
flags=omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE,
width=WIDTH,
height=HEIGHT
)
await self.wait_n_updates()
log_complete_threw = False
class LocalExpection(RuntimeError):
pass
class ThrowingViewportReadyDelegate(ViewportReadyDelegate):
def log_complete(self):
nonlocal log_complete_threw
log_complete_threw = True
raise LocalExpection("Expected to throw")
try:
delegate = ThrowingViewportReadyDelegate()
delegate.build_ui()
await self.wait_n_updates()
await self.capture_and_compare(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_threw_begin"))
delegate.on_complete()
except LocalExpection:
pass
self.assertTrue(log_complete_threw)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_threw_end"))
| 5,879 | Python | 38.463087 | 143 | 0.647899 |
omniverse-code/kit/exts/omni.kit.viewport.ready/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.kit.viewport.ready`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`_.
## [1.0.2] - 2022-10-28
### Fixed
- Possibility that RTX has sent a ready event before omni.ui has called the build_fn callback.
### Added
- Setting to force the message to only ever appear once in application session (on by default).
- Setting to specify a background color for the "RTX Loading" frame (transparent by default).
## [1.0.1] - 2022-04-22
### Added
- Log to stdout when requested
### Fixed
- Early exit wait loop after Viewport created
## [1.0.0] - 2022-04-12
### Added
- Initial release
| 672 | Markdown | 29.590908 | 95 | 0.720238 |
omniverse-code/kit/exts/omni.kit.viewport.ready/docs/README.md | # Viewport Ready extension [omni.kit.viewport.ready]
Utility extension to place a message (or omni.ui objects) in the Viewport until a rendered frame has been delivered.
| 170 | Markdown | 55.999981 | 116 | 0.8 |
omniverse-code/kit/exts/omni.kit.viewport.ready/docs/index.rst | omni.kit.viewport.ready
###########################
Viewport Ready
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule:: omni.kit.viewport.ready
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
| 289 | reStructuredText | 13.499999 | 43 | 0.598616 |
omniverse-code/kit/exts/omni.kit.viewport.ready/docs/Overview.md | # Overview
| 11 | Markdown | 4.999998 | 10 | 0.727273 |
omniverse-code/kit/exts/omni.volume_nodes/ogn/docs/SaveVDB.rst | .. _omni_volume_SaveVDB_1:
.. _omni_volume_SaveVDB:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Save VDB
:keywords: lang-en omnigraph node Omni Volume WriteOnly volume save-v-d-b
Save VDB
========
.. <description>
Saves a VDB from file and puts it in a memory buffer.
.. </description>
Installation
------------
To use this node enable :ref:`omni.volume_nodes<ext_omni_volume_nodes>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:assetPath", "``token``", "Path to VDB file to save.", ""
"inputs:compressionMode", "``token``", "The compression mode to use when encoding", "None"
"", "*allowedTokens*", "None,Blosc,Zip", ""
"", "*default*", "None", ""
"inputs:data", "``uint[]``", "Data to save to file in NanoVDB or OpenVDB memory format.", "[]"
"inputs:execIn", "``execution``", "Input execution", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:execOut", "``execution``", "Output execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.volume.SaveVDB"
"Version", "1"
"Extension", "omni.volume_nodes"
"Has State?", "True"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"tags", "VDB"
"uiName", "Save VDB"
"__tokens", "{""none"": ""None"", ""blosc"": ""Blosc"", ""zip"": ""Zip""}"
"Categories", "Omni Volume"
"Generated Class Name", "SaveVDBDatabase"
"Python Module", "omni.volume_nodes"
| 1,894 | reStructuredText | 24.266666 | 98 | 0.541183 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.