file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/components.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import functools
from debugpy.common import json, log, messaging, util
ACCEPT_CONNECTIONS_TIMEOUT = 10
class ComponentNotAvailable(Exception):
def __init__(self, type):
super().__init__(f"{type.__name__} is not available")
class Component(util.Observable):
"""A component managed by a debug adapter: client, launcher, or debug server.
Every component belongs to a Session, which is used for synchronization and
shared data.
Every component has its own message channel, and provides message handlers for
that channel. All handlers should be decorated with @Component.message_handler,
which ensures that Session is locked for the duration of the handler. Thus, only
one handler is running at any given time across all components, unless the lock
is released explicitly or via Session.wait_for().
Components report changes to their attributes to Session, allowing one component
to wait_for() a change caused by another component.
"""
def __init__(self, session, stream=None, channel=None):
assert (stream is None) ^ (channel is None)
try:
lock_held = session.lock.acquire(blocking=False)
assert lock_held, "__init__ of a Component subclass must lock its Session"
finally:
session.lock.release()
super().__init__()
self.session = session
if channel is None:
stream.name = str(self)
channel = messaging.JsonMessageChannel(stream, self)
channel.start()
else:
channel.name = channel.stream.name = str(self)
channel.handlers = self
self.channel = channel
self.is_connected = True
# Do this last to avoid triggering useless notifications for assignments above.
self.observers += [lambda *_: self.session.notify_changed()]
def __str__(self):
return f"{type(self).__name__}[{self.session.id}]"
@property
def client(self):
return self.session.client
@property
def launcher(self):
return self.session.launcher
@property
def server(self):
return self.session.server
def wait_for(self, *args, **kwargs):
return self.session.wait_for(*args, **kwargs)
@staticmethod
def message_handler(f):
"""Applied to a message handler to automatically lock and unlock the session
for its duration, and to validate the session state.
If the handler raises ComponentNotAvailable or JsonIOError, converts it to
Message.cant_handle().
"""
@functools.wraps(f)
def lock_and_handle(self, message):
try:
with self.session:
return f(self, message)
except ComponentNotAvailable as exc:
raise message.cant_handle("{0}", exc, silent=True)
except messaging.MessageHandlingError as exc:
if exc.cause is message:
raise
else:
exc.propagate(message)
except messaging.JsonIOError as exc:
raise message.cant_handle(
"{0} disconnected unexpectedly", exc.stream.name, silent=True
)
return lock_and_handle
def disconnect(self):
with self.session:
self.is_connected = False
self.session.finalize("{0} has disconnected".format(self))
def missing(session, type):
class Missing(object):
"""A dummy component that raises ComponentNotAvailable whenever some
attribute is accessed on it.
"""
__getattr__ = __setattr__ = lambda self, *_: report()
__bool__ = __nonzero__ = lambda self: False
def report():
try:
raise ComponentNotAvailable(type)
except Exception as exc:
log.reraise_exception("{0} in {1}", exc, session)
return Missing()
class Capabilities(dict):
"""A collection of feature flags for a component. Corresponds to JSON properties
in the DAP "initialize" request or response, other than those that identify the
party.
"""
PROPERTIES = {}
"""JSON property names and default values for the the capabilities represented
by instances of this class. Keys are names, and values are either default values
or validators.
If the value is callable, it must be a JSON validator; see debugpy.common.json for
details. If the value is not callable, it is as if json.default(value) validator
was used instead.
"""
def __init__(self, component, message):
"""Parses an "initialize" request or response and extracts the feature flags.
For every "X" in self.PROPERTIES, sets self["X"] to the corresponding value
from message.payload if it's present there, or to the default value otherwise.
"""
assert message.is_request("initialize") or message.is_response("initialize")
self.component = component
payload = message.payload
for name, validate in self.PROPERTIES.items():
value = payload.get(name, ())
if not callable(validate):
validate = json.default(validate)
try:
value = validate(value)
except Exception as exc:
raise message.isnt_valid("{0} {1}", json.repr(name), exc)
assert (
value != ()
), f"{validate} must provide a default value for missing properties."
self[name] = value
log.debug("{0}", self)
def __repr__(self):
return f"{type(self).__name__}: {json.repr(dict(self))}"
def require(self, *keys):
for key in keys:
if not self[key]:
raise messaging.MessageHandlingError(
f"{self.component} does not have capability {json.repr(key)}",
)
| 6,081 | Python | 32.054348 | 87 | 0.617333 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/__main__.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import argparse
import atexit
import codecs
import locale
import os
import sys
# WARNING: debugpy and submodules must not be imported on top level in this module,
# and should be imported locally inside main() instead.
def main(args):
# If we're talking DAP over stdio, stderr is not guaranteed to be read from,
# so disable it to avoid the pipe filling and locking up. This must be done
# as early as possible, before the logging module starts writing to it.
if args.port is None:
sys.stderr = stderr = open(os.devnull, "w")
atexit.register(stderr.close)
from debugpy import adapter
from debugpy.common import json, log, sockets
from debugpy.adapter import clients, servers, sessions
if args.for_server is not None:
if os.name == "posix":
# On POSIX, we need to leave the process group and its session, and then
# daemonize properly by double-forking (first fork already happened when
# this process was spawned).
# NOTE: if process is already the session leader, then
# setsid would fail with `operation not permitted`
if os.getsid(os.getpid()) != os.getpid():
os.setsid()
if os.fork() != 0:
sys.exit(0)
for stdio in sys.stdin, sys.stdout, sys.stderr:
if stdio is not None:
stdio.close()
if args.log_stderr:
log.stderr.levels |= set(log.LEVELS)
if args.log_dir is not None:
log.log_dir = args.log_dir
log.to_file(prefix="debugpy.adapter")
log.describe_environment("debugpy.adapter startup environment:")
servers.access_token = args.server_access_token
if args.for_server is None:
adapter.access_token = codecs.encode(os.urandom(32), "hex").decode("ascii")
endpoints = {}
try:
client_host, client_port = clients.serve(args.host, args.port)
except Exception as exc:
if args.for_server is None:
raise
endpoints = {"error": "Can't listen for client connections: " + str(exc)}
else:
endpoints["client"] = {"host": client_host, "port": client_port}
if args.for_server is not None:
try:
server_host, server_port = servers.serve()
except Exception as exc:
endpoints = {"error": "Can't listen for server connections: " + str(exc)}
else:
endpoints["server"] = {"host": server_host, "port": server_port}
log.info(
"Sending endpoints info to debug server at localhost:{0}:\n{1}",
args.for_server,
json.repr(endpoints),
)
try:
sock = sockets.create_client()
try:
sock.settimeout(None)
sock.connect(("127.0.0.1", args.for_server))
sock_io = sock.makefile("wb", 0)
try:
sock_io.write(json.dumps(endpoints).encode("utf-8"))
finally:
sock_io.close()
finally:
sockets.close_socket(sock)
except Exception:
log.reraise_exception("Error sending endpoints info to debug server:")
if "error" in endpoints:
log.error("Couldn't set up endpoints; exiting.")
sys.exit(1)
listener_file = os.getenv("DEBUGPY_ADAPTER_ENDPOINTS")
if listener_file is not None:
log.info(
"Writing endpoints info to {0!r}:\n{1}", listener_file, json.repr(endpoints)
)
def delete_listener_file():
log.info("Listener ports closed; deleting {0!r}", listener_file)
try:
os.remove(listener_file)
except Exception:
log.swallow_exception(
"Failed to delete {0!r}", listener_file, level="warning"
)
try:
with open(listener_file, "w") as f:
atexit.register(delete_listener_file)
print(json.dumps(endpoints), file=f)
except Exception:
log.reraise_exception("Error writing endpoints info to file:")
if args.port is None:
clients.Client("stdio")
# These must be registered after the one above, to ensure that the listener sockets
# are closed before the endpoint info file is deleted - this way, another process
# can wait for the file to go away as a signal that the ports are no longer in use.
atexit.register(servers.stop_serving)
atexit.register(clients.stop_serving)
servers.wait_until_disconnected()
log.info("All debug servers disconnected; waiting for remaining sessions...")
sessions.wait_until_ended()
log.info("All debug sessions have ended; exiting.")
def _parse_argv(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
"--for-server", type=int, metavar="PORT", help=argparse.SUPPRESS
)
parser.add_argument(
"--port",
type=int,
default=None,
metavar="PORT",
help="start the adapter in debugServer mode on the specified port",
)
parser.add_argument(
"--host",
type=str,
default="127.0.0.1",
metavar="HOST",
help="start the adapter in debugServer mode on the specified host",
)
parser.add_argument(
"--access-token", type=str, help="access token expected from the server"
)
parser.add_argument(
"--server-access-token", type=str, help="access token expected by the server"
)
parser.add_argument(
"--log-dir",
type=str,
metavar="DIR",
help="enable logging and use DIR to save adapter logs",
)
parser.add_argument(
"--log-stderr", action="store_true", help="enable logging to stderr"
)
args = parser.parse_args(argv[1:])
if args.port is None:
if args.log_stderr:
parser.error("--log-stderr requires --port")
if args.for_server is not None:
parser.error("--for-server requires --port")
return args
if __name__ == "__main__":
# debugpy can also be invoked directly rather than via -m. In this case, the first
# entry on sys.path is the one added automatically by Python for the directory
# containing this file. This means that import debugpy will not work, since we need
# the parent directory of debugpy/ to be in sys.path, rather than debugpy/adapter/.
#
# The other issue is that many other absolute imports will break, because they
# will be resolved relative to debugpy/adapter/ - e.g. `import state` will then try
# to import debugpy/adapter/state.py.
#
# To fix both, we need to replace the automatically added entry such that it points
# at parent directory of debugpy/ instead of debugpy/adapter, import debugpy with that
# in sys.path, and then remove the first entry entry altogether, so that it doesn't
# affect any further imports we might do. For example, suppose the user did:
#
# python /foo/bar/debugpy/adapter ...
#
# At the beginning of this script, sys.path will contain "/foo/bar/debugpy/adapter"
# as the first entry. What we want is to replace it with "/foo/bar', then import
# debugpy with that in effect, and then remove the replaced entry before any more
# code runs. The imported debugpy module will remain in sys.modules, and thus all
# future imports of it or its submodules will resolve accordingly.
if "debugpy" not in sys.modules:
# Do not use dirname() to walk up - this can be a relative path, e.g. ".".
sys.path[0] = sys.path[0] + "/../../"
__import__("debugpy")
del sys.path[0]
# Apply OS-global and user-specific locale settings.
try:
locale.setlocale(locale.LC_ALL, "")
except Exception:
# On POSIX, locale is set via environment variables, and this can fail if
# those variables reference a non-existing locale. Ignore and continue using
# the default "C" locale if so.
pass
main(_parse_argv(sys.argv))
| 8,257 | Python | 35.219298 | 90 | 0.619232 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/servers.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import annotations
import os
import subprocess
import sys
import threading
import time
import debugpy
from debugpy import adapter
from debugpy.common import json, log, messaging, sockets
from debugpy.adapter import components
import traceback
import io
access_token = None
"""Access token used to authenticate with the servers."""
listener = None
"""Listener socket that accepts server connections."""
_lock = threading.RLock()
_connections = []
"""All servers that are connected to this adapter, in order in which they connected.
"""
_connections_changed = threading.Event()
class Connection(object):
"""A debug server that is connected to the adapter.
Servers that are not participating in a debug session are managed directly by the
corresponding Connection instance.
Servers that are participating in a debug session are managed by that sessions's
Server component instance, but Connection object remains, and takes over again
once the session ends.
"""
disconnected: bool
process_replaced: bool
"""Whether this is a connection to a process that is being replaced in situ
by another process, e.g. via exec().
"""
server: Server | None
"""The Server component, if this debug server belongs to Session.
"""
pid: int | None
ppid: int | None
channel: messaging.JsonMessageChannel
def __init__(self, sock):
from debugpy.adapter import sessions
self.disconnected = False
self.process_replaced = False
self.server = None
self.pid = None
stream = messaging.JsonIOStream.from_socket(sock, str(self))
self.channel = messaging.JsonMessageChannel(stream, self)
self.channel.start()
try:
self.authenticate()
info = self.channel.request("pydevdSystemInfo")
process_info = info("process", json.object())
self.pid = process_info("pid", int)
self.ppid = process_info("ppid", int, optional=True)
if self.ppid == ():
self.ppid = None
self.channel.name = stream.name = str(self)
with _lock:
# The server can disconnect concurrently before we get here, e.g. if
# it was force-killed. If the disconnect() handler has already run,
# don't register this server or report it, since there's nothing to
# deregister it.
if self.disconnected:
return
# An existing connection with the same PID and process_replaced == True
# corresponds to the process that replaced itself with this one, so it's
# not an error.
if any(
conn.pid == self.pid and not conn.process_replaced
for conn in _connections
):
raise KeyError(f"{self} is already connected to this adapter")
is_first_server = len(_connections) == 0
_connections.append(self)
_connections_changed.set()
except Exception:
log.swallow_exception("Failed to accept incoming server connection:")
self.channel.close()
# If this was the first server to connect, and the main thread is inside
# wait_until_disconnected(), we want to unblock it and allow it to exit.
dont_wait_for_first_connection()
# If we couldn't retrieve all the necessary info from the debug server,
# or there's a PID clash, we don't want to track this debuggee anymore,
# but we want to continue accepting connections.
return
parent_session = sessions.get(self.ppid)
if parent_session is None:
parent_session = sessions.get(self.pid)
if parent_session is None:
log.info("No active debug session for parent process of {0}.", self)
else:
if self.pid == parent_session.pid:
parent_server = parent_session.server
if not (parent_server and parent_server.connection.process_replaced):
log.error("{0} is not expecting replacement.", parent_session)
self.channel.close()
return
try:
parent_session.client.notify_of_subprocess(self)
return
except Exception:
# This might fail if the client concurrently disconnects from the parent
# session. We still want to keep the connection around, in case the
# client reconnects later. If the parent session was "launch", it'll take
# care of closing the remaining server connections.
log.swallow_exception(
"Failed to notify parent session about {0}:", self
)
# If we got to this point, the subprocess notification was either not sent,
# or not delivered successfully. For the first server, this is expected, since
# it corresponds to the root process, and there is no other debug session to
# notify. But subsequent server connections represent subprocesses, and those
# will not start running user code until the client tells them to. Since there
# isn't going to be a client without the notification, such subprocesses have
# to be unblocked.
if is_first_server:
return
log.info("No clients to wait for - unblocking {0}.", self)
try:
self.channel.request("initialize", {"adapterID": "debugpy"})
self.channel.request("attach", {"subProcessId": self.pid})
self.channel.request("configurationDone")
self.channel.request("disconnect")
except Exception:
log.swallow_exception("Failed to unblock orphaned subprocess:")
self.channel.close()
def __str__(self):
return "Server" + ("[?]" if self.pid is None else f"[pid={self.pid}]")
def authenticate(self):
if access_token is None and adapter.access_token is None:
return
auth = self.channel.request(
"pydevdAuthorize", {"debugServerAccessToken": access_token}
)
if auth["clientAccessToken"] != adapter.access_token:
self.channel.close()
raise RuntimeError('Mismatched "clientAccessToken"; server not authorized.')
def request(self, request):
raise request.isnt_valid(
"Requests from the debug server to the client are not allowed."
)
def event(self, event):
pass
def terminated_event(self, event):
self.channel.close()
def disconnect(self):
with _lock:
self.disconnected = True
if self.server is not None:
# If the disconnect happened while Server was being instantiated,
# we need to tell it, so that it can clean up via Session.finalize().
# It will also take care of deregistering the connection in that case.
self.server.disconnect()
elif self in _connections:
_connections.remove(self)
_connections_changed.set()
def attach_to_session(self, session):
"""Attaches this server to the specified Session as a Server component.
Raises ValueError if the server already belongs to some session.
"""
with _lock:
if self.server is not None:
raise ValueError
log.info("Attaching {0} to {1}", self, session)
self.server = Server(session, self)
class Server(components.Component):
"""Handles the debug server side of a debug session."""
message_handler = components.Component.message_handler
connection: Connection
class Capabilities(components.Capabilities):
PROPERTIES = {
"supportsCompletionsRequest": False,
"supportsConditionalBreakpoints": False,
"supportsConfigurationDoneRequest": False,
"supportsDataBreakpoints": False,
"supportsDelayedStackTraceLoading": False,
"supportsDisassembleRequest": False,
"supportsEvaluateForHovers": False,
"supportsExceptionInfoRequest": False,
"supportsExceptionOptions": False,
"supportsFunctionBreakpoints": False,
"supportsGotoTargetsRequest": False,
"supportsHitConditionalBreakpoints": False,
"supportsLoadedSourcesRequest": False,
"supportsLogPoints": False,
"supportsModulesRequest": False,
"supportsReadMemoryRequest": False,
"supportsRestartFrame": False,
"supportsRestartRequest": False,
"supportsSetExpression": False,
"supportsSetVariable": False,
"supportsStepBack": False,
"supportsStepInTargetsRequest": False,
"supportsTerminateRequest": True,
"supportsTerminateThreadsRequest": False,
"supportsValueFormattingOptions": False,
"exceptionBreakpointFilters": [],
"additionalModuleColumns": [],
"supportedChecksumAlgorithms": [],
}
def __init__(self, session, connection):
assert connection.server is None
with session:
assert not session.server
super().__init__(session, channel=connection.channel)
self.connection = connection
assert self.session.pid is None
if self.session.launcher and self.session.launcher.pid != self.pid:
log.info(
"Launcher reported PID={0}, but server reported PID={1}",
self.session.launcher.pid,
self.pid,
)
self.session.pid = self.pid
session.server = self
@property
def pid(self):
"""Process ID of the debuggee process, as reported by the server."""
return self.connection.pid
@property
def ppid(self):
"""Parent process ID of the debuggee process, as reported by the server."""
return self.connection.ppid
def initialize(self, request):
assert request.is_request("initialize")
self.connection.authenticate()
request = self.channel.propagate(request)
request.wait_for_response()
self.capabilities = self.Capabilities(self, request.response)
# Generic request handler, used if there's no specific handler below.
@message_handler
def request(self, request):
# Do not delegate requests from the server by default. There is a security
# boundary between the server and the adapter, and we cannot trust arbitrary
# requests sent over that boundary, since they may contain arbitrary code
# that the client will execute - e.g. "runInTerminal". The adapter must only
# propagate requests that it knows are safe.
raise request.isnt_valid(
"Requests from the debug server to the client are not allowed."
)
# Generic event handler, used if there's no specific handler below.
@message_handler
def event(self, event):
self.client.propagate_after_start(event)
@message_handler
def initialized_event(self, event):
# pydevd doesn't send it, but the adapter will send its own in any case.
pass
@message_handler
def process_event(self, event):
# If there is a launcher, it's handling the process event.
if not self.launcher:
self.client.propagate_after_start(event)
@message_handler
def continued_event(self, event):
# https://github.com/microsoft/ptvsd/issues/1530
#
# DAP specification says that a step request implies that only the thread on
# which that step occurred is resumed for the duration of the step. However,
# for VS compatibility, pydevd can operate in a mode that resumes all threads
# instead. This is set according to the value of "steppingResumesAllThreads"
# in "launch" or "attach" request, which defaults to true. If explicitly set
# to false, pydevd will only resume the thread that was stepping.
#
# To ensure that the client is aware that other threads are getting resumed in
# that mode, pydevd sends a "continued" event with "allThreadsResumed": true.
# when responding to a step request. This ensures correct behavior in VSCode
# and other DAP-conformant clients.
#
# On the other hand, VS does not follow the DAP specification in this regard.
# When it requests a step, it assumes that all threads will be resumed, and
# does not expect to see "continued" events explicitly reflecting that fact.
# If such events are sent regardless, VS behaves erratically. Thus, we have
# to suppress them specifically for VS.
if self.client.client_id not in ("visualstudio", "vsformac"):
self.client.propagate_after_start(event)
@message_handler
def exited_event(self, event: messaging.Event):
if event("pydevdReason", str, optional=True) == "processReplaced":
# The parent process used some API like exec() that replaced it with another
# process in situ. The connection will shut down immediately afterwards, but
# we need to keep the corresponding session alive long enough to report the
# subprocess to it.
self.connection.process_replaced = True
else:
# If there is a launcher, it's handling the exit code.
if not self.launcher:
self.client.propagate_after_start(event)
@message_handler
def terminated_event(self, event):
# Do not propagate this, since we'll report our own.
self.channel.close()
def detach_from_session(self):
with _lock:
self.is_connected = False
self.channel.handlers = self.connection
self.channel.name = self.channel.stream.name = str(self.connection)
self.connection.server = None
def disconnect(self):
if self.connection.process_replaced:
# Wait for the replacement server to connect to the adapter, and to report
# itself to the client for this session if there is one.
log.info("{0} is waiting for replacement subprocess.", self)
session = self.session
if not session.client or not session.client.is_connected:
wait_for_connection(
session, lambda conn: conn.pid == self.pid, timeout=30
)
else:
self.wait_for(
lambda: (
not session.client
or not session.client.is_connected
or any(
conn.pid == self.pid
for conn in session.client.known_subprocesses
)
),
timeout=30,
)
with _lock:
_connections.remove(self.connection)
_connections_changed.set()
super().disconnect()
def serve(host="127.0.0.1", port=0):
global listener
listener = sockets.serve("Server", Connection, host, port)
return listener.getsockname()
def is_serving():
return listener is not None
def stop_serving():
global listener
try:
if listener is not None:
listener.close()
listener = None
except Exception:
log.swallow_exception(level="warning")
def connections():
with _lock:
return list(_connections)
def wait_for_connection(session, predicate, timeout=None):
"""Waits until there is a server matching the specified predicate connected to
this adapter, and returns the corresponding Connection.
If there is more than one server connection already available, returns the oldest
one.
"""
def wait_for_timeout():
time.sleep(timeout)
wait_for_timeout.timed_out = True
with _lock:
_connections_changed.set()
wait_for_timeout.timed_out = timeout == 0
if timeout:
thread = threading.Thread(
target=wait_for_timeout, name="servers.wait_for_connection() timeout"
)
thread.daemon = True
thread.start()
if timeout != 0:
log.info("{0} waiting for connection from debug server...", session)
while True:
with _lock:
_connections_changed.clear()
conns = (conn for conn in _connections if predicate(conn))
conn = next(conns, None)
if conn is not None or wait_for_timeout.timed_out:
return conn
_connections_changed.wait()
def wait_until_disconnected():
"""Blocks until all debug servers disconnect from the adapter.
If there are no server connections, waits until at least one is established first,
before waiting for it to disconnect.
"""
while True:
_connections_changed.wait()
with _lock:
_connections_changed.clear()
if not len(_connections):
return
def dont_wait_for_first_connection():
"""Unblocks any pending wait_until_disconnected() call that is waiting on the
first server to connect.
"""
with _lock:
_connections_changed.set()
def inject(pid, debugpy_args, on_output):
host, port = listener.getsockname()
cmdline = [
sys.executable,
os.path.dirname(debugpy.__file__),
"--connect",
host + ":" + str(port),
]
if adapter.access_token is not None:
cmdline += ["--adapter-access-token", adapter.access_token]
cmdline += debugpy_args
cmdline += ["--pid", str(pid)]
log.info("Spawning attach-to-PID debugger injector: {0!r}", cmdline)
try:
injector = subprocess.Popen(
cmdline,
bufsize=0,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
except Exception as exc:
log.swallow_exception(
"Failed to inject debug server into process with PID={0}", pid
)
raise messaging.MessageHandlingError(
"Failed to inject debug server into process with PID={0}: {1}".format(
pid, exc
)
)
# We need to capture the output of the injector - needed so that it doesn't
# get blocked on a write() syscall (besides showing it to the user if it
# is taking longer than expected).
output_collected = []
output_collected.append("--- Starting attach to pid: {0} ---\n".format(pid))
def capture(stream):
nonlocal output_collected
try:
while True:
line = stream.readline()
if not line:
break
line = line.decode("utf-8", "replace")
output_collected.append(line)
log.info("Injector[PID={0}] output: {1}", pid, line.rstrip())
log.info("Injector[PID={0}] exited.", pid)
except Exception:
s = io.StringIO()
traceback.print_exc(file=s)
on_output("stderr", s.getvalue())
threading.Thread(
target=capture,
name=f"Injector[PID={pid}] stdout",
args=(injector.stdout,),
daemon=True,
).start()
def info_on_timeout():
nonlocal output_collected
taking_longer_than_expected = False
initial_time = time.time()
while True:
time.sleep(1)
returncode = injector.poll()
if returncode is not None:
if returncode != 0:
# Something didn't work out. Let's print more info to the user.
on_output(
"stderr",
"Attach to PID failed.\n\n",
)
old = output_collected
output_collected = []
contents = "".join(old)
on_output("stderr", "".join(contents))
break
elapsed = time.time() - initial_time
on_output(
"stdout", "Attaching to PID: %s (elapsed: %.2fs).\n" % (pid, elapsed)
)
if not taking_longer_than_expected:
if elapsed > 10:
taking_longer_than_expected = True
if sys.platform in ("linux", "linux2"):
on_output(
"stdout",
"\nThe attach to PID is taking longer than expected.\n",
)
on_output(
"stdout",
"On Linux it's possible to customize the value of\n",
)
on_output(
"stdout",
"`PYDEVD_GDB_SCAN_SHARED_LIBRARIES` so that fewer libraries.\n",
)
on_output(
"stdout",
"are scanned when searching for the needed symbols.\n\n",
)
on_output(
"stdout",
"i.e.: set in your environment variables (and restart your editor/client\n",
)
on_output(
"stdout",
"so that it picks up the updated environment variable value):\n\n",
)
on_output(
"stdout",
"PYDEVD_GDB_SCAN_SHARED_LIBRARIES=libdl, libltdl, libc, libfreebl3\n\n",
)
on_output(
"stdout",
"-- the actual library may be different (the gdb output typically\n",
)
on_output(
"stdout",
"-- writes the libraries that will be used, so, it should be possible\n",
)
on_output(
"stdout",
"-- to test other libraries if the above doesn't work).\n\n",
)
if taking_longer_than_expected:
# If taking longer than expected, start showing the actual output to the user.
old = output_collected
output_collected = []
contents = "".join(old)
if contents:
on_output("stderr", contents)
threading.Thread(
target=info_on_timeout, name=f"Injector[PID={pid}] info on timeout", daemon=True
).start()
| 23,348 | Python | 36.720517 | 104 | 0.575338 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/sessions.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import itertools
import os
import signal
import threading
import time
from debugpy import common
from debugpy.common import log, util
from debugpy.adapter import components, launchers, servers
_lock = threading.RLock()
_sessions = set()
_sessions_changed = threading.Event()
class Session(util.Observable):
"""A debug session involving a client, an adapter, a launcher, and a debug server.
The client and the adapter are always present, and at least one of launcher and debug
server is present, depending on the scenario.
"""
_counter = itertools.count(1)
def __init__(self):
from debugpy.adapter import clients
super().__init__()
self.lock = threading.RLock()
self.id = next(self._counter)
self._changed_condition = threading.Condition(self.lock)
self.client = components.missing(self, clients.Client)
"""The client component. Always present."""
self.launcher = components.missing(self, launchers.Launcher)
"""The launcher componet. Always present in "launch" sessions, and never
present in "attach" sessions.
"""
self.server = components.missing(self, servers.Server)
"""The debug server component. Always present, unless this is a "launch"
session with "noDebug".
"""
self.no_debug = None
"""Whether this is a "noDebug" session."""
self.pid = None
"""Process ID of the debuggee process."""
self.debug_options = {}
"""Debug options as specified by "launch" or "attach" request."""
self.is_finalizing = False
"""Whether finalize() has been invoked."""
self.observers += [lambda *_: self.notify_changed()]
def __str__(self):
return f"Session[{self.id}]"
def __enter__(self):
"""Lock the session for exclusive access."""
self.lock.acquire()
return self
def __exit__(self, exc_type, exc_value, exc_tb):
"""Unlock the session."""
self.lock.release()
def register(self):
with _lock:
_sessions.add(self)
_sessions_changed.set()
def notify_changed(self):
with self:
self._changed_condition.notify_all()
# A session is considered ended once all components disconnect, and there
# are no further incoming messages from anything to handle.
components = self.client, self.launcher, self.server
if all(not com or not com.is_connected for com in components):
with _lock:
if self in _sessions:
log.info("{0} has ended.", self)
_sessions.remove(self)
_sessions_changed.set()
def wait_for(self, predicate, timeout=None):
"""Waits until predicate() becomes true.
The predicate is invoked with the session locked. If satisfied, the method
returns immediately. Otherwise, the lock is released (even if it was held
at entry), and the method blocks waiting for some attribute of either self,
self.client, self.server, or self.launcher to change. On every change, session
is re-locked and predicate is re-evaluated, until it is satisfied.
While the session is unlocked, message handlers for components other than
the one that is waiting can run, but message handlers for that one are still
blocked.
If timeout is not None, the method will unblock and return after that many
seconds regardless of whether the predicate was satisfied. The method returns
False if it timed out, and True otherwise.
"""
def wait_for_timeout():
time.sleep(timeout)
wait_for_timeout.timed_out = True
self.notify_changed()
wait_for_timeout.timed_out = False
if timeout is not None:
thread = threading.Thread(
target=wait_for_timeout, name="Session.wait_for() timeout"
)
thread.daemon = True
thread.start()
with self:
while not predicate():
if wait_for_timeout.timed_out:
return False
self._changed_condition.wait()
return True
def finalize(self, why, terminate_debuggee=None):
"""Finalizes the debug session.
If the server is present, sends "disconnect" request with "terminateDebuggee"
set as specified request to it; waits for it to disconnect, allowing any
remaining messages from it to be handled; and closes the server channel.
If the launcher is present, sends "terminate" request to it, regardless of the
value of terminate; waits for it to disconnect, allowing any remaining messages
from it to be handled; and closes the launcher channel.
If the client is present, sends "terminated" event to it.
If terminate_debuggee=None, it is treated as True if the session has a Launcher
component, and False otherwise.
"""
if self.is_finalizing:
return
self.is_finalizing = True
log.info("{0}; finalizing {1}.", why, self)
if terminate_debuggee is None:
terminate_debuggee = bool(self.launcher)
try:
self._finalize(why, terminate_debuggee)
except Exception:
# Finalization should never fail, and if it does, the session is in an
# indeterminate and likely unrecoverable state, so just fail fast.
log.swallow_exception("Fatal error while finalizing {0}", self)
os._exit(1)
log.info("{0} finalized.", self)
def _finalize(self, why, terminate_debuggee):
# If the client started a session, and then disconnected before issuing "launch"
# or "attach", the main thread will be blocked waiting for the first server
# connection to come in - unblock it, so that we can exit.
servers.dont_wait_for_first_connection()
if self.server:
if self.server.is_connected:
if terminate_debuggee and self.launcher and self.launcher.is_connected:
# If we were specifically asked to terminate the debuggee, and we
# can ask the launcher to kill it, do so instead of disconnecting
# from the server to prevent debuggee from running any more code.
self.launcher.terminate_debuggee()
else:
# Otherwise, let the server handle it the best it can.
try:
self.server.channel.request(
"disconnect", {"terminateDebuggee": terminate_debuggee}
)
except Exception:
pass
self.server.detach_from_session()
if self.launcher and self.launcher.is_connected:
# If there was a server, we just disconnected from it above, which should
# cause the debuggee process to exit, unless it is being replaced in situ -
# so let's wait for that first.
if self.server and not self.server.connection.process_replaced:
log.info('{0} waiting for "exited" event...', self)
if not self.wait_for(
lambda: self.launcher.exit_code is not None,
timeout=common.PROCESS_EXIT_TIMEOUT,
):
log.warning('{0} timed out waiting for "exited" event.', self)
# Terminate the debuggee process if it's still alive for any reason -
# whether it's because there was no server to handle graceful shutdown,
# or because the server couldn't handle it for some reason - unless the
# process is being replaced in situ.
if not (self.server and self.server.connection.process_replaced):
self.launcher.terminate_debuggee()
# Wait until the launcher message queue fully drains. There is no timeout
# here, because the final "terminated" event will only come after reading
# user input in wait-on-exit scenarios. In addition, if the process was
# replaced in situ, the launcher might still have more output to capture
# from its replacement.
log.info("{0} waiting for {1} to disconnect...", self, self.launcher)
self.wait_for(lambda: not self.launcher.is_connected)
try:
self.launcher.channel.close()
except Exception:
log.swallow_exception()
if self.client:
if self.client.is_connected:
# Tell the client that debugging is over, but don't close the channel until it
# tells us to, via the "disconnect" request.
try:
self.client.channel.send_event("terminated")
except Exception:
pass
if (
self.client.start_request is not None
and self.client.start_request.command == "launch"
and not (self.server and self.server.connection.process_replaced)
):
servers.stop_serving()
log.info(
'"launch" session ended - killing remaining debuggee processes.'
)
pids_killed = set()
if self.launcher and self.launcher.pid is not None:
# Already killed above.
pids_killed.add(self.launcher.pid)
while True:
conns = [
conn
for conn in servers.connections()
if conn.pid not in pids_killed
]
if not len(conns):
break
for conn in conns:
log.info("Killing {0}", conn)
try:
os.kill(conn.pid, signal.SIGTERM)
except Exception:
log.swallow_exception("Failed to kill {0}", conn)
pids_killed.add(conn.pid)
def get(pid):
with _lock:
return next((session for session in _sessions if session.pid == pid), None)
def wait_until_ended():
"""Blocks until all sessions have ended.
A session ends when all components that it manages disconnect from it.
"""
while True:
with _lock:
if not len(_sessions):
return
_sessions_changed.clear()
_sessions_changed.wait()
| 10,889 | Python | 37.617021 | 94 | 0.584994 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/util.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import inspect
import os
import sys
def evaluate(code, path=__file__, mode="eval"):
# Setting file path here to avoid breaking here if users have set
# "break on exception raised" setting. This code can potentially run
# in user process and is indistinguishable if the path is not set.
# We use the path internally to skip exception inside the debugger.
expr = compile(code, path, "eval")
return eval(expr, {}, sys.modules)
class Observable(object):
"""An object with change notifications."""
observers = () # used when attributes are set before __init__ is invoked
def __init__(self):
self.observers = []
def __setattr__(self, name, value):
try:
return super().__setattr__(name, value)
finally:
for ob in self.observers:
ob(self, name)
class Env(dict):
"""A dict for environment variables."""
@staticmethod
def snapshot():
"""Returns a snapshot of the current environment."""
return Env(os.environ)
def copy(self, updated_from=None):
result = Env(self)
if updated_from is not None:
result.update(updated_from)
return result
def prepend_to(self, key, entry):
"""Prepends a new entry to a PATH-style environment variable, creating
it if it doesn't exist already.
"""
try:
tail = os.path.pathsep + self[key]
except KeyError:
tail = ""
self[key] = entry + tail
def force_str(s, encoding, errors="strict"):
"""Converts s to str, using the provided encoding. If s is already str,
it is returned as is.
"""
return s.decode(encoding, errors) if isinstance(s, bytes) else str(s)
def force_bytes(s, encoding, errors="strict"):
"""Converts s to bytes, using the provided encoding. If s is already bytes,
it is returned as is.
If errors="strict" and s is bytes, its encoding is verified by decoding it;
UnicodeError is raised if it cannot be decoded.
"""
if isinstance(s, str):
return s.encode(encoding, errors)
else:
s = bytes(s)
if errors == "strict":
# Return value ignored - invoked solely for verification.
s.decode(encoding, errors)
return s
def force_ascii(s, errors="strict"):
"""Same as force_bytes(s, "ascii", errors)"""
return force_bytes(s, "ascii", errors)
def force_utf8(s, errors="strict"):
"""Same as force_bytes(s, "utf8", errors)"""
return force_bytes(s, "utf8", errors)
def nameof(obj, quote=False):
"""Returns the most descriptive name of a Python module, class, or function,
as a Unicode string
If quote=True, name is quoted with repr().
Best-effort, but guaranteed to not fail - always returns something.
"""
try:
name = obj.__qualname__
except Exception:
try:
name = obj.__name__
except Exception:
# Fall back to raw repr(), and skip quoting.
try:
name = repr(obj)
except Exception:
return "<unknown>"
else:
quote = False
if quote:
try:
name = repr(name)
except Exception:
pass
return force_str(name, "utf-8", "replace")
def srcnameof(obj):
"""Returns the most descriptive name of a Python module, class, or function,
including source information (filename and linenumber), if available.
Best-effort, but guaranteed to not fail - always returns something.
"""
name = nameof(obj, quote=True)
# Get the source information if possible.
try:
src_file = inspect.getsourcefile(obj)
except Exception:
pass
else:
name += f" (file {src_file!r}"
try:
_, src_lineno = inspect.getsourcelines(obj)
except Exception:
pass
else:
name += f", line {src_lineno}"
name += ")"
return name
def hide_debugpy_internals():
"""Returns True if the caller should hide something from debugpy."""
return "DEBUGPY_TRACE_DEBUGPY" not in os.environ
def hide_thread_from_debugger(thread):
"""Disables tracing for the given thread if DEBUGPY_TRACE_DEBUGPY is not set.
DEBUGPY_TRACE_DEBUGPY is used to debug debugpy with debugpy
"""
if hide_debugpy_internals():
thread.pydev_do_not_trace = True
thread.is_pydev_daemon_thread = True
| 4,646 | Python | 27.163636 | 81 | 0.610848 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/stacks.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""Provides facilities to dump all stacks of all threads in the process.
"""
import os
import sys
import time
import threading
import traceback
from debugpy.common import log
def dump():
"""Dump stacks of all threads in this process, except for the current thread."""
tid = threading.current_thread().ident
pid = os.getpid()
log.info("Dumping stacks for process {0}...", pid)
for t_ident, frame in sys._current_frames().items():
if t_ident == tid:
continue
for t in threading.enumerate():
if t.ident == tid:
t_name = t.name
t_daemon = t.daemon
break
else:
t_name = t_daemon = "<unknown>"
stack = "".join(traceback.format_stack(frame))
log.info(
"Stack of thread {0} (tid={1}, pid={2}, daemon={3}):\n\n{4}",
t_name,
t_ident,
pid,
t_daemon,
stack,
)
log.info("Finished dumping stacks for process {0}.", pid)
def dump_after(secs):
"""Invokes dump() on a background thread after waiting for the specified time."""
def dumper():
time.sleep(secs)
try:
dump()
except:
log.swallow_exception()
thread = threading.Thread(target=dumper)
thread.daemon = True
thread.start()
| 1,526 | Python | 23.238095 | 85 | 0.574705 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/log.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import atexit
import contextlib
import functools
import inspect
import io
import os
import platform
import sys
import threading
import traceback
import debugpy
from debugpy.common import json, timestamp, util
LEVELS = ("debug", "info", "warning", "error")
"""Logging levels, lowest to highest importance.
"""
log_dir = os.getenv("DEBUGPY_LOG_DIR")
"""If not None, debugger logs its activity to a file named debugpy.*-<pid>.log
in the specified directory, where <pid> is the return value of os.getpid().
"""
timestamp_format = "09.3f"
"""Format spec used for timestamps. Can be changed to dial precision up or down.
"""
_lock = threading.RLock()
_tls = threading.local()
_files = {} # filename -> LogFile
_levels = set() # combined for all log files
def _update_levels():
global _levels
_levels = frozenset(level for file in _files.values() for level in file.levels)
class LogFile(object):
def __init__(self, filename, file, levels=LEVELS, close_file=True):
info("Also logging to {0}.", json.repr(filename))
self.filename = filename
self.file = file
self.close_file = close_file
self._levels = frozenset(levels)
with _lock:
_files[self.filename] = self
_update_levels()
info(
"{0} {1}\n{2} {3} ({4}-bit)\ndebugpy {5}",
platform.platform(),
platform.machine(),
platform.python_implementation(),
platform.python_version(),
64 if sys.maxsize > 2 ** 32 else 32,
debugpy.__version__,
_to_files=[self],
)
@property
def levels(self):
return self._levels
@levels.setter
def levels(self, value):
with _lock:
self._levels = frozenset(LEVELS if value is all else value)
_update_levels()
def write(self, level, output):
if level in self.levels:
try:
self.file.write(output)
self.file.flush()
except Exception:
pass
def close(self):
with _lock:
del _files[self.filename]
_update_levels()
info("Not logging to {0} anymore.", json.repr(self.filename))
if self.close_file:
try:
self.file.close()
except Exception:
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
class NoLog(object):
file = filename = None
__bool__ = __nonzero__ = lambda self: False
def close(self):
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
# Used to inject a newline into stderr if logging there, to clean up the output
# when it's intermixed with regular prints from other sources.
def newline(level="info"):
with _lock:
stderr.write(level, "\n")
def write(level, text, _to_files=all):
assert level in LEVELS
t = timestamp.current()
format_string = "{0}+{1:" + timestamp_format + "}: "
prefix = format_string.format(level[0].upper(), t)
text = getattr(_tls, "prefix", "") + text
indent = "\n" + (" " * len(prefix))
output = indent.join(text.split("\n"))
output = prefix + output + "\n\n"
with _lock:
if _to_files is all:
_to_files = _files.values()
for file in _to_files:
file.write(level, output)
return text
def write_format(level, format_string, *args, **kwargs):
# Don't spend cycles doing expensive formatting if we don't have to. Errors are
# always formatted, so that error() can return the text even if it's not logged.
if level != "error" and level not in _levels:
return
try:
text = format_string.format(*args, **kwargs)
except Exception:
reraise_exception()
return write(level, text, kwargs.pop("_to_files", all))
debug = functools.partial(write_format, "debug")
info = functools.partial(write_format, "info")
warning = functools.partial(write_format, "warning")
def error(*args, **kwargs):
"""Logs an error.
Returns the output wrapped in AssertionError. Thus, the following::
raise log.error(s, ...)
has the same effect as::
log.error(...)
assert False, (s.format(...))
"""
return AssertionError(write_format("error", *args, **kwargs))
def _exception(format_string="", *args, **kwargs):
level = kwargs.pop("level", "error")
exc_info = kwargs.pop("exc_info", sys.exc_info())
if format_string:
format_string += "\n\n"
format_string += "{exception}\nStack where logged:\n{stack}"
exception = "".join(traceback.format_exception(*exc_info))
f = inspect.currentframe()
f = f.f_back if f else f # don't log this frame
try:
stack = "".join(traceback.format_stack(f))
finally:
del f # avoid cycles
write_format(
level, format_string, *args, exception=exception, stack=stack, **kwargs
)
def swallow_exception(format_string="", *args, **kwargs):
"""Logs an exception with full traceback.
If format_string is specified, it is formatted with format(*args, **kwargs), and
prepended to the exception traceback on a separate line.
If exc_info is specified, the exception it describes will be logged. Otherwise,
sys.exc_info() - i.e. the exception being handled currently - will be logged.
If level is specified, the exception will be logged as a message of that level.
The default is "error".
"""
_exception(format_string, *args, **kwargs)
def reraise_exception(format_string="", *args, **kwargs):
"""Like swallow_exception(), but re-raises the current exception after logging it."""
assert "exc_info" not in kwargs
_exception(format_string, *args, **kwargs)
raise
def to_file(filename=None, prefix=None, levels=LEVELS):
"""Starts logging all messages at the specified levels to the designated file.
Either filename or prefix must be specified, but not both.
If filename is specified, it designates the log file directly.
If prefix is specified, the log file is automatically created in options.log_dir,
with filename computed as prefix + os.getpid(). If log_dir is None, no log file
is created, and the function returns immediately.
If the file with the specified or computed name is already being used as a log
file, it is not overwritten, but its levels are updated as specified.
The function returns an object with a close() method. When the object is closed,
logs are not written into that file anymore. Alternatively, the returned object
can be used in a with-statement:
with log.to_file("some.log"):
# now also logging to some.log
# not logging to some.log anymore
"""
assert (filename is not None) ^ (prefix is not None)
if filename is None:
if log_dir is None:
return NoLog()
try:
os.makedirs(log_dir)
except OSError:
pass
filename = f"{log_dir}/{prefix}-{os.getpid()}.log"
file = _files.get(filename)
if file is None:
file = LogFile(filename, io.open(filename, "w", encoding="utf-8"), levels)
else:
file.levels = levels
return file
@contextlib.contextmanager
def prefixed(format_string, *args, **kwargs):
"""Adds a prefix to all messages logged from the current thread for the duration
of the context manager.
"""
prefix = format_string.format(*args, **kwargs)
old_prefix = getattr(_tls, "prefix", "")
_tls.prefix = prefix + old_prefix
try:
yield
finally:
_tls.prefix = old_prefix
def describe_environment(header):
import sysconfig
import site # noqa
result = [header, "\n\n"]
def report(s, *args, **kwargs):
result.append(s.format(*args, **kwargs))
def report_paths(get_paths, label=None):
prefix = f" {label or get_paths}: "
expr = None
if not callable(get_paths):
expr = get_paths
get_paths = lambda: util.evaluate(expr)
try:
paths = get_paths()
except AttributeError:
report("{0}<missing>\n", prefix)
return
except Exception:
swallow_exception(
"Error evaluating {0}",
repr(expr) if expr else util.srcnameof(get_paths),
)
return
if not isinstance(paths, (list, tuple)):
paths = [paths]
for p in sorted(paths):
report("{0}{1}", prefix, p)
if p is not None:
rp = os.path.realpath(p)
if p != rp:
report("({0})", rp)
report("\n")
prefix = " " * len(prefix)
report("System paths:\n")
report_paths("sys.prefix")
report_paths("sys.base_prefix")
report_paths("sys.real_prefix")
report_paths("site.getsitepackages()")
report_paths("site.getusersitepackages()")
site_packages = [
p
for p in sys.path
if os.path.exists(p) and os.path.basename(p) == "site-packages"
]
report_paths(lambda: site_packages, "sys.path (site-packages)")
for name in sysconfig.get_path_names():
expr = "sysconfig.get_path({0!r})".format(name)
report_paths(expr)
report_paths("os.__file__")
report_paths("threading.__file__")
report_paths("debugpy.__file__")
result = "".join(result).rstrip("\n")
info("{0}", result)
stderr = LogFile(
"<stderr>",
sys.stderr,
levels=os.getenv("DEBUGPY_LOG_STDERR", "warning error").split(),
close_file=False,
)
@atexit.register
def _close_files():
for file in tuple(_files.values()):
file.close()
# The following are helper shortcuts for printf debugging. They must never be used
# in production code.
def _repr(value): # pragma: no cover
warning("$REPR {0!r}", value)
def _vars(*names): # pragma: no cover
locals = inspect.currentframe().f_back.f_locals
if names:
locals = {name: locals[name] for name in names if name in locals}
warning("$VARS {0!r}", locals)
def _stack(): # pragma: no cover
stack = "\n".join(traceback.format_stack())
warning("$STACK:\n\n{0}", stack)
def _threads(): # pragma: no cover
output = "\n".join([str(t) for t in threading.enumerate()])
warning("$THREADS:\n\n{0}", output)
| 10,723 | Python | 26.782383 | 89 | 0.604775 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/timestamp.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""Provides monotonic timestamps with a resetable zero.
"""
import time
__all__ = ["current", "reset"]
def current():
return time.monotonic() - timestamp_zero
def reset():
global timestamp_zero
timestamp_zero = time.monotonic()
reset()
| 410 | Python | 16.869564 | 65 | 0.707317 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/__init__.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import annotations
import os
import typing
if typing.TYPE_CHECKING:
__all__: list[str]
__all__ = []
# The lower time bound for assuming that the process hasn't spawned successfully.
PROCESS_SPAWN_TIMEOUT = float(os.getenv("DEBUGPY_PROCESS_SPAWN_TIMEOUT", 15))
# The lower time bound for assuming that the process hasn't exited gracefully.
PROCESS_EXIT_TIMEOUT = float(os.getenv("DEBUGPY_PROCESS_EXIT_TIMEOUT", 5))
| 592 | Python | 30.210525 | 81 | 0.753378 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/sockets.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import socket
import sys
import threading
from debugpy.common import log
from debugpy.common.util import hide_thread_from_debugger
def create_server(host, port=0, backlog=socket.SOMAXCONN, timeout=None):
"""Return a local server socket listening on the given port."""
assert backlog > 0
if host is None:
host = "127.0.0.1"
if port is None:
port = 0
try:
server = _new_sock()
if port != 0:
# If binding to a specific port, make sure that the user doesn't have
# to wait until the OS times out the socket to be able to use that port
# again.if the server or the adapter crash or are force-killed.
if sys.platform == "win32":
server.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
else:
try:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except (AttributeError, OSError):
pass # Not available everywhere
server.bind((host, port))
if timeout is not None:
server.settimeout(timeout)
server.listen(backlog)
except Exception:
server.close()
raise
return server
def create_client():
"""Return a client socket that may be connected to a remote address."""
return _new_sock()
def _new_sock():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
# Set TCP keepalive on an open socket.
# It activates after 1 second (TCP_KEEPIDLE,) of idleness,
# then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL),
# and closes the connection after 5 failed ping (TCP_KEEPCNT), or 15 seconds
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
except (AttributeError, OSError):
pass # May not be available everywhere.
return sock
def shut_down(sock, how=socket.SHUT_RDWR):
"""Shut down the given socket."""
sock.shutdown(how)
def close_socket(sock):
"""Shutdown and close the socket."""
try:
shut_down(sock)
except Exception:
pass
sock.close()
def serve(name, handler, host, port=0, backlog=socket.SOMAXCONN, timeout=None):
"""Accepts TCP connections on the specified host and port, and invokes the
provided handler function for every new connection.
Returns the created server socket.
"""
assert backlog > 0
try:
listener = create_server(host, port, backlog, timeout)
except Exception:
log.reraise_exception(
"Error listening for incoming {0} connections on {1}:{2}:", name, host, port
)
host, port = listener.getsockname()
log.info("Listening for incoming {0} connections on {1}:{2}...", name, host, port)
def accept_worker():
while True:
try:
sock, (other_host, other_port) = listener.accept()
except (OSError, socket.error):
# Listener socket has been closed.
break
log.info(
"Accepted incoming {0} connection from {1}:{2}.",
name,
other_host,
other_port,
)
handler(sock)
thread = threading.Thread(target=accept_worker)
thread.daemon = True
hide_thread_from_debugger(thread)
thread.start()
return listener
| 4,064 | Python | 30.269231 | 88 | 0.621801 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/json.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""Improved JSON serialization.
"""
import builtins
import json
import numbers
import operator
JsonDecoder = json.JSONDecoder
class JsonEncoder(json.JSONEncoder):
"""Customizable JSON encoder.
If the object implements __getstate__, then that method is invoked, and its
result is serialized instead of the object itself.
"""
def default(self, value):
try:
get_state = value.__getstate__
except AttributeError:
pass
else:
return get_state()
return super().default(value)
class JsonObject(object):
"""A wrapped Python object that formats itself as JSON when asked for a string
representation via str() or format().
"""
json_encoder_factory = JsonEncoder
"""Used by __format__ when format_spec is not empty."""
json_encoder = json_encoder_factory(indent=4)
"""The default encoder used by __format__ when format_spec is empty."""
def __init__(self, value):
assert not isinstance(value, JsonObject)
self.value = value
def __getstate__(self):
raise NotImplementedError
def __repr__(self):
return builtins.repr(self.value)
def __str__(self):
return format(self)
def __format__(self, format_spec):
"""If format_spec is empty, uses self.json_encoder to serialize self.value
as a string. Otherwise, format_spec is treated as an argument list to be
passed to self.json_encoder_factory - which defaults to JSONEncoder - and
then the resulting formatter is used to serialize self.value as a string.
Example::
format("{0} {0:indent=4,sort_keys=True}", json.repr(x))
"""
if format_spec:
# At this point, format_spec is a string that looks something like
# "indent=4,sort_keys=True". What we want is to build a function call
# from that which looks like:
#
# json_encoder_factory(indent=4,sort_keys=True)
#
# which we can then eval() to create our encoder instance.
make_encoder = "json_encoder_factory(" + format_spec + ")"
encoder = eval(
make_encoder, {"json_encoder_factory": self.json_encoder_factory}
)
else:
encoder = self.json_encoder
return encoder.encode(self.value)
# JSON property validators, for use with MessageDict.
#
# A validator is invoked with the actual value of the JSON property passed to it as
# the sole argument; or if the property is missing in JSON, then () is passed. Note
# that None represents an actual null in JSON, while () is a missing value.
#
# The validator must either raise TypeError or ValueError describing why the property
# value is invalid, or else return the value of the property, possibly after performing
# some substitutions - e.g. replacing () with some default value.
def _converter(value, classinfo):
"""Convert value (str) to number, otherwise return None if is not possible"""
for one_info in classinfo:
if issubclass(one_info, numbers.Number):
try:
return one_info(value)
except ValueError:
pass
def of_type(*classinfo, **kwargs):
"""Returns a validator for a JSON property that requires it to have a value of
the specified type. If optional=True, () is also allowed.
The meaning of classinfo is the same as for isinstance().
"""
assert len(classinfo)
optional = kwargs.pop("optional", False)
assert not len(kwargs)
def validate(value):
if (optional and value == ()) or isinstance(value, classinfo):
return value
else:
converted_value = _converter(value, classinfo)
if converted_value:
return converted_value
if not optional and value == ():
raise ValueError("must be specified")
raise TypeError("must be " + " or ".join(t.__name__ for t in classinfo))
return validate
def default(default):
"""Returns a validator for a JSON property with a default value.
The validator will only allow property values that have the same type as the
specified default value.
"""
def validate(value):
if value == ():
return default
elif isinstance(value, type(default)):
return value
else:
raise TypeError("must be {0}".format(type(default).__name__))
return validate
def enum(*values, **kwargs):
"""Returns a validator for a JSON enum.
The validator will only allow the property to have one of the specified values.
If optional=True, and the property is missing, the first value specified is used
as the default.
"""
assert len(values)
optional = kwargs.pop("optional", False)
assert not len(kwargs)
def validate(value):
if optional and value == ():
return values[0]
elif value in values:
return value
else:
raise ValueError("must be one of: {0!r}".format(list(values)))
return validate
def array(validate_item=False, vectorize=False, size=None):
"""Returns a validator for a JSON array.
If the property is missing, it is treated as if it were []. Otherwise, it must
be a list.
If validate_item=False, it's treated as if it were (lambda x: x) - i.e. any item
is considered valid, and is unchanged. If validate_item is a type or a tuple,
it's treated as if it were json.of_type(validate).
Every item in the list is replaced with validate_item(item) in-place, propagating
any exceptions raised by the latter. If validate_item is a type or a tuple, it is
treated as if it were json.of_type(validate_item).
If vectorize=True, and the value is neither a list nor a dict, it is treated as
if it were a single-element list containing that single value - e.g. "foo" is
then the same as ["foo"]; but {} is an error, and not [{}].
If size is not None, it can be an int, a tuple of one int, a tuple of two ints,
or a set. If it's an int, the array must have exactly that many elements. If it's
a tuple of one int, it's the minimum length. If it's a tuple of two ints, they
are the minimum and the maximum lengths. If it's a set, it's the set of sizes that
are valid - e.g. for {2, 4}, the array can be either 2 or 4 elements long.
"""
if not validate_item:
validate_item = lambda x: x
elif isinstance(validate_item, type) or isinstance(validate_item, tuple):
validate_item = of_type(validate_item)
if size is None:
validate_size = lambda _: True
elif isinstance(size, set):
size = {operator.index(n) for n in size}
validate_size = lambda value: (
len(value) in size
or "must have {0} elements".format(
" or ".join(str(n) for n in sorted(size))
)
)
elif isinstance(size, tuple):
assert 1 <= len(size) <= 2
size = tuple(operator.index(n) for n in size)
min_len, max_len = (size + (None,))[0:2]
validate_size = lambda value: (
"must have at least {0} elements".format(min_len)
if len(value) < min_len
else "must have at most {0} elements".format(max_len)
if max_len is not None and len(value) < max_len
else True
)
else:
size = operator.index(size)
validate_size = lambda value: (
len(value) == size or "must have {0} elements".format(size)
)
def validate(value):
if value == ():
value = []
elif vectorize and not isinstance(value, (list, dict)):
value = [value]
of_type(list)(value)
size_err = validate_size(value) # True if valid, str if error
if size_err is not True:
raise ValueError(size_err)
for i, item in enumerate(value):
try:
value[i] = validate_item(item)
except (TypeError, ValueError) as exc:
raise type(exc)(f"[{repr(i)}] {exc}")
return value
return validate
def object(validate_value=False):
"""Returns a validator for a JSON object.
If the property is missing, it is treated as if it were {}. Otherwise, it must
be a dict.
If validate_value=False, it's treated as if it were (lambda x: x) - i.e. any
value is considered valid, and is unchanged. If validate_value is a type or a
tuple, it's treated as if it were json.of_type(validate_value).
Every value in the dict is replaced with validate_value(value) in-place, propagating
any exceptions raised by the latter. If validate_value is a type or a tuple, it is
treated as if it were json.of_type(validate_value). Keys are not affected.
"""
if isinstance(validate_value, type) or isinstance(validate_value, tuple):
validate_value = of_type(validate_value)
def validate(value):
if value == ():
return {}
of_type(dict)(value)
if validate_value:
for k, v in value.items():
try:
value[k] = validate_value(v)
except (TypeError, ValueError) as exc:
raise type(exc)(f"[{repr(k)}] {exc}")
return value
return validate
def repr(value):
return JsonObject(value)
dumps = json.dumps
loads = json.loads
| 9,674 | Python | 32.020478 | 88 | 0.620219 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/messaging.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""An implementation of the session and presentation layers as used in the Debug
Adapter Protocol (DAP): channels and their lifetime, JSON messages, requests,
responses, and events.
https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol
"""
from __future__ import annotations
import collections
import contextlib
import functools
import itertools
import os
import socket
import sys
import threading
from debugpy.common import json, log, util
from debugpy.common.util import hide_thread_from_debugger
class JsonIOError(IOError):
"""Indicates that a read or write operation on JsonIOStream has failed."""
def __init__(self, *args, **kwargs):
stream = kwargs.pop("stream")
cause = kwargs.pop("cause", None)
if not len(args) and cause is not None:
args = [str(cause)]
super().__init__(*args, **kwargs)
self.stream = stream
"""The stream that couldn't be read or written.
Set by JsonIOStream.read_json() and JsonIOStream.write_json().
JsonMessageChannel relies on this value to decide whether a NoMoreMessages
instance that bubbles up to the message loop is related to that loop.
"""
self.cause = cause
"""The underlying exception, if any."""
class NoMoreMessages(JsonIOError, EOFError):
"""Indicates that there are no more messages that can be read from or written
to a stream.
"""
def __init__(self, *args, **kwargs):
args = args if len(args) else ["No more messages"]
super().__init__(*args, **kwargs)
class JsonIOStream(object):
"""Implements a JSON value stream over two byte streams (input and output).
Each value is encoded as a DAP packet, with metadata headers and a JSON payload.
"""
MAX_BODY_SIZE = 0xFFFFFF
json_decoder_factory = json.JsonDecoder
"""Used by read_json() when decoder is None."""
json_encoder_factory = json.JsonEncoder
"""Used by write_json() when encoder is None."""
@classmethod
def from_stdio(cls, name="stdio"):
"""Creates a new instance that receives messages from sys.stdin, and sends
them to sys.stdout.
"""
return cls(sys.stdin.buffer, sys.stdout.buffer, name)
@classmethod
def from_process(cls, process, name="stdio"):
"""Creates a new instance that receives messages from process.stdin, and sends
them to process.stdout.
"""
return cls(process.stdout, process.stdin, name)
@classmethod
def from_socket(cls, sock, name=None):
"""Creates a new instance that sends and receives messages over a socket."""
sock.settimeout(None) # make socket blocking
if name is None:
name = repr(sock)
# TODO: investigate switching to buffered sockets; readline() on unbuffered
# sockets is very slow! Although the implementation of readline() itself is
# native code, it calls read(1) in a loop - and that then ultimately calls
# SocketIO.readinto(), which is implemented in Python.
socket_io = sock.makefile("rwb", 0)
# SocketIO.close() doesn't close the underlying socket.
def cleanup():
try:
sock.shutdown(socket.SHUT_RDWR)
except Exception:
pass
sock.close()
return cls(socket_io, socket_io, name, cleanup)
def __init__(self, reader, writer, name=None, cleanup=lambda: None):
"""Creates a new JsonIOStream.
reader must be a BytesIO-like object, from which incoming messages will be
read by read_json().
writer must be a BytesIO-like object, into which outgoing messages will be
written by write_json().
cleanup must be a callable; it will be invoked without arguments when the
stream is closed.
reader.readline() must treat "\n" as the line terminator, and must leave "\r"
as is - it must not replace "\r\n" with "\n" automatically, as TextIO does.
"""
if name is None:
name = f"reader={reader!r}, writer={writer!r}"
self.name = name
self._reader = reader
self._writer = writer
self._cleanup = cleanup
self._closed = False
def close(self):
"""Closes the stream, the reader, and the writer."""
if self._closed:
return
self._closed = True
log.debug("Closing {0} message stream", self.name)
try:
try:
# Close the writer first, so that the other end of the connection has
# its message loop waiting on read() unblocked. If there is an exception
# while closing the writer, we still want to try to close the reader -
# only one exception can bubble up, so if both fail, it'll be the one
# from reader.
try:
self._writer.close()
finally:
if self._reader is not self._writer:
self._reader.close()
finally:
self._cleanup()
except Exception:
log.reraise_exception("Error while closing {0} message stream", self.name)
def _log_message(self, dir, data, logger=log.debug):
return logger("{0} {1} {2}", self.name, dir, data)
def _read_line(self, reader):
line = b""
while True:
try:
line += reader.readline()
except Exception as exc:
raise NoMoreMessages(str(exc), stream=self)
if not line:
raise NoMoreMessages(stream=self)
if line.endswith(b"\r\n"):
line = line[0:-2]
return line
def read_json(self, decoder=None):
"""Read a single JSON value from reader.
Returns JSON value as parsed by decoder.decode(), or raises NoMoreMessages
if there are no more values to be read.
"""
decoder = decoder if decoder is not None else self.json_decoder_factory()
reader = self._reader
read_line = functools.partial(self._read_line, reader)
# If any error occurs while reading and parsing the message, log the original
# raw message data as is, so that it's possible to diagnose missing or invalid
# headers, encoding issues, JSON syntax errors etc.
def log_message_and_reraise_exception(format_string="", *args, **kwargs):
if format_string:
format_string += "\n\n"
format_string += "{name} -->\n{raw_lines}"
raw_lines = b"".join(raw_chunks).split(b"\n")
raw_lines = "\n".join(repr(line) for line in raw_lines)
log.reraise_exception(
format_string, *args, name=self.name, raw_lines=raw_lines, **kwargs
)
raw_chunks = []
headers = {}
while True:
try:
line = read_line()
except Exception:
# Only log it if we have already read some headers, and are looking
# for a blank line terminating them. If this is the very first read,
# there's no message data to log in any case, and the caller might
# be anticipating the error - e.g. NoMoreMessages on disconnect.
if headers:
log_message_and_reraise_exception(
"Error while reading message headers:"
)
else:
raise
raw_chunks += [line, b"\n"]
if line == b"":
break
key, _, value = line.partition(b":")
headers[key] = value
try:
length = int(headers[b"Content-Length"])
if not (0 <= length <= self.MAX_BODY_SIZE):
raise ValueError
except (KeyError, ValueError):
try:
raise IOError("Content-Length is missing or invalid:")
except Exception:
log_message_and_reraise_exception()
body_start = len(raw_chunks)
body_remaining = length
while body_remaining > 0:
try:
chunk = reader.read(body_remaining)
if not chunk:
raise EOFError
except Exception as exc:
# Not logged due to https://github.com/microsoft/ptvsd/issues/1699
raise NoMoreMessages(str(exc), stream=self)
raw_chunks.append(chunk)
body_remaining -= len(chunk)
assert body_remaining == 0
body = b"".join(raw_chunks[body_start:])
try:
body = body.decode("utf-8")
except Exception:
log_message_and_reraise_exception()
try:
body = decoder.decode(body)
except Exception:
log_message_and_reraise_exception()
# If parsed successfully, log as JSON for readability.
self._log_message("-->", body)
return body
def write_json(self, value, encoder=None):
"""Write a single JSON value into writer.
Value is written as encoded by encoder.encode().
"""
if self._closed:
# Don't log this - it's a common pattern to write to a stream while
# anticipating EOFError from it in case it got closed concurrently.
raise NoMoreMessages(stream=self)
encoder = encoder if encoder is not None else self.json_encoder_factory()
writer = self._writer
# Format the value as a message, and try to log any failures using as much
# information as we already have at the point of the failure. For example,
# if it fails after it is serialized to JSON, log that JSON.
try:
body = encoder.encode(value)
except Exception:
self._log_message("<--", repr(value), logger=log.reraise_exception)
body = body.encode("utf-8")
header = f"Content-Length: {len(body)}\r\n\r\n".encode("ascii")
data = header + body
data_written = 0
try:
while data_written < len(data):
written = writer.write(data[data_written:])
data_written += written
writer.flush()
except Exception as exc:
self._log_message("<--", value, logger=log.swallow_exception)
raise JsonIOError(stream=self, cause=exc)
self._log_message("<--", value)
def __repr__(self):
return f"{type(self).__name__}({self.name!r})"
class MessageDict(collections.OrderedDict):
"""A specialized dict that is used for JSON message payloads - Request.arguments,
Response.body, and Event.body.
For all members that normally throw KeyError when a requested key is missing, this
dict raises InvalidMessageError instead. Thus, a message handler can skip checks
for missing properties, and just work directly with the payload on the assumption
that it is valid according to the protocol specification; if anything is missing,
it will be reported automatically in the proper manner.
If the value for the requested key is itself a dict, it is returned as is, and not
automatically converted to MessageDict. Thus, to enable convenient chaining - e.g.
d["a"]["b"]["c"] - the dict must consistently use MessageDict instances rather than
vanilla dicts for all its values, recursively. This is guaranteed for the payload
of all freshly received messages (unless and until it is mutated), but there is no
such guarantee for outgoing messages.
"""
def __init__(self, message, items=None):
assert message is None or isinstance(message, Message)
if items is None:
super().__init__()
else:
super().__init__(items)
self.message = message
"""The Message object that owns this dict.
For any instance exposed via a Message object corresponding to some incoming
message, it is guaranteed to reference that Message object. There is no similar
guarantee for outgoing messages.
"""
def __repr__(self):
try:
return format(json.repr(self))
except Exception:
return super().__repr__()
def __call__(self, key, validate, optional=False):
"""Like get(), but with validation.
The item is first retrieved as if with self.get(key, default=()) - the default
value is () rather than None, so that JSON nulls are distinguishable from
missing properties.
If optional=True, and the value is (), it's returned as is. Otherwise, the
item is validated by invoking validate(item) on it.
If validate=False, it's treated as if it were (lambda x: x) - i.e. any value
is considered valid, and is returned unchanged. If validate is a type or a
tuple, it's treated as json.of_type(validate). Otherwise, if validate is not
callable(), it's treated as json.default(validate).
If validate() returns successfully, the item is substituted with the value
it returns - thus, the validator can e.g. replace () with a suitable default
value for the property.
If validate() raises TypeError or ValueError, raises InvalidMessageError with
the same text that applies_to(self.messages).
See debugpy.common.json for reusable validators.
"""
if not validate:
validate = lambda x: x
elif isinstance(validate, type) or isinstance(validate, tuple):
validate = json.of_type(validate, optional=optional)
elif not callable(validate):
validate = json.default(validate)
value = self.get(key, ())
try:
value = validate(value)
except (TypeError, ValueError) as exc:
message = Message if self.message is None else self.message
err = str(exc)
if not err.startswith("["):
err = " " + err
raise message.isnt_valid("{0}{1}", json.repr(key), err)
return value
def _invalid_if_no_key(func):
def wrap(self, key, *args, **kwargs):
try:
return func(self, key, *args, **kwargs)
except KeyError:
message = Message if self.message is None else self.message
raise message.isnt_valid("missing property {0!r}", key)
return wrap
__getitem__ = _invalid_if_no_key(collections.OrderedDict.__getitem__)
__delitem__ = _invalid_if_no_key(collections.OrderedDict.__delitem__)
pop = _invalid_if_no_key(collections.OrderedDict.pop)
del _invalid_if_no_key
def _payload(value):
"""JSON validator for message payload.
If that value is missing or null, it is treated as if it were {}.
"""
if value is not None and value != ():
if isinstance(value, dict): # can be int, str, list...
assert isinstance(value, MessageDict)
return value
# Missing payload. Construct a dummy MessageDict, and make it look like it was
# deserialized. See JsonMessageChannel._parse_incoming_message for why it needs
# to have associate_with().
def associate_with(message):
value.message = message
value = MessageDict(None)
value.associate_with = associate_with
return value
class Message(object):
"""Represents a fully parsed incoming or outgoing message.
https://microsoft.github.io/debug-adapter-protocol/specification#protocolmessage
"""
def __init__(self, channel, seq, json=None):
self.channel = channel
self.seq = seq
"""Sequence number of the message in its channel.
This can be None for synthesized Responses.
"""
self.json = json
"""For incoming messages, the MessageDict containing raw JSON from which
this message was originally parsed.
"""
def __str__(self):
return json.repr(self.json) if self.json is not None else repr(self)
def describe(self):
"""A brief description of the message that is enough to identify it.
Examples:
'#1 request "launch" from IDE'
'#2 response to #1 request "launch" from IDE'.
"""
raise NotImplementedError
@property
def payload(self) -> MessageDict:
"""Payload of the message - self.body or self.arguments, depending on the
message type.
"""
raise NotImplementedError
def __call__(self, *args, **kwargs):
"""Same as self.payload(...)."""
return self.payload(*args, **kwargs)
def __contains__(self, key):
"""Same as (key in self.payload)."""
return key in self.payload
def is_event(self, *event):
"""Returns True if this message is an Event of one of the specified types."""
if not isinstance(self, Event):
return False
return event == () or self.event in event
def is_request(self, *command):
"""Returns True if this message is a Request of one of the specified types."""
if not isinstance(self, Request):
return False
return command == () or self.command in command
def is_response(self, *command):
"""Returns True if this message is a Response to a request of one of the
specified types.
"""
if not isinstance(self, Response):
return False
return command == () or self.request.command in command
def error(self, exc_type, format_string, *args, **kwargs):
"""Returns a new exception of the specified type from the point at which it is
invoked, with the specified formatted message as the reason.
The resulting exception will have its cause set to the Message object on which
error() was called. Additionally, if that message is a Request, a failure
response is immediately sent.
"""
assert issubclass(exc_type, MessageHandlingError)
silent = kwargs.pop("silent", False)
reason = format_string.format(*args, **kwargs)
exc = exc_type(reason, self, silent) # will log it
if isinstance(self, Request):
self.respond(exc)
return exc
def isnt_valid(self, *args, **kwargs):
"""Same as self.error(InvalidMessageError, ...)."""
return self.error(InvalidMessageError, *args, **kwargs)
def cant_handle(self, *args, **kwargs):
"""Same as self.error(MessageHandlingError, ...)."""
return self.error(MessageHandlingError, *args, **kwargs)
class Event(Message):
"""Represents an incoming event.
https://microsoft.github.io/debug-adapter-protocol/specification#event
It is guaranteed that body is a MessageDict associated with this Event, and so
are all the nested dicts in it. If "body" was missing or null in JSON, body is
an empty dict.
To handle the event, JsonMessageChannel tries to find a handler for this event in
JsonMessageChannel.handlers. Given event="X", if handlers.X_event exists, then it
is the specific handler for this event. Otherwise, handlers.event must exist, and
it is the generic handler for this event. A missing handler is a fatal error.
No further incoming messages are processed until the handler returns, except for
responses to requests that have wait_for_response() invoked on them.
To report failure to handle the event, the handler must raise an instance of
MessageHandlingError that applies_to() the Event object it was handling. Any such
failure is logged, after which the message loop moves on to the next message.
Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
the appropriate exception type that applies_to() the Event object.
"""
def __init__(self, channel, seq, event, body, json=None):
super().__init__(channel, seq, json)
self.event = event
if isinstance(body, MessageDict) and hasattr(body, "associate_with"):
body.associate_with(self)
self.body = body
def describe(self):
return f"#{self.seq} event {json.repr(self.event)} from {self.channel}"
@property
def payload(self):
return self.body
@staticmethod
def _parse(channel, message_dict):
seq = message_dict("seq", int)
event = message_dict("event", str)
body = message_dict("body", _payload)
message = Event(channel, seq, event, body, json=message_dict)
channel._enqueue_handlers(message, message._handle)
def _handle(self):
channel = self.channel
handler = channel._get_handler_for("event", self.event)
try:
try:
result = handler(self)
assert (
result is None
), f"Handler {util.srcnameof(handler)} tried to respond to {self.describe()}."
except MessageHandlingError as exc:
if not exc.applies_to(self):
raise
log.error(
"Handler {0}\ncouldn't handle {1}:\n{2}",
util.srcnameof(handler),
self.describe(),
str(exc),
)
except Exception:
log.reraise_exception(
"Handler {0}\ncouldn't handle {1}:",
util.srcnameof(handler),
self.describe(),
)
NO_RESPONSE = object()
"""Can be returned from a request handler in lieu of the response body, to indicate
that no response is to be sent.
Request.respond() must be invoked explicitly at some later point to provide a response.
"""
class Request(Message):
"""Represents an incoming or an outgoing request.
Incoming requests are represented directly by instances of this class.
Outgoing requests are represented by instances of OutgoingRequest, which provides
additional functionality to handle responses.
For incoming requests, it is guaranteed that arguments is a MessageDict associated
with this Request, and so are all the nested dicts in it. If "arguments" was missing
or null in JSON, arguments is an empty dict.
To handle the request, JsonMessageChannel tries to find a handler for this request
in JsonMessageChannel.handlers. Given command="X", if handlers.X_request exists,
then it is the specific handler for this request. Otherwise, handlers.request must
exist, and it is the generic handler for this request. A missing handler is a fatal
error.
The handler is then invoked with the Request object as its sole argument.
If the handler itself invokes respond() on the Request at any point, then it must
not return any value.
Otherwise, if the handler returns NO_RESPONSE, no response to the request is sent.
It must be sent manually at some later point via respond().
Otherwise, a response to the request is sent with the returned value as the body.
To fail the request, the handler can return an instance of MessageHandlingError,
or respond() with one, or raise one such that it applies_to() the Request object
being handled.
Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
the appropriate exception type that applies_to() the Request object.
"""
def __init__(self, channel, seq, command, arguments, json=None):
super().__init__(channel, seq, json)
self.command = command
if isinstance(arguments, MessageDict) and hasattr(arguments, "associate_with"):
arguments.associate_with(self)
self.arguments = arguments
self.response = None
"""Response to this request.
For incoming requests, it is set as soon as the request handler returns.
For outgoing requests, it is set as soon as the response is received, and
before self._handle_response is invoked.
"""
def describe(self):
return f"#{self.seq} request {json.repr(self.command)} from {self.channel}"
@property
def payload(self):
return self.arguments
def respond(self, body):
assert self.response is None
d = {"type": "response", "request_seq": self.seq, "command": self.command}
if isinstance(body, Exception):
d["success"] = False
d["message"] = str(body)
else:
d["success"] = True
if body is not None and body != {}:
d["body"] = body
with self.channel._send_message(d) as seq:
pass
self.response = Response(self.channel, seq, self, body)
@staticmethod
def _parse(channel, message_dict):
seq = message_dict("seq", int)
command = message_dict("command", str)
arguments = message_dict("arguments", _payload)
message = Request(channel, seq, command, arguments, json=message_dict)
channel._enqueue_handlers(message, message._handle)
def _handle(self):
channel = self.channel
handler = channel._get_handler_for("request", self.command)
try:
try:
result = handler(self)
except MessageHandlingError as exc:
if not exc.applies_to(self):
raise
result = exc
log.error(
"Handler {0}\ncouldn't handle {1}:\n{2}",
util.srcnameof(handler),
self.describe(),
str(exc),
)
if result is NO_RESPONSE:
assert self.response is None, (
"Handler {0} for {1} must not return NO_RESPONSE if it has already "
"invoked request.respond().".format(
util.srcnameof(handler), self.describe()
)
)
elif self.response is not None:
assert result is None or result is self.response.body, (
"Handler {0} for {1} must not return a response body if it has "
"already invoked request.respond().".format(
util.srcnameof(handler), self.describe()
)
)
else:
assert result is not None, (
"Handler {0} for {1} must either call request.respond() before it "
"returns, or return the response body, or return NO_RESPONSE.".format(
util.srcnameof(handler), self.describe()
)
)
try:
self.respond(result)
except NoMoreMessages:
log.warning(
"Channel was closed before the response from handler {0} to {1} could be sent",
util.srcnameof(handler),
self.describe(),
)
except Exception:
log.reraise_exception(
"Handler {0}\ncouldn't handle {1}:",
util.srcnameof(handler),
self.describe(),
)
class OutgoingRequest(Request):
"""Represents an outgoing request, for which it is possible to wait for a
response to be received, and register a response handler.
"""
_parse = _handle = None
def __init__(self, channel, seq, command, arguments):
super().__init__(channel, seq, command, arguments)
self._response_handlers = []
def describe(self):
return f"{self.seq} request {json.repr(self.command)} to {self.channel}"
def wait_for_response(self, raise_if_failed=True):
"""Waits until a response is received for this request, records the Response
object for it in self.response, and returns response.body.
If no response was received from the other party before the channel closed,
self.response is a synthesized Response with body=NoMoreMessages().
If raise_if_failed=True and response.success is False, raises response.body
instead of returning.
"""
with self.channel:
while self.response is None:
self.channel._handlers_enqueued.wait()
if raise_if_failed and not self.response.success:
raise self.response.body
return self.response.body
def on_response(self, response_handler):
"""Registers a handler to invoke when a response is received for this request.
The handler is invoked with Response as its sole argument.
If response has already been received, invokes the handler immediately.
It is guaranteed that self.response is set before the handler is invoked.
If no response was received from the other party before the channel closed,
self.response is a dummy Response with body=NoMoreMessages().
The handler is always invoked asynchronously on an unspecified background
thread - thus, the caller of on_response() can never be blocked or deadlocked
by the handler.
No further incoming messages are processed until the handler returns, except for
responses to requests that have wait_for_response() invoked on them.
"""
with self.channel:
self._response_handlers.append(response_handler)
self._enqueue_response_handlers()
def _enqueue_response_handlers(self):
response = self.response
if response is None:
# Response._parse() will submit the handlers when response is received.
return
def run_handlers():
for handler in handlers:
try:
try:
handler(response)
except MessageHandlingError as exc:
if not exc.applies_to(response):
raise
log.error(
"Handler {0}\ncouldn't handle {1}:\n{2}",
util.srcnameof(handler),
response.describe(),
str(exc),
)
except Exception:
log.reraise_exception(
"Handler {0}\ncouldn't handle {1}:",
util.srcnameof(handler),
response.describe(),
)
handlers = self._response_handlers[:]
self.channel._enqueue_handlers(response, run_handlers)
del self._response_handlers[:]
class Response(Message):
"""Represents an incoming or an outgoing response to a Request.
https://microsoft.github.io/debug-adapter-protocol/specification#response
error_message corresponds to "message" in JSON, and is renamed for clarity.
If success is False, body is None. Otherwise, it is a MessageDict associated
with this Response, and so are all the nested dicts in it. If "body" was missing
or null in JSON, body is an empty dict.
If this is a response to an outgoing request, it will be handled by the handler
registered via self.request.on_response(), if any.
Regardless of whether there is such a handler, OutgoingRequest.wait_for_response()
can also be used to retrieve and handle the response. If there is a handler, it is
executed before wait_for_response() returns.
No further incoming messages are processed until the handler returns, except for
responses to requests that have wait_for_response() invoked on them.
To report failure to handle the event, the handler must raise an instance of
MessageHandlingError that applies_to() the Response object it was handling. Any
such failure is logged, after which the message loop moves on to the next message.
Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
the appropriate exception type that applies_to() the Response object.
"""
def __init__(self, channel, seq, request, body, json=None):
super().__init__(channel, seq, json)
self.request = request
"""The request to which this is the response."""
if isinstance(body, MessageDict) and hasattr(body, "associate_with"):
body.associate_with(self)
self.body = body
"""Body of the response if the request was successful, or an instance
of some class derived from Exception it it was not.
If a response was received from the other side, but request failed, it is an
instance of MessageHandlingError containing the received error message. If the
error message starts with InvalidMessageError.PREFIX, then it's an instance of
the InvalidMessageError specifically, and that prefix is stripped.
If no response was received from the other party before the channel closed,
it is an instance of NoMoreMessages.
"""
def describe(self):
return f"#{self.seq} response to {self.request.describe()}"
@property
def payload(self):
return self.body
@property
def success(self):
"""Whether the request succeeded or not."""
return not isinstance(self.body, Exception)
@property
def result(self):
"""Result of the request. Returns the value of response.body, unless it
is an exception, in which case it is raised instead.
"""
if self.success:
return self.body
else:
raise self.body
@staticmethod
def _parse(channel, message_dict, body=None):
seq = message_dict("seq", int) if (body is None) else None
request_seq = message_dict("request_seq", int)
command = message_dict("command", str)
success = message_dict("success", bool)
if body is None:
if success:
body = message_dict("body", _payload)
else:
error_message = message_dict("message", str)
exc_type = MessageHandlingError
if error_message.startswith(InvalidMessageError.PREFIX):
error_message = error_message[len(InvalidMessageError.PREFIX) :]
exc_type = InvalidMessageError
body = exc_type(error_message, silent=True)
try:
with channel:
request = channel._sent_requests.pop(request_seq)
known_request = True
except KeyError:
# Synthetic Request that only has seq and command as specified in response
# JSON, for error reporting purposes.
request = OutgoingRequest(channel, request_seq, command, "<unknown>")
known_request = False
if not success:
body.cause = request
response = Response(channel, seq, request, body, json=message_dict)
with channel:
request.response = response
request._enqueue_response_handlers()
if known_request:
return response
else:
raise response.isnt_valid(
"request_seq={0} does not match any known request", request_seq
)
class Disconnect(Message):
"""A dummy message used to represent disconnect. It's always the last message
received from any channel.
"""
def __init__(self, channel):
super().__init__(channel, None)
def describe(self):
return f"disconnect from {self.channel}"
class MessageHandlingError(Exception):
"""Indicates that a message couldn't be handled for some reason.
If the reason is a contract violation - i.e. the message that was handled did not
conform to the protocol specification - InvalidMessageError, which is a subclass,
should be used instead.
If any message handler raises an exception not derived from this class, it will
escape the message loop unhandled, and terminate the process.
If any message handler raises this exception, but applies_to(message) is False, it
is treated as if it was a generic exception, as desribed above. Thus, if a request
handler issues another request of its own, and that one fails, the failure is not
silently propagated. However, a request that is delegated via Request.delegate()
will also propagate failures back automatically. For manual propagation, catch the
exception, and call exc.propagate().
If any event handler raises this exception, and applies_to(event) is True, the
exception is silently swallowed by the message loop.
If any request handler raises this exception, and applies_to(request) is True, the
exception is silently swallowed by the message loop, and a failure response is sent
with "message" set to str(reason).
Note that, while errors are not logged when they're swallowed by the message loop,
by that time they have already been logged by their __init__ (when instantiated).
"""
def __init__(self, reason, cause=None, silent=False):
"""Creates a new instance of this class, and immediately logs the exception.
Message handling errors are logged immediately unless silent=True, so that the
precise context in which they occured can be determined from the surrounding
log entries.
"""
self.reason = reason
"""Why it couldn't be handled. This can be any object, but usually it's either
str or Exception.
"""
assert cause is None or isinstance(cause, Message)
self.cause = cause
"""The Message object for the message that couldn't be handled. For responses
to unknown requests, this is a synthetic Request.
"""
if not silent:
try:
raise self
except MessageHandlingError:
log.swallow_exception()
def __hash__(self):
return hash((self.reason, id(self.cause)))
def __eq__(self, other):
if not isinstance(other, MessageHandlingError):
return NotImplemented
if type(self) is not type(other):
return NotImplemented
if self.reason != other.reason:
return False
if self.cause is not None and other.cause is not None:
if self.cause.seq != other.cause.seq:
return False
return True
def __ne__(self, other):
return not self == other
def __str__(self):
return str(self.reason)
def __repr__(self):
s = type(self).__name__
if self.cause is None:
s += f"reason={self.reason!r})"
else:
s += f"channel={self.cause.channel.name!r}, cause={self.cause.seq!r}, reason={self.reason!r})"
return s
def applies_to(self, message):
"""Whether this MessageHandlingError can be treated as a reason why the
handling of message failed.
If self.cause is None, this is always true.
If self.cause is not None, this is only true if cause is message.
"""
return self.cause is None or self.cause is message
def propagate(self, new_cause):
"""Propagates this error, raising a new instance of the same class with the
same reason, but a different cause.
"""
raise type(self)(self.reason, new_cause, silent=True)
class InvalidMessageError(MessageHandlingError):
"""Indicates that an incoming message did not follow the protocol specification -
for example, it was missing properties that are required, or the message itself
is not allowed in the current state.
Raised by MessageDict in lieu of KeyError for missing keys.
"""
PREFIX = "Invalid message: "
"""Automatically prepended to the "message" property in JSON responses, when the
handler raises InvalidMessageError.
If a failed response has "message" property that starts with this prefix, it is
reported as InvalidMessageError rather than MessageHandlingError.
"""
def __str__(self):
return InvalidMessageError.PREFIX + str(self.reason)
class JsonMessageChannel(object):
"""Implements a JSON message channel on top of a raw JSON message stream, with
support for DAP requests, responses, and events.
The channel can be locked for exclusive use via the with-statement::
with channel:
channel.send_request(...)
# No interleaving messages can be sent here from other threads.
channel.send_event(...)
"""
def __init__(self, stream, handlers=None, name=None):
self.stream = stream
self.handlers = handlers
self.name = name if name is not None else stream.name
self.started = False
self._lock = threading.RLock()
self._closed = False
self._seq_iter = itertools.count(1)
self._sent_requests = {} # {seq: Request}
self._handler_queue = [] # [(what, handler)]
self._handlers_enqueued = threading.Condition(self._lock)
self._handler_thread = None
self._parser_thread = None
def __str__(self):
return self.name
def __repr__(self):
return f"{type(self).__name__}({self.name!r})"
def __enter__(self):
self._lock.acquire()
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self._lock.release()
def close(self):
"""Closes the underlying stream.
This does not immediately terminate any handlers that are already executing,
but they will be unable to respond. No new request or event handlers will
execute after this method is called, even for messages that have already been
received. However, response handlers will continue to executed for any request
that is still pending, as will any handlers registered via on_response().
"""
with self:
if not self._closed:
self._closed = True
self.stream.close()
def start(self):
"""Starts a message loop which parses incoming messages and invokes handlers
for them on a background thread, until the channel is closed.
Incoming messages, including responses to requests, will not be processed at
all until this is invoked.
"""
assert not self.started
self.started = True
self._parser_thread = threading.Thread(
target=self._parse_incoming_messages, name=f"{self} message parser"
)
hide_thread_from_debugger(self._parser_thread)
self._parser_thread.daemon = True
self._parser_thread.start()
def wait(self):
"""Waits for the message loop to terminate, and for all enqueued Response
message handlers to finish executing.
"""
parser_thread = self._parser_thread
try:
if parser_thread is not None:
parser_thread.join()
except AssertionError:
log.debug("Handled error joining parser thread.")
try:
handler_thread = self._handler_thread
if handler_thread is not None:
handler_thread.join()
except AssertionError:
log.debug("Handled error joining handler thread.")
# Order of keys for _prettify() - follows the order of properties in
# https://microsoft.github.io/debug-adapter-protocol/specification
_prettify_order = (
"seq",
"type",
"request_seq",
"success",
"command",
"event",
"message",
"arguments",
"body",
"error",
)
def _prettify(self, message_dict):
"""Reorders items in a MessageDict such that it is more readable."""
for key in self._prettify_order:
if key not in message_dict:
continue
value = message_dict[key]
del message_dict[key]
message_dict[key] = value
@contextlib.contextmanager
def _send_message(self, message):
"""Sends a new message to the other party.
Generates a new sequence number for the message, and provides it to the
caller before the message is sent, using the context manager protocol::
with send_message(...) as seq:
# The message hasn't been sent yet.
...
# Now the message has been sent.
Safe to call concurrently for the same channel from different threads.
"""
assert "seq" not in message
with self:
seq = next(self._seq_iter)
message = MessageDict(None, message)
message["seq"] = seq
self._prettify(message)
with self:
yield seq
self.stream.write_json(message)
def send_request(self, command, arguments=None, on_before_send=None):
"""Sends a new request, and returns the OutgoingRequest object for it.
If arguments is None or {}, "arguments" will be omitted in JSON.
If on_before_send is not None, invokes on_before_send() with the request
object as the sole argument, before the request actually gets sent.
Does not wait for response - use OutgoingRequest.wait_for_response().
Safe to call concurrently for the same channel from different threads.
"""
d = {"type": "request", "command": command}
if arguments is not None and arguments != {}:
d["arguments"] = arguments
with self._send_message(d) as seq:
request = OutgoingRequest(self, seq, command, arguments)
if on_before_send is not None:
on_before_send(request)
self._sent_requests[seq] = request
return request
def send_event(self, event, body=None):
"""Sends a new event.
If body is None or {}, "body" will be omitted in JSON.
Safe to call concurrently for the same channel from different threads.
"""
d = {"type": "event", "event": event}
if body is not None and body != {}:
d["body"] = body
with self._send_message(d):
pass
def request(self, *args, **kwargs):
"""Same as send_request(...).wait_for_response()"""
return self.send_request(*args, **kwargs).wait_for_response()
def propagate(self, message):
"""Sends a new message with the same type and payload.
If it was a request, returns the new OutgoingRequest object for it.
"""
assert message.is_request() or message.is_event()
if message.is_request():
return self.send_request(message.command, message.arguments)
else:
self.send_event(message.event, message.body)
def delegate(self, message):
"""Like propagate(message).wait_for_response(), but will also propagate
any resulting MessageHandlingError back.
"""
try:
result = self.propagate(message)
if result.is_request():
result = result.wait_for_response()
return result
except MessageHandlingError as exc:
exc.propagate(message)
def _parse_incoming_messages(self):
log.debug("Starting message loop for channel {0}", self)
try:
while True:
self._parse_incoming_message()
except NoMoreMessages as exc:
log.debug("Exiting message loop for channel {0}: {1}", self, exc)
with self:
# Generate dummy responses for all outstanding requests.
err_message = str(exc)
# Response._parse() will remove items from _sent_requests, so
# make a snapshot before iterating.
sent_requests = list(self._sent_requests.values())
for request in sent_requests:
response_json = MessageDict(
None,
{
"seq": -1,
"request_seq": request.seq,
"command": request.command,
"success": False,
"message": err_message,
},
)
Response._parse(self, response_json, body=exc)
assert not len(self._sent_requests)
self._enqueue_handlers(Disconnect(self), self._handle_disconnect)
self.close()
_message_parsers = {
"event": Event._parse,
"request": Request._parse,
"response": Response._parse,
}
def _parse_incoming_message(self):
"""Reads incoming messages, parses them, and puts handlers into the queue
for _run_handlers() to invoke, until the channel is closed.
"""
# Set up a dedicated decoder for this message, to create MessageDict instances
# for all JSON objects, and track them so that they can be later wired up to
# the Message they belong to, once it is instantiated.
def object_hook(d):
d = MessageDict(None, d)
if "seq" in d:
self._prettify(d)
d.associate_with = associate_with
message_dicts.append(d)
return d
# A hack to work around circular dependency between messages, and instances of
# MessageDict in their payload. We need to set message for all of them, but it
# cannot be done until the actual Message is created - which happens after the
# dicts are created during deserialization.
#
# So, upon deserialization, every dict in the message payload gets a method
# that can be called to set MessageDict.message for *all* dicts belonging to
# that message. This method can then be invoked on the top-level dict by the
# parser, after it has parsed enough of the dict to create the appropriate
# instance of Event, Request, or Response for this message.
def associate_with(message):
for d in message_dicts:
d.message = message
del d.associate_with
message_dicts = []
decoder = self.stream.json_decoder_factory(object_hook=object_hook)
message_dict = self.stream.read_json(decoder)
assert isinstance(message_dict, MessageDict) # make sure stream used decoder
msg_type = message_dict("type", json.enum("event", "request", "response"))
parser = self._message_parsers[msg_type]
try:
parser(self, message_dict)
except InvalidMessageError as exc:
log.error(
"Failed to parse message in channel {0}: {1} in:\n{2}",
self,
str(exc),
json.repr(message_dict),
)
except Exception as exc:
if isinstance(exc, NoMoreMessages) and exc.stream is self.stream:
raise
log.swallow_exception(
"Fatal error in channel {0} while parsing:\n{1}",
self,
json.repr(message_dict),
)
os._exit(1)
def _enqueue_handlers(self, what, *handlers):
"""Enqueues handlers for _run_handlers() to run.
`what` is the Message being handled, and is used for logging purposes.
If the background thread with _run_handlers() isn't running yet, starts it.
"""
with self:
self._handler_queue.extend((what, handler) for handler in handlers)
self._handlers_enqueued.notify_all()
# If there is anything to handle, but there's no handler thread yet,
# spin it up. This will normally happen only once, on the first call
# to _enqueue_handlers(), and that thread will run all the handlers
# for parsed messages. However, this can also happen is somebody calls
# Request.on_response() - possibly concurrently from multiple threads -
# after the channel has already been closed, and the initial handler
# thread has exited. In this case, we spin up a new thread just to run
# the enqueued response handlers, and it will exit as soon as it's out
# of handlers to run.
if len(self._handler_queue) and self._handler_thread is None:
self._handler_thread = threading.Thread(
target=self._run_handlers,
name=f"{self} message handler",
)
hide_thread_from_debugger(self._handler_thread)
self._handler_thread.start()
def _run_handlers(self):
"""Runs enqueued handlers until the channel is closed, or until the handler
queue is empty once the channel is closed.
"""
while True:
with self:
closed = self._closed
if closed:
# Wait for the parser thread to wrap up and enqueue any remaining
# handlers, if it is still running.
self._parser_thread.join()
# From this point on, _enqueue_handlers() can only get called
# from Request.on_response().
with self:
if not closed and not len(self._handler_queue):
# Wait for something to process.
self._handlers_enqueued.wait()
# Make a snapshot before releasing the lock.
handlers = self._handler_queue[:]
del self._handler_queue[:]
if closed and not len(handlers):
# Nothing to process, channel is closed, and parser thread is
# not running anymore - time to quit! If Request.on_response()
# needs to call _enqueue_handlers() later, it will spin up
# a new handler thread.
self._handler_thread = None
return
for what, handler in handlers:
# If the channel is closed, we don't want to process any more events
# or requests - only responses and the final disconnect handler. This
# is to guarantee that if a handler calls close() on its own channel,
# the corresponding request or event is the last thing to be processed.
if closed and handler in (Event._handle, Request._handle):
continue
with log.prefixed("/handling {0}/\n", what.describe()):
try:
handler()
except Exception:
# It's already logged by the handler, so just fail fast.
self.close()
os._exit(1)
def _get_handler_for(self, type, name):
"""Returns the handler for a message of a given type."""
with self:
handlers = self.handlers
for handler_name in (name + "_" + type, type):
try:
return getattr(handlers, handler_name)
except AttributeError:
continue
raise AttributeError(
"handler object {0} for channel {1} has no handler for {2} {3!r}".format(
util.srcnameof(handlers),
self,
type,
name,
)
)
def _handle_disconnect(self):
handler = getattr(self.handlers, "disconnect", lambda: None)
try:
handler()
except Exception:
log.reraise_exception(
"Handler {0}\ncouldn't handle disconnect from {1}:",
util.srcnameof(handler),
self,
)
class MessageHandlers(object):
"""A simple delegating message handlers object for use with JsonMessageChannel.
For every argument provided, the object gets an attribute with the corresponding
name and value.
"""
def __init__(self, **kwargs):
for name, func in kwargs.items():
setattr(self, name, func)
| 56,396 | Python | 36.448207 | 106 | 0.601337 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/singleton.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import functools
import threading
class Singleton(object):
"""A base class for a class of a singleton object.
For any derived class T, the first invocation of T() will create the instance,
and any future invocations of T() will return that instance.
Concurrent invocations of T() from different threads are safe.
"""
# A dual-lock scheme is necessary to be thread safe while avoiding deadlocks.
# _lock_lock is shared by all singleton types, and is used to construct their
# respective _lock instances when invoked for a new type. Then _lock is used
# to synchronize all further access for that type, including __init__. This way,
# __init__ for any given singleton can access another singleton, and not get
# deadlocked if that other singleton is trying to access it.
_lock_lock = threading.RLock()
_lock = None
# Specific subclasses will get their own _instance set in __new__.
_instance = None
_is_shared = None # True if shared, False if exclusive
def __new__(cls, *args, **kwargs):
# Allow arbitrary args and kwargs if shared=False, because that is guaranteed
# to construct a new singleton if it succeeds. Otherwise, this call might end
# up returning an existing instance, which might have been constructed with
# different arguments, so allowing them is misleading.
assert not kwargs.get("shared", False) or (len(args) + len(kwargs)) == 0, (
"Cannot use constructor arguments when accessing a Singleton without "
"specifying shared=False."
)
# Avoid locking as much as possible with repeated double-checks - the most
# common path is when everything is already allocated.
if not cls._instance:
# If there's no per-type lock, allocate it.
if cls._lock is None:
with cls._lock_lock:
if cls._lock is None:
cls._lock = threading.RLock()
# Now that we have a per-type lock, we can synchronize construction.
if not cls._instance:
with cls._lock:
if not cls._instance:
cls._instance = object.__new__(cls)
# To prevent having __init__ invoked multiple times, call
# it here directly, and then replace it with a stub that
# does nothing - that stub will get auto-invoked on return,
# and on all future singleton accesses.
cls._instance.__init__()
cls.__init__ = lambda *args, **kwargs: None
return cls._instance
def __init__(self, *args, **kwargs):
"""Initializes the singleton instance. Guaranteed to only be invoked once for
any given type derived from Singleton.
If shared=False, the caller is requesting a singleton instance for their own
exclusive use. This is only allowed if the singleton has not been created yet;
if so, it is created and marked as being in exclusive use. While it is marked
as such, all attempts to obtain an existing instance of it immediately raise
an exception. The singleton can eventually be promoted to shared use by calling
share() on it.
"""
shared = kwargs.pop("shared", True)
with self:
if shared:
assert (
type(self)._is_shared is not False
), "Cannot access a non-shared Singleton."
type(self)._is_shared = True
else:
assert type(self)._is_shared is None, "Singleton is already created."
def __enter__(self):
"""Lock this singleton to prevent concurrent access."""
type(self)._lock.acquire()
return self
def __exit__(self, exc_type, exc_value, exc_tb):
"""Unlock this singleton to allow concurrent access."""
type(self)._lock.release()
def share(self):
"""Share this singleton, if it was originally created with shared=False."""
type(self)._is_shared = True
class ThreadSafeSingleton(Singleton):
"""A singleton that incorporates a lock for thread-safe access to its members.
The lock can be acquired using the context manager protocol, and thus idiomatic
use is in conjunction with a with-statement. For example, given derived class T::
with T() as t:
t.x = t.frob(t.y)
All access to the singleton from the outside should follow this pattern for both
attributes and method calls. Singleton members can assume that self is locked by
the caller while they're executing, but recursive locking of the same singleton
on the same thread is also permitted.
"""
threadsafe_attrs = frozenset()
"""Names of attributes that are guaranteed to be used in a thread-safe manner.
This is typically used in conjunction with share() to simplify synchronization.
"""
readonly_attrs = frozenset()
"""Names of attributes that are readonly. These can be read without locking, but
cannot be written at all.
Every derived class gets its own separate set. Thus, for any given singleton type
T, an attribute can be made readonly after setting it, with T.readonly_attrs.add().
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Make sure each derived class gets a separate copy.
type(self).readonly_attrs = set(type(self).readonly_attrs)
# Prevent callers from reading or writing attributes without locking, except for
# reading attributes listed in threadsafe_attrs, and methods specifically marked
# with @threadsafe_method. Such methods should perform the necessary locking to
# ensure thread safety for the callers.
@staticmethod
def assert_locked(self):
lock = type(self)._lock
assert lock.acquire(blocking=False), (
"ThreadSafeSingleton accessed without locking. Either use with-statement, "
"or if it is a method or property, mark it as @threadsafe_method or with "
"@autolocked_method, as appropriate."
)
lock.release()
def __getattribute__(self, name):
value = object.__getattribute__(self, name)
if name not in (type(self).threadsafe_attrs | type(self).readonly_attrs):
if not getattr(value, "is_threadsafe_method", False):
ThreadSafeSingleton.assert_locked(self)
return value
def __setattr__(self, name, value):
assert name not in type(self).readonly_attrs, "This attribute is read-only."
if name not in type(self).threadsafe_attrs:
ThreadSafeSingleton.assert_locked(self)
return object.__setattr__(self, name, value)
def threadsafe_method(func):
"""Marks a method of a ThreadSafeSingleton-derived class as inherently thread-safe.
A method so marked must either not use any singleton state, or lock it appropriately.
"""
func.is_threadsafe_method = True
return func
def autolocked_method(func):
"""Automatically synchronizes all calls of a method of a ThreadSafeSingleton-derived
class by locking the singleton for the duration of each call.
"""
@functools.wraps(func)
@threadsafe_method
def lock_and_call(self, *args, **kwargs):
with self:
return func(self, *args, **kwargs)
return lock_and_call
| 7,666 | Python | 40.22043 | 89 | 0.644665 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/server/attach_pid_injected.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""Script injected into the debuggee process during attach-to-PID."""
import os
__file__ = os.path.abspath(__file__)
_debugpy_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
def attach(setup):
log = None
try:
import sys
if "threading" not in sys.modules:
try:
def on_warn(msg):
print(msg, file=sys.stderr)
def on_exception(msg):
print(msg, file=sys.stderr)
def on_critical(msg):
print(msg, file=sys.stderr)
pydevd_attach_to_process_path = os.path.join(
_debugpy_dir,
"debugpy",
"_vendored",
"pydevd",
"pydevd_attach_to_process",
)
assert os.path.exists(pydevd_attach_to_process_path)
sys.path.insert(0, pydevd_attach_to_process_path)
# NOTE: that it's not a part of the pydevd PYTHONPATH
import attach_script
attach_script.fix_main_thread_id(
on_warn=on_warn, on_exception=on_exception, on_critical=on_critical
)
# NOTE: At this point it should be safe to remove this.
sys.path.remove(pydevd_attach_to_process_path)
except:
import traceback
traceback.print_exc()
raise
sys.path.insert(0, _debugpy_dir)
try:
import debugpy
import debugpy.server
from debugpy.common import json, log
import pydevd
finally:
assert sys.path[0] == _debugpy_dir
del sys.path[0]
py_db = pydevd.get_global_debugger()
if py_db is not None:
py_db.dispose_and_kill_all_pydevd_threads(wait=False)
if setup["log_to"] is not None:
debugpy.log_to(setup["log_to"])
log.info("Configuring injected debugpy: {0}", json.repr(setup))
if setup["mode"] == "listen":
debugpy.listen(setup["address"])
elif setup["mode"] == "connect":
debugpy.connect(
setup["address"], access_token=setup["adapter_access_token"]
)
else:
raise AssertionError(repr(setup))
except:
import traceback
traceback.print_exc()
if log is None:
raise
else:
log.reraise_exception()
log.info("debugpy injected successfully")
| 2,734 | Python | 28.408602 | 87 | 0.525969 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/server/__init__.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
# "force_pydevd" must be imported first to ensure (via side effects)
# that the debugpy-vendored copy of pydevd gets used.
import debugpy._vendored.force_pydevd # noqa
| 323 | Python | 39.499995 | 68 | 0.773994 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/server/api.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import codecs
import os
import pydevd
import socket
import sys
import threading
import debugpy
from debugpy import adapter
from debugpy.common import json, log, sockets
from _pydevd_bundle.pydevd_constants import get_global_debugger
from pydevd_file_utils import absolute_path
from debugpy.common.util import hide_debugpy_internals
_tls = threading.local()
# TODO: "gevent", if possible.
_config = {
"qt": "none",
"subProcess": True,
"python": sys.executable,
"pythonEnv": {},
}
_config_valid_values = {
# If property is not listed here, any value is considered valid, so long as
# its type matches that of the default value in _config.
"qt": ["auto", "none", "pyside", "pyside2", "pyqt4", "pyqt5"],
}
# This must be a global to prevent it from being garbage collected and triggering
# https://bugs.python.org/issue37380.
_adapter_process = None
def _settrace(*args, **kwargs):
log.debug("pydevd.settrace(*{0!r}, **{1!r})", args, kwargs)
# The stdin in notification is not acted upon in debugpy, so, disable it.
kwargs.setdefault("notify_stdin", False)
try:
return pydevd.settrace(*args, **kwargs)
except Exception:
raise
else:
_settrace.called = True
_settrace.called = False
def ensure_logging():
"""Starts logging to log.log_dir, if it hasn't already been done."""
if ensure_logging.ensured:
return
ensure_logging.ensured = True
log.to_file(prefix="debugpy.server")
log.describe_environment("Initial environment:")
if log.log_dir is not None:
pydevd.log_to(log.log_dir + "/debugpy.pydevd.log")
ensure_logging.ensured = False
def log_to(path):
if ensure_logging.ensured:
raise RuntimeError("logging has already begun")
log.debug("log_to{0!r}", (path,))
if path is sys.stderr:
log.stderr.levels |= set(log.LEVELS)
else:
log.log_dir = path
def configure(properties=None, **kwargs):
if _settrace.called:
raise RuntimeError("debug adapter is already running")
ensure_logging()
log.debug("configure{0!r}", (properties, kwargs))
if properties is None:
properties = kwargs
else:
properties = dict(properties)
properties.update(kwargs)
for k, v in properties.items():
if k not in _config:
raise ValueError("Unknown property {0!r}".format(k))
expected_type = type(_config[k])
if type(v) is not expected_type:
raise ValueError("{0!r} must be a {1}".format(k, expected_type.__name__))
valid_values = _config_valid_values.get(k)
if (valid_values is not None) and (v not in valid_values):
raise ValueError("{0!r} must be one of: {1!r}".format(k, valid_values))
_config[k] = v
def _starts_debugging(func):
def debug(address, **kwargs):
if _settrace.called:
raise RuntimeError("this process already has a debug adapter")
try:
_, port = address
except Exception:
port = address
address = ("127.0.0.1", port)
try:
port.__index__() # ensure it's int-like
except Exception:
raise ValueError("expected port or (host, port)")
if not (0 <= port < 2 ** 16):
raise ValueError("invalid port number")
ensure_logging()
log.debug("{0}({1!r}, **{2!r})", func.__name__, address, kwargs)
log.info("Initial debug configuration: {0}", json.repr(_config))
qt_mode = _config.get("qt", "none")
if qt_mode != "none":
pydevd.enable_qt_support(qt_mode)
settrace_kwargs = {
"suspend": False,
"patch_multiprocessing": _config.get("subProcess", True),
}
if hide_debugpy_internals():
debugpy_path = os.path.dirname(absolute_path(debugpy.__file__))
settrace_kwargs["dont_trace_start_patterns"] = (debugpy_path,)
settrace_kwargs["dont_trace_end_patterns"] = (str("debugpy_launcher.py"),)
try:
return func(address, settrace_kwargs, **kwargs)
except Exception:
log.reraise_exception("{0}() failed:", func.__name__, level="info")
return debug
@_starts_debugging
def listen(address, settrace_kwargs, in_process_debug_adapter=False):
# Errors below are logged with level="info", because the caller might be catching
# and handling exceptions, and we don't want to spam their stderr unnecessarily.
if in_process_debug_adapter:
host, port = address
log.info("Listening: pydevd without debugpy adapter: {0}:{1}", host, port)
settrace_kwargs['patch_multiprocessing'] = False
_settrace(
host=host,
port=port,
wait_for_ready_to_run=False,
block_until_connected=False,
**settrace_kwargs
)
return
import subprocess
server_access_token = codecs.encode(os.urandom(32), "hex").decode("ascii")
try:
endpoints_listener = sockets.create_server("127.0.0.1", 0, timeout=10)
except Exception as exc:
log.swallow_exception("Can't listen for adapter endpoints:")
raise RuntimeError("can't listen for adapter endpoints: " + str(exc))
try:
endpoints_host, endpoints_port = endpoints_listener.getsockname()
log.info(
"Waiting for adapter endpoints on {0}:{1}...",
endpoints_host,
endpoints_port,
)
host, port = address
adapter_args = [
_config.get("python", sys.executable),
os.path.dirname(adapter.__file__),
"--for-server",
str(endpoints_port),
"--host",
host,
"--port",
str(port),
"--server-access-token",
server_access_token,
]
if log.log_dir is not None:
adapter_args += ["--log-dir", log.log_dir]
log.info("debugpy.listen() spawning adapter: {0}", json.repr(adapter_args))
# On Windows, detach the adapter from our console, if any, so that it doesn't
# receive Ctrl+C from it, and doesn't keep it open once we exit.
creationflags = 0
if sys.platform == "win32":
creationflags |= 0x08000000 # CREATE_NO_WINDOW
creationflags |= 0x00000200 # CREATE_NEW_PROCESS_GROUP
# On embedded applications, environment variables might not contain
# Python environment settings.
python_env = _config.get("pythonEnv")
if not bool(python_env):
python_env = None
# Adapter will outlive this process, so we shouldn't wait for it. However, we
# need to ensure that the Popen instance for it doesn't get garbage-collected
# by holding a reference to it in a non-local variable, to avoid triggering
# https://bugs.python.org/issue37380.
try:
global _adapter_process
_adapter_process = subprocess.Popen(
adapter_args, close_fds=True, creationflags=creationflags, env=python_env
)
if os.name == "posix":
# It's going to fork again to daemonize, so we need to wait on it to
# clean it up properly.
_adapter_process.wait()
else:
# Suppress misleading warning about child process still being alive when
# this process exits (https://bugs.python.org/issue38890).
_adapter_process.returncode = 0
pydevd.add_dont_terminate_child_pid(_adapter_process.pid)
except Exception as exc:
log.swallow_exception("Error spawning debug adapter:", level="info")
raise RuntimeError("error spawning debug adapter: " + str(exc))
try:
sock, _ = endpoints_listener.accept()
try:
sock.settimeout(None)
sock_io = sock.makefile("rb", 0)
try:
endpoints = json.loads(sock_io.read().decode("utf-8"))
finally:
sock_io.close()
finally:
sockets.close_socket(sock)
except socket.timeout:
log.swallow_exception(
"Timed out waiting for adapter to connect:", level="info"
)
raise RuntimeError("timed out waiting for adapter to connect")
except Exception as exc:
log.swallow_exception("Error retrieving adapter endpoints:", level="info")
raise RuntimeError("error retrieving adapter endpoints: " + str(exc))
finally:
endpoints_listener.close()
log.info("Endpoints received from adapter: {0}", json.repr(endpoints))
if "error" in endpoints:
raise RuntimeError(str(endpoints["error"]))
try:
server_host = str(endpoints["server"]["host"])
server_port = int(endpoints["server"]["port"])
client_host = str(endpoints["client"]["host"])
client_port = int(endpoints["client"]["port"])
except Exception as exc:
log.swallow_exception(
"Error parsing adapter endpoints:\n{0}\n",
json.repr(endpoints),
level="info",
)
raise RuntimeError("error parsing adapter endpoints: " + str(exc))
log.info(
"Adapter is accepting incoming client connections on {0}:{1}",
client_host,
client_port,
)
_settrace(
host=server_host,
port=server_port,
wait_for_ready_to_run=False,
block_until_connected=True,
access_token=server_access_token,
**settrace_kwargs
)
log.info("pydevd is connected to adapter at {0}:{1}", server_host, server_port)
return client_host, client_port
@_starts_debugging
def connect(address, settrace_kwargs, access_token=None):
host, port = address
_settrace(host=host, port=port, client_access_token=access_token, **settrace_kwargs)
class wait_for_client:
def __call__(self):
ensure_logging()
log.debug("wait_for_client()")
pydb = get_global_debugger()
if pydb is None:
raise RuntimeError("listen() or connect() must be called first")
cancel_event = threading.Event()
self.cancel = cancel_event.set
pydevd._wait_for_attach(cancel=cancel_event)
@staticmethod
def cancel():
raise RuntimeError("wait_for_client() must be called first")
wait_for_client = wait_for_client()
def is_client_connected():
return pydevd._is_attached()
def breakpoint():
ensure_logging()
if not is_client_connected():
log.info("breakpoint() ignored - debugger not attached")
return
log.debug("breakpoint()")
# Get the first frame in the stack that's not an internal frame.
pydb = get_global_debugger()
stop_at_frame = sys._getframe().f_back
while (
stop_at_frame is not None
and pydb.get_file_type(stop_at_frame) == pydb.PYDEV_FILE
):
stop_at_frame = stop_at_frame.f_back
_settrace(
suspend=True,
trace_only_current_thread=True,
patch_multiprocessing=False,
stop_at_frame=stop_at_frame,
)
stop_at_frame = None
def debug_this_thread():
ensure_logging()
log.debug("debug_this_thread()")
_settrace(suspend=False)
def trace_this_thread(should_trace):
ensure_logging()
log.debug("trace_this_thread({0!r})", should_trace)
pydb = get_global_debugger()
if should_trace:
pydb.enable_tracing()
else:
pydb.disable_tracing()
| 11,789 | Python | 31.213115 | 89 | 0.603359 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/server/cli.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import json
import os
import re
import sys
from importlib.util import find_spec
# debugpy.__main__ should have preloaded pydevd properly before importing this module.
# Otherwise, some stdlib modules above might have had imported threading before pydevd
# could perform the necessary detours in it.
assert "pydevd" in sys.modules
import pydevd
# Note: use the one bundled from pydevd so that it's invisible for the user.
from _pydevd_bundle import pydevd_runpy as runpy
import debugpy
from debugpy.common import log
from debugpy.server import api
TARGET = "<filename> | -m <module> | -c <code> | --pid <pid>"
HELP = """debugpy {0}
See https://aka.ms/debugpy for documentation.
Usage: debugpy --listen | --connect
[<host>:]<port>
[--wait-for-client]
[--configure-<name> <value>]...
[--log-to <path>] [--log-to-stderr]
{1}
[<arg>]...
""".format(
debugpy.__version__, TARGET
)
class Options(object):
mode = None
address = None
log_to = None
log_to_stderr = False
target = None
target_kind = None
wait_for_client = False
adapter_access_token = None
options = Options()
options.config = {"qt": "none", "subProcess": True}
def in_range(parser, start, stop):
def parse(s):
n = parser(s)
if start is not None and n < start:
raise ValueError("must be >= {0}".format(start))
if stop is not None and n >= stop:
raise ValueError("must be < {0}".format(stop))
return n
return parse
pid = in_range(int, 0, None)
def print_help_and_exit(switch, it):
print(HELP, file=sys.stderr)
sys.exit(0)
def print_version_and_exit(switch, it):
print(debugpy.__version__)
sys.exit(0)
def set_arg(varname, parser=(lambda x: x)):
def do(arg, it):
value = parser(next(it))
setattr(options, varname, value)
return do
def set_const(varname, value):
def do(arg, it):
setattr(options, varname, value)
return do
def set_address(mode):
def do(arg, it):
if options.address is not None:
raise ValueError("--listen and --connect are mutually exclusive")
# It's either host:port, or just port.
value = next(it)
host, sep, port = value.partition(":")
if not sep:
host = "127.0.0.1"
port = value
try:
port = int(port)
except Exception:
port = -1
if not (0 <= port < 2 ** 16):
raise ValueError("invalid port number")
options.mode = mode
options.address = (host, port)
return do
def set_config(arg, it):
prefix = "--configure-"
assert arg.startswith(prefix)
name = arg[len(prefix) :]
value = next(it)
if name not in options.config:
raise ValueError("unknown property {0!r}".format(name))
expected_type = type(options.config[name])
try:
if expected_type is bool:
value = {"true": True, "false": False}[value.lower()]
else:
value = expected_type(value)
except Exception:
raise ValueError("{0!r} must be a {1}".format(name, expected_type.__name__))
options.config[name] = value
def set_target(kind, parser=(lambda x: x), positional=False):
def do(arg, it):
options.target_kind = kind
target = parser(arg if positional else next(it))
if isinstance(target, bytes):
# target may be the code, so, try some additional encodings...
try:
target = target.decode(sys.getfilesystemencoding())
except UnicodeDecodeError:
try:
target = target.decode("utf-8")
except UnicodeDecodeError:
import locale
target = target.decode(locale.getpreferredencoding(False))
options.target = target
return do
# fmt: off
switches = [
# Switch Placeholder Action
# ====== =========== ======
# Switches that are documented for use by end users.
("-(\\?|h|-help)", None, print_help_and_exit),
("-(V|-version)", None, print_version_and_exit),
("--log-to" , "<path>", set_arg("log_to")),
("--log-to-stderr", None, set_const("log_to_stderr", True)),
("--listen", "<address>", set_address("listen")),
("--connect", "<address>", set_address("connect")),
("--wait-for-client", None, set_const("wait_for_client", True)),
("--configure-.+", "<value>", set_config),
# Switches that are used internally by the client or debugpy itself.
("--adapter-access-token", "<token>", set_arg("adapter_access_token")),
# Targets. The "" entry corresponds to positional command line arguments,
# i.e. the ones not preceded by any switch name.
("", "<filename>", set_target("file", positional=True)),
("-m", "<module>", set_target("module")),
("-c", "<code>", set_target("code")),
("--pid", "<pid>", set_target("pid", pid)),
]
# fmt: on
def consume_argv():
while len(sys.argv) >= 2:
value = sys.argv[1]
del sys.argv[1]
yield value
def parse_argv():
seen = set()
it = consume_argv()
while True:
try:
arg = next(it)
except StopIteration:
raise ValueError("missing target: " + TARGET)
switch = arg
if not switch.startswith("-"):
switch = ""
for pattern, placeholder, action in switches:
if re.match("^(" + pattern + ")$", switch):
break
else:
raise ValueError("unrecognized switch " + switch)
if switch in seen:
raise ValueError("duplicate switch " + switch)
else:
seen.add(switch)
try:
action(arg, it)
except StopIteration:
assert placeholder is not None
raise ValueError("{0}: missing {1}".format(switch, placeholder))
except Exception as exc:
raise ValueError("invalid {0} {1}: {2}".format(switch, placeholder, exc))
if options.target is not None:
break
if options.mode is None:
raise ValueError("either --listen or --connect is required")
if options.adapter_access_token is not None and options.mode != "connect":
raise ValueError("--adapter-access-token requires --connect")
if options.target_kind == "pid" and options.wait_for_client:
raise ValueError("--pid does not support --wait-for-client")
assert options.target is not None
assert options.target_kind is not None
assert options.address is not None
def start_debugging(argv_0):
# We need to set up sys.argv[0] before invoking either listen() or connect(),
# because they use it to report the "process" event. Thus, we can't rely on
# run_path() and run_module() doing that, even though they will eventually.
sys.argv[0] = argv_0
log.debug("sys.argv after patching: {0!r}", sys.argv)
debugpy.configure(options.config)
if options.mode == "listen":
debugpy.listen(options.address)
elif options.mode == "connect":
debugpy.connect(options.address, access_token=options.adapter_access_token)
else:
raise AssertionError(repr(options.mode))
if options.wait_for_client:
debugpy.wait_for_client()
def run_file():
target = options.target
start_debugging(target)
# run_path has one difference with invoking Python from command-line:
# if the target is a file (rather than a directory), it does not add its
# parent directory to sys.path. Thus, importing other modules from the
# same directory is broken unless sys.path is patched here.
if os.path.isfile(target):
dir = os.path.dirname(target)
sys.path.insert(0, dir)
else:
log.debug("Not a file: {0!r}", target)
log.describe_environment("Pre-launch environment:")
log.info("Running file {0!r}", target)
runpy.run_path(target, run_name="__main__")
def run_module():
# Add current directory to path, like Python itself does for -m. This must
# be in place before trying to use find_spec below to resolve submodules.
sys.path.insert(0, str(""))
# We want to do the same thing that run_module() would do here, without
# actually invoking it.
argv_0 = sys.argv[0]
try:
spec = find_spec(options.target)
if spec is not None:
argv_0 = spec.origin
except Exception:
log.swallow_exception("Error determining module path for sys.argv")
start_debugging(argv_0)
log.describe_environment("Pre-launch environment:")
log.info("Running module {0!r}", options.target)
# Docs say that runpy.run_module is equivalent to -m, but it's not actually
# the case for packages - -m sets __name__ to "__main__", but run_module sets
# it to "pkg.__main__". This breaks everything that uses the standard pattern
# __name__ == "__main__" to detect being run as a CLI app. On the other hand,
# runpy._run_module_as_main is a private function that actually implements -m.
try:
run_module_as_main = runpy._run_module_as_main
except AttributeError:
log.warning("runpy._run_module_as_main is missing, falling back to run_module.")
runpy.run_module(options.target, alter_sys=True)
else:
run_module_as_main(options.target, alter_argv=True)
def run_code():
# Add current directory to path, like Python itself does for -c.
sys.path.insert(0, str(""))
code = compile(options.target, str("<string>"), str("exec"))
start_debugging(str("-c"))
log.describe_environment("Pre-launch environment:")
log.info("Running code:\n\n{0}", options.target)
eval(code, {})
def attach_to_pid():
pid = options.target
log.info("Attaching to process with PID={0}", pid)
encode = lambda s: list(bytearray(s.encode("utf-8"))) if s is not None else None
script_dir = os.path.dirname(debugpy.server.__file__)
assert os.path.exists(script_dir)
script_dir = encode(script_dir)
setup = {
"mode": options.mode,
"address": options.address,
"wait_for_client": options.wait_for_client,
"log_to": options.log_to,
"adapter_access_token": options.adapter_access_token,
}
setup = encode(json.dumps(setup))
python_code = """
import codecs;
import json;
import sys;
decode = lambda s: codecs.utf_8_decode(bytearray(s))[0] if s is not None else None;
script_dir = decode({script_dir});
setup = json.loads(decode({setup}));
sys.path.insert(0, script_dir);
import attach_pid_injected;
del sys.path[0];
attach_pid_injected.attach(setup);
"""
python_code = (
python_code.replace("\r", "")
.replace("\n", "")
.format(script_dir=script_dir, setup=setup)
)
log.info("Code to be injected: \n{0}", python_code.replace(";", ";\n"))
# pydevd restriction on characters in injected code.
assert not (
{'"', "'", "\r", "\n"} & set(python_code)
), "Injected code should not contain any single quotes, double quotes, or newlines."
pydevd_attach_to_process_path = os.path.join(
os.path.dirname(pydevd.__file__), "pydevd_attach_to_process"
)
assert os.path.exists(pydevd_attach_to_process_path)
sys.path.append(pydevd_attach_to_process_path)
try:
import add_code_to_python_process # noqa
log.info("Injecting code into process with PID={0} ...", pid)
add_code_to_python_process.run_python_code(
pid,
python_code,
connect_debugger_tracing=True,
show_debug_info=int(os.getenv("DEBUGPY_ATTACH_BY_PID_DEBUG_INFO", "0")),
)
except Exception:
log.reraise_exception("Code injection into PID={0} failed:", pid)
log.info("Code injection into PID={0} completed.", pid)
def main():
original_argv = list(sys.argv)
try:
parse_argv()
except Exception as exc:
print(str(HELP) + str("\nError: ") + str(exc), file=sys.stderr)
sys.exit(2)
if options.log_to is not None:
debugpy.log_to(options.log_to)
if options.log_to_stderr:
debugpy.log_to(sys.stderr)
api.ensure_logging()
log.info(
str("sys.argv before parsing: {0!r}\n" " after parsing: {1!r}"),
original_argv,
sys.argv,
)
try:
run = {
"file": run_file,
"module": run_module,
"code": run_code,
"pid": attach_to_pid,
}[options.target_kind]
run()
except SystemExit as exc:
log.reraise_exception(
"Debuggee exited via SystemExit: {0!r}", exc.code, level="debug"
)
| 13,289 | Python | 29.551724 | 89 | 0.589059 |
omniverse-code/kit/exts/omni.kit.debug.python/config/extension.toml | [package]
version = "0.2.0"
title = "A debugger for Python"
description="Uses debugpy which implements the Debug Adapter Protocol"
authors = ["NVIDIA"]
repository = ""
category = "Internal"
keywords = ["kit"]
readme = "docs/README.md"
changelog="docs/CHANGELOG.md"
[dependencies]
"omni.kit.pip_archive" = {}
[[python.module]]
name = "omni.kit.debug.python"
[settings.exts."omni.kit.debug.python"]
# Host and port for listen to debugger for
host = "127.0.0.1"
port = 3000
# Enable debugpy builtin logging, logs go into ${logs} folder
debugpyLogging = false
# Block until client (debugger) connected
waitForClient = false
# break immediately (also waits for client)
break = false
[[test]]
pyCoverageEnabled = false
waiver = "Developer tool. Brings 3rd party (debugpy) to another 3rd party (VSCode), doesn't have much to test and building an integration test is not worth it."
| 882 | TOML | 24.228571 | 160 | 0.732426 |
omniverse-code/kit/exts/omni.kit.debug.python/omni/kit/debug/python.py | import sys
import carb.tokens
import carb.settings
import omni.ext
import omni.kit.pipapi
# Try import to allow documentation build without debugpy
try:
import debugpy
except ModuleNotFoundError:
pass
def _print(msg):
print(f"[omni.kit.debug.python] {msg}")
def wait_for_client():
_print("Waiting for debugger to connect...")
debugpy.wait_for_client()
def breakpoint():
wait_for_client()
debugpy.breakpoint()
def is_attached() -> bool:
return debugpy.is_client_connected()
def enable_logging():
path = carb.tokens.get_tokens_interface().resolve("${logs}")
_print(f"Enabled logging to '{path}'")
debugpy.log_to(path)
_listen_address = None
def get_listen_address():
return _listen_address
class Extension(omni.ext.IExt):
def on_startup(self):
settings = carb.settings.get_settings()
host = settings.get("/exts/omni.kit.debug.python/host")
port = settings.get("/exts/omni.kit.debug.python/port")
debugpyLogging = settings.get("/exts/omni.kit.debug.python/debugpyLogging")
waitForClient = settings.get("/exts/omni.kit.debug.python/waitForClient")
break_ = settings.get("/exts/omni.kit.debug.python/break")
if debugpyLogging:
enable_logging()
# Start debugging server
python_exe = "python.exe" if sys.platform == "win32" else "bin/python3"
python_cmd = sys.prefix + "/" + python_exe
debugpy.configure(python=python_cmd)
global _listen_address
try:
_listen_address = debugpy.listen((host, port))
_print(f"Running python debugger on: {_listen_address}")
except Exception as e:
_print(f"Error running python debugger: {e}")
if waitForClient:
wait_for_client()
if break_:
breakpoint()
| 1,852 | Python | 23.706666 | 83 | 0.641469 |
omniverse-code/kit/exts/omni.kit.debug.python/docs/CHANGELOG.md | # CHANGELOG
## [0.2.0] - 2022-09-28
- Prebundle debugpy
## [0.1.0] - 2020-02-22
- Initial commit
| 101 | Markdown | 9.199999 | 23 | 0.594059 |
omniverse-code/kit/exts/omni.activity.core/config/extension.toml | [package]
title = "Omni Activity Core"
category = "Telemetry"
version = "1.0.1"
description = "The activity and the progress processor"
authors = ["NVIDIA"]
keywords = ["activity"]
[[python.module]]
name = "omni.activity.core"
[[native.plugin]]
path = "bin/*.plugin"
| 269 | TOML | 18.285713 | 55 | 0.69145 |
omniverse-code/kit/exts/omni.activity.core/omni/activity/core/_activity.pyi | from __future__ import annotations
import omni.activity.core._activity
import typing
import omni.core._core
__all__ = [
"EventType",
"IActivity",
"IEvent",
"INode",
"began",
"disable",
"enable",
"ended",
"get_instance",
"progress",
"updated"
]
class EventType():
"""
Members:
BEGAN : /< The activity is started
UPDATED : /< The activity is changed
ENDED : /< The activity is finished
"""
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
"""
BEGAN: omni.activity.core._activity.EventType # value = <EventType.BEGAN: 0>
ENDED: omni.activity.core._activity.EventType # value = <EventType.ENDED: 2>
UPDATED: omni.activity.core._activity.EventType # value = <EventType.UPDATED: 1>
__members__: dict # value = {'BEGAN': <EventType.BEGAN: 0>, 'UPDATED': <EventType.UPDATED: 1>, 'ENDED': <EventType.ENDED: 2>}
pass
class IActivity(_IActivity, omni.core._core.IObject):
"""
@brief The activity and the progress processor.
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
def create_callback_to_pop(self, fn: typing.Callable[[INode], None]) -> int:
"""
Subscribes to event dispatching on the stream.
See :class:`.Subscription` for more information on subscribing mechanism.
Args:
fn: The callback to be called on event dispatch.
Returns:
The subscription holder.
"""
def pump(self) -> None:
"""
@brief Process the callback. Should be called once per frame.
"""
def push_event_dict(self, node_path: str, type: EventType, event_payload: capsule) -> bool:
"""
@brief Push event to the system.
TODO: eventPayload is a placeholder
TODO: eventPayload should be carb::dictionary
"""
def remove_callback(self, id: int) -> None:
"""
@brief Remove the callback.
"""
@property
def current_timestamp(self) -> int:
"""
:type: int
"""
@property
def enabled(self) -> None:
"""
:type: None
"""
@enabled.setter
def enabled(self, arg1: bool) -> None:
pass
pass
class IEvent(_IEvent, omni.core._core.IObject):
"""
@brief The event contains custom data. It can be speed, progress, etc.
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
@property
def event_timestamp(self) -> int:
"""
:type: int
"""
@property
def event_type(self) -> EventType:
"""
:type: EventType
"""
@property
def payload(self) -> carb.dictionary._dictionary.Item:
"""
:type: carb.dictionary._dictionary.Item
"""
pass
class INode(_INode, omni.core._core.IObject):
"""
@brief Node can contain other nodes and events.
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
def get_child(self, n: int) -> INode:
"""
@brief Get the child node
"""
def get_event(self, n: int) -> IEvent:
"""
@brief Get the activity
"""
@property
def child_count(self) -> int:
"""
:type: int
"""
@property
def event_count(self) -> int:
"""
:type: int
"""
@property
def name(self) -> str:
"""
:type: str
"""
pass
class _IActivity(omni.core._core.IObject):
pass
class _IEvent(omni.core._core.IObject):
pass
class _INode(omni.core._core.IObject):
pass
def began(arg0: str, **kwargs) -> None:
pass
def disable() -> None:
pass
def enable() -> None:
pass
def ended(arg0: str, **kwargs) -> None:
pass
def get_instance() -> IActivity:
pass
def progress(arg0: str, arg1: float, **kwargs) -> None:
pass
def updated(arg0: str, **kwargs) -> None:
pass
| 4,644 | unknown | 24.805555 | 129 | 0.543712 |
omniverse-code/kit/exts/omni.activity.core/omni/activity/core/tests/test_activity.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.activity.core as act
import omni.kit.app
import omni.kit.test
class TestActivity(omni.kit.test.AsyncTestCase):
async def test_general(self):
called = []
def callback(node: act.INode):
self.assertEqual(node.name, "Test")
self.assertEqual(node.child_count, 1)
child = node.get_child(0)
self.assertEqual(child.name, "SubTest")
self.assertEqual(child.event_count, 2)
began = child.get_event(0)
ended = child.get_event(1)
self.assertEqual(began.event_type, act.EventType.BEGAN)
self.assertEqual(ended.event_type, act.EventType.ENDED)
self.assertEqual(began.payload["progress"], 0.0)
self.assertEqual(ended.payload["progress"], 1.0)
called.append(True)
id = act.get_instance().create_callback_to_pop(callback)
act.enable()
act.began("Test|SubTest", progress=0.0)
act.ended("Test|SubTest", progress=1.0)
act.disable()
act.get_instance().pump()
act.get_instance().remove_callback(id)
self.assertEquals(len(called), 1)
| 1,599 | Python | 31.653061 | 77 | 0.65666 |
omniverse-code/kit/exts/omni.hydra.index/omni/hydra/index/tests/__init__.py | from .nvindex_render_test import *
| 35 | Python | 16.999992 | 34 | 0.771429 |
omniverse-code/kit/exts/omni.hydra.index/omni/hydra/index/tests/nvindex_render_test.py | #!/usr/bin/env python3
import omni.kit.commands
import omni.kit.test
import omni.usd
from omni.rtx.tests import RtxTest, testSettings, postLoadTestSettings
from omni.rtx.tests.test_common import set_transform_helper, wait_for_update
from omni.kit.test_helpers_gfx.compare_utils import ComparisonMetric
from pxr import Sdf, Gf, UsdVol
from pathlib import Path
EXTENSION_DIR = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
TESTS_DIR = EXTENSION_DIR.joinpath('data', 'tests')
USD_DIR = TESTS_DIR.joinpath('usd')
GOLDEN_IMAGES_DIR = TESTS_DIR.joinpath('golden')
VOLUMES_DIR = TESTS_DIR.joinpath('volumes')
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
# This class is auto-discoverable by omni.kit.test
class IndexRenderTest(RtxTest):
WINDOW_SIZE = (512, 512)
THRESHOLD = 1e-5
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
self.ctx.new_stage()
self.add_dir_light()
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
# Overridden with custom paths
async def capture_and_compare(self, img_subdir: Path = "", golden_img_name=None, threshold=THRESHOLD,
metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED):
golden_img_dir = GOLDEN_IMAGES_DIR.joinpath(img_subdir)
output_img_dir = OUTPUTS_DIR.joinpath(img_subdir)
if not golden_img_name:
golden_img_name = f"{self.__test_name}.png"
return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric)
# Overridden with custom paths
def open_usd(self, usdSubpath: Path):
path = USD_DIR.joinpath(usdSubpath)
self.ctx.open_stage(str(path))
def get_volumes_path(self, volumeSubPath: Path):
return Sdf.AssetPath(str(VOLUMES_DIR.joinpath(volumeSubPath)))
def change_reference(self, prim_path, reference):
stage = self.ctx.get_stage()
prim = stage.GetPrimAtPath(prim_path)
ref = prim.GetReferences()
ref.ClearReferences()
ref.AddReference(Sdf.Reference(reference))
async def run_imge_test(self, usd_file: str, image_name: str, fn = None):
if usd_file:
self.open_usd(usd_file)
if fn:
fn()
await wait_for_update()
await self.capture_and_compare(golden_img_name=image_name)
#
# The tests
#
async def test_render_torus(self):
await self.run_imge_test('torus.usda', 'nvindex-torus.png')
async def test_render_torus_colormap(self):
await self.run_imge_test('torus-colormap.usda', 'nvindex-torus-colormap-2.png')
colormap_prim_path = '/World/Volume/mat/Colormap'
# Switch to another colormap
await self.run_imge_test(None, 'nvindex-torus-colormap-3.png',
lambda: self.change_reference(colormap_prim_path, './colormap3.usda'))
# Switch to colormap defined by RGBA control-points
colormap = self.ctx.get_stage().GetPrimAtPath(colormap_prim_path)
colormap.CreateAttribute("domain", Sdf.ValueTypeNames.Float2).Set((0.0, 1.0))
colormap.CreateAttribute("colormapSource", Sdf.ValueTypeNames.Token).Set("rgbaPoints")
colormap.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray).Set([0.5, 0.7, 1.0])
colormap.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array).Set([(0, 1, 0, 0.14), (1, 0, 0, 0.25), (1, 1, 0, 0.25)])
await self.run_imge_test(None, 'nvindex-torus-colormap-rgba-points.png')
async def test_render_torus_shader(self):
await self.run_imge_test('torus-shader.usda', 'nvindex-torus-shader.png')
async def test_render_torus_settings(self):
await self.run_imge_test('torus-settings.usda', 'nvindex-torus-settings.png')
async def test_render_torus_create(self):
PRIM_PATH = "/World/volume"
open_vdb_asset = UsdVol.OpenVDBAsset.Define(self.ctx.get_stage(), PRIM_PATH + "/OpenVDBAsset")
open_vdb_asset.GetFilePathAttr().Set(self.get_volumes_path("torus.vdb"))
# Use default field in the OpenVDB file, instead of setting it explicitly:
# open_vdb_asset.GetFieldNameAttr().Set("torus_fog")
volume = UsdVol.Volume.Define(self.ctx.get_stage(), PRIM_PATH)
volume.CreateFieldRelationship("torus", open_vdb_asset.GetPath())
set_transform_helper(volume.GetPath(), translate=Gf.Vec3d(0, 150, 0), scale=Gf.Vec3d(20.0, 20.0, 20.0))
await wait_for_update()
await self.run_imge_test(None, 'nvindex-torus-create.png')
| 4,689 | Python | 40.504424 | 135 | 0.670719 |
omniverse-code/kit/exts/omni.kit.compatibility_checker/config/extension.toml | [package]
version = "0.1.0"
title = "Kit Compatibility Checker"
category = "Internal"
[dependencies]
"omni.appwindow" = { }
"omni.gpu_foundation" = { }
"omni.kit.notification_manager" = { optional=true }
"omni.kit.window.viewport" = { optional=true }
"omni.kit.renderer.core" = { optional=true }
[[python.module]]
name = "omni.kit.compatibility_checker"
[settings]
[settings.exts."omni.kit.compatibility_checker"]
# supportedGpus = [
# "*GeForce RTX ????*",
# "*Quadro RTX ????*",
# "*RTX ?????*",
# "*TITAN RTX*"
# ]
"windows-x86_64".minOsVersion = 0 #19042
# "windows-x86_64".driverBlacklistRanges = [
# ["0.0", "456.39", "The minimum RTX requirement"],
# ["460.0", "461.92", "Driver crashes or image artifacts"],
# ]
"linux-x86_64".minOsVersion = 0
# "linux-x86_64".driverBlacklistRanges = [
# ["0.0", "450.57", "The minimum RTX requirement"],
# ["455.23", "455.24", "NVIDIA OptiX bug"],
# ["460.0", "460.62", "Driver crashes or image artifacts"],
# ]
"linux-aarch64".minOsVersion = 0
# "linux-aarch64".driverBlacklistRanges = [
# ["0.0", "450.57", "The minimum RTX requirement"]
# ]
[[test]]
args = []
dependencies = ["omni.kit.renderer.core"]
| 1,194 | TOML | 25.555555 | 63 | 0.623953 |
omniverse-code/kit/exts/omni.kit.compatibility_checker/omni/kit/compatibility_checker/scripts/extension.py | import asyncio
import importlib
import fnmatch
import carb
import carb.settings
import omni.appwindow
import omni.ext
import omni.gpu_foundation_factory
import omni.kit.app
import omni.kit.renderer.bind
RENDERER_ENABLED_SETTINGS_PATH = "/renderer/enabled"
CHECKER_SETTINGS_PATH = "exts/omni.kit.compatibility_checker/"
def escape_for_fnmatch(s: str) -> str:
return s.replace("[", "[[]")
def get_gpus_list_from_device(device):
gpus_list = omni.gpu_foundation_factory.get_gpus_list(device)
try:
gpus_list.remove("Microsoft Basic Render Driver")
except ValueError:
pass
return gpus_list
def get_driver_version_from_device(device):
driver_version = omni.gpu_foundation_factory.get_driver_version(device)
return driver_version
def check_supported_gpu(gpus_list, supported_gpus):
gpu_good = False
for gpu in gpus_list:
for supported_gpu in supported_gpus:
if fnmatch.fnmatch(escape_for_fnmatch(gpu), supported_gpu):
gpu_good = True
break
return gpu_good
def check_driver_version(driver_version, driver_blacklist_ranges):
for driver_blacklist_range in driver_blacklist_ranges:
version_from = [int(i) for i in driver_blacklist_range[0].split(".")]
version_to = [int(i) for i in driver_blacklist_range[1].split(".")]
def is_driver_in_range(version, version_from, version_to):
version_int = version[0] * 100 + version[1]
version_from_int = version_from[0] * 100 + version_from[1]
version_to_int = version_to[0] * 100 + version_to[1]
if version_int < version_from_int or version_int >= version_to_int:
return False
return True
if is_driver_in_range(driver_version, version_from, version_to):
return False, driver_blacklist_range
return True, []
def check_os_version(min_os_version):
os_good = True
os_version = omni.gpu_foundation_factory.get_os_build_number()
if os_version < min_os_version:
os_good = False
return os_good, os_version
class Extension(omni.ext.IExt):
def __init__(self):
super().__init__()
pass
def _check_rtx_renderer_state(self):
if self._module_viewport:
enabled_renderers = self._settings.get(RENDERER_ENABLED_SETTINGS_PATH).lower().split(',')
rtx_enabled = 'rtx' in enabled_renderers
# Viewport 1.5 doesn't have methods to return attached context, but it also doesn't
# quite work with multiple contexts out of the box, so we just assume default context.
# In VP 2.0, the hope is to have better communication protocol with HydraEngine
# so there will be no need for this whole compatibility checker anyway.
usd_context = omni.usd.get_context("")
attached_hydra_engines = usd_context.get_attached_hydra_engine_names()
if rtx_enabled and ("rtx" not in attached_hydra_engines):
return False
return True
async def _compatibility_check(self):
# Wait a couple of frames to make sure all subsystems are properly initialized
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
rtx_renderer_good = self._check_rtx_renderer_state()
if rtx_renderer_good is True:
# Early exit if renderer is OK, no need to check driver, GPU and OS version in this case
return
# Renderer wasn't initialized properly
message = "RTX engine creation failed. RTX renderers in viewport will be disabled. Please make sure selected GPU is RTX-capable, and GPU drivers meet requirements."
carb.log_error(message)
if self._module_notification_manager is not None:
def open_log():
log_file_path = self._settings.get("/log/file")
import webbrowser
webbrowser.open(log_file_path)
dismiss_button = self._module_notification_manager.NotificationButtonInfo("Dismiss", None)
show_log_file_button = self._module_notification_manager.NotificationButtonInfo("Open log", open_log)
self._module_notification_manager.post_notification(message, hide_after_timeout=False, button_infos=[dismiss_button, show_log_file_button])
platform_info = omni.kit.app.get_app().get_platform_info()
platform_settings_path = CHECKER_SETTINGS_PATH + platform_info['platform'] + "/"
min_os_version = self._settings.get(platform_settings_path + "minOsVersion")
driver_blacklist_ranges = self._settings.get(platform_settings_path + "driverBlacklistRanges")
supported_gpus = self._settings.get(CHECKER_SETTINGS_PATH + "supportedGpus")
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
device = self._renderer.get_graphics_device(omni.appwindow.get_default_app_window())
if supported_gpus is None:
carb.log_warn("Supported GPUs list is empty, skipping GPU compatibility check!")
else:
gpus_list = get_gpus_list_from_device(device)
gpu_good = check_supported_gpu(gpus_list, supported_gpus)
if gpu_good is not True:
message = "Available GPUs are not supported. List of available GPUs:\n%s" % (gpus_list)
carb.log_error(message)
if self._module_notification_manager is not None:
self._module_notification_manager.post_notification(message, hide_after_timeout=False)
driver_good = True
if driver_blacklist_ranges is None:
carb.log_warn("Supported drivers list is empty, skipping GPU compatibility check!")
else:
driver_version = get_driver_version_from_device(device)
driver_good, driver_blacklist_range = check_driver_version(driver_version, driver_blacklist_ranges)
if driver_good is not True:
message = "Driver version %d.%d is not supported. Driver is in blacklisted range %s-%s. Reason for blacklisting: %s." % (
driver_version[0],
driver_version[1],
driver_blacklist_range[0],
driver_blacklist_range[1],
driver_blacklist_range[2]
)
carb.log_error(message)
if self._module_notification_manager is not None:
self._module_notification_manager.post_notification(message, hide_after_timeout=False)
os_good, os_version = check_os_version(min_os_version)
if os_good is not True:
message = "Please update the OS. Minimum required OS build number for %s is %d, current version is %d." % (platform_info['platform'], min_os_version, os_version)
carb.log_error(message)
if self._module_notification_manager is not None:
self._module_notification_manager.post_notification(message, hide_after_timeout=False)
def on_startup(self):
self._settings = carb.settings.get_settings()
try:
self._module_viewport = importlib.import_module('omni.kit.viewport_legacy')
except ImportError:
self._module_viewport = None
try:
self._module_notification_manager = importlib.import_module('omni.kit.notification_manager')
except ImportError:
self._module_notification_manager = None
asyncio.ensure_future(self._compatibility_check())
def on_shutdown(self):
self._settings = None
| 7,626 | Python | 43.086705 | 173 | 0.64385 |
omniverse-code/kit/exts/omni.kit.compatibility_checker/omni/kit/compatibility_checker/tests/test_compatibility_checker.py | import inspect
import pathlib
import carb
import carb.settings
import carb.tokens
import omni.kit.app
import omni.kit.test
import omni.kit.compatibility_checker
class CompatibilityCheckerTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.acquire_settings_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
def __test_name(self) -> str:
return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}"
async def tearDown(self):
self._renderer = None
self._app_window_factory = None
self._settings = None
async def test_1_check_gpu(self):
supported_gpus = [
"*GeForce RTX ????*",
"*Quadro RTX ????*",
"*RTX ?????*",
"*TITAN RTX*"
]
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA GeForce RTX 2060 OC"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["GeForce RTX 2080 Ti"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA GeForce RTX 3080"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA Quadro RTX A6000"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["Quadro RTX 8000"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["RTX A6000"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["TITAN RTX"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA GeForce GTX 1060 OC"], supported_gpus)
self.assertTrue(gpu_good is not True)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA GeForce RTX 2060 OC", "Not NVIDIA not GeForce"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["Not NVIDIA not GeForce", "NVIDIA GeForce RTX 2060 OC"], supported_gpus)
self.assertTrue(gpu_good)
async def test_2_check_drivers_blacklist(self):
driver_blacklist_ranges = [
["0.0", "100.0", "Minimum RTX req"],
["110.0", "111.0", "Bugs"],
["120.3", "120.5", "More bugs"],
]
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([95, 0], driver_blacklist_ranges)
self.assertTrue(driver_good is not True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([105, 0], driver_blacklist_ranges)
self.assertTrue(driver_good)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([110, 5], driver_blacklist_ranges)
self.assertTrue(driver_good is not True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([115, 0], driver_blacklist_ranges)
self.assertTrue(driver_good)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([120, 3], driver_blacklist_ranges)
self.assertTrue(driver_good is not True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([120, 4], driver_blacklist_ranges)
self.assertTrue(driver_good is not True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([120, 5], driver_blacklist_ranges)
self.assertTrue(driver_good is True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([130, 5], driver_blacklist_ranges)
self.assertTrue(driver_good)
| 4,128 | Python | 42.010416 | 143 | 0.67563 |
omniverse-code/kit/exts/omni.kit.compatibility_checker/omni/kit/compatibility_checker/tests/__init__.py | from .test_compatibility_checker import *
| 42 | Python | 20.49999 | 41 | 0.809524 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/config/extension.toml | [package]
version = "1.0.3"
authors = ["NVIDIA"]
title = "Omni.UI Style Documentation"
description="The interactive documentation for omni.ui style"
readme = "docs/README.md"
repository = ""
category = "Documentation"
keywords = ["ui", "style", "docs", "documentation"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.kit.documentation.builder" = {}
[[python.module]]
name = "omni.kit.documentation.ui.style"
[documentation]
pages = [
"docs/overview.md",
"docs/styling.md",
"docs/shades.md",
"docs/fonts.md",
"docs/units.md",
"docs/shapes.md",
"docs/line.md",
"docs/buttons.md",
"docs/sliders.md",
"docs/widgets.md",
"docs/containers.md",
"docs/window.md",
"docs/CHANGELOG.md",
]
args = []
menu = "Help/API/Omni.UI Style"
title = "Omni.UI Style Documentation"
| 892 | TOML | 21.324999 | 61 | 0.653587 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/omni/kit/documentation/ui/style/ui_style_docs_window.py | # Copyright (c) 2018-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.
#
__all__ = ["UIStyleDocsWindow"]
from omni.kit.documentation.builder import DocumentationBuilderWindow
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
DOCS_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("docs")
PAGES = ["overview.md", "styling.md", "shades.md", "fonts.md", "units.md", "shapes.md", "line.md", "buttons.md",
"sliders.md", "widgets.md", "containers.md", "window.md"]
class UIStyleDocsWindow(DocumentationBuilderWindow):
"""The window with the documentation"""
def __init__(self, title: str, **kwargs):
filenames = [f"{DOCS_PATH.joinpath(page_source)}" for page_source in PAGES]
super().__init__(title, filenames=filenames, **kwargs)
| 1,149 | Python | 43.230768 | 112 | 0.733681 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/styling.md | # The Style Sheet Syntax
omni.ui Style Sheet rules are almost identical to those of HTML CSS. It applies to the style of all omni ui elements.
Style sheets consist of a sequence of style rules. A style rule is made up of a selector and a declaration. The selector specifies which widgets are affected by the rule. The declaration specifies which properties should be set on the widget. For example:
```execute 200
## Double comment means hide from shippet
from omni.ui import color as cl
##
with ui.VStack(width=0, style={"Button": {"background_color": cl("#097eff")}}):
ui.Button("Style Example")
```
In the above style rule, Button is the selector, and {"background_color": cl("#097eff")} is the declaration. The rule specifies that Button should use blue as its background color.
## Selector
There are three types of selectors, type Selector, name Selector and state Selector They are structured as:
Type Selector :: Name Selector : State Selector
e.g.,Button::okButton:hovered
### Type Selector
where `Button` is the type selector, which matches the ui.Button's type.
### Name Selector
`okButton` is the type selector, which selects all Button instances whose object name is okButton. It separates from the type selector with `::`.
### State Selector
`hovered` is the state selector, which by itself matches all Button instances whose state is hovered. It separates from the other selectors with `:`.
When type, name and state selector are used together, it defines the style of all Button typed instances named as `okButton` and in hovered, while `Button:hovered` defines the style of all Button typed instances which are in hovered states.
These are the states recognized by omni.ui:
* hovered : the mouse in the widget area
* pressed : the mouse is pressing in the widget area
* selected : the widget is selected
* disabled : the widget is disabled
* checked : the widget is checked
* drop : the rectangle is accepting a drop. For example,
style = {"Rectangle:drop" : {"background_color": cl.blue}} meaning if the drop is acceptable, the rectangle is blue.
## Style Override
### Omit the selector
It's possible to omit the selector and override the property in all the widget types.
In this example, the style is set to VStack. The style will be propagated to all the widgets in VStack including VStack itself. Since only `background_color` is in the style, only the widgets which have `background_color` as the style will have the background color set. For VStack and Label which don't have `background_color`, the style is ignored. Button and FloatField get the blue background color.
```execute 200
from omni.ui import color as cl
with ui.VStack(width=400, style={"background_color": cl("#097eff")}, spacing=5):
ui.Button("One")
ui.Button("Two")
ui.FloatField()
ui.Label("Label doesn't have background_color style")
```
### Style overridden with name and state selector
In this example, we set the "Button" style for all the buttons, then override different buttons with name selector style, e.g. "Button::one" and "Button::two". Furthermore, the we also set different style for Button::one when pressed or hovered, e.g. "Button::one:hovered" and "Button::one:pressed", which will override "Button::one" style when button is pressed or hovered.
```execute 200
from omni.ui import color as cl
style1 = {
"Button": {"border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0},
"Button::one": {
"background_color": cl("#097eff"),
"background_gradient_color": cl("#6db2fa"),
"border_color": cl("#1d76fd"),
},
"Button.Label::one": {"color": cl.white},
"Button::one:hovered": {"background_color": cl("#006eff"), "background_gradient_color": cl("#5aaeff")},
"Button::one:pressed": {"background_color": cl("#6db2fa"), "background_gradient_color": cl("#097eff")},
"Button::two": {"background_color": cl.white, "border_color": cl("#B1B1B1")},
"Button.Label::two": {"color": cl("#272727")},
"Button::three:hovered": {
"background_color": cl("#006eff"),
"background_gradient_color": cl("#5aaeff"),
"border_color": cl("#1d76fd"),
},
"Button::four:pressed": {
"background_color": cl("#6db2fa"),
"background_gradient_color": cl("#097eff"),
"border_color": cl("#1d76fd"),
},
}
with ui.HStack(style=style1):
ui.Button("One", name="one")
ui.Button("Two", name="two")
ui.Button("Three", name="three")
ui.Button("Four", name="four")
ui.Button("Five", name="five")
```
### Style override to different levels of the widgets
It's possible to assign any style override to any level of the widgets. It can be assigned to both parents and children at the same time.
In this example, we have style_system which will be propagated to all buttons, but buttons with its own style will override the style_system.
```execute 200
from omni.ui import color as cl
style_system = {
"Button": {
"background_color": cl("#E1E1E1"),
"border_color": cl("#ADADAD"),
"border_width": 0.5,
"border_radius": 3.0,
"margin": 5.0,
"padding": 5.0,
},
"Button.Label": {
"color": cl.black,
},
"Button:hovered": {
"background_color": cl("#e5f1fb"),
"border_color": cl("#0078d7"),
},
"Button:pressed": {
"background_color": cl("#cce4f7"),
"border_color": cl("#005499"),
"border_width": 1.0
},
}
with ui.HStack(style=style_system):
ui.Button("One")
ui.Button("Two", style={"color": cl("#AAAAAA")})
ui.Button("Three", style={"background_color": cl("#097eff"), "background_gradient_color": cl("#6db2fa")})
ui.Button(
"Four", style={":hovered": {"background_color": cl("#006eff"), "background_gradient_color": cl("#5aaeff")}}
)
ui.Button(
"Five",
style={"Button:pressed": {"background_color": cl("#6db2fa"), "background_gradient_color": cl("#097eff")}},
)
```
### Customize the selector type using style_type_name_override
What if the user has a customized widget which is not a standard omni.ui one. How to define that Type Selector? In this case, We can use `style_type_name_override` to override the type name. `name` attribute is the Name Selector and State Selector can be added as usual.
Another use case is when we have a giant list of the same typed widgets, for example `Button`, but some of the Buttons are in the main window, and some of the Buttons are in the pop-up window, which we want to differentiate for easy look-up. Instead of calling all of them the same Type Selector as `Button` and only have different Name Selectors, we can override the type name for the main window buttons as `WindowButton` and the pop-up window buttons as `PopupButton`. This groups the style-sheet into categories and makes the change of the look or debug much easier.
Here is an example where we use `style_type_name_override` to override the style type name.
```execute 200
from omni.ui import color as cl
style={
"WindowButton::one": {"background_color": cl("#006eff")},
"WindowButton::one:hovered": {"background_color": cl("#006eff"), "background_gradient_color": cl("#FFAEFF")},
"PopupButton::two": {"background_color": cl("#6db2fa")},
"PopupButton::two:hovered": {"background_color": cl("#6db2fa"), "background_gradient_color": cl("#097eff")},
}
with ui.HStack(width=400, style=style, spacing=5):
ui.Button("Open", style_type_name_override="WindowButton", name="one")
ui.Button("Save", style_type_name_override="PopupButton", name="two")
```
### Default style override
From the above examples, we know that if we want to propagate the style to all children, we just need to set the style to the parent widget, but this rule doesn't apply to windows. The style set to the window will not propagate to its widgets. If we want to propagate the style to ui.Window and their widgets, we should set the default style with `ui.style.default`.
```python
from omni.ui import color as cl
ui.style.default = {
"background_color": cl.blue,
"border_radius": 10,
"border_width": 5,
"border_color": cl.red,
}
```
## Debug Color
All shapes or widgets can be styled to use a debug color that enables you to visualize their frame. It is very useful when debugging complicated ui layout with overlaps.
Here we use red as the debug_color to indicate the label widget:
```execute 200
from omni.ui import color as cl
style = {"background_color": cl("#DDDD00"), "color": cl.white, "debug_color":cl("#FF000055")}
ui.Label("Label with Debug", width=200, style=style)
```
If several widgets are adjacent, we can use the `debug_color` in the `hovered` state to differentiate the widget with others.
```execute 200
from omni.ui import color as cl
style = {
"Label": {"padding": 3, "background_color": cl("#DDDD00"),"color": cl.white},
"Label:hovered": {"debug_color": cl("#00FFFF55")},}
with ui.HStack(width=500, style=style):
ui.Label("Label 1", width=50)
ui.Label("Label 2")
ui.Label("Label 3", width=100, alignment=ui.Alignment.CENTER)
ui.Spacer()
ui.Label("Label 3", width=50)
```
## Visibility
This property holds whether the shape or widget is visible. Invisible shape or widget is not rendered, and it doesn't take part in the layout. The layout skips it.
In the following example, click the button from one to five to hide itself. The `Visible all` button brings them all back.
```execute 200
def invisible(button):
button.visible = False
def visible(buttons):
for button in buttons:
button.visible = True
buttons = []
with ui.HStack():
for n in ["One", "Two", "Three", "Four", "Five"]:
button = ui.Button(n, width=0)
button.set_clicked_fn(lambda b=button: invisible(b))
buttons.append(button)
ui.Spacer()
button = ui.Button("Visible all", width=0)
button.set_clicked_fn(lambda b=buttons: visible(b))
``` | 9,962 | Markdown | 43.878378 | 570 | 0.691929 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/widgets.md | # Widgets
## Label
Labels are used everywhere in omni.ui. They are text only objects.
Here is a list of styles you can customize on Label:
> color (color): the color of the text
> font_size (float): the size of the text
> margin (float): the distance between the label and the parent widget defined boundary
> margin_width (float): the width distance between the label and the parent widget defined boundary
> margin_height (float): the height distance between the label and the parent widget defined boundary
> alignment (enum): defines how the label is positioned in the parent defined space. There are 9 alignments supported which are quite self-explanatory.
* ui.Alignment.LEFT_CENTER
* ui.Alignment.LEFT_TOP
* ui.Alignment.LEFT_BOTTOM
* ui.Alignment.RIGHT_CENTER
* ui.Alignment.RIGHT_TOP
* ui.Alignment.RIGHT_BOTTOM
* ui.Alignment.CENTER
* ui.Alignment.CENTER_TOP
* ui.Alignment.CENTER_BOTTOM
Here are a few examples of labels:
```execute 200
from omni.ui import color as cl
ui.Label("this is a simple label", style={"color":cl.red, "margin": 5})
```
```execute 200
from omni.ui import color as cl
ui.Label("label with alignment", style={"color":cl.green, "margin": 5}, alignment=ui.Alignment.CENTER)
```
Notice that alignment could be either a property or a style.
```execute 200
from omni.ui import color as cl
label_style = {
"Label": {"font_size": 20, "color": cl.blue, "alignment":ui.Alignment.RIGHT, "margin_height": 20}
}
ui.Label("Label with style", style=label_style)
```
When the text of the Label is too long, it can be elided by `...`:
```execute 200
from omni.ui import color as cl
ui.Label(
"Label can be elided: Lorem ipsum dolor "
"sit amet, consectetur adipiscing elit, sed do "
"eiusmod tempor incididunt ut labore et dolore "
"magna aliqua. Ut enim ad minim veniam, quis "
"nostrud exercitation ullamco laboris nisi ut "
"aliquip ex ea commodo consequat. Duis aute irure "
"dolor in reprehenderit in voluptate velit esse "
"cillum dolore eu fugiat nulla pariatur. Excepteur "
"sint occaecat cupidatat non proident, sunt in "
"culpa qui officia deserunt mollit anim id est "
"laborum.",
style={"color":cl.white},
elided_text=True,
)
```
## CheckBox
A CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are typically used to represent features in an application that can be enabled or disabled without affecting others.
The checkbox is implemented using the model-delegate-view pattern. The model is the central component of this system. It is the application's dynamic data structure independent of the widget. It directly manages the data, logic and rules of the checkbox. If the model is not specified, the simple one is created automatically when the object is constructed.
Here is a list of styles you can customize on Line:
> color (color): the color of the tick
> background_color (color): the background color of the check box
> font_size: the size of the tick
> border_radius (float): the radius of the corner angle if the user wants to round the check box.
Default checkbox
```execute 200
with ui.HStack(width=0, spacing=5):
ui.CheckBox().model.set_value(True)
ui.CheckBox()
ui.Label("Default")
```
Disabled checkbox:
```execute 200
with ui.HStack(width=0, spacing=5):
ui.CheckBox(enabled=False).model.set_value(True)
ui.CheckBox(enabled=False)
ui.Label("Disabled")
```
In the following example, the models of two checkboxes are connected, and if one checkbox is changed, it makes another checkbox change as well.
```execute 200
from omni.ui import color as cl
with ui.HStack(width=0, spacing=5):
# Create two checkboxes
style = {"CheckBox":{
"color": cl.white, "border_radius": 0, "background_color": cl("#ff5555"), "font_size": 30}}
first = ui.CheckBox(style=style)
second = ui.CheckBox(style=style)
# Connect one to another
first.model.add_value_changed_fn(lambda a, b=second: b.model.set_value(not a.get_value_as_bool()))
second.model.add_value_changed_fn(lambda a, b=first: b.model.set_value(not a.get_value_as_bool()))
# Set the first one to True
first.model.set_value(True)
ui.Label("One of two")
```
In the following example, that is a bit more complicated, only one checkbox can be enabled.
```execute 200
from omni.ui import color as cl
style = {"CheckBox":{
"color": cl("#ff5555"), "border_radius": 5, "background_color": cl(0.35), "font_size": 20}}
with ui.HStack(width=0, spacing=5):
# Create two checkboxes
first = ui.CheckBox(style=style)
second = ui.CheckBox(style=style)
third = ui.CheckBox(style=style)
def like_radio(model, first, second):
"""Turn on the model and turn off two checkboxes"""
if model.get_value_as_bool():
model.set_value(True)
first.model.set_value(False)
second.model.set_value(False)
# Connect one to another
first.model.add_value_changed_fn(lambda a, b=second, c=third: like_radio(a, b, c))
second.model.add_value_changed_fn(lambda a, b=first, c=third: like_radio(a, b, c))
third.model.add_value_changed_fn(lambda a, b=first, c=second: like_radio(a, b, c))
# Set the first one to True
first.model.set_value(True)
ui.Label("Almost like radio box")
```
## ComboBox
The ComboBox widget is a combination of a button and a drop-down list. A ComboBox is a selection widget that displays the current item and can pop up a list of selectable items.
Here is a list of styles you can customize on ComboBox:
> color (color): the color of the combo box text and the arrow of the drop-down button
> background_color (color): the background color of the combo box
> secondary_color (color): the color of the drop-down button's background
> selected_color (color): the selected highlight color of option items
> secondary_selected_color (color): the color of the option item text
> font_size (float): the size of the text
> border_radius (float): the border radius if the user wants to round the ComboBox
> padding (float): the overall padding of the ComboBox. If padding is defined, padding_height and padding_width will have no effects.
> padding_height (float): the width padding of the drop-down list
> padding_width (float): the height padding of the drop-down list
> secondary_padding (float): the height padding between the ComboBox and options
Default ComboBox:
```execute 200
ui.ComboBox(1, "Option 1", "Option 2", "Option 3")
```
ComboBox with style
```execute 200
from omni.ui import color as cl
style={"ComboBox":{
"color": cl.red,
"background_color": cl(0.15),
"secondary_color": cl("#1111aa"),
"selected_color": cl.green,
"secondary_selected_color": cl.white,
"font_size": 15,
"border_radius": 20,
"padding_height": 2,
"padding_width": 20,
"secondary_padding": 30,
}}
with ui.VStack():
ui.ComboBox(1, "Option 1", "Option 2", "Option 3", style=style)
ui.Spacer(height=20)
```
The following example demonstrates how to add items to the ComboBox.
```execute 200
editable_combo = ui.ComboBox()
ui.Button(
"Add item to combo",
clicked_fn=lambda m=editable_combo.model: m.append_child_item(
None, ui.SimpleStringModel("Hello World")),
)
```
The minimal model implementation to have more flexibility of the data. It requires holding the value models and reimplementing two methods: `get_item_children` and `get_item_value_model`.
```execute 200
class MinimalItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = ui.SimpleStringModel(text)
class MinimalModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(
lambda a: self._item_changed(None))
self._items = [
MinimalItem(text)
for text in ["Option 1", "Option 2"]
]
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
self._minimal_model = MinimalModel()
with ui.VStack():
ui.ComboBox(self._minimal_model, style={"font_size": 22})
ui.Spacer(height=10)
```
The example of communication between widgets. Type anything in the field and it will appear in the combo box.
```execute 200
editable_combo = None
class StringModel(ui.SimpleStringModel):
'''
String Model activated when editing is finished.
Adds item to combo box.
'''
def __init__(self):
super().__init__("")
def end_edit(self):
combo_model = editable_combo.model
# Get all the options ad list of strings
all_options = [
combo_model.get_item_value_model(child).as_string
for child in combo_model.get_item_children()
]
# Get the current string of this model
fieldString = self.as_string
if fieldString:
if fieldString in all_options:
index = all_options.index(fieldString)
else:
# It's a new string in the combo box
combo_model.append_child_item(
None,
ui.SimpleStringModel(fieldString)
)
index = len(all_options)
combo_model.get_item_value_model().set_value(index)
self._field_model = StringModel()
def combo_changed(combo_model, item):
all_options = [
combo_model.get_item_value_model(child).as_string
for child in combo_model.get_item_children()
]
current_index = combo_model.get_item_value_model().as_int
self._field_model.as_string = all_options[current_index]
with ui.HStack():
ui.StringField(self._field_model)
editable_combo = ui.ComboBox(width=0, arrow_only=True)
editable_combo.model.add_item_changed_fn(combo_changed)
```
## TreeView
TreeView is a widget that presents a hierarchical view of information. Each item can have a number of subitems. An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if any exist, and collapsed to hide subitems.
TreeView can be used in file manager applications, where it allows the user to navigate the file system directories. They are also used to present hierarchical data, such as the scene object hierarchy.
TreeView uses a model-delegate-view pattern to manage the relationship between data and the way it is presented. The separation of functionality gives developers greater flexibility to customize the presentation of items and provides a standard interface to allow a wide range of data sources to be used with other widgets.
Here is a list of styles you can customize on TreeView:
> background_color (color): the background color of the TreeView
> background_selected_color (color): the hover color of the TreeView selected item. The actual selected color of the TreeView selected item should be defined by the "background_color" of "TreeView:selected"
> secondary_color (color): the TreeView slider color
Here is a list of styles you can customize on TreeView.Item:
> margin (float): the margin between TreeView items. This will be overridden by the value of margin_width or margin_height
> margin_width (float): the margin width between TreeView items
> margin_height (float): the margin height between TreeView items
> color (color): the text color of the TreeView items
> font_size (float): the text size of the TreeView items
The following example demonstrates how to make a single level tree appear like a simple list.
```execute 200
from omni.ui import color as cl
style = {"TreeView": {
"background_color": cl("#E0FFE0"),
"background_selected_color": cl("#FF905C"),
"secondary_color": cl("#00FF00"),
},
"TreeView:selected": {"background_color": cl("#888888")},
"TreeView.Item": {
"margin": 4,
"margin_width": 20,
"color": cl("#555555"),
"font_size": 15,
},
"TreeView.Item:selected": {"color": cl("#DD2825")},
}
class CommandItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
class CommandModel(ui.AbstractItemModel):
"""
Represents the list of commands registered in Kit.
It is used to make a single level tree appear like a simple list.
"""
def __init__(self):
super().__init__()
self._commands = []
try:
import omni.kit.commands
except ModuleNotFoundError:
return
omni.kit.commands.subscribe_on_change(self._commands_changed)
self._commands_changed()
def _commands_changed(self):
"""Called by subscribe_on_change"""
self._commands = []
import omni.kit.commands
for cmd_list in omni.kit.commands.get_commands().values():
for k in cmd_list.values():
self._commands.append(CommandItem(k.__name__))
self._item_changed(None)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._commands
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
if item and isinstance(item, CommandItem):
return item.name_model
with ui.ScrollingFrame(
height=400,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
style=style
):
self._command_model = CommandModel()
tree_view = ui.TreeView(self._command_model, root_visible=False, header_visible=False)
```
The following example demonstrates reordering with drag and drop. You can drag one item of the TreeView and move to the position you want to insert the item to.
```execute 200
from omni.ui import color as cl
class ListItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
def __repr__(self):
return f'"{self.name_model.as_string}"'
class ListModel(ui.AbstractItemModel):
"""
Represents the model for lists. It's very easy to initialize it
with any string list:
string_list = ["Hello", "World"]
model = ListModel(*string_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
self._children = [ListItem(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
class ListModelWithReordering(ListModel):
"""
Represents the model for the list with the ability to reorder the
list with drag and drop.
"""
def __init__(self, *args):
super().__init__(*args)
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
# As we don't do Drag and Drop to the operating system, we return the string.
return item.name_model.as_string
def drop_accepted(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called to highlight target when drag and drop."""
# If target_item is None, it's the drop to root. Since it's
# list model, we support reorganization of root only and we
# don't want to create a tree.
return not target_item and drop_location >= 0
def drop(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called when dropping something to the item."""
try:
source_id = self._children.index(source)
except ValueError:
# Not in the list. This is the source from another model.
return
if source_id == drop_location:
# Nothing to do
return
self._children.remove(source)
if drop_location > len(self._children):
# Drop it to the end
self._children.append(source)
else:
if source_id < drop_location:
# Because when we removed source, the array became shorter
drop_location = drop_location - 1
self._children.insert(drop_location, source)
self._item_changed(None)
with ui.ScrollingFrame(
height=150,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._list_model = ListModelWithReordering("Simplest", "List", "Model", "With", "Reordering")
tree_view = ui.TreeView(
self._list_model,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
drop_between_items=True,
)
```
The following example demonstrates the ability to edit TreeView items.
```execute 200
from omni.ui import color as cl
class FloatModel(ui.AbstractValueModel):
"""An example of custom float model that can be used for formatted string output"""
def __init__(self, value: float):
super().__init__()
self._value = value
def get_value_as_float(self):
"""Reimplemented get float"""
return self._value or 0.0
def get_value_as_string(self):
"""Reimplemented get string"""
# This string goes to the field.
if self._value is None:
return ""
# General format. This prints the number as a fixed-point
# number, unless the number is too large, in which case it
# switches to 'e' exponent notation.
return "{0:g}".format(self._value)
def set_value(self, value):
"""Reimplemented set"""
try:
value = float(value)
except ValueError:
value = None
if value != self._value:
# Tell the widget that the model is changed
self._value = value
self._value_changed()
class NameValueItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text, value):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.value_model = FloatModel(value)
def __repr__(self):
return f'"{self.name_model.as_string} {self.value_model.as_string}"'
class NameValueModel(ui.AbstractItemModel):
"""
Represents the model for name-value tables. It's very easy to initialize it
with any string-float list:
my_list = ["Hello", 1.0, "World", 2.0]
model = NameValueModel(*my_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
# ["Hello", 1.0, "World", 2.0"] -> [("Hello", 1.0), ("World", 2.0)]
regrouped = zip(*(iter(args),) * 2)
self._children = [NameValueItem(*t) for t in regrouped]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 2
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel for the first column
and SimpleFloatModel for the second column.
"""
return item.value_model if column_id == 1 else item.name_model
class EditableDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def __init__(self):
super().__init__()
self.subscription = None
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
stack = ui.ZStack(height=20)
with stack:
value_model = model.get_item_value_model(item, column_id)
label = ui.Label(value_model.as_string)
if column_id == 1:
field = ui.FloatField(value_model, visible=False)
else:
field = ui.StringField(value_model, visible=False)
# Start editing when double clicked
stack.set_mouse_double_clicked_fn(lambda x, y, b, m, f=field, l=label: self.on_double_click(b, f, l))
def on_double_click(self, button, field, label):
"""Called when the user double-clicked the item in TreeView"""
if button != 0:
return
# Make Field visible when double clicked
field.visible = True
field.focus_keyboard()
# When editing is finished (enter pressed of mouse clicked outside of the viewport)
self.subscription = field.model.subscribe_end_edit_fn(
lambda m, f=field, l=label: self.on_end_edit(m, f, l)
)
def on_end_edit(self, model, field, label):
"""Called when the user is editing the item and pressed Enter or clicked outside of the item"""
field.visible = False
label.text = model.as_string
self.subscription = None
with ui.ScrollingFrame(
height=100,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
style={"Field": {"background_color": cl.black}},
):
self._name_value_model = NameValueModel("First", 0.2, "Second", 0.3, "Last", 0.4)
self._name_value_delegate = EditableDelegate()
tree_view = ui.TreeView(
self._name_value_model,
delegate=self._name_value_delegate,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
)
```
This is an example of async filling the TreeView model. It's collecting only as many as it's possible of USD prims for 0.016s and waits for the next frame, so the UI is not locked even if the USD Stage is extremely big.
To play with it, create several materials in the stage or open a stage which contains materials, click "Traverse All" or "Stop Traversing".
```execute 200
import asyncio
import time
from omni.ui import color as cl
class ListItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
def __repr__(self):
return f'"{self.name_model.as_string}"'
class ListModel(ui.AbstractItemModel):
"""
Represents the model for lists. It's very easy to initialize it
with any string list:
string_list = ["Hello", "World"]
model = ListModel(*string_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
self._children = [ListItem(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
class AsyncQueryModel(ListModel):
"""
This is an example of async filling the TreeView model. It's
collecting only as many as it's possible of USD prims for 0.016s
and waits for the next frame, so the UI is not locked even if the
USD Stage is extremely big.
"""
def __init__(self):
super().__init__()
self._stop_event = None
def destroy(self):
self.stop()
def stop(self):
"""Stop traversing the stage"""
if self._stop_event:
self._stop_event.set()
def reset(self):
"""Traverse the stage and keep materials"""
self.stop()
self._stop_event = asyncio.Event()
self._children.clear()
self._item_changed(None)
asyncio.ensure_future(self.__get_all(self._stop_event))
def __push_collected(self, collected):
"""Add given array to the model"""
for c in collected:
self._children.append(c)
self._item_changed(None)
async def __get_all(self, stop_event):
"""Traverse the stage portion at time, so it doesn't freeze"""
stop_event.clear()
start_time = time.time()
# The widget will be updated not faster than 60 times a second
update_every = 1.0 / 60.0
import omni.usd
from pxr import Usd
from pxr import UsdShade
context = omni.usd.get_context()
stage = context.get_stage()
if not stage:
return
# Buffer to keep the portion of the items before sending to the
# widget
collected = []
for p in stage.Traverse(
Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded)
):
if stop_event.is_set():
break
if p.IsA(UsdShade.Material):
# Collect materials only
collected.append(ListItem(str(p.GetPath())))
elapsed_time = time.time()
# Loop some amount of time so fps will be about 60FPS
if elapsed_time - start_time > update_every:
start_time = elapsed_time
# Append the portion and update the widget
if collected:
self.__push_collected(collected)
collected = []
# Wait one frame to let other tasks go
await omni.kit.app.get_app().next_update_async()
self.__push_collected(collected)
try:
import omni.usd
from pxr import Usd
usd_available = True
except ModuleNotFoundError:
usd_available = False
if usd_available:
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
style={"Field": {"background_color": cl.black}},
):
self._async_query_model = AsyncQueryModel()
ui.TreeView(
self._async_query_model,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
)
self._loaded_label = ui.Label("Press Button to Load Materials", name="text")
with ui.HStack():
ui.Button("Traverse All", clicked_fn=self._async_query_model.reset)
ui.Button("Stop Traversing", clicked_fn=self._async_query_model.stop)
def _item_changed(model, item):
if item is None:
count = len(model._children)
self._loaded_label.text = f"{count} Materials Traversed"
self._async_query_sub = self._async_query_model.subscribe_item_changed_fn(_item_changed)
``` | 28,899 | Markdown | 34.503685 | 357 | 0.641718 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/sliders.md | # Fields and Sliders
## Common Styling for Fields and Sliders
Here is a list of common style you can customize on Fields and Sliders:
> background_color (color): the background color of the field or slider
> border_color (color): the border color if the field or slider background has a border
> border_radius (float): the border radius if the user wants to round the field or slider
> border_width (float): the border width if the field or slider background has a border
> padding (float): the distance between the text and the border of the field or slider
> font_size (float): the size of the text in the field or slider
## Field
There are fields for string, float and int models.
Except the common style for Fields and Sliders, here is a list of styles you can customize on Field:
> color (color): the color of the text
> background_selected_color (color): the background color of the selected text
### StringField
The StringField widget is a one-line text editor. A field allows the user to enter and edit a single line of plain text. It's implemented using the model-delegate-view pattern and uses AbstractValueModel as the central component of the system.
The following example demonstrates how to connect a StringField and a Label. You can type anything into the StringField.
```execute 200
from omni.ui import color as cl
field_style = {
"Field": {
"background_color": cl(0.8),
"border_color": cl.blue,
"background_selected_color": cl.yellow,
"border_radius": 5,
"border_width": 1,
"color": cl.red,
"font_size": 20.0,
"padding": 5,
},
"Field:pressed": {"background_color": cl.white, "border_color": cl.green, "border_width": 2, "padding": 8},
}
def setText(label, text):
"""Sets text on the label"""
# This function exists because lambda cannot contain assignment
label.text = f"You wrote '{text}'"
with ui.HStack():
field = ui.StringField(style=field_style)
ui.Spacer(width=5)
label = ui.Label("", name="text")
field.model.add_value_changed_fn(lambda m, label=label: setText(label, m.get_value_as_string()))
ui.Spacer(width=10)
```
The following example demonstrates that the CheckBox's model decides the content of the Field. Click to edit and update the string field value also updates the value of the CheckBox. The field can only have one of the two options, either 'True' or 'False', because the model only supports those two possibilities.
```execute 200
from omni.ui import color as cl
with ui.HStack():
field = ui.StringField(width=100, style={"background_color": cl.black})
checkbox = ui.CheckBox(width=0)
field.model = checkbox.model
```
In this example, the field can have anything because the model accepts any string. The model returns bool for checkbox, and the checkbox is unchecked when the string is empty or 'False'.
```execute 200
from omni.ui import color as cl
with ui.HStack():
field = ui.StringField(width=100, style={"background_color": cl.black})
checkbox = ui.CheckBox(width=0)
checkbox.model = field.model
```
The Field widget doesn't keep the data due to the model-delegate-view pattern. However, there are two ways to track the state of the widget. It's possible to re-implement the AbstractValueModel. The second way is using the callbacks of the model. Here is a minimal example of callbacks. When you start editing the field, you will see "Editing is started", and when you finish editing by press `enter`, you will see "Editing is finished".
```execute 200
def on_value(label):
label.text = "Value is changed"
def on_begin(label):
label.text = "Editing is started"
def on_end(label):
label.text = "Editing is finished"
label = ui.Label("Nothing happened", name="text")
model = ui.StringField().model
model.add_value_changed_fn(lambda m, l=label: on_value(l))
model.add_begin_edit_fn(lambda m, l=label: on_begin(l))
model.add_end_edit_fn(lambda m, l=label: on_end(l))
```
### Multiline StringField
Property `multiline` of `StringField` allows users to press enter and create a new line. It's possible to finish editing with Ctrl-Enter.
```execute 200
from omni.ui import color as cl
import inspect
field_style = {
"Field": {
"background_color": cl(0.8),
"color": cl.black,
},
"Field:pressed": {"background_color": cl(0.8)},
}
field_callbacks = lambda: field_callbacks()
with ui.Frame(style=field_style, height=200):
model = ui.SimpleStringModel("hello \nworld \n")
field = ui.StringField(model, multiline=True)
```
### FloatField and IntField
The following example shows how string field, float field and int field interact with each other. All three fields share the same default FloatModel:
```execute 200
with ui.HStack(spacing=5):
ui.Label("FloatField")
ui.Label("IntField")
ui.Label("StringField")
with ui.HStack(spacing=5):
left = ui.FloatField()
center = ui.IntField()
right = ui.StringField()
center.model = left.model
right.model = left.model
ui.Spacer(height=5)
```
## MultiField
MultiField widget groups the widgets that have multiple similar widgets to represent each item in the model. It's handy to use them for arrays and multi-component data like float3, matrix, and color.
MultiField is using `Field` as the Type Selector. Therefore, the list of styless we can customize on MultiField is the same as Field
### MultiIntField
Each of the field value could be changed by editing
```execute 200
from omni.ui import color as cl
field_style = {
"Field": {
"background_color": cl(0.8),
"border_color": cl.blue,
"border_radius": 5,
"border_width": 1,
"color": cl.red,
"font_size": 20.0,
"padding": 5,
},
"Field:pressed": {"background_color": cl.white, "border_color": cl.green, "border_width": 2, "padding": 8},
}
ui.MultiIntField(0, 0, 0, 0, style=field_style)
```
### MultiFloatField
Use MultiFloatField to construct a matrix field:
```execute 200
args = [1.0 if i % 5 == 0 else 0.0 for i in range(16)]
ui.MultiFloatField(*args, width=ui.Percent(50), h_spacing=5, v_spacing=2)
```
### MultiFloatDragField
Each of the field value could be changed by dragging
```execute 200
ui.MultiFloatDragField(0.0, 0.0, 0.0, 0.0)
```
## Sliders
The Sliders are more like a traditional slider that can be dragged and snapped where you click. The value of the slider can be shown on the slider or not, but can not be edited directly by clicking.
Except the common style for Fields and Sliders, here is a list of styles you can customize on ProgressBar:
> color (color): the color of the text
> secondary_color (color): the color of the handle in `ui.SliderDrawMode.HANDLE` draw_mode or the background color of the left portion of the slider in `ui.SliderDrawMode.DRAG` draw_mode
> secondary_selected_color (color): the color of the handle when selected, not useful when the draw_mode is FILLED since there is no handle drawn.
> draw_mode (enum): defines how the slider handle is drawn. There are three types of draw_mode.
* ui.SliderDrawMode.HANDLE: draw the handle as a knob at the slider position
* ui.SliderDrawMode.DRAG: the same as `ui.SliderDrawMode.HANDLE` for now
* ui.SliderDrawMode.FILLED: the handle is eventually the boundary between the `secondary_color` and `background_color`
Sliders with different draw_mode:
```execute 200
from omni.ui import color as cl
with ui.VStack(spacing=5):
ui.FloatSlider(style={"background_color": cl(0.8),
"secondary_color": cl(0.6),
"color": cl(0.1),
"draw_mode": ui.SliderDrawMode.HANDLE}
).model.set_value(0.5)
ui.FloatSlider(style={"background_color": cl(0.8),
"secondary_color": cl(0.6),
"color": cl(0.1),
"draw_mode": ui.SliderDrawMode.DRAG}
).model.set_value(0.5)
ui.FloatSlider(style={"background_color": cl(0.8),
"secondary_color": cl(0.6),
"color": cl(0.1),
"draw_mode": ui.SliderDrawMode.FILLED}
).model.set_value(0.5)
```
### FloatSlider
Default slider whose range is between 0 to 1:
```execute 200
ui.FloatSlider()
```
With defined Min/Max whose range is between min to max:
```execute 200
ui.FloatSlider(min=0, max=10)
```
With defined Min/Max from the model. Notice the model allows the value range between 0 to 100, but the FloatSlider has a more strict range between 0 to 10.
```execute 200
model = ui.SimpleFloatModel(1.0, min=0, max=100)
ui.FloatSlider(model, min=0, max=10)
```
With styles and rounded slider:
```execute 200
from omni.ui import color as cl
with ui.HStack(width=200):
ui.Spacer(width=20)
with ui.VStack():
ui.Spacer(height=5)
ui.FloatSlider(
min=-180,
max=180,
style={
"color": cl.blue,
"background_color": cl(0.8),
"draw_mode": ui.SliderDrawMode.HANDLE,
"secondary_color": cl.red,
"secondary_selected_color": cl.green,
"font_size": 20,
"border_width": 3,
"border_color": cl.black,
"border_radius": 10,
"padding": 10,
}
)
ui.Spacer(height=5)
ui.Spacer(width=20)
```
Filled mode slider with style:
```execute 200
from omni.ui import color as cl
with ui.HStack(width=200):
ui.Spacer(width=20)
with ui.VStack():
ui.Spacer(height=5)
ui.FloatSlider(
min=-180,
max=180,
style={
"color": cl.blue,
"background_color": cl(0.8),
"draw_mode": ui.SliderDrawMode.FILLED,
"secondary_color": cl.red,
"font_size": 20,
"border_radius": 10,
"padding": 10,
}
)
ui.Spacer(height=5)
ui.Spacer(width=20)
```
Transparent background:
```execute 200
from omni.ui import color as cl
with ui.HStack(width=200):
ui.Spacer(width=20)
with ui.VStack():
ui.Spacer(height=5)
ui.FloatSlider(
min=-180,
max=180,
style={
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl.transparent,
"color": cl.red,
"border_width": 1,
"border_color": cl.white,
}
)
ui.Spacer(height=5)
ui.Spacer(width=20)
```
Slider with transparent value. Notice the use of `step` attribute
```execute 200
from omni.ui import color as cl
with ui.HStack():
# a separate float field
field = ui.FloatField(height=15, width=50)
# a slider using field's model
ui.FloatSlider(
min=0,
max=20,
step=0.25,
model=field.model,
style={
"color":cl.transparent,
"background_color": cl(0.3),
"draw_mode": ui.SliderDrawMode.HANDLE}
)
# default value
field.model.set_value(12.0)
```
### IntSlider
Default slider whose range is between 0 to 100:
```execute 200
ui.IntSlider()
```
With defined Min/Max whose range is between min to max. Note that the handle width is much wider.
```execute 200
ui.IntSlider(min=0, max=20)
```
With style:
```execute 200
from omni.ui import color as cl
with ui.HStack(width=200):
ui.Spacer(width=20)
with ui.VStack():
ui.Spacer(height=5)
ui.IntSlider(
min=0,
max=20,
style={
"background_color": cl("#BBFFBB"),
"color": cl.purple,
"draw_mode": ui.SliderDrawMode.HANDLE,
"secondary_color": cl.green,
"secondary_selected_color": cl.red,
"font_size": 14.0,
"border_width": 3,
"border_color": cl.green,
"padding": 5,
}
).model.set_value(4)
ui.Spacer(height=5)
ui.Spacer(width=20)
```
## Drags
The Drags are very similar to Sliders, but more like Field in the way that they behave. You can double click to edit the value but they also have a mean to be 'Dragged' to increase or decrease the value.
Except the common style for Fields and Sliders, here is a list of styles you can customize on ProgressBar:
> color (color): the color of the text
> secondary_color (color): the left portion of the slider in `ui.SliderDrawMode.DRAG` draw_mode
### FloatDrag
Default float drag whose range is -inf and +inf
```execute 200
ui.FloatDrag()
```
With defined Min/Max whose range is between min to max:
```execute 200
ui.FloatDrag(min=-10, max=10, step=0.1)
```
With styles and rounded shape:
```execute 200
from omni.ui import color as cl
with ui.HStack(width=200):
ui.Spacer(width=20)
with ui.VStack():
ui.Spacer(height=5)
ui.FloatDrag(
min=-180,
max=180,
style={
"color": cl.blue,
"background_color": cl(0.8),
"secondary_color": cl.red,
"font_size": 20,
"border_width": 3,
"border_color": cl.black,
"border_radius": 10,
"padding": 10,
}
)
ui.Spacer(height=5)
ui.Spacer(width=20)
```
### IntDrag
Default int drag whose range is -inf and +inf
```execute 200
ui.IntDrag()
```
With defined Min/Max whose range is between min to max:
```execute 200
ui.IntDrag(min=-10, max=10)
```
With styles and rounded slider:
```execute 200
from omni.ui import color as cl
with ui.HStack(width=200):
ui.Spacer(width=20)
with ui.VStack():
ui.Spacer(height=5)
ui.IntDrag(
min=-180,
max=180,
style={
"color": cl.blue,
"background_color": cl(0.8),
"secondary_color": cl.purple,
"font_size": 20,
"border_width": 4,
"border_color": cl.black,
"border_radius": 20,
"padding": 5,
}
)
ui.Spacer(height=5)
ui.Spacer(width=20)
```
## ProgressBar
A ProgressBar is a widget that indicates the progress of an operation.
Except the common style for Fields and Sliders, here is a list of styles you can customize on ProgressBar:
> color (color): the color of the progress bar indicating the progress value of the progress bar in the portion of the overall value
> secondary_color (color): the color of the text indicating the progress value
In the following example, it shows how to use ProgressBar and override the style of the overlay text.
```execute 200
from omni.ui import color as cl
class CustomProgressValueModel(ui.AbstractValueModel):
"""An example of custom float model that can be used for progress bar"""
def __init__(self, value: float):
super().__init__()
self._value = value
def set_value(self, value):
"""Reimplemented set"""
try:
value = float(value)
except ValueError:
value = None
if value != self._value:
# Tell the widget that the model is changed
self._value = value
self._value_changed()
def get_value_as_float(self):
return self._value
def get_value_as_string(self):
return "Custom Overlay"
with ui.VStack(spacing=5):
# Create ProgressBar
first = ui.ProgressBar()
# Range is [0.0, 1.0]
first.model.set_value(0.5)
second = ui.ProgressBar()
second.model.set_value(1.0)
# Overrides the overlay of ProgressBar
model = CustomProgressValueModel(0.8)
third = ui.ProgressBar(model)
third.model.set_value(0.1)
# Styling its color
fourth = ui.ProgressBar(style={"color": cl("#0000dd")})
fourth.model.set_value(0.3)
# Styling its border width
ui.ProgressBar(style={"border_width": 2, "border_color": cl("#dd0000"), "color": cl("#0000dd")}).model.set_value(0.7)
# Styling its border radius
ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000dd")}).model.set_value(0.6)
# Styling its background color
ui.ProgressBar(style={"border_radius": 10, "background_color": cl("#0000dd")}).model.set_value(0.6)
# Styling the text color
ui.ProgressBar(style={"ProgressBar":{"border_radius": 30, "secondary_color": cl("#00dddd"), "font_size": 20}}).model.set_value(0.6)
# Two progress bars in a row with padding
with ui.HStack():
ui.ProgressBar(style={"color": cl("#0000dd"), "padding": 100}).model.set_value(1.0)
ui.ProgressBar().model.set_value(0.0)
```
## Tooltip
All Widget can be augmented with a tooltip. It can take 2 forms, either a simple ui.Label or a callback when using the callback of `tooltip_fn=` or `widget.set_tooltip_fn()`. You can create the tooltip for any widget.
Except the common style for Fields and Sliders, here is a list of styles you can customize on Line:
> color (color): the color of the text of the tooltip.
> margin_width (float): the width distance between the tooltip content and the parent widget defined boundary
> margin_height (float): the height distance between the tooltip content and the parent widget defined boundary
Here is a simple label tooltip with style when you hover over a button:
```execute 200
from omni.ui import color as cl
tooltip_style = {
"Tooltip": {
"background_color": cl("#DDDD00"),
"color": cl(0.2),
"padding": 10,
"border_width": 3,
"border_color": cl.red,
"font_size": 20,
"border_radius": 10}}
ui.Button("Simple Label Tooltip", name="tooltip", width=200, tooltip="I am a text ToolTip", style=tooltip_style)
```
You can create a callback function as the tooltip where you can create any types of widgets you like in the tooltip and layout them. Make the tooltip very illustrative to have Image or Field or Label etc.
```execute 200
from omni.ui import color as cl
def create_tooltip():
with ui.VStack(width=200, style=tooltip_style):
with ui.HStack():
ui.Label("Fancy tooltip", width=150)
ui.IntField().model.set_value(12)
ui.Line(height=2, style={"color":cl.white})
with ui.HStack():
ui.Label("Anything is possible", width=150)
ui.StringField().model.set_value("you bet")
image_source = "resources/desktop-icons/omniverse_512.png"
ui.Image(
image_source,
width=200,
height=200,
alignment=ui.Alignment.CENTER,
style={"margin": 0},
)
tooltip_style = {
"Tooltip": {
"background_color": cl(0.2),
"border_width": 2,
"border_radius": 5,
"margin_width": 5,
"margin_height": 10
},
}
ui.Button("Callback function Tooltip", width=200, style=tooltip_style, tooltip_fn=create_tooltip)
```
You can define a fixed position for tooltip:
```execute 200
ui.Button("Fixed-position Tooltip", width=200, tooltip="Hello World", tooltip_offset_y=22)
```
You can also define a random position for tooltip:
```execute 200
import random
button = ui.Button("Random-position Tooltip", width=200, tooltip_offset_y=22)
def create_tooltip(button=button):
button.tooltip_offset_x = random.randint(0, 200)
ui.Label("Hello World")
button.set_tooltip_fn(create_tooltip)
``` | 20,428 | Markdown | 34.777583 | 437 | 0.609898 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/fonts.md | # Fonts
## Font style
It's possible to set different font types with the style. The style key 'font' should point to the font file, which allows packaging of the font to the extension. We support both TTF and OTF formats. All text-based widgets support custom fonts.
```execute 200
with ui.VStack():
ui.Label("Omniverse", style={"font":"${fonts}/OpenSans-SemiBold.ttf", "font_size": 40.0})
ui.Label("Omniverse", style={"font":"${fonts}/roboto_medium.ttf", "font_size": 40.0})
```
## Font size
It's possible to set the font size with the style.
Drag the following slider to change the size of the text.
```execute 200
def value_changed(label, value):
label.style = {"color": ui.color(0), "font_size": value.as_float}
slider = ui.FloatSlider(min=1.0, max=150.0)
slider.model.as_float = 10.0
label = ui.Label("Omniverse", style={"color": ui.color(0), "font_size": 7.0})
slider.model.add_value_changed_fn(partial(value_changed, label))
## Double comment means hide from shippet
ui.Spacer(height=30)
##
``` | 1,019 | Markdown | 35.42857 | 244 | 0.705594 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/containers.md | # Container widgets
Container widgets are used for grouping items. It's possible to add children to the container with Python's `with` statement. It's not possible to reparent items. Instead, it's necessary to remove the item and recreate a similar item under another parent.
## Stack
We have three main components: VStack, HStack, and ZStack.
Here is a list of styles you can customize on Stack:
> margin (float): the distance between the stack items and the parent widget defined boundary
> margin_width (float): the width distance between the stack items and the parent widget defined boundary
> margin_height (float): the height distance between the stack items and the parent widget defined boundary
It's possible to determine the direction of a stack with the property `direction`. Here is an example of a stack which is able to change its direction dynamically by clicking the button `Change`.
```execute 200
def rotate(dirs, stack, label):
dirs[0] = (dirs[0] + 1) % len(dirs[1])
stack.direction = dirs[1][dirs[0]]
label.text = str(stack.direction)
dirs = [
0,
[
ui.Direction.LEFT_TO_RIGHT,
ui.Direction.RIGHT_TO_LEFT,
ui.Direction.TOP_TO_BOTTOM,
ui.Direction.BOTTOM_TO_TOP,
],
]
stack = ui.Stack(ui.Direction.LEFT_TO_RIGHT, width=0, height=0, style={"margin_height": 5, "margin_width": 10})
with stack:
for name in ["One", "Two", "Three", "Four"]:
ui.Button(name)
ui.Spacer(height=100)
with ui.HStack():
ui.Label("Current direction is ", name="text", width=0)
label = ui.Label("", name="text")
button = ui.Button("Change")
button.set_clicked_fn(lambda d=dirs, s=stack, l=label: rotate(d, s, l))
rotate(dirs, stack, label)
```
### HStack
This class is used to construct horizontal layout objects.
The simplest use of the class is like this:
```execute 200
with ui.HStack(style={"margin": 10}):
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
```
### VStack
The VStack class lines up widgets vertically.
```execute 200
with ui.VStack(width=100.0, style={"margin": 5}):
with ui.VStack():
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
```
### ZStack
ZStack is a view that overlays its children, aligning them on top of each other. The later one is on top of the previous ones.
```execute 200
with ui.VStack(width=100.0, style={"margin": 5}):
with ui.ZStack():
ui.Button("Very Long Text to See How Big it Can Be", height=0)
ui.Button("Another\nMultiline\nButton", width=0)
```
### Layout
Here is an example of using combined HStack and VStack:
```execute 200
with ui.VStack():
for i in range(2):
with ui.HStack():
ui.Spacer(width=50)
with ui.VStack(height=0):
ui.Button("Left {}".format(i), height=0)
ui.Button("Vertical {}".format(i), height=50)
with ui.HStack(width=ui.Fraction(2)):
ui.Button("Right {}".format(i))
ui.Button("Horizontal {}".format(i), width=ui.Fraction(2))
ui.Spacer(width=50)
```
### Spacing
Spacing is a property of Stack. It defines the non-stretchable space in pixels between child items of the layout.
Here is an example that you can change the HStack spacing by a slider
```execute 200
from omni.ui import color as cl
SPACING = 5
def set_spacing(stack, spacing):
stack.spacing = spacing
ui.Spacer(height=SPACING)
spacing_stack = ui.HStack(style={"margin": 0})
with spacing_stack:
for name in ["One", "Two", "Three", "Four"]:
ui.Button(name)
ui.Spacer(height=SPACING)
with ui.HStack(spacing=SPACING):
with ui.HStack(width=100):
ui.Spacer()
ui.Label("spacing", width=0, name="text")
with ui.HStack(width=ui.Percent(20)):
field = ui.FloatField(width=50)
slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent})
# Link them together
slider.model = field.model
slider.model.add_value_changed_fn(
lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float()))
```
## Frame
Frame is a container that can keep only one child. Each child added to Frame overrides the previous one. This feature is used for creating dynamic layouts. The whole layout can be easily recreated with a simple callback.
Here is a list of styles you can customize on Frame:
> padding (float): the distance between the child widgets and the border of the button
In the following example, you can drag the IntDrag to change the slider value. The buttons are recreated each time the slider changes.
```execute 200
self._recreate_ui = ui.Frame(height=40, style={"Frame":{"padding": 5}})
def changed(model, recreate_ui=self._recreate_ui):
with recreate_ui:
with ui.HStack():
for i in range(model.get_value_as_int()):
ui.Button(f"Button #{i}")
model = ui.IntDrag(min=0, max=10).model
self._sub_recreate = model.subscribe_value_changed_fn(changed)
```
Another feature of Frame is the ability to clip its child. When the content of Frame is bigger than Frame itself, the exceeding part is not drawn if the clipping is on. There are two clipping types: `horizontal_clipping` and `vertical_clipping`.
Here is an example of vertical clipping.
```execute 200
with ui.Frame(vertical_clipping=True, height=20):
ui.Label("This should be clipped vertically. " * 10, word_wrap=True)
```
## CanvasFrame
CanvasFrame is the widget that allows the user to pan and zoom its children with a mouse. It has a layout that can be infinitely moved in any direction.
Here is a list of styles you can customize on CanvasFrame:
> background_color (color): the main color of the rectangle
Here is an example of a CanvasFrame, you can scroll the middle mouse to zoom the canvas and middle mouse move to pan in it (press CTRL to avoid scrolling the docs).
```execute 200
from omni.ui import color as cl
TEXT = (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
)
IMAGE = "resources/icons/ov_logo_square.png"
with ui.CanvasFrame(height=256, style={"CanvasFrame":{"background_color": cl("#aa4444")}}):
with ui.VStack(height=0, spacing=10):
ui.Label(TEXT, name="text", word_wrap=True)
ui.Button("Button")
ui.Image(IMAGE, width=128, height=128)
```
## ScrollingFrame
The ScrollingFrame class provides the ability to scroll onto other widgets. ScrollingFrame is used to display the contents of children widgets within a frame. If the widget exceeds the size of the frame, the frame can provide scroll bars so that the entire area of the child widget can be viewed by scrolling.
Here is a list of styles you can customize on ScrollingFrame:
> scrollbar_size (float): the width of the scroll bar
> secondary_color (color): the color the scroll bar
> background_color (color): the background color the scroll frame
Here is an example of a ScrollingFrame, you can scroll the middle mouse to scroll the frame.
```execute 200
from omni.ui import color as cl
with ui.HStack():
left_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style={"ScrollingFrame":{
"scrollbar_size":10,
"secondary_color": cl.red,
"background_color": cl("#4444dd")}}
)
with left_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Left {i}")
right_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style={"ScrollingFrame":{
"scrollbar_size":30,
"secondary_color": cl.blue,
"background_color": cl("#44dd44")}}
)
with right_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Right {i}")
# Synchronize the scroll position of two frames
def set_scroll_y(frame, y):
frame.scroll_y = y
left_frame.set_scroll_y_changed_fn(lambda y, frame=right_frame: set_scroll_y(frame, y))
right_frame.set_scroll_y_changed_fn(lambda y, frame=left_frame: set_scroll_y(frame, y))
```
## CollapsableFrame
CollapsableFrame is a frame widget that can hide or show its content. It has two states: expanded and collapsed. When it's collapsed, it looks like a button. If it's expanded, it looks like a button and a frame with the content. It's handy to group properties, and temporarily hide them to get more space for something else.
Here is a list of styles you can customize on Image:
> background_color (color): the background color of the CollapsableFrame widget
> secondary_color (color): the background color of the CollapsableFrame's header
> border_radius (float): the border radius if user wants to round the CollapsableFrame
> border_color (color): the border color if the CollapsableFrame has a border
> border_width (float): the border width if the CollapsableFrame has a border
> padding (float): the distance between the header or the content to the border of the CollapsableFrame
> margin (float): the distance between the CollapsableFrame and other widgets
Here is a default `CollapsableFrame` example:
```execute 200
with ui.CollapsableFrame("Header"):
with ui.VStack(height=0):
ui.Button("Hello World")
ui.Button("Hello World")
```
It's possible to use a custom header.
```execute 200
from omni.ui import color as cl
def custom_header(collapsed, title):
with ui.HStack():
with ui.ZStack(width=30):
ui.Circle(name="title")
with ui.HStack():
ui.Spacer()
align = ui.Alignment.V_CENTER
ui.Line(name="title", width=6, alignment=align)
ui.Spacer()
if collapsed:
with ui.VStack():
ui.Spacer()
align = ui.Alignment.H_CENTER
ui.Line(name="title", height=6, alignment=align)
ui.Spacer()
ui.Label(title, name="title")
style = {
"CollapsableFrame": {
"background_color": cl(0.5),
"secondary_color": cl("#CC211B"),
"border_radius": 10,
"border_color": cl.blue,
"border_width": 2,
},
"CollapsableFrame:hovered": {"secondary_color": cl("#FF4321")},
"CollapsableFrame:pressed": {"secondary_color": cl.red},
"Label::title": {"color": cl.white},
"Circle::title": {
"color": cl.yellow,
"background_color": cl.transparent,
"border_color": cl(0.9),
"border_width": 0.75,
},
"Line::title": {"color": cl(0.9), "border_width": 1},
}
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer(width=5)
with ui.CollapsableFrame("Header", build_header_fn=custom_header, style=style):
with ui.VStack(height=0):
ui.Button("Hello World")
ui.Button("Hello World")
ui.Spacer(width=5)
ui.Spacer(height=5)
```
This example demonstrates how padding and margin work in the collapsable frame.
```execute 200
from omni.ui import color as cl
style = {
"CollapsableFrame": {
"border_color": cl("#005B96"),
"border_radius": 4,
"border_width": 2,
"padding": 0,
"margin": 0,
}
}
frame = ui.CollapsableFrame("Header", style=style)
with frame:
with ui.VStack(height=0):
ui.Button("Hello World")
ui.Button("Hello World")
def set_style(field, model, style=style, frame=frame):
frame_style = style["CollapsableFrame"]
frame_style[field] = model.get_value_as_float()
frame.set_style(style)
with ui.HStack():
ui.Label("Padding:", width=ui.Percent(10), name="text")
model = ui.FloatSlider(min=0, max=50).model
model.add_value_changed_fn(lambda m: set_style("padding", m))
with ui.HStack():
ui.Label("Margin:", width=ui.Percent(10), name="text")
model = ui.FloatSlider(min=0, max=50).model
model.add_value_changed_fn(lambda m: set_style("margin", m))
```
## Order in Stack and use of content_clipping
Due to Imgui, ScrollingFrame and CanvasFrame will create a new window, meaning if we have them in a ZStack, they don't respect the Stack order. To fix that we need to create a separate window, with the widget wrapped in a `ui.Frame(separate_window=True)` will fix the order issue. And if we also want the mouse input in the new separate window, we use `ui.HStack(content_clipping=True)` for that.
In the following example, you won't see the red rectangle.
```execute 200
from omni.ui import color as cl
with ui.ZStack():
ui.Rectangle(width=200, height=200, style={'background_color':cl.green})
with ui.CanvasFrame(width=150, height=150):
ui.Rectangle(style={'background_color':cl.blue})
ui.Rectangle(width=100, height=100, style={'background_color':cl.red})
```
With the use of `separate_window=True` or `content_clipping=True`, you will see the red rectangle.
```execute 200
from omni.ui import color as cl
with ui.ZStack():
ui.Rectangle(width=200, height=200, style={'background_color':cl.green})
with ui.CanvasFrame(width=150, height=150):
ui.Rectangle(style={'background_color':cl.blue})
with ui.Frame(separate_window=True):
ui.Rectangle(width=100, height=100, style={'background_color':cl.red})
```
```execute 200
from omni.ui import color as cl
with ui.ZStack():
ui.Rectangle(width=200, height=200, style={'background_color':cl.green})
with ui.CanvasFrame(width=150, height=150):
ui.Rectangle(style={'background_color':cl.blue})
with ui.HStack(content_clipping=True):
ui.Rectangle(width=100, height=100, style={'background_color':cl.red})
```
In the following example, you will see the button click action is captured on Button 1.
```execute 200
from functools import partial
def clicked(name):
print(f'clicked {name}')
with ui.ZStack():
b1 = ui.Button('Button 1')
b1.set_clicked_fn(partial(clicked, b1.text))
b2 = ui.Button('Button 2')
b2.set_clicked_fn(partial(clicked, b2.text))
```
With the use of `content_clipping=True`, you will see the button click action is now fixed and captured on Button 2.
```execute 200
from functools import partial
def clicked(name):
print(f'clicked {name}')
with ui.ZStack():
b1 = ui.Button('Button 1')
b1.set_clicked_fn(partial(clicked, b1.text))
with ui.VStack(content_clipping=1):
b2 = ui.Button('Button 2')
b2.set_clicked_fn(partial(clicked, b2.text))
```
## Grid
Grid is a container that arranges its child views in a grid. Depends on the direction the grid size grows with creating more children, we call it VGrid (grow in vertical direction) and HGrid (grow in horizontal direction)
There is currently no style you can customize on Grid.
### VGrid
VGrid has two modes for cell width:
- If the user sets column_count, the column width is computed from the grid width.
- If the user sets column_width, the column count is computed from the grid width.
VGrid also has two modes for height:
- If the user sets row_height, VGrid uses it to set the height for all the cells. It's the fast mode because it's considered that the cell height never changes. VGrid easily predicts which cells are visible.
- If the user sets nothing, VGrid computes the size of the children. This mode is slower than the previous one, but the advantage is that all the rows can be different custom sizes. VGrid still only draws visible items, but to predict it, it uses cache, which can be big if VGrid has hundreds of thousands of items.
Here is an example of VGrid:
```execute 200
from omni.ui import color as cl
with ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
with ui.VGrid(column_width=100, row_height=100):
for i in range(100):
with ui.ZStack():
ui.Rectangle(
style={
"border_color": cl.red,
"background_color": cl.white,
"border_width": 1,
"margin": 0,
}
)
ui.Label(f"{i}", style={"margin": 5})
```
### HGrid
HGrid works exactly like VGrid, but with swapped width and height.
```execute 200
from omni.ui import color as cl
with ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.HGrid(column_width=100, row_height=100):
for i in range(100):
with ui.ZStack():
ui.Rectangle(
style={
"border_color": cl.red,
"background_color": cl.white,
"border_width": 1,
"margin": 0,
}
)
ui.Label(f"{i}", style={"margin": 5})
```
## Placer
Placer enables you to place a widget precisely with offset. Placer's property `draggable` allows changing the position of the child widget by dragging it with the mouse.
There is currently no style you can customize on Placer.
Here is an example of 4 Placers. Two of them have fixed positions, each with a ui.Button as the child. You can see the buttons are moved to the exact place by the parent Placer, one at (100, 10) and the other at (200, 50). The third one is `draggable`, which has a Circle as the child, so that you can move the circle freely with mouse drag in the frame. The fourth one is also `draggable`, which has a ZStack as the child. The ZStack is composed of Rectangle and HStack and Label. This Placer is only draggable on the Y-axis, defined by `drag_axis=ui.Axis.Y`, so that you can only move the ZStack on the y-axis.
```execute 200
from omni.ui import color as cl
with ui.ScrollingFrame(
height=170,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.ZStack():
with ui.HStack():
for index in range(60):
ui.Line(width=10, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.LEFT)
with ui.VStack():
ui.Line(
height=10,
width=600,
style={"color": cl.black, "border_width": 0.5},
alignment=ui.Alignment.TOP,
)
for index in range(15):
ui.Line(
height=10,
width=600,
style={"color": cl.black, "border_width": 0.5},
alignment=ui.Alignment.TOP,
)
ui.Line(
height=10,
width=600,
style={"color": cl.black, "border_width": 0.5},
alignment=ui.Alignment.TOP,
)
with ui.Placer(offset_x=100, offset_y=10):
ui.Button("moved 100px in X, and 10px in Y", width=0, height=20, name="placed")
with ui.Placer(offset_x=200, offset_y=50):
ui.Button("moved 200px X , and 50 Y", width=0, height=0)
def set_text(widget, text):
widget.text = text
with ui.Placer(draggable=True, offset_x=300, offset_y=100):
ui.Circle(radius=50, width=50, height=50, size_policy=ui.CircleSizePolicy.STRETCH, name="placed")
placer = ui.Placer(draggable=True, drag_axis=ui.Axis.Y, offset_x=400, offset_y=120)
with placer:
with ui.ZStack(width=180, height=40):
ui.Rectangle(name="placed")
with ui.HStack(spacing=5):
ui.Circle(
radius=3,
width=15,
size_policy=ui.CircleSizePolicy.FIXED,
style={"background_color": cl.white},
)
ui.Label("UP / Down", style={"color": cl.white, "font_size": 16.0})
offset_label = ui.Label("120", style={"color": cl.white})
placer.set_offset_y_changed_fn(lambda o: set_text(offset_label, str(o)))
```
The following example shows the way to interact between three Placers to create a resizable rectangle's body, left handle and right handle. The rectangle can be moved on X-axis and can be resized with small orange handles.
When multiple widgets fire the callbacks simultaneously, it's possible to collect the event data and process them one frame later using asyncio.
```execute 200
import asyncio
import omni.kit.app
from omni.ui import color as cl
def placer_track(self, id):
# Initial size
BEGIN = 50 + 100 * id
END = 120 + 100 * id
HANDLE_WIDTH = 10
class EditScope:
"""The class to avoid circular event calling"""
def __init__(self):
self.active = False
def __enter__(self):
self.active = True
def __exit__(self, type, value, traceback):
self.active = False
def __bool__(self):
return not self.active
class DoLater:
"""A helper to collect data and process it one frame later"""
def __init__(self):
self.__task = None
self.__data = []
def do(self, data):
# Collect data
self.__data.append(data)
# Update in the next frame. We need it because we want to accumulate the affected prims
if self.__task is None or self.__task.done():
self.__task = asyncio.ensure_future(self.__delayed_do())
async def __delayed_do(self):
# Wait one frame
await omni.kit.app.get_app().next_update_async()
print(f"In the previous frame the user clicked the rectangles: {self.__data}")
self.__data.clear()
self.edit = EditScope()
self.dolater = DoLater()
def start_moved(start, body, end):
if not self.edit:
# Something already edits it
return
with self.edit:
body.offset_x = start.offset_x
rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH)
def body_moved(start, body, end, rect):
if not self.edit:
# Something already edits it
return
with self.edit:
start.offset_x = body.offset_x
end.offset_x = body.offset_x + rect.width.value - HANDLE_WIDTH
def end_moved(start, body, end, rect):
if not self.edit:
# Something already edits it
return
with self.edit:
body.offset_x = start.offset_x
rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH)
with ui.ZStack(height=30):
# Body
body = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN)
with body:
rect = ui.Rectangle(width=END - BEGIN + HANDLE_WIDTH)
rect.set_mouse_pressed_fn(lambda x, y, b, m, id=id: self.dolater.do(id))
# Left handle
start = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN)
with start:
ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")})
# Right handle
end = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=END)
with end:
ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")})
# Connect them together
start.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end: start_moved(s, b, e))
body.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: body_moved(s, b, e, r))
end.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: end_moved(s, b, e, r))
ui.Spacer(height=5)
with ui.ZStack():
placer_track(self, 0)
placer_track(self, 1)
ui.Spacer(height=5)
```
It's possible to set `offset_x` and `offset_y` in percentages. It allows stacking the children to the proportions of the parent widget. If the parent size is changed, then the offset is updated accordingly.
```execute 200
from omni.ui import color as cl
# The size of the rectangle
SIZE = 20.0
with ui.ZStack(height=200):
# Background
ui.Rectangle(style={"background_color": cl(0.6)})
# Small rectangle
p = ui.Percent(50)
placer = ui.Placer(draggable=True, offset_x=p, offset_y=p)
with placer:
ui.Rectangle(width=SIZE, height=SIZE)
def clamp_x(offset):
if offset.value < 0:
placer.offset_x = ui.Percent(0)
max_per = 100.0 - SIZE / placer.computed_width * 100.0
if offset.value > max_per:
placer.offset_x = ui.Percent(max_per)
def clamp_y(offset):
if offset.value < 0:
placer.offset_y = ui.Percent(0)
max_per = 100.0 - SIZE / placer.computed_height * 100.0
if offset.value > max_per:
placer.offset_y = ui.Percent(max_per)
# Callbacks
placer.set_offset_x_changed_fn(clamp_x)
placer.set_offset_y_changed_fn(clamp_y)
```
| 25,689 | Markdown | 37.115727 | 612 | 0.647592 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/shapes.md | # Shapes
Shapes enable you to build custom widgets with specific looks. There are many shapes you can stylize: Rectangle, Circle, Ellipse, Triangle and FreeShapes of FreeRectangle, FreeCircle, FreeEllipse, FreeTriangle. In most cases those shapes will fit into the widget size which is defined by the parent widget they are in.
The FreeShapes are the shapes that are independent of the layout. It means it can be stuck to other shapes. It means it is possible to stick the freeshape to the layout's widgets, and the freeshape will follow the changes of the layout automatically.
## Common Style of shapes
Here is a list of common style you can customize on all the Shapes:
> background_color (color): the background color of the shape
> border_width (float): the border width if the shape has a border
> border_color (color): the border color if the shape has a border
## Rectangle
Rectangle is a shape with four sides and four corners. You can use Rectangle to draw rectangle shapes, or mix it with other controls e.g. using ZStack to create an advanced look.
Except the common style for shapes, here is a list of styles you can customize on Rectangle:
> background_gradient_color (color): the gradient color on the top part of the rectangle
> border_radius (float): default rectangle has 4 right corner angles, border_radius defines the radius of the corner angle if the user wants to round the rectangle corner. We only support one border_radius across all the corners, but users can choose which corner to be rounded.
> corner_flag (enum): defines which corner or corners to be rounded
Here is a list of the supported corner flags:
```execute 200
from omni.ui import color as cl
corner_flags = {
"ui.CornerFlag.NONE": ui.CornerFlag.NONE,
"ui.CornerFlag.TOP_LEFT": ui.CornerFlag.TOP_LEFT,
"ui.CornerFlag.TOP_RIGHT": ui.CornerFlag.TOP_RIGHT,
"ui.CornerFlag.BOTTOM_LEFT": ui.CornerFlag.BOTTOM_LEFT,
"ui.CornerFlag.BOTTOM_RIGHT": ui.CornerFlag.BOTTOM_RIGHT,
"ui.CornerFlag.TOP": ui.CornerFlag.TOP,
"ui.CornerFlag.BOTTOM": ui.CornerFlag.BOTTOM,
"ui.CornerFlag.LEFT": ui.CornerFlag.LEFT,
"ui.CornerFlag.RIGHT": ui.CornerFlag.RIGHT,
"ui.CornerFlag.ALL": ui.CornerFlag.ALL,
}
with ui.ScrollingFrame(
height=100,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in corner_flags.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": 10}}):
ui.Rectangle(
style={"background_color": cl("#aa4444"), "border_radius": 20.0, "corner_flag": value}
)
ui.Spacer(height=10)
ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER)
```
Here are a few examples of Rectangle using different selections of styles:
Default rectangle which is scaled to fit:
```execute 200
with ui.Frame(height=20):
ui.Rectangle(name="default")
```
This rectangle uses its own style to control colors and shape. Notice how three colors "background_color", "border_color" and "border_color" are affecting the look of the rectangle:
```execute 200
from omni.ui import color as cl
with ui.Frame(height=40):
ui.Rectangle(style={"Rectangle":{
"background_color":cl("#aa4444"),
"border_color":cl("#22FF22"),
"background_gradient_color": cl("#4444aa"),
"border_width": 2.0,
"border_radius": 5.0}})
```
This rectangle uses fixed width and height. Notice the `border_color` is not doing anything if `border_width` is not defined.
```execute 200
from omni.ui import color as cl
with ui.Frame(height=20):
ui.Rectangle(width=40, height=10, style={"background_color":cl(0.6), "border_color":cl("#ff2222")})
```
Compose with ZStack for an advanced look
```execute 200
from omni.ui import color as cl
with ui.Frame(height=20):
with ui.ZStack(height=20):
ui.Rectangle(width=150,
style={"background_color":cl(0.6),
"border_color":cl(0.1),
"border_width": 1.0,
"border_radius": 8.0} )
with ui.HStack():
ui.Spacer(width=10)
ui.Image("resources/icons/Cloud.png", width=20, height=20 )
ui.Label( "Search Field", style={"color":cl(0.875)})
```
## FreeRectangle
FreeRectangle is a rectangle whose width and height will be determined by other widgets. The supported style list is the same as Rectangle.
Here is an example of a FreeRectangle with style following two draggable circles:
```execute 200
from omni.ui import color as cl
with ui.Frame(height=200):
with ui.ZStack():
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Circle(width=10, height=10)
with ui.Placer(draggable=True, offset_x=150, offset_y=150):
control2 = ui.Circle(width=10, height=10)
# The rectangle that fits to the control points
ui.FreeRectangle(control1, control2, style={
"background_color":cl(0.6),
"border_color":cl(0.1),
"border_width": 1.0,
"border_radius": 8.0})
```
## Circle
You can use Circle to draw a circular shape. Circle doesn't have any other style except the common style for shapes.
Here is some of the properties you can customize on Circle:
> size_policy (enum): there are two types of the size_policy, fixed and stretch.
* ui.CircleSizePolicy.FIXED: the size of the circle is defined by the radius and is fixed without being affected by the parent scaling.
* ui.CircleSizePolicy.STRETCH: the size of the circle is defined by the parent and will be stretched if the parent widget size changed.
> alignment (enum): the position of the circle in the parent defined space
> arc (enum): this property defines the way to draw a half or a quarter of the circle.
Here is a list of the supported Alignment and Arc value for the Circle:
```execute 200
from omni.ui import color as cl
alignments = {
"ui.Alignment.CENTER": ui.Alignment.CENTER,
"ui.Alignment.LEFT_TOP": ui.Alignment.LEFT_TOP,
"ui.Alignment.LEFT_CENTER": ui.Alignment.LEFT_CENTER,
"ui.Alignment.LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM,
"ui.Alignment.CENTER_TOP": ui.Alignment.CENTER_TOP,
"ui.Alignment.CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM,
"ui.Alignment.RIGHT_TOP": ui.Alignment.RIGHT_TOP,
"ui.Alignment.RIGHT_CENTER": ui.Alignment.RIGHT_CENTER,
"ui.Alignment.RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM,
}
ui.Label("Alignment: ")
with ui.ScrollingFrame(
height=150,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": 10}}, spacing=10):
with ui.ZStack():
ui.Rectangle(name="table", style={"border_color":cl.white, "border_width": 1.0})
ui.Circle(
radius=10,
size_policy=ui.CircleSizePolicy.FIXED,
name="orientation",
alignment=value,
style={"background_color": cl("#aa4444")},
)
ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER)
ui.Spacer(height=10)
ui.Label("Arc: ")
with ui.ScrollingFrame(
height=150,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": 10}}, spacing=10):
with ui.ZStack():
ui.Rectangle(name="table", style={"border_color":cl.white, "border_width": 1.0})
ui.Circle(
radius=10,
size_policy=ui.CircleSizePolicy.FIXED,
name="orientation",
arc=value,
style={
"background_color": cl("#aa4444"),
"border_color": cl.blue,
"border_width": 2,
},
)
ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER)
```
Default circle which is scaled to fit, the alignment is centered:
```execute 200
with ui.Frame(height=20):
ui.Circle(name="default")
```
This circle is scaled to fit with 100 height:
```execute 200
with ui.Frame(height=100):
ui.Circle(name="default")
```
This circle has a fixed radius of 20, the alignment is LEFT_CENTER:
```execute 200
from omni.ui import color as cl
style = {"Circle": {"background_color": cl("#1111ff"), "border_color": cl("#cc0000"), "border_width": 4}}
with ui.Frame(height=100, style=style):
with ui.HStack():
ui.Rectangle(width=40, style={"background_color": cl.white})
ui.Circle(radius=20, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER)
```
This circle has a fixed radius of 10, the alignment is RIGHT_CENTER
```execute 200
from omni.ui import color as cl
style = {"Circle": {"background_color": cl("#ff1111"), "border_color": cl.blue, "border_width": 2}}
with ui.Frame(height=100, width=200, style=style):
with ui.ZStack():
ui.Rectangle(style={"background_color": cl(0.4)})
ui.Circle(radius=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.RIGHT_CENTER)
```
This circle has a fixed radius of 10, it has all the same style as the previous one, except its size_policy is `ui.CircleSizePolicy.STRETCH`
```execute 200
from omni.ui import color as cl
style = {"Circle": {"background_color": cl("#ff1111"), "border_color": cl.blue, "border_width": 2}}
with ui.Frame(height=100, width=200, style=style):
with ui.ZStack():
ui.Rectangle(style={"background_color": cl(0.4)})
ui.Circle(radius=10, size_policy=ui.CircleSizePolicy.STRETCH, alignment=ui.Alignment.RIGHT_CENTER)
```
## FreeCircle
FreeCircle is a circle whose radius will be determined by other widgets. The supported style list is the same as Circle.
Here is an example of a FreeCircle with style following two draggable rectangles:
```execute 200
from omni.ui import color as cl
with ui.Frame(height=200):
with ui.ZStack():
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Rectangle(width=10, height=10)
with ui.Placer(draggable=True, offset_x=150, offset_y=150):
control2 = ui.Rectangle(width=10, height=10)
# The rectangle that fits to the control points
ui.FreeCircle(control1, control2, style={
"background_color":cl.transparent,
"border_color":cl.red,
"border_width": 2.0})
```
## Ellipse
Ellipse is drawn in a rectangle bounding box, and It is always scaled to fit the rectangle's width and height. Ellipse doesn't have any other style except the common style for shapes.
Default ellipse is scaled to fit:
```execute 200
with ui.Frame(height=20, width=150):
ui.Ellipse(name="default")
```
Stylish ellipse with border and colors:
```execute 200
from omni.ui import color as cl
style = {"Ellipse": {"background_color": cl("#1111ff"), "border_color": cl("#cc0000"), "border_width": 4}}
with ui.Frame(height=100, width=50):
ui.Ellipse(style=style)
```
## FreeEllipse
FreeEllipse is an ellipse whose width and height will be determined by other widgets. The supported style list is the same as Ellipse.
Here is an example of a FreeEllipse with style following two draggable circles:
```execute 200
from omni.ui import color as cl
with ui.Frame(height=200):
with ui.ZStack():
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Circle(width=10, height=10)
with ui.Placer(draggable=True, offset_x=150, offset_y=200):
control2 = ui.Circle(width=10, height=10)
# The rectangle that fits to the control points
ui.FreeEllipse(control1, control2, style={
"background_color":cl.purple})
```
## Triangle
You can use Triangle to draw Triangle shape. Triangle doesn't have any other style except the common style for shapes.
Here is some of the properties you can customize on Triangle:
> alignment (enum): the alignment defines where the tip of the triangle is, base will be at the opposite side
Here is a list of the supported alignment value for the triangle:
```execute 200
from omni.ui import color as cl
alignments = {
"ui.Alignment.LEFT_TOP": ui.Alignment.LEFT_TOP,
"ui.Alignment.LEFT_CENTER": ui.Alignment.LEFT_CENTER,
"ui.Alignment.LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM,
"ui.Alignment.CENTER_TOP": ui.Alignment.CENTER_TOP,
"ui.Alignment.CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM,
"ui.Alignment.RIGHT_TOP": ui.Alignment.RIGHT_TOP,
"ui.Alignment.RIGHT_CENTER": ui.Alignment.RIGHT_CENTER,
"ui.Alignment.RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM,
}
colors = [cl.red, cl.yellow, cl.purple, cl("#ff0ff0"), cl.green, cl("#f00fff"), cl("#fff000"), cl("#aa3333")]
index = 0
with ui.ScrollingFrame(
height=160,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": 10}}):
color = colors[index]
index = index + 1
ui.Triangle(alignment=value, style={"Triangle":{"background_color": color}})
ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER, height=20)
```
Here are a few examples of Triangle using different selections of styles:
The triangle is scaled to fit, base on the left and tip on the center right. Users can define the border_color and border_width but without background_color to make the triangle look like it's drawn in wireframe style.
```execute 200
from omni.ui import color as cl
style = {
"Triangle::default":
{
"background_color": cl.green,
"border_color": cl.white,
"border_width": 1
},
"Triangle::transparent":
{
"border_color": cl.purple,
"border_width": 4,
},
}
with ui.Frame(height=100, width=200, style=style):
with ui.HStack(spacing=10, style={"margin": 5}):
ui.Triangle(name="default")
ui.Triangle(name="transparent", alignment=ui.Alignment.CENTER_TOP)
```
## FreeTriangle
FreeTriangle is a triangle whose width and height will be determined by other widgets. The supported style list is the same as Triangle.
Here is an example of a FreeTriangle with style following two draggable rectangles. The default alignment is `ui.Alignment.RIGHT_CENTER`. We make the alignment as `ui.Alignment.CENTER_BOTTOM`.
```execute 200
from omni.ui import color as cl
with ui.Frame(height=200):
with ui.ZStack():
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Rectangle(width=10, height=10)
with ui.Placer(draggable=True, offset_x=150, offset_y=200):
control2 = ui.Rectangle(width=10, height=10)
# The rectangle that fits to the control points
ui.FreeTriangle(control1, control2, alignment=ui.Alignment.CENTER_BOTTOM, style={
"background_color":cl.blue,
"border_color":cl.red,
"border_width": 2.0})
``` | 16,520 | Markdown | 43.292225 | 318 | 0.656416 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/buttons.md | # Buttons and Images
## Common Styling for Buttons and Images
Here is a list of common style you can customize on Buttons and Images:
> border_color (color): the border color if the button or image background has a border
> border_radius (float): the border radius if the user wants to round the button or image
> border_width (float): the border width if the button or image or image background has a border
> margin (float): the distance between the widget content and the parent widget defined boundary
> margin_width (float): the width distance between the widget content and the parent widget defined boundary
> margin_height (float): the height distance between the widget content and the parent widget defined boundary
## Button
The Button widget provides a command button. Click a button to execute a command. The command button is perhaps the most commonly used widget in any graphical user interface. It is rectangular and typically displays a text label or image describing its action.
Except the common style for Buttons and Images, here is a list of styles you can customize on Button:
> background_color (color): the background color of the button
> padding (float): the distance between the content widgets (e.g. Image or Label) and the border of the button
> stack_direction (enum): defines how the content widgets (e.g. Image or Label) on the button are placed.
There are 6 types of stack_directions supported
* ui.Direction.TOP_TO_BOTTOM : layout from top to bottom
* ui.Direction.BOTTOM_TO_TOP : layout from bottom to top
* ui.Direction.LEFT_TO_RIGHT : layout from left to right
* ui.Direction.RIGHT_TO_LEFT : layout from right to left
* ui.Direction.BACK_TO_FRONT : layout from back to front
* ui.Direction.FRONT_TO_BACK : layout from front to back
To control the style of the button content, you can customize `Button.Image` when image on button and `Button.Label` when text on button.
Here is an example showing a list of buttons with different types of the stack directions:
```execute 200
from omni.ui import color as cl
direction_flags = {
"ui.Direction.TOP_TO_BOTTOM": ui.Direction.TOP_TO_BOTTOM,
"ui.Direction.BOTTOM_TO_TOP": ui.Direction.BOTTOM_TO_TOP,
"ui.Direction.LEFT_TO_RIGHT": ui.Direction.LEFT_TO_RIGHT,
"ui.Direction.RIGHT_TO_LEFT": ui.Direction.RIGHT_TO_LEFT,
"ui.Direction.BACK_TO_FRONT": ui.Direction.BACK_TO_FRONT,
"ui.Direction.FRONT_TO_BACK": ui.Direction.FRONT_TO_BACK,
}
with ui.ScrollingFrame(
height=50,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in direction_flags.items():
button_style = {"Button": {"stack_direction": value}}
ui_button = ui.Button(
key,
image_url="resources/icons/Nav_Flymode.png",
image_width=24,
height=40,
style=button_style
)
```
Here is an example of two buttons. Pressing the second button makes the name of the first button longer. And press the first button makes the name of itself shorter:
```execute 200
from omni.ui import color as cl
style_system = {
"Button": {
"background_color": cl(0.85),
"border_color": cl.yellow,
"border_width": 2,
"border_radius": 5,
"padding": 5,
},
"Button.Label": {"color": cl.red, "font_size": 17},
"Button:hovered": {"background_color": cl("#E5F1FB"), "border_color": cl("#0078D7"), "border_width": 2.0},
"Button:pressed": {"background_color": cl("#CCE4F7"), "border_color": cl("#005499"), "border_width": 2.0},
}
def make_longer_text(button):
"""Set the text of the button longer"""
button.text = "Longer " + button.text
def make_shorter_text(button):
"""Set the text of the button shorter"""
splitted = button.text.split(" ", 1)
button.text = splitted[1] if len(splitted) > 1 else splitted[0]
with ui.HStack(style=style_system):
btn_with_text = ui.Button("Text", width=0)
ui.Button("Press me", width=0, clicked_fn=lambda b=btn_with_text: make_longer_text(b))
btn_with_text.set_clicked_fn(lambda b=btn_with_text: make_shorter_text(b))
```
Here is an example where you can tweak most of the Button's style and see the results:
```execute 200
from omni.ui import color as cl
style = {
"Button": {"stack_direction": ui.Direction.TOP_TO_BOTTOM},
"Button.Image": {
"color": cl("#99CCFF"),
"image_url": "resources/icons/Learn_128.png",
"alignment": ui.Alignment.CENTER,
},
"Button.Label": {"alignment": ui.Alignment.CENTER},
}
def direction(model, button, style=style):
value = model.get_item_value_model().get_value_as_int()
direction = (
ui.Direction.TOP_TO_BOTTOM,
ui.Direction.BOTTOM_TO_TOP,
ui.Direction.LEFT_TO_RIGHT,
ui.Direction.RIGHT_TO_LEFT,
ui.Direction.BACK_TO_FRONT,
ui.Direction.FRONT_TO_BACK,
)[value]
style["Button"]["stack_direction"] = direction
button.set_style(style)
def align(model, button, image, style=style):
value = model.get_item_value_model().get_value_as_int()
alignment = (
ui.Alignment.LEFT_TOP,
ui.Alignment.LEFT_CENTER,
ui.Alignment.LEFT_BOTTOM,
ui.Alignment.CENTER_TOP,
ui.Alignment.CENTER,
ui.Alignment.CENTER_BOTTOM,
ui.Alignment.RIGHT_TOP,
ui.Alignment.RIGHT_CENTER,
ui.Alignment.RIGHT_BOTTOM,
)[value]
if image:
style["Button.Image"]["alignment"] = alignment
else:
style["Button.Label"]["alignment"] = alignment
button.set_style(style)
def layout(model, button, padding, style=style):
if padding == 0:
padding = "padding"
elif padding == 1:
padding = "margin"
elif padding == 2:
padding = "margin_width"
else:
padding = "margin_height"
style["Button"][padding] = model.get_value_as_float()
button.set_style(style)
def spacing(model, button):
button.spacing = model.get_value_as_float()
button = ui.Button("Label", style=style, width=64, height=64)
with ui.HStack(width=ui.Percent(50)):
ui.Label('"Button": {"stack_direction"}', name="text")
options = (
0,
"TOP_TO_BOTTOM",
"BOTTOM_TO_TOP",
"LEFT_TO_RIGHT",
"RIGHT_TO_LEFT",
"BACK_TO_FRONT",
"FRONT_TO_BACK",
)
model = ui.ComboBox(*options).model
model.add_item_changed_fn(lambda m, i, b=button: direction(m, b))
alignment = (
4,
"LEFT_TOP",
"LEFT_CENTER",
"LEFT_BOTTOM",
"CENTER_TOP",
"CENTER",
"CENTER_BOTTOM",
"RIGHT_TOP",
"RIGHT_CENTER",
"RIGHT_BOTTOM",
)
with ui.HStack(width=ui.Percent(50)):
ui.Label('"Button.Image": {"alignment"}', name="text")
model = ui.ComboBox(*alignment).model
model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 1))
with ui.HStack(width=ui.Percent(50)):
ui.Label('"Button.Label": {"alignment"}', name="text")
model = ui.ComboBox(*alignment).model
model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 0))
with ui.HStack(width=ui.Percent(50)):
ui.Label("padding", name="text")
model = ui.FloatSlider(min=0, max=500).model
model.add_value_changed_fn(lambda m, b=button: layout(m, b, 0))
with ui.HStack(width=ui.Percent(50)):
ui.Label("margin", name="text")
model = ui.FloatSlider(min=0, max=500).model
model.add_value_changed_fn(lambda m, b=button: layout(m, b, 1))
with ui.HStack(width=ui.Percent(50)):
ui.Label("margin_width", name="text")
model = ui.FloatSlider(min=0, max=500).model
model.add_value_changed_fn(lambda m, b=button: layout(m, b, 2))
with ui.HStack(width=ui.Percent(50)):
ui.Label("margin_height", name="text")
model = ui.FloatSlider(min=0, max=500).model
model.add_value_changed_fn(lambda m, b=button: layout(m, b, 3))
with ui.HStack(width=ui.Percent(50)):
ui.Label("Button.spacing", name="text")
model = ui.FloatSlider(min=0, max=50).model
model.add_value_changed_fn(lambda m, b=button: spacing(m, b))
```
## Radio Button
RadioButton is the widget that allows the user to choose only one from a predefined set of mutually exclusive options.
RadioButtons are arranged in collections of two or more buttons within a RadioCollection, which is the central component of the system and controls the behavior of all the RadioButtons in the collection.
Except the common style for Buttons and Images, here is a list of styles you can customize on RadioButton:
> background_color (color): the background color of the RadioButton
> padding (float): the distance between the the RadioButton content widget (e.g. Image) and the RadioButton border
To control the style of the button image, you can customize `RadioButton.Image`. For example RadioButton.Image's image_url defines the image when it's not checked. You can define the image for checked status with `RadioButton.Image:checked` style.
Here is an example of RadioCollection which contains 5 RadioButtons with style. Also there is an IntSlider which shares the model with the RadioCollection, so that when RadioButton value or the IntSlider value changes, the other one will update too.
```execute 200
from omni.ui import color as cl
style = {
"RadioButton": {
"background_color": cl.cyan,
"margin_width": 2,
"padding": 1,
"border_radius": 0,
"border_color": cl.white,
"border_width": 1.0},
"RadioButton.Image": {
"image_url": f"../exts/omni.kit.documentation.ui.style/icons/radio_off.svg",
},
"RadioButton.Image:checked": {
"image_url": f"../exts/omni.kit.documentation.ui.style/icons/radio_on.svg"},
}
collection = ui.RadioCollection()
for i in range(5):
with ui.HStack(style=style):
ui.RadioButton(radio_collection=collection, width=30, height=30)
ui.Label(f"Option {i}", name="text")
ui.IntSlider(collection.model, min=0, max=4)
```
## ToolButton
ToolButton is functionally similar to Button, but provides a model that determines if the button is checked. This button toggles between checked (on) and unchecked (off) when the user clicks it.
Here is an example of a ToolButton:
```execute 200
def update_label(model, label):
checked = model.get_value_as_bool()
label.text = f"The check status button is {checked}"
with ui.VStack(spacing=5):
model = ui.ToolButton(text="click", name="toolbutton", width=100).model
checked = model.get_value_as_bool()
label = ui.Label(f"The check status button is {checked}")
model.add_value_changed_fn(lambda m, l=label: update_label(m, l))
```
## ColorWidget
The ColorWidget is a button that displays the color from the item model and can open a picker window. The color dialog's function is to allow users to choose color.
Except the common style for Buttons and Images, here is a list of styles you can customize on ColorWidget:
> background_color (color): the background color of the tooltip widget when hover over onto the ColorWidget
> color (color): the text color of the tooltip widget when hover over onto the ColorWidget
Here is an example of a ColorWidget with three FloatFields. The ColorWidget model is shared with the FloatFields so that users can click and edit the field value to change the ColorWidget's color, and the value change of the ColorWidget will also reflect in the value change of the FloatFields.
```execute 200
from omni.ui import color as cl
with ui.HStack(spacing=5):
color_model = ui.ColorWidget(width=0, height=0, style={"ColorWidget":{
"border_width": 2,
"border_color": cl.white,
"border_radius": 4,
"color": cl.pink,
"margin": 2
}}).model
for item in color_model.get_item_children():
component = color_model.get_item_value_model(item)
ui.FloatField(component)
```
Here is an example of a ColorWidget with three FloatDrags. The ColorWidget model is shared with the FloatDrags so that users can drag the field value to change the color, and the value change of the ColorWidget will also reflect in the value change of the FloatDrags.
```execute 200
from omni.ui import color as cl
with ui.HStack(spacing=5):
color_model = ui.ColorWidget(0.125, 0.25, 0.5, width=0, height=0, style={
"background_color": cl.pink
}).model
for item in color_model.get_item_children():
component = color_model.get_item_value_model(item)
ui.FloatDrag(component, min=0, max=1)
```
Here is an example of a ColorWidget with a ComboBox. The ColorWidget model is shared with the ComboBox. Only the value change of the ColorWidget will reflect in the value change of the ComboBox.
```execute 200
with ui.HStack(spacing=5):
color_model = ui.ColorWidget(width=0, height=0).model
ui.ComboBox(color_model)
```
Here is an interactive example with USD. You can create a Mesh in the Stage. Choose `Pixar Storm` as the render. Select the mesh and use this ColorWidget to change the color of the mesh. You can use `Ctrl+z` for undoing and `Ctrl+y` for redoing.
```execute 200
import omni.kit.commands
from omni.usd.commands import UsdStageHelper
from pxr import UsdGeom
from pxr import Gf
import omni.usd
class SetDisplayColorCommand(omni.kit.commands.Command, UsdStageHelper):
"""
Change prim display color undoable **Command**. Unlike ChangePropertyCommand, it can undo property creation.
Args:
gprim (Gprim): Prim to change display color on.
value: Value to change to.
value: Value to undo to.
"""
def __init__(self, gprim: UsdGeom.Gprim, color: Any, prev: Any):
self._gprim = gprim
self._color = color
self._prev = prev
def do(self):
color_attr = self._gprim.CreateDisplayColorAttr()
color_attr.Set([self._color])
def undo(self):
color_attr = self._gprim.GetDisplayColorAttr()
if self._prev is None:
color_attr.Clear()
else:
color_attr.Set([self._prev])
omni.kit.commands.register(SetDisplayColorCommand)
class FloatModel(ui.SimpleFloatModel):
def __init__(self, parent):
super().__init__()
self._parent = weakref.ref(parent)
def begin_edit(self):
parent = self._parent()
parent.begin_edit(None)
def end_edit(self):
parent = self._parent()
parent.end_edit(None)
class USDColorItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
class USDColorModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
self._items = [USDColorItem(FloatModel(self)) for i in range(3)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
# Omniverse contexts
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="omni.example.ui ColorWidget stage update"
)
# Privates
self._subscription = None
self._gprim = None
self._prev_color = None
self._edit_mode_counter = 0
def _on_stage_event(self, event):
"""Called with subscription to pop"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
"""Called when the user changes the selection"""
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
self._subscription = None
self._gprim = None
# When TC runs tests, it's possible that stage is None
if selection and stage:
self._gprim = UsdGeom.Gprim.Get(stage, selection[0])
if self._gprim:
color_attr = self._gprim.GetDisplayColorAttr()
usd_watcher = omni.usd.get_watcher()
self._subscription = usd_watcher.subscribe_to_change_info_path(
color_attr.GetPath(), self._on_usd_changed
)
# Change the widget color
self._on_usd_changed()
def _on_value_changed(self, item):
"""Called when the submodel is changed"""
if not self._gprim:
return
if self._edit_mode_counter > 0:
# Change USD only if we are in edit mode.
color_attr = self._gprim.CreateDisplayColorAttr()
color = Gf.Vec3f(
self._items[0].model.get_value_as_float(),
self._items[1].model.get_value_as_float(),
self._items[2].model.get_value_as_float(),
)
color_attr.Set([color])
self._item_changed(item)
def _on_usd_changed(self, path=None):
"""Called with UsdWatcher when something in USD is changed"""
color = self._get_current_color() or Gf.Vec3f(0.0)
for i in range(len(self._items)):
self._items[i].model.set_value(color[i])
def _get_current_color(self):
"""Returns color of the current object"""
if self._gprim:
color_attr = self._gprim.GetDisplayColorAttr()
if color_attr:
color_array = color_attr.Get()
if color_array:
return color_array[0]
def get_item_children(self, item):
"""Reimplemented from the base class"""
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
if self._edit_mode_counter == 0:
self._prev_color = self._get_current_color()
self._edit_mode_counter += 1
def end_edit(self, item):
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
self._edit_mode_counter -= 1
if not self._gprim or self._edit_mode_counter > 0:
return
color = Gf.Vec3f(
self._items[0].model.get_value_as_float(),
self._items[1].model.get_value_as_float(),
self._items[2].model.get_value_as_float(),
)
omni.kit.commands.execute("SetDisplayColor", gprim=self._gprim, color=color, prev=self._prev_color)
with ui.HStack(spacing=5):
ui.ColorWidget(USDColorModel(), width=0)
ui.Label("Interactive ColorWidget with USD", name="text")
```
## Image
The Image type displays an image. The source of the image is specified as a URL using the source property. By default, specifying the width and height of the item makes the image to be scaled to fit that size. This behavior can be changed by setting the `fill_policy` property, allowing the image to be stretched or scaled instead. The property alignment controls how the scaled image is aligned in the parent defined space.
Except the common style for Buttons and Images, here is a list of styles you can customize on Image:
> image_url (str): the url path of the image source
> color (color): the overlay color of the image
> corner_flag (enum): defines which corner or corners to be rounded. The supported corner flags are the same as Rectangle since Image is eventually an image on top of a rectangle under the hood.
> fill_policy (enum): defines how the Image fills the rectangle.
There are three types of fill_policy
* ui.FillPolicy.STRETCH: stretch the image to fill the entire rectangle.
* ui.FillPolicy.PRESERVE_ASPECT_FIT: uniformly to fit the image without stretching or cropping.
* ui.FillPolicy.PRESERVE_ASPECT_CROP: scaled uniformly to fill, cropping if necessary
> alignment (enum): defines how the image is positioned in the parent defined space. There are 9 alignments supported which are quite self-explanatory.
* ui.Alignment.LEFT_CENTER
* ui.Alignment.LEFT_TOP
* ui.Alignment.LEFT_BOTTOM
* ui.Alignment.RIGHT_CENTER
* ui.Alignment.RIGHT_TOP
* ui.Alignment.RIGHT_BOTTOM
* ui.Alignment.CENTER
* ui.Alignment.CENTER_TOP
* ui.Alignment.CENTER_BOTTOM
Default Image is scaled uniformly to fit without stretching or cropping (ui.FillPolicy.PRESERVE_ASPECT_FIT), and aligned to ui.Alignment.CENTER:
```execute 200
source = "resources/desktop-icons/omniverse_512.png"
with ui.Frame(width=200, height=100):
ui.Image(source)
```
The image is stretched to fit and aligned to the left
```execute 200
source = "resources/desktop-icons/omniverse_512.png"
with ui.Frame(width=200, height=100):
ui.Image(source, fill_policy=ui.FillPolicy.STRETCH, alignment=ui.Alignment.LEFT_CENTER)
```
The image is scaled uniformly to fill, cropping if necessary and aligned to the top
```execute 200
source = "resources/desktop-icons/omniverse_512.png"
with ui.Frame(width=200, height=100):
ui.Image(source, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
alignment=ui.Alignment.CENTER_TOP)
```
The image is scaled uniformly to fit without cropping and aligned to the right. Notice the fill_policy and alignment are defined in style.
```execute 200
source = "resources/desktop-icons/omniverse_512.png"
with ui.Frame(width=200, height=100):
ui.Image(source, style={
"Image": {
"fill_policy": ui.FillPolicy.PRESERVE_ASPECT_FIT,
"alignment": ui.Alignment.RIGHT_CENTER,
"margin": 5}})
```
The image has rounded corners and an overlayed color. Note image_url is in the style dictionary.
```execute 200
from omni.ui import color as cl
source = "resources/desktop-icons/omniverse_512.png"
with ui.Frame(width=200, height=100):
ui.Image(style={"image_url": source, "border_radius": 10, "color": cl("#5eb3ff")})
```
The image is scaled uniformly to fill, cropping if necessary and aligned to the bottom, with a blue border.
```execute 200
from omni.ui import color as cl
source = "resources/desktop-icons/omniverse_512.png"
with ui.Frame(width=200, height=100):
ui.Image(
source,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
alignment=ui.Alignment.CENTER_BOTTOM,
style={"Image":{
"border_width": 5,
"border_color": cl("#1ab3ff"),
"corner_flag": ui.CornerFlag.TOP,
"border_radius": 15}})
```
The image is arranged in a HStack with different margin styles defined. Note image_url is in the style dict.
```execute 200
source = "resources/desktop-icons/omniverse_512.png"
with ui.Frame(height=100):
with ui.HStack(spacing =5, style={"Image":{'image_url': source}}):
ui.Image()
ui.Image(style={"Image":{"margin_height": 15}})
ui.Image()
ui.Image(style={"Image":{"margin_width": 20}})
ui.Image()
ui.Image(style={"Image":{"margin": 10}})
ui.Image()
```
It's possible to set a different image per style state. And switch them depending on the mouse hovering, selection state, etc.
```execute 200
styles = [
{
"": {"image_url": "resources/icons/Nav_Walkmode.png"},
":hovered": {"image_url": "resources/icons/Nav_Flymode.png"},
},
{
"": {"image_url": "resources/icons/Move_local_64.png"},
":hovered": {"image_url": "resources/icons/Move_64.png"},
},
{
"": {"image_url": "resources/icons/Rotate_local_64.png"},
":hovered": {"image_url": "resources/icons/Rotate_global.png"},
},
]
def set_image(model, image):
value = model.get_item_value_model().get_value_as_int()
image.set_style(styles[value])
with ui.Frame(height=80):
with ui.VStack():
image = ui.Image(width=64, height=64, style=styles[0])
with ui.HStack(width=ui.Percent(50)):
ui.Label("Select a texture to display", name="text")
model = ui.ComboBox(0, "Navigation", "Move", "Rotate").model
model.add_item_changed_fn(lambda m, i, im=image: set_image(m, im))
```
## ImageWithProvider
ImageWithProvider also displays an image just like Image. It is a much more advanced image widget. ImageWithProvider blocks until the image is loaded, Image doesn't block. Sometimes Image blinks because when the first frame is created, the image is not loaded. Users are recommended to use ImageWithProvider if the UI is updated pretty often. Because it doesn't blink when recreating.
It has the almost the same style list as Image, except the fill_policy has different enum values.
> fill_policy (enum): defines how the Image fills the rectangle.
There are three types of fill_policy
* ui.IwpFillPolicy.IWP_STRETCH: stretch the image to fill the entire rectangle.
* ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT: uniformly to fit the image without stretching or cropping.
* ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_CROP: scaled uniformly to fill, cropping if necessary
The image source comes from `ImageProvider` which could be `ByteImageProvider`, `RasterImageProvider` or `VectorImageProvider`.
`RasterImageProvider` and `VectorImageProvider` are using image urls like Image. Here is an example taken from Image. Notice the fill_policy value difference.
```execute 200
from omni.ui import color as cl
source = "resources/desktop-icons/omniverse_512.png"
with ui.Frame(width=200, height=100):
ui.ImageWithProvider(
source,
style={
"ImageWithProvider": {
"border_width": 5,
"border_color": cl("#1ab3ff"),
"corner_flag": ui.CornerFlag.TOP,
"border_radius": 15,
"fill_policy": ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_CROP,
"alignment": ui.Alignment.CENTER_BOTTOM}})
```
`ByteImageProvider` is really useful to create gradient images. Here is an example:
```execute 200
self._byte_provider = ui.ByteImageProvider()
self._byte_provider.set_bytes_data([
255, 0, 0, 255, # red
255, 255, 0, 255, # yellow
0, 255, 0, 255, # green
0, 255, 255, 255, # cyan
0, 0, 255, 255], # blue
[5, 1]) # size
with ui.Frame(height=20):
ui.ImageWithProvider(self._byte_provider,fill_policy=ui.IwpFillPolicy.IWP_STRETCH)
```
## Plot
The Plot class displays a line or histogram image. The data of the image is specified as a data array or a provider function.
Except the common style for Buttons and Images, here is a list of styles you can customize on Plot:
> color (color): the color of the plot, line color in the line typed plot or rectangle bar color in the histogram typed plot
> selected_color (color): the selected color of the plot, dot in the line typed plot and rectangle bar in the histogram typed plot
> background_color (color): the background color of the plot
> secondary_color (color): the color of the text and the border of the text box which shows the plot selection value
> background_selected_color (color): the background color of the text box which shows the plot selection value
Here are couple of examples of Plots:
```execute 200
import math
from omni.ui import color as cl
data = []
for i in range(360):
data.append(math.cos(math.radians(i)))
def on_data_provider(index):
return math.sin(math.radians(index))
with ui.Frame(height=20):
with ui.HStack():
plot_1 = ui.Plot(ui.Type.LINE, -1.0, 1.0, *data, width=360, height=100,
style={"Plot":{
"color": cl.red,
"background_color": cl(0.08),
"secondary_color": cl("#aa1111"),
"selected_color": cl.green,
"background_selected_color": cl.white,
"border_width":5,
"border_color": cl.blue,
"border_radius": 20
}})
ui.Spacer(width = 20)
plot_2 = ui.Plot(ui.Type.HISTOGRAM, -1.0, 1.0, on_data_provider, 360, width=360, height=100,
style={"Plot":{
"color": cl.blue,
"background_color": cl("#551111"),
"secondary_color": cl("#11AA11"),
"selected_color": cl(0.67),
"margin_height": 10,
}})
plot_2.value_stride = 6
``` | 28,831 | Markdown | 39.211994 | 424 | 0.660296 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/CHANGELOG.md | # Changelog
The documentation for omni.ui style
## [1.0.3] - 2022-10-20
### Fixed
- Fixed font session crash
### Added
- The extension to the doc system
## [1.0.2] - 2022-07-20
### Added
- Order in Stack and use of content_clipping section
- ToolButton section
## [1.0.1] - 2022-07-20
### Changed
- Added help menu API doc entrance
- Clarified the window style
## [1.0.0] - 2022-06-15
### Added
- The initial documentation
| 428 | Markdown | 16.874999 | 52 | 0.675234 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/overview.md | # Overview
OmniUI style allows users to build customized widgets, make these widgets visually pleasant and functionally indicative with user interactions.
Each widget has its own style to be tweaked with based on their use cases and behaviors, while they also follow the same syntax rules. The container widgets provide a customized style for the widgets layout, providing flexibility for the arrangement of elements.
Each omni ui item has its own style to be tweaked with based on their use cases and behaviors, while they also follow the same syntax rules for the style definition.
Shades are used to have different themes for the entire ui, e.g. dark themed ui and light themed ui. Omni.ui also supports different font styles and sizes. Different length units allows users to define the widgets accurate to exact pixel or proportional to the parent widget or siblings.
Shapes are the most basic elements in the ui, which allows users to create stylish ui shapes, rectangles, circles, triangles, line and curve. Freeshapes are the extended shapes, which allows users to control some of the attributes dynamically through bounded widgets.
Widgets are mostly a combination of shapes, images or texts, which are created to be stepping stones for the entire ui window. Each of the widget has its own style to be characterized.
The container widgets provide a customized style for the widgets layout, providing flexibility for the arrangement of elements and possibility of creating more complicated and customized widgets.
| 1,528 | Markdown | 94.562494 | 287 | 0.816099 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/window.md | # Window Widgets
## MainWindow
The MainWindow represents the main window for an application. There should only be one MainWindow in each application.
Here is a list of styles you can customize on MainWindow:
> background_color (color): the background color of the main window.
> margin_height (float): the height distance between the window content and the window border.
> margin_width (float): the width distance between the window content and the window border.
Here is an example of a main window with style. Click the button to show the main window. Since the example is running within a MainWindow already, creating a new MainWindow will not run correctly in this example, but it demonstrates how to set the style of the `MainWindow`. And note the style of MainWindow is not propagated to other windows.
```execute 200
from omni.ui import color as cl
self._main_window = None
self._window1 = None
self._window2 = None
def create_main_window():
if not self._main_window:
self._main_window = ui.MainWindow()
self._main_window.main_frame.set_style({
"MainWindow": {
"background_color": cl.purple,
"margin_height": 20,
"margin_width": 10
}})
self._window1 = ui.Window("window 1", width=300, height=300)
self._window2 = ui.Window("window 2", width=300, height=300)
main_dockspace = ui.Workspace.get_window("DockSpace")
self._window1.dock_in(main_dockspace, ui.DockPosition.SAME)
self._window2.dock_in(main_dockspace, ui.DockPosition.SAME)
self._window2.focus()
self._window2.visible = True
ui.Button("click for Main Window", width=180, clicked_fn=create_main_window)
```
## Window
The window is a child window of the MainWindow. And it can be docked. You can have any type of widgets as the window content widgets.
Here is a list of styles you can customize on Window:
> background_color (color): the background color of the window.
> border_color (color): the border color if the window has a border.
> border_radius (float): the radius of the corner angle if the user wants to round the window.
> border_width (float): the border width if the window has a border.
Here is an example of a window with style. Click the button to show the window.
```execute 200
from omni.ui import color as cl
self._style_window_example = None
def create_styled_window():
if not self._style_window_example:
self._style_window_example = ui.Window("Styled Window Example", width=300, height=300)
self._style_window_example.frame.set_style({
"Window": {
"background_color": cl.blue,
"border_radius": 10,
"border_width": 5,
"border_color": cl.red,
}})
self._style_window_example.visible = True
ui.Button("click for Styled Window", width=180, clicked_fn=create_styled_window)
```
Note that a window's style is set from its frame since ui.Window itself is not a widget. We can't set style to it like other widgets. ui.Window's frame is a normal ui.Frame widget which itself doesn't have styles like `background_color` or `border_radius` (see `Container Widgets`->`Frame`). We specifically interpret the input ui.Window's frame style as the window style here. Therefore, the window style is not propagated to the content widget either just like the MainWindow.
If you want to set up a default style for the entire window. You should use `ui.style.default`. More details in `The Style Sheet Syntax` -> `Style Override` -> `Default style override`.
## Menu
The Menu class provides a menu widget for use in menu bars, context menus, and other popup menus. It can be either a pull-down menu in a menu bar or a standalone context menu. Pull-down menus are shown by the menu bar when the user clicks on the respective item. Context menus are usually invoked by some special keyboard key or by right-clicking.
Here is a list of styles you can customize on Menu:
> color (color): the color of the menu text
> background_color (color): the background color of sub menu window
> background_selected_color (color): the background color when the current menu is selected
> border_color (color): the border color of the sub menu window if it has a border
> border_width (float): the border width of the sub menu window if it has a border
> border_radius (float): the border radius of the sub menu window if user wants to round the sub menu window
> padding (float): the padding size of the sub menu window
Here is a list of styles you can customize on MenuItem:
> color (color): the color of the menu Item text
> background_selected_color (color): the background color when the current menu is selected
Right click for the context menu with customized menu style:
```execute 200
from omni.ui import color as cl
self.context_menu = None
def show_context_menu(x, y, button, modifier, widget):
if button != 1:
return
self.context_menu = ui.Menu("Context menu",
style={
"Menu": {
"background_color": cl.blue,
"color": cl.pink,
"background_selected_color": cl.green,
"border_radius": 5,
"border_width": 2,
"border_color": cl.yellow,
"padding": 15
},
"MenuItem": {
"color": cl.white,
"background_selected_color": cl.cyan},
"Separator": {
"color": cl.red},
},)
with self.context_menu:
ui.MenuItem("Delete Shot")
ui.Separator()
ui.MenuItem("Attach Selected Camera")
with ui.Menu("Sub-menu"):
ui.MenuItem("One")
ui.MenuItem("Two")
ui.MenuItem("Three")
ui.Separator()
ui.MenuItem("Four")
with ui.Menu("Five"):
ui.MenuItem("Six")
ui.MenuItem("Seven")
self.context_menu.show()
with ui.VStack():
button = ui.Button("Right click to context menu", height=0, width=0)
button.set_mouse_pressed_fn(lambda x, y, b, m, widget=button: show_context_menu(x, y, b, m, widget))
```
Left click for the push button menu with default menu style:
```execute 200
self.pushed_menu = None
def show_pushed_menu(x, y, button, modifier, widget):
self.pushed_menu = ui.Menu("Pushed menu")
with self.pushed_menu:
ui.MenuItem("Camera 1")
ui.MenuItem("Camera 2")
ui.MenuItem("Camera 3")
ui.Separator()
with ui.Menu("More Cameras"):
ui.MenuItem("This Menu is Pushed")
ui.MenuItem("and Aligned with a widget")
self.pushed_menu.show_at(
(int)(widget.screen_position_x), (int)(widget.screen_position_y + widget.computed_content_height)
)
with ui.VStack():
button = ui.Button("Pushed Button Menu", height=0, width=0)
button.set_mouse_pressed_fn(lambda x, y, b, m, widget=button: show_pushed_menu(x, y, b, m, widget))
```
### Separator
Separator is a type of MenuItem which creates a separator line in the UI elements.
From the above example, you can see the use of Separator in Menu.
Here is a list of styles you can customize on Separator:
> color (color): the color of the Separator
## MenuBar
All the Windows in Omni.UI can have a MenuBar. To add a MenuBar to your window add this flag to your constructor: omni.ui.Window(flags=ui.WINDOW_FLAGS_MENU_BAR). The MenuBar object can then be accessed through the menu_bar read-only property on your window.
A MenuBar is a container so it is built like a Frame or Stack but only takes Menu objects as children. You can leverage the 'priority' property on the Menu to order them. They will automatically be sorted when they are added, but if you change the priority of an item then you need to explicitly call sort().
MenuBar has exactly the same style list you can customize as Menu.
Here is an example of MenuBar with style for the Window:
```execute 200
from omni.ui import color as cl
style={"MenuBar": {
"background_color": cl.blue,
"color": cl.pink,
"background_selected_color": cl.green,
"border_radius": 2,
"border_width": 1,
"border_color": cl.yellow,
"padding": 2}}
self._window_menu_example = None
def create_and_show_window_with_menu():
if not self._window_menu_example:
self._window_menu_example = ui.Window(
"Window Menu Example",
width=300,
height=300,
flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_BACKGROUND,
)
menu_bar = self._window_menu_example.menu_bar
menu_bar.style = style
with menu_bar:
with ui.Menu("File"):
ui.MenuItem("Load")
ui.MenuItem("Save")
ui.MenuItem("Export")
with ui.Menu("Window"):
ui.MenuItem("Hide")
with self._window_menu_example.frame:
with ui.VStack():
ui.Button("This Window has a Menu")
def show_hide_menu(menubar):
menubar.visible = not menubar.visible
ui.Button("Click here to show/hide Menu", clicked_fn=lambda m=menu_bar: show_hide_menu(m))
def add_menu(menubar):
with menubar:
with ui.Menu("New Menu"):
ui.MenuItem("I don't do anything")
ui.Button("Add New Menu", clicked_fn=lambda m=menu_bar: add_menu(m))
self._window_menu_example.visible = True
with ui.HStack(width=0):
ui.Button("window with MenuBar Example", width=180, clicked_fn=create_and_show_window_with_menu)
ui.Label("this populates the menuBar", name="text", width=180, style={"margin_width": 10})
```
| 9,911 | Markdown | 43.25 | 478 | 0.649379 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/shades.md | # Shades
Shades are used to have multiple named color palettes with the ability for runtime switch. For example, one App could have several ui themes users can switch during using the App.
The shade can be defined with the following code:
```python
cl.shade(cl("#FF6600"), red=cl("#0000FF"), green=cl("#66FF00"))
```
It can be assigned to the color style. It's possible to switch the color with the following command globally:
```python
cl.set_shade("red")
```
## Example
```execute 200
from omni.ui import color as cl
from omni.ui import constant as fl
def set_color(color):
cl.example_color = color
def set_width(value):
fl.example_width = value
cl.example_color = cl.green
fl.example_width = 1.0
with ui.HStack(height=100, spacing=5):
with ui.ZStack():
ui.Rectangle(
style={
"background_color": cl.shade(
"aqua",
orange=cl.orange,
another=cl.example_color,
transparent=cl(0, 0, 0, 0),
black=cl.black,
),
"border_width": fl.shade(1, orange=4, another=8),
"border_radius": fl.one,
"border_color": cl.black,
},
)
ui.Label(
"ui.Rectangle(\n"
"\tstyle={\n"
'\t\t"background_color":\n'
"\t\t\tcl.shade(\n"
'\t\t\t\t"aqua",\n'
"\t\t\t\torange=cl(1, 0.5, 0),\n"
"\t\t\t\tanother=cl.example_color),\n"
'\t\t"border_width":\n'
"\t\t\tfl.shade(1, orange=4, another=8)})",
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.ZStack():
ui.Rectangle(
style={
"background_color": cl.example_color,
"border_width": fl.example_width,
"border_radius": fl.one,
"border_color": cl.black,
}
)
ui.Label(
"ui.Rectangle(\n"
"\tstyle={\n"
'\t\t"background_color": cl.example_color,\n'
'\t\t"border_width": fl.example_width)})',
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.VStack(style={"Button": {"background_color": cl("097EFF")}}):
ui.Label("Click the following buttons to change the shader of the left rectangle")
with ui.HStack():
ui.Button("cl.set_shade()", clicked_fn=partial(cl.set_shade, ""))
ui.Button('cl.set_shade("orange")', clicked_fn=partial(cl.set_shade, "orange"))
ui.Button('cl.set_shade("another")', clicked_fn=partial(cl.set_shade, "another"))
ui.Label("Click the following buttons to change the border width of the right rectangle")
with ui.HStack():
ui.Button("fl.example_width = 1", clicked_fn=partial(set_width, 1))
ui.Button("fl.example_width = 4", clicked_fn=partial(set_width, 4))
ui.Label("Click the following buttons to change the background color of both rectangles")
with ui.HStack():
ui.Button('cl.example_color = "green"', clicked_fn=partial(set_color, "green"))
ui.Button("cl.example_color = cl(0.8)", clicked_fn=partial(set_color, cl(0.8)))
## Double comment means hide from shippet
ui.Spacer(height=15)
##
```
## URL Shades Example
It's also possible to use shades for specifying shortcuts to the images and style-based paths.
```execute 200
from omni.ui import color as cl
from omni.ui.url_utils import url
def set_url(url_path: str):
url.example_url = url_path
walk = "resources/icons/Nav_Walkmode.png"
fly = "resources/icons/Nav_Flymode.png"
url.example_url = walk
with ui.HStack(height=100, spacing=5):
with ui.ZStack():
ui.Image(style={"image_url": url.example_url})
ui.Label(
'ui.Image(\n\tstyle={"image_url": cl.example_url})\n',
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.ZStack():
ui.ImageWithProvider(
style={
"image_url": url.shade(
"resources/icons/Move_local_64.png",
another="resources/icons/Move_64.png",
orange="resources/icons/Rotate_local_64.png",
)
}
)
ui.Label(
"ui.ImageWithProvider(\n"
"\tstyle={\n"
'\t\t"image_url":\n'
"\t\t\tst.shade(\n"
'\t\t\t\t"Move_local_64.png",\n'
'\t\t\t\tanother="Move_64.png")})\n',
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.HStack():
# buttons to change the url for the image
with ui.VStack():
ui.Button("url.example_url = Nav_Walkmode.png", clicked_fn=partial(set_url, walk))
ui.Button("url.example_url = Nav_Flymode.png", clicked_fn=partial(set_url, fly))
# buttons to switch between shades to different image
with ui.VStack():
ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, ""))
ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another"))
```
| 5,364 | Markdown | 33.612903 | 179 | 0.560962 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/line.md | # Lines and Curves
## Common Style of Lines and Curves
Here is a list of common style you can customize on all the Lines and Curves:
> color (color): the color of the line or curve
> border_width (float): the thickness of the line or curve
## Line
Line is the simplest shape that represents a straight line. It has two points, color and thickness. You can use Line to draw line shapes. Line doesn't have any other style except the common style for Lines and Curves.
Here is some of the properties you can customize on Line:
> alignment (enum): the Alignment defines where the line is in parent defined space. It is always scaled to fit.
Here is a list of the supported Alignment value for the line:
```execute 200
from omni.ui import color as cl
style ={
"Rectangle::table": {"background_color": cl.transparent, "border_color": cl(0.8), "border_width": 0.25},
"Line::demo": {"color": cl("#007777"), "border_width": 3},
"ScrollingFrame": {"background_color": cl.transparent},
}
alignments = {
"ui.Alignment.LEFT": ui.Alignment.LEFT,
"ui.Alignment.RIGHT": ui.Alignment.RIGHT,
"ui.Alignment.H_CENTER": ui.Alignment.H_CENTER,
"ui.Alignment.TOP": ui.Alignment.TOP,
"ui.Alignment.BOTTOM": ui.Alignment.BOTTOM,
"ui.Alignment.V_CENTER": ui.Alignment.V_CENTER,
}
with ui.ScrollingFrame(
height=100,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style=style,
):
with ui.HStack(height=100):
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": 10}}, spacing=10):
ui.Line(name="demo", alignment=value)
ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER)
```
By default, the line is scaled to fit.
```execute 200
from omni.ui import color as cl
style = {"Line::default": {"color": cl.red, "border_width": 1}}
with ui.Frame(height=50, style=style):
ui.Line(name="default")
```
Users can define the color and border_width to make customized lines.
```execute 200
from omni.ui import color as cl
with ui.Frame(height=50):
with ui.ZStack(width=200):
ui.Rectangle(style={"background_color": cl(0.4)})
ui.Line(alignment=ui.Alignment.H_CENTER, style={"border_width":5, "color": cl("#880088")})
```
## FreeLine
FreeLine is a line whose length will be determined by other widgets. The supported style list is the same as Line.
Here is an example of a FreeLine with style following two draggable circles. Notice the control widgets are not the start and end points of the line. By default, the alignment of the line is `ui.Alighment.V_CENTER`, and the line direction won't be changed by the control widgets.
```execute 200
from omni.ui import color as cl
with ui.Frame(height=200):
with ui.ZStack():
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Circle(width=10, height=10)
with ui.Placer(draggable=True, offset_x=150, offset_y=200):
control2 = ui.Circle(width=10, height=10)
# The rectangle that fits to the control points
ui.FreeLine(control1, control2, style={"color":cl.yellow})
```
## BezierCurve
BezierCurve is a shape drawn with multiple lines which has a bent or turns in it. They are used to model smooth curves that can be scaled indefinitely. BezierCurve doesn't have any other style except the common style for Lines and Curves.
Here is a BezierCurve with style:
```execute 200
from omni.ui import color as cl
style = {"BezierCurve": {"color": cl.red, "border_width": 2}}
ui.Spacer(height=2)
with ui.Frame(height=50, style=style):
ui.BezierCurve()
ui.Spacer(height=2)
```
## FreeBezierCurve
FreeBezierCurve is using two widgets to get the position of the curve ends. This is super useful to build graph connections. The supported style list is the same as BezierCurve.
Here is an example of a FreeBezierCurve which is controlled by 4 control points.
```execute 200
from omni.ui import color as cl
with ui.ZStack(height=400):
# The Bezier tangents
tangents = [(50, 50), (-50, -50)]
# Four draggable rectangles that represent the control points
placer1 = ui.Placer(draggable=True, offset_x=0, offset_y=0)
with placer1:
rect1 = ui.Rectangle(width=20, height=20)
placer2 = ui.Placer(draggable=True, offset_x=50, offset_y=50)
with placer2:
rect2 = ui.Rectangle(width=20, height=20)
placer3 = ui.Placer(draggable=True, offset_x=100, offset_y=100)
with placer3:
rect3 = ui.Rectangle(width=20, height=20)
placer4 = ui.Placer(draggable=True, offset_x=150, offset_y=150)
with placer4:
rect4 = ui.Rectangle(width=20, height=20)
# The bezier curve
curve = ui.FreeBezierCurve(rect1, rect4, style={"color": cl.red, "border_width": 5})
curve.start_tangent_width = ui.Pixel(tangents[0][0])
curve.start_tangent_height = ui.Pixel(tangents[0][1])
curve.end_tangent_width = ui.Pixel(tangents[1][0])
curve.end_tangent_height = ui.Pixel(tangents[1][1])
# The logic of moving the control points
def left_moved(_):
x = placer1.offset_x
y = placer1.offset_y
tangent = tangents[0]
placer2.offset_x = x + tangent[0]
placer2.offset_y = y + tangent[1]
def right_moved(_):
x = placer4.offset_x
y = placer4.offset_y
tangent = tangents[1]
placer3.offset_x = x + tangent[0]
placer3.offset_y = y + tangent[1]
def left_tangent_moved(_):
x1 = placer1.offset_x
y1 = placer1.offset_y
x2 = placer2.offset_x
y2 = placer2.offset_y
tangent = (x2 - x1, y2 - y1)
tangents[0] = tangent
curve.start_tangent_width = ui.Pixel(tangent[0])
curve.start_tangent_height = ui.Pixel(tangent[1])
def right_tangent_moved(_):
x1 = placer4.offset_x
y1 = placer4.offset_y
x2 = placer3.offset_x
y2 = placer3.offset_y
tangent = (x2 - x1, y2 - y1)
tangents[1] = tangent
curve.end_tangent_width = ui.Pixel(tangent[0])
curve.end_tangent_height = ui.Pixel(tangent[1])
# Callback for moving the control points
placer1.set_offset_x_changed_fn(left_moved)
placer1.set_offset_y_changed_fn(left_moved)
placer2.set_offset_x_changed_fn(left_tangent_moved)
placer2.set_offset_y_changed_fn(left_tangent_moved)
placer3.set_offset_x_changed_fn(right_tangent_moved)
placer3.set_offset_y_changed_fn(right_tangent_moved)
placer4.set_offset_x_changed_fn(right_moved)
placer4.set_offset_y_changed_fn(right_moved)
``` | 6,767 | Markdown | 38.811764 | 279 | 0.67578 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/units.md | # Length Units
The Framework UI offers several different units for expressing length: Pixel, Percent and Fraction. There is no restriction on where certain units should be used.
## Pixel
Pixel is the size in pixels and scaled with the HiDPI scale factor. Pixel is the default unit. If a number is not specified to be a certain unit, it is Pixel. e.g. `width=100` meaning `width=ui.Pixel(100)`.
```execute 200
with ui.HStack():
ui.Button("40px", width=ui.Pixel(40))
ui.Button("60px", width=ui.Pixel(60))
ui.Button("100px", width=100)
ui.Button("120px", width=120)
ui.Button("150px", width=150)
```
## Percent
Percent and Fraction units make it possible to specify sizes relative to the parent size. 1 Percent is 1/100 of the parent size.
```execute 200
with ui.HStack():
ui.Button("5%", width=ui.Percent(5))
ui.Button("10%", width=ui.Percent(10))
ui.Button("15%", width=ui.Percent(15))
ui.Button("20%", width=ui.Percent(20))
ui.Button("25%", width=ui.Percent(25))
```
## Fraction
Fraction length is made to take the available space of the parent widget and then divide it among all the child widgets with Fraction length in proportion to their Fraction factor.
```execute 200
with ui.HStack():
ui.Button("One", width=ui.Fraction(1))
ui.Button("Two", width=ui.Fraction(2))
ui.Button("Three", width=ui.Fraction(3))
ui.Button("Four", width=ui.Fraction(4))
ui.Button("Five", width=ui.Fraction(5))
```
| 1,462 | Markdown | 36.51282 | 206 | 0.697674 |
omniverse-code/kit/exts/omni.graph.docs/docs/tutorials/tutorial28.rst | .. _ogn_tutorial_simple_ogn_compute_vectorized_node:
Tutorial 28 - Node with simple OGN computeVectorized
====================================================
This tutorial demonstrates how to compose nodes that implements a very simple computeVectorized function. It shows how to access the data,
using the different available methods.
OgnTutorialVectorizedPassthrough.ogn
------------------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.TutorialVectorizedPassThrough", which takes input
of a floating point value, and just copy it to its output.
.. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial28/OgnTutorialVectorizedPassthrough.ogn
:linenos:
:language: json
OgnTutorialVectorizedPassthrough.cpp
------------------------------------
The *cpp* file contains the implementation of the node. It takes a floating point input and just copy it to its output,
demonstrating how to handle a vectorized compute. It shows what would be the implementation for a regular `compute` function,
and the different way it could implement a `computeVectorized` function.
- method #1: by switching the entire database to the next instance, while performing the computation in a loop
- method #2: by directly indexing attributes for the right instance in a loop
- method #3: by retrieving the raw data, and working directly with it
.. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial28/OgnTutorialVectorizedPassthrough.cpp
:linenos:
:language: c++
| 1,593 | reStructuredText | 52.133332 | 138 | 0.723792 |
omniverse-code/kit/exts/omni.graph.docs/docs/tutorials/tutorial29.rst | .. _ogn_tutorial_simple_abi_compute_vectorized_node:
Tutorial 29 - Node with simple ABI computeVectorized
====================================================
This tutorial demonstrates how to compose nodes that implements a very simple computeVectorized function using directly ABIs.
It shows how to access the data, using the different available methods.
OgnTutorialVectorizedABIPassThrough.cpp
---------------------------------------
The *cpp* file contains the implementation of the node. It takes a floating point input and just copy it to its output,
demonstrating how to handle a vectorized compute. It shows what would be the implementation for a regular `compute` function,
and the different way it could implement a `computeVectorized` function.
- method #1: by indexing attribute retrieval ABI function directly in a loop
- method #2: by mutating the attribute data handle in a loop
- method #3: by retrieving the raw data, and working directly with it
.. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial29/OgnTutorialVectorizedABIPassthrough.cpp
:linenos:
:language: c++
| 1,142 | reStructuredText | 53.428569 | 134 | 0.724168 |
omniverse-code/kit/exts/omni.graph.docs/docs/tutorials/tutorial30.rst | .. _ogn_tutorial_advanced_compute_vectorized_node:
Tutorial 30 - Node with more advanced computeVectorized
=======================================================
This tutorial demonstrates how to compose nodes that implements a computeVectorized function. It shows how to access the raw vectorized data,
and how it can be used to write a performant tight loop using SIMD instructions.
OgnTutorialSIMDAdd.ogn
--------------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.TutorialSIMDFloatAdd", which takes inputs
of 2 floating point values, and performs a sum.
.. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial30/OgnTutorialSIMDAdd.ogn
:linenos:
:language: json
OgnTutorialSIMDAdd.cpp
---------------------------------
The *cpp* file contains the implementation of the node. It takes two floating point inputs and performs a sum,
demonstrating how to handle a vectorized compute. It shows how to retrieve the vectorized array of inputs and output,
how to reason about the number of instances provided, and how to optimize the compute taking advantage of those vectorized inputs.
Since a SIMD instruction requires a given alignment for its arguments, the compute is divided in 3 sections:
- a first section that does a regular sum input on the few first instances that don't have a proper alignment
- a second, the heart of the function, that does as much SIMD adds as it can, performing them 4 elements by 4 elements
- a last section that perform regular sum on the few remaining items that did not fit in the SIMD register
.. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial30/OgnTutorialSIMDAdd.cpp
:linenos:
:language: c++
| 1,781 | reStructuredText | 56.483869 | 141 | 0.732173 |
omniverse-code/kit/exts/omni.graph.docs/docs/tutorials/tutorial10.rst | .. _ogn_tutorial_simpleDataPy:
Tutorial 10 - Simple Data Node in Python
========================================
The simple data node creates one input attribute and one output attribute of each of the simple types, where "simple"
refers to data types that have a single component and are not arrays. (e.g. "float" is simple, "float[3]" is not, nor is
"float[]"). See also :ref:`ogn_tutorial_simpleData` for a similar example in C++.
Automatic Python Node Registration
----------------------------------
By implementing the standard Carbonite extension interfact in Python, OmniGraph will know to scan your Python import
path for to recursively scan the directory, import all Python node files it finds, and register those nodes.
It will also deregister those nodes when the extension shuts down. Here is an example of the directory structure for
an extension with a single node in it. (For extensions that have a `premake5.lua` build script this will be in the
build directory. For standalone extensions it is in your source directory.)
.. code-block:: text
omni.my.extension/
omni/
my/
extension/
nodes/
OgnMyNode.ogn
OgnMyNode.py
OgnTutorialSimpleDataPy.ogn
---------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.SimpleDataPy", which has one
input and one output attribute of each simple type.
.. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial10/OgnTutorialSimpleDataPy.ogn
:linenos:
:language: json
OgnTutorialSimpleDataPy.py
--------------------------
The *py* file contains the implementation of the compute method, which modifies
each of the inputs in a simple way to create outputs that have different values.
.. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial10/OgnTutorialSimpleDataPy.py
:linenos:
:language: python
Note how the attribute values are available through the ``OgnTutorialSimpleDataPyDatabase`` class. The generated
interface creates access methods for every attribute, named for the attribute itself. They are all implemented as Python
properties, where inputs only have get methods and outputs have both get and set methods.
Pythonic Attribute Data
-----------------------
Three subsections are creating in the generated database class. The main section implements the node type ABI methods
and uses introspection on your node class to call any versions of the ABI methods you have defined (see later
tutorials for examples of how this works).
The other two subsections are classes containing attribute access properties for inputs and outputs. For naming
consistency the class members are called *inputs* and *outputs*. For example, you can access the value of the input
attribute named *foo* by referencing ``db.inputs.foo``.
Pythonic Attribute Access
-------------------------
In the USD file the attribute names are automatically namespaced as *inputs:FOO* or *outputs:BAR*. In the Python
interface the colon is illegal so the contained classes above are used to make use of the dot-separated equivalent,
as *inputs.FOO* or *outputs.BAR*.
While the underlying data types are stored in their exact form there is conversion when they are passed back to Python
as Python has a more limited set of data types, though they all have compatible ranges. For this class, these are the
types the properties provide:
+-------------------+---------------+
| Database Property | Returned Type |
+===================+===============+
| inputs.a_bool | bool |
+-------------------+---------------+
| inputs.a_half | float |
+-------------------+---------------+
| inputs.a_int | int |
+-------------------+---------------+
| inputs.a_int64 | int |
+-------------------+---------------+
| inputs.a_float | float |
+-------------------+---------------+
| inputs.a_double | float |
+-------------------+---------------+
| inputs.a_token | str |
+-------------------+---------------+
| outputs.a_bool | bool |
+-------------------+---------------+
| outputs.a_half | float |
+-------------------+---------------+
| outputs.a_int | int |
+-------------------+---------------+
| outputs.a_int64 | int |
+-------------------+---------------+
| outputs.a_float | float |
+-------------------+---------------+
| outputs.a_double | float |
+-------------------+---------------+
| outputs.a_token | str |
+-------------------+---------------+
The data returned are all references to the real data in the Fabric, our managed memory store, pointed to the
correct location at evaluation time.
Python Helpers
--------------
A few helpers are provided in the database class definition to help make coding with it more natural.
Python logging
++++++++++++++
Two helper functions are providing in the database class to help provide more information when the compute method of
a node has failed. Two methods are provided, both taking a formatted string describing the problem.
:py:meth:`log_error(message)<omni.graph.core.Database.log_error>` is used when the compute has run into some
inconsistent or unexpected data, such as two input arrays that are supposed to have the same size but do not,
like the normals and vertexes on a mesh.
:py:meth:`log_warning(message)<omni.graph.core.Database.log_warning>` can be used when the compute has hit an unusual
case but can still provide a consistent output for it, for example the deformation of an empty mesh would result in an
empty mesh and a warning since that is not a typical use for the node.
Direct Pythonic ABI Access
++++++++++++++++++++++++++
All of the generated database classes provide access to the underlying *INodeType* ABI for those rare situations
where you want to access the ABI directly. There are two members provided, which correspond to the objects passed
in to the ABI compute method.
There is the graph evaluation context member, :py:attr:`db.abi_context<omni.graph.core.Database.abi_context>`,
for accessing the underlying OmniGraph evaluation context and its interface.
There is also the OmniGraph node member, :py:attr:`db.abi_node<omni.graph.core.Database.abi_node>`, for accessing
the underlying OmniGraph node object and its interface.
| 6,464 | reStructuredText | 45.847826 | 122 | 0.64604 |
omniverse-code/kit/exts/omni.kit.widget.versioning/scripts/demo_checkpoint.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.ui as ui
from omni.kit.widget.versioning import CheckpointWidget, CheckpointCombobox, LAYOUT_TABLE_VIEW, LAYOUT_SLIM_VIEW
def create_checkpoint_view(url: str, layout: int):
view = CheckpointWidget(url, layout=layout)
view.add_context_menu(
"Menu Action",
"pencil.svg",
lambda menu, cp: print(f"Apply '{menu}' to '{cp.get_relative_path()}'"),
None,
)
view.set_mouse_double_clicked_fn(
lambda b, k, cp: print(f"Double clicked '{cp.get_relative_path()}")
)
if __name__ == "__main__":
url = "omniverse://ov-rc/Users/[email protected]/sphere.usd"
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
window = ui.Window("DemoFileBrowser", width=800, height=500, flags=window_flags)
with window.frame:
with ui.VStack(style={"margin": 0}):
ui.Label(url, height=30)
with ui.HStack():
create_checkpoint_view(url, LAYOUT_TABLE_VIEW)
ui.Spacer(width=10)
with ui.VStack(width=250):
create_checkpoint_view(url, LAYOUT_SLIM_VIEW)
ui.Spacer(width=10)
with ui.VStack(width=100, height=20):
combo_box = CheckpointCombobox(url, lambda sel: print(f"Selected: {sel.get_full_url()}"))
| 1,733 | Python | 42.349999 | 112 | 0.656088 |
omniverse-code/kit/exts/omni.kit.widget.versioning/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.3.8"
category = "Internal"
# 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 = "Versioning Widgets"
description="Versioning widgets that displays branch and checkpoint related information."
# 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", "checkpoint", "branch", "versioning"]
# 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.ui" = {}
"omni.client" = {}
# Main python module this extension provides, it will be publicly available as "import omni.example.hello".
[[python.module]]
name = "omni.kit.widget.versioning"
[[python.scriptFolder]]
path = "scripts"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=true",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers",
"omni.kit.window.content_browser",
]
stdoutFailPatterns.exclude = [
]
| 1,758 | TOML | 27.370967 | 107 | 0.722412 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/slim_view.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 functools import partial
from omni import ui
from .checkpoints_model import CheckpointItem, CheckpointModel
from .style import get_style
class CheckpointSlimView:
def __init__(self, model: CheckpointModel, **kwargs):
self._model = model
self._tree_view = None
self._delegate = CheckpointSlimViewDelegate(**kwargs)
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._build_ui()
def _build_ui(self):
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="TreeView.Background")
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
root_visible=False,
header_visible=False,
column_widths=[ui.Fraction(1)],
style_type_name_override="TreeView"
)
self._tree_view.set_selection_changed_fn(self._on_selection_changed)
def _on_selection_changed(self, selections):
if len(selections) > 1:
# only allow selecting one checkpoint
self._tree_view.selection = [selections[-1]]
if self._selection_changed_fn:
self._selection_changed_fn(selections)
def destroy(self):
if self._delegate:
self._delegate.destroy()
self._delegate = None
self._tree_view = None
class CheckpointSlimViewDelegate(ui.AbstractItemDelegate):
def __init__(self, **kwargs):
super().__init__()
self._widget = None
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
def build_branch(self, model, item, column_id, level, expanded):
pass
def build_widget(self, model: CheckpointModel, item: CheckpointItem, column_id: int, level: int, expanded: bool):
"""Create a widget per item"""
if not item or column_id > 0:
return
tooltip = f"#{item.entry.relative_path[1:]}. {item.entry.comment}\n"
tooltip += f"{CheckpointItem.datetime_to_string(item.entry.modified_time)}\n"
tooltip += f"{item.entry.modified_by}"
def on_mouse_pressed(item: CheckpointItem, x, y, b, key_mod):
if self._mouse_pressed_fn:
self._mouse_pressed_fn(b, key_mod, item)
def on_mouse_double_clicked(item: CheckpointItem, x, y, b, key_mod):
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(b, key_mod, item)
with ui.ZStack(style=get_style()):
self._widget = ui.Rectangle(
mouse_pressed_fn=partial(on_mouse_pressed, item),
mouse_double_clicked_fn=partial(on_mouse_double_clicked, item),
style_type_name_override="Card"
)
with ui.VStack(spacing=0):
ui.Spacer(height=4)
with ui.HStack():
ui.Label(
f"#{item.entry.relative_path[1:]}.", width=0,
style_type_name_override="Card.Label"
)
ui.Spacer(width=2)
if item.entry.comment:
ui.Label(
f"{item.entry.comment}",
tooltip=tooltip,
word_wrap=not item.comment_elided,
elided_text=item.comment_elided,
style_type_name_override="Card.Label"
)
else:
ui.Label(
f"{CheckpointItem.datetime_to_string(item.entry.modified_time)}",
style_type_name_override="Card.Label"
)
if item.entry.comment:
ui.Label(
f"{CheckpointItem.datetime_to_string(item.entry.modified_time)}",
style_type_name_override="Card.Label"
)
ui.Label(f"{item.entry.modified_by}", style_type_name_override="Card.Label")
ui.Spacer(height=8)
ui.Separator(style_type_name_override="Card.Separator")
ui.Spacer(height=4)
def destroy(self):
self._widget = None
self._mouse_pressed_fn = None
self._mouse_double_clicked_fn = None
| 4,884 | Python | 40.398305 | 117 | 0.564087 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/checkpoints_model.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 asyncio
import copy
import carb
import omni.client
import omni.kit.app
from omni.kit.async_engine import run_coroutine
import omni.ui as ui
from datetime import datetime
class DummyNoneNode:
def __init__(self, entry: omni.client.ListEntry):
self.relative_path = " <head>"
self.access = entry.access
self.flags = entry.flags
self.size = entry.size
self.modified_time = entry.modified_time
self.created_time = entry.created_time
self.modified_by = entry.modified_by
self.created_by = entry.created_by
self.version = entry.version
self.comment = "<Not using Checkpoint>"
class CheckpointItem(ui.AbstractItem):
def __init__(self, entry, url):
super().__init__()
self.comment_elided = True
self.url = url # url without query
self.entry = entry
@property
def comment(self):
if self.entry:
return self.entry.comment
return ""
def get_full_url(self):
if isinstance(self.entry, DummyNoneNode):
return self.url
return self.url + "?" + self.entry.relative_path
def get_relative_path(self):
if isinstance(self.entry, DummyNoneNode):
return None
return self.entry.relative_path
@staticmethod
def size_to_string(size: int):
return f"{size/1.e9:.2f} GB" if size > 1.e9 else (\
f"{size/1.e6:.2f} MB" if size > 1.e6 else f"{size/1.e3:.2f} KB")
@staticmethod
def datetime_to_string(dt: datetime):
return dt.strftime("%x %I:%M%p")
class CheckpointModel(ui.AbstractItemModel):
def __init__(self, show_none_entry):
super().__init__()
self._show_none_entry = show_none_entry
self._checkpoints = []
self._checkpoints_filtered = []
self._url = ""
self._incoming_url = ""
self._url_without_query = ""
self._search_kw = ""
self._checkpoint = None
self._on_list_checkpoint_fn = None
self._single_column = False
self._list_task = None
self._restore_task = None
self._set_url_task = None
self._multi_select = False
self._file_status_request = omni.client.register_file_status_callback(self._on_file_status)
self._resolve_subscription = None
self._run_loop = asyncio.get_event_loop()
def reset(self):
self._checkpoints = []
self._checkpoints_filtered = []
if self._list_task:
self._list_task.cancel()
self._list_task = None
if self._restore_task:
self._restore_task.cancel()
self._restore_task = None
def destroy(self):
self._on_list_checkpoint_fn = None
self.reset()
self._file_status_request = None
self._resolve_subscription = None
self._run_loop = None
if self._set_url_task:
self._set_url_task.cancel()
self._set_url_task = None
@property
def single_column(self):
return self._single_column
@single_column.setter
def single_column(self, value: bool):
"""Set the one-column mode"""
self._single_column = not not value
self._item_changed(None)
def empty(self):
return not self.get_item_children(None)
def set_multi_select(self, state: bool):
self._multi_select = state
def set_url(self, url):
self._incoming_url = url
# In file dialog, if select file A, then select file B, it emits selection event of "file A", "None", "file B"
# Do a async task to eat the "None" event to avoid flickering
async def delayed_set_url():
await omni.kit.app.get_app().next_update_async()
if self._url != self._incoming_url:
self._url = self._incoming_url
self.reset()
if self._url:
client_url = omni.client.break_url(self._url)
if client_url.query:
_, self._checkpoint = omni.client.get_branch_and_checkpoint_from_query(client_url.query)
else:
self._checkpoint = 0
self._url_without_query = omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=client_url.path,
fragment=client_url.fragment,
)
self.list_checkpoint()
self._resolve_subscription = omni.client.resolve_subscribe_with_callback(
self._url_without_query, [self._url_without_query], None,
lambda result, event, entry, url: self._on_file_change_event(result))
else:
self._no_checkpoint(True)
self._set_url_task = None
if not self._set_url_task:
self._set_url_task = run_coroutine(delayed_set_url())
def _on_file_change_event(self, result: omni.client.Result):
if result == omni.client.Result.OK:
async def set_url():
self.list_checkpoint()
# must run on main thread as this one does not have async loop...
asyncio.run_coroutine_threadsafe(set_url(), loop=self._run_loop)
def get_url(self):
return self._url
def set_search(self, keywords):
if self._search_kw != keywords:
self._search_kw = keywords
self._re_filter()
def set_on_list_checkpoint_fn(self, fn):
self._on_list_checkpoint_fn = fn
def on_list_checkpoints(self, file_entry, checkpoints_entries):
self._checkpoints = []
current_cp_item = None
for cp in checkpoints_entries:
item = CheckpointItem(cp, self._url_without_query)
self._checkpoints.append(item)
if not current_cp_item and str(self._checkpoint) == cp.relative_path[1:]:
current_cp_item = item
# OM-45546: Add back the <head> dummy option for files with checkpoints
if self._show_none_entry:
none_entry = DummyNoneNode(file_entry)
item = CheckpointItem(none_entry, self._url_without_query)
self._checkpoints.append(item)
if self._checkpoint == 0:
current_cp_item = item
# newest checkpoints at top
self._checkpoints.reverse()
self._re_filter()
self._item_changed(None)
if self._on_list_checkpoint_fn:
self._on_list_checkpoint_fn(supports_checkpointing=True,
has_checkpoints=len(self._checkpoints),
current_checkpoint=current_cp_item,
multi_select=self._multi_select)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._checkpoints if self._search_kw == "" else self._checkpoints_filtered
def get_item_value_model_count(self, item):
"""The number of columns"""
if self._single_column:
return 1
return 5
def list_checkpoint(self):
self._list_task = run_coroutine(self._list_checkpoint_async())
def restore_checkpoint(self, file_path, checkpoint_path):
self._restore_task = run_coroutine(self._restore_checkpoint(file_path, checkpoint_path))
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
return item.get_full_url()
async def _list_checkpoint_async(self):
if self._url_without_query == "omniverse://":
support_checkpointing = True
else:
client_url = omni.client.break_url(self._url_without_query)
server_url = omni.client.make_url(scheme=client_url.scheme, host=client_url.host, port=client_url.port)
result, server_info = await omni.client.get_server_info_async(server_url)
support_checkpointing = True if result and server_info and server_info.checkpoints_enabled else False
result, server_info = await omni.client.get_server_info_async(self._url_without_query)
if not result or not server_info or not server_info.checkpoints_enabled:
self._no_checkpoint(support_checkpointing)
return
# Have to use async version. _with_callback comes from a different thread
result, entry = await omni.client.stat_async(self._url_without_query)
if entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
# Can't have checkpoint on folder
self._no_checkpoint(support_checkpointing)
return
result, entries = await omni.client.list_checkpoints_async(self._url_without_query)
if result != omni.client.Result.OK:
carb.log_warn(f"Failed to get checkpoints for {self._url_without_query}: {result}")
self.on_list_checkpoints(entry, entries)
self._list_task = None
def _on_file_status(self, url, status, percent):
if status == omni.client.FileStatus.WRITING and percent == 100 and url == self._url_without_query:
async def set_url():
self.list_checkpoint()
# must run on main thread as this one does not have async loop...
asyncio.run_coroutine_threadsafe(set_url(), loop=self._run_loop)
def _no_checkpoint(self, support_checkpointing):
self._checkpoints.clear()
self._item_changed(None)
if self._on_list_checkpoint_fn:
self._on_list_checkpoint_fn(supports_checkpointing=support_checkpointing,
has_checkpoints=False,
current_checkpoint=None,
multi_select=self._multi_select)
async def _restore_checkpoint(self, file_path, checkpoint_path):
id = checkpoint_path.rfind('&') + 1
relative_path = checkpoint_path[id:] if id > 0 else ''
result = await omni.client.copy_async(checkpoint_path, file_path, message=f"Restored checkpoint #{relative_path}")
carb.log_warn(f"Restore checkpoint {checkpoint_path} to {file_path}: {result}")
if result:
self.list_checkpoint()
def _re_filter(self):
self._checkpoints_filtered.clear()
if self._search_kw == "":
self._checkpoints_filtered = copy.copy(self._checkpoints)
else:
kws = self._search_kw.split(' ')
for cp in self._checkpoints:
for kw in kws:
if kw.lower() in cp.entry.comment.lower():
self._checkpoints_filtered.append(cp)
break
if kw.lower() in cp.entry.relative_path.lower():
self._checkpoints_filtered.append(cp)
break
self._item_changed(None)
| 11,745 | Python | 38.548821 | 122 | 0.587399 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/style.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
import omni.ui as ui
from omni.kit.widget.versioning import get_icons_path
def get_style():
style = carb.settings.get_settings().get("/persistent/app/window/uiStyle")
if not style:
style = "NvidiaDark"
FONT_SIZE = 14.0
if style == "NvidiaLight": # pragma: no cover -- unused style
WIDGET_BACKGROUND_COLOR = 0xFF454545
BUTTON_BACKGROUND_COLOR = 0xFF545454
BUTTON_FONT_COLOR = 0xFFD6D6D6
INPUT_BACKGROUND_COLOR = 0xFF454545
INPUT_FONT_COLOR = 0xFFD6D6D6
INPUT_HINT_COLOR = 0xFF9E9E9E
CARD_BACKGROUND_COLOR = 0xFF545454
CARD_HOVERED_COLOR = 0xFF6E6E6E
CARD_SELECTED_COLOR = 0xFFBEBBAE
CARD_FONT_COLOR = 0xFFD6D6D6
CARD_SEPARATOR_COLOR = 0x44D6D6D6
MENU_BACKGROUND_COLOR = 0xFF454545
MENU_FONT_COLOR = 0xFFD6D6D6
MENU_SEPARATOR_COLOR = 0x44D6D6D6
NOTIFICATION_BACKGROUND_COLOR = 0xFF545454
NOTIFICATION_FONT_COLOR = 0xFFD6D6D6
TREEVIEW_BACKGROUND_COLOR = 0xFF545454
TREEVIEW_ITEM_COLOR = 0xFFD6D6D6
TREEVIEW_HEADER_BACKGROUND_COLOR = 0xFF545454
TREEVIEW_HEADER_COLOR = 0xFFD6D6D6
TREEVIEW_SELECTED_COLOR = 0x109D905C
else:
WIDGET_BACKGROUND_COLOR = 0xFF343432
BUTTON_BACKGROUND_COLOR = 0xFF23211F
BUTTON_FONT_COLOR = 0xFF9E9E9E
INPUT_BACKGROUND_COLOR = 0xFF23211F
INPUT_FONT_COLOR = 0xFF9E9E9E
INPUT_HINT_COLOR = 0xFF4A4A4A
CARD_BACKGROUND_COLOR = 0xFF23211F
CARD_HOVERED_COLOR = 0xFF3A3A3A
CARD_SELECTED_COLOR = 0xFF8A8777
CARD_FONT_COLOR = 0xFF9E9E9E
CARD_SEPARATOR_COLOR = 0x449E9E9E
MENU_BACKGROUND_COLOR = 0xFF343432
MENU_FONT_COLOR = 0xFF9E9E9E
MENU_SEPARATOR_COLOR = 0x449E9E9E
NOTIFICATION_BACKGROUND_COLOR = 0xFF343432
NOTIFICATION_FONT_COLOR = 0xFF9E9E9E
TREEVIEW_BACKGROUND_COLOR = 0xFF23211F
TREEVIEW_ITEM_COLOR = 0xFF9E9E9E
TREEVIEW_HEADER_BACKGROUND_COLOR = 0xFF343432
TREEVIEW_HEADER_COLOR = 0xFF9E9E9E
TREEVIEW_SELECTED_COLOR = 0x664F4D43
style = {
"Window": {"secondary_background_color": 0},
"ScrollingFrame": {"background_color": WIDGET_BACKGROUND_COLOR, "margin_width": 0},
"ComboBox": {"background_color": BUTTON_BACKGROUND_COLOR, "color": BUTTON_FONT_COLOR},
"ComboBox.Field": {"background_color": INPUT_BACKGROUND_COLOR, "color": INPUT_FONT_COLOR},
"ComboBox.Field::hint": {"background_color": 0x0, "color": INPUT_HINT_COLOR},
"Card": {"background_color": CARD_BACKGROUND_COLOR, "color": CARD_FONT_COLOR, "margin_height": 1, "border_width": 2},
"Card:hovered": {"background_color": CARD_HOVERED_COLOR, "border_color": CARD_HOVERED_COLOR, "border_width": 2},
"Card:pressed": {"background_color": CARD_HOVERED_COLOR, "border_color": CARD_HOVERED_COLOR, "border_width": 2},
"Card:selected": {"background_color": CARD_SELECTED_COLOR, "border_color": CARD_SELECTED_COLOR, "border_width": 2},
"Card.Label": {"background_color": 0x0, "color": CARD_FONT_COLOR, "margin_width": 4},
"Card.Label:selected": {"background_color": 0x0, "color": CARD_BACKGROUND_COLOR, "margin_width": 4},
"Card.Separator": {"background_color": 0x0, "color": CARD_SEPARATOR_COLOR},
"Menu": {"background_color": MENU_BACKGROUND_COLOR, "color": MENU_FONT_COLOR, "border_radius": 2},
"Menu.Item": {"background_color": 0x0, "margin": 0},
"Menu.Separator": {"background_color": 0x0, "color": MENU_SEPARATOR_COLOR, "alignment": ui.Alignment.CENTER},
"Notification": {"background_color": NOTIFICATION_BACKGROUND_COLOR, "margin_width": 0},
"Notification.Label": {"background_color": 0x0, "color": NOTIFICATION_FONT_COLOR, "alignment": ui.Alignment.CENTER_TOP},
"TreeView": {"background_color": 0x0},
"TreeView.Background": {"background_color": TREEVIEW_BACKGROUND_COLOR},
"TreeView.Header": {"background_color": TREEVIEW_HEADER_BACKGROUND_COLOR, "color": TREEVIEW_HEADER_COLOR},
"TreeView.Header::label": {"margin": 4},
"TreeView.Item": {"margin":4, "background_color": 0x0, "color": TREEVIEW_ITEM_COLOR},
"TreeView.Item:selected": {"margin":4, "color": TREEVIEW_SELECTED_COLOR},
}
return style
| 4,783 | Python | 49.357894 | 128 | 0.673218 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/extension.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.ext
from functools import lru_cache
from pathlib import Path
ICON_PATH = ""
@lru_cache()
def get_icons_path() -> str:
return ICON_PATH
class VerioningExtension(omni.ext.IExt):
def on_startup(self, ext_id):
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global ICON_PATH
ICON_PATH = Path(extension_path).joinpath("data").joinpath("icons")
def on_shutdown(self):
pass
| 927 | Python | 28.935483 | 76 | 0.731392 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/__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.
#
LAYOUT_SLIM_VIEW = 1
LAYOUT_TABLE_VIEW = 2
LAYOUT_DEFAULT = 3
from .extension import *
from .widget import CheckpointWidget
from .checkpoints_model import CheckpointModel, CheckpointItem
from .checkpoint_combobox import CheckpointCombobox
from .checkpoint_helper import CheckpointHelper
| 722 | Python | 37.05263 | 76 | 0.815789 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/context_menu.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.ui as ui
from typing import Callable, List
from functools import partial
from carb import log_warn
from .checkpoints_model import CheckpointItem
from .style import get_style
class ContextMenu:
"""
Creates popup menu for the hovered CheckpointItem. In addition to the set of default actions below,
users can add more via the add_menu_item API.
"""
def __init__(self):
self._context_menu: ui.Menu = None
self._menu_dict: list = []
self._context: dict = None
self._build_ui()
@property
def menu(self) -> ui.Menu:
""":obj:`omni.ui.Menu` The menu widget"""
return self._context_menu
@property
def context(self) -> dict:
"""dict: Provides data to the callback. Available keys are {'item', 'is_bookmark', 'is_connection', 'selected'}"""
return self._context
def show(self, item: CheckpointItem, selected: List[CheckpointItem] = []):
"""
Creates the popup menu from definition for immediate display. Receives as input, information about the
item. These values are made available to the callback via the 'context' dictionary.
Args:
item (CheckpointItem): Item for which to create menu.,
selected (List[CheckpointItem]): List of currently selected items. Default [].
"""
self._context = {}
self._context["item"] = item
self._context["selected"] = selected
self._context_menu = ui.Menu("Context menu", style=get_style(), style_type_name_override="Menu")
with self._context_menu:
prev_entry = None
for i, menu_entry in enumerate(self._menu_dict):
if i == len(self._menu_dict) - 1 and not menu_entry.get("name"):
# Don't draw separator as last item
break
if menu_entry.get("name") or (prev_entry and prev_entry.get("name")):
# Don't draw 2 separators in a row
self._build_menu(menu_entry, self._context)
prev_entry = menu_entry
# Show it
if len(self._menu_dict) > 0:
self._context_menu.show()
def _build_ui(self):
pass
def _build_menu(self, menu_entry, context):
from omni.kit.ui import get_custom_glyph_code
enabled = 1
if "enable_fn" in menu_entry and menu_entry["enable_fn"]:
enabled = menu_entry["enable_fn"](context)
if enabled < 0:
return
if menu_entry["name"] == "":
ui.Separator(style_type_name_override="Menu.Separator")
else:
menu_name = ""
if "glyph" in menu_entry:
menu_name = " " + get_custom_glyph_code("${glyphs}/" + menu_entry["glyph"]) + " "
if "onclick_fn" in menu_entry and menu_entry["onclick_fn"]:
menu_item = ui.MenuItem(
menu_name + menu_entry["name"],
triggered_fn=partial(menu_entry["onclick_fn"], context),
enabled=bool(enabled),
style_type_name_override="Menu.Item",
)
else:
menu_item = ui.MenuItem(menu_name + menu_entry["name"], enabled=False, style_type_name_override="Menu.Item")
def add_menu_item(self, name: str, glyph: str, onclick_fn: Callable, enable_fn: Callable, index: int = -1) -> str:
"""
Adds menu item, with corresponding callbacks, to this context menu.
Args:
name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the context menu.
glyph (str): Associated glyph to display for this menu item.
onclick_fn (Callable): This callback function is executed when the menu item is clicked. Function signature:
void fn(name: str, item: CheckpointItem), where name is menu name.
enable_fn (Callable): Returns 1 to enable this menu item, 0 to disable, -1 to hide.
Function signature: bool fn(name: str, item: CheckpointItem).
index (int): The position that this menu item will be inserted to.
Returns:
str: Name of menu item if successful, None otherwise.
"""
if name and name in [item.get("name", None) for item in self._menu_dict]:
# Reject duplicates
return None
menu_item = {"name": name, "glyph": glyph or ""}
if onclick_fn:
menu_item["onclick_fn"] = lambda context, name=name: onclick_fn(name, context["item"])
if enable_fn:
menu_item["enable_fn"] = lambda context, name=name: enable_fn(name, context["item"])
if index < 0 or index >= len(self._menu_dict):
index = len(self._menu_dict)
self._menu_dict.insert(index, menu_item)
return name
def delete_menu_item(self, name: str):
"""
Deletes the menu item, with the given name, from this context menu.
Args:
name (str): Name of the menu item (e.g. 'Open').
"""
if not name:
return
found = (i for i, item in enumerate(self._menu_dict) if name == item.get("name", None))
for j in sorted([i for i in found], reverse=True):
del self._menu_dict[j]
def _build_ui(self):
'''
Example:
self._menu_dict = [
{
"name": "Test",
"glyph": "pencil.svg",
"onclick_fn": lambda context: print(">>> TESTING"),
},
]
'''
pass
def _on_copy_to_clipboard(self, item: CheckpointItem):
try:
import omni.kit.clipboard
omni.kit.clipboard.copy(item.path)
except ImportError:
log_warn("Warning: Could not import omni.kit.clipboard.")
def destroy(self):
self._context_menu = None
self._menu_dict = None
self._context = None
| 6,430 | Python | 36.389535 | 124 | 0.580093 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/checkpoint_helper.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 asyncio
import omni.client
from typing import Callable
class CheckpointHelper:
server_cache = {}
@staticmethod
def extract_server_from_url(url: str) -> str:
server_url = ""
if url:
client_url = omni.client.break_url(url)
server_url = omni.client.make_url(scheme=client_url.scheme, host=client_url.host, port=client_url.port)
return server_url
@staticmethod
async def is_checkpoint_enabled_async(url: str) -> bool:
server_url = CheckpointHelper.extract_server_from_url(url)
if not server_url:
enabled = False
elif server_url in CheckpointHelper.server_cache:
enabled = CheckpointHelper.server_cache[server_url]
else:
result, server_info = await omni.client.get_server_info_async(server_url)
supports_checkpoint = result and server_info and server_info.checkpoints_enabled
CheckpointHelper.server_cache[server_url] = supports_checkpoint
enabled = supports_checkpoint
return enabled
@staticmethod
def is_checkpoint_enabled_with_callback(url: str, callback: Callable):
async def is_checkpoint_enabled_async(url: str, callback: Callable):
enabled = await CheckpointHelper.is_checkpoint_enabled_async(url)
if callback:
callback(CheckpointHelper.extract_server_from_url(url), enabled)
asyncio.ensure_future(is_checkpoint_enabled_async(url, callback)) | 1,937 | Python | 40.234042 | 115 | 0.694373 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/checkpoint_widget.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 asyncio
import weakref
import omni.kit.app
import omni.ui as ui
from .checkpoints_model import CheckpointsModel
from .checkpoints_delegate import CheckpointsDelegate
from .style import get_style
class CheckpointWidget:
def __init__(self, url: str = "", width=700, show_none_entry=False, **kwargs):
"""
Build a CheckpointWidget. Called while constructing UI layout.
Args:
url (str): The url of the file to list checkpoints from.
width (str): Width of the checkpoint widget.
show_none_entry (bool): Whether to show a dummy "head" entry to represent not using checkpoint.
"""
self._checkpoint_model = CheckpointsModel(show_none_entry)
self._checkpoint_model.set_on_list_checkpoint_fn(self._on_list_checkpoint)
self._checkpoint_delegate = CheckpointsDelegate(kwargs.get("open_file", None))
self._tree_view = None
self._labels = {}
self._on_selection_changed_fn = []
self._on_list_checkpoint_fn = kwargs.get("on_list_checkpoint_fn", None)
self._build_layout(width)
self.set_url(url)
self.set_multi_select(False)
self._on_list_checkpoint(supports_checkpointing=True,
has_checkpoints=True,
current_checkpoint=None,
multi_select=False)
def __del__(self):
self.destroy()
def destroy(self):
self._tree_view = None
self._labels = None
self._checkpoint_stack = None
self._root_frame = None
if self._checkpoint_model:
self._checkpoint_model.destroy()
self._checkpoint_model = None
self._checkpoint_delegate = None
self._on_selection_changed_fn.clear()
def set_multi_select(self, state:bool):
self._checkpoint_model.set_multi_select(state)
def set_url(self, url: str):
self._checkpoint_model.set_url(url)
def set_search(self, keywords):
self._checkpoint_model.set_search(keywords)
def add_on_selection_changed_fn(self, fn):
self._on_selection_changed_fn.append(fn)
def set_on_list_checkpoint_fn(self, fn):
self._on_list_checkpoint_fn = fn
def empty(self):
return self._checkpoint_model.empty()
def _build_layout(self, width):
self._root_frame = ui.Frame(visible=True, width=width)
with self._root_frame:
with ui.ZStack():
self._labels["cp_not_suppored"] = ui.Label("Checkpoints Not Supported.", style={"font_size": 18})
self._labels["multi_select"] = ui.Label("Checkpoints Cannot Be Displayed For Multiple Items.", style={"font_size": 18})
with ui.VStack():
self._checkpoint_stack = ui.VStack(visible=False, style=get_style())
with self._checkpoint_stack:
with ui.ScrollingFrame(
height=ui.Fraction(1),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="TreeView",
):
self._tree_view = ui.TreeView(
self._checkpoint_model,
root_visible=False,
header_visible=True,
delegate=self._checkpoint_delegate,
column_widths=[80, ui.Fraction(1), 20, 120, 100, 150],
)
# only allow selecting one checkpoint
def on_selection_changed(weak_self, selection):
weak_self = weak_self()
if not weak_self:
return
if len(selection) > 1:
selection = [selection[-1]]
if weak_self._tree_view.selection != selection:
weak_self._tree_view.selection = selection
for fn in weak_self._on_selection_changed_fn:
fn(selection[0] if selection else None)
self._tree_view.set_selection_changed_fn(
lambda selection, weak_self=weakref.ref(self): on_selection_changed(weak_self, selection)
)
self._labels["no_checkpoint"] = ui.Label("No Checkpoint")
def _on_list_checkpoint(self, supports_checkpointing, has_checkpoints, current_checkpoint, multi_select):
if multi_select:
self._root_frame.visible = True
self._checkpoint_stack.visible = False
self._labels["no_checkpoint"].visible = False
self._labels["cp_not_suppored"].visible = False
self._labels["multi_select"].visible = True
elif not supports_checkpointing:
self._checkpoint_stack.visible = False
self._root_frame.visible = True
self._labels["no_checkpoint"].visible = False
self._labels["cp_not_suppored"].visible = True
self._labels["multi_select"].visible = False
else:
self._checkpoint_stack.visible = has_checkpoints
self._root_frame.visible = has_checkpoints
self._labels["cp_not_suppored"].visible = False
self._labels["multi_select"].visible = False
self._labels["no_checkpoint"].visible = not has_checkpoints
# Must delay the selection for one frame so that treeview is synced with model for scroll to selection to work.
async def delayed_selection(weak_tree_view, callback):
tree_view = weak_tree_view()
if not tree_view:
return
await omni.kit.app.get_app().next_update_async()
if current_checkpoint:
tree_view.selection = [current_checkpoint]
else:
tree_view.selection = []
if callback:
callback(tree_view.selection)
asyncio.ensure_future(delayed_selection(weakref.ref(self._tree_view), self._on_list_checkpoint_fn))
| 6,876 | Python | 42.251572 | 135 | 0.566172 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/widget.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 asyncio
import weakref
import omni.kit.app
import omni.ui as ui
import carb
from typing import List, Callable
from . import LAYOUT_SLIM_VIEW, LAYOUT_TABLE_VIEW, LAYOUT_DEFAULT
from .checkpoints_model import CheckpointModel, CheckpointItem
from .table_view import CheckpointTableView
from .slim_view import CheckpointSlimView
from .context_menu import ContextMenu
from .style import get_style
class CheckpointWidget:
def __init__(self, url: str = "", show_none_entry=False, **kwargs):
"""
Build a CheckpointWidget. Called while constructing UI layout.
Args:
url (str): The url of the file to list checkpoints from.
show_none_entry (bool): Whether to show a dummy "head" entry to represent not using checkpoint.
"""
self._model = CheckpointModel(show_none_entry)
self._model.set_on_list_checkpoint_fn(self._on_list_checkpoint)
self._view = None
self._checkpoint_stack = None
self._notify_stack = None
self._labels = {}
self._context_menu = None
self._theme = carb.settings.get_settings().get("/persistent/app/window/uiStyle") or "NvidiaDark"
self._layout = kwargs.get("layout", LAYOUT_DEFAULT)
self._on_selection_changed_fn = []
self._on_list_checkpoint_fn = kwargs.get("on_list_checkpoint_fn", None)
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
self._build_ui()
self.set_url(url)
def __del__(self):
self.destroy()
def destroy(self):
self._view = None
self._labels = None
self._checkpoint_stack = None
self._notify_stack = None
if self._model:
self._model.destroy()
self._model = None
if self._context_menu:
self._context_menu.destroy()
self._content_menu = None
self._on_selection_changed_fn.clear()
def set_mouse_pressed_fn(self, mouse_pressed_fn: Callable):
self._mouse_pressed_fn = mouse_pressed_fn
def set_mouse_double_clicked_fn(self, mouse_double_clicked_fn: Callable):
self._mouse_double_clicked_fn = mouse_double_clicked_fn
def set_multi_select(self, state:bool):
self._model.set_multi_select(state)
def set_url(self, url: str):
self._model.set_url(url)
def set_search(self, keywords):
self._model.set_search(keywords)
def add_on_selection_changed_fn(self, fn):
self._on_selection_changed_fn.append(fn)
def set_on_list_checkpoint_fn(self, fn):
self._on_list_checkpoint_fn = fn
def empty(self):
return self._model.empty()
def _build_ui(self):
with ui.Frame(visible=True, style=get_style()):
with ui.ZStack():
self._notify_stack = ui.VStack(style_type_name_override="Notification", visible=False)
with self._notify_stack:
ui.Spacer(height=20)
with ui.HStack(height=0):
ui.Spacer()
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
thumbnail = f"{ext_path}/data/icons/{self._theme}/select_file.png"
ui.ImageWithProvider(thumbnail,
width=100, height=100,
fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT)
ui.Spacer()
ui.Spacer(height=20)
with ui.HStack(height=0):
ui.Spacer()
with ui.HStack(width=150):
self._labels["default"] = ui.Label(
"Select a file to see Checkpoints.",
word_wrap=True, style_type_name_override="Notification.Label", visible=True)
self._labels["cp_not_suppored"] = ui.Label(
"Location does not support Checkpoints.",
word_wrap=True, style_type_name_override="Notification.Label", visible=False)
self._labels["multi_select"] = ui.Label(
"Checkpoints Cannot Be Displayed For Multiple Items.",
word_wrap=True, style_type_name_override="Notification.Label", visible=False)
self._labels["no_checkpoint"] = ui.Label(
"Selected file has no Checkpoints.",
word_wrap=True, style_type_name_override="Notification.Label", visible=False)
ui.Spacer()
ui.Spacer()
self._checkpoint_stack = ui.VStack(visible=False)
with self._checkpoint_stack:
if self._layout in [LAYOUT_SLIM_VIEW, LAYOUT_DEFAULT]:
self._model.single_column = True
self._view = CheckpointSlimView(
self._model,
selection_changed_fn=self._on_selection_changed,
mouse_pressed_fn=self._on_mouse_pressed,
mouse_double_clicked_fn=self._on_mouse_double_clicked
)
else:
self._view = CheckpointTableView(
self._model,
selection_changed_fn=self._on_selection_changed,
mouse_pressed_fn=self._on_mouse_pressed,
mouse_double_clicked_fn=self._on_mouse_double_clicked
)
# Create popup menus
self._context_menu = ContextMenu()
self._on_list_checkpoint(supports_checkpointing=False,
has_checkpoints=False,
current_checkpoint=None,
multi_select=False)
def _on_selection_changed(self, selections: List[CheckpointItem]):
for selection_changed_fn in self._on_selection_changed_fn:
selection_changed_fn(selections[0] if selections else None)
def _on_mouse_pressed(self, button: int, key_mod: int, item: CheckpointItem):
if button == 1:
# Right mouse button: display context menu
self._context_menu.show(item)
if self._mouse_pressed_fn:
self.mouse_pressed_fn(button, key_mod, item)
def _on_mouse_double_clicked(self, button: int, key_mod: int, item: CheckpointItem):
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(button, key_mod, item)
def _on_list_checkpoint(self, supports_checkpointing, has_checkpoints, current_checkpoint, multi_select):
if has_checkpoints and not multi_select:
self._checkpoint_stack.visible = True
self._notify_stack.visible = False
else:
self._checkpoint_stack.visible = False
self._notify_stack.visible = True
if self._notify_stack.visible:
self._labels["default"].visible = False
if multi_select:
self._labels["no_checkpoint"].visible = False
self._labels["cp_not_suppored"].visible = False
self._labels["multi_select"].visible = True
elif not supports_checkpointing:
self._labels["no_checkpoint"].visible = False
self._labels["cp_not_suppored"].visible = True
self._labels["multi_select"].visible = False
else:
self._labels["no_checkpoint"].visible = not has_checkpoints
self._labels["cp_not_suppored"].visible = False
self._labels["multi_select"].visible = False
# Must delay the selection for one frame so that treeview is synced with model for scroll to selection to work.
async def delayed_selection(weak_view, callback):
view = weak_view()
if not view:
return
await omni.kit.app.get_app().next_update_async()
if current_checkpoint:
view.selection = [current_checkpoint]
else:
view.selection = []
if callback:
callback(view.selection)
asyncio.ensure_future(delayed_selection(weakref.ref(self._view), self._on_list_checkpoint_fn))
@staticmethod
def create_checkpoint_widget() -> 'CheckpointWidget':
widget = CheckpointWidget(show_none_entry=True)
return widget
@staticmethod
def on_model_url_changed(widget: 'CheckpointWidget', urls: List[str]):
if not widget:
return
if urls:
widget.set_url(urls[-1] or None)
widget.set_multi_select(len(urls) > 1)
else:
widget.set_url(None)
widget.set_multi_select(False)
@staticmethod
def delete_checkpoint_widget(widget: 'CheckpointWidget'):
if widget:
widget.destroy()
def add_context_menu(self, name: str, glyph: str, click_fn: Callable, enable_fn: Callable, index: int = -1) -> str:
"""
Adds menu item, with corresponding callbacks, to the context menu.
Args:
name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the context menu.
glyph (str): Associated glyph to display for this menu item.
click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature:
void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item.
enable_fn (Callable): Returns 1 to enable this menu item, 0 to disable, -1 to hide.
Function signature: bool fn(name: str, item: CheckpointItem).
index (int): The position that this menu item will be inserted to.
Returns:
str: Name of menu item if successful, None otherwise.
"""
if self._context_menu:
return self._context_menu.add_menu_item(name, glyph, click_fn, enable_fn, index=index)
return None
def delete_context_menu(self, name: str):
"""
Deletes the menu item, with the given name, from the context menu.
Args:
name (str): Name of the menu item (e.g. 'Open').
"""
if self._context_menu:
self._context_menu.delete_menu_item(name)
| 11,060 | Python | 42.03891 | 120 | 0.576582 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/checkpoint_combobox.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 asyncio
from functools import lru_cache
from typing import Optional
import omni.client
import omni.kit.app
import omni.ui as ui
import carb
from .widget import CheckpointWidget
from .style import get_style
from .checkpoints_model import CheckpointItem
@lru_cache()
def _get_down_arrow_icon_path(theme: str) -> str:
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
return f"{ext_path}/data/icons/{theme}/down_arrow.svg"
class CheckpointCombobox:
def __init__(
self,
absolute_asset_path,
on_selection_changed_fn,
width: ui.Length=ui.Pixel(100),
has_pre_spacer: bool=True,
popup_width: int=450,
visible: bool=True,
modal: bool=False,
):
self._get_comment_task = None
self._theme = carb.settings.get_settings().get("/persistent/app/window/uiStyle") or "NvidiaDark"
self._url = absolute_asset_path
self._width = width
self._has_pre_spacer = has_pre_spacer
self._popup_width = popup_width
self._visible = visible
self._modal = modal
self.__on_selection_changed_fn = on_selection_changed_fn
self.__container: Optional[ui.ZStack] = None
self.__checkpoint_field: Optional[ui.StringField] = None
self._build_checkpoint_combobox()
def destroy(self):
self._checkpoint_list_popup = None
self._search_field_value_change_sub = None
self._search_field_begin_edit_sub = None
self._search_field_end_edit_sub = None
if self._get_comment_task:
self._get_comment_task.cancel()
self._get_comment_task = None
@property
def visible(self) -> bool:
return self._visible
@visible.setter
def visible(self, value: bool) -> None:
self._visible = value
if self.__container:
self.__container.visible = value
@property
def url(self) -> str:
return self._url
@url.setter
def url(self, value: str) -> None:
self._url = value
if self.__checkpoint_field:
self.__config_field()
def _build_checkpoint_combobox(self):
self.__container = ui.ZStack(visible=self._visible, style=get_style())
with self.__container:
with ui.HStack():
if self._has_pre_spacer:
ui.Spacer()
with ui.ZStack(width=self._width):
self.__checkpoint_field = ui.StringField(read_only=True, enabled=False, style_type_name_override="ComboBox")
self.__config_field()
arrow_outer_size = 14
arrow_size = 10
with ui.HStack():
ui.Spacer()
with ui.VStack(width=arrow_outer_size):
ui.Spacer(height=6)
ui.Image(_get_down_arrow_icon_path(self._theme), width=arrow_size, height=arrow_size)
def on_mouse_pressed(field):
popup_width = self._popup_width if self._popup_width > 0 else field.computed_width
popup_height = 200
self._show_checkpoint_widget(
self._url,
field.screen_position_x - popup_width + field.computed_content_width,
field.screen_position_y,
field.computed_content_height,
popup_width,
popup_height,
)
self.__checkpoint_field.set_mouse_pressed_fn(
lambda x, y, b, m, field=self.__checkpoint_field: on_mouse_pressed(field)
)
return None
def __config_field(self):
(client_url, checkpoint) = self.__get_current_checkpoint()
self.__checkpoint_field.model.set_value(str(checkpoint) if checkpoint else "<head>")
if checkpoint:
async def get_comment():
result, entries = await omni.client.list_checkpoints_async(self._url)
if result:
for entry in entries:
if entry.relative_path == client_url.query:
self.__checkpoint_field.set_tooltip(entry.comment)
break
self._get_comment_task = asyncio.ensure_future(get_comment())
else:
self.__checkpoint_field.set_tooltip("<Not using Checkpoint>")
def __get_current_checkpoint(self):
checkpoint = 0
client_url = omni.client.break_url(self._url)
if client_url.query:
_, checkpoint = omni.client.get_branch_and_checkpoint_from_query(client_url.query)
return (client_url, checkpoint)
def __on_checkpoint_selection_changed(self, item: CheckpointItem):
if item:
self.url = item.get_full_url()
self._checkpoint_list_popup.visible = False
if self.__on_selection_changed_fn:
self.__on_selection_changed_fn(item)
def _build_list_popup(self, url):
with ui.VStack():
with ui.ZStack(height=0):
search_field = ui.StringField(style_type_name_override="ComboBox.Field")
search_label = ui.Label(" Search", name="hint", enabled=False, style_type_name_override="ComboBox.Field")
checkpoint_widget = CheckpointWidget(url, show_none_entry=True)
self._search_field_value_change_sub = search_field.model.subscribe_value_changed_fn(
lambda model: checkpoint_widget.set_search(model.get_value_as_string())
)
def begin_search(model):
search_label.visible = False
self._search_field_begin_edit_sub = search_field.model.subscribe_begin_edit_fn(begin_search)
def end_search(model):
if model.get_value_as_string() != "":
search_label.visible = True
self._search_field_end_edit_sub = search_field.model.subscribe_end_edit_fn(end_search)
checkpoint_widget.add_on_selection_changed_fn(self.__on_checkpoint_selection_changed)
def on_visibility_changed(visible):
checkpoint_widget.destroy()
self._checkpoint_list_popup.set_visibility_changed_fn(on_visibility_changed)
def _show_checkpoint_widget(self, url, pos_x, pos_y, pos_y_offset, width, height):
# If there is not enough space to expand the list downward, expand it upward instead
# TODO multi OS window?
window_height = ui.Workspace.get_main_window_height()
window_width = ui.Workspace.get_main_window_width()
if pos_y + height > window_height:
pos_y -= height
else:
pos_y += pos_y_offset
if self._modal:
flags = (ui.WINDOW_FLAGS_MODAL | ui.WINDOW_FLAGS_NO_BACKGROUND)
else:
flags = ui.WINDOW_FLAGS_POPUP
flags = (
flags
| ui.WINDOW_FLAGS_NO_TITLE_BAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
)
self._checkpoint_list_popup = ui.Window(
"Checkpoint Widget Window",
flags=flags,
padding_x=1,
padding_y=1,
width= window_width if self._modal else width,
height=window_height if self._modal else height,
)
self._checkpoint_list_popup.frame.set_style(get_style())
if self._modal:
# Modal window, simulate a popup window
# - background transparent
# - mouse press outside list will hide window
def __hide_list_popup():
self._checkpoint_list_popup.visible = False
with self._checkpoint_list_popup.frame:
with ui.HStack():
ui.Spacer(width=pos_x, mouse_pressed_fn=lambda x, y, b, a: __hide_list_popup())
with ui.VStack():
ui.Spacer(height=pos_y, mouse_pressed_fn=lambda x, y, b, a: __hide_list_popup())
self._build_list_popup(url)
ui.Spacer(height=window_height-pos_y-height, mouse_pressed_fn=lambda x, y, b, a: __hide_list_popup())
ui.Spacer(width=window_width-pos_x-width, mouse_pressed_fn=lambda x, y, b, a: __hide_list_popup())
else:
self._checkpoint_list_popup.position_x = pos_x
self._checkpoint_list_popup.position_y = pos_y
with self._checkpoint_list_popup.frame:
self._build_list_popup(url)
| 9,158 | Python | 39.171052 | 128 | 0.575126 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/tests/test_versioning.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.kit.app
import omni.client
from datetime import datetime
from unittest.mock import patch, Mock
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit.test_suite.helpers import get_test_data_path
from omni.kit.window.content_browser import get_content_window
import omni.ui as ui
import omni.kit.ui_test as ui_test
from omni.kit.widget.versioning import CheckpointWidget, CheckpointCombobox, LAYOUT_TABLE_VIEW, LAYOUT_SLIM_VIEW
from ..checkpoint_helper import CheckpointHelper
from ..checkpoints_model import CheckpointModel
class MockServer:
def __init__(self, cache_enabled=False, checkpoints_enabled=False, omniojects_enabled=False, username="", version=""):
self.cache_enabled = cache_enabled
self.checkpoints_enabled = checkpoints_enabled
self.omniojects_enabled = omniojects_enabled
self.username = username
self.version = version
class MockFileEntry:
def __init__(self, relative_path="", access="", flags="", size=0, modified_time="", created_time="", modified_by="", created_by="", version="", comment="<Test Node>"):
self.relative_path = relative_path
self.access = access
self.flags = flags
self.size = size
self.modified_time = modified_time
self.created_time = created_time
self.modified_by = modified_by
self.created_by = created_by
self.version = version
self.comment = comment
class _TestBase(AsyncTestCase):
# Before running each test
async def setUp(self):
self._mock_server = MockServer(
cache_enabled=False,
checkpoints_enabled=True,
omniojects_enabled=True,
username="[email protected]",
version="TestServer"
)
self._mock_file_entries = [
MockFileEntry(
access=1,
created_by="[email protected]",
created_time=datetime.min.time(),
flags=513,
modified_by="[email protected]",
modified_time=datetime.min.time(),
relative_path="&1",
size=160,
version=12023408,
comment="<1>"
),
MockFileEntry(
access=1,
created_by="[email protected]",
created_time=datetime.min.time(),
flags=513,
modified_by="[email protected]",
modified_time=datetime.min.time(),
relative_path="&2",
size=260,
version=12023408,
comment="<2>"
)
]
# After running each test
async def tearDown(self):
pass
async def _mock_get_server_info_async(self, url: str):
return omni.client.Result.OK, self._mock_server
async def _mock_list_checkpoints_async(self, query: str):
return omni.client.Result.OK, self._mock_file_entries
def _mock_checkpoint_query(self, query: str):
return (None, 1)
def _mock_copy_async(self, path, filepath, message=""):
return omni.client.Result.OK
def _mock_on_file_change(self, result):
pass
def _mock_resolve_subscribe(self, url, urls, cb1, cb2):
cb2(omni.client.Result.OK, None, self._mock_file_entries[0], None)
class TestVersioningWindow(_TestBase):
async def test_versioning_widget(self):
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async),\
patch("omni.client.list_checkpoints_async", side_effect=self._mock_list_checkpoints_async),\
patch("omni.client.copy_async", side_effect=self._mock_copy_async) as _mock,\
patch("omni.client.resolve_subscribe_with_callback", side_effect=self._mock_resolve_subscribe),\
patch.object(CheckpointModel, "_on_file_change_event", side_effect=self._mock_on_file_change) as _mock_file_change:
under_test = get_content_window()
# TODO: Filebrowser file selection not working for grid_view
under_test.toggle_grid_view(False)
test_path = get_test_data_path(__name__, "4Lights.usda")
await under_test.select_items_async(test_path)
await ui_test.wait_n_updates(2)
# Confirm that checkpoint widget displays the expected checkpoint entry
cp_widget = under_test.get_checkpoint_widget()
cp_model = cp_widget._model
cp_items = cp_model.get_item_children(None)
self.assertTrue(len(cp_items))
# Last item is the latest
self.assertEqual(cp_items[-1].entry, self._mock_file_entries[0])
# test restore
cp_model.restore_checkpoint("omniverse://dummy.usd", "omniverse://dummy.usd?&2")
await ui_test.wait_n_updates(5)
_mock.assert_called_once_with("omniverse://dummy.usd?&2", "omniverse://dummy.usd",
message="Restored checkpoint #2")
# OMFP-3807: restore should trigger file change,check here
_mock_file_change.assert_called()
async def test_versioning_widget_table_view(self):
mock_double_click = Mock()
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async),\
patch("omni.client.list_checkpoints_async", side_effect=self._mock_list_checkpoints_async):
url = get_test_data_path(__name__, "4Lights.usda")
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
window = ui.Window("TestTableView", width=800, height=500, flags=window_flags)
with window.frame:
with ui.VStack():
widget = CheckpointWidget(url, layout=LAYOUT_TABLE_VIEW)
widget.set_url(url)
widget.add_context_menu(
"Foo",
"pencil.svg",
Mock(),
None,
)
widget.add_context_menu(
"Bar",
"pencil.svg",
Mock(),
None,
)
widget.set_mouse_double_clicked_fn(lambda b, k, cp: mock_double_click(cp))
window.focus()
await ui_test.wait_n_updates(5)
cp_items = widget._model.get_item_children(None)
# test that table view displays our test file entry correctly
self.assertFalse(widget.empty())
item = cp_items[-1]
# Last item is the latest
self.assertEqual(item.entry, self._mock_file_entries[0])
self.assertEqual(item.comment, "<1>")
self.assertTrue(item.get_full_url().endswith(f"4Lights.usda?&1"))
self.assertEqual(item.get_relative_path(), "&1")
# test search filtering
treeview_item = ui_test.find("TestTableView//Frame/**/Label[*].text=='1'")
self.assertIsNotNone(treeview_item)
widget.set_search("2")
await ui_test.human_delay()
treeview_item = ui_test.find("TestTableView//Frame/**/Label[*].text=='1'")
self.assertIsNone(treeview_item)
# restore keywords back
widget.set_search("")
# test double click
treeview_item = ui_test.find("TestTableView//Frame/**/Label[*].text=='1'")
self.assertIsNotNone(treeview_item)
await treeview_item.double_click()
mock_double_click.assert_called_once_with(item)
# test context menu
await treeview_item.right_click()
await ui_test.human_delay()
await ui_test.select_context_menu("Foo")
# test delete context menu
widget.delete_context_menu("Foo")
await ui_test.human_delay()
await treeview_item.right_click()
menu = await ui_test.get_context_menu()
self.assertEqual(menu['_'], ['Bar'])
async def test_checkpoint_combo_box(self):
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async),\
patch("omni.client.list_checkpoints_async", side_effect=self._mock_list_checkpoints_async),\
patch("omni.client.get_branch_and_checkpoint_from_query", side_effect=self._mock_checkpoint_query):
url = "omniverse://dummy.usd"
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
window = ui.Window("TestComboBox", width=800, height=500, flags=window_flags)
with window.frame:
with ui.VStack():
combo_box = CheckpointCombobox(url, lambda sel: print(f"Selected: {sel.get_full_url()}"))
window.focus()
await ui_test.wait_n_updates(5)
# test visible
self.assertTrue(combo_box.visible)
combo_box.visible = False
self.assertFalse(combo_box.visible)
combo_box.visible = True
# test url
self.assertEqual(url, combo_box.url)
url = "omniverse://dummy.usd?1"
combo_box.url = url
self.assertEqual(url, combo_box.url)
# test show checkpoints
field = ui_test.find_all("TestComboBox//Frame/**/StringField[*]")[0]
self.assertIsNotNone(field)
await field.click()
await ui_test.human_delay()
self.assertTrue(combo_box._checkpoint_list_popup.visible)
class TestCheckpointHelper(_TestBase):
async def test_extract_server_from_url(self):
self.assertFalse(CheckpointHelper.extract_server_from_url(""))
self.assertEqual(CheckpointHelper.extract_server_from_url("omniverse://dummy/foo.bar"), "omniverse://dummy")
async def test_is_checkpoint_enabled(self):
enabled = await CheckpointHelper.is_checkpoint_enabled_async("")
self.assertFalse(enabled)
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async) as _mock:
enabled = await CheckpointHelper.is_checkpoint_enabled_async("omniverse://dummy/foo.bar")
self.assertTrue(enabled)
_mock.assert_called_once()
_mock.reset_mock()
# test that server result is cached
self.assertTrue("omniverse://dummy" in CheckpointHelper.server_cache)
enabled = await CheckpointHelper.is_checkpoint_enabled_async("omniverse://dummy/baz.abc")
self.assertTrue(enabled)
_mock.assert_not_called()
async def test_is_checkpoint_enabled_with_callback(self):
callback = Mock()
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async):
CheckpointHelper.is_checkpoint_enabled_with_callback("omniverse://dummy/foo.bar", callback)
await ui_test.wait_n_updates(2)
callback.assert_called_once_with("omniverse://dummy", True)
| 11,526 | Python | 41.692592 | 171 | 0.603418 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/tests/__init__.py | from .test_versioning import TestCheckpointHelper, TestVersioningWindow
| 72 | Python | 35.499982 | 71 | 0.888889 |
omniverse-code/kit/exts/omni.kit.widget.versioning/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.3.8] - 2022-04-27
### Changed
- Fixes unittests.
## [1.3.7] - 2022-04-18
### Changed
- Added CheckpointHelper.
## [1.3.6] - 2021-11-22
### Changed
- Fixed UI layout when imported into the filepicker detail view.
## [1.3.5] - 2021-08-12
### Changed
- Added method to retrieve comment from the Checkpoint item.
## [1.3.4] - 2021-07-20
### Changed
- Adds enable_fn to context menu
## [1.3.3] - 2021-07-20
### Changed
- Fixes checkpoint selection
## [1.3.2] - 2021-07-13
### Changed
- Fixed selection handling, particularly useful for the combo box
## [1.3.1] - 2021-07-12
### Changed
- Added compact view for checkpoint list
- Refactored the widget for incorporating into redesigned filepicker
## [1.2.1] - 2021-06-10
### Changed
- Added open checkpoint from checkpoint list
## [1.2.0] - 2021-06-10
### Changed
- Checkpoint window always shows when enabled
## [1.1.3] - 2021-06-07
### Changed
- Added `on_list_checkpoint_fn` to execute user callback when listing updated.
## [1.1.2] - 2021-05-04
### Changed
- Updated styling on checkpoint widget
## [1.1.1] - 2021-04-08
### Changed
- Right click on any column of a checkpoint entry now brings up the "Restore Checkpoint" context menu.
## [1.1.0] - 2021-03-25
### Added
- Added support `add_on_selection_changed_fn` to checkpoint widget.
- Added `CheckpointCombobox` widget for easy selection of checkpoint as a combobox.
## [1.0.0] - 2021-02-01
### Added
- Initial version.
| 1,537 | Markdown | 22.30303 | 102 | 0.683149 |
omniverse-code/kit/exts/omni.kit.widget.versioning/docs/index.rst | omni.kit.widget.versioning: Versioning Widgets Extension
#########################################################
.. toctree::
:maxdepth: 1
CHANGELOG
Versioning Widgets
==========================
.. automodule:: omni.kit.widget.versioning
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
| 350 | reStructuredText | 20.937499 | 57 | 0.537143 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/Sdf/_Sdf.pyi | from __future__ import annotations
import usdrt.Sdf._Sdf
import typing
__all__ = [
"AncestorsRange",
"AssetPath",
"Path",
"ValueTypeName",
"ValueTypeNames"
]
class AncestorsRange():
def GetPath(self) -> Path: ...
def __init__(self, arg0: Path) -> None: ...
def __iter__(self) -> typing.Iterator: ...
pass
class AssetPath():
def __eq__(self, arg0: AssetPath) -> bool: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, path: str) -> None: ...
@typing.overload
def __init__(self, path: str, resolvedPath: str) -> None: ...
def __ne__(self, arg0: AssetPath) -> bool: ...
def __repr__(self) -> str: ...
def __str__(self) -> str: ...
@property
def path(self) -> str:
"""
:type: str
"""
@property
def resolvedPath(self) -> str:
"""
:type: str
"""
__hash__ = None
pass
class Path():
def AppendChild(self, childName: TfToken) -> Path: ...
def AppendPath(self, newSuffix: Path) -> Path: ...
def AppendProperty(self, propName: TfToken) -> Path: ...
def ContainsPropertyElements(self) -> bool: ...
def GetAbsoluteRootOrPrimPath(self) -> Path: ...
@staticmethod
def GetAncestorsRange(*args, **kwargs) -> typing.Any: ...
def GetCommonPrefix(self, path: Path) -> Path: ...
def GetNameToken(self) -> TfToken: ...
def GetParentPath(self) -> Path: ...
def GetPrefixes(self) -> typing.List[Path]: ...
def GetPrimPath(self) -> Path: ...
def GetString(self) -> str: ...
def GetText(self) -> str: ...
def GetToken(self) -> TfToken: ...
def HasPrefix(self, arg0: Path) -> bool: ...
def IsAbsolutePath(self) -> bool: ...
def IsAbsoluteRootOrPrimPath(self) -> bool: ...
def IsAbsoluteRootPath(self) -> bool: ...
def IsEmpty(self) -> bool: ...
def IsNamespacedPropertyPath(self) -> bool: ...
def IsPrimPath(self) -> bool: ...
def IsPrimPropertyPath(self) -> bool: ...
def IsPropertyPath(self) -> bool: ...
def IsRootPrimPath(self) -> bool: ...
def RemoveCommonSuffix(self, otherPath: Path, stopAtRootPrim: bool = False) -> typing.Tuple[Path, Path]: ...
def ReplaceName(self, newName: TfToken) -> Path: ...
def ReplacePrefix(self, oldPrefix: Path, newPrefix: Path, fixTargetPaths: bool = True) -> Path: ...
def __eq__(self, arg0: Path) -> bool: ...
def __hash__(self) -> int: ...
@typing.overload
def __init__(self, arg0: str) -> None: ...
@typing.overload
def __init__(self, arg0: Path) -> None: ...
@typing.overload
def __init__(self) -> None: ...
def __lt__(self, arg0: Path) -> bool: ...
def __ne__(self, arg0: Path) -> bool: ...
def __repr__(self) -> str: ...
def __str__(self) -> str: ...
@property
def isEmpty(self) -> bool:
"""
:type: bool
"""
@property
def name(self) -> str:
"""
:type: str
"""
@property
def pathElementCount(self) -> int:
"""
:type: int
"""
@property
def pathString(self) -> str:
"""
:type: str
"""
absoluteRootPath: usdrt.Sdf._Sdf.Path # value = Sdf.Path('/')
emptyPath: usdrt.Sdf._Sdf.Path # value = Sdf.Path('')
pass
class ValueTypeName():
def GetAsString(self) -> str: ...
def GetAsToken(self) -> TfToken: ...
@staticmethod
def GetAsTypeC(*args, **kwargs) -> typing.Any: ...
def __eq__(self, arg0: ValueTypeName) -> bool: ...
def __init__(self) -> None: ...
def __ne__(self, arg0: ValueTypeName) -> bool: ...
def __repr__(self) -> str: ...
@property
def arrayType(self) -> ValueTypeName:
"""
:type: ValueTypeName
"""
@property
def isArray(self) -> bool:
"""
:type: bool
"""
@property
def isScalar(self) -> bool:
"""
:type: bool
"""
@property
def scalarType(self) -> ValueTypeName:
"""
:type: ValueTypeName
"""
__hash__ = None
pass
class ValueTypeNames():
AncestorPrimTypeTag: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('tag (ancestorPrimTypeName)')
AppliedSchemaTypeTag: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('tag (appliedSchema)')
Asset: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('asset')
AssetArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('asset[]')
Bool: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('bool')
BoolArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('bool[]')
Color3d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3 (color)')
Color3dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3[] (color)')
Color3f: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3 (color)')
Color3fArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3[] (color)')
Color3h: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3 (color)')
Color3hArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3[] (color)')
Color4d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double4 (color)')
Color4dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double4[] (color)')
Color4f: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float4 (color)')
Color4fArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float4[] (color)')
Color4h: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half4 (color)')
Color4hArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half4[] (color)')
Double: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double')
Double2: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double2')
Double2Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double2[]')
Double3: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3')
Double3Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3[]')
Double4: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double4')
Double4Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double4[]')
DoubleArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double[]')
Float: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float')
Float2: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float2')
Float2Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float2[]')
Float3: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3')
Float3Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3[]')
Float4: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float4')
Float4Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float4[]')
FloatArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float[]')
Frame4d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double16 (frame)')
Frame4dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double16[] (frame)')
Half: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half')
Half2: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half2')
Half2Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half2[]')
Half3: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3')
Half3Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3[]')
Half4: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half4')
Half4Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half4[]')
HalfArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half[]')
Int: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int')
Int2: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int2')
Int2Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int2[]')
Int3: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int3')
Int3Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int3[]')
Int4: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int4')
Int4Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int4[]')
Int64: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int64')
Int64Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int64[]')
IntArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('int[]')
Matrix2d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double4 (matrix)')
Matrix2dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double4[] (matrix)')
Matrix3d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double9 (matrix)')
Matrix3dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double9[] (matrix)')
Matrix4d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double16 (matrix)')
Matrix4dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double16[] (matrix)')
Normal3d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3 (normal)')
Normal3dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3[] (normal)')
Normal3f: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3 (normal)')
Normal3fArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3[] (normal)')
Normal3h: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3 (normal)')
Normal3hArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3[] (normal)')
Point3d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3 (position)')
Point3dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3[] (position)')
Point3f: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3 (position)')
Point3fArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3[] (position)')
Point3h: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3 (position)')
Point3hArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3[] (position)')
PrimTypeTag: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('tag (primTypeName)')
Quatd: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double4 (quaternion)')
QuatdArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double4[] (quaternion)')
Quatf: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float4 (quaternion)')
QuatfArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float4[] (quaternion)')
Quath: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half4 (quaternion)')
QuathArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half4[] (quaternion)')
Range3d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double6')
String: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('uchar[] (text)')
StringArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('uchar[][] (text)')
Tag: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('tag')
TexCoord2d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double2 (texCoord)')
TexCoord2dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double2[] (texCoord)')
TexCoord2f: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float2 (texCoord)')
TexCoord2fArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float2[] (texCoord)')
TexCoord2h: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half2 (texCoord)')
TexCoord2hArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half2[] (texCoord)')
TexCoord3d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3 (texCoord)')
TexCoord3dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3[] (texCoord)')
TexCoord3f: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3 (texCoord)')
TexCoord3fArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3[] (texCoord)')
TexCoord3h: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3 (texCoord)')
TexCoord3hArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3[] (texCoord)')
TimeCode: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double (timecode)')
TimeCodeArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double[] (timecode)')
Token: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('token')
TokenArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('token[]')
UChar: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('uchar')
UCharArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('uchar[]')
UInt: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('uint')
UInt64: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('uint64')
UInt64Array: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('uint64[]')
UIntArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('uint[]')
Vector3d: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3 (vector)')
Vector3dArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('double3[] (vector)')
Vector3f: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3 (vector)')
Vector3fArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('float3[] (vector)')
Vector3h: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3 (vector)')
Vector3hArray: usdrt.Sdf._Sdf.ValueTypeName # value = Sdf.ValueTypeName('half3[] (vector)')
pass
| 13,961 | unknown | 54.848 | 112 | 0.667359 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_examples.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestDocExamples(TestClass):
@tc_logger
def test_usdrt_one_property(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example one property RT
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
path = "/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"
prim = stage.GetPrimAtPath(path)
attr = prim.GetAttribute(UsdGeom.Tokens.primvarsDisplayColor)
# Get the value of displayColor on White_Wall_Back,
# which is mid-gray on this stage
result = attr.Get()
self.assertEqual(len(result), 1)
self.assertEqual(result[0], Gf.Vec3f(0.5, 0.5, 0.5))
# Set the value of displayColor to red,
# and verify the change by getting the value
attr.Set(Vt.Vec3fArray([Gf.Vec3f(1, 0, 0)]))
result = attr.Get()
self.assertEqual(len(result), 1)
self.assertEqual(result[0], Gf.Vec3f(1, 0, 0))
# End example one property RT
@tc_logger
def test_usd_one_property(self):
from pxr import Gf, Sdf, Usd, UsdUtils, Vt
# FIXME - Fabric is holding notices to a stage in the cache
# and gets hung here if the cache isn't cleared first - How?
UsdUtils.StageCache.Get().Clear()
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example one property USD
from pxr import Gf, Sdf, Usd, Vt
path = "/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"
prim = stage.GetPrimAtPath(path)
attr = prim.GetAttribute("primvars:displayColor")
# Get the value of displayColor on White_Wall_Back,
# which is mid-gray on this stage
result = attr.Get()
self.assertEqual(len(result), 1)
self.assertEqual(result[0], Gf.Vec3f(0.5, 0.5, 0.5))
# Set the value of displayColor to red,
# and verify the change by getting the value
attr.Set(Vt.Vec3fArray([Gf.Vec3f(1, 0, 0)]))
result = attr.Get()
self.assertEqual(len(result), 1)
self.assertEqual(result[0], Gf.Vec3f(1, 0, 0))
# End example one property USD
@tc_logger
def test_usdrt_many_property(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example many prims RT
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
red = Vt.Vec3fArray([Gf.Vec3f(1, 0, 0)])
meshPaths = stage.GetPrimsWithTypeName("Mesh")
for meshPath in meshPaths:
prim = stage.GetPrimAtPath(meshPath)
if prim.HasAttribute(UsdGeom.Tokens.primvarsDisplayColor):
prim.GetAttribute(UsdGeom.Tokens.primvarsDisplayColor).Set(red)
# End example many prims RT
@tc_logger
def test_usdrt_abstract_schema_query(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example abstract query
from usdrt import Gf, Sdf, Usd, UsdGeom
gPrimPaths = stage.GetPrimsWithTypeName("Gprim")
attr = UsdGeom.Tokens.doubleSided
doubleSided = []
for gPrimPath in gPrimPaths:
prim = stage.GetPrimAtPath(gPrimPath)
if prim.HasAttribute(attr) and prim.GetAttribute(attr).Get():
doubleSided.append(prim)
@tc_logger
def test_usd_many_property(self):
from pxr import Gf, Sdf, Usd, UsdUtils
# FIXME - Fabric is holding notices to a stage in the cache
# and gets hung here if the cache isn't cleared first - How?
UsdUtils.StageCache.Get().Clear()
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example many prims USD
from pxr import Gf, Usd, UsdGeom, Vt
red = Vt.Vec3fArray([Gf.Vec3f(1, 0, 0)])
for prim in stage.Traverse():
if prim.GetTypeName() == "Mesh":
prim.GetAttribute(UsdGeom.Tokens.primvarsDisplayColor).Set(red)
# End example many prims USD
@tc_logger
def test_usdrt_one_relationship(self):
from usdrt import Gf, Sdf, Usd, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example relationship RT
from usdrt import Gf, Sdf, Usd, UsdGeom
path = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"
prim = stage.GetPrimAtPath(path)
rel = prim.GetRelationship(UsdShade.Tokens.materialBinding)
# The currently bound Material prim, and a new
# Material prim to bind
old_mtl = "/Cornell_Box/Root/Looks/Green1SG"
new_mtl = "/Cornell_Box/Root/Looks/Red1SG"
# Get the first target
self.assertTrue(rel.HasAuthoredTargets())
mtl_path = rel.GetTargets()[0]
self.assertEqual(mtl_path, old_mtl)
# Update the relationship to target a different material
rel.SetTargets([new_mtl])
updated_path = rel.GetTargets()[0]
self.assertEqual(updated_path, new_mtl)
# End example relationship RT
@tc_logger
def test_usd_one_relationship(self):
from pxr import Gf, Sdf, Usd, UsdUtils, Vt
# FIXME - Fabric is holding notices to a stage in the cache
# and gets hung here if the cache isn't cleared first - How?
UsdUtils.StageCache.Get().Clear()
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example relationship USD
from pxr import Gf, Sdf, Usd
path = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"
prim = stage.GetPrimAtPath(path)
rel = prim.GetRelationship("material:binding")
# The currently bound Material prim, and a new
# Material prim to bind
old_mtl = "/Cornell_Box/Root/Looks/Green1SG"
new_mtl = "/Cornell_Box/Root/Looks/Red1SG"
# Get the first target
self.assertTrue(rel.HasAuthoredTargets())
mtl_path = rel.GetTargets()[0]
self.assertEqual(mtl_path, old_mtl)
# Update the relationship to target a different material
rel.SetTargets([new_mtl])
updated_path = rel.GetTargets()[0]
self.assertEqual(updated_path, new_mtl)
# End example relationship USD
@tc_logger
def test_usd_usdrt_interop(self):
if True:
# FIXME - crash on Linux here on TC why?
return
from pxr import UsdUtils
# Paranoia - see above test
UsdUtils.StageCache.Get().Clear()
# Begin example interop
from pxr import Sdf, Usd, UsdUtils
from usdrt import Usd as RtUsd
usd_stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage_id = UsdUtils.StageCache.Get().Insert(usd_stage)
stage = RtUsd.Stage.Attach(usd_stage_id.ToLongInt())
mesh_paths = stage.GetPrimsWithTypeName("Mesh")
for mesh_path in mesh_paths:
# strings can be implicitly converted to SdfPath in Python
usd_prim = usd_stage.GetPrimAtPath(str(mesh_path))
if usd_prim.HasVariantSets():
print(f"Found Mesh with variantSet: {mesh_path}")
# End example interop
@tc_logger
def test_vt_array_gpu(self):
if platform.processor() == "aarch64":
return
import weakref
try:
import warp as wp
except ImportError:
if TestClass is omni.kit.test.AsyncTestCase:
# warp not available for testing in kit at this time
return
raise
# Begin example GPU
import numpy as np
import warp as wp
from usdrt import Gf, Sdf, Usd, Vt
def warp_array_from_cuda_array_interface(a):
cai = a.__cuda_array_interface__
return wp.types.array(
dtype=wp.vec3,
length=cai["shape"][0],
capacity=cai["shape"][0] * wp.types.type_size_in_bytes(wp.vec3),
ptr=cai["data"][0],
device="cuda",
owner=False,
requires_grad=False,
)
stage = Usd.Stage.CreateInMemory("test.usda")
prim = stage.DefinePrim(Sdf.Path("/prim"))
attr = prim.CreateAttribute("points", Sdf.ValueTypeNames.Point3fArray, True)
# First create a warp array from numpy
points = np.zeros(shape=(1024, 3), dtype=np.float32)
for i in range(1024):
for j in range(3):
points[i][j] = i * 3 + j
warp_points = wp.array(points, device="cpu")
with wp.ScopedCudaGuard():
gpu_warp_points = warp_points.to("cuda")
warp_ref = weakref.ref(gpu_warp_points)
# Create a VtArray from a warp array
vt_points = Vt.Vec3fArray(gpu_warp_points)
# Set the Fabric attribute which will make a CUDA copy
# from warp to Fabric
attr.Set(vt_points)
wp.synchronize()
# Retrieve a new Fabric VtArray from USDRT
new_vt_points = attr.Get()
self.assertTrue(new_vt_points.HasFabricGpuData())
# Create a warp array from the VtArray
new_warp_points = warp_array_from_cuda_array_interface(new_vt_points)
# Delete the fabric VtArray to ensure the data was
# really copied into warp
del new_vt_points
# Convert warp points back to numpy
new_points = new_warp_points.numpy()
# Now compare the round-trip through USDRT and GPU was a success
self.assertEqual(points.shape, new_points.shape)
for i in range(1024):
for j in range(3):
self.assertEqual(points[i][j], new_points[i][j])
# End example GPU
| 11,265 | Python | 30.915014 | 84 | 0.613848 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_path.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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.
"""
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
import os
import pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
def get_path_parts():
from usdrt import Sdf
parts = [
Sdf.Path("/Cornell_Box"),
Sdf.Path("/Cornell_Box/Root"),
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"),
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall"),
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"),
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices"),
]
return parts
class TestSdfPath(TestClass):
@tc_logger
def test_get_prefixes(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = get_path_parts()
prefixes = path.GetPrefixes()
self.assertEqual(prefixes, expected)
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = "Sdf.Path('/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices')"
self.assertEqual(repr(path), expected)
@tc_logger
def test_str_representation(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices"
self.assertEqual(str(path), expected)
@tc_logger
def test_implicit_string_conversion(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
primFromString = stage.GetPrimAtPath("/Cornell_Box")
self.assertTrue(primFromString)
@tc_logger
def test_get_string(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices"
self.assertEqual(path.GetString(), expected)
self.assertEqual(path.pathString, expected)
@tc_logger
def test_get_text(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices"
self.assertEqual(path.GetText(), expected)
@tc_logger
def test_get_name_token(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/foo/bar/baz").name, "baz")
self.assertEqual(Sdf.Path("/foo").name, "foo")
self.assertEqual(Sdf.Path.emptyPath.name, "")
self.assertEqual(Sdf.Path("/foo/bar/baz.prop").name, "prop")
self.assertEqual(Sdf.Path("/foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
self.assertEqual(Sdf.Path("foo/bar/baz").name, "baz")
self.assertEqual(Sdf.Path("foo").name, "foo")
self.assertEqual(Sdf.Path("foo/bar/baz.prop").name, "prop")
self.assertEqual(Sdf.Path("foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
@tc_logger
def test_get_prim_path(self):
from usdrt import Sdf, Usd
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG")
self.assertEqual(path.GetPrimPath(), expected)
@tc_logger
def test_path_element_count(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/").pathElementCount, 0)
self.assertEqual(Sdf.Path("/abc").pathElementCount, 1)
self.assertEqual(Sdf.Path("/abc/xyz").pathElementCount, 2)
@tc_logger
def test_get_name(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/foo/bar/baz").name, "baz")
self.assertEqual(Sdf.Path("/foo").name, "foo")
self.assertEqual(Sdf.Path.emptyPath.name, "")
self.assertEqual(Sdf.Path("/foo/bar/baz.prop").name, "prop")
self.assertEqual(Sdf.Path("/foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
self.assertEqual(Sdf.Path("foo/bar/baz").name, "baz")
self.assertEqual(Sdf.Path("foo").name, "foo")
self.assertEqual(Sdf.Path("foo/bar/baz.prop").name, "prop")
self.assertEqual(Sdf.Path("foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
@tc_logger
def test_path_queries(self):
from usdrt import Sdf
absRoot = Sdf.Path("/")
absolute = Sdf.Path("/absolute/path/test")
relative = Sdf.Path("../relative/path/test")
prim = Sdf.Path("/this/is/a/prim/path")
rootPrim = Sdf.Path("/root")
propPath = Sdf.Path("/this/path/has.propPart")
namespaceProp = Sdf.Path("/this/path/has.namespaced(self):propPart")
self.assertTrue(absolute.IsAbsolutePath())
self.assertFalse(relative.IsAbsolutePath())
self.assertTrue(absRoot.IsAbsoluteRootPath())
self.assertFalse(absolute.IsAbsoluteRootPath())
self.assertFalse(Sdf.Path.emptyPath.IsAbsoluteRootPath())
self.assertTrue(prim.IsPrimPath())
self.assertFalse(propPath.IsPrimPath())
self.assertFalse(Sdf.Path.emptyPath.IsPrimPath())
self.assertTrue(absolute.IsAbsoluteRootOrPrimPath())
self.assertTrue(prim.IsAbsoluteRootOrPrimPath())
self.assertFalse(relative.IsAbsoluteRootOrPrimPath())
self.assertFalse(propPath.IsAbsoluteRootOrPrimPath())
self.assertFalse(Sdf.Path.emptyPath.IsAbsoluteRootOrPrimPath())
self.assertTrue(rootPrim.IsRootPrimPath())
self.assertFalse(prim.IsRootPrimPath())
self.assertFalse(Sdf.Path.emptyPath.IsRootPrimPath())
self.assertTrue(propPath.IsPropertyPath())
self.assertFalse(prim.IsPropertyPath())
self.assertFalse(Sdf.Path.emptyPath.IsPropertyPath())
self.assertTrue(propPath.IsPrimPropertyPath())
self.assertFalse(prim.IsPrimPropertyPath())
self.assertFalse(Sdf.Path.emptyPath.IsPrimPropertyPath())
self.assertTrue(namespaceProp.IsNamespacedPropertyPath())
self.assertFalse(propPath.IsNamespacedPropertyPath())
self.assertFalse(prim.IsNamespacedPropertyPath())
self.assertFalse(Sdf.Path.emptyPath.IsNamespacedPropertyPath())
self.assertTrue(Sdf.Path.emptyPath.IsEmpty())
self.assertFalse(propPath.IsEmpty())
self.assertFalse(prim.IsEmpty())
@tc_logger
def test_operators(self):
from usdrt import Sdf
# Test lessthan
self.assertTrue(Sdf.Path("aaa") < Sdf.Path("aab"))
self.assertTrue(not Sdf.Path("aaa") < Sdf.Path())
self.assertTrue(Sdf.Path("/") < Sdf.Path("/a"))
# string conversion
self.assertEqual(Sdf.Path("foo"), "foo")
self.assertEqual("foo", Sdf.Path("foo"))
self.assertNotEqual(Sdf.Path("foo"), "bar")
self.assertNotEqual("bar", Sdf.Path("foo"))
@tc_logger
def test_contains_property_elements(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
self.assertTrue(path.ContainsPropertyElements())
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG")
self.assertFalse(path.ContainsPropertyElements())
@tc_logger
def test_get_parent_path(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/foo/bar/baz").GetParentPath(), Sdf.Path("/foo/bar"))
self.assertEqual(Sdf.Path("/foo").GetParentPath(), Sdf.Path("/"))
self.assertEqual(Sdf.Path.emptyPath.GetParentPath(), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path("/foo/bar/baz.prop").GetParentPath(), Sdf.Path("/foo/bar/baz"))
self.assertEqual(Sdf.Path("foo/bar/baz").GetParentPath(), Sdf.Path("foo/bar"))
# self.assertEqual(Sdf.Path("foo").GetParentPath(), Sdf.Path("."))
self.assertEqual(Sdf.Path("foo/bar/baz.prop").GetParentPath(), Sdf.Path("foo/bar/baz"))
@tc_logger
def test_get_prim_path(self):
from usdrt import Sdf
primPath = Sdf.Path("/A/B/C").GetPrimPath()
self.assertEqual(primPath, Sdf.Path("/A/B/C"))
primPath = Sdf.Path("/A/B/C.foo").GetPrimPath()
self.assertEqual(primPath, Sdf.Path("/A/B/C"))
primPath = Sdf.Path("/A/B/C.foo:bar:baz").GetPrimPath()
self.assertEqual(primPath, Sdf.Path("/A/B/C"))
@tc_logger
def test_get_absolute_root_or_prim_path(self):
from usdrt import Sdf
self.assertTrue(Sdf.Path.absoluteRootPath, Sdf.Path("/"))
@tc_logger
def test_append_path(self):
from usdrt import Sdf
# append to empty path -> empty path
# with self.assertRaises(Tf.ErrorException):
# Sdf.Path().AppendPath( Sdf.Path() )
# with self.assertRaises(Tf.ErrorException):
# Sdf.Path().AppendPath( Sdf.Path('A') )
# append to root/prim path
self.assertEqual(Sdf.Path("/").AppendPath(Sdf.Path("A")), Sdf.Path("/A"))
self.assertEqual(Sdf.Path("/A").AppendPath(Sdf.Path("B")), Sdf.Path("/A/B"))
# append empty to root/prim path -> no change
# with self.assertRaises(Tf.ErrorException):
# Sdf.Path('/').AppendPath( Sdf.Path() )
# with self.assertRaises(Tf.ErrorException):
# Sdf.Path('/A').AppendPath( Sdf.Path() )
@tc_logger
def test_append_child(self):
from usdrt import Sdf
aPath = Sdf.Path("/foo")
self.assertEqual(aPath.AppendChild("bar"), Sdf.Path("/foo/bar"))
aPath = Sdf.Path("foo")
self.assertEqual(aPath.AppendChild("bar"), Sdf.Path("foo/bar"))
aPath = Sdf.Path("/foo.prop")
self.assertEqual(aPath.AppendChild("bar"), Sdf.Path.emptyPath)
@tc_logger
def test_append_property(self):
from usdrt import Sdf
aPath = Sdf.Path("/foo")
self.assertEqual(aPath.AppendProperty("prop"), Sdf.Path("/foo.prop"))
self.assertEqual(aPath.AppendProperty("prop:foo:bar"), Sdf.Path("/foo.prop:foo:bar"))
aPath = Sdf.Path("/foo.prop")
self.assertEqual(aPath.AppendProperty("prop2"), Sdf.Path.emptyPath)
self.assertEqual(aPath.AppendProperty("prop2:foo:bar"), Sdf.Path.emptyPath)
@tc_logger
def test_replace_prefix(self):
from usdrt import Sdf
# Test HasPrefix
self.assertFalse(Sdf.Path.emptyPath.HasPrefix("A"))
self.assertFalse(Sdf.Path("A").HasPrefix(Sdf.Path.emptyPath))
aPath = Sdf.Path("/Chars/Buzz_1/LArm.FB")
self.assertEqual(aPath.HasPrefix("/Chars/Buzz_1"), True)
self.assertEqual(aPath.HasPrefix("Buzz_1"), False)
# Replace aPath's prefix and get a new path
bPath = aPath.ReplacePrefix("/Chars/Buzz_1", "/Chars/Buzz_2")
self.assertEqual(bPath, Sdf.Path("/Chars/Buzz_2/LArm.FB"))
# Specify a bogus prefix to replace and get an empty path
cPath = bPath.ReplacePrefix("/BadPrefix/Buzz_2", "/ReleasedChars/Buzz_2")
self.assertEqual(cPath, bPath)
# ReplacePrefix with an empty old or new prefix returns an empty path.
self.assertEqual(Sdf.Path("/A/B").ReplacePrefix(Sdf.Path.emptyPath, "/C"), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path("/A/B").ReplacePrefix("/A", Sdf.Path.emptyPath), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path.emptyPath.ReplacePrefix(Sdf.Path.emptyPath, "/C"), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path.emptyPath.ReplacePrefix("/A", Sdf.Path.emptyPath), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path.emptyPath.ReplacePrefix("/A", "/B"), Sdf.Path.emptyPath)
self.assertEqual(
Sdf.Path("/Cone").ReplacePrefix(Sdf.Path.absoluteRootPath, Sdf.Path("/World")), Sdf.Path("/World/Cone")
)
@tc_logger
def test_get_common_prefix(self):
from usdrt import Sdf
# prefix exists
self.assertEqual(
Sdf.Path("/prefix/is/common/one").GetCommonPrefix(Sdf.Path("/prefix/is/common/two")),
Sdf.Path("/prefix/is/common"),
)
self.assertEqual(
Sdf.Path("/prefix/is/common.one").GetCommonPrefix(Sdf.Path("/prefix/is/common.two")),
Sdf.Path("/prefix/is/common"),
)
self.assertEqual(
Sdf.Path("/prefix/is/common.oneone").GetCommonPrefix(Sdf.Path("/prefix/is/common.one")),
Sdf.Path("/prefix/is/common"),
)
# paths are the same
self.assertEqual(
Sdf.Path("/paths/are/the/same").GetCommonPrefix(Sdf.Path("/paths/are/the/same")),
Sdf.Path("/paths/are/the/same"),
)
# empty path, both parts
self.assertEqual(Sdf.Path.emptyPath.GetCommonPrefix(Sdf.Path("/foo/bar")), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path("/foo/bar").GetCommonPrefix(Sdf.Path.emptyPath), Sdf.Path.emptyPath)
# no common prefix
self.assertEqual(Sdf.Path("/a/b/c").GetCommonPrefix(Sdf.Path("/d/e/f")), Sdf.Path.absoluteRootPath)
# absolute root path
self.assertEqual(Sdf.Path.GetCommonPrefix(Sdf.Path("/"), Sdf.Path("/World")), Sdf.Path.absoluteRootPath)
# make sure its valid
self.assertEqual(Sdf.Path.GetCommonPrefix(Sdf.Path("/W"), Sdf.Path("/World/Cube")), Sdf.Path.absoluteRootPath)
self.assertEqual(Sdf.Path.GetCommonPrefix(Sdf.Path("/A"), Sdf.Path("/B")), Sdf.Path.absoluteRootPath)
@tc_logger
def test_remove_common_suffix(self):
from usdrt import Sdf
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/X/Y/Z")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A/B/C"))
self.assertEqual(r2, Sdf.Path("/X/Y/Z"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B/C"))
self.assertEqual(r2, Sdf.Path("/X/Y/Z"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("X/Y/Z")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B/C"))
self.assertEqual(r2, Sdf.Path("X/Y/Z"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B/C"))
self.assertEqual(r2, Sdf.Path("X/Y/Z"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/X/Y/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/X/Y"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/X/Y"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("X/Y/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("X/Y"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("X/Y"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("/X/Y/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("/X/Y"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("/X/Y"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/X/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A"))
self.assertEqual(r2, Sdf.Path("/X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A"))
self.assertEqual(r2, Sdf.Path("/X"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("X/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("X"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("/X/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("/X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("/X"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/A/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/"))
self.assertEqual(r2, Sdf.Path("/"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A"))
self.assertEqual(r2, Sdf.Path("/A"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("A/B/C")
# (r1, r2) = aPath.RemoveCommonSuffix(bPath)
# self.assertEqual(r1, Sdf.Path('.'))
# self.assertEqual(r2, Sdf.Path('.'))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("A"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("/A/B/C")
# (r1, r2) = aPath.RemoveCommonSuffix(bPath)
# self.assertEqual(r1, Sdf.Path('.'))
# self.assertEqual(r2, Sdf.Path('/'))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("/A"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/X/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/X"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("X/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("X"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A"))
self.assertEqual(r2, Sdf.Path("/"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/B"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("B/C")
# (r1, r2) = aPath.RemoveCommonSuffix(bPath)
# self.assertEqual(r1, Sdf.Path('A'))
# self.assertEqual(r2, Sdf.Path('.'))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("B"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B/C"))
self.assertEqual(r2, Sdf.Path("/C"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("C")
# (r1, r2) = aPath.RemoveCommonSuffix(bPath)
# self.assertEqual(r1, Sdf.Path('A/B'))
# self.assertEqual(r2, Sdf.Path('.'))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B/C"))
self.assertEqual(r2, Sdf.Path("C"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("/"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B/C"))
self.assertEqual(r2, Sdf.Path("/C"))
@tc_logger
def test_replace_name(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/foo/bar/baz").ReplaceName("foo"), Sdf.Path("/foo/bar/foo"))
self.assertEqual(Sdf.Path("/foo").ReplaceName("bar"), Sdf.Path("/bar"))
self.assertEqual(Sdf.Path("/foo/bar/baz.prop").ReplaceName("attr"), Sdf.Path("/foo/bar/baz.attr"))
self.assertEqual(
Sdf.Path("/foo/bar/baz.prop").ReplaceName("attr:argle:bargle"), Sdf.Path("/foo/bar/baz.attr:argle:bargle")
)
self.assertEqual(Sdf.Path("/foo/bar/baz.prop:argle:bargle").ReplaceName("attr"), Sdf.Path("/foo/bar/baz.attr"))
self.assertEqual(
Sdf.Path("/foo/bar/baz.prop:argle:bargle").ReplaceName("attr:foo:fa:raw"),
Sdf.Path("/foo/bar/baz.attr:foo:fa:raw"),
)
self.assertEqual(Sdf.Path("foo/bar/baz").ReplaceName("foo"), Sdf.Path("foo/bar/foo"))
self.assertEqual(Sdf.Path("foo").ReplaceName("bar"), Sdf.Path("bar"))
self.assertEqual(Sdf.Path("foo/bar/baz.prop").ReplaceName("attr"), Sdf.Path("foo/bar/baz.attr"))
self.assertEqual(
Sdf.Path("foo/bar/baz.prop").ReplaceName("attr:argle:bargle"), Sdf.Path("foo/bar/baz.attr:argle:bargle")
)
# STATIC TESTS
@tc_logger
def test_empty_path(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path.emptyPath, Sdf.Path(""))
self.assertEqual(Sdf.Path.emptyPath, Sdf.Path())
@tc_logger
def test_absolute_root_path(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path.absoluteRootPath, Sdf.Path("/"))
@tc_logger
def test_hashing(self):
from usdrt import Sdf
test_paths = get_path_parts()
d = {}
for i in enumerate(test_paths):
d[i[1]] = i[0]
for i in enumerate(test_paths):
self.assertEqual(d[i[1]], i[0])
class TestSdfPathAncestorsRange(TestClass):
@tc_logger
def test_iterator(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = get_path_parts()
expected.reverse()
i = 0
for ancestor in path.GetAncestorsRange():
self.assertEqual(ancestor, expected[i])
i += 1
@tc_logger
def test_get_path(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = get_path_parts()
expected.reverse()
ar = path.GetAncestorsRange()
self.assertEqual(ar.GetPath(), path)
| 25,107 | Python | 37.509202 | 119 | 0.627753 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_usd_timecode.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 math
import os
import pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdTimeCode(TestClass):
@tc_logger
def test_timecode(self):
from usdrt import Usd
# ctor
t0 = Usd.TimeCode()
self.assertTrue(t0)
self.assertEqual(t0.GetValue(), 0.0)
t1 = Usd.TimeCode(1.0)
self.assertTrue(t1)
self.assertEqual(t1.GetValue(), 1.0)
nan = Usd.TimeCode(float("nan"))
self.assertTrue(nan)
self.assertTrue(math.isnan(nan.GetValue()))
# operators
self.assertTrue(t1 == Usd.TimeCode(1.0))
self.assertFalse(t0 == t1)
self.assertFalse(t1 == nan)
self.assertTrue(nan == nan)
self.assertTrue(t0 != t1)
self.assertFalse(t1 != Usd.TimeCode(1.0))
self.assertTrue(t1 != nan)
self.assertFalse(nan != nan)
self.assertTrue(t0 <= t1)
self.assertFalse(t1 <= t0)
self.assertTrue(t1 <= Usd.TimeCode(1.0))
self.assertFalse(t1 <= nan)
self.assertTrue(nan <= t1)
self.assertTrue(t0 < t1)
self.assertFalse(t1 < t0)
self.assertFalse(t1 < Usd.TimeCode(1.0))
self.assertFalse(t1 < nan)
self.assertTrue(nan < t1)
self.assertTrue(t1 >= t0)
self.assertFalse(t0 >= t1)
self.assertTrue(t1 >= Usd.TimeCode(1.0))
self.assertTrue(t1 >= nan)
self.assertFalse(nan >= t1)
self.assertTrue(t1 > t0)
self.assertFalse(t0 > t1)
self.assertFalse(t1 > Usd.TimeCode(1.0))
self.assertTrue(t1 > nan)
self.assertFalse(nan > t1)
# is earliest time
self.assertFalse(t1.IsEarliestTime())
self.assertTrue(Usd.TimeCode(-1.7976931348623157e308).IsEarliestTime())
# is default
self.assertFalse(t1.IsDefault())
self.assertTrue(nan.IsDefault())
# static methods
self.assertEqual(Usd.TimeCode.EarliestTime().GetValue(), -1.7976931348623157e308)
self.assertTrue(math.isnan(Usd.TimeCode.Default().GetValue()))
@tc_logger
def test_time_code_repr(self):
"""
Validates the string representation of the default time code.
"""
from usdrt import Usd
defaultTime = Usd.TimeCode.Default()
timeRepr = repr(defaultTime)
self.assertEqual(timeRepr, "Usd.TimeCode.Default()")
self.assertEqual(eval(timeRepr), defaultTime)
@tc_logger
def testEarliestTimeRepr(self):
"""
Validates the string representation of the earliest time code.
"""
from usdrt import Usd
earliestTime = Usd.TimeCode.EarliestTime()
timeRepr = repr(earliestTime)
self.assertEqual(timeRepr, "Usd.TimeCode.EarliestTime()")
self.assertEqual(eval(timeRepr), earliestTime)
@tc_logger
def testDefaultConstructedTimeRepr(self):
"""
Validates the string representation of a time code created using
the default constructor.
"""
from usdrt import Usd
timeCode = Usd.TimeCode()
timeRepr = repr(timeCode)
self.assertEqual(timeRepr, "Usd.TimeCode()")
self.assertEqual(eval(timeRepr), timeCode)
@tc_logger
def testNumericTimeRepr(self):
"""
Validates the string representation of a numeric time code.
"""
from usdrt import Usd
timeCode = Usd.TimeCode(123.0)
timeRepr = repr(timeCode)
self.assertEqual(timeRepr, "Usd.TimeCode(123.0)")
self.assertEqual(eval(timeRepr), timeCode)
| 4,605 | Python | 27.7875 | 89 | 0.633876 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_primrange.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdPrimRange(TestClass):
@tc_logger
def test_creation(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
prim_range = Usd.PrimRange(prim)
self.assertTrue(prim_range)
@tc_logger
def test_iterator(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
prim_range = Usd.PrimRange(prim)
self.assertTrue(prim_range)
count = 0
for this_prim in prim_range:
count += 1
self.assertEqual(count, 15)
self.assertEqual(this_prim.GetPath(), Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side"))
count = 0
it = iter(prim_range)
for this_prim in it:
if this_prim.GetName() == "Green_Wall":
it.PruneChildren()
count += 1
self.assertEqual(count, 14)
self.assertEqual(this_prim.GetPath(), Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side"))
prim = stage.GetPrimAtPath(Sdf.Path("/Emissive_square/Root"))
self.assertTrue(prim)
prim_range = Usd.PrimRange(prim)
self.assertTrue(prim_range)
count = 0
for this_prim in prim_range:
count += 1
self.assertEqual(count, 5)
self.assertEqual(this_prim.GetPath(), Sdf.Path("/Emissive_square/Root/Looks/EmissiveSG/Emissive"))
count = 0
it = iter(prim_range)
for this_prim in it:
it.PruneChildren()
count += 1
self.assertEqual(count, 1)
self.assertEqual(this_prim.GetPath(), Sdf.Path("/Emissive_square/Root"))
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Emissive_square/Root"))
self.assertTrue(prim)
prim_range = Usd.PrimRange(prim)
self.assertTrue(prim_range)
expected = "PrimRange(</Emissive_square/Root>)"
self.assertEquals(repr(prim_range), expected)
| 3,515 | Python | 27.585366 | 106 | 0.640114 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_rtchangetracker.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestRtChangeTracker(TestClass):
@tc_logger
def test_ctor(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_track_attribute(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
tracker.TrackAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
self.assertFalse(tracker.HasChanges())
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute("inputs:color")
newColor = Gf.Vec3f(0, 0.5, 0.5)
attr.Set(newColor, Usd.TimeCode(0.0))
self.assertTrue(tracker.HasChanges())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_stop_tracking_attribute(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
tracker.TrackAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
self.assertFalse(tracker.HasChanges())
tracker.StopTrackingAttribute("inputs:color")
self.assertFalse(tracker.IsTrackingAttribute("inputs:color"))
newColor = Gf.Vec3f(0, 0.6, 0.6)
attr.Set(newColor, Usd.TimeCode(0.0))
self.assertFalse(tracker.HasChanges())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_pause_and_resume_tracking(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
tracker.TrackAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
tracker.PauseTracking()
newColorA = Gf.Vec3f(0, 0.7, 0.7)
attr.Set(newColorA, Usd.TimeCode(0.0))
self.assertFalse(tracker.HasChanges())
tracker.ResumeTracking()
newColorB = Gf.Vec3f(0, 0.8, 0.8)
attr.Set(newColorB, Usd.TimeCode(0.0))
self.assertTrue(tracker.HasChanges())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_is_change_tracking_paused(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
tracker.TrackAttribute("inputs:color")
self.assertFalse(tracker.IsChangeTrackingPaused())
tracker.PauseTracking()
self.assertTrue(tracker.IsChangeTrackingPaused())
tracker.ResumeTracking()
self.assertFalse(tracker.IsChangeTrackingPaused())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_has_and_clear_changes(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
self.assertFalse(tracker.HasChanges())
newColor = Gf.Vec3f(0, 0.9, 0.9)
attr.Set(newColor, Usd.TimeCode(0.0))
self.assertTrue(tracker.HasChanges())
tracker.ClearChanges()
self.assertFalse(tracker.HasChanges())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_get_all_changed_prims(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
colorAttr = lightPrim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
# No changes
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 0)
# Change on one prim
newColor = Gf.Vec3f(0, 0.4, 0.4)
colorAttr.Set(newColor, Usd.TimeCode(0.0))
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 1)
self.assertEqual(changedPrims[0], Sdf.Path("/DistantLight"))
# Change on two prims
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
visAttr = cubePrim.GetAttribute("visibility")
visAttr.Set("invisible", Usd.TimeCode(0.0))
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 2)
# Change on a prim that already has a change
lightVisAttr = lightPrim.GetAttribute("visibility")
lightVisAttr.Set("invisible", Usd.TimeCode(0.0))
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 2)
# Change an untracked attr on a third prim
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.3, 0.3)
displayColor.Set(newDisplayColor)
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 2)
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_get_all_changed_attributes(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
colorAttr = lightPrim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
# No changes
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 0)
# Change attr on one prim
newColor = Gf.Vec3f(0.5, 0.6, 0.7)
colorAttr.Set(newColor, Usd.TimeCode(0.0))
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 1)
self.assertEqual(changedAttrs[0], "/DistantLight.inputs:color")
# Change attr on a second prim
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
cubeVisAttr = cubePrim.GetAttribute("visibility")
cubeVisAttr.Set("invisible", Usd.TimeCode(0.0))
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 2)
# Change a second attr on one of the prims
lightVisAttr = lightPrim.GetAttribute("visibility")
lightVisAttr.Set("invisible", Usd.TimeCode(0.0))
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 3)
# Change an untracked attr on a third prim
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.3, 0.3)
displayColor.Set(newDisplayColor, Usd.TimeCode(0.0))
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 3)
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_prim_changed(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
colorAttr = lightPrim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
# UsdPrim version of PrimChanged()
self.assertFalse(tracker.PrimChanged(lightPrim))
newColor = Gf.Vec3f(0.6, 0.7, 0.8)
colorAttr.Set(newColor, Usd.TimeCode(0.0))
self.assertTrue(tracker.PrimChanged(lightPrim))
# SdfPath version of PrimChanged()
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
self.assertFalse(tracker.PrimChanged(Sdf.Path("/Cube_5")))
cubeVisAttr = cubePrim.GetAttribute("visibility")
cubeVisAttr.Set("invisible", Usd.TimeCode(0.0))
self.assertTrue(tracker.PrimChanged(Sdf.Path("/Cube_5")))
# Change an untracked attr on a third prim
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.4, 0.4)
displayColor.Set(newDisplayColor, Usd.TimeCode(0.0))
self.assertFalse(tracker.PrimChanged(spherePrim))
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_attribute_changed(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
colorAttr = lightPrim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
# UsdPrim version of AttributeChanged()
self.assertFalse(tracker.AttributeChanged(colorAttr))
newColor = Gf.Vec3f(0.7, 0.8, 0.9)
colorAttr.Set(newColor, Usd.TimeCode(0.0))
self.assertTrue(tracker.AttributeChanged(colorAttr))
# SdfPath version of AttributeChanged()
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
self.assertFalse(tracker.AttributeChanged(Sdf.Path("/Cube_5.visibility")))
cubeVisAttr = cubePrim.GetAttribute("visibility")
cubeVisAttr.Set("invisible", Usd.TimeCode(0.0))
self.assertTrue(tracker.AttributeChanged(Sdf.Path("/Cube_5.visibility")))
# Change an untracked attr on a third prim
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.5, 0.5)
displayColor.Set(newDisplayColor, Usd.TimeCode(0.0))
self.assertFalse(tracker.AttributeChanged(displayColor))
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_get_changed_attributes(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
tracker.TrackAttribute("subdivisionScheme")
# Change one attr on a prim
lightColor = lightPrim.GetAttribute("inputs:color")
self.assertEqual(len(tracker.GetChangedAttributes(lightPrim)), 0)
newColor = Gf.Vec3f(0.2, 0.3, 0.4)
lightColor.Set(newColor, Usd.TimeCode(0.0))
testResult = tracker.GetChangedAttributes(lightPrim)
self.assertEqual(len(testResult), 1)
self.assertEqual(testResult[0], "inputs:color")
# Change multiple tracked attrs on a prim
cubeVis = cubePrim.GetAttribute("visibility")
cubeVis.Set("invisible", Usd.TimeCode(0.0))
cubeSubdiv = cubePrim.GetAttribute("subdivisionScheme")
cubeSubdiv.Set("loop", Usd.TimeCode(0.0))
self.assertEqual(len(tracker.GetChangedAttributes(cubePrim)), 2)
# Change untracked attr on a prim
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.3, 0.5)
displayColor.Set(newDisplayColor, Usd.TimeCode(0.0))
self.assertEqual(len(tracker.GetChangedAttributes(spherePrim)), 0)
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_is_tracking_attribute(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertFalse(tracker.IsTrackingAttribute("inputs:color"))
tracker.TrackAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
tracker.TrackAttribute("visibility")
self.assertTrue(tracker.IsTrackingAttribute("visibility"))
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
tracker.StopTrackingAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("visibility"))
self.assertFalse(tracker.IsTrackingAttribute("inputs:color"))
tracker.StopTrackingAttribute("visibility")
self.assertFalse(tracker.IsTrackingAttribute("visibility"))
self.assertFalse(tracker.IsTrackingAttribute("fakeAttr"))
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_get_tracked_attributes(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertEqual(len(tracker.GetTrackedAttributes()), 0)
tracker.TrackAttribute("inputs:color")
self.assertEqual(len(tracker.GetTrackedAttributes()), 1)
self.assertEqual(tracker.GetTrackedAttributes()[0], "inputs:color")
tracker.TrackAttribute("visibility")
self.assertEqual(len(tracker.GetTrackedAttributes()), 2)
tracker.StopTrackingAttribute("inputs:color")
self.assertEqual(len(tracker.GetTrackedAttributes()), 1)
self.assertEqual(tracker.GetTrackedAttributes()[0], "visibility")
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
| 17,463 | Python | 35.383333 | 87 | 0.664033 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_array.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 ctypes
import pathlib
import platform
import weakref
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
if platform.processor() == "aarch64":
# warp not supported on aarch64 yet for our testing
return
import warp as wp
wp.init()
except ImportError:
# not needed in Kit /
# warp not available in default kit install
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
def warp_array_from_cuda_array_interface(a):
import warp as wp
cai = a.__cuda_array_interface__
return wp.types.array(
dtype=wp.vec3,
length=cai["shape"][0],
capacity=cai["shape"][0] * wp.types.type_size_in_bytes(wp.vec3),
ptr=cai["data"][0],
device="cuda",
owner=False,
requires_grad=False,
)
class TestVtArray(TestClass):
@tc_logger
def test_init(self):
from usdrt import Vt
empty = Vt.IntArray()
self.assertEquals(len(empty), 0)
allocated = Vt.IntArray(10)
self.assertEquals(len(allocated), 10)
from_list = Vt.IntArray([0, 1, 2, 3])
self.assertEquals(len(from_list), 4)
@tc_logger
def test_getset(self):
from usdrt import Vt
test_list = Vt.IntArray([0, 1, 2, 3])
self.assertEquals(len(test_list), 4)
for i in range(4):
self.assertEquals(test_list[i], i)
test_list[3] = 100
self.assertEquals(test_list[3], 100)
@tc_logger
def test_iterator(self):
from usdrt import Vt
test_list = Vt.IntArray([0, 1, 2, 3])
i = 0
for item in test_list:
self.assertEquals(i, item)
i += 1
@tc_logger
def test_is_fabric(self):
from usdrt import Sdf, Usd, Vt
test_list = Vt.IntArray([0, 1, 2, 3])
self.assertFalse(test_list.IsPythonData())
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute("faceVertexIndices")
self.assertTrue(attr)
result = attr.Get()
self.assertEquals(result[0], 1)
self.assertTrue(result.IsFabricData())
result[0] = 9
self.assertTrue(result.IsFabricData())
result2 = attr.Get()
self.assertTrue(result2.IsFabricData())
self.assertEquals(result2[0], 9)
result2.DetachFromSource()
result2[0] = 15
result3 = attr.Get()
self.assertEquals(result3[0], 9)
def _getNumpyPoints(self):
import numpy as np
points = np.zeros(shape=(1024, 3), dtype=np.float32)
points[0][0] = 999.0
points[0][1] = 998.0
points[0][2] = 997.0
points[1][0] = 1.0
points[1][1] = 2.0
points[1][2] = 3.0
points[10][0] = 10.0
points[10][1] = 20.0
points[10][2] = 30.0
return points
@tc_logger
def test_array_interface(self):
import numpy as np
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/prim"))
attr = prim.CreateAttribute("points", Sdf.ValueTypeNames.Point3fArray, True)
self.assertTrue(attr)
points = self._getNumpyPoints()
pointsRef = weakref.ref(points)
pointsId = id(points)
# Create a VtArray from a numpy array using the buffer protocol
vtPoints = Vt.Vec3fArray(points)
# Ensure the VtArray incremented the refcount on points
self.assertEqual(ctypes.c_long.from_address(pointsId).value, 2)
# Delete the numpy reference to check that the VtArray kept it alive
del points
# Ensure VtArray released the refcount on points
self.assertEqual(ctypes.c_long.from_address(pointsId).value, 1)
# Set the Fabric attribute which will make a copy from numpy to Fabric
self.assertTrue(attr.Set(vtPoints))
del vtPoints
# Ensure VtArray released the refcount on points
self.assertIsNone(pointsRef())
# Retrieve a new Fabric VtArray from usdrt
fabricPoints = attr.Get()
self.assertTrue(fabricPoints.IsFabricData())
# Create a new attribute which would invalidate any existing Fabric pointer
attr2 = prim.CreateAttribute("badattr", Sdf.ValueTypeNames.Float, True)
self.assertTrue(attr2.Set(3.5))
newPoints = np.array(fabricPoints)
# Delete the fabric VtArray to ensure the data was really copied into numpy
del fabricPoints
# Now compare the round-trip through usdrt was a success
points = self._getNumpyPoints()
for i in range(1024):
for j in range(3):
self.assertEqual(
points[i][j], newPoints[i][j], msg=f"points[{i}][{j}]: {points[i][j]} != {newPoints[i][j]}"
)
@tc_logger
def test_cuda_array_interface(self):
if platform.processor() == "aarch64":
return
import numpy as np
from usdrt import Sdf, Usd, Vt
try:
import warp as wp
except ImportError:
if TestClass is omni.kit.test.AsyncTestCase:
# warp not available for testing in kit at this time
return
raise
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/prim"))
attr = prim.CreateAttribute("points", Sdf.ValueTypeNames.Point3fArray, True)
self.assertTrue(attr)
idattr = prim.CreateAttribute("faceVertexIndices", Sdf.ValueTypeNames.IntArray, True)
self.assertTrue(idattr)
tag = prim.CreateAttribute("Deformable", Sdf.ValueTypeNames.PrimTypeTag, True)
self.assertTrue(tag)
# First create a warp array from numpy
points = self._getNumpyPoints()
warpPoints = wp.array(points, device="cpu")
with wp.ScopedCudaGuard():
gpuWarpPoints = warpPoints.to("cuda")
warpId = id(gpuWarpPoints)
warpRef = weakref.ref(gpuWarpPoints)
# Create a VtArray from a warp array using the __cuda_array_interface__
self.assertEqual(ctypes.c_long.from_address(warpId).value, 1)
vtPoints = Vt.Vec3fArray(gpuWarpPoints)
self.assertEqual(ctypes.c_long.from_address(warpId).value, 2)
# Delete the warp reference to check that the VtArray kept it alive
del gpuWarpPoints
self.assertEqual(ctypes.c_long.from_address(warpId).value, 1)
# Set the Fabric attribute which will make a CUDA copy from warp to Fabric
self.assertTrue(attr.Set(vtPoints))
# OM-84460 - IntArray supported for 1d warp arrays
warp_ids = wp.zeros(shape=1024, dtype=int, device="cuda")
vt_ids = Vt.IntArray(warp_ids)
self.assertTrue(idattr.Set(vt_ids))
wp.synchronize()
# Check the VtArray destruction released the warp array
del vtPoints
self.assertIsNone(warpRef())
# Retrieve a new Fabric VtArray from usdrt
newVtPoints = attr.Get()
self.assertTrue(newVtPoints.HasFabricGpuData())
# Create a new attribute which would invalidate any existing Fabric pointer
attr2 = prim.CreateAttribute("badattr", Sdf.ValueTypeNames.Float, True)
attr2.Set(3.5)
newWarpPoints = warp_array_from_cuda_array_interface(newVtPoints)
# Delete the fabric VtArray to ensure the data was really copied into warp
del newVtPoints
newPoints = newWarpPoints.numpy()
# Now compare the round-trip through usdrt was a success
self.assertEqual(points.shape, newPoints.shape)
for i in range(1024):
for j in range(3):
self.assertEqual(
points[i][j], newPoints[i][j], msg=f"points[{i}][{j}]: {points[i][j]} != {newPoints[i][j]}"
)
@tc_logger
def test_repr(self):
from usdrt import Vt
test_array = Vt.IntArray(4)
result = "Vt.IntArray(4, ("
for i in range(4):
test_array[i] = i
result += str(i)
if i < 3:
result += ", "
else:
result += ")"
result += ")"
self.assertEqual(result, repr(test_array))
@tc_logger
def test_str(self):
from usdrt import Vt
from pxr import Vt as PxrVt
test_array = Vt.IntArray(range(4))
expected = str(PxrVt.IntArray(range(4)))
self.assertEqual(str(test_array), expected)
@tc_logger
def test_assetarray(self):
from usdrt import Sdf, Vt
test_array = Vt.AssetArray(4)
for i in range(4):
test_array[i] = Sdf.AssetPath(f"hello{i}", f"hello{i}.txt")
self.assertEqual(len(test_array), 4)
# This should not cause a crash
del test_array
@tc_logger
def test_arraybuffer_types(self):
import numpy as np
from usdrt import Vt
self.assertTrue(Vt.BoolArray(np.zeros(shape=(10, 1), dtype=np.bool_)).IsPythonData())
self.assertTrue(Vt.CharArray(np.zeros(shape=(10, 1), dtype=np.byte)).IsPythonData())
self.assertTrue(Vt.UCharArray(np.zeros(shape=(10, 1), dtype=np.ubyte)).IsPythonData())
self.assertTrue(Vt.DoubleArray(np.zeros(shape=(10, 1), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.FloatArray(np.zeros(shape=(10, 1), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.HalfArray(np.zeros(shape=(10, 1), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.IntArray(np.zeros(shape=(10, 1), dtype=np.intc)).IsPythonData())
self.assertTrue(Vt.Int64Array(np.zeros(shape=(10, 1), dtype=np.longlong)).IsPythonData())
self.assertTrue(Vt.ShortArray(np.zeros(shape=(10, 1), dtype=np.short)).IsPythonData())
self.assertTrue(Vt.UInt64Array(np.zeros(shape=(10, 1), dtype=np.ulonglong)).IsPythonData())
self.assertTrue(Vt.UIntArray(np.zeros(shape=(10, 1), dtype=np.uintc)).IsPythonData())
self.assertTrue(Vt.UShortArray(np.zeros(shape=(10, 1), dtype=np.ushort)).IsPythonData())
self.assertTrue(Vt.Matrix3dArray(np.zeros(shape=(10, 9), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Matrix3fArray(np.zeros(shape=(10, 9), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.Matrix4dArray(np.zeros(shape=(10, 16), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Matrix4fArray(np.zeros(shape=(10, 16), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.QuatdArray(np.zeros(shape=(10, 4), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.QuatfArray(np.zeros(shape=(10, 4), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.QuathArray(np.zeros(shape=(10, 4), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.Vec2dArray(np.zeros(shape=(10, 2), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Vec3dArray(np.zeros(shape=(10, 3), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Vec4dArray(np.zeros(shape=(10, 4), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Vec2fArray(np.zeros(shape=(10, 2), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.Vec3fArray(np.zeros(shape=(10, 3), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.Vec4fArray(np.zeros(shape=(10, 4), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.Vec2hArray(np.zeros(shape=(10, 2), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.Vec3hArray(np.zeros(shape=(10, 3), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.Vec4hArray(np.zeros(shape=(10, 4), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.Vec2iArray(np.zeros(shape=(10, 2), dtype=np.intc)).IsPythonData())
self.assertTrue(Vt.Vec3iArray(np.zeros(shape=(10, 3), dtype=np.intc)).IsPythonData())
self.assertTrue(Vt.Vec4iArray(np.zeros(shape=(10, 4), dtype=np.intc)).IsPythonData())
@tc_logger
def test_implicit_conversion_bindings(self):
from usdrt import Gf, Sdf, Usd, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/prim"))
# IntArray
intarray = prim.CreateAttribute("intarray", Sdf.ValueTypeNames.IntArray, True)
self.assertTrue(intarray)
intarray.Set(Vt.IntArray([0, 1, 2]))
intlist = list(prim.GetAttribute("intarray").Get())
self.assertEqual(len(intlist), 3)
intlist.extend([3])
self.assertEqual(len(intlist), 4)
self.assertTrue(prim.GetAttribute("intarray").Set(intlist))
updated_list = prim.GetAttribute("intarray").Get()
self.assertEqual(len(updated_list), 4)
self.assertEqual(list(updated_list), [0, 1, 2, 3])
# Point3fArray
points = prim.CreateAttribute("points", Sdf.ValueTypeNames.Point3fArray, True)
self.assertTrue(points)
points.Set(Vt.Vec3fArray([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]))
vertices = list(prim.GetAttribute("points").Get())
self.assertEqual(len(vertices), 3)
vertices.extend([[3.0, 3.0, 3.0]])
prim.GetAttribute("points").Set(vertices)
updated_vertices = prim.GetAttribute("points").Get()
self.assertEqual(len(updated_vertices), 4)
| 14,605 | Python | 34.537713 | 111 | 0.621294 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_rtboundable.py | __copyright__ = "Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestRtBoundable(TestClass):
@tc_logger
def test_ctor(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
empty = Rt.Boundable()
self.assertFalse(empty)
@tc_logger
def test_get_prim(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
check_prim = boundable.GetPrim()
self.assertEqual(prim.GetPath(), check_prim.GetPath())
@tc_logger
def test_get_path(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
self.assertEqual(prim.GetPath(), boundable.GetPath())
@tc_logger
def test_world_extent(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
extent = Gf.Range3d(Gf.Vec3d(-10, -10, -10), Gf.Vec3d(10, 10, 10))
attr = boundable.CreateWorldExtentAttr(extent)
self.assertTrue(attr)
attr = boundable.GetWorldExtentAttr()
self.assertTrue(attr)
world_ext = attr.Get()
self.assertEqual(extent, world_ext)
@tc_logger
def test_has_world_extent(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
self.assertFalse(boundable.HasWorldExtent())
extent = Gf.Range3d(Gf.Vec3d(-10, -10, -10), Gf.Vec3d(10, 10, 10))
attr = boundable.CreateWorldExtentAttr(extent)
self.assertTrue(attr)
self.assertTrue(boundable.HasWorldExtent())
@tc_logger
def test_clear_world_extent(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
self.assertFalse(boundable.HasWorldXform())
extent = Gf.Range3d(Gf.Vec3d(-10, -10, -10), Gf.Vec3d(10, 10, 10))
attr = boundable.CreateWorldExtentAttr(extent)
self.assertTrue(attr)
self.assertTrue(boundable.HasWorldExtent())
boundable.ClearWorldExtent()
self.assertFalse(boundable.HasWorldExtent())
@tc_logger
def test_set_world_extent_from_usd(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
self.assertFalse(boundable.HasWorldExtent())
self.assertTrue(boundable.SetWorldExtentFromUsd())
self.assertTrue(boundable.HasWorldExtent())
attr = boundable.GetWorldExtentAttr()
self.assertTrue(attr)
extent = attr.Get()
expected = Gf.Range3d(Gf.Vec3d(247.11319, -249.90994, 0.0), Gf.Vec3d(247.11328, 249.91781, 500.0))
self.assertTrue(Gf.IsClose(extent.GetMin(), expected.GetMin(), 0.001))
self.assertTrue(Gf.IsClose(extent.GetMax(), expected.GetMax(), 0.001))
@tc_logger
def test_boundable_tokens(self):
from usdrt import Rt
self.assertEqual(Rt.Tokens.worldExtent, "_worldExtent")
@tc_logger
def test_repr_representation(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
expected = "Boundable(</Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back>)"
self.assertEqual(repr(boundable), expected)
| 6,321 | Python | 28.962085 | 106 | 0.655434 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_rtxformable.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestRtXformable(TestClass):
@tc_logger
def test_ctor(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
empty = Rt.Xformable()
self.assertFalse(empty)
@tc_logger
def test_get_prim(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
check_prim = xformable.GetPrim()
self.assertEqual(prim.GetPath(), check_prim.GetPath())
@tc_logger
def test_get_path(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertEqual(prim.GetPath(), xformable.GetPath())
@tc_logger
def test_world_position(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
new_world_pos = Gf.Vec3d(100, 200, 300)
offset = Gf.Vec3d(100, 200, 300)
attr = xformable.CreateWorldPositionAttr(new_world_pos)
self.assertTrue(attr)
attr = xformable.GetWorldPositionAttr()
self.assertTrue(attr)
world_pos = attr.Get()
self.assertEqual(new_world_pos, world_pos)
world_pos += offset
attr.Set(world_pos)
@tc_logger
def test_world_orientation(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
new_world_or = Gf.Quatf(0.5, -1, 2, -3)
attr = xformable.CreateWorldOrientationAttr(new_world_or)
self.assertTrue(attr)
attr = xformable.GetWorldOrientationAttr()
self.assertTrue(attr)
world_or = attr.Get()
self.assertEqual(new_world_or, world_or)
@tc_logger
def test_world_scale(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
new_world_scale = Gf.Vec3f(100, 200, 300)
attr = xformable.CreateWorldScaleAttr(new_world_scale)
self.assertTrue(attr)
attr = xformable.GetWorldScaleAttr()
self.assertTrue(attr)
world_scale = attr.Get()
self.assertEqual(new_world_scale, world_scale)
@tc_logger
def test_local_matrix(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
new_local_matrix = Gf.Matrix4d(2)
attr = xformable.CreateLocalMatrixAttr(new_local_matrix)
self.assertTrue(attr)
attr = xformable.GetLocalMatrixAttr()
self.assertTrue(attr)
local_matrix = attr.Get()
self.assertEqual(new_local_matrix, local_matrix)
@tc_logger
def test_has_world_xform(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasWorldXform())
new_world_pos = Gf.Vec3d(100, 200, 300)
attr = xformable.CreateWorldPositionAttr(new_world_pos)
self.assertTrue(attr)
self.assertTrue(xformable.HasWorldXform())
@tc_logger
def test_clear_world_xform(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasWorldXform())
new_world_pos = Gf.Vec3d(100, 200, 300)
attr = xformable.CreateWorldPositionAttr(new_world_pos)
self.assertTrue(attr)
self.assertTrue(xformable.HasWorldXform())
xformable.ClearWorldXform()
self.assertFalse(xformable.HasWorldXform())
@tc_logger
def test_set_world_xform_from_usd(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasWorldXform())
self.assertTrue(xformable.SetWorldXformFromUsd())
self.assertTrue(xformable.HasWorldXform())
pos_attr = xformable.GetWorldPositionAttr()
self.assertTrue(pos_attr)
orient_attr = xformable.GetWorldOrientationAttr()
self.assertTrue(orient_attr)
scale_attr = xformable.GetWorldScaleAttr()
self.assertTrue(scale_attr)
self.assertTrue(Gf.IsClose(pos_attr.Get(), Gf.Vec3d(0, 0, 250), 0.00001))
self.assertTrue(Gf.IsClose(orient_attr.Get(), Gf.Quatf(0.5, -0.5, 0.5, -0.5), 0.00001))
self.assertTrue(Gf.IsClose(scale_attr.Get(), Gf.Vec3f(1, 1, 1), 0.00001))
@tc_logger
def test_has_local_xform(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasLocalXform())
new_local_mat = Gf.Matrix4d(2)
attr = xformable.CreateLocalMatrixAttr(new_local_mat)
self.assertTrue(attr)
self.assertTrue(xformable.HasLocalXform())
@tc_logger
def test_clear_local_xform(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasLocalXform())
new_local_mat = Gf.Matrix4d(2)
attr = xformable.CreateLocalMatrixAttr(new_local_mat)
self.assertTrue(attr)
self.assertTrue(xformable.HasLocalXform())
xformable.ClearLocalXform()
self.assertFalse(xformable.HasLocalXform())
@tc_logger
def test_set_local_xform_from_usd(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasLocalXform())
self.assertTrue(xformable.SetLocalXformFromUsd())
self.assertTrue(xformable.HasLocalXform())
attr = xformable.GetLocalMatrixAttr()
self.assertTrue(attr)
self.assertTrue(Gf.IsClose(attr.Get(), Gf.Matrix4d(1), 0.00001))
@tc_logger
def test_tokens(self):
from usdrt import Rt
self.assertEqual(Rt.Tokens.worldPosition, "_worldPosition")
self.assertEqual(Rt.Tokens.worldOrientation, "_worldOrientation")
self.assertEqual(Rt.Tokens.worldScale, "_worldScale")
self.assertEqual(Rt.Tokens.localMatrix, "_localMatrix")
@tc_logger
def test_repr_representation(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
expected = "Xformable(</Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back>)"
self.assertEqual(repr(xformable), expected)
| 10,955 | Python | 29.518106 | 97 | 0.651118 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_pointInstancer.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdGeomPointInstancer(TestClass):
@tc_logger
def test_get_relationship(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/inst"), "PointInstancer")
self.assertFalse(prim.HasRelationship("prototypes"))
inst = UsdGeom.PointInstancer(prim)
self.assertTrue(inst)
# create attribute using prim api
rel = prim.CreateRelationship(UsdGeom.Tokens.prototypes, False)
self.assertTrue(rel)
# verify get attribute using schema api
protoRel = inst.GetPrototypesRel()
self.assertTrue(protoRel)
self.assertTrue(protoRel.GetName() == "prototypes")
@tc_logger
def test_create_relationship(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/inst"), "PointInstancer")
self.assertFalse(prim.HasRelationship("prototypes"))
# create rel using schema api
inst = UsdGeom.PointInstancer(prim)
self.assertTrue(inst)
rel = inst.CreatePrototypesRel()
# verify using prim api
self.assertTrue(rel)
self.assertTrue(prim.HasRelationship(UsdGeom.Tokens.prototypes))
self.assertTrue(rel.GetName() == "prototypes")
| 2,519 | Python | 27.965517 | 78 | 0.687177 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_prim.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdPrim(TestClass):
@tc_logger
def test_has_attribute(self):
from usdrt import Sdf, Usd, UsdGeom
# print("Attach to {}".format(os.getpid()))
# time.sleep(10)
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
self.assertTrue(prim.HasAttribute(UsdGeom.Tokens.xformOpOrder))
self.assertFalse(prim.HasAttribute(UsdGeom.Tokens.radius))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
self.assertTrue(prim.HasAttribute(UsdGeom.Tokens.faceVertexIndices))
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.HasAttribute(UsdGeom.Tokens.radius))
@tc_logger
def test_get_attribute(self):
from usdrt import Sdf, Usd, UsdGeom
# print("Attach to {}".format(os.getpid()))
# time.sleep(10)
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr)
self.assertTrue(attr.GetName() == UsdGeom.Tokens.doubleSided)
# TODO get value
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.GetAttribute(UsdGeom.Tokens.radius))
@tc_logger
def test_get_attributes(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attributes = prim.GetAttributes()
self.assertTrue(len(attributes) == 12)
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.GetAttributes())
@tc_logger
def test_create_attribute(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/prim"))
self.assertFalse(prim.HasAttribute("myAttr"))
attr = prim.CreateAttribute("myAttr", Sdf.ValueTypeNames.Int, True)
self.assertTrue(attr)
self.assertTrue(prim.HasAttribute("myAttr"))
self.assertTrue(attr.GetName() == "myAttr")
@tc_logger
def test_create_attribute_invalid(self):
# Ensure creating attribute on invalid prim does not crash
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/invalid"))
self.assertFalse(prim)
self.assertFalse(prim.IsValid())
# this should not crash
attr = prim.CreateAttribute("testAttr", Sdf.ValueTypeNames.Int, True)
self.assertFalse(attr)
# this should not crash
xformable = Rt.Xformable(prim)
attr = xformable.CreateWorldPositionAttr(Gf.Vec3d(0, 200, 0))
self.assertFalse(attr)
@tc_logger
def test_has_relationship(self):
from usdrt import Sdf, Usd, UsdGeom, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"))
self.assertTrue(prim)
self.assertTrue(prim.HasRelationship(UsdShade.Tokens.materialBinding))
self.assertFalse(prim.HasRelationship(UsdGeom.Tokens.proxyPrim))
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.HasRelationship(UsdShade.Tokens.materialBinding))
@tc_logger
def test_get_relationship(self):
from usdrt import Sdf, Usd, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"))
self.assertTrue(prim)
rel = prim.GetRelationship(UsdShade.Tokens.materialBinding)
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.GetRelationship(UsdShade.Tokens.materialBinding))
@tc_logger
def test_get_relationships(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"))
self.assertTrue(prim)
relationships = prim.GetRelationships()
self.assertEqual(len(relationships), 1)
targets = relationships[0].GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
# non-authored relationships from schema (proxyPrim) not included here
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall"))
relationships = prim.GetRelationships()
self.assertEqual(len(relationships), 0)
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.GetRelationships())
@tc_logger
def test_create_relationship(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"))
self.assertTrue(prim)
self.assertFalse(prim.HasRelationship("foobar"))
rel = prim.CreateRelationship("foobar")
self.assertTrue(prim.HasRelationship("foobar"))
self.assertFalse(rel.HasAuthoredTargets())
@tc_logger
def test_create_relationship_invalid(self):
# OM_81734 Ensure creating rel on invalid prim does not crash
from usdrt import Sdf, Usd
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/invalid"))
self.assertFalse(prim)
self.assertFalse(prim.IsValid())
# this should not crash
rel = prim.CreateRelationship("testrel")
self.assertFalse(rel)
@tc_logger
def test_remove_property(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall"))
self.assertTrue(prim)
self.assertTrue(prim.HasAttribute(UsdGeom.Tokens.extent))
self.assertTrue(prim.RemoveProperty(UsdGeom.Tokens.extent))
self.assertFalse(prim.HasAttribute(UsdGeom.Tokens.extent))
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.RemoveProperty(UsdGeom.Tokens.extent))
@tc_logger
def test_family(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
child = prim.GetChild("White_Wall_Back")
self.assertTrue(child)
self.assertTrue(child.GetPath() == Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
parent = prim.GetParent()
self.assertTrue(parent)
self.assertTrue(parent.GetPath() == Sdf.Path("/Cornell_Box/Root"))
sibling = prim.GetNextSibling()
self.assertTrue(sibling)
self.assertTrue(sibling.GetPath() == Sdf.Path("/Cornell_Box/Root/Looks"))
children = prim.GetChildren()
i = 0
for child in children:
child_direct = prim.GetChild(child.GetName())
self.assertEqual(child.GetName(), child_direct.GetName())
i += 1
self.assertEqual(i, 5)
@tc_logger
def test_get_type(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
test_type = prim.GetTypeName()
self.assertEqual(test_type, "Xform")
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
test_type = prim.GetTypeName()
self.assertEqual(test_type, "Mesh")
@tc_logger
def test_set_type(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
self.assertEqual(prim.GetTypeName(), "Xform")
self.assertTrue(prim.SetTypeName("SkelRoot"))
self.assertEqual(prim.GetTypeName(), "SkelRoot")
@tc_logger
def test_has_authored_type(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Emissive_square/Root"))
self.assertTrue(prim)
self.assertFalse(prim.HasAuthoredTypeName())
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
self.assertTrue(prim.HasAuthoredTypeName())
@tc_logger
def test_clear_type(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
self.assertTrue(prim.HasAuthoredTypeName())
prim.ClearTypeName()
self.assertFalse(prim.HasAuthoredTypeName())
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
expected = "Prim(</Cornell_Box/Root/Cornell_Box1_LP>)"
self.assertEqual(repr(prim), expected)
@tc_logger
def test_has_api(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
self.assertTrue(prim.HasAPI("ShapingAPI"))
self.assertFalse(prim.HasAPI("DoesNotExist"))
@tc_logger
def test_apply_api(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
self.assertTrue(prim.ApplyAPI("Test1"))
self.assertTrue(prim.HasAPI("Test1"))
self.assertTrue(prim.AddAppliedSchema("Test2"))
self.assertTrue(prim.HasAPI("Test2"))
@tc_logger
def test_remove_api(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
self.assertTrue(prim.ApplyAPI("Test1"))
self.assertTrue(prim.HasAPI("Test1"))
self.assertTrue(prim.AddAppliedSchema("Test2"))
self.assertTrue(prim.HasAPI("Test2"))
self.assertTrue(prim.RemoveAPI("Test1"))
self.assertFalse(prim.HasAPI("Test1"))
self.assertTrue(prim.RemoveAppliedSchema("Test2"))
self.assertFalse(prim.HasAPI("Test2"))
@tc_logger
def test_get_applied_schemas(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
schemas = prim.GetAppliedSchemas()
self.assertEqual(len(schemas), 5)
self.assertTrue("LightAPI" in schemas)
self.assertTrue("ShapingAPI" in schemas)
self.assertTrue("CollectionAPI" in schemas)
self.assertTrue("CollectionAPI:lightLink" in schemas)
self.assertTrue("CollectionAPI:shadowLink" in schemas)
@tc_logger
def test_get_stage(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
# force stage2 out of scope
stage2 = prim.GetStage()
self.assertTrue(stage2)
del stage2
# ensure underlying shared data is unchanged
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
| 15,183 | Python | 31.444444 | 105 | 0.652704 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_valuetypename.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestSdfValueTypeName(TestClass):
@tc_logger
def test_get_scalar_type(self):
from usdrt import Sdf
scalar_int = Sdf.ValueTypeNames.IntArray.scalarType
self.assertEqual(scalar_int, Sdf.ValueTypeNames.Int)
@tc_logger
def test_get_array_type(self):
from usdrt import Sdf
array_int = Sdf.ValueTypeNames.Int.arrayType
self.assertEqual(array_int, Sdf.ValueTypeNames.IntArray)
@tc_logger
def test_is_array(self):
from usdrt import Sdf
array_type = Sdf.ValueTypeNames.IntArray
scalar_type = Sdf.ValueTypeNames.Int
self.assertTrue(array_type.isArray)
self.assertFalse(scalar_type.isArray)
@tc_logger
def test_is_scalar(self):
from usdrt import Sdf
array_type = Sdf.ValueTypeNames.IntArray
scalar_type = Sdf.ValueTypeNames.Int
self.assertFalse(array_type.isScalar)
self.assertTrue(scalar_type.isScalar)
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf
array_type = Sdf.ValueTypeNames.IntArray
scalar_type = Sdf.ValueTypeNames.Int
array_expected = "Sdf.ValueTypeName('int[]')"
scalar_expected = "Sdf.ValueTypeName('int')"
self.assertEquals(repr(array_type), array_expected)
self.assertEquals(repr(scalar_type), scalar_expected)
| 2,477 | Python | 25.361702 | 78 | 0.691966 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/__init__.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 gc
scan_for_test_modules = True
def tc_logger(func):
"""
Print TC macros about the test when running on TC
(unneeded in kit)
"""
def wrapper(*args, **kwargs):
func(*args, **kwargs)
# Always reset global stage cache and collect
# garbage to ensure stage and Fabric cleanup
from pxr import UsdUtils
UsdUtils.StageCache.Get().Clear()
gc.collect()
return wrapper
| 895 | Python | 27.903225 | 78 | 0.710615 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_relationship.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdRelationship(TestClass):
@tc_logger
def test_has_authored_targets(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
self.assertTrue(rel.HasAuthoredTargets())
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall.proxyPrim"))
self.assertTrue(rel)
self.assertFalse(rel.HasAuthoredTargets())
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.HasAuthoredTargets())
@tc_logger
def test_get_targets(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.GetTargets())
@tc_logger
def test_add_target(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
new_target = Sdf.Path("/Cornell_Box/Root/Looks/Red1SG")
self.assertTrue(rel.AddTarget(new_target))
targets = rel.GetTargets()
self.assertEqual(len(targets), 2)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
self.assertEqual(targets[1], new_target)
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall.proxyPrim"))
self.assertTrue(rel)
proxy_prim_target = Sdf.Path("/Cube_5")
self.assertTrue(rel.AddTarget(proxy_prim_target))
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], proxy_prim_target)
# OM-75327 - add a target to a new relationship
prim = stage.GetPrimAtPath("/Cornell_Box")
self.assertTrue(prim)
rel = prim.CreateRelationship("testRel")
self.assertTrue(rel)
self.assertTrue(rel.AddTarget(proxy_prim_target))
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cube_5"))
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.AddTarget(proxy_prim_target))
@tc_logger
def test_remove_target(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
# It's valid to try to remove a target that is not
# in the list of targets in the relationship
target_not_in_list = Sdf.Path("/Foo/Bar")
self.assertTrue(rel.RemoveTarget(target_not_in_list))
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
# Removing a valid target will return empty target lists with GetTarget
target_in_list = Sdf.Path("/Cornell_Box/Root/Looks/Green1SG")
self.assertTrue(rel.RemoveTarget(target_in_list))
targets = rel.GetTargets()
self.assertEqual(len(targets), 0)
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.RemoveTarget(target_not_in_list))
@tc_logger
def test_clear_targets(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
self.assertTrue(rel.ClearTargets(True))
targets = rel.GetTargets()
self.assertEqual(len(targets), 0)
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.ClearTargets(True))
@tc_logger
def test_set_targets(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
new_targets = [Sdf.Path("/Cornell_Box/Root/Looks/Red1SG")]
self.assertTrue(rel.SetTargets(new_targets))
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Red1SG"))
too_many_targets = [Sdf.Path("/Foo"), Sdf.Path("/Bar")]
self.assertTrue(rel.SetTargets(too_many_targets))
targets = rel.GetTargets()
self.assertEqual(len(targets), 2)
self.assertEqual(targets[0], Sdf.Path("/Foo"))
self.assertEqual(targets[1], Sdf.Path("/Bar"))
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.SetTargets(new_targets))
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
expected = "Relationship(<material:binding>)"
self.assertEquals(repr(rel), expected)
| 8,239 | Python | 33.333333 | 109 | 0.653356 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_usd_collectionAPI.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdCollectionAPI(TestClass):
@tc_logger
def test_boolean_operator(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_collection.usda")
self.assertTrue(stage)
testPrim = stage.GetPrimAtPath("/CollectionTest")
self.assertTrue(testPrim)
explicitColl = Usd.CollectionAPI(testPrim, "leafGeom")
self.assertTrue(explicitColl)
explicitColl = Usd.CollectionAPI(testPrim, "test")
self.assertFalse(explicitColl)
@tc_logger
def test_create_relationship(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_collection.usda")
self.assertTrue(stage)
testPrim = stage.GetPrimAtPath("/CollectionTest")
sphere = stage.GetPrimAtPath("/CollectionTest/Geom/Shapes/Sphere")
self.assertTrue(testPrim)
self.assertTrue(sphere.IsValid())
self.assertTrue(testPrim.ApplyAPI("CollectionAPI:test"))
explicitColl = Usd.CollectionAPI(testPrim, "test")
self.assertTrue(explicitColl)
# create rel using schema api
rel = explicitColl.CreateIncludesRel()
self.assertTrue(rel)
rel.AddTarget(sphere.GetPath())
self.assertTrue(rel.HasAuthoredTargets())
# verify using prim api
relVerify = testPrim.GetRelationship("collection:test:includes")
self.assertTrue(relVerify)
self.assertTrue(relVerify.HasAuthoredTargets())
@tc_logger
def test_get_relationship(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_collection.usda")
self.assertTrue(stage)
testPrim = stage.GetPrimAtPath("/CollectionTest")
sphere = stage.GetPrimAtPath("/CollectionTest/Geom/Shapes/Sphere")
self.assertTrue(testPrim)
self.assertTrue(sphere.IsValid())
self.assertTrue(testPrim.ApplyAPI("CollectionAPI:test"))
# create relationship using prim api
rel = testPrim.CreateRelationship("collection:test:includes", False)
self.assertTrue(rel)
rel.AddTarget(sphere.GetPath())
self.assertTrue(rel.HasAuthoredTargets())
# verify get relationship using schema api
coll = Usd.CollectionAPI(testPrim, "test")
inclRel = coll.GetIncludesRel()
self.assertTrue(inclRel)
self.assertTrue(inclRel.GetName() == "collection:test:includes")
self.assertTrue(inclRel.HasAuthoredTargets())
| 3,638 | Python | 29.325 | 81 | 0.685542 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_attribute.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
if platform.processor() == "aarch64":
# warp not supported on aarch64 yet for our testing
return
import warp as wp
wp.init()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdAttribute(TestClass):
@tc_logger
def test_get(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, UsdLux
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr)
result = False
result = attr.Get()
self.assertTrue(result)
self.assertTrue(isinstance(result, bool))
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdLux.Tokens.inputsIntensity)
self.assertTrue(attr)
result = 5.0
result = attr.Get()
self.assertEquals(result, 150.0)
self.assertTrue(isinstance(result, float))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.faceVertexIndices)
self.assertTrue(attr)
result = attr.Get()
self.assertEquals(len(result), 4)
self.assertTrue(result.IsFabricData())
self.assertEquals(result[0], 1)
self.assertEquals(result[1], 3)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute(UsdLux.Tokens.inputsColor)
result = attr.Get()
self.assertTrue(isinstance(result, Gf.Vec3f))
self.assertEquals(result, Gf.Vec3f(1, 1, 1))
attr = prim.GetAttribute(UsdGeom.Tokens.visibility)
result = attr.Get()
self.assertEquals(result, UsdGeom.Tokens.inherited)
prim = stage.GetPrimAtPath(Sdf.Path("/Cube_5/subset/BasicShapeMaterial/BasicShapeMaterial"))
attr = prim.GetAttribute("path")
result = attr.Get()
self.assertEquals(result, "/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial")
# invalid attr should not cause crash
attr = prim.GetAttribute("invalid")
self.assertFalse(attr)
self.assertFalse(attr.Get())
@tc_logger
def test_set(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, UsdLux, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr)
result = False
result = attr.Get()
self.assertTrue(result)
self.assertTrue(isinstance(result, bool))
attr.Set(False)
result = attr.Get()
self.assertFalse(result)
self.assertTrue(isinstance(result, bool))
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdLux.Tokens.inputsIntensity)
self.assertTrue(attr)
result = 5.0
result = attr.Get()
self.assertEquals(result, 150.0)
self.assertTrue(isinstance(result, float))
attr.Set(15.5)
result = attr.Get()
self.assertEquals(result, 15.5)
self.assertTrue(isinstance(result, float))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.faceVertexIndices)
self.assertTrue(attr)
newValues = Vt.IntArray([9, 8, 7, 6])
self.assertTrue(attr.Set(newValues))
result = attr.Get()
self.assertEquals(len(result), 4)
self.assertTrue(result.IsFabricData())
for i in range(4):
self.assertEquals(result[i], 9 - i)
newValues = Vt.IntArray([0, 1, 2, 3, 4, 5, 6])
self.assertTrue(attr.Set(newValues))
result = attr.Get()
self.assertEquals(len(result), 7)
self.assertTrue(result.IsFabricData())
for i in range(7):
self.assertEquals(result[i], i)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute(UsdLux.Tokens.inputsColor)
newColor = Gf.Vec3f(0, 0.5, 0.5)
self.assertTrue(attr.Set(newColor))
vecCheck = attr.Get()
self.assertTrue(isinstance(vecCheck, Gf.Vec3f))
self.assertEquals(vecCheck, Gf.Vec3f(0, 0.5, 0.5))
# setting with an invalid type for the attr should fail
self.assertFalse(attr.Set("stringvalue"))
result = attr.Get()
self.assertEquals(result, Gf.Vec3f(0, 0.5, 0.5))
attr = prim.GetAttribute(UsdGeom.Tokens.visibility)
result = attr.Get()
self.assertEquals(result, UsdGeom.Tokens.inherited)
self.assertTrue(attr.Set(UsdGeom.Tokens.invisible))
result = attr.Get()
self.assertEquals(result, UsdGeom.Tokens.invisible)
prim = stage.GetPrimAtPath(Sdf.Path("/Cube_5/subset/BasicShapeMaterial/BasicShapeMaterial"))
attr = prim.GetAttribute("path")
result = attr.Get()
self.assertEquals(result, "/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial")
newString = "/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial100"
self.assertTrue(attr.Set(newString))
result = attr.Get()
self.assertEquals(result, "/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial100")
# invalid attr should not cause crash
attr = prim.GetAttribute("invalid")
self.assertFalse(attr)
self.assertFalse(attr.Set("stringvalue"))
@tc_logger
def test_has_value(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr.HasValue())
attr2 = prim.GetAttribute(UsdGeom.Tokens.purpose)
self.assertFalse(attr2.HasValue())
# invalid attr should not cause crash
attr = prim.GetAttribute("invalid")
self.assertFalse(attr)
self.assertFalse(attr.HasValue())
@tc_logger
def test_name(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.primvarsDisplayColor)
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
self.assertEquals(attr.GetName(), UsdGeom.Tokens.primvarsDisplayColor)
self.assertEquals(attr.GetBaseName(), "displayColor")
self.assertEquals(attr.GetNamespace(), "primvars")
parts = attr.SplitName()
self.assertEquals(len(parts), 2)
self.assertEquals(parts[0], "primvars")
self.assertEquals(parts[1], "displayColor")
@tc_logger
def test_create_every_attribute_type(self):
from usdrt import Gf, Sdf, Usd, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/test"), "Xform")
self.assertTrue(prim)
# These are the types that I know are missing support, either
# because Fabric doesn't support them (string array), or USDRT hasn't implemented
# support yet (assets), or there will never be a Python rep (PrimTagType)
KNOWN_INVALID_TYPES = [
"StringArray",
]
KNOWN_UNSUPPORTED_TYPES = [
"Frame4d",
"Frame4dArray",
]
NO_DATA_TAG_TYPES = [
"PrimTypeTag",
"AppliedSchemaTypeTag",
"AncestorPrimTypeTag",
"Tag",
]
# These are the types that should be supported and are not for some
# reason - OM-53013
FIXME_UNSUPPORTED_TYPES = [
"Matrix2d",
"Matrix2dArray",
"TimeCode",
"TimeCodeArray",
]
for type_name in dir(Sdf.ValueTypeNames):
if type_name.startswith("__"):
continue
if type_name in KNOWN_INVALID_TYPES:
continue
value_type_name = getattr(Sdf.ValueTypeNames, type_name)
if not isinstance(value_type_name, Sdf.ValueTypeName):
continue
attr = prim.CreateAttribute(type_name, value_type_name, True)
self.assertTrue(attr)
result = attr.Get()
if result is None:
# Python bindings warn about unsupported type using C++ name,
# add a note to clarify using SdfValueTypeName
self.assertTrue(
type_name in KNOWN_UNSUPPORTED_TYPES
or type_name in FIXME_UNSUPPORTED_TYPES
or type_name in NO_DATA_TAG_TYPES
)
if type_name in FIXME_UNSUPPORTED_TYPES:
reason = "this will be fixed eventually"
elif type_name in KNOWN_UNSUPPORTED_TYPES:
reason = "this is intentional"
elif type_name in NO_DATA_TAG_TYPES:
reason = "expected no data attribute"
print(f"i.e. SdfValueTypeName.{type_name} - {reason}")
@tc_logger
def test_get_type(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.faceVertexCounts)
self.assertTrue(attr)
self.assertEqual(attr.GetTypeName(), Sdf.ValueTypeNames.IntArray)
attr = prim.GetAttribute(UsdGeom.Tokens.normals)
self.assertTrue(attr)
self.assertEqual(attr.GetTypeName(), Sdf.ValueTypeNames.Normal3fArray)
# invalid attr should not cause crash
attr = prim.GetAttribute("invalid")
self.assertFalse(attr)
self.assertFalse(attr.GetTypeName())
@tc_logger
def test_get_type(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.faceVertexCounts)
self.assertTrue(attr)
expected = "Attribute(</Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back.faceVertexCounts>)"
self.assertEqual(repr(attr), expected)
@tc_logger
def test_cpu_gpu_data_sync(self):
if platform.processor() == "aarch64":
return
from usdrt import Sdf, Usd, UsdGeom, Vt
try:
import warp as wp
except ImportError:
if TestClass is omni.kit.test.AsyncTestCase:
# warp not available for testing in kit at this time
return
raise
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.points)
self.assertTrue(attr)
self.assertTrue(attr.IsCpuDataValid())
self.assertFalse(attr.IsGpuDataValid())
# Force sync to GPU
attr.SyncDataToGpu()
self.assertTrue(attr.IsCpuDataValid())
self.assertTrue(attr.IsGpuDataValid())
# Write a new GPU value
points = attr.Get()
wp_points = wp.array(points, device="cpu")
with wp.ScopedCudaGuard():
wpgpu_points = wp_points.to("cuda")
vt_gpu = Vt.Vec3fArray(wpgpu_points)
attr.Set(vt_gpu)
wp.synchronize()
self.assertFalse(attr.IsCpuDataValid())
self.assertTrue(attr.IsGpuDataValid())
# Force sync to CPU
attr.SyncDataToCpu()
self.assertTrue(attr.IsCpuDataValid())
self.assertTrue(attr.IsGpuDataValid())
# Invalidate data on CPU
attr.InvalidateCpuData()
self.assertFalse(attr.IsCpuDataValid())
self.assertTrue(attr.IsGpuDataValid())
# Invalidate data on GPU
attr.InvalidateGpuData()
self.assertTrue(attr.IsCpuDataValid())
self.assertFalse(attr.IsGpuDataValid())
# Test Connections
@tc_logger
def test_has_authored_connections(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
self.assertTrue(attr.HasAuthoredConnections())
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:surface"))
self.assertTrue(attr)
self.assertFalse(attr.HasAuthoredConnections())
attr = stage.GetAttributeAtPath(
Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.info:implementationSource")
)
self.assertTrue(attr)
self.assertFalse(attr.HasAuthoredConnections())
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.HasAuthoredConnections())
@tc_logger
def test_get_connections(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out"))
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.GetConnections())
@tc_logger
def test_add_connection(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
path = Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement")
attr = stage.GetAttributeAtPath(path)
self.assertTrue(attr)
new_connection = Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:surface")
self.assertTrue(attr.AddConnection(new_connection))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], new_connection)
# add a connection to a new attribute
proxy_prim_connection = Sdf.Path("/Cube_5")
prim = stage.GetPrimAtPath("/Cornell_Box")
self.assertTrue(prim)
attr = prim.CreateAttribute("testAttr", Sdf.ValueTypeNames.Token, True)
self.assertTrue(attr)
self.assertTrue(attr.AddConnection(proxy_prim_connection))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cube_5"))
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.AddConnection(Sdf.Path("/Cube_5")))
@tc_logger
def test_remove_connection(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
# It's valid to try to remove a connection that is not
# in the list of connections
connection_not_in_list = Sdf.Path("/Foo/Bar")
self.assertTrue(attr.RemoveConnection(connection_not_in_list))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out"))
# Removing a valid connection will return empty connection lists with GetConnections
connection_in_list = Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out")
self.assertTrue(attr.RemoveConnection(connection_in_list))
connections = attr.GetConnections()
self.assertEqual(len(connections), 0)
# multiple connections not supported yet
# test removing if there are multiple in the list
# multiple_connections = [Sdf.Path("/Foo"), Sdf.Path("/Bar")]
# self.assertTrue(attr.SetConnections(multiple_connections))
# self.assertTrue(attr.RemoveConnection(Sdf.Path("/Bar")))
# connections = attr.GetConnections()
# self.assertEqual(len(connections), 1)
# self.assertEqual(connections[0], Sdf.Path("/Foo"))
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.RemoveConnection(Sdf.Path("/Cube_5")))
@tc_logger
def test_clear_connections(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out"))
self.assertTrue(attr.ClearConnections())
connections = attr.GetConnections()
self.assertEqual(len(connections), 0)
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.ClearConnections())
@tc_logger
def test_set_connections(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out"))
new_connections = [Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side.outputs:out")]
self.assertTrue(attr.SetConnections(new_connections))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side.outputs:out"))
too_many_connections = [Sdf.Path("/Foo"), Sdf.Path("/Bar")]
# do nothing for now, this isnt supported
self.assertFalse(attr.SetConnections(too_many_connections))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
# same as previous connection
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side.outputs:out"))
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.SetConnections(new_connections))
| 21,466 | Python | 34.897993 | 110 | 0.642178 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_assetpath.py | __copyright__ = "Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestSdfAssetPath(TestClass):
@tc_logger
def test_ctor(self):
from usdrt import Sdf
emptypath = Sdf.AssetPath()
self.assertEqual(emptypath.path, "")
self.assertEqual(emptypath.resolvedPath, "")
asset_only = Sdf.AssetPath("hello")
self.assertEqual(asset_only.path, "hello")
self.assertEqual(asset_only.resolvedPath, "")
asset_and_resolved = Sdf.AssetPath("hello", "hello.txt")
self.assertEqual(asset_and_resolved.path, "hello")
self.assertEqual(asset_and_resolved.resolvedPath, "hello.txt")
@tc_logger
def test_get_asset(self):
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath("/Cornell_Box/Root/Looks/Green1SG/Green_Side")
self.assertTrue(prim)
attr = prim.GetAttribute("info:mdl:sourceAsset")
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
val = attr.Get()
self.assertEqual(val.path, "./Green_Side.mdl")
self.assertTrue(os.path.normpath(val.resolvedPath).endswith(os.path.normpath("data/usd/tests/Green_Side.mdl")))
@tc_logger
def test_get_assetlist(self):
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_assetlist.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/World"))
self.assertTrue(prim)
attr = prim.GetAttribute("test:assetlist")
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
val = attr.Get()
self.assertEqual(len(val), 3)
unresolved = ["./asset.txt", "./asset_other.txt", "./existing_1042.txt"]
resolved_ends = [
os.path.normpath(i)
for i in ["data/usd/tests/asset.txt", "data/usd/tests/asset_other.txt", "data/usd/tests/existing_1042.txt"]
]
for i in range(3):
self.assertEqual(val[i].path, unresolved[i])
self.assertTrue(os.path.normpath(val[i].resolvedPath).endswith(resolved_ends[i]))
@tc_logger
def test_set_asset(self):
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath("/Cornell_Box/Root/Looks/Green1SG/Green_Side")
self.assertTrue(prim)
attr = prim.GetAttribute("info:mdl:sourceAsset")
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
newval = Sdf.AssetPath("hello", "hello.txt")
self.assertTrue(attr.Set(newval))
val = attr.Get()
self.assertEqual(val.path, "hello")
self.assertEqual(val.resolvedPath, "hello.txt")
@tc_logger
def test_set_assetlist(self):
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_assetlist.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/World"))
self.assertTrue(prim)
attr = prim.GetAttribute("test:assetlist")
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
newval = Vt.AssetArray(4)
for i in range(4):
newval[i] = Sdf.AssetPath(f"hello{i}", f"hello{i}.txt")
attr.Set(newval)
# Freeing the original array must be fine
del newval
val = attr.Get()
self.assertEqual(len(val), 4)
for i in range(4):
self.assertEqual(val[i].path, f"hello{i}")
self.assertEqual(val[i].resolvedPath, f"hello{i}.txt")
| 4,750 | Python | 28.509317 | 119 | 0.638526 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_cube.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdGeomCube(TestClass):
@tc_logger
def test_get_attribute(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cube.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cube/Geom/cube"))
self.assertTrue(prim)
cube = UsdGeom.Cube(prim)
self.assertTrue(cube)
# create attribute using prim api
attr = prim.CreateAttribute(UsdGeom.Tokens.size, Sdf.ValueTypeNames.Double, False)
self.assertTrue(attr)
# verify get attribute using schema api
cubeAttr = cube.GetSizeAttr()
self.assertTrue(cubeAttr)
self.assertTrue(cubeAttr.GetName() == "size")
val = cubeAttr.Get()
assert val == 25
@tc_logger
def test_create_attribute(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/Cube/Geom/cube"), "Cube")
self.assertFalse(prim.HasAttribute("size"))
# create attribute using schema api
cube = UsdGeom.Cube(prim)
self.assertTrue(cube)
attr = cube.CreateSizeAttr()
# verify using prim api
self.assertTrue(attr)
self.assertTrue(prim.HasAttribute(UsdGeom.Tokens.size))
self.assertTrue(attr.GetName() == "size")
@tc_logger
def test_boolean_operator(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cube.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath("/Cube/Geom/cube")
self.assertTrue(prim)
# is this a valid schema object?
self.assertTrue(UsdGeom.Cube(prim))
self.assertTrue(prim)
self.assertFalse(UsdGeom.Cone(prim))
self.assertTrue(prim)
# verify we have an api applied
self.assertTrue(prim.HasAPI("MotionAPI"))
# is this a valid api applied in fabric?
self.assertTrue(UsdGeom.MotionAPI(prim))
self.assertFalse(UsdGeom.VisibilityAPI(prim))
@tc_logger
def test_define(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = UsdGeom.Cube.Define(stage, Sdf.Path("/Cube/Geom/cube"))
self.assertTrue(prim)
| 3,504 | Python | 27.266129 | 90 | 0.658961 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_schema_base.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestSchemaBase(TestClass):
@tc_logger
def test_invalid_schema_base(self):
from usdrt import Sdf, Usd
sb = Usd.SchemaBase()
# Conversion to bool should return False.
self.assertFalse(sb)
# It should still be safe to get the prim, but the prim will be invalid.
p = sb.GetPrim()
self.assertFalse(p.IsValid())
# It should still be safe to get the path, but the path will be empty.
self.assertEqual(sb.GetPrimPath(), Sdf.Path(""))
# Try creating a CollectionAPI from it, and make sure the result is
# a suitably invalid CollactionAPI object.
coll = Usd.CollectionAPI(sb, "newcollection")
self.assertFalse(coll)
# revisit
# with self.assertRaises(RuntimeError):
# coll.CreateExpansionRuleAttr()
class TestImports(TestClass):
@tc_logger
def test_usd_schema_imports(self):
try:
from usdrt import Usd
except ImportError:
self.fail("from usdrt import Usd failed")
try:
from usdrt import UsdGeom
except ImportError:
self.fail("from usdrt import UsdGeom failed")
try:
from usdrt import UsdLux
except ImportError:
self.fail("from usdrt import UsdLux failed")
try:
from usdrt import UsdMedia
except ImportError:
self.fail("from usdrt import UsdMedia failed")
try:
from usdrt import UsdRender
except ImportError:
self.fail("from usdrt import UsdRender failed")
try:
from usdrt import UsdShade
except ImportError:
self.fail("from usdrt import UsdShade failed")
try:
from usdrt import UsdSkel
except ImportError:
self.fail("from usdrt import UsdSkel failed")
try:
from usdrt import UsdUI
except ImportError:
self.fail("from usdrt import UsdUI failed")
try:
from usdrt import UsdVol
except ImportError:
self.fail("from usdrt import UsdVol failed")
# Nvidia Schemas
try:
from usdrt import UsdPhysics
except ImportError:
self.fail("from usdrt import UsdPhysics failed")
try:
from usdrt import PhysxSchema
except ImportError:
self.fail("from usdrt import PhysxSchema failed")
try:
from usdrt import ForceFieldSchema
except ImportError:
self.fail("from usdrt import ForceFieldSchema failed")
try:
from usdrt import DestructionSchema
except ImportError:
self.fail("from usdrt import DestructionSchema failed")
| 3,879 | Python | 27.740741 | 80 | 0.633668 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_stage.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import random
import sys
import tempfile
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
def get_tmp_usda_path(outdir):
timestr = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
randstr = random.randint(0, 32767)
return os.path.join(outdir, f"{timestr}_{randstr}.usda")
class TestUsdStage(TestClass):
@tc_logger
def test_open(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
@tc_logger
def test_create_new(self):
from usdrt import Sdf, Usd
with tempfile.TemporaryDirectory() as tempdir:
stage = Usd.Stage.CreateNew(get_tmp_usda_path(tempdir))
self.assertTrue(stage)
@tc_logger
def test_attach(self):
import pxr
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
layer = pxr.Sdf.Layer.FindOrOpen(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage = cache.FindOneMatching(layer)
stage_id = cache.GetId(usd_stage).ToLongInt()
attached_stage = Usd.Stage.Attach(stage_id)
self.assertTrue(attached_stage)
# verify attached stage can access stage in progress
prim = attached_stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
# verify destruction of attached stage does not destroy stage in progress
del attached_stage
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
cache.Clear()
@tc_logger
def test_attach_no_swh(self):
import pxr
from usdrt import Sdf, Usd
# Note - no SWH created here
stage = pxr.Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
id = cache.Insert(stage)
stage_id = id.ToLongInt()
# This creates the SWH
self.assertFalse(Usd.Stage.SimStageWithHistoryExists(stage_id))
attached_stage = Usd.Stage.Attach(stage_id)
self.assertTrue(attached_stage)
self.assertTrue(Usd.Stage.SimStageWithHistoryExists(stage_id))
# verify attached stage can access stage in progress
prim = attached_stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
# verify that assumed ownership cleans up SWH on destruction
self.assertTrue(Usd.Stage.SimStageWithHistoryExists(stage_id))
# deprecated API support for 104
self.assertTrue(Usd.Stage.StageWithHistoryExists(stage_id))
del attached_stage
self.assertFalse(Usd.Stage.SimStageWithHistoryExists(stage_id))
# deprecated API support for 104
self.assertFalse(Usd.Stage.StageWithHistoryExists(stage_id))
cache.Clear()
@tc_logger
def test_invalid_swh_id(self):
import pxr
from usdrt import Sdf, Usd
# OM-85698 can pass invalid ID to StageWithHistoryExists
self.assertFalse(Usd.Stage.SimStageWithHistoryExists(-1))
self.assertFalse(Usd.Stage.StageWithHistoryExists(-1))
@tc_logger
def test_get_sip_id(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
id = stage.GetStageReaderWriterId()
self.assertNotEqual(id.id, 0)
# deprecated API support for 104
id2 = stage.GetStageInProgressId()
self.assertNotEqual(id2.id, 0)
self.assertEqual(id.id, id2.id)
@tc_logger
def test_get_prim_at_path(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
@tc_logger
def test_get_prim_at_path_invalid(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
@tc_logger
def test_get_prim_at_path_only_in_fabric(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
defined = stage.DefinePrim("/Test", "Cube")
self.assertTrue(defined)
got = stage.GetPrimAtPath("/Test")
self.assertTrue(got)
self.assertEqual(got.GetName(), "Test")
@tc_logger
def test_get_default_prim(self):
from usdrt import Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetDefaultPrim()
self.assertTrue(prim)
self.assertTrue(prim.GetName() == "Cornell_Box")
@tc_logger
def test_get_pseudo_root(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPseudoRoot()
self.assertTrue(prim)
self.assertTrue(prim.GetPath() == Sdf.Path("/"))
@tc_logger
def test_define_prim(self):
from usdrt import Sdf, Usd
with tempfile.TemporaryDirectory() as tempdir:
stage = Usd.Stage.CreateNew(get_tmp_usda_path(tempdir))
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/Test"), "Mesh")
self.assertTrue(prim)
self.assertEqual(prim.GetName(), "Test")
self.assertEqual(prim.GetTypeName(), "Mesh")
prim_notype = stage.DefinePrim(Sdf.Path("/Test2"))
self.assertTrue(prim_notype)
self.assertEqual(prim_notype.GetName(), "Test2")
self.assertEqual(prim_notype.GetTypeName(), "")
@tc_logger
def test_define_prim_with_complete_type(self):
from usdrt import Sdf, Usd
# OM-90066 - use either alias or complete type name to define prim
with tempfile.TemporaryDirectory() as tempdir:
stage = Usd.Stage.CreateNew(get_tmp_usda_path(tempdir))
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/Test"), "Mesh")
self.assertTrue(prim)
self.assertEqual(prim.GetName(), "Test")
self.assertEqual(prim.GetTypeName(), "Mesh")
prim = stage.DefinePrim(Sdf.Path("/Test2"), "UsdGeomMesh")
self.assertTrue(prim)
self.assertEqual(prim.GetTypeName(), "Mesh")
result = stage.GetPrimsWithTypeName("Xformable")
self.assertEqual(len(result), 2)
self.assertTrue(Sdf.Path("/Test") in result)
self.assertTrue(Sdf.Path("/Test2") in result)
@tc_logger
def test_get_attribute_at_path(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back.points"))
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
self.assertTrue(attr.GetName() == UsdGeom.Tokens.points)
@tc_logger
def test_get_attribute_at_path_invalid(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Invalid.points"))
self.assertFalse(attr)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(attr)
@tc_logger
def test_get_relationship_at_path(self):
from usdrt import Sdf, Usd, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
self.assertTrue(rel.HasAuthoredTargets())
self.assertEqual(rel.GetName(), UsdShade.Tokens.materialBinding)
@tc_logger
def test_get_relationship_at_path_invalid(self):
from usdrt import Sdf, Usd, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(Sdf.Path("/Invalid.material:binding"))
self.assertFalse(rel)
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
@tc_logger
def test_traverse(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
prim_range = stage.Traverse()
self.assertTrue(prim_range)
count = 0
for this_prim in prim_range:
count += 1
prim = this_prim
self.assertTrue(count == 40)
self.assertEqual(prim.GetPath(), Sdf.Path("/RectLight"))
@tc_logger
def test_write_layer(self):
"""
Note that in this implementation, WriteToLayer has the same limitations
as Fabric's exportUsd. New prims are not typed, empty prims may be
defined as overs, etc...
"""
import pxr
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
world = stage.DefinePrim(Sdf.Path("/World"), "Xform")
triangle = stage.DefinePrim(Sdf.Path("/World/Triangle"), "Mesh")
points = triangle.CreateAttribute(UsdGeom.Tokens.points, Sdf.ValueTypeNames.Point3fArray, False)
faceVertexCounts = triangle.CreateAttribute(UsdGeom.Tokens.faceVertexCounts, Sdf.ValueTypeNames.IntArray, False)
faceVertexIndices = triangle.CreateAttribute(
UsdGeom.Tokens.faceVertexIndices, Sdf.ValueTypeNames.IntArray, False
)
points.Set(Vt.Vec3fArray([Gf.Vec3f(1, 0, 0), Gf.Vec3f(0, 1, 0), Gf.Vec3f(-1, 0, 0)]))
faceVertexCounts.Set(Vt.IntArray([3]))
faceVertexIndices.Set(Vt.IntArray([0, 1, 2]))
with tempfile.TemporaryDirectory() as tempdir:
test_file = get_tmp_usda_path(tempdir)
stage.WriteToLayer(test_file)
# Verfiy that data was stored to the new layer
test_stage = pxr.Usd.Stage.Open(test_file)
attr = test_stage.GetAttributeAtPath(pxr.Sdf.Path("/World/Triangle.points"))
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
self.assertEqual(len(attr.Get()), 3)
prim = test_stage.GetPrimAtPath(pxr.Sdf.Path("/World/Triangle"))
self.assertEqual(prim.GetTypeName(), "Mesh")
@tc_logger
def test_write_stage(self):
"""
Note that in this implementation, WriteToStage has the same limitations
as Fabric's cacheToUsd. Most importantly, new prims defined in
Fabric are not written out to the USD Stage
"""
import pxr
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
layer = pxr.Sdf.Layer.FindOrOpen(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage = cache.FindOneMatching(layer)
stage_id = cache.GetId(usd_stage).ToLongInt()
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
# Change doubleSided to False in Fabric
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr)
result = attr.Set(False)
self.assertTrue(result)
attr = prim.GetAttribute(UsdGeom.Tokens.normals)
self.assertTrue(attr)
result = attr.Get()
self.assertEquals(len(result), 4)
for i in range(4):
self.assertEquals(result[i], Gf.Vec3f(0, 0, -1))
# Change normals to (1, 0, 0) in Fabric
self.assertTrue(result.IsFabricData())
for i in range(4):
result[i] = Gf.Vec3f(1, 0, 0)
stage.WriteToStage()
usd_prim = usd_stage.GetPrimAtPath(pxr.Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
# Verify doubleSided is now false on USD stage
usd_attr = usd_prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertFalse(usd_attr.Get())
# Verify normals are now (1, 0, 0) on USD stage
usd_attr = usd_prim.GetAttribute(UsdGeom.Tokens.normals)
new_normals = usd_attr.Get()
self.assertEquals(len(new_normals), 4)
for i in range(4):
self.assertEquals(new_normals[i], pxr.Gf.Vec3f(1, 0, 0))
# Clear stage cache, since we modified the USD stage
cache.Clear()
@tc_logger
def test_set_attribute_value(self):
from usdrt import Gf, Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
newNormals = Vt.Vec3fArray([Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0)])
attrPath = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back.normals")
result = stage.SetAttributeValue(attrPath, newNormals)
self.assertTrue(result)
attr = stage.GetAttributeAtPath(attrPath)
self.assertTrue(attr)
value = attr.Get()
for i in range(4):
self.assertEquals(value[i], Gf.Vec3f(1, 0, 0))
@tc_logger
def test_set_attribute_value_invalid_prim(self):
from usdrt import Gf, Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
newNormals = Vt.Vec3fArray([Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0)])
attrPath = Sdf.Path("/Invalid.normals")
result = stage.SetAttributeValue(attrPath, newNormals)
self.assertFalse(result)
@tc_logger
def test_has_prim_at_path(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# No prims populated into Fabric yet
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
# Prim is now in Fabric
self.assertTrue(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
# OM-87225
# prim not in fabric
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cube_5")))
# do a stage query, this will tag everything with metadata
paths = stage.GetPrimsWithTypeName("Mesh")
# prim not in fabric when we ignore tags by default
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cube_5")))
# prim in fabric if we include tags in the query
self.assertTrue(stage.HasPrimAtPath(Sdf.Path("/Cube_5"), excludeTags=False))
@tc_logger
def test_remove_prim(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# No prims populated into Fabric yet
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
# Prim is now in Fabric
self.assertTrue(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
self.assertTrue(stage.RemovePrim(Sdf.Path("/Cornell_Box")))
# Prim removed from Fabric by RemovePrim
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
# Remove non-existant prim does not cause crash, but returns False
self.assertFalse(stage.RemovePrim(Sdf.Path("/Cornell_Box")))
@tc_logger
def test_remove_prim_from_usd(self):
import pxr
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
layer = pxr.Sdf.Layer.FindOrOpen(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage = cache.FindOneMatching(layer)
stage_id = cache.GetId(usd_stage).ToLongInt()
path = "/DistantLight/BillboardComponent_0"
# Populate into Fabric
prim = stage.GetPrimAtPath(Sdf.Path(path))
# Remove from USD stage
usd_stage.RemovePrim(path)
# The prim is still in Fabric
self.assertTrue(stage.HasPrimAtPath(Sdf.Path(path)))
expected_attrs = [UsdGeom.Tokens.visibility, UsdGeom.Tokens.xformOpOrder, "xformOp:transform"]
for attr in prim.GetAttributes():
self.assertTrue(attr.GetName() in expected_attrs)
# Removing prim from Fabric is okay
self.assertTrue(stage.RemovePrim(Sdf.Path(path)))
self.assertFalse(stage.HasPrimAtPath(Sdf.Path(path)))
cache.Clear()
@tc_logger
def test_repr_representation(self):
import pxr
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
layer = pxr.Sdf.Layer.FindOrOpen(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage = cache.FindOneMatching(layer)
stage_id = cache.GetId(usd_stage).ToLongInt()
expected = "Stage(<ID: " + str(stage_id) + ">)"
self.assertEquals(repr(stage), expected)
@tc_logger
def test_layer_rewrite(self):
# OM-70883
import pxr
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
world = stage.DefinePrim(Sdf.Path("/World"), "Xform")
triangle = stage.DefinePrim(Sdf.Path("/World/Triangle"), "Mesh")
points = triangle.CreateAttribute(UsdGeom.Tokens.points, Sdf.ValueTypeNames.Point3fArray, False)
faceVertexCounts = triangle.CreateAttribute(UsdGeom.Tokens.faceVertexCounts, Sdf.ValueTypeNames.IntArray, False)
faceVertexIndices = triangle.CreateAttribute(
UsdGeom.Tokens.faceVertexIndices, Sdf.ValueTypeNames.IntArray, False
)
points.Set(Vt.Vec3fArray([Gf.Vec3f(1, 0, 0), Gf.Vec3f(0, 1, 0), Gf.Vec3f(-1, 0, 0)]))
faceVertexCounts.Set(Vt.IntArray([3]))
faceVertexIndices.Set(Vt.IntArray([0, 1, 2]))
with tempfile.TemporaryDirectory() as tempdir:
test_file = get_tmp_usda_path(tempdir)
stage.WriteToLayer(test_file)
# In OM-70883, multiple WriteToLayer on the same file causes a crash
stage.WriteToLayer(test_file)
# Verfiy that data was stored to the new layer
test_stage = pxr.Usd.Stage.Open(test_file)
attr = test_stage.GetAttributeAtPath(pxr.Sdf.Path("/World/Triangle.points"))
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
self.assertEqual(len(attr.Get()), 3)
prim = test_stage.GetPrimAtPath(pxr.Sdf.Path("/World/Triangle"))
self.assertEqual(prim.GetTypeName(), "Mesh")
@tc_logger
def test_get_prims_with_type_name(self):
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
paths = stage.GetPrimsWithTypeName("Mesh")
self.assertEqual(len(paths), 8)
paths = stage.GetPrimsWithTypeName("Shader")
self.assertEqual(len(paths), 5)
paths = stage.GetPrimsWithTypeName("Invalid")
self.assertEqual(len(paths), 0)
paths = stage.GetPrimsWithTypeName("UsdGeomBoundable")
aliasPaths = stage.GetPrimsWithTypeName("Boundable")
self.assertEqual(len(paths), len(aliasPaths))
@tc_logger
def test_get_prims_with_applied_api_name(self):
# Begin example query by API
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
paths = stage.GetPrimsWithAppliedAPIName("ShapingAPI")
self.assertEqual(len(paths), 2)
paths = stage.GetPrimsWithAppliedAPIName("CollectionAPI:lightLink")
self.assertEqual(len(paths), 5)
# End example query by API
paths = stage.GetPrimsWithAppliedAPIName("Invalid:test")
self.assertEqual(len(paths), 0)
@tc_logger
def test_get_prims_with_type_and_applied_api_name(self):
# Begin example query mixed
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
paths = stage.GetPrimsWithTypeAndAppliedAPIName("Mesh", ["CollectionAPI:test"])
self.assertEqual(len(paths), 1)
# End example query mixed
paths = stage.GetPrimsWithTypeAndAppliedAPIName("Invalid", ["Invalid:test"])
self.assertEqual(len(paths), 0)
@tc_logger
def test_get_stage_extent(self):
# Begin example stage extent
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
bound = stage.GetStageExtent()
self.assertTrue(Gf.IsClose(bound.GetMin(), Gf.Vec3d(-333.8142, -249.9100, -5.444), 0.01))
self.assertTrue(Gf.IsClose(bound.GetMax(), Gf.Vec3d(247.1132, 249.9178, 500.0), 0.01))
# End example stage extent
@tc_logger
def test_get_prims_with_type_and_scenegraph_instancing(self):
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/xform_component_hierarchy_instances.usda")
self.assertTrue(stage)
# There are 2 prototype proxy meshes on the stage
paths = stage.GetPrimsWithTypeName("Mesh")
self.assertEqual(len(paths), 2)
paths = stage.GetPrimsWithTypeName("Invalid")
self.assertEqual(len(paths), 0)
@tc_logger
def test_get_prims_with_type_and_unknown_schema(self):
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/TestConversionOnLoad.usda")
self.assertTrue(stage)
# This is an old OG schema that no longer exists
paths = stage.GetPrimsWithTypeName("ComputeGraphSettings")
self.assertEqual(len(paths), 1)
| 23,789 | Python | 32.985714 | 120 | 0.638068 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_schema_registry.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestSchemaRegistry(TestClass):
@tc_logger
def test_IsA(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(bool(stage))
prim = stage.DefinePrim(Sdf.Path("/cube"), "UsdGeomCube")
schemaRegistry = Usd.SchemaRegistry.GetInstance()
self.assertTrue(bool(schemaRegistry))
self.assertTrue(prim.IsA("UsdGeomCube"))
self.assertTrue(prim.IsA("Cube"))
self.assertTrue(prim.IsA(Usd.Typed))
self.assertTrue(prim.IsA(UsdGeom.Cube))
self.assertTrue(prim.IsA(UsdGeom.Xformable))
self.assertTrue(schemaRegistry.IsA(prim.GetTypeName(), Usd.Typed))
self.assertTrue(schemaRegistry.IsA(prim.GetTypeName(), UsdGeom.Cube))
self.assertTrue(schemaRegistry.IsA(UsdGeom.Cube, "UsdTyped"))
self.assertTrue(schemaRegistry.IsA(UsdGeom.Cube, Usd.Typed))
self.assertTrue(schemaRegistry.IsA(prim.GetTypeName(), "UsdTyped"))
self.assertTrue(schemaRegistry.IsA(prim.GetTypeName(), "UsdGeomCube"))
self.assertFalse(schemaRegistry.IsA(prim.GetTypeName(), "UsdGeomCone"))
self.assertFalse(schemaRegistry.IsA(prim.GetTypeName(), "Invalid"))
@tc_logger
def test_IsConcrete(self):
from usdrt import Sdf, Usd
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsConcrete("UsdModelAPI"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsConcrete("invalid"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsConcrete("UsdGeomCube"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsConcrete("Cube"))
@tc_logger
def test_IsAppliedAPISchema(self):
from usdrt import Sdf, Usd
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsAppliedAPISchema("UsdGeomCube"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsAppliedAPISchema("UsdGeomModelAPI"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsAppliedAPISchema("invalid"))
@tc_logger
def test_IsMultipleApplyAPISchema(self):
from usdrt import Sdf, Usd
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsMultipleApplyAPISchema("UsdGeomCube"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsMultipleApplyAPISchema("UsdCollectionAPI"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsMultipleApplyAPISchema("CollectionAPI"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsMultipleApplyAPISchema("invalid"))
@tc_logger
def test_IsTyped(self):
from usdrt import Sdf, Usd
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsTyped("UsdGeomCube"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsTyped("Cube"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsTyped("UsdModelAPI"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsTyped("invalid"))
@tc_logger
def test_GetSchemaTypeName(self):
from usdrt import Sdf, Usd, UsdGeom
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetSchemaTypeName(UsdGeom.Cube), "UsdGeomCube")
@tc_logger
def test_GetAliasFromName(self):
from usdrt import Sdf, Usd, UsdGeom
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetAliasFromName("Cube"), "Cube")
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetAliasFromName("UsdGeomCube"), "Cube")
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetAliasFromName(""), "")
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetAliasFromName("invalid"), "invalid")
| 4,667 | Python | 36.951219 | 105 | 0.716092 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/UsdUI/_UsdUI.pyi | from __future__ import annotations
import usdrt.UsdUI._UsdUI
import typing
import usdrt.Sdf._Sdf
import usdrt.Usd._Usd
__all__ = [
"Backdrop",
"NodeGraphNodeAPI",
"SceneGraphPrimAPI",
"Tokens"
]
class Backdrop(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateDescriptionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Backdrop: ...
def GetDescriptionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class NodeGraphNodeAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDisplayColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateExpansionStateAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateIconAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStackingOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDisplayColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExpansionStateAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetIconAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetStackingOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class SceneGraphPrimAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDisplayGroupAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDisplayNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDisplayGroupAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDisplayNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
closed = 'closed'
minimized = 'minimized'
open = 'open'
uiDescription = 'ui:description'
uiDisplayGroup = 'ui:displayGroup'
uiDisplayName = 'ui:displayName'
uiNodegraphNodeDisplayColor = 'ui:nodegraph:node:displayColor'
uiNodegraphNodeExpansionState = 'ui:nodegraph:node:expansionState'
uiNodegraphNodeIcon = 'ui:nodegraph:node:icon'
uiNodegraphNodePos = 'ui:nodegraph:node:pos'
uiNodegraphNodeSize = 'ui:nodegraph:node:size'
uiNodegraphNodeStackingOrder = 'ui:nodegraph:node:stackingOrder'
pass
| 3,245 | unknown | 40.088607 | 87 | 0.65886 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/UsdPhysics/_UsdPhysics.pyi | from __future__ import annotations
import usdrt.UsdPhysics._UsdPhysics
import typing
import usdrt.Sdf._Sdf
import usdrt.Usd._Usd
import usdrt.UsdGeom._UsdGeom
__all__ = [
"ArticulationRootAPI",
"CollisionAPI",
"CollisionGroup",
"DistanceJoint",
"DriveAPI",
"FilteredPairsAPI",
"FixedJoint",
"Joint",
"LimitAPI",
"MassAPI",
"MaterialAPI",
"MeshCollisionAPI",
"PrismaticJoint",
"RevoluteJoint",
"RigidBodyAPI",
"Scene",
"SphericalJoint",
"Tokens"
]
class ArticulationRootAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class CollisionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCollisionEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetCollisionEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class CollisionGroup(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateFilteredGroupsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateInvertFilteredGroupsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMergeGroupNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> CollisionGroup: ...
def GetFilteredGroupsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetInvertFilteredGroupsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMergeGroupNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class DistanceJoint(Joint, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateMaxDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> DistanceJoint: ...
def GetMaxDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class DriveAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxForceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTargetPositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTargetVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxForceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTargetPositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTargetVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class FilteredPairsAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateFilteredPairsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetFilteredPairsRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class FixedJoint(Joint, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> FixedJoint: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Joint(usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateBody0Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateBody1Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateBreakForceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateBreakTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollisionEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateExcludeFromArticulationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateJointEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLocalPos0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLocalPos1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLocalRot0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLocalRot1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Joint: ...
def GetBody0Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetBody1Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetBreakForceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBreakTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExcludeFromArticulationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetJointEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalPos0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalPos1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalRot0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalRot1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class LimitAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateHighAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLowAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHighAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLowAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class MassAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCenterOfMassAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDiagonalInertiaAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMassAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePrincipalAxesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCenterOfMassAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDiagonalInertiaAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMassAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPrincipalAxesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class MaterialAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDynamicFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestitutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStaticFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDynamicFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestitutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStaticFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class MeshCollisionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateApproximationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetApproximationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PrismaticJoint(Joint, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLowerLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpperLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PrismaticJoint: ...
def GetAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLowerLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetUpperLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class RevoluteJoint(Joint, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLowerLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpperLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> RevoluteJoint: ...
def GetAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLowerLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetUpperLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class RigidBodyAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAngularVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateKinematicEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRigidBodyEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateStartsAsleepAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAngularVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetKinematicEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRigidBodyEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetStartsAsleepAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Scene(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateGravityDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGravityMagnitudeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Scene: ...
def GetGravityDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGravityMagnitudeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class SphericalJoint(Joint, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateConeAngle0LimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateConeAngle1LimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> SphericalJoint: ...
def GetAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetConeAngle0LimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetConeAngle1LimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
acceleration = 'acceleration'
angular = 'angular'
boundingCube = 'boundingCube'
boundingSphere = 'boundingSphere'
colliders = 'colliders'
convexDecomposition = 'convexDecomposition'
convexHull = 'convexHull'
distance = 'distance'
drive = 'drive'
force = 'force'
kilogramsPerUnit = 'kilogramsPerUnit'
limit = 'limit'
linear = 'linear'
meshSimplification = 'meshSimplification'
none = 'none'
physicsAngularVelocity = 'physics:angularVelocity'
physicsApproximation = 'physics:approximation'
physicsAxis = 'physics:axis'
physicsBody0 = 'physics:body0'
physicsBody1 = 'physics:body1'
physicsBreakForce = 'physics:breakForce'
physicsBreakTorque = 'physics:breakTorque'
physicsCenterOfMass = 'physics:centerOfMass'
physicsCollisionEnabled = 'physics:collisionEnabled'
physicsConeAngle0Limit = 'physics:coneAngle0Limit'
physicsConeAngle1Limit = 'physics:coneAngle1Limit'
physicsDamping = 'physics:damping'
physicsDensity = 'physics:density'
physicsDiagonalInertia = 'physics:diagonalInertia'
physicsDynamicFriction = 'physics:dynamicFriction'
physicsExcludeFromArticulation = 'physics:excludeFromArticulation'
physicsFilteredGroups = 'physics:filteredGroups'
physicsFilteredPairs = 'physics:filteredPairs'
physicsGravityDirection = 'physics:gravityDirection'
physicsGravityMagnitude = 'physics:gravityMagnitude'
physicsHigh = 'physics:high'
physicsInvertFilteredGroups = 'physics:invertFilteredGroups'
physicsJointEnabled = 'physics:jointEnabled'
physicsKinematicEnabled = 'physics:kinematicEnabled'
physicsLocalPos0 = 'physics:localPos0'
physicsLocalPos1 = 'physics:localPos1'
physicsLocalRot0 = 'physics:localRot0'
physicsLocalRot1 = 'physics:localRot1'
physicsLow = 'physics:low'
physicsLowerLimit = 'physics:lowerLimit'
physicsMass = 'physics:mass'
physicsMaxDistance = 'physics:maxDistance'
physicsMaxForce = 'physics:maxForce'
physicsMergeGroup = 'physics:mergeGroup'
physicsMinDistance = 'physics:minDistance'
physicsPrincipalAxes = 'physics:principalAxes'
physicsRestitution = 'physics:restitution'
physicsRigidBodyEnabled = 'physics:rigidBodyEnabled'
physicsSimulationOwner = 'physics:simulationOwner'
physicsStartsAsleep = 'physics:startsAsleep'
physicsStaticFriction = 'physics:staticFriction'
physicsStiffness = 'physics:stiffness'
physicsTargetPosition = 'physics:targetPosition'
physicsTargetVelocity = 'physics:targetVelocity'
physicsType = 'physics:type'
physicsUpperLimit = 'physics:upperLimit'
physicsVelocity = 'physics:velocity'
rotX = 'rotX'
rotY = 'rotY'
rotZ = 'rotZ'
transX = 'transX'
transY = 'transY'
transZ = 'transZ'
x = 'X'
y = 'Y'
z = 'Z'
pass
| 18,503 | unknown | 45.609572 | 111 | 0.662271 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/PhysxSchema/_PhysxSchema.pyi | from __future__ import annotations
import usdrt.PhysxSchema._PhysxSchema
import typing
import usdrt.Sdf._Sdf
import usdrt.Usd._Usd
import usdrt.UsdGeom._UsdGeom
import usdrt.UsdPhysics._UsdPhysics
__all__ = [
"JointStateAPI",
"PhysxArticulationAPI",
"PhysxArticulationForceSensorAPI",
"PhysxAutoAttachmentAPI",
"PhysxAutoParticleClothAPI",
"PhysxCameraAPI",
"PhysxCameraDroneAPI",
"PhysxCameraFollowAPI",
"PhysxCameraFollowLookAPI",
"PhysxCameraFollowVelocityAPI",
"PhysxCharacterControllerAPI",
"PhysxCollisionAPI",
"PhysxContactReportAPI",
"PhysxConvexDecompositionCollisionAPI",
"PhysxConvexHullCollisionAPI",
"PhysxCookedDataAPI",
"PhysxDeformableAPI",
"PhysxDeformableBodyAPI",
"PhysxDeformableBodyMaterialAPI",
"PhysxDeformableSurfaceAPI",
"PhysxDeformableSurfaceMaterialAPI",
"PhysxDiffuseParticlesAPI",
"PhysxForceAPI",
"PhysxHairAPI",
"PhysxHairMaterialAPI",
"PhysxJointAPI",
"PhysxLimitAPI",
"PhysxMaterialAPI",
"PhysxPBDMaterialAPI",
"PhysxParticleAPI",
"PhysxParticleAnisotropyAPI",
"PhysxParticleClothAPI",
"PhysxParticleIsosurfaceAPI",
"PhysxParticleSamplingAPI",
"PhysxParticleSetAPI",
"PhysxParticleSmoothingAPI",
"PhysxParticleSystem",
"PhysxPhysicsAttachment",
"PhysxPhysicsDistanceJointAPI",
"PhysxPhysicsGearJoint",
"PhysxPhysicsInstancer",
"PhysxPhysicsJointInstancer",
"PhysxPhysicsRackAndPinionJoint",
"PhysxRigidBodyAPI",
"PhysxSDFMeshCollisionAPI",
"PhysxSceneAPI",
"PhysxSphereFillCollisionAPI",
"PhysxTendonAttachmentAPI",
"PhysxTendonAttachmentLeafAPI",
"PhysxTendonAttachmentRootAPI",
"PhysxTendonAxisAPI",
"PhysxTendonAxisRootAPI",
"PhysxTriangleMeshCollisionAPI",
"PhysxTriangleMeshSimplificationCollisionAPI",
"PhysxTriggerAPI",
"PhysxTriggerStateAPI",
"PhysxVehicleAPI",
"PhysxVehicleAckermannSteeringAPI",
"PhysxVehicleAutoGearBoxAPI",
"PhysxVehicleBrakesAPI",
"PhysxVehicleClutchAPI",
"PhysxVehicleContextAPI",
"PhysxVehicleControllerAPI",
"PhysxVehicleDriveBasicAPI",
"PhysxVehicleDriveStandardAPI",
"PhysxVehicleEngineAPI",
"PhysxVehicleGearsAPI",
"PhysxVehicleMultiWheelDifferentialAPI",
"PhysxVehicleSteeringAPI",
"PhysxVehicleSuspensionAPI",
"PhysxVehicleSuspensionComplianceAPI",
"PhysxVehicleTankControllerAPI",
"PhysxVehicleTankDifferentialAPI",
"PhysxVehicleTireAPI",
"PhysxVehicleTireFrictionTable",
"PhysxVehicleWheelAPI",
"PhysxVehicleWheelAttachmentAPI",
"PhysxVehicleWheelControllerAPI",
"TetrahedralMesh",
"Tokens"
]
class JointStateAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreatePositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxArticulationAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateArticulationEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnabledSelfCollisionsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSleepThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSolverPositionIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSolverVelocityIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStabilizationThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetArticulationEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnabledSelfCollisionsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSleepThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSolverPositionIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSolverVelocityIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetStabilizationThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxArticulationForceSensorAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateConstraintSolverForcesEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateForceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateForwardDynamicsForcesEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSensorEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWorldFrameEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetConstraintSolverForcesEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetForceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetForwardDynamicsForcesEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSensorEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWorldFrameEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxAutoAttachmentAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCollisionFilteringOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDeformableVertexOverlapOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableCollisionFilteringAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableDeformableFilteringPairsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableDeformableVertexAttachmentsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableRigidSurfaceAttachmentsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRigidSurfaceSamplingDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionFilteringOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDeformableVertexOverlapOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableCollisionFilteringAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableDeformableFilteringPairsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableDeformableVertexAttachmentsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableRigidSurfaceAttachmentsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRigidSurfaceSamplingDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxAutoParticleClothAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDisableMeshWeldingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringBendStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringShearStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringStretchStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDisableMeshWeldingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSpringBendStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringShearStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringStretchStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxCameraAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAlwaysUpdateEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePhysxCameraSubjectRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetAlwaysUpdateEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPhysxCameraSubjectRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxCameraDroneAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateFeedForwardVelocityGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFollowDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFollowHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHorizontalVelocityGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePositionOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRotationFilterTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVelocityFilterTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVerticalVelocityGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFeedForwardVelocityGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFollowDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFollowHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHorizontalVelocityGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPositionOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRotationFilterTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetVelocityFilterTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVerticalVelocityGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxCameraFollowAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCameraPositionTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFollowMaxDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFollowMaxSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFollowMinDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFollowMinSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFollowTurnRateGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLookAheadMaxDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLookAheadMaxSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLookAheadMinDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLookAheadMinSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLookAheadTurnRateGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLookPositionHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLookPositionTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePitchAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePitchAngleTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePositionOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSlowPitchAngleSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSlowSpeedPitchAngleScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVelocityNormalMinSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateYawAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateYawRateTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCameraPositionTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFollowMaxDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFollowMaxSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFollowMinDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFollowMinSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFollowTurnRateGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLookAheadMaxDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLookAheadMaxSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLookAheadMinDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLookAheadMinSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLookAheadTurnRateGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLookPositionHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLookPositionTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPitchAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPitchAngleTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPositionOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSlowPitchAngleSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSlowSpeedPitchAngleScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVelocityNormalMinSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetYawAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetYawRateTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxCameraFollowLookAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDownHillGroundAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDownHillGroundPitchAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFollowReverseDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFollowReverseSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpHillGroundAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpHillGroundPitchAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVelocityBlendTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDownHillGroundAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDownHillGroundPitchAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFollowReverseDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFollowReverseSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetUpHillGroundAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUpHillGroundPitchAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVelocityBlendTimeConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxCameraFollowVelocityAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxCharacterControllerAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateClimbingModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInvisibleWallHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxJumpHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMoveTargetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNonWalkableModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateScaleCoeffAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateSlopeLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStepOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVolumeGrowthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetClimbingModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInvisibleWallHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxJumpHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMoveTargetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNonWalkableModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetScaleCoeffAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetSlopeLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetStepOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUpAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVolumeGrowthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxCollisionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinTorsionalPatchRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTorsionalPatchRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinTorsionalPatchRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTorsionalPatchRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxContactReportAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateReportPairsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetReportPairsRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxConvexDecompositionCollisionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateErrorPercentageAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHullVertexLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxConvexHullsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShrinkWrapAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVoxelResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetErrorPercentageAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHullVertexLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxConvexHullsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetShrinkWrapAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVoxelResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxConvexHullCollisionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateHullVertexLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHullVertexLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxCookedDataAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateBufferAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBufferAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxDeformableAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDeformableEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxDepenetrationVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSelfCollisionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSelfCollisionFilterDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSettlingThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSimulationIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateSimulationVelocitiesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSleepDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSleepThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSolverPositionIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVertexVelocityDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDeformableEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxDepenetrationVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSelfCollisionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSelfCollisionFilterDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSettlingThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSimulationIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetSimulationVelocitiesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSleepDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSleepThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSolverPositionIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVertexVelocityDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxDeformableBodyAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCollisionIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollisionPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollisionRestPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDisableGravityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSimulationPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSimulationRestPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionRestPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDisableGravityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSimulationPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSimulationRestPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxDeformableBodyMaterialAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDampingScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDynamicFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateElasticityDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePoissonsRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateYoungsModulusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDynamicFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetElasticityDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPoissonsRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetYoungsModulusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxDeformableSurfaceAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateBendingStiffnessScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollisionIterationMultiplierAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollisionPairUpdateFrequencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFlatteningEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBendingStiffnessScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionIterationMultiplierAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionPairUpdateFrequencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFlatteningEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxDeformableSurfaceMaterialAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDynamicFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePoissonsRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateYoungsModulusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDynamicFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPoissonsRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetYoungsModulusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxDiffuseParticlesAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAirDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateBubbleDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateBuoyancyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollisionDecayAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDiffuseParticlesEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDivergenceWeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateKineticEnergyWeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLifetimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxDiffuseParticleMultiplierAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePressureWeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUseAccurateVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAirDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBubbleDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBuoyancyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionDecayAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDiffuseParticlesEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDivergenceWeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetKineticEnergyWeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLifetimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxDiffuseParticleMultiplierAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPressureWeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUseAccurateVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateForceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateForceEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWorldFrameEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetForceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetForceEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWorldFrameEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxHairAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateExternalCollisionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGlobalShapeComplianceAtRootAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGlobalShapeComplianceStrandAttenuationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInterHairRepulsionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLocalShapeMatchingComplianceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLocalShapeMatchingGroupOverlapAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLocalShapeMatchingGroupSizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLocalShapeMatchingLinearStretchingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSegmentLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTwosidedAttachmentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVelSmoothingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExternalCollisionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGlobalShapeComplianceAtRootAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGlobalShapeComplianceStrandAttenuationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInterHairRepulsionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalShapeMatchingComplianceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalShapeMatchingGroupOverlapAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalShapeMatchingGroupSizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalShapeMatchingLinearStretchingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSegmentLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTwosidedAttachmentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVelSmoothingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxHairMaterialAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateContactOffsetMultiplierAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCurveBendStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCurveThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDynamicFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateYoungsModulusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetContactOffsetMultiplierAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCurveBendStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCurveThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDynamicFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetYoungsModulusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxJointAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateArmatureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableProjectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateJointFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxJointVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetArmatureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableProjectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetJointFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxJointVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxLimitAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateBounceThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateContactDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestitutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBounceThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetContactDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestitutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxMaterialAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCompliantContactDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCompliantContactStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFrictionCombineModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateImprovePatchFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestitutionCombineModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCompliantContactDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCompliantContactStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFrictionCombineModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetImprovePatchFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestitutionCombineModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxPBDMaterialAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAdhesionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateAdhesionOffsetScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCflCoefficientAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCohesionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGravityScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLiftAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParticleAdhesionScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParticleFrictionScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSurfaceTensionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateViscosityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVorticityConfinementAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAdhesionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAdhesionOffsetScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCflCoefficientAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCohesionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFrictionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGravityScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLiftAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticleAdhesionScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticleFrictionScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSurfaceTensionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetViscosityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVorticityConfinementAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxParticleAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateParticleEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParticleGroupAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParticleSystemRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateSelfCollisionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticleEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticleGroupAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticleSystemRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSelfCollisionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxParticleAnisotropyAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateMaxAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParticleAnisotropyEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticleAnisotropyEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxParticleClothAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreatePressureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSelfCollisionFilterAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringDampingsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringRestLengthsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringStiffnessesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPressureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSelfCollisionFilterAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringDampingsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringRestLengthsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringStiffnessesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxParticleIsosurfaceAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateGridFilteringPassesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGridSmoothingRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGridSpacingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateIsosurfaceEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxSubgridsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxTrianglesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxVerticesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNumMeshNormalSmoothingPassesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNumMeshSmoothingPassesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSurfaceDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGridFilteringPassesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGridSmoothingRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGridSpacingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetIsosurfaceEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxSubgridsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxTrianglesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxVerticesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNumMeshNormalSmoothingPassesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNumMeshSmoothingPassesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSurfaceDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxParticleSamplingAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateMaxSamplesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParticlesRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateSamplingDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVolumeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxSamplesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticlesRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetSamplingDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetVolumeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxParticleSetAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateFluidAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSimulationPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFluidAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSimulationPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxParticleSmoothingAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateParticleSmoothingEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticleSmoothingEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxParticleSystem(usdrt.UsdGeom._UsdGeom.Gprim, usdrt.UsdGeom._UsdGeom.Boundable, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFluidRestOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGlobalSelfCollisionEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxDepenetrationVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxNeighborhoodAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNonParticleCollisionEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParticleContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParticleSystemEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateSolidRestOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSolverPositionIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWindAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PhysxParticleSystem: ...
def GetContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFluidRestOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGlobalSelfCollisionEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxDepenetrationVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxNeighborhoodAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNonParticleCollisionEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticleContactOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParticleSystemEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSimulationOwnerRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetSolidRestOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSolverPositionIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWindAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxPhysicsAttachment(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateActor0Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateActor1Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateAttachmentEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollisionFilterIndices0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollisionFilterIndices1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFilterType0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFilterType1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePoints0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePoints1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PhysxPhysicsAttachment: ...
def GetActor0Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetActor1Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetAttachmentEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionFilterIndices0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionFilterIndices1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFilterType0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFilterType1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPoints0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPoints1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxPhysicsDistanceJointAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateSpringDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSpringDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxPhysicsGearJoint(usdrt.UsdPhysics._UsdPhysics.Joint, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateGearRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHinge0Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateHinge1Rel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PhysxPhysicsGearJoint: ...
def GetGearRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHinge0Rel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetHinge1Rel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxPhysicsJointInstancer(PhysxPhysicsInstancer, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreatePhysicsBody0IndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePhysicsBody0sRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreatePhysicsBody1IndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePhysicsBody1sRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreatePhysicsLocalPos0sAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePhysicsLocalPos1sAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePhysicsLocalRot0sAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePhysicsLocalRot1sAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PhysxPhysicsJointInstancer: ...
def GetPhysicsBody0IndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPhysicsBody0sRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetPhysicsBody1IndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPhysicsBody1sRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetPhysicsLocalPos0sAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPhysicsLocalPos1sAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPhysicsLocalRot0sAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPhysicsLocalRot1sAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxPhysicsInstancer(usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreatePhysicsProtoIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePhysicsPrototypesRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PhysxPhysicsInstancer: ...
def GetPhysicsProtoIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPhysicsPrototypesRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxPhysicsRackAndPinionJoint(usdrt.UsdPhysics._UsdPhysics.Joint, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateHingeRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreatePrismaticRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PhysxPhysicsRackAndPinionJoint: ...
def GetHingeRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetPrismaticRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxRigidBodyAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAngularDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCfmScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateContactSlopCoefficientAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDisableGravityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableGyroscopicForcesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableSpeculativeCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLinearDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLockedPosAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLockedRotAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxAngularVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxContactImpulseAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxDepenetrationVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxLinearVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRetainAccelerationsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSleepThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSolveContactAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSolverPositionIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSolverVelocityIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStabilizationThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAngularDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCfmScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetContactSlopCoefficientAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDisableGravityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableGyroscopicForcesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableSpeculativeCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLinearDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLockedPosAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLockedRotAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxAngularVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxContactImpulseAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxDepenetrationVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxLinearVelocityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRetainAccelerationsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSleepThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSolveContactAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSolverPositionIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSolverVelocityIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetStabilizationThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxSDFMeshCollisionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateSdfBitsPerSubgridPixelAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSdfEnableRemeshingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSdfMarginAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSdfNarrowBandThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSdfResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSdfSubgridResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSdfBitsPerSubgridPixelAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSdfEnableRemeshingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSdfMarginAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSdfNarrowBandThicknessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSdfResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSdfSubgridResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxSceneAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateBounceThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateBroadphaseTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollisionSystemAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableEnhancedDeterminismAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableGPUDynamicsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableSceneQuerySupportAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableStabilizationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFrictionCorrelationDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFrictionOffsetThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFrictionTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuCollisionStackSizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuFoundLostAggregatePairsCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuFoundLostPairsCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuHeapCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuMaxDeformableSurfaceContactsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuMaxHairContactsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuMaxNumPartitionsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuMaxParticleContactsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuMaxRigidContactCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuMaxRigidPatchCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuMaxSoftBodyContactsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuTempBufferCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGpuTotalAggregatePairsCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInvertCollisionGroupFilterAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxBiasCoefficientAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateReportKinematicKinematicPairsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateReportKinematicStaticPairsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSolverTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTimeStepsPerSecondAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpdateTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBounceThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBroadphaseTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollisionSystemAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableCCDAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableEnhancedDeterminismAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableGPUDynamicsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableSceneQuerySupportAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableStabilizationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFrictionCorrelationDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFrictionOffsetThresholdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFrictionTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuCollisionStackSizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuFoundLostAggregatePairsCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuFoundLostPairsCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuHeapCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuMaxDeformableSurfaceContactsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuMaxHairContactsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuMaxNumPartitionsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuMaxParticleContactsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuMaxRigidContactCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuMaxRigidPatchCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuMaxSoftBodyContactsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuTempBufferCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGpuTotalAggregatePairsCapacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInvertCollisionGroupFilterAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxBiasCoefficientAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinIterationCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetReportKinematicKinematicPairsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetReportKinematicStaticPairsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSolverTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTimeStepsPerSecondAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUpdateTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxSphereFillCollisionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateFillModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxSpheresAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSeedCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVoxelResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFillModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxSpheresAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSeedCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVoxelResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxTendonAttachmentAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateGearingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLocalPosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParentAttachmentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParentLinkRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetGearingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalPosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParentAttachmentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParentLinkRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxTendonAttachmentLeafAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateLowerLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpperLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLowerLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetUpperLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxTendonAttachmentRootAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLimitStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTendonEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLimitStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTendonEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxTendonAxisAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateForceCoefficientAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGearingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateJointAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetForceCoefficientAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGearingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetJointAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxTendonAxisRootAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLimitStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLowerLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTendonEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpperLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLimitStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLowerLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTendonEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUpperLimitAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxTriangleMeshCollisionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateWeldToleranceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetWeldToleranceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxTriangleMeshSimplificationCollisionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateSimplificationMetricAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWeldToleranceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSimplificationMetricAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWeldToleranceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxTriggerAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateEnterScriptTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLeaveScriptTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateOnEnterScriptAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateOnLeaveScriptAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnterScriptTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLeaveScriptTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetOnEnterScriptAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetOnLeaveScriptAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxTriggerStateAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateTriggeredCollisionsRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTriggeredCollisionsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDriveRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateHighForwardSpeedSubStepCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLateralStickyTireDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLateralStickyTireThresholdSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLateralStickyTireThresholdTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLongitudinalStickyTireDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLongitudinalStickyTireThresholdSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLongitudinalStickyTireThresholdTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLowForwardSpeedSubStepCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinActiveLongitudinalSlipDenominatorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinLateralSlipDenominatorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinLongitudinalSlipDenominatorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinPassiveLongitudinalSlipDenominatorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSubStepThresholdLongitudinalSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSuspensionLineQueryTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVehicleEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDriveRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetHighForwardSpeedSubStepCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLateralStickyTireDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLateralStickyTireThresholdSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLateralStickyTireThresholdTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLongitudinalStickyTireDampingAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLongitudinalStickyTireThresholdSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLongitudinalStickyTireThresholdTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLowForwardSpeedSubStepCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinActiveLongitudinalSlipDenominatorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinLateralSlipDenominatorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinLongitudinalSlipDenominatorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinPassiveLongitudinalSlipDenominatorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSubStepThresholdLongitudinalSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSuspensionLineQueryTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVehicleEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleAckermannSteeringAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateMaxSteerAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTrackWidthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheel0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheel1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelBaseAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxSteerAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTrackWidthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheel0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheel1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheelBaseAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleAutoGearBoxAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDownRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLatencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDownRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLatencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetUpRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleBrakesAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateMaxBrakeTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTorqueMultipliersAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxBrakeTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTorqueMultipliersAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheelsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleClutchAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleContextAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateForwardAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLongitudinalAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUpdateModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVerticalAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetForwardAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLongitudinalAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetUpAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUpdateModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVerticalAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleControllerAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAcceleratorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateBrake0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateBrake1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateBrakeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHandbrakeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSteerAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSteerLeftAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSteerRightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTargetGearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAcceleratorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBrake0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBrake1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBrakeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHandbrakeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSteerAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSteerLeftAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSteerRightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTargetGearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleDriveBasicAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreatePeakTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPeakTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleDriveStandardAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAutoGearBoxRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateClutchRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateEngineRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateGearsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetAutoGearBoxRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetClutchRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetEngineRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetGearsRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleEngineAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDampingRateFullThrottleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDampingRateZeroThrottleClutchDisengagedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDampingRateZeroThrottleClutchEngagedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateIdleRotationSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxRotationSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMoiAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePeakTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTorqueCurveAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingRateFullThrottleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingRateZeroThrottleClutchDisengagedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingRateZeroThrottleClutchEngagedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetIdleRotationSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxRotationSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMoiAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPeakTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTorqueCurveAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleGearsAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateRatioScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSwitchTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRatioScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSwitchTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleMultiWheelDifferentialAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAverageWheelSpeedRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTorqueRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAverageWheelSpeedRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTorqueRatiosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheelsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleSteeringAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAngleMultipliersAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxSteerAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAngleMultipliersAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxSteerAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetWheelsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleSuspensionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCamberAtMaxCompressionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCamberAtMaxDroopAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCamberAtRestAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxCompressionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxDroopAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringDamperRateAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpringStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSprungMassAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTravelDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCamberAtMaxCompressionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCamberAtMaxDroopAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCamberAtRestAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxCompressionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxDroopAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSpringDamperRateAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpringStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSprungMassAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTravelDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleSuspensionComplianceAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateSuspensionForceAppPointAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTireForceAppPointAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelCamberAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelToeAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSuspensionForceAppPointAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTireForceAppPointAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheelCamberAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheelToeAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleTankControllerAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateThrust0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateThrust1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetThrust0Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetThrust1Attr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleTankDifferentialAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateNumberOfWheelsPerTrackAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateThrustIndexPerTrackAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTrackToWheelIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelIndicesInTrackOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNumberOfWheelsPerTrackAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetThrustIndexPerTrackAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTrackToWheelIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheelIndicesInTrackOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleTireAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCamberStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCamberStiffnessPerUnitGravityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFrictionTableRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateFrictionVsSlipGraphAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLatStiffXAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLatStiffYAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLateralStiffnessGraphAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLongitudinalStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLongitudinalStiffnessPerUnitGravityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRestLoadAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCamberStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCamberStiffnessPerUnitGravityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFrictionTableRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetFrictionVsSlipGraphAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLatStiffXAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLatStiffYAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLateralStiffnessGraphAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLongitudinalStiffnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLongitudinalStiffnessPerUnitGravityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRestLoadAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleTireFrictionTable(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateDefaultFrictionValueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFrictionValuesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGroundMaterialsRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PhysxVehicleTireFrictionTable: ...
def GetDefaultFrictionValueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFrictionValuesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGroundMaterialsRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleWheelAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDampingRateAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMassAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxBrakeTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxHandBrakeTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaxSteerAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMoiAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateToeAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWidthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDampingRateAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMassAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxBrakeTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxHandBrakeTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaxSteerAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMoiAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetToeAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWidthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleWheelAttachmentAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCollisionGroupRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateDrivenAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateIndexAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSuspensionForceAppPointOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSuspensionFrameOrientationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSuspensionFramePositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSuspensionRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateSuspensionTravelDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTireForceAppPointOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTireRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateWheelCenterOfMassOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelFrameOrientationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelFramePositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWheelRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetCollisionGroupRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetDrivenAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetIndexAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSuspensionForceAppPointOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSuspensionFrameOrientationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSuspensionFramePositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSuspensionRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetSuspensionTravelDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTireForceAppPointOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTireRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetWheelCenterOfMassOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheelFrameOrientationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheelFramePositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWheelRel(self) -> usdrt.Usd._Usd.Relationship: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxVehicleWheelControllerAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateBrakeTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDriveTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSteerAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetBrakeTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDriveTorqueAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSteerAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class TetrahedralMesh(usdrt.UsdGeom._UsdGeom.PointBased, usdrt.UsdGeom._UsdGeom.Gprim, usdrt.UsdGeom._UsdGeom.Boundable, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> TetrahedralMesh: ...
def GetIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
acceleration = 'acceleration'
actor0 = 'actor0'
actor1 = 'actor1'
alwaysUpdateEnabled = 'alwaysUpdateEnabled'
asynchronous = 'Asynchronous'
attachmentEnabled = 'attachmentEnabled'
average = 'average'
bitsPerPixel16 = 'BitsPerPixel16'
bitsPerPixel32 = 'BitsPerPixel32'
bitsPerPixel8 = 'BitsPerPixel8'
bounceThreshold = 'bounceThreshold'
brakes0 = 'brakes0'
brakes1 = 'brakes1'
buffer = 'buffer'
clothConstaint = 'clothConstaint'
collisionFilterIndices0 = 'collisionFilterIndices0'
collisionFilterIndices1 = 'collisionFilterIndices1'
constrained = 'constrained'
contactDistance = 'contactDistance'
contactOffset = 'contactOffset'
convexDecomposition = 'convexDecomposition'
convexHull = 'convexHull'
damping = 'damping'
defaultFrictionValue = 'defaultFrictionValue'
disabled = 'Disabled'
easy = 'easy'
enableCCD = 'enableCCD'
filterType0 = 'filterType0'
filterType1 = 'filterType1'
flood = 'flood'
fluidRestOffset = 'fluidRestOffset'
force = 'force'
forceCoefficient = 'forceCoefficient'
frictionValues = 'frictionValues'
gPU = 'GPU'
gearing = 'gearing'
geometry = 'Geometry'
globalSelfCollisionEnabled = 'globalSelfCollisionEnabled'
groundMaterials = 'groundMaterials'
indices = 'indices'
jointAxis = 'jointAxis'
limitStiffness = 'limitStiffness'
localPos = 'localPos'
lowerLimit = 'lowerLimit'
mBP = 'MBP'
max = 'max'
maxBrakeTorque = 'maxBrakeTorque'
maxDepenetrationVelocity = 'maxDepenetrationVelocity'
maxNeighborhood = 'maxNeighborhood'
maxVelocity = 'maxVelocity'
min = 'min'
multiply = 'multiply'
negX = 'negX'
negY = 'negY'
negZ = 'negZ'
nonParticleCollisionEnabled = 'nonParticleCollisionEnabled'
offset = 'offset'
oneDirectional = 'oneDirectional'
pCM = 'PCM'
pGS = 'PGS'
parentAttachment = 'parentAttachment'
parentLink = 'parentLink'
particleContactOffset = 'particleContactOffset'
particleSystemEnabled = 'particleSystemEnabled'
patch = 'patch'
physicsBody0Indices = 'physics:body0Indices'
physicsBody0s = 'physics:body0s'
physicsBody1Indices = 'physics:body1Indices'
physicsBody1s = 'physics:body1s'
physicsGearRatio = 'physics:gearRatio'
physicsHinge = 'physics:hinge'
physicsHinge0 = 'physics:hinge0'
physicsHinge1 = 'physics:hinge1'
physicsLocalPos0s = 'physics:localPos0s'
physicsLocalPos1s = 'physics:localPos1s'
physicsLocalRot0s = 'physics:localRot0s'
physicsLocalRot1s = 'physics:localRot1s'
physicsPosition = 'physics:position'
physicsPrismatic = 'physics:prismatic'
physicsProtoIndices = 'physics:protoIndices'
physicsPrototypes = 'physics:prototypes'
physicsRatio = 'physics:ratio'
physicsVelocity = 'physics:velocity'
physxArticulationArticulationEnabled = 'physxArticulation:articulationEnabled'
physxArticulationEnabledSelfCollisions = 'physxArticulation:enabledSelfCollisions'
physxArticulationForceSensorConstraintSolverForcesEnabled = 'physxArticulationForceSensor:constraintSolverForcesEnabled'
physxArticulationForceSensorForce = 'physxArticulationForceSensor:force'
physxArticulationForceSensorForwardDynamicsForcesEnabled = 'physxArticulationForceSensor:forwardDynamicsForcesEnabled'
physxArticulationForceSensorSensorEnabled = 'physxArticulationForceSensor:sensorEnabled'
physxArticulationForceSensorTorque = 'physxArticulationForceSensor:torque'
physxArticulationForceSensorWorldFrameEnabled = 'physxArticulationForceSensor:worldFrameEnabled'
physxArticulationSleepThreshold = 'physxArticulation:sleepThreshold'
physxArticulationSolverPositionIterationCount = 'physxArticulation:solverPositionIterationCount'
physxArticulationSolverVelocityIterationCount = 'physxArticulation:solverVelocityIterationCount'
physxArticulationStabilizationThreshold = 'physxArticulation:stabilizationThreshold'
physxAutoAttachmentCollisionFilteringOffset = 'physxAutoAttachment:collisionFilteringOffset'
physxAutoAttachmentDeformableVertexOverlapOffset = 'physxAutoAttachment:deformableVertexOverlapOffset'
physxAutoAttachmentEnableCollisionFiltering = 'physxAutoAttachment:enableCollisionFiltering'
physxAutoAttachmentEnableDeformableFilteringPairs = 'physxAutoAttachment:enableDeformableFilteringPairs'
physxAutoAttachmentEnableDeformableVertexAttachments = 'physxAutoAttachment:enableDeformableVertexAttachments'
physxAutoAttachmentEnableRigidSurfaceAttachments = 'physxAutoAttachment:enableRigidSurfaceAttachments'
physxAutoAttachmentRigidSurfaceSamplingDistance = 'physxAutoAttachment:rigidSurfaceSamplingDistance'
physxAutoParticleClothDisableMeshWelding = 'physxAutoParticleCloth:disableMeshWelding'
physxAutoParticleClothSpringBendStiffness = 'physxAutoParticleCloth:springBendStiffness'
physxAutoParticleClothSpringDamping = 'physxAutoParticleCloth:springDamping'
physxAutoParticleClothSpringShearStiffness = 'physxAutoParticleCloth:springShearStiffness'
physxAutoParticleClothSpringStretchStiffness = 'physxAutoParticleCloth:springStretchStiffness'
physxCameraSubject = 'physxCamera:subject'
physxCharacterControllerClimbingMode = 'physxCharacterController:climbingMode'
physxCharacterControllerContactOffset = 'physxCharacterController:contactOffset'
physxCharacterControllerInvisibleWallHeight = 'physxCharacterController:invisibleWallHeight'
physxCharacterControllerMaxJumpHeight = 'physxCharacterController:maxJumpHeight'
physxCharacterControllerMoveTarget = 'physxCharacterController:moveTarget'
physxCharacterControllerNonWalkableMode = 'physxCharacterController:nonWalkableMode'
physxCharacterControllerScaleCoeff = 'physxCharacterController:scaleCoeff'
physxCharacterControllerSimulationOwner = 'physxCharacterController:simulationOwner'
physxCharacterControllerSlopeLimit = 'physxCharacterController:slopeLimit'
physxCharacterControllerStepOffset = 'physxCharacterController:stepOffset'
physxCharacterControllerUpAxis = 'physxCharacterController:upAxis'
physxCharacterControllerVolumeGrowth = 'physxCharacterController:volumeGrowth'
physxCollisionContactOffset = 'physxCollision:contactOffset'
physxCollisionCustomGeometry = 'physxCollisionCustomGeometry'
physxCollisionMinTorsionalPatchRadius = 'physxCollision:minTorsionalPatchRadius'
physxCollisionRestOffset = 'physxCollision:restOffset'
physxCollisionTorsionalPatchRadius = 'physxCollision:torsionalPatchRadius'
physxContactReportReportPairs = 'physxContactReport:reportPairs'
physxContactReportThreshold = 'physxContactReport:threshold'
physxConvexDecompositionCollisionErrorPercentage = 'physxConvexDecompositionCollision:errorPercentage'
physxConvexDecompositionCollisionHullVertexLimit = 'physxConvexDecompositionCollision:hullVertexLimit'
physxConvexDecompositionCollisionMaxConvexHulls = 'physxConvexDecompositionCollision:maxConvexHulls'
physxConvexDecompositionCollisionMinThickness = 'physxConvexDecompositionCollision:minThickness'
physxConvexDecompositionCollisionShrinkWrap = 'physxConvexDecompositionCollision:shrinkWrap'
physxConvexDecompositionCollisionVoxelResolution = 'physxConvexDecompositionCollision:voxelResolution'
physxConvexHullCollisionHullVertexLimit = 'physxConvexHullCollision:hullVertexLimit'
physxConvexHullCollisionMinThickness = 'physxConvexHullCollision:minThickness'
physxCookedData = 'physxCookedData'
physxDeformableBodyMaterialDampingScale = 'physxDeformableBodyMaterial:dampingScale'
physxDeformableBodyMaterialDensity = 'physxDeformableBodyMaterial:density'
physxDeformableBodyMaterialDynamicFriction = 'physxDeformableBodyMaterial:dynamicFriction'
physxDeformableBodyMaterialElasticityDamping = 'physxDeformableBodyMaterial:elasticityDamping'
physxDeformableBodyMaterialPoissonsRatio = 'physxDeformableBodyMaterial:poissonsRatio'
physxDeformableBodyMaterialYoungsModulus = 'physxDeformableBodyMaterial:youngsModulus'
physxDeformableCollisionIndices = 'physxDeformable:collisionIndices'
physxDeformableCollisionPoints = 'physxDeformable:collisionPoints'
physxDeformableCollisionRestPoints = 'physxDeformable:collisionRestPoints'
physxDeformableDeformableEnabled = 'physxDeformable:deformableEnabled'
physxDeformableDisableGravity = 'physxDeformable:disableGravity'
physxDeformableEnableCCD = 'physxDeformable:enableCCD'
physxDeformableMaxDepenetrationVelocity = 'physxDeformable:maxDepenetrationVelocity'
physxDeformableRestPoints = 'physxDeformable:restPoints'
physxDeformableSelfCollision = 'physxDeformable:selfCollision'
physxDeformableSelfCollisionFilterDistance = 'physxDeformable:selfCollisionFilterDistance'
physxDeformableSettlingThreshold = 'physxDeformable:settlingThreshold'
physxDeformableSimulationIndices = 'physxDeformable:simulationIndices'
physxDeformableSimulationOwner = 'physxDeformable:simulationOwner'
physxDeformableSimulationPoints = 'physxDeformable:simulationPoints'
physxDeformableSimulationRestPoints = 'physxDeformable:simulationRestPoints'
physxDeformableSimulationVelocities = 'physxDeformable:simulationVelocities'
physxDeformableSleepDamping = 'physxDeformable:sleepDamping'
physxDeformableSleepThreshold = 'physxDeformable:sleepThreshold'
physxDeformableSolverPositionIterationCount = 'physxDeformable:solverPositionIterationCount'
physxDeformableSurfaceBendingStiffnessScale = 'physxDeformableSurface:bendingStiffnessScale'
physxDeformableSurfaceCollisionIterationMultiplier = 'physxDeformableSurface:collisionIterationMultiplier'
physxDeformableSurfaceCollisionPairUpdateFrequency = 'physxDeformableSurface:collisionPairUpdateFrequency'
physxDeformableSurfaceFlatteningEnabled = 'physxDeformableSurface:flatteningEnabled'
physxDeformableSurfaceMaterialDensity = 'physxDeformableSurfaceMaterial:density'
physxDeformableSurfaceMaterialDynamicFriction = 'physxDeformableSurfaceMaterial:dynamicFriction'
physxDeformableSurfaceMaterialPoissonsRatio = 'physxDeformableSurfaceMaterial:poissonsRatio'
physxDeformableSurfaceMaterialThickness = 'physxDeformableSurfaceMaterial:thickness'
physxDeformableSurfaceMaterialYoungsModulus = 'physxDeformableSurfaceMaterial:youngsModulus'
physxDeformableSurfaceMaxVelocity = 'physxDeformableSurface:maxVelocity'
physxDeformableVertexVelocityDamping = 'physxDeformable:vertexVelocityDamping'
physxDiffuseParticlesAirDrag = 'physxDiffuseParticles:airDrag'
physxDiffuseParticlesBubbleDrag = 'physxDiffuseParticles:bubbleDrag'
physxDiffuseParticlesBuoyancy = 'physxDiffuseParticles:buoyancy'
physxDiffuseParticlesCollisionDecay = 'physxDiffuseParticles:collisionDecay'
physxDiffuseParticlesDiffuseParticlesEnabled = 'physxDiffuseParticles:diffuseParticlesEnabled'
physxDiffuseParticlesDivergenceWeight = 'physxDiffuseParticles:divergenceWeight'
physxDiffuseParticlesKineticEnergyWeight = 'physxDiffuseParticles:kineticEnergyWeight'
physxDiffuseParticlesLifetime = 'physxDiffuseParticles:lifetime'
physxDiffuseParticlesMaxDiffuseParticleMultiplier = 'physxDiffuseParticles:maxDiffuseParticleMultiplier'
physxDiffuseParticlesPressureWeight = 'physxDiffuseParticles:pressureWeight'
physxDiffuseParticlesThreshold = 'physxDiffuseParticles:threshold'
physxDiffuseParticlesUseAccurateVelocity = 'physxDiffuseParticles:useAccurateVelocity'
physxDroneCameraFeedForwardVelocityGain = 'physxDroneCamera:feedForwardVelocityGain'
physxDroneCameraFollowDistance = 'physxDroneCamera:followDistance'
physxDroneCameraFollowHeight = 'physxDroneCamera:followHeight'
physxDroneCameraHorizontalVelocityGain = 'physxDroneCamera:horizontalVelocityGain'
physxDroneCameraMaxDistance = 'physxDroneCamera:maxDistance'
physxDroneCameraMaxSpeed = 'physxDroneCamera:maxSpeed'
physxDroneCameraPositionOffset = 'physxDroneCamera:positionOffset'
physxDroneCameraRotationFilterTimeConstant = 'physxDroneCamera:rotationFilterTimeConstant'
physxDroneCameraVelocityFilterTimeConstant = 'physxDroneCamera:velocityFilterTimeConstant'
physxDroneCameraVerticalVelocityGain = 'physxDroneCamera:verticalVelocityGain'
physxFollowCameraCameraPositionTimeConstant = 'physxFollowCamera:cameraPositionTimeConstant'
physxFollowCameraFollowMaxDistance = 'physxFollowCamera:followMaxDistance'
physxFollowCameraFollowMaxSpeed = 'physxFollowCamera:followMaxSpeed'
physxFollowCameraFollowMinDistance = 'physxFollowCamera:followMinDistance'
physxFollowCameraFollowMinSpeed = 'physxFollowCamera:followMinSpeed'
physxFollowCameraFollowTurnRateGain = 'physxFollowCamera:followTurnRateGain'
physxFollowCameraLookAheadMaxSpeed = 'physxFollowCamera:lookAheadMaxSpeed'
physxFollowCameraLookAheadMinDistance = 'physxFollowCamera:lookAheadMinDistance'
physxFollowCameraLookAheadMinSpeed = 'physxFollowCamera:lookAheadMinSpeed'
physxFollowCameraLookAheadTurnRateGain = 'physxFollowCamera:lookAheadTurnRateGain'
physxFollowCameraLookPositionHeight = 'physxFollowCamera:lookPositionHeight'
physxFollowCameraLookPositionTimeConstant = 'physxFollowCamera:lookPositionTimeConstant'
physxFollowCameraPitchAngle = 'physxFollowCamera:pitchAngle'
physxFollowCameraPitchAngleTimeConstant = 'physxFollowCamera:pitchAngleTimeConstant'
physxFollowCameraPositionOffset = 'physxFollowCamera:positionOffset'
physxFollowCameraSlowPitchAngleSpeed = 'physxFollowCamera:slowPitchAngleSpeed'
physxFollowCameraSlowSpeedPitchAngleScale = 'physxFollowCamera:slowSpeedPitchAngleScale'
physxFollowCameraVelocityNormalMinSpeed = 'physxFollowCamera:velocityNormalMinSpeed'
physxFollowCameraYawAngle = 'physxFollowCamera:yawAngle'
physxFollowCameraYawRateTimeConstant = 'physxFollowCamera:yawRateTimeConstant'
physxFollowFollowCameraLookAheadMaxDistance = 'physxFollowFollowCamera:lookAheadMaxDistance'
physxFollowLookCameraDownHillGroundAngle = 'physxFollowLookCamera:downHillGroundAngle'
physxFollowLookCameraDownHillGroundPitch = 'physxFollowLookCamera:downHillGroundPitch'
physxFollowLookCameraFollowReverseDistance = 'physxFollowLookCamera:followReverseDistance'
physxFollowLookCameraFollowReverseSpeed = 'physxFollowLookCamera:followReverseSpeed'
physxFollowLookCameraUpHillGroundAngle = 'physxFollowLookCamera:upHillGroundAngle'
physxFollowLookCameraUpHillGroundPitch = 'physxFollowLookCamera:upHillGroundPitch'
physxFollowLookCameraVelocityBlendTimeConstant = 'physxFollowLookCamera:velocityBlendTimeConstant'
physxForceForce = 'physxForce:force'
physxForceForceEnabled = 'physxForce:forceEnabled'
physxForceMode = 'physxForce:mode'
physxForceTorque = 'physxForce:torque'
physxForceWorldFrameEnabled = 'physxForce:worldFrameEnabled'
physxHairExternalCollision = 'physxHair:externalCollision'
physxHairGlobalShapeComplianceAtRoot = 'physxHair:globalShapeComplianceAtRoot'
physxHairGlobalShapeComplianceStrandAttenuation = 'physxHair:globalShapeComplianceStrandAttenuation'
physxHairInterHairRepulsion = 'physxHair:interHairRepulsion'
physxHairLocalShapeMatchingCompliance = 'physxHair:localShapeMatchingCompliance'
physxHairLocalShapeMatchingGroupOverlap = 'physxHair:localShapeMatchingGroupOverlap'
physxHairLocalShapeMatchingGroupSize = 'physxHair:localShapeMatchingGroupSize'
physxHairLocalShapeMatchingLinearStretching = 'physxHair:localShapeMatchingLinearStretching'
physxHairMaterialContactOffset = 'physxHairMaterial:contactOffset'
physxHairMaterialContactOffsetMultiplier = 'physxHairMaterial:contactOffsetMultiplier'
physxHairMaterialCurveBendStiffness = 'physxHairMaterial:curveBendStiffness'
physxHairMaterialCurveThickness = 'physxHairMaterial:curveThickness'
physxHairMaterialDensity = 'physxHairMaterial:density'
physxHairMaterialDynamicFriction = 'physxHairMaterial:dynamicFriction'
physxHairMaterialYoungsModulus = 'physxHairMaterial:youngsModulus'
physxHairSegmentLength = 'physxHair:segmentLength'
physxHairTwosidedAttachment = 'physxHair:twosidedAttachment'
physxHairVelSmoothing = 'physxHair:velSmoothing'
physxJointArmature = 'physxJoint:armature'
physxJointEnableProjection = 'physxJoint:enableProjection'
physxJointJointFriction = 'physxJoint:jointFriction'
physxJointMaxJointVelocity = 'physxJoint:maxJointVelocity'
physxLimit = 'physxLimit'
physxMaterialCompliantContactDamping = 'physxMaterial:compliantContactDamping'
physxMaterialCompliantContactStiffness = 'physxMaterial:compliantContactStiffness'
physxMaterialFrictionCombineMode = 'physxMaterial:frictionCombineMode'
physxMaterialImprovePatchFriction = 'physxMaterial:improvePatchFriction'
physxMaterialRestitutionCombineMode = 'physxMaterial:restitutionCombineMode'
physxPBDMaterialAdhesion = 'physxPBDMaterial:adhesion'
physxPBDMaterialAdhesionOffsetScale = 'physxPBDMaterial:adhesionOffsetScale'
physxPBDMaterialCflCoefficient = 'physxPBDMaterial:cflCoefficient'
physxPBDMaterialCohesion = 'physxPBDMaterial:cohesion'
physxPBDMaterialDamping = 'physxPBDMaterial:damping'
physxPBDMaterialDensity = 'physxPBDMaterial:density'
physxPBDMaterialDrag = 'physxPBDMaterial:drag'
physxPBDMaterialFriction = 'physxPBDMaterial:friction'
physxPBDMaterialGravityScale = 'physxPBDMaterial:gravityScale'
physxPBDMaterialLift = 'physxPBDMaterial:lift'
physxPBDMaterialParticleAdhesionScale = 'physxPBDMaterial:particleAdhesionScale'
physxPBDMaterialParticleFrictionScale = 'physxPBDMaterial:particleFrictionScale'
physxPBDMaterialSurfaceTension = 'physxPBDMaterial:surfaceTension'
physxPBDMaterialViscosity = 'physxPBDMaterial:viscosity'
physxPBDMaterialVorticityConfinement = 'physxPBDMaterial:vorticityConfinement'
physxParticleAnisotropyMax = 'physxParticleAnisotropy:max'
physxParticleAnisotropyMin = 'physxParticleAnisotropy:min'
physxParticleAnisotropyParticleAnisotropyEnabled = 'physxParticleAnisotropy:particleAnisotropyEnabled'
physxParticleAnisotropyScale = 'physxParticleAnisotropy:scale'
physxParticleFluid = 'physxParticle:fluid'
physxParticleIsosurfaceGridFilteringPasses = 'physxParticleIsosurface:gridFilteringPasses'
physxParticleIsosurfaceGridSmoothingRadius = 'physxParticleIsosurface:gridSmoothingRadius'
physxParticleIsosurfaceGridSpacing = 'physxParticleIsosurface:gridSpacing'
physxParticleIsosurfaceIsosurfaceEnabled = 'physxParticleIsosurface:isosurfaceEnabled'
physxParticleIsosurfaceMaxSubgrids = 'physxParticleIsosurface:maxSubgrids'
physxParticleIsosurfaceMaxTriangles = 'physxParticleIsosurface:maxTriangles'
physxParticleIsosurfaceMaxVertices = 'physxParticleIsosurface:maxVertices'
physxParticleIsosurfaceNumMeshNormalSmoothingPasses = 'physxParticleIsosurface:numMeshNormalSmoothingPasses'
physxParticleIsosurfaceNumMeshSmoothingPasses = 'physxParticleIsosurface:numMeshSmoothingPasses'
physxParticleIsosurfaceSurfaceDistance = 'physxParticleIsosurface:surfaceDistance'
physxParticleParticleEnabled = 'physxParticle:particleEnabled'
physxParticleParticleGroup = 'physxParticle:particleGroup'
physxParticleParticleSystem = 'physxParticle:particleSystem'
physxParticlePressure = 'physxParticle:pressure'
physxParticleRestPoints = 'physxParticle:restPoints'
physxParticleSamplingMaxSamples = 'physxParticleSampling:maxSamples'
physxParticleSamplingParticles = 'physxParticleSampling:particles'
physxParticleSamplingSamplingDistance = 'physxParticleSampling:samplingDistance'
physxParticleSamplingVolume = 'physxParticleSampling:volume'
physxParticleSelfCollision = 'physxParticle:selfCollision'
physxParticleSelfCollisionFilter = 'physxParticle:selfCollisionFilter'
physxParticleSimulationPoints = 'physxParticle:simulationPoints'
physxParticleSmoothingParticleSmoothingEnabled = 'physxParticleSmoothing:particleSmoothingEnabled'
physxParticleSmoothingStrength = 'physxParticleSmoothing:strength'
physxParticleSpringDampings = 'physxParticle:springDampings'
physxParticleSpringIndices = 'physxParticle:springIndices'
physxParticleSpringRestLengths = 'physxParticle:springRestLengths'
physxParticleSpringStiffnesses = 'physxParticle:springStiffnesses'
physxPhysicsDistanceJointSpringDamping = 'physxPhysicsDistanceJoint:springDamping'
physxPhysicsDistanceJointSpringEnabled = 'physxPhysicsDistanceJoint:springEnabled'
physxPhysicsDistanceJointSpringStiffness = 'physxPhysicsDistanceJoint:springStiffness'
physxRigidBodyAngularDamping = 'physxRigidBody:angularDamping'
physxRigidBodyCfmScale = 'physxRigidBody:cfmScale'
physxRigidBodyContactSlopCoefficient = 'physxRigidBody:contactSlopCoefficient'
physxRigidBodyDisableGravity = 'physxRigidBody:disableGravity'
physxRigidBodyEnableCCD = 'physxRigidBody:enableCCD'
physxRigidBodyEnableGyroscopicForces = 'physxRigidBody:enableGyroscopicForces'
physxRigidBodyEnableSpeculativeCCD = 'physxRigidBody:enableSpeculativeCCD'
physxRigidBodyLinearDamping = 'physxRigidBody:linearDamping'
physxRigidBodyLockedPosAxis = 'physxRigidBody:lockedPosAxis'
physxRigidBodyLockedRotAxis = 'physxRigidBody:lockedRotAxis'
physxRigidBodyMaxAngularVelocity = 'physxRigidBody:maxAngularVelocity'
physxRigidBodyMaxContactImpulse = 'physxRigidBody:maxContactImpulse'
physxRigidBodyMaxDepenetrationVelocity = 'physxRigidBody:maxDepenetrationVelocity'
physxRigidBodyMaxLinearVelocity = 'physxRigidBody:maxLinearVelocity'
physxRigidBodyRetainAccelerations = 'physxRigidBody:retainAccelerations'
physxRigidBodySleepThreshold = 'physxRigidBody:sleepThreshold'
physxRigidBodySolveContact = 'physxRigidBody:solveContact'
physxRigidBodySolverPositionIterationCount = 'physxRigidBody:solverPositionIterationCount'
physxRigidBodySolverVelocityIterationCount = 'physxRigidBody:solverVelocityIterationCount'
physxRigidBodyStabilizationThreshold = 'physxRigidBody:stabilizationThreshold'
physxSDFMeshCollisionSdfBitsPerSubgridPixel = 'physxSDFMeshCollision:sdfBitsPerSubgridPixel'
physxSDFMeshCollisionSdfEnableRemeshing = 'physxSDFMeshCollision:sdfEnableRemeshing'
physxSDFMeshCollisionSdfMargin = 'physxSDFMeshCollision:sdfMargin'
physxSDFMeshCollisionSdfNarrowBandThickness = 'physxSDFMeshCollision:sdfNarrowBandThickness'
physxSDFMeshCollisionSdfResolution = 'physxSDFMeshCollision:sdfResolution'
physxSDFMeshCollisionSdfSubgridResolution = 'physxSDFMeshCollision:sdfSubgridResolution'
physxSceneBounceThreshold = 'physxScene:bounceThreshold'
physxSceneBroadphaseType = 'physxScene:broadphaseType'
physxSceneCollisionSystem = 'physxScene:collisionSystem'
physxSceneEnableCCD = 'physxScene:enableCCD'
physxSceneEnableEnhancedDeterminism = 'physxScene:enableEnhancedDeterminism'
physxSceneEnableGPUDynamics = 'physxScene:enableGPUDynamics'
physxSceneEnableSceneQuerySupport = 'physxScene:enableSceneQuerySupport'
physxSceneEnableStabilization = 'physxScene:enableStabilization'
physxSceneFrictionCorrelationDistance = 'physxScene:frictionCorrelationDistance'
physxSceneFrictionOffsetThreshold = 'physxScene:frictionOffsetThreshold'
physxSceneFrictionType = 'physxScene:frictionType'
physxSceneGpuCollisionStackSize = 'physxScene:gpuCollisionStackSize'
physxSceneGpuFoundLostAggregatePairsCapacity = 'physxScene:gpuFoundLostAggregatePairsCapacity'
physxSceneGpuFoundLostPairsCapacity = 'physxScene:gpuFoundLostPairsCapacity'
physxSceneGpuHeapCapacity = 'physxScene:gpuHeapCapacity'
physxSceneGpuMaxDeformableSurfaceContacts = 'physxScene:gpuMaxDeformableSurfaceContacts'
physxSceneGpuMaxHairContacts = 'physxScene:gpuMaxHairContacts'
physxSceneGpuMaxNumPartitions = 'physxScene:gpuMaxNumPartitions'
physxSceneGpuMaxParticleContacts = 'physxScene:gpuMaxParticleContacts'
physxSceneGpuMaxRigidContactCount = 'physxScene:gpuMaxRigidContactCount'
physxSceneGpuMaxRigidPatchCount = 'physxScene:gpuMaxRigidPatchCount'
physxSceneGpuMaxSoftBodyContacts = 'physxScene:gpuMaxSoftBodyContacts'
physxSceneGpuTempBufferCapacity = 'physxScene:gpuTempBufferCapacity'
physxSceneGpuTotalAggregatePairsCapacity = 'physxScene:gpuTotalAggregatePairsCapacity'
physxSceneInvertCollisionGroupFilter = 'physxScene:invertCollisionGroupFilter'
physxSceneMaxBiasCoefficient = 'physxScene:maxBiasCoefficient'
physxSceneMaxIterationCount = 'physxScene:maxIterationCount'
physxSceneMinIterationCount = 'physxScene:minIterationCount'
physxSceneReportKinematicKinematicPairs = 'physxScene:reportKinematicKinematicPairs'
physxSceneReportKinematicStaticPairs = 'physxScene:reportKinematicStaticPairs'
physxSceneSolverType = 'physxScene:solverType'
physxSceneTimeStepsPerSecond = 'physxScene:timeStepsPerSecond'
physxSceneUpdateType = 'physxScene:updateType'
physxSphereFillCollisionFillMode = 'physxSphereFillCollision:fillMode'
physxSphereFillCollisionMaxSpheres = 'physxSphereFillCollision:maxSpheres'
physxSphereFillCollisionSeedCount = 'physxSphereFillCollision:seedCount'
physxSphereFillCollisionVoxelResolution = 'physxSphereFillCollision:voxelResolution'
physxTendon = 'physxTendon'
physxTriangleMeshCollisionWeldTolerance = 'physxTriangleMeshCollision:weldTolerance'
physxTriangleMeshSimplificationCollisionMetric = 'physxTriangleMeshSimplificationCollision:metric'
physxTriangleMeshSimplificationCollisionWeldTolerance = 'physxTriangleMeshSimplificationCollision:weldTolerance'
physxTriggerEnterScriptType = 'physxTrigger:enterScriptType'
physxTriggerLeaveScriptType = 'physxTrigger:leaveScriptType'
physxTriggerOnEnterScript = 'physxTrigger:onEnterScript'
physxTriggerOnLeaveScript = 'physxTrigger:onLeaveScript'
physxTriggerTriggeredCollisions = 'physxTrigger:triggeredCollisions'
physxVehicleAckermannSteeringMaxSteerAngle = 'physxVehicleAckermannSteering:maxSteerAngle'
physxVehicleAckermannSteeringStrength = 'physxVehicleAckermannSteering:strength'
physxVehicleAckermannSteeringTrackWidth = 'physxVehicleAckermannSteering:trackWidth'
physxVehicleAckermannSteeringWheel0 = 'physxVehicleAckermannSteering:wheel0'
physxVehicleAckermannSteeringWheel1 = 'physxVehicleAckermannSteering:wheel1'
physxVehicleAckermannSteeringWheelBase = 'physxVehicleAckermannSteering:wheelBase'
physxVehicleAutoGearBoxDownRatios = 'physxVehicleAutoGearBox:downRatios'
physxVehicleAutoGearBoxLatency = 'physxVehicleAutoGearBox:latency'
physxVehicleAutoGearBoxUpRatios = 'physxVehicleAutoGearBox:upRatios'
physxVehicleBrakes = 'physxVehicleBrakes'
physxVehicleClutchStrength = 'physxVehicleClutch:strength'
physxVehicleContextForwardAxis = 'physxVehicleContext:forwardAxis'
physxVehicleContextLongitudinalAxis = 'physxVehicleContext:longitudinalAxis'
physxVehicleContextUpAxis = 'physxVehicleContext:upAxis'
physxVehicleContextUpdateMode = 'physxVehicleContext:updateMode'
physxVehicleContextVerticalAxis = 'physxVehicleContext:verticalAxis'
physxVehicleControllerAccelerator = 'physxVehicleController:accelerator'
physxVehicleControllerBrake = 'physxVehicleController:brake'
physxVehicleControllerBrake0 = 'physxVehicleController:brake0'
physxVehicleControllerBrake1 = 'physxVehicleController:brake1'
physxVehicleControllerHandbrake = 'physxVehicleController:handbrake'
physxVehicleControllerSteer = 'physxVehicleController:steer'
physxVehicleControllerSteerLeft = 'physxVehicleController:steerLeft'
physxVehicleControllerSteerRight = 'physxVehicleController:steerRight'
physxVehicleControllerTargetGear = 'physxVehicleController:targetGear'
physxVehicleDrive = 'physxVehicle:drive'
physxVehicleDriveBasicPeakTorque = 'physxVehicleDriveBasic:peakTorque'
physxVehicleDriveStandardAutoGearBox = 'physxVehicleDriveStandard:autoGearBox'
physxVehicleDriveStandardClutch = 'physxVehicleDriveStandard:clutch'
physxVehicleDriveStandardEngine = 'physxVehicleDriveStandard:engine'
physxVehicleDriveStandardGears = 'physxVehicleDriveStandard:gears'
physxVehicleEngineDampingRateFullThrottle = 'physxVehicleEngine:dampingRateFullThrottle'
physxVehicleEngineDampingRateZeroThrottleClutchDisengaged = 'physxVehicleEngine:dampingRateZeroThrottleClutchDisengaged'
physxVehicleEngineDampingRateZeroThrottleClutchEngaged = 'physxVehicleEngine:dampingRateZeroThrottleClutchEngaged'
physxVehicleEngineIdleRotationSpeed = 'physxVehicleEngine:idleRotationSpeed'
physxVehicleEngineMaxRotationSpeed = 'physxVehicleEngine:maxRotationSpeed'
physxVehicleEngineMoi = 'physxVehicleEngine:moi'
physxVehicleEnginePeakTorque = 'physxVehicleEngine:peakTorque'
physxVehicleEngineTorqueCurve = 'physxVehicleEngine:torqueCurve'
physxVehicleGearsRatioScale = 'physxVehicleGears:ratioScale'
physxVehicleGearsRatios = 'physxVehicleGears:ratios'
physxVehicleGearsSwitchTime = 'physxVehicleGears:switchTime'
physxVehicleHighForwardSpeedSubStepCount = 'physxVehicle:highForwardSpeedSubStepCount'
physxVehicleLateralStickyTireDamping = 'physxVehicle:lateralStickyTireDamping'
physxVehicleLateralStickyTireThresholdSpeed = 'physxVehicle:lateralStickyTireThresholdSpeed'
physxVehicleLateralStickyTireThresholdTime = 'physxVehicle:lateralStickyTireThresholdTime'
physxVehicleLongitudinalStickyTireDamping = 'physxVehicle:longitudinalStickyTireDamping'
physxVehicleLongitudinalStickyTireThresholdSpeed = 'physxVehicle:longitudinalStickyTireThresholdSpeed'
physxVehicleLongitudinalStickyTireThresholdTime = 'physxVehicle:longitudinalStickyTireThresholdTime'
physxVehicleLowForwardSpeedSubStepCount = 'physxVehicle:lowForwardSpeedSubStepCount'
physxVehicleMinActiveLongitudinalSlipDenominator = 'physxVehicle:minActiveLongitudinalSlipDenominator'
physxVehicleMinLateralSlipDenominator = 'physxVehicle:minLateralSlipDenominator'
physxVehicleMinLongitudinalSlipDenominator = 'physxVehicle:minLongitudinalSlipDenominator'
physxVehicleMinPassiveLongitudinalSlipDenominator = 'physxVehicle:minPassiveLongitudinalSlipDenominator'
physxVehicleMultiWheelDifferentialAverageWheelSpeedRatios = 'physxVehicleMultiWheelDifferential:averageWheelSpeedRatios'
physxVehicleMultiWheelDifferentialTorqueRatios = 'physxVehicleMultiWheelDifferential:torqueRatios'
physxVehicleMultiWheelDifferentialWheels = 'physxVehicleMultiWheelDifferential:wheels'
physxVehicleSteeringAngleMultipliers = 'physxVehicleSteering:angleMultipliers'
physxVehicleSteeringMaxSteerAngle = 'physxVehicleSteering:maxSteerAngle'
physxVehicleSteeringWheels = 'physxVehicleSteering:wheels'
physxVehicleSubStepThresholdLongitudinalSpeed = 'physxVehicle:subStepThresholdLongitudinalSpeed'
physxVehicleSuspensionCamberAtMaxCompression = 'physxVehicleSuspension:camberAtMaxCompression'
physxVehicleSuspensionCamberAtMaxDroop = 'physxVehicleSuspension:camberAtMaxDroop'
physxVehicleSuspensionCamberAtRest = 'physxVehicleSuspension:camberAtRest'
physxVehicleSuspensionComplianceSuspensionForceAppPoint = 'physxVehicleSuspensionCompliance:suspensionForceAppPoint'
physxVehicleSuspensionComplianceTireForceAppPoint = 'physxVehicleSuspensionCompliance:tireForceAppPoint'
physxVehicleSuspensionComplianceWheelCamberAngle = 'physxVehicleSuspensionCompliance:wheelCamberAngle'
physxVehicleSuspensionComplianceWheelToeAngle = 'physxVehicleSuspensionCompliance:wheelToeAngle'
physxVehicleSuspensionLineQueryType = 'physxVehicle:suspensionLineQueryType'
physxVehicleSuspensionMaxCompression = 'physxVehicleSuspension:maxCompression'
physxVehicleSuspensionMaxDroop = 'physxVehicleSuspension:maxDroop'
physxVehicleSuspensionSpringDamperRate = 'physxVehicleSuspension:springDamperRate'
physxVehicleSuspensionSpringStrength = 'physxVehicleSuspension:springStrength'
physxVehicleSuspensionSprungMass = 'physxVehicleSuspension:sprungMass'
physxVehicleSuspensionTravelDistance = 'physxVehicleSuspension:travelDistance'
physxVehicleTankControllerThrust0 = 'physxVehicleTankController:thrust0'
physxVehicleTankControllerThrust1 = 'physxVehicleTankController:thrust1'
physxVehicleTankDifferentialNumberOfWheelsPerTrack = 'physxVehicleTankDifferential:numberOfWheelsPerTrack'
physxVehicleTankDifferentialThrustIndexPerTrack = 'physxVehicleTankDifferential:thrustIndexPerTrack'
physxVehicleTankDifferentialTrackToWheelIndices = 'physxVehicleTankDifferential:trackToWheelIndices'
physxVehicleTankDifferentialWheelIndicesInTrackOrder = 'physxVehicleTankDifferential:wheelIndicesInTrackOrder'
physxVehicleTireCamberStiffness = 'physxVehicleTire:camberStiffness'
physxVehicleTireCamberStiffnessPerUnitGravity = 'physxVehicleTire:camberStiffnessPerUnitGravity'
physxVehicleTireFrictionTable = 'physxVehicleTire:frictionTable'
physxVehicleTireFrictionVsSlipGraph = 'physxVehicleTire:frictionVsSlipGraph'
physxVehicleTireLatStiffX = 'physxVehicleTire:latStiffX'
physxVehicleTireLatStiffY = 'physxVehicleTire:latStiffY'
physxVehicleTireLateralStiffnessGraph = 'physxVehicleTire:lateralStiffnessGraph'
physxVehicleTireLongitudinalStiffness = 'physxVehicleTire:longitudinalStiffness'
physxVehicleTireLongitudinalStiffnessPerUnitGravity = 'physxVehicleTire:longitudinalStiffnessPerUnitGravity'
physxVehicleTireRestLoad = 'physxVehicleTire:restLoad'
physxVehicleVehicleEnabled = 'physxVehicle:vehicleEnabled'
physxVehicleWheelAttachmentCollisionGroup = 'physxVehicleWheelAttachment:collisionGroup'
physxVehicleWheelAttachmentDriven = 'physxVehicleWheelAttachment:driven'
physxVehicleWheelAttachmentIndex = 'physxVehicleWheelAttachment:index'
physxVehicleWheelAttachmentSuspension = 'physxVehicleWheelAttachment:suspension'
physxVehicleWheelAttachmentSuspensionForceAppPointOffset = 'physxVehicleWheelAttachment:suspensionForceAppPointOffset'
physxVehicleWheelAttachmentSuspensionFrameOrientation = 'physxVehicleWheelAttachment:suspensionFrameOrientation'
physxVehicleWheelAttachmentSuspensionFramePosition = 'physxVehicleWheelAttachment:suspensionFramePosition'
physxVehicleWheelAttachmentSuspensionTravelDirection = 'physxVehicleWheelAttachment:suspensionTravelDirection'
physxVehicleWheelAttachmentTire = 'physxVehicleWheelAttachment:tire'
physxVehicleWheelAttachmentTireForceAppPointOffset = 'physxVehicleWheelAttachment:tireForceAppPointOffset'
physxVehicleWheelAttachmentWheel = 'physxVehicleWheelAttachment:wheel'
physxVehicleWheelAttachmentWheelCenterOfMassOffset = 'physxVehicleWheelAttachment:wheelCenterOfMassOffset'
physxVehicleWheelAttachmentWheelFrameOrientation = 'physxVehicleWheelAttachment:wheelFrameOrientation'
physxVehicleWheelAttachmentWheelFramePosition = 'physxVehicleWheelAttachment:wheelFramePosition'
physxVehicleWheelControllerBrakeTorque = 'physxVehicleWheelController:brakeTorque'
physxVehicleWheelControllerDriveTorque = 'physxVehicleWheelController:driveTorque'
physxVehicleWheelControllerSteerAngle = 'physxVehicleWheelController:steerAngle'
physxVehicleWheelDampingRate = 'physxVehicleWheel:dampingRate'
physxVehicleWheelMass = 'physxVehicleWheel:mass'
physxVehicleWheelMaxBrakeTorque = 'physxVehicleWheel:maxBrakeTorque'
physxVehicleWheelMaxHandBrakeTorque = 'physxVehicleWheel:maxHandBrakeTorque'
physxVehicleWheelMaxSteerAngle = 'physxVehicleWheel:maxSteerAngle'
physxVehicleWheelMoi = 'physxVehicleWheel:moi'
physxVehicleWheelRadius = 'physxVehicleWheel:radius'
physxVehicleWheelToeAngle = 'physxVehicleWheel:toeAngle'
physxVehicleWheelWidth = 'physxVehicleWheel:width'
points0 = 'points0'
points1 = 'points1'
posX = 'posX'
posY = 'posY'
posZ = 'posZ'
preventClimbing = 'preventClimbing'
preventClimbingForceSliding = 'preventClimbingForceSliding'
raycast = 'raycast'
referenceFrameIsCenterOfMass = 'physxVehicle:referenceFrameIsCenterOfMass'
restLength = 'restLength'
restOffset = 'restOffset'
restitution = 'restitution'
rotX = 'rotX'
rotY = 'rotY'
rotZ = 'rotZ'
sAP = 'SAP'
sAT = 'SAT'
scriptBuffer = 'scriptBuffer'
scriptFile = 'scriptFile'
sdf = 'sdf'
simulationOwner = 'simulationOwner'
solidRestOffset = 'solidRestOffset'
solverPositionIterationCount = 'solverPositionIterationCount'
sphereFill = 'sphereFill'
state = 'state'
stiffness = 'stiffness'
surface = 'surface'
sweep = 'sweep'
synchronous = 'Synchronous'
tGS = 'TGS'
tendonEnabled = 'tendonEnabled'
torqueMultipliers = 'torqueMultipliers'
transX = 'transX'
transY = 'transY'
transZ = 'transZ'
triangleMesh = 'triangleMesh'
twoDirectional = 'twoDirectional'
undefined = 'undefined'
upperLimit = 'upperLimit'
velocityChange = 'velocityChange'
vertices = 'Vertices'
wheels = 'wheels'
wind = 'wind'
x = 'X'
y = 'Y'
z = 'Z'
pass
| 143,948 | unknown | 58.556889 | 238 | 0.723081 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/UsdRender/_UsdRender.pyi | from __future__ import annotations
import usdrt.UsdRender._UsdRender
import typing
import usdrt.Sdf._Sdf
import usdrt.Usd._Usd
__all__ = [
"DenoisePass",
"Pass",
"Product",
"Settings",
"SettingsBase",
"Tokens",
"Var"
]
class DenoisePass(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> DenoisePass: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Pass(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateCommandAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDenoiseEnableAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDenoisePassRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateFileNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInputPassesRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreatePassTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRenderSourceRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Pass: ...
def GetCommandAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDenoiseEnableAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDenoisePassRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetFileNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInputPassesRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetPassTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRenderSourceRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Product(SettingsBase, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateOrderedVarsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateProductNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateProductTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Product: ...
def GetOrderedVarsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetProductNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetProductTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Settings(SettingsBase, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateIncludedPurposesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaterialBindingPurposesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateProductsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateRenderingColorSpaceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Settings: ...
def GetIncludedPurposesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaterialBindingPurposesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetProductsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetRenderingColorSpaceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class SettingsBase(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAspectRatioConformPolicyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCameraRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateDataWindowNDCAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDisableMotionBlurAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInstantaneousShutterAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePixelAspectRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAspectRatioConformPolicyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCameraRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetDataWindowNDCAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDisableMotionBlurAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInstantaneousShutterAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPixelAspectRatioAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetResolutionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
adjustApertureHeight = 'adjustApertureHeight'
adjustApertureWidth = 'adjustApertureWidth'
adjustPixelAspectRatio = 'adjustPixelAspectRatio'
aspectRatioConformPolicy = 'aspectRatioConformPolicy'
camera = 'camera'
color3f = 'color3f'
command = 'command'
cropAperture = 'cropAperture'
dataType = 'dataType'
dataWindowNDC = 'dataWindowNDC'
denoiseEnable = 'denoise:enable'
denoisePass = 'denoise:pass'
disableMotionBlur = 'disableMotionBlur'
expandAperture = 'expandAperture'
fileName = 'fileName'
full = 'full'
includedPurposes = 'includedPurposes'
inputPasses = 'inputPasses'
instantaneousShutter = 'instantaneousShutter'
intrinsic = 'intrinsic'
lpe = 'lpe'
materialBindingPurposes = 'materialBindingPurposes'
orderedVars = 'orderedVars'
passType = 'passType'
pixelAspectRatio = 'pixelAspectRatio'
preview = 'preview'
primvar = 'primvar'
productName = 'productName'
productType = 'productType'
products = 'products'
raster = 'raster'
raw = 'raw'
renderSettingsPrimPath = 'renderSettingsPrimPath'
renderSource = 'renderSource'
renderingColorSpace = 'renderingColorSpace'
resolution = 'resolution'
sourceName = 'sourceName'
sourceType = 'sourceType'
pass
class Var(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateDataTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSourceNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSourceTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Var: ...
def GetDataTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSourceNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSourceTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
| 7,749 | unknown | 43.034091 | 90 | 0.661247 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/Rt/__init__.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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.core
# TODO: automate this
from usdrt import Gf, Sdf, Usd
from ._Rt import *
| 542 | Python | 32.937498 | 78 | 0.787823 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/Rt/_Rt.pyi | from __future__ import annotations
import usdrt.Rt._Rt
import typing
import usdrt.Gf._Gf
import usdrt.Sdf._Sdf
import usdrt.Usd._Usd
__all__ = [
"Boundable",
"ChangeTracker",
"Tokens",
"Xformable"
]
class Boundable(Xformable):
def ClearWorldExtent(self) -> bool: ...
def CreateWorldExtentAttr(self, defaultValue: usdrt.Gf._Gf.Range3d = Gf.Range3d(Gf.Vec3d(0.0, 0.0, 0.0), Gf.Vec3d(0.0, 0.0, 0.0))) -> usdrt.Usd._Usd.Attribute: ...
def GetWorldExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def HasWorldExtent(self) -> bool: ...
def SetWorldExtentFromUsd(self) -> bool: ...
def __init__(self, prim: usdrt.Usd._Usd.Prim = Prim(invalid)) -> None: ...
def __repr__(self) -> str: ...
pass
class ChangeTracker():
@typing.overload
def AttributeChanged(self, attr: usdrt.Usd._Usd.Attribute) -> bool: ...
@typing.overload
def AttributeChanged(self, attrPath: usdrt.Sdf._Sdf.Path) -> bool: ...
def ClearChanges(self) -> None: ...
def GetAllChangedAttributes(self) -> typing.List[usdrt.Sdf._Sdf.Path]: ...
def GetAllChangedPrims(self) -> typing.List[usdrt.Sdf._Sdf.Path]: ...
@typing.overload
def GetChangedAttributes(self, prim: usdrt.Usd._Usd.Prim) -> typing.List[TfToken]: ...
@typing.overload
def GetChangedAttributes(self, primPath: usdrt.Sdf._Sdf.Path) -> typing.List[TfToken]: ...
def GetTrackedAttributes(self) -> typing.List[TfToken]: ...
def HasChanges(self) -> bool: ...
def IsChangeTrackingPaused(self) -> bool: ...
def IsTrackingAttribute(self, attrName: TfToken) -> bool: ...
def PauseTracking(self) -> None: ...
@typing.overload
def PrimChanged(self, prim: usdrt.Usd._Usd.Prim) -> bool: ...
@typing.overload
def PrimChanged(self, primPath: usdrt.Sdf._Sdf.Path) -> bool: ...
def ResumeTracking(self) -> None: ...
def StopTrackingAttribute(self, attrName: TfToken) -> None: ...
def TrackAttribute(self, attrName: TfToken) -> None: ...
def __init__(self, arg0: usdrt.Usd._Usd.Stage) -> None: ...
pass
class Tokens():
localMatrix = '_localMatrix'
worldExtent = '_worldExtent'
worldOrientation = '_worldOrientation'
worldPosition = '_worldPosition'
worldScale = '_worldScale'
pass
class Xformable():
def ClearLocalXform(self) -> bool: ...
def ClearWorldXform(self) -> bool: ...
def CreateLocalMatrixAttr(self, defaultValue: usdrt.Gf._Gf.Matrix4d = Gf.Matrix4d(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)) -> usdrt.Usd._Usd.Attribute: ...
def CreateWorldOrientationAttr(self, defaultValue: usdrt.Gf._Gf.Quatf = Gf.Quatf(0.0, Gf.Vec3f(0.0, 0.0, 0.0))) -> usdrt.Usd._Usd.Attribute: ...
def CreateWorldPositionAttr(self, defaultValue: usdrt.Gf._Gf.Vec3d = Gf.Vec3d(0.0, 0.0, 0.0)) -> usdrt.Usd._Usd.Attribute: ...
def CreateWorldScaleAttr(self, defaultValue: usdrt.Gf._Gf.Vec3f = Gf.Vec3f(0.0, 0.0, 0.0)) -> usdrt.Usd._Usd.Attribute: ...
def GetLocalMatrixAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPath(self) -> usdrt.Sdf._Sdf.Path: ...
def GetPrim(self) -> usdrt.Usd._Usd.Prim: ...
def GetWorldOrientationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWorldPositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWorldScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def HasLocalXform(self) -> bool: ...
def HasWorldXform(self) -> bool: ...
def SetLocalXformFromUsd(self) -> bool: ...
def SetWorldXformFromUsd(self) -> bool: ...
def __bool__(self) -> bool: ...
def __init__(self, prim: usdrt.Usd._Usd.Prim = Prim(invalid)) -> None: ...
def __repr__(self) -> str: ...
pass
| 3,681 | unknown | 45.607594 | 202 | 0.642217 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/UsdLux/_UsdLux.pyi | from __future__ import annotations
import usdrt.UsdLux._UsdLux
import typing
import usdrt.Sdf._Sdf
import usdrt.Usd._Usd
import usdrt.UsdGeom._UsdGeom
__all__ = [
"BoundableLightBase",
"CylinderLight",
"DiskLight",
"DistantLight",
"DomeLight",
"GeometryLight",
"LightAPI",
"LightFilter",
"LightListAPI",
"ListAPI",
"MeshLightAPI",
"NonboundableLightBase",
"PluginLight",
"PluginLightFilter",
"PortalLight",
"RectLight",
"ShadowAPI",
"ShapingAPI",
"SphereLight",
"Tokens",
"VolumeLightAPI"
]
class CylinderLight(BoundableLightBase, usdrt.UsdGeom._UsdGeom.Boundable, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTreatAsLineAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> CylinderLight: ...
def GetLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTreatAsLineAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class DiskLight(BoundableLightBase, usdrt.UsdGeom._UsdGeom.Boundable, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> DiskLight: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class BoundableLightBase(usdrt.UsdGeom._UsdGeom.Boundable, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class DistantLight(NonboundableLightBase, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateIntensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> DistantLight: ...
def GetAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetIntensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class DomeLight(NonboundableLightBase, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateGuideRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePortalsRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateTextureFileAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTextureFormatAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> DomeLight: ...
def GetGuideRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPortalsRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTextureFileAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTextureFormatAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class GeometryLight(NonboundableLightBase, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateGeometryRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> GeometryLight: ...
def GetGeometryRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class LightAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCollectionLightLinkIncludeRootAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCollectionShadowLinkIncludeRootAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateColorTemperatureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDiffuseAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEnableColorTemperatureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateExposureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFiltersRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateIntensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMaterialSyncModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNormalizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpecularAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollectionLightLinkIncludeRootAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCollectionShadowLinkIncludeRootAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetColorTemperatureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDiffuseAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnableColorTemperatureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExposureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFiltersRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetIntensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMaterialSyncModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNormalizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpecularAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class LightFilter(usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateCollectionFilterLinkIncludeRootAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> LightFilter: ...
def GetCollectionFilterLinkIncludeRootAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class LightListAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateLightListCacheBehaviorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLightListRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetLightListCacheBehaviorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightListRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class ListAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateLightListCacheBehaviorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLightListRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetLightListCacheBehaviorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightListRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class MeshLightAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateLightMaterialSyncModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightMaterialSyncModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class NonboundableLightBase(usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PluginLight(usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PluginLight: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PluginLightFilter(LightFilter, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PluginLightFilter: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PortalLight(BoundableLightBase, usdrt.UsdGeom._UsdGeom.Boundable, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PortalLight: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class RectLight(BoundableLightBase, usdrt.UsdGeom._UsdGeom.Boundable, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTextureFileAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWidthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> RectLight: ...
def GetHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTextureFileAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWidthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class ShadowAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateShadowColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShadowDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShadowEnableAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShadowFalloffAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShadowFalloffGammaAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetShadowColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShadowDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShadowEnableAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShadowFalloffAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShadowFalloffGammaAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class ShapingAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateShapingConeAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShapingConeSoftnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShapingFocusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShapingFocusTintAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShapingIesAngleScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShapingIesFileAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShapingIesNormalizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetShapingConeAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShapingConeSoftnessAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShapingFocusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShapingFocusTintAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShapingIesAngleScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShapingIesFileAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShapingIesNormalizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class SphereLight(BoundableLightBase, usdrt.UsdGeom._UsdGeom.Boundable, usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTreatAsPointAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> SphereLight: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTreatAsPointAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
angular = 'angular'
automatic = 'automatic'
collectionFilterLinkIncludeRoot = 'collection:filterLink:includeRoot'
collectionLightLinkIncludeRoot = 'collection:lightLink:includeRoot'
collectionShadowLinkIncludeRoot = 'collection:shadowLink:includeRoot'
consumeAndContinue = 'consumeAndContinue'
consumeAndHalt = 'consumeAndHalt'
cubeMapVerticalCross = 'cubeMapVerticalCross'
cylinderLight = 'CylinderLight'
diskLight = 'DiskLight'
distantLight = 'DistantLight'
domeLight = 'DomeLight'
extent = 'extent'
filterLink = 'filterLink'
geometry = 'geometry'
geometryLight = 'GeometryLight'
guideRadius = 'guideRadius'
ignore = 'ignore'
independent = 'independent'
inputsAngle = 'inputs:angle'
inputsColor = 'inputs:color'
inputsColorTemperature = 'inputs:colorTemperature'
inputsDiffuse = 'inputs:diffuse'
inputsEnableColorTemperature = 'inputs:enableColorTemperature'
inputsExposure = 'inputs:exposure'
inputsHeight = 'inputs:height'
inputsIntensity = 'inputs:intensity'
inputsLength = 'inputs:length'
inputsNormalize = 'inputs:normalize'
inputsRadius = 'inputs:radius'
inputsShadowColor = 'inputs:shadow:color'
inputsShadowDistance = 'inputs:shadow:distance'
inputsShadowEnable = 'inputs:shadow:enable'
inputsShadowFalloff = 'inputs:shadow:falloff'
inputsShadowFalloffGamma = 'inputs:shadow:falloffGamma'
inputsShapingConeAngle = 'inputs:shaping:cone:angle'
inputsShapingConeSoftness = 'inputs:shaping:cone:softness'
inputsShapingFocus = 'inputs:shaping:focus'
inputsShapingFocusTint = 'inputs:shaping:focusTint'
inputsShapingIesAngleScale = 'inputs:shaping:ies:angleScale'
inputsShapingIesFile = 'inputs:shaping:ies:file'
inputsShapingIesNormalize = 'inputs:shaping:ies:normalize'
inputsSpecular = 'inputs:specular'
inputsTextureFile = 'inputs:texture:file'
inputsTextureFormat = 'inputs:texture:format'
inputsWidth = 'inputs:width'
latlong = 'latlong'
lightFilterShaderId = 'lightFilter:shaderId'
lightFilters = 'light:filters'
lightLink = 'lightLink'
lightList = 'lightList'
lightListCacheBehavior = 'lightList:cacheBehavior'
lightMaterialSyncMode = 'light:materialSyncMode'
lightShaderId = 'light:shaderId'
materialGlowTintsLight = 'materialGlowTintsLight'
meshLight = 'MeshLight'
mirroredBall = 'mirroredBall'
noMaterialResponse = 'noMaterialResponse'
orientToStageUpAxis = 'orientToStageUpAxis'
portalLight = 'PortalLight'
portals = 'portals'
rectLight = 'RectLight'
shadowLink = 'shadowLink'
sphereLight = 'SphereLight'
treatAsLine = 'treatAsLine'
treatAsPoint = 'treatAsPoint'
volumeLight = 'VolumeLight'
pass
class VolumeLightAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateLightMaterialSyncModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightMaterialSyncModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLightShaderIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
| 21,824 | unknown | 48.377828 | 191 | 0.670867 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/ForceFieldSchema/_ForceFieldSchema.pyi | from __future__ import annotations
import usdrt.ForceFieldSchema._ForceFieldSchema
import typing
import usdrt.Usd._Usd
__all__ = [
"PhysxForceFieldAPI",
"PhysxForceFieldConicalAPI",
"PhysxForceFieldDragAPI",
"PhysxForceFieldLinearAPI",
"PhysxForceFieldNoiseAPI",
"PhysxForceFieldPlanarAPI",
"PhysxForceFieldRingAPI",
"PhysxForceFieldSphericalAPI",
"PhysxForceFieldSpinAPI",
"PhysxForceFieldWindAPI",
"Tokens"
]
class PhysxForceFieldAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRangeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSurfaceAreaScaleEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSurfaceSampleDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPositionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRangeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSurfaceAreaScaleEnabledAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSurfaceSampleDensityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceFieldConicalAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLinearFalloffAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePowerFalloffAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAngleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLinearFalloffAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPowerFalloffAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceFieldDragAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMinimumSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMinimumSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceFieldLinearAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceFieldNoiseAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAmplitudeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFrequencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAmplitudeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFrequencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceFieldPlanarAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNormalAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNormalAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceFieldRingAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNormalAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpinConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpinInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpinLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNormalAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSpinConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpinInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpinLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceFieldSphericalAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceFieldSpinAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpinAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetConstantAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInverseSquareAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLinearAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSpinAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class PhysxForceFieldWindAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAverageDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateAverageSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDirectionVariationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDirectionVariationFrequencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpeedVariationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSpeedVariationFrequencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAverageDirectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAverageSpeedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDirectionVariationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDirectionVariationFrequencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDragAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSpeedVariationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetSpeedVariationFrequencyAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim, arg1: TfToken) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase, arg1: TfToken) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
forceFieldBodies = 'forceFieldBodies'
physxForceField = 'physxForceField'
physxForceFieldConicalAngle = 'physxForceFieldConical:angle'
physxForceFieldConicalConstant = 'physxForceFieldConical:constant'
physxForceFieldConicalInverseSquare = 'physxForceFieldConical:inverseSquare'
physxForceFieldConicalLinear = 'physxForceFieldConical:linear'
physxForceFieldConicalLinearFalloff = 'physxForceFieldConical:linearFalloff'
physxForceFieldConicalPowerFalloff = 'physxForceFieldConical:powerFalloff'
physxForceFieldDragLinear = 'physxForceFieldDrag:linear'
physxForceFieldDragMinimumSpeed = 'physxForceFieldDrag:minimumSpeed'
physxForceFieldDragSquare = 'physxForceFieldDrag:square'
physxForceFieldEnabled = 'physxForceField:enabled'
physxForceFieldLinearConstant = 'physxForceFieldLinear:constant'
physxForceFieldLinearDirection = 'physxForceFieldLinear:direction'
physxForceFieldLinearInverseSquare = 'physxForceFieldLinear:inverseSquare'
physxForceFieldLinearLinear = 'physxForceFieldLinear:linear'
physxForceFieldNoiseAmplitude = 'physxForceFieldNoise:amplitude'
physxForceFieldNoiseDrag = 'physxForceFieldNoise:drag'
physxForceFieldNoiseFrequency = 'physxForceFieldNoise:frequency'
physxForceFieldPlanarConstant = 'physxForceFieldPlanar:constant'
physxForceFieldPlanarInverseSquare = 'physxForceFieldPlanar:inverseSquare'
physxForceFieldPlanarLinear = 'physxForceFieldPlanar:linear'
physxForceFieldPlanarNormal = 'physxForceFieldPlanar:normal'
physxForceFieldPosition = 'physxForceField:position'
physxForceFieldRange = 'physxForceField:range'
physxForceFieldRingConstant = 'physxForceFieldRing:constant'
physxForceFieldRingInverseSquare = 'physxForceFieldRing:inverseSquare'
physxForceFieldRingLinear = 'physxForceFieldRing:linear'
physxForceFieldRingNormalAxis = 'physxForceFieldRing:normalAxis'
physxForceFieldRingRadius = 'physxForceFieldRing:radius'
physxForceFieldRingSpinConstant = 'physxForceFieldRing:spinConstant'
physxForceFieldRingSpinInverseSquare = 'physxForceFieldRing:spinInverseSquare'
physxForceFieldRingSpinLinear = 'physxForceFieldRing:spinLinear'
physxForceFieldSphericalConstant = 'physxForceFieldSpherical:constant'
physxForceFieldSphericalInverseSquare = 'physxForceFieldSpherical:inverseSquare'
physxForceFieldSphericalLinear = 'physxForceFieldSpherical:linear'
physxForceFieldSpinConstant = 'physxForceFieldSpin:constant'
physxForceFieldSpinInverseSquare = 'physxForceFieldSpin:inverseSquare'
physxForceFieldSpinLinear = 'physxForceFieldSpin:linear'
physxForceFieldSpinSpinAxis = 'physxForceFieldSpin:spinAxis'
physxForceFieldSurfaceAreaScaleEnabled = 'physxForceField:surfaceAreaScaleEnabled'
physxForceFieldSurfaceSampleDensity = 'physxForceField:surfaceSampleDensity'
physxForceFieldWindAverageDirection = 'physxForceFieldWind:averageDirection'
physxForceFieldWindAverageSpeed = 'physxForceFieldWind:averageSpeed'
physxForceFieldWindDirectionVariation = 'physxForceFieldWind:directionVariation'
physxForceFieldWindDirectionVariationFrequency = 'physxForceFieldWind:directionVariationFrequency'
physxForceFieldWindDrag = 'physxForceFieldWind:drag'
physxForceFieldWindSpeedVariation = 'physxForceFieldWind:speedVariation'
physxForceFieldWindSpeedVariationFrequency = 'physxForceFieldWind:speedVariationFrequency'
pass
| 14,685 | unknown | 53.798507 | 102 | 0.704869 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/UsdShade/_UsdShade.pyi | from __future__ import annotations
import usdrt.UsdShade._UsdShade
import typing
import usdrt.Sdf._Sdf
import usdrt.Usd._Usd
__all__ = [
"ConnectableAPI",
"CoordSysAPI",
"Material",
"MaterialBindingAPI",
"NodeDefAPI",
"NodeGraph",
"Shader",
"Tokens"
]
class ConnectableAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class CoordSysAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Material(NodeGraph, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateDisplacementAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSurfaceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVolumeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Material: ...
def GetDisplacementAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSurfaceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVolumeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class MaterialBindingAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class NodeDefAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateImplementationSourceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetIdAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetImplementationSourceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class NodeGraph(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> NodeGraph: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Shader(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Shader: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
allPurpose = ''
bindMaterialAs = 'bindMaterialAs'
coordSys = 'coordSys:'
displacement = 'displacement'
fallbackStrength = 'fallbackStrength'
full = 'full'
id = 'id'
infoId = 'info:id'
infoImplementationSource = 'info:implementationSource'
inputs = 'inputs:'
interfaceOnly = 'interfaceOnly'
materialBind = 'materialBind'
materialBinding = 'material:binding'
materialBindingCollection = 'material:binding:collection'
materialVariant = 'materialVariant'
outputs = 'outputs:'
outputsDisplacement = 'outputs:displacement'
outputsSurface = 'outputs:surface'
outputsVolume = 'outputs:volume'
preview = 'preview'
sdrMetadata = 'sdrMetadata'
sourceAsset = 'sourceAsset'
sourceCode = 'sourceCode'
strongerThanDescendants = 'strongerThanDescendants'
subIdentifier = 'subIdentifier'
surface = 'surface'
universalRenderContext = ''
universalSourceType = ''
volume = 'volume'
weakerThanDescendants = 'weakerThanDescendants'
pass
| 5,048 | unknown | 35.854014 | 88 | 0.634509 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/DestructionSchema/_DestructionSchema.pyi | from __future__ import annotations
import usdrt.DestructionSchema._DestructionSchema
import typing
import usdrt.Usd._Usd
__all__ = [
"DestructibleBaseAPI",
"DestructibleBondAPI",
"DestructibleChunkAPI",
"DestructibleInstAPI",
"Tokens"
]
class DestructibleBaseAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateDefaultBondStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDefaultChunkStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSupportDepthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDefaultBondStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDefaultChunkStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSupportDepthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class DestructibleBondAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateAreaAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateAttachedRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateCentroidAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNormalAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUnbreakableAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAreaAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAttachedRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetCentroidAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNormalAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUnbreakableAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class DestructibleChunkAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateCentroidAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateParentChunkRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVolumeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCentroidAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetParentChunkRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStrengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVolumeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class DestructibleInstAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateBaseRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetBaseRel(self) -> usdrt.Usd._Usd.Relationship: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
destructArea = 'destruct:area'
destructAttached = 'destruct:attached'
destructBase = 'destruct:base'
destructCentroid = 'destruct:centroid'
destructDefaultBondStrength = 'destruct:defaultBondStrength'
destructDefaultChunkStrength = 'destruct:defaultChunkStrength'
destructNormal = 'destruct:normal'
destructParentChunk = 'destruct:parentChunk'
destructStrength = 'destruct:strength'
destructSupportDepth = 'destruct:supportDepth'
destructUnbreakable = 'destruct:unbreakable'
destructVolume = 'destruct:volume'
pass
| 4,304 | unknown | 43.381443 | 84 | 0.667519 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/Vt/_Vt.pyi | from __future__ import annotations
import usdrt.Vt._Vt
import typing
import numpy
import usdrt.Gf._Gf
_Shape = typing.Tuple[int, ...]
__all__ = [
"AssetArray",
"BoolArray",
"CharArray",
"DoubleArray",
"FloatArray",
"HalfArray",
"Int64Array",
"IntArray",
"Matrix3dArray",
"Matrix3fArray",
"Matrix4dArray",
"Matrix4fArray",
"QuatdArray",
"QuatfArray",
"QuathArray",
"ShortArray",
"StringArray",
"TokenArray",
"UCharArray",
"UInt64Array",
"UIntArray",
"UShortArray",
"Vec2dArray",
"Vec2fArray",
"Vec2hArray",
"Vec2iArray",
"Vec3dArray",
"Vec3fArray",
"Vec3hArray",
"Vec3iArray",
"Vec4dArray",
"Vec4fArray",
"Vec4hArray",
"Vec4iArray"
]
class AssetArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
@staticmethod
def __getitem__(*args, **kwargs) -> typing.Any: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.uint64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt::SdfAssetPath]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
@staticmethod
def __setitem__(*args, **kwargs) -> typing.Any: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class BoolArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> bool: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[bool]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[bool]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: bool) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class CharArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> str: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.int8]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[str]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: str) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class DoubleArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> float: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[float]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: float) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class FloatArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> float: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[float]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: float) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class HalfArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> GfHalf: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float16]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[GfHalf]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: GfHalf) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Int64Array():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> int: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.int64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[int]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: int) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class IntArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> int: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.int32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[int]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: int) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Matrix3dArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Matrix3d: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Matrix3d]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Matrix3d) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Matrix3fArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Matrix3f: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Matrix3f]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Matrix3f) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Matrix4dArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Matrix4d: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Matrix4d]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Matrix4d) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Matrix4fArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Matrix4f: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Matrix4f]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Matrix4f) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class QuatdArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Quatd: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Quatd]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Quatd) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class QuatfArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Quatf: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Quatf]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Quatf) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class QuathArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Quath: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float16]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Quath]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Quath) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class ShortArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> int: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.int16]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[int]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: int) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class StringArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> str: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.int8]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[str]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: str) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class TokenArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> TfToken: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.uint64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[TfToken]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: TfToken) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class UCharArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> int: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.uint8]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[int]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: int) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class UInt64Array():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> int: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.uint64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[int]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: int) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class UIntArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> int: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.uint32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[int]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: int) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class UShortArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> int: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.uint16]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[int]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: int) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec2dArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec2d: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec2d]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec2d) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec2fArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec2f: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec2f]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec2f) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec2hArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec2h: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float16]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec2h]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec2h) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec2iArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec2i: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.int32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec2i]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec2i) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec3dArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec3d: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec3d]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec3d) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec3fArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec3f: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec3f]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec3f) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec3hArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec3h: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float16]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec3h]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec3h) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec3iArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec3i: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.int32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec3i]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec3i) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec4dArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec4d: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float64]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec4d]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec4d) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec4fArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec4f: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec4f]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec4f) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec4hArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec4h: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.float16]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec4h]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec4h) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
class Vec4iArray():
def DetachFromSource(self) -> None: ...
def HasFabricGpuData(self) -> bool: ...
def IsFabricData(self) -> bool: ...
def IsOwnData(self) -> bool: ...
def IsPythonData(self) -> bool: ...
def __getitem__(self, arg0: int) -> usdrt.Gf._Gf.Vec4i: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
@typing.overload
def __init__(self, arg0: object) -> None: ...
@typing.overload
def __init__(self, arg0: numpy.ndarray[numpy.int32]) -> None: ...
@typing.overload
def __init__(self, arg0: typing.List[usdrt.Gf._Gf.Vec4i]) -> None: ...
def __iter__(self) -> typing.Iterator: ...
def __len__(self) -> int: ...
def __repr__(self) -> str: ...
def __setitem__(self, arg0: int, arg1: usdrt.Gf._Gf.Vec4i) -> None: ...
def __str__(self) -> str: ...
@property
def __array_interface__(self) -> dict:
"""
:type: dict
"""
@property
def __cuda_array_interface__(self) -> dict:
"""
:type: dict
"""
pass
| 38,143 | unknown | 31.601709 | 78 | 0.523556 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/UsdGeom/_UsdGeom.pyi | from __future__ import annotations
import usdrt.UsdGeom._UsdGeom
import typing
import usdrt.Sdf._Sdf
import usdrt.Usd._Usd
__all__ = [
"BasisCurves",
"Boundable",
"Camera",
"Capsule",
"Cone",
"Cube",
"Curves",
"Cylinder",
"Gprim",
"HermiteCurves",
"Imageable",
"Mesh",
"ModelAPI",
"MotionAPI",
"NurbsCurves",
"NurbsPatch",
"Plane",
"PointBased",
"PointInstancer",
"Points",
"PrimvarsAPI",
"Scope",
"Sphere",
"Subset",
"Tokens",
"VisibilityAPI",
"Xform",
"XformCommonAPI",
"Xformable"
]
class BasisCurves(Curves, PointBased, Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateBasisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWrapAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> BasisCurves: ...
def GetBasisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetWrapAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Boundable(Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Camera(Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateClippingPlanesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateClippingRangeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateExposureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFStopAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFocalLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFocusDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHorizontalApertureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHorizontalApertureOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateProjectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShutterCloseAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateShutterOpenAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStereoRoleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVerticalApertureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVerticalApertureOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Camera: ...
def GetClippingPlanesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetClippingRangeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExposureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFStopAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFocalLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFocusDistanceAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHorizontalApertureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHorizontalApertureOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetProjectionAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetShutterCloseAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetShutterOpenAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetStereoRoleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVerticalApertureAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVerticalApertureOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Capsule(Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Capsule: ...
def GetAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Cone(Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Cone: ...
def GetAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Cube(Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Cube: ...
def GetExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSizeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Curves(PointBased, Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateCurveVertexCountsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWidthsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCurveVertexCountsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetWidthsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Cylinder(Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Cylinder: ...
def GetAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHeightAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class HermiteCurves(Curves, PointBased, Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateTangentsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> HermiteCurves: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTangentsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Mesh(PointBased, Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateCornerIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCornerSharpnessesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCreaseIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCreaseLengthsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateCreaseSharpnessesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFaceVaryingLinearInterpolationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFaceVertexCountsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFaceVertexIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateHoleIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInterpolateBoundaryAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateSubdivisionSchemeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTriangleSubdivisionRuleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Mesh: ...
def GetCornerIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCornerSharpnessesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCreaseIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCreaseLengthsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetCreaseSharpnessesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFaceVaryingLinearInterpolationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFaceVertexCountsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFaceVertexIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetHoleIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInterpolateBoundaryAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetSubdivisionSchemeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTriangleSubdivisionRuleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class NurbsCurves(Curves, PointBased, Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateFormAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateKnotsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePointWeightsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRangesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> NurbsCurves: ...
def GetFormAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetKnotsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPointWeightsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRangesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class NurbsPatch(PointBased, Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreatePointWeightsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTrimCurveCountsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTrimCurveKnotsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTrimCurveOrdersAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTrimCurvePointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTrimCurveRangesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateTrimCurveVertexCountsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUFormAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUKnotsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateURangeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateUVertexCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVFormAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVKnotsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVRangeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVVertexCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> NurbsPatch: ...
def GetPointWeightsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetTrimCurveCountsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTrimCurveKnotsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTrimCurveOrdersAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTrimCurvePointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTrimCurveRangesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetTrimCurveVertexCountsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUFormAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUKnotsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetURangeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetUVertexCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVFormAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVKnotsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVRangeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetVVertexCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Plane(Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDoubleSidedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWidthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Plane: ...
def GetAxisAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDoubleSidedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetLengthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetWidthAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Points(PointBased, Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateIdsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateWidthsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Points: ...
def GetIdsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetWidthsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PointBased(Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAccelerationsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNormalsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVelocitiesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAccelerationsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNormalsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPointsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetVelocitiesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Gprim(Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateDisplayColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDisplayOpacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateDoubleSidedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateOrientationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDisplayColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDisplayOpacityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetDoubleSidedAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetOrientationAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Scope(Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Scope: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Sphere(Gprim, Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Sphere: ...
def GetExtentAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRadiusAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Imageable(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateProxyPrimRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreatePurposeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVisibilityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetProxyPrimRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetPurposeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetVisibilityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class ModelAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateModelApplyDrawModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModelCardGeometryAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModelCardTextureXNegAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModelCardTextureXPosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModelCardTextureYNegAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModelCardTextureYPosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModelCardTextureZNegAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModelCardTextureZPosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModelDrawModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateModelDrawModeColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelApplyDrawModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelCardGeometryAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelCardTextureXNegAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelCardTextureXPosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelCardTextureYNegAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelCardTextureYPosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelCardTextureZNegAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelCardTextureZPosAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelDrawModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetModelDrawModeColorAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class MotionAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateMotionBlurScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateNonlinearSampleCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVelocityScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMotionBlurScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetNonlinearSampleCountAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetVelocityScaleAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PointInstancer(Boundable, Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAccelerationsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateAngularVelocitiesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateIdsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateInvisibleIdsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateOrientationsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePositionsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateProtoIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePrototypesRel(self) -> usdrt.Usd._Usd.Relationship: ...
def CreateScalesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateVelocitiesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> PointInstancer: ...
def GetAccelerationsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetAngularVelocitiesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetIdsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetInvisibleIdsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetOrientationsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPositionsAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetProtoIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPrototypesRel(self) -> usdrt.Usd._Usd.Relationship: ...
def GetScalesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetVelocitiesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class PrimvarsAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Subset(usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateElementTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFamilyNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Subset: ...
def GetElementTypeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFamilyNameAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetIndicesAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
accelerations = 'accelerations'
all = 'all'
angularVelocities = 'angularVelocities'
axis = 'axis'
basis = 'basis'
bezier = 'bezier'
bilinear = 'bilinear'
boundaries = 'boundaries'
bounds = 'bounds'
box = 'box'
bspline = 'bspline'
cards = 'cards'
catmullClark = 'catmullClark'
catmullRom = 'catmullRom'
clippingPlanes = 'clippingPlanes'
clippingRange = 'clippingRange'
closed = 'closed'
constant = 'constant'
cornerIndices = 'cornerIndices'
cornerSharpnesses = 'cornerSharpnesses'
cornersOnly = 'cornersOnly'
cornersPlus1 = 'cornersPlus1'
cornersPlus2 = 'cornersPlus2'
creaseIndices = 'creaseIndices'
creaseLengths = 'creaseLengths'
creaseSharpnesses = 'creaseSharpnesses'
cross = 'cross'
cubic = 'cubic'
curveVertexCounts = 'curveVertexCounts'
default_ = 'default'
doubleSided = 'doubleSided'
edgeAndCorner = 'edgeAndCorner'
edgeOnly = 'edgeOnly'
elementSize = 'elementSize'
elementType = 'elementType'
exposure = 'exposure'
extent = 'extent'
extentsHint = 'extentsHint'
fStop = 'fStop'
face = 'face'
faceVarying = 'faceVarying'
faceVaryingLinearInterpolation = 'faceVaryingLinearInterpolation'
faceVertexCounts = 'faceVertexCounts'
faceVertexIndices = 'faceVertexIndices'
familyName = 'familyName'
focalLength = 'focalLength'
focusDistance = 'focusDistance'
form = 'form'
fromTexture = 'fromTexture'
guide = 'guide'
guideVisibility = 'guideVisibility'
height = 'height'
hermite = 'hermite'
holeIndices = 'holeIndices'
horizontalAperture = 'horizontalAperture'
horizontalApertureOffset = 'horizontalApertureOffset'
ids = 'ids'
inactiveIds = 'inactiveIds'
indices = 'indices'
inherited = 'inherited'
interpolateBoundary = 'interpolateBoundary'
interpolation = 'interpolation'
invisible = 'invisible'
invisibleIds = 'invisibleIds'
knots = 'knots'
left = 'left'
leftHanded = 'leftHanded'
length = 'length'
linear = 'linear'
loop = 'loop'
metersPerUnit = 'metersPerUnit'
modelApplyDrawMode = 'model:applyDrawMode'
modelCardGeometry = 'model:cardGeometry'
modelCardTextureXNeg = 'model:cardTextureXNeg'
modelCardTextureXPos = 'model:cardTextureXPos'
modelCardTextureYNeg = 'model:cardTextureYNeg'
modelCardTextureYPos = 'model:cardTextureYPos'
modelCardTextureZNeg = 'model:cardTextureZNeg'
modelCardTextureZPos = 'model:cardTextureZPos'
modelDrawMode = 'model:drawMode'
modelDrawModeColor = 'model:drawModeColor'
mono = 'mono'
motionBlurScale = 'motion:blurScale'
motionNonlinearSampleCount = 'motion:nonlinearSampleCount'
motionVelocityScale = 'motion:velocityScale'
nonOverlapping = 'nonOverlapping'
none = 'none'
nonperiodic = 'nonperiodic'
normals = 'normals'
open = 'open'
order = 'order'
orientation = 'orientation'
orientations = 'orientations'
origin = 'origin'
orthographic = 'orthographic'
partition = 'partition'
periodic = 'periodic'
perspective = 'perspective'
pinned = 'pinned'
pivot = 'pivot'
pointWeights = 'pointWeights'
points = 'points'
positions = 'positions'
power = 'power'
primvarsDisplayColor = 'primvars:displayColor'
primvarsDisplayOpacity = 'primvars:displayOpacity'
projection = 'projection'
protoIndices = 'protoIndices'
prototypes = 'prototypes'
proxy = 'proxy'
proxyPrim = 'proxyPrim'
proxyVisibility = 'proxyVisibility'
purpose = 'purpose'
radius = 'radius'
ranges = 'ranges'
render = 'render'
renderVisibility = 'renderVisibility'
right = 'right'
rightHanded = 'rightHanded'
scales = 'scales'
shutterClose = 'shutter:close'
shutterOpen = 'shutter:open'
size = 'size'
smooth = 'smooth'
stereoRole = 'stereoRole'
subdivisionScheme = 'subdivisionScheme'
tangents = 'tangents'
triangleSubdivisionRule = 'triangleSubdivisionRule'
trimCurveCounts = 'trimCurve:counts'
trimCurveKnots = 'trimCurve:knots'
trimCurveOrders = 'trimCurve:orders'
trimCurvePoints = 'trimCurve:points'
trimCurveRanges = 'trimCurve:ranges'
trimCurveVertexCounts = 'trimCurve:vertexCounts'
type = 'type'
uForm = 'uForm'
uKnots = 'uKnots'
uOrder = 'uOrder'
uRange = 'uRange'
uVertexCount = 'uVertexCount'
unauthoredValuesIndex = 'unauthoredValuesIndex'
uniform = 'uniform'
unrestricted = 'unrestricted'
upAxis = 'upAxis'
vForm = 'vForm'
vKnots = 'vKnots'
vOrder = 'vOrder'
vRange = 'vRange'
vVertexCount = 'vVertexCount'
varying = 'varying'
velocities = 'velocities'
vertex = 'vertex'
verticalAperture = 'verticalAperture'
verticalApertureOffset = 'verticalApertureOffset'
visibility = 'visibility'
visible = 'visible'
width = 'width'
widths = 'widths'
wrap = 'wrap'
x = 'X'
xformOpOrder = 'xformOpOrder'
y = 'Y'
z = 'Z'
pass
class VisibilityAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
def CreateGuideVisibilityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateProxyVisibilityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateRenderVisibilityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGuideVisibilityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetProxyVisibilityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetRenderVisibilityAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Xform(Xformable, Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> Xform: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class XformCommonAPI(usdrt.Usd._Usd.APISchemaBase, usdrt.Usd._Usd.SchemaBase):
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Xformable(Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateXformOpOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetXformOpOrderAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
| 35,108 | unknown | 45.379128 | 129 | 0.654865 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/UsdMedia/_UsdMedia.pyi | from __future__ import annotations
import usdrt.UsdMedia._UsdMedia
import typing
import usdrt.Sdf._Sdf
import usdrt.Usd._Usd
import usdrt.UsdGeom._UsdGeom
__all__ = [
"SpatialAudio",
"Tokens"
]
class SpatialAudio(usdrt.UsdGeom._UsdGeom.Xformable, usdrt.UsdGeom._UsdGeom.Imageable, usdrt.Usd._Usd.Typed, usdrt.Usd._Usd.SchemaBase):
def CreateAuralModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateEndTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateFilePathAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateMediaOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreatePlaybackModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def CreateStartTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def Define(stage: usdrt.Usd._Usd.Stage, path: usdrt.Sdf._Sdf.Path) -> SpatialAudio: ...
def GetAuralModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetEndTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetFilePathAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetGainAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetMediaOffsetAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def GetPlaybackModeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
@staticmethod
def GetSchemaTypeName() -> TfToken: ...
def GetStartTimeAttr(self) -> usdrt.Usd._Usd.Attribute: ...
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.Prim) -> None: ...
@typing.overload
def __init__(self, arg0: usdrt.Usd._Usd.SchemaBase) -> None: ...
def __repr__(self) -> str: ...
pass
class Tokens():
auralMode = 'auralMode'
endTime = 'endTime'
filePath = 'filePath'
gain = 'gain'
loopFromStage = 'loopFromStage'
loopFromStart = 'loopFromStart'
loopFromStartToEnd = 'loopFromStartToEnd'
mediaOffset = 'mediaOffset'
nonSpatial = 'nonSpatial'
onceFromStart = 'onceFromStart'
onceFromStartToEnd = 'onceFromStartToEnd'
playbackMode = 'playbackMode'
spatial = 'spatial'
startTime = 'startTime'
pass
| 2,148 | unknown | 37.374999 | 136 | 0.669926 |
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/base/tf/token.h | // Copyright (c) 2021-2023, 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.
//
#pragma once
//! @file
//!
//! @brief TODO
#include <omni/fabric/IToken.h>
#include <string>
namespace usdrt
{
class TfToken
{
public:
TfToken();
TfToken(const omni::fabric::Token& token);
TfToken(const std::string& token);
TfToken(const char* token);
const std::string GetString() const;
const char* GetText() const;
void pyUpdate(const char* fromPython);
// TODO: other TfToken APIs
bool IsEmpty() const;
bool operator==(const TfToken& other) const;
bool operator!=(const TfToken& other) const;
bool operator<(const TfToken& other) const;
operator omni::fabric::TokenC() const;
private:
omni::fabric::Token m_token;
};
inline TfToken::TfToken()
{
// m_token constructs uninitialized by default
}
inline TfToken::TfToken(const omni::fabric::Token& token) : m_token(token)
{
}
inline TfToken::TfToken(const std::string& token) : m_token(token.c_str())
{
}
inline TfToken::TfToken(const char* token) : m_token(token)
{
}
inline bool TfToken::operator==(const TfToken& other) const
{
return m_token == other.m_token;
}
inline bool TfToken::operator!=(const TfToken& other) const
{
return !(m_token == other.m_token);
}
inline bool TfToken::operator<(const TfToken& other) const
{
return m_token < other.m_token;
}
inline TfToken::operator omni::fabric::TokenC() const
{
return omni::fabric::TokenC(m_token);
}
inline const std::string TfToken::GetString() const
{
return m_token.getString();
}
inline const char* TfToken::GetText() const
{
return m_token.getText();
}
inline void TfToken::pyUpdate(const char* fromPython)
{
m_token = omni::fabric::Token(fromPython);
}
inline bool TfToken::IsEmpty() const
{
return m_token == omni::fabric::kUninitializedToken;
}
typedef std::vector<TfToken> TfTokenVector;
}
| 2,261 | C | 20.339622 | 77 | 0.704113 |
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/base/vt/array.h | // Copyright (c) 2022-2023, 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.
//
#pragma once
//! @file
//!
//! @brief TODO
#include <gsl/span>
#include <omni/fabric/IFabric.h>
#include <omni/python/PyBind.h>
#include <memory>
namespace usdrt
{
/* VtArray can:
* own its own CPU memory via a std::vector<ElementType> which follows COW semantics the same way Pixar's VtArray does
* refer to a Fabric CPU/GPU attribute via a stage ID, a path and an attribute
* refer to an external CPU python array (numpy) or GPU python array (pytorch/warp)
*/
template <typename ElementType>
class VtArray
{
public:
using element_type = ElementType;
using value_type = std::remove_cv_t<ElementType>;
using size_type = std::size_t;
using pointer = element_type*;
using const_pointer = const element_type*;
using reference = element_type&;
using const_reference = const element_type&;
using difference_type = std::ptrdiff_t;
VtArray();
VtArray(const VtArray<ElementType>& other);
VtArray(VtArray<ElementType>&& other);
VtArray(size_t n);
VtArray(gsl::span<ElementType> span);
VtArray(const std::vector<ElementType>& vec);
VtArray(size_t n, ElementType* data, void* gpuData, const py::object& externalArray = py::none());
VtArray(std::initializer_list<ElementType> initList);
VtArray(omni::fabric::StageReaderWriterId stageId, omni::fabric::PathC path, omni::fabric::TokenC attr);
~VtArray();
VtArray& operator=(const VtArray<ElementType>& other);
VtArray& operator=(gsl::span<ElementType> other);
VtArray& operator=(std::initializer_list<ElementType> initList);
ElementType& operator[](size_t index);
ElementType const& operator[](size_t index) const;
size_t size() const;
size_t capacity() const;
bool empty() const;
void reset();
void resize(size_t newSize);
void reserve(size_t num);
void push_back(const ElementType& element);
pointer data()
{
detach();
return span().data();
}
const_pointer data() const
{
return span().data();
}
const_pointer cdata() const
{
return span().data();
}
gsl::span<ElementType> span() const;
// Special RT functionality...
// When a VtArray is initialized from Fabric data,
// generally with UsdAttribute.Get(),
// its underlying span will point at data directly in
// Fabric. In this default attached state, the VtArray
// can be used to modify Fabric arrays directly.
// The developer may choose to make an instance-local
// copy of the array data using DetachFromSource, at
// which point modifications happen on the instance-local
// array. IsFabricData() will let you know if a VtArray
// instance is reading/writing Fabric data directly.
void DetachFromSource();
bool IsFabricData() const;
bool IsPythonData() const;
bool IsOwnData() const;
bool HasFabricCpuData() const;
bool HasFabricGpuData() const;
void* GetGpuData() const;
typedef gsl::details::span_iterator<ElementType> iterator;
typedef gsl::details::span_iterator<const ElementType> const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
iterator begin()
{
detach();
return span().begin();
}
iterator end()
{
return span().end();
}
const_iterator cbegin()
{
return span().begin();
}
const_iterator cend()
{
return span().end();
}
reverse_iterator rbegin()
{
detach();
return reverse_iterator(span().end());
}
reverse_iterator rend()
{
return reverse_iterator(span().begin());
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator(span().end());
}
const_reverse_iterator rend() const
{
return const_reverse_iterator(span().begin());
}
const_reverse_iterator crbegin() const
{
return rbegin();
}
const_reverse_iterator crend() const
{
return rend();
}
private:
// If the m_data span is pointing at fabric data,
// or if multiple VtArray instances are pointing
// at the same underlying data, make a copy
// of the data that is unique to this instance.
// This is used to implement Copy On Write
// and Copy On Non-Const Access, like Pixar's VtArray
void detach();
// Make an copy of data from iterable source that
// is unique to this instance.
template <typename Source>
void localize(const Source& other);
size_t m_size = 0;
size_t m_capacity = 0;
ElementType* m_data = nullptr;
void* m_gpuData = nullptr;
// Use a shared_ptr for lazy reference counting
// in order to implement COW/CONCA functionality.
std::shared_ptr<gsl::span<ElementType>> m_sharedData;
// When a VtArray points to Fabric data we avoid using pointers which can change
// without notice, instead we use Path and Attribute.
omni::fabric::StageReaderWriterId m_stageId{ 0 };
omni::fabric::PathC m_path{ 0 };
omni::fabric::TokenC m_attr{ 0 };
// When creating a VtArray from an external python object (buffer or cuda array interface)
// we keep a reference to the external object in order to keep it alive until the VtArray is destroyed.
py::object m_externalArray = py::none();
};
template <typename ElementType>
inline VtArray<ElementType>::VtArray()
{
m_sharedData = std::make_shared<gsl::span<ElementType>>();
}
template <typename ElementType>
inline VtArray<ElementType>::VtArray(const VtArray<ElementType>& other)
: m_size(other.m_size),
m_capacity(other.m_capacity),
m_data(other.m_data),
m_gpuData(other.m_gpuData),
m_sharedData(other.m_sharedData),
m_stageId(other.m_stageId),
m_path(other.m_path),
m_attr(other.m_attr),
m_externalArray(other.m_externalArray)
{
}
template <typename ElementType>
inline VtArray<ElementType>::VtArray(VtArray<ElementType>&& other)
: m_size(other.m_size),
m_capacity(other.m_capacity),
m_data(other.m_data),
m_gpuData(other.m_gpuData),
m_sharedData(std::move(other.m_sharedData)),
m_stageId(other.m_stageId),
m_path(other.m_path),
m_attr(other.m_attr),
m_externalArray(std::move(other.m_externalArray))
{
other.m_data = nullptr;
other.m_size = 0;
other.m_capacity = 0;
other.m_gpuData = nullptr;
other.m_stageId.id = 0;
other.m_path.path = 0;
other.m_attr.token = 0;
}
template <typename ElementType>
inline VtArray<ElementType>::VtArray(size_t n) : m_size(n), m_capacity(n)
{
m_sharedData = std::make_shared<gsl::span<ElementType>>(new ElementType[m_size], m_size);
}
template <typename ElementType>
inline VtArray<ElementType>::VtArray(gsl::span<ElementType> span) : m_size(span.size()), m_capacity(span.size())
{
localize(span);
}
template <typename ElementType>
inline VtArray<ElementType>::VtArray(size_t n, ElementType* data, void* gpuData, const py::object& externalArray)
: m_size(n), m_capacity(n), m_data(data), m_gpuData(gpuData), m_externalArray(externalArray)
{
}
template <typename ElementType>
inline VtArray<ElementType>::VtArray(omni::fabric::StageReaderWriterId stageId,
omni::fabric::PathC path,
omni::fabric::TokenC attr)
: m_stageId(stageId), m_path(path), m_attr(attr)
{
}
template <typename ElementType>
inline VtArray<ElementType>::VtArray(std::initializer_list<ElementType> initList)
{
localize(initList);
}
template <typename ElementType>
inline VtArray<ElementType>::VtArray(const std::vector<ElementType>& vec)
{
localize(vec);
}
template <typename ElementType>
inline VtArray<ElementType>& VtArray<ElementType>::operator=(const VtArray<ElementType>& other)
{
m_size = other.m_size;
m_capacity = other.m_capacity;
m_data = other.m_data;
m_gpuData = other.m_gpuData;
m_sharedData = other.m_sharedData;
m_stageId = other.m_stageId;
m_path = other.m_path;
m_attr = other.m_attr;
m_externalArray = other.m_externalArray;
return *this;
}
template <typename ElementType>
inline VtArray<ElementType>& VtArray<ElementType>::operator=(gsl::span<ElementType> other)
{
localize(other);
return *this;
}
template <typename ElementType>
inline VtArray<ElementType>& VtArray<ElementType>::operator=(std::initializer_list<ElementType> initList)
{
localize(initList);
return *this;
}
template <typename ElementType>
inline ElementType const& VtArray<ElementType>::operator[](size_t index) const
{
return span()[index];
}
template <typename ElementType>
inline ElementType& VtArray<ElementType>::operator[](size_t index)
{
if (m_stageId.id == 0)
{
// Allow writing to Fabric only
detach();
}
return span()[index];
}
template <typename ElementType>
inline VtArray<ElementType>::~VtArray()
{
reset();
}
template <typename ElementType>
inline void VtArray<ElementType>::reset()
{
if (m_sharedData.use_count() == 1 && m_sharedData->data())
{
delete[] m_sharedData->data();
}
m_data = nullptr;
m_gpuData = nullptr;
m_size = 0;
m_capacity = 0;
m_stageId.id = 0;
m_path.path = 0;
m_attr.token = 0;
m_externalArray = py::none();
}
template <typename ElementType>
inline gsl::span<ElementType> VtArray<ElementType>::span() const
{
if (m_sharedData)
{
// Note - the m_sharedData span may be larger than m_size
// if there is reserved capacity, so return a new span
// that has a size of m_size
return gsl::span<ElementType>(m_sharedData->data(), m_size);
}
if (m_data)
{
return gsl::span<ElementType>(m_data, m_size);
}
if (m_gpuData)
{
return gsl::span<ElementType>((ElementType*)m_gpuData, m_size);
}
if (m_stageId.id)
{
auto iStageReaderWriter = carb::getCachedInterface<omni::fabric::IStageReaderWriter>();
size_t size = iStageReaderWriter->getArrayAttributeSize(m_stageId, m_path, m_attr);
auto validBits = iStageReaderWriter->getAttributeValidBits(m_stageId, m_path, m_attr);
if (uint32_t(validBits & omni::fabric::ValidMirrors::eCPU) != 0)
{
auto fabSpan = iStageReaderWriter->getArrayAttribute(m_stageId, m_path, m_attr);
return gsl::span<ElementType>((ElementType*)fabSpan.ptr, size);
}
else if (uint32_t(validBits & omni::fabric::ValidMirrors::eCudaGPU) != 0)
{
auto fabSpan = iStageReaderWriter->getAttributeGpu(m_stageId, m_path, m_attr);
return gsl::span<ElementType>((ElementType*)fabSpan.ptr, size);
}
}
return gsl::span<ElementType>();
}
template <typename ElementType>
inline size_t VtArray<ElementType>::size() const
{
return span().size();
}
template <typename ElementType>
inline size_t VtArray<ElementType>::capacity() const
{
if (!IsOwnData())
{
return span().size();
}
return m_capacity;
}
template <typename ElementType>
inline bool VtArray<ElementType>::empty() const
{
return span().empty();
}
template <typename ElementType>
inline bool VtArray<ElementType>::IsFabricData() const
{
return m_stageId.id != 0;
}
template <typename ElementType>
inline bool VtArray<ElementType>::IsPythonData() const
{
return !m_externalArray.is(py::none());
}
template <typename ElementType>
inline bool VtArray<ElementType>::IsOwnData() const
{
return (bool)m_sharedData;
}
template <typename ElementType>
inline bool VtArray<ElementType>::HasFabricGpuData() const
{
if (m_stageId.id)
{
auto iStageReaderWriter = carb::getCachedInterface<omni::fabric::IStageReaderWriter>();
auto validBits = iStageReaderWriter->getAttributeValidBits(m_stageId, m_path, m_attr);
return uint32_t(validBits & omni::fabric::ValidMirrors::eCudaGPU) != 0;
}
return false;
}
template <typename ElementType>
inline bool VtArray<ElementType>::HasFabricCpuData() const
{
if (m_stageId.id)
{
auto iStageReaderWriter = carb::getCachedInterface<omni::fabric::IStageReaderWriter>();
auto validBits = iStageReaderWriter->getAttributeValidBits(m_stageId, m_path, m_attr);
return uint32_t(validBits & omni::fabric::ValidMirrors::eCPU) != 0;
}
return false;
}
template <typename ElementType>
inline void* VtArray<ElementType>::GetGpuData() const
{
if (m_gpuData)
return m_gpuData;
if (m_stageId.id)
{
auto iStageReaderWriter = carb::getCachedInterface<omni::fabric::IStageReaderWriter>();
auto validBits = iStageReaderWriter->getAttributeValidBits(m_stageId, m_path, m_attr);
if (uint32_t(validBits & omni::fabric::ValidMirrors::eCudaGPU) != 0)
{
auto fabCSpan = iStageReaderWriter->getAttributeRdGpu(m_stageId, m_path, m_attr);
return *(void**)fabCSpan.ptr;
}
}
return nullptr;
}
template <typename ElementType>
inline void VtArray<ElementType>::DetachFromSource()
{
detach();
}
template <typename ElementType>
inline void VtArray<ElementType>::detach()
{
if (m_sharedData && m_sharedData.use_count() == 1)
{
// No need to detach from anything
return;
}
// multiple VtArray have pointers to
// the same underyling data, so localize
// a copy before modifiying
// This mirror's VtArray's COW, CONCA behavior
// https://graphics.pixar.com/usd/release/api/class_vt_array.html#details
localize(span());
}
template <typename ElementType>
template <typename Source>
inline void VtArray<ElementType>::localize(const Source& other)
{
reset();
m_size = other.size();
m_capacity = other.size();
m_sharedData = std::make_shared<gsl::span<ElementType>>(new ElementType[m_size], m_size);
std::copy(other.begin(), other.end(), m_sharedData->begin());
}
template <typename ElementType>
inline void VtArray<ElementType>::resize(size_t newSize)
{
detach();
std::shared_ptr<gsl::span<ElementType>> tmpSpan =
std::make_shared<gsl::span<ElementType>>(new ElementType[newSize], newSize);
if (newSize > m_capacity)
{
std::copy(m_sharedData->begin(), m_sharedData->end(), tmpSpan->begin());
}
else
{
std::copy(m_sharedData->begin(), m_sharedData->begin() + newSize, tmpSpan->begin());
}
delete m_sharedData->data();
m_sharedData = tmpSpan;
m_size = newSize;
m_capacity = newSize;
}
template <typename ElementType>
inline void VtArray<ElementType>::reserve(size_t num)
{
detach();
if (num <= m_capacity)
{
return;
}
std::shared_ptr<gsl::span<ElementType>> tmpSpan = std::make_shared<gsl::span<ElementType>>(new ElementType[num], num);
if (m_size > 0)
{
std::copy(m_sharedData->begin(), m_sharedData->end(), tmpSpan->begin());
delete m_sharedData->data();
}
m_sharedData = tmpSpan;
m_capacity = num;
}
template <typename ElementType>
inline void VtArray<ElementType>::push_back(const ElementType& element)
{
detach();
if (m_size == m_capacity)
{
if (m_size == 0)
{
reserve(2);
}
else
{
reserve(m_size * 2);
}
}
(*m_sharedData)[m_size] = element;
m_size++;
}
} // namespace usdrt
| 15,883 | C | 27.364286 | 122 | 0.659132 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.